Use gdb::byte_vector in agent_expr
[binutils-gdb.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3 Copyright (C) 1988-2023 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20 /* See the GDB User Guide for details of the GDB remote protocol. */
21
22 #include "defs.h"
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "bfd.h"
28 #include "symfile.h"
29 #include "target.h"
30 #include "process-stratum-target.h"
31 #include "gdbcmd.h"
32 #include "objfiles.h"
33 #include "gdbthread.h"
34 #include "remote.h"
35 #include "remote-notif.h"
36 #include "regcache.h"
37 #include "value.h"
38 #include "observable.h"
39 #include "solib.h"
40 #include "cli/cli-decode.h"
41 #include "cli/cli-setshow.h"
42 #include "target-descriptions.h"
43 #include "gdb_bfd.h"
44 #include "gdbsupport/filestuff.h"
45 #include "gdbsupport/rsp-low.h"
46 #include "disasm.h"
47 #include "location.h"
48
49 #include "gdbsupport/gdb_sys_time.h"
50
51 #include "gdbsupport/event-loop.h"
52 #include "event-top.h"
53 #include "inf-loop.h"
54
55 #include <signal.h>
56 #include "serial.h"
57
58 #include "gdbcore.h"
59
60 #include "remote-fileio.h"
61 #include "gdbsupport/fileio.h"
62 #include <sys/stat.h>
63 #include "xml-support.h"
64
65 #include "memory-map.h"
66
67 #include "tracepoint.h"
68 #include "ax.h"
69 #include "ax-gdb.h"
70 #include "gdbsupport/agent.h"
71 #include "btrace.h"
72 #include "record-btrace.h"
73 #include "gdbsupport/scoped_restore.h"
74 #include "gdbsupport/environ.h"
75 #include "gdbsupport/byte-vector.h"
76 #include "gdbsupport/search.h"
77 #include <algorithm>
78 #include <iterator>
79 #include <unordered_map>
80 #include "async-event.h"
81 #include "gdbsupport/selftest.h"
82
83 /* The remote target. */
84
85 static const char remote_doc[] = N_("\
86 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
87 Specify the serial device it is connected to\n\
88 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
89
90 /* See remote.h */
91
92 bool remote_debug = false;
93
94 #define OPAQUETHREADBYTES 8
95
96 /* a 64 bit opaque identifier */
97 typedef unsigned char threadref[OPAQUETHREADBYTES];
98
99 struct gdb_ext_thread_info;
100 struct threads_listing_context;
101 typedef int (*rmt_thread_action) (threadref *ref, void *context);
102 struct protocol_feature;
103 struct packet_reg;
104
105 struct stop_reply;
106 typedef std::unique_ptr<stop_reply> stop_reply_up;
107
108 /* Generic configuration support for packets the stub optionally
109 supports. Allows the user to specify the use of the packet as well
110 as allowing GDB to auto-detect support in the remote stub. */
111
112 enum packet_support
113 {
114 PACKET_SUPPORT_UNKNOWN = 0,
115 PACKET_ENABLE,
116 PACKET_DISABLE
117 };
118
119 /* Convert the packet support auto_boolean to a name used for gdb printing. */
120
121 static const char *
122 get_packet_support_name (auto_boolean support)
123 {
124 switch (support)
125 {
126 case AUTO_BOOLEAN_TRUE:
127 return "on";
128 case AUTO_BOOLEAN_FALSE:
129 return "off";
130 case AUTO_BOOLEAN_AUTO:
131 return "auto";
132 default:
133 gdb_assert_not_reached ("invalid var_auto_boolean");
134 }
135 }
136
137 /* Convert the target type (future remote target or currently connected target)
138 to a name used for gdb printing. */
139
140 static const char *
141 get_target_type_name (bool target_connected)
142 {
143 if (target_connected)
144 return _("on the current remote target");
145 else
146 return _("on future remote targets");
147 }
148
149 /* Analyze a packet's return value and update the packet config
150 accordingly. */
151
152 enum packet_result
153 {
154 PACKET_ERROR,
155 PACKET_OK,
156 PACKET_UNKNOWN
157 };
158
159 /* Enumeration of packets for a remote target. */
160
161 enum {
162 PACKET_vCont = 0,
163 PACKET_X,
164 PACKET_qSymbol,
165 PACKET_P,
166 PACKET_p,
167 PACKET_Z0,
168 PACKET_Z1,
169 PACKET_Z2,
170 PACKET_Z3,
171 PACKET_Z4,
172 PACKET_vFile_setfs,
173 PACKET_vFile_open,
174 PACKET_vFile_pread,
175 PACKET_vFile_pwrite,
176 PACKET_vFile_close,
177 PACKET_vFile_unlink,
178 PACKET_vFile_readlink,
179 PACKET_vFile_fstat,
180 PACKET_qXfer_auxv,
181 PACKET_qXfer_features,
182 PACKET_qXfer_exec_file,
183 PACKET_qXfer_libraries,
184 PACKET_qXfer_libraries_svr4,
185 PACKET_qXfer_memory_map,
186 PACKET_qXfer_osdata,
187 PACKET_qXfer_threads,
188 PACKET_qXfer_statictrace_read,
189 PACKET_qXfer_traceframe_info,
190 PACKET_qXfer_uib,
191 PACKET_qGetTIBAddr,
192 PACKET_qGetTLSAddr,
193 PACKET_qSupported,
194 PACKET_qTStatus,
195 PACKET_QPassSignals,
196 PACKET_QCatchSyscalls,
197 PACKET_QProgramSignals,
198 PACKET_QSetWorkingDir,
199 PACKET_QStartupWithShell,
200 PACKET_QEnvironmentHexEncoded,
201 PACKET_QEnvironmentReset,
202 PACKET_QEnvironmentUnset,
203 PACKET_qCRC,
204 PACKET_qSearch_memory,
205 PACKET_vAttach,
206 PACKET_vRun,
207 PACKET_QStartNoAckMode,
208 PACKET_vKill,
209 PACKET_qXfer_siginfo_read,
210 PACKET_qXfer_siginfo_write,
211 PACKET_qAttached,
212
213 /* Support for conditional tracepoints. */
214 PACKET_ConditionalTracepoints,
215
216 /* Support for target-side breakpoint conditions. */
217 PACKET_ConditionalBreakpoints,
218
219 /* Support for target-side breakpoint commands. */
220 PACKET_BreakpointCommands,
221
222 /* Support for fast tracepoints. */
223 PACKET_FastTracepoints,
224
225 /* Support for static tracepoints. */
226 PACKET_StaticTracepoints,
227
228 /* Support for installing tracepoints while a trace experiment is
229 running. */
230 PACKET_InstallInTrace,
231
232 PACKET_bc,
233 PACKET_bs,
234 PACKET_TracepointSource,
235 PACKET_QAllow,
236 PACKET_qXfer_fdpic,
237 PACKET_QDisableRandomization,
238 PACKET_QAgent,
239 PACKET_QTBuffer_size,
240 PACKET_Qbtrace_off,
241 PACKET_Qbtrace_bts,
242 PACKET_Qbtrace_pt,
243 PACKET_qXfer_btrace,
244
245 /* Support for the QNonStop packet. */
246 PACKET_QNonStop,
247
248 /* Support for the QThreadEvents packet. */
249 PACKET_QThreadEvents,
250
251 /* Support for multi-process extensions. */
252 PACKET_multiprocess_feature,
253
254 /* Support for enabling and disabling tracepoints while a trace
255 experiment is running. */
256 PACKET_EnableDisableTracepoints_feature,
257
258 /* Support for collecting strings using the tracenz bytecode. */
259 PACKET_tracenz_feature,
260
261 /* Support for continuing to run a trace experiment while GDB is
262 disconnected. */
263 PACKET_DisconnectedTracing_feature,
264
265 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
266 PACKET_augmented_libraries_svr4_read_feature,
267
268 /* Support for the qXfer:btrace-conf:read packet. */
269 PACKET_qXfer_btrace_conf,
270
271 /* Support for the Qbtrace-conf:bts:size packet. */
272 PACKET_Qbtrace_conf_bts_size,
273
274 /* Support for swbreak+ feature. */
275 PACKET_swbreak_feature,
276
277 /* Support for hwbreak+ feature. */
278 PACKET_hwbreak_feature,
279
280 /* Support for fork events. */
281 PACKET_fork_event_feature,
282
283 /* Support for vfork events. */
284 PACKET_vfork_event_feature,
285
286 /* Support for the Qbtrace-conf:pt:size packet. */
287 PACKET_Qbtrace_conf_pt_size,
288
289 /* Support for exec events. */
290 PACKET_exec_event_feature,
291
292 /* Support for query supported vCont actions. */
293 PACKET_vContSupported,
294
295 /* Support remote CTRL-C. */
296 PACKET_vCtrlC,
297
298 /* Support TARGET_WAITKIND_NO_RESUMED. */
299 PACKET_no_resumed,
300
301 /* Support for memory tagging, allocation tag fetch/store
302 packets and the tag violation stop replies. */
303 PACKET_memory_tagging_feature,
304
305 PACKET_MAX
306 };
307
308 struct threads_listing_context;
309
310 /* Stub vCont actions support.
311
312 Each field is a boolean flag indicating whether the stub reports
313 support for the corresponding action. */
314
315 struct vCont_action_support
316 {
317 /* vCont;t */
318 bool t = false;
319
320 /* vCont;r */
321 bool r = false;
322
323 /* vCont;s */
324 bool s = false;
325
326 /* vCont;S */
327 bool S = false;
328 };
329
330 /* About this many threadids fit in a packet. */
331
332 #define MAXTHREADLISTRESULTS 32
333
334 /* Data for the vFile:pread readahead cache. */
335
336 struct readahead_cache
337 {
338 /* Invalidate the readahead cache. */
339 void invalidate ();
340
341 /* Invalidate the readahead cache if it is holding data for FD. */
342 void invalidate_fd (int fd);
343
344 /* Serve pread from the readahead cache. Returns number of bytes
345 read, or 0 if the request can't be served from the cache. */
346 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
347
348 /* The file descriptor for the file that is being cached. -1 if the
349 cache is invalid. */
350 int fd = -1;
351
352 /* The offset into the file that the cache buffer corresponds
353 to. */
354 ULONGEST offset = 0;
355
356 /* The buffer holding the cache contents. */
357 gdb::byte_vector buf;
358
359 /* Cache hit and miss counters. */
360 ULONGEST hit_count = 0;
361 ULONGEST miss_count = 0;
362 };
363
364 /* Description of the remote protocol for a given architecture. */
365
366 struct packet_reg
367 {
368 long offset; /* Offset into G packet. */
369 long regnum; /* GDB's internal register number. */
370 LONGEST pnum; /* Remote protocol register number. */
371 int in_g_packet; /* Always part of G packet. */
372 /* long size in bytes; == register_size (target_gdbarch (), regnum);
373 at present. */
374 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
375 at present. */
376 };
377
378 struct remote_arch_state
379 {
380 explicit remote_arch_state (struct gdbarch *gdbarch);
381
382 /* Description of the remote protocol registers. */
383 long sizeof_g_packet;
384
385 /* Description of the remote protocol registers indexed by REGNUM
386 (making an array gdbarch_num_regs in size). */
387 std::unique_ptr<packet_reg[]> regs;
388
389 /* This is the size (in chars) of the first response to the ``g''
390 packet. It is used as a heuristic when determining the maximum
391 size of memory-read and memory-write packets. A target will
392 typically only reserve a buffer large enough to hold the ``g''
393 packet. The size does not include packet overhead (headers and
394 trailers). */
395 long actual_register_packet_size;
396
397 /* This is the maximum size (in chars) of a non read/write packet.
398 It is also used as a cap on the size of read/write packets. */
399 long remote_packet_size;
400 };
401
402 /* Description of the remote protocol state for the currently
403 connected target. This is per-target state, and independent of the
404 selected architecture. */
405
406 class remote_state
407 {
408 public:
409
410 remote_state ();
411 ~remote_state ();
412
413 /* Get the remote arch state for GDBARCH. */
414 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
415
416 public: /* data */
417
418 /* A buffer to use for incoming packets, and its current size. The
419 buffer is grown dynamically for larger incoming packets.
420 Outgoing packets may also be constructed in this buffer.
421 The size of the buffer is always at least REMOTE_PACKET_SIZE;
422 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
423 packets. */
424 gdb::char_vector buf;
425
426 /* True if we're going through initial connection setup (finding out
427 about the remote side's threads, relocating symbols, etc.). */
428 bool starting_up = false;
429
430 /* If we negotiated packet size explicitly (and thus can bypass
431 heuristics for the largest packet size that will not overflow
432 a buffer in the stub), this will be set to that packet size.
433 Otherwise zero, meaning to use the guessed size. */
434 long explicit_packet_size = 0;
435
436 /* True, if in no ack mode. That is, neither GDB nor the stub will
437 expect acks from each other. The connection is assumed to be
438 reliable. */
439 bool noack_mode = false;
440
441 /* True if we're connected in extended remote mode. */
442 bool extended = false;
443
444 /* True if we resumed the target and we're waiting for the target to
445 stop. In the mean time, we can't start another command/query.
446 The remote server wouldn't be ready to process it, so we'd
447 timeout waiting for a reply that would never come and eventually
448 we'd close the connection. This can happen in asynchronous mode
449 because we allow GDB commands while the target is running. */
450 bool waiting_for_stop_reply = false;
451
452 /* The status of the stub support for the various vCont actions. */
453 vCont_action_support supports_vCont;
454
455 /* True if the user has pressed Ctrl-C, but the target hasn't
456 responded to that. */
457 bool ctrlc_pending_p = false;
458
459 /* True if we saw a Ctrl-C while reading or writing from/to the
460 remote descriptor. At that point it is not safe to send a remote
461 interrupt packet, so we instead remember we saw the Ctrl-C and
462 process it once we're done with sending/receiving the current
463 packet, which should be shortly. If however that takes too long,
464 and the user presses Ctrl-C again, we offer to disconnect. */
465 bool got_ctrlc_during_io = false;
466
467 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
468 remote_open knows that we don't have a file open when the program
469 starts. */
470 struct serial *remote_desc = nullptr;
471
472 /* These are the threads which we last sent to the remote system. The
473 TID member will be -1 for all or -2 for not sent yet. */
474 ptid_t general_thread = null_ptid;
475 ptid_t continue_thread = null_ptid;
476
477 /* This is the traceframe which we last selected on the remote system.
478 It will be -1 if no traceframe is selected. */
479 int remote_traceframe_number = -1;
480
481 char *last_pass_packet = nullptr;
482
483 /* The last QProgramSignals packet sent to the target. We bypass
484 sending a new program signals list down to the target if the new
485 packet is exactly the same as the last we sent. IOW, we only let
486 the target know about program signals list changes. */
487 char *last_program_signals_packet = nullptr;
488
489 gdb_signal last_sent_signal = GDB_SIGNAL_0;
490
491 bool last_sent_step = false;
492
493 /* The execution direction of the last resume we got. */
494 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
495
496 char *finished_object = nullptr;
497 char *finished_annex = nullptr;
498 ULONGEST finished_offset = 0;
499
500 /* Should we try the 'ThreadInfo' query packet?
501
502 This variable (NOT available to the user: auto-detect only!)
503 determines whether GDB will use the new, simpler "ThreadInfo"
504 query or the older, more complex syntax for thread queries.
505 This is an auto-detect variable (set to true at each connect,
506 and set to false when the target fails to recognize it). */
507 bool use_threadinfo_query = false;
508 bool use_threadextra_query = false;
509
510 threadref echo_nextthread {};
511 threadref nextthread {};
512 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
513
514 /* The state of remote notification. */
515 struct remote_notif_state *notif_state = nullptr;
516
517 /* The branch trace configuration. */
518 struct btrace_config btrace_config {};
519
520 /* The argument to the last "vFile:setfs:" packet we sent, used
521 to avoid sending repeated unnecessary "vFile:setfs:" packets.
522 Initialized to -1 to indicate that no "vFile:setfs:" packet
523 has yet been sent. */
524 int fs_pid = -1;
525
526 /* A readahead cache for vFile:pread. Often, reading a binary
527 involves a sequence of small reads. E.g., when parsing an ELF
528 file. A readahead cache helps mostly the case of remote
529 debugging on a connection with higher latency, due to the
530 request/reply nature of the RSP. We only cache data for a single
531 file descriptor at a time. */
532 struct readahead_cache readahead_cache;
533
534 /* The list of already fetched and acknowledged stop events. This
535 queue is used for notification Stop, and other notifications
536 don't need queue for their events, because the notification
537 events of Stop can't be consumed immediately, so that events
538 should be queued first, and be consumed by remote_wait_{ns,as}
539 one per time. Other notifications can consume their events
540 immediately, so queue is not needed for them. */
541 std::vector<stop_reply_up> stop_reply_queue;
542
543 /* Asynchronous signal handle registered as event loop source for
544 when we have pending events ready to be passed to the core. */
545 struct async_event_handler *remote_async_inferior_event_token = nullptr;
546
547 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
548 ``forever'' still use the normal timeout mechanism. This is
549 currently used by the ASYNC code to guarentee that target reads
550 during the initial connect always time-out. Once getpkt has been
551 modified to return a timeout indication and, in turn
552 remote_wait()/wait_for_inferior() have gained a timeout parameter
553 this can go away. */
554 int wait_forever_enabled_p = 1;
555
556 private:
557 /* Mapping of remote protocol data for each gdbarch. Usually there
558 is only one entry here, though we may see more with stubs that
559 support multi-process. */
560 std::unordered_map<struct gdbarch *, remote_arch_state>
561 m_arch_states;
562 };
563
564 static const target_info remote_target_info = {
565 "remote",
566 N_("Remote target using gdb-specific protocol"),
567 remote_doc
568 };
569
570 /* Description of a remote packet. */
571
572 struct packet_description
573 {
574 /* Name of the packet used for gdb output. */
575 const char *name;
576
577 /* Title of the packet, used by the set/show remote name-packet
578 commands to identify the individual packages and gdb output. */
579 const char *title;
580 };
581
582 /* Configuration of a remote packet. */
583
584 struct packet_config
585 {
586 /* If auto, GDB auto-detects support for this packet or feature,
587 either through qSupported, or by trying the packet and looking
588 at the response. If true, GDB assumes the target supports this
589 packet. If false, the packet is disabled. Configs that don't
590 have an associated command always have this set to auto. */
591 enum auto_boolean detect;
592
593 /* Does the target support this packet? */
594 enum packet_support support;
595 };
596
597 /* User configurable variables for the number of characters in a
598 memory read/write packet. MIN (rsa->remote_packet_size,
599 rsa->sizeof_g_packet) is the default. Some targets need smaller
600 values (fifo overruns, et.al.) and some users need larger values
601 (speed up transfers). The variables ``preferred_*'' (the user
602 request), ``current_*'' (what was actually set) and ``forced_*''
603 (Positive - a soft limit, negative - a hard limit). */
604
605 struct memory_packet_config
606 {
607 const char *name;
608 long size;
609 int fixed_p;
610 };
611
612 /* These global variables contain the default configuration for every new
613 remote_feature object. */
614 static memory_packet_config memory_read_packet_config =
615 {
616 "memory-read-packet-size",
617 };
618 static memory_packet_config memory_write_packet_config =
619 {
620 "memory-write-packet-size",
621 };
622
623 /* This global array contains packet descriptions (name and title). */
624 static packet_description packets_descriptions[PACKET_MAX];
625 /* This global array contains the default configuration for every new
626 per-remote target array. */
627 static packet_config remote_protocol_packets[PACKET_MAX];
628
629 /* Description of a remote target's features. It stores the configuration
630 and provides functions to determine supported features of the target. */
631
632 struct remote_features
633 {
634 remote_features ()
635 {
636 m_memory_read_packet_config = memory_read_packet_config;
637 m_memory_write_packet_config = memory_write_packet_config;
638
639 std::copy (std::begin (remote_protocol_packets),
640 std::end (remote_protocol_packets),
641 std::begin (m_protocol_packets));
642 }
643 ~remote_features () = default;
644
645 DISABLE_COPY_AND_ASSIGN (remote_features);
646
647 /* Returns whether a given packet defined by its enum value is supported. */
648 enum packet_support packet_support (int) const;
649
650 /* Returns the packet's corresponding "set remote foo-packet" command
651 state. See struct packet_config for more details. */
652 enum auto_boolean packet_set_cmd_state (int packet) const
653 { return m_protocol_packets[packet].detect; }
654
655 /* Returns true if the multi-process extensions are in effect. */
656 int remote_multi_process_p () const
657 { return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE; }
658
659 /* Returns true if fork events are supported. */
660 int remote_fork_event_p () const
661 { return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE; }
662
663 /* Returns true if vfork events are supported. */
664 int remote_vfork_event_p () const
665 { return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE; }
666
667 /* Returns true if exec events are supported. */
668 int remote_exec_event_p () const
669 { return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE; }
670
671 /* Returns true if memory tagging is supported, false otherwise. */
672 bool remote_memory_tagging_p () const
673 { return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE; }
674
675 /* Reset all packets back to "unknown support". Called when opening a
676 new connection to a remote target. */
677 void reset_all_packet_configs_support ();
678
679 /* Check result value in BUF for packet WHICH_PACKET and update the packet's
680 support configuration accordingly. */
681 packet_result packet_ok (const char *buf, const int which_packet);
682 packet_result packet_ok (const gdb::char_vector &buf, const int which_packet);
683
684 /* Configuration of a remote target's memory read packet. */
685 memory_packet_config m_memory_read_packet_config;
686 /* Configuration of a remote target's memory write packet. */
687 memory_packet_config m_memory_write_packet_config;
688
689 /* The per-remote target array which stores a remote's packet
690 configurations. */
691 packet_config m_protocol_packets[PACKET_MAX];
692 };
693
694 class remote_target : public process_stratum_target
695 {
696 public:
697 remote_target () = default;
698 ~remote_target () override;
699
700 const target_info &info () const override
701 { return remote_target_info; }
702
703 const char *connection_string () override;
704
705 thread_control_capabilities get_thread_control_capabilities () override
706 { return tc_schedlock; }
707
708 /* Open a remote connection. */
709 static void open (const char *, int);
710
711 void close () override;
712
713 void detach (inferior *, int) override;
714 void disconnect (const char *, int) override;
715
716 void commit_resumed () override;
717 void resume (ptid_t, int, enum gdb_signal) override;
718 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
719 bool has_pending_events () override;
720
721 void fetch_registers (struct regcache *, int) override;
722 void store_registers (struct regcache *, int) override;
723 void prepare_to_store (struct regcache *) override;
724
725 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
726
727 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
728 enum remove_bp_reason) override;
729
730
731 bool stopped_by_sw_breakpoint () override;
732 bool supports_stopped_by_sw_breakpoint () override;
733
734 bool stopped_by_hw_breakpoint () override;
735
736 bool supports_stopped_by_hw_breakpoint () override;
737
738 bool stopped_by_watchpoint () override;
739
740 bool stopped_data_address (CORE_ADDR *) override;
741
742 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
743
744 int can_use_hw_breakpoint (enum bptype, int, int) override;
745
746 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
747
748 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
749
750 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
751
752 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
753 struct expression *) override;
754
755 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
756 struct expression *) override;
757
758 void kill () override;
759
760 void load (const char *, int) override;
761
762 void mourn_inferior () override;
763
764 void pass_signals (gdb::array_view<const unsigned char>) override;
765
766 int set_syscall_catchpoint (int, bool, int,
767 gdb::array_view<const int>) override;
768
769 void program_signals (gdb::array_view<const unsigned char>) override;
770
771 bool thread_alive (ptid_t ptid) override;
772
773 const char *thread_name (struct thread_info *) override;
774
775 void update_thread_list () override;
776
777 std::string pid_to_str (ptid_t) override;
778
779 const char *extra_thread_info (struct thread_info *) override;
780
781 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
782
783 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
784 int handle_len,
785 inferior *inf) override;
786
787 gdb::byte_vector thread_info_to_thread_handle (struct thread_info *tp)
788 override;
789
790 void stop (ptid_t) override;
791
792 void interrupt () override;
793
794 void pass_ctrlc () override;
795
796 enum target_xfer_status xfer_partial (enum target_object object,
797 const char *annex,
798 gdb_byte *readbuf,
799 const gdb_byte *writebuf,
800 ULONGEST offset, ULONGEST len,
801 ULONGEST *xfered_len) override;
802
803 ULONGEST get_memory_xfer_limit () override;
804
805 void rcmd (const char *command, struct ui_file *output) override;
806
807 const char *pid_to_exec_file (int pid) override;
808
809 void log_command (const char *cmd) override
810 {
811 serial_log_command (this, cmd);
812 }
813
814 CORE_ADDR get_thread_local_address (ptid_t ptid,
815 CORE_ADDR load_module_addr,
816 CORE_ADDR offset) override;
817
818 bool can_execute_reverse () override;
819
820 std::vector<mem_region> memory_map () override;
821
822 void flash_erase (ULONGEST address, LONGEST length) override;
823
824 void flash_done () override;
825
826 const struct target_desc *read_description () override;
827
828 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
829 const gdb_byte *pattern, ULONGEST pattern_len,
830 CORE_ADDR *found_addrp) override;
831
832 bool can_async_p () override;
833
834 bool is_async_p () override;
835
836 void async (bool) override;
837
838 int async_wait_fd () override;
839
840 void thread_events (int) override;
841
842 int can_do_single_step () override;
843
844 void terminal_inferior () override;
845
846 void terminal_ours () override;
847
848 bool supports_non_stop () override;
849
850 bool supports_multi_process () override;
851
852 bool supports_disable_randomization () override;
853
854 bool filesystem_is_local () override;
855
856
857 int fileio_open (struct inferior *inf, const char *filename,
858 int flags, int mode, int warn_if_slow,
859 fileio_error *target_errno) override;
860
861 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
862 ULONGEST offset, fileio_error *target_errno) override;
863
864 int fileio_pread (int fd, gdb_byte *read_buf, int len,
865 ULONGEST offset, fileio_error *target_errno) override;
866
867 int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
868
869 int fileio_close (int fd, fileio_error *target_errno) override;
870
871 int fileio_unlink (struct inferior *inf,
872 const char *filename,
873 fileio_error *target_errno) override;
874
875 gdb::optional<std::string>
876 fileio_readlink (struct inferior *inf,
877 const char *filename,
878 fileio_error *target_errno) override;
879
880 bool supports_enable_disable_tracepoint () override;
881
882 bool supports_string_tracing () override;
883
884 int remote_supports_cond_tracepoints ();
885
886 bool supports_evaluation_of_breakpoint_conditions () override;
887
888 int remote_supports_fast_tracepoints ();
889
890 int remote_supports_static_tracepoints ();
891
892 int remote_supports_install_in_trace ();
893
894 bool can_run_breakpoint_commands () override;
895
896 void trace_init () override;
897
898 void download_tracepoint (struct bp_location *location) override;
899
900 bool can_download_tracepoint () override;
901
902 void download_trace_state_variable (const trace_state_variable &tsv) override;
903
904 void enable_tracepoint (struct bp_location *location) override;
905
906 void disable_tracepoint (struct bp_location *location) override;
907
908 void trace_set_readonly_regions () override;
909
910 void trace_start () override;
911
912 int get_trace_status (struct trace_status *ts) override;
913
914 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
915 override;
916
917 void trace_stop () override;
918
919 int trace_find (enum trace_find_type type, int num,
920 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
921
922 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
923
924 int save_trace_data (const char *filename) override;
925
926 int upload_tracepoints (struct uploaded_tp **utpp) override;
927
928 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
929
930 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
931
932 int get_min_fast_tracepoint_insn_len () override;
933
934 void set_disconnected_tracing (int val) override;
935
936 void set_circular_trace_buffer (int val) override;
937
938 void set_trace_buffer_size (LONGEST val) override;
939
940 bool set_trace_notes (const char *user, const char *notes,
941 const char *stopnotes) override;
942
943 int core_of_thread (ptid_t ptid) override;
944
945 int verify_memory (const gdb_byte *data,
946 CORE_ADDR memaddr, ULONGEST size) override;
947
948
949 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
950
951 void set_permissions () override;
952
953 bool static_tracepoint_marker_at (CORE_ADDR,
954 struct static_tracepoint_marker *marker)
955 override;
956
957 std::vector<static_tracepoint_marker>
958 static_tracepoint_markers_by_strid (const char *id) override;
959
960 traceframe_info_up traceframe_info () override;
961
962 bool use_agent (bool use) override;
963 bool can_use_agent () override;
964
965 struct btrace_target_info *
966 enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
967
968 void disable_btrace (struct btrace_target_info *tinfo) override;
969
970 void teardown_btrace (struct btrace_target_info *tinfo) override;
971
972 enum btrace_error read_btrace (struct btrace_data *data,
973 struct btrace_target_info *btinfo,
974 enum btrace_read_type type) override;
975
976 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
977 bool augmented_libraries_svr4_read () override;
978 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
979 void follow_exec (inferior *, ptid_t, const char *) override;
980 int insert_fork_catchpoint (int) override;
981 int remove_fork_catchpoint (int) override;
982 int insert_vfork_catchpoint (int) override;
983 int remove_vfork_catchpoint (int) override;
984 int insert_exec_catchpoint (int) override;
985 int remove_exec_catchpoint (int) override;
986 enum exec_direction_kind execution_direction () override;
987
988 bool supports_memory_tagging () override;
989
990 bool fetch_memtags (CORE_ADDR address, size_t len,
991 gdb::byte_vector &tags, int type) override;
992
993 bool store_memtags (CORE_ADDR address, size_t len,
994 const gdb::byte_vector &tags, int type) override;
995
996 public: /* Remote specific methods. */
997
998 void remote_download_command_source (int num, ULONGEST addr,
999 struct command_line *cmds);
1000
1001 void remote_file_put (const char *local_file, const char *remote_file,
1002 int from_tty);
1003 void remote_file_get (const char *remote_file, const char *local_file,
1004 int from_tty);
1005 void remote_file_delete (const char *remote_file, int from_tty);
1006
1007 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
1008 ULONGEST offset, fileio_error *remote_errno);
1009 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
1010 ULONGEST offset, fileio_error *remote_errno);
1011 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
1012 ULONGEST offset, fileio_error *remote_errno);
1013
1014 int remote_hostio_send_command (int command_bytes, int which_packet,
1015 fileio_error *remote_errno, const char **attachment,
1016 int *attachment_len);
1017 int remote_hostio_set_filesystem (struct inferior *inf,
1018 fileio_error *remote_errno);
1019 /* We should get rid of this and use fileio_open directly. */
1020 int remote_hostio_open (struct inferior *inf, const char *filename,
1021 int flags, int mode, int warn_if_slow,
1022 fileio_error *remote_errno);
1023 int remote_hostio_close (int fd, fileio_error *remote_errno);
1024
1025 int remote_hostio_unlink (inferior *inf, const char *filename,
1026 fileio_error *remote_errno);
1027
1028 struct remote_state *get_remote_state ();
1029
1030 long get_remote_packet_size (void);
1031 long get_memory_packet_size (struct memory_packet_config *config);
1032
1033 long get_memory_write_packet_size ();
1034 long get_memory_read_packet_size ();
1035
1036 char *append_pending_thread_resumptions (char *p, char *endp,
1037 ptid_t ptid);
1038 static void open_1 (const char *name, int from_tty, int extended_p);
1039 void start_remote (int from_tty, int extended_p);
1040 void remote_detach_1 (struct inferior *inf, int from_tty);
1041
1042 char *append_resumption (char *p, char *endp,
1043 ptid_t ptid, int step, gdb_signal siggnal);
1044 int remote_resume_with_vcont (ptid_t scope_ptid, int step,
1045 gdb_signal siggnal);
1046
1047 thread_info *add_current_inferior_and_thread (const char *wait_status);
1048
1049 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
1050 target_wait_flags options);
1051 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
1052 target_wait_flags options);
1053
1054 ptid_t process_stop_reply (struct stop_reply *stop_reply,
1055 target_waitstatus *status);
1056
1057 ptid_t select_thread_for_ambiguous_stop_reply
1058 (const struct target_waitstatus &status);
1059
1060 void remote_notice_new_inferior (ptid_t currthread, bool executing);
1061
1062 void print_one_stopped_thread (thread_info *thread);
1063 void process_initial_stop_replies (int from_tty);
1064
1065 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
1066 bool silent_p);
1067
1068 void btrace_sync_conf (const btrace_config *conf);
1069
1070 void remote_btrace_maybe_reopen ();
1071
1072 void remove_new_fork_children (threads_listing_context *context);
1073 void kill_new_fork_children (inferior *inf);
1074 void discard_pending_stop_replies (struct inferior *inf);
1075 int stop_reply_queue_length ();
1076
1077 void check_pending_events_prevent_wildcard_vcont
1078 (bool *may_global_wildcard_vcont);
1079
1080 void discard_pending_stop_replies_in_queue ();
1081 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
1082 struct stop_reply *queued_stop_reply (ptid_t ptid);
1083 int peek_stop_reply (ptid_t ptid);
1084 void remote_parse_stop_reply (const char *buf, stop_reply *event);
1085
1086 void remote_stop_ns (ptid_t ptid);
1087 void remote_interrupt_as ();
1088 void remote_interrupt_ns ();
1089
1090 char *remote_get_noisy_reply ();
1091 int remote_query_attached (int pid);
1092 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
1093 int try_open_exec);
1094
1095 ptid_t remote_current_thread (ptid_t oldpid);
1096 ptid_t get_current_thread (const char *wait_status);
1097
1098 void set_thread (ptid_t ptid, int gen);
1099 void set_general_thread (ptid_t ptid);
1100 void set_continue_thread (ptid_t ptid);
1101 void set_general_process ();
1102
1103 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
1104
1105 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
1106 gdb_ext_thread_info *info);
1107 int remote_get_threadinfo (threadref *threadid, int fieldset,
1108 gdb_ext_thread_info *info);
1109
1110 int parse_threadlist_response (const char *pkt, int result_limit,
1111 threadref *original_echo,
1112 threadref *resultlist,
1113 int *doneflag);
1114 int remote_get_threadlist (int startflag, threadref *nextthread,
1115 int result_limit, int *done, int *result_count,
1116 threadref *threadlist);
1117
1118 int remote_threadlist_iterator (rmt_thread_action stepfunction,
1119 void *context, int looplimit);
1120
1121 int remote_get_threads_with_ql (threads_listing_context *context);
1122 int remote_get_threads_with_qxfer (threads_listing_context *context);
1123 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
1124
1125 void extended_remote_restart ();
1126
1127 void get_offsets ();
1128
1129 void remote_check_symbols ();
1130
1131 void remote_supported_packet (const struct protocol_feature *feature,
1132 enum packet_support support,
1133 const char *argument);
1134
1135 void remote_query_supported ();
1136
1137 void remote_packet_size (const protocol_feature *feature,
1138 packet_support support, const char *value);
1139
1140 void remote_serial_quit_handler ();
1141
1142 void remote_detach_pid (int pid);
1143
1144 void remote_vcont_probe ();
1145
1146 void remote_resume_with_hc (ptid_t ptid, int step,
1147 gdb_signal siggnal);
1148
1149 void send_interrupt_sequence ();
1150 void interrupt_query ();
1151
1152 void remote_notif_get_pending_events (const notif_client *nc);
1153
1154 int fetch_register_using_p (struct regcache *regcache,
1155 packet_reg *reg);
1156 int send_g_packet ();
1157 void process_g_packet (struct regcache *regcache);
1158 void fetch_registers_using_g (struct regcache *regcache);
1159 int store_register_using_P (const struct regcache *regcache,
1160 packet_reg *reg);
1161 void store_registers_using_G (const struct regcache *regcache);
1162
1163 void set_remote_traceframe ();
1164
1165 void check_binary_download (CORE_ADDR addr);
1166
1167 target_xfer_status remote_write_bytes_aux (const char *header,
1168 CORE_ADDR memaddr,
1169 const gdb_byte *myaddr,
1170 ULONGEST len_units,
1171 int unit_size,
1172 ULONGEST *xfered_len_units,
1173 char packet_format,
1174 int use_length);
1175
1176 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
1177 const gdb_byte *myaddr, ULONGEST len,
1178 int unit_size, ULONGEST *xfered_len);
1179
1180 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
1181 ULONGEST len_units,
1182 int unit_size, ULONGEST *xfered_len_units);
1183
1184 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
1185 ULONGEST memaddr,
1186 ULONGEST len,
1187 int unit_size,
1188 ULONGEST *xfered_len);
1189
1190 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
1191 gdb_byte *myaddr, ULONGEST len,
1192 int unit_size,
1193 ULONGEST *xfered_len);
1194
1195 packet_result remote_send_printf (const char *format, ...)
1196 ATTRIBUTE_PRINTF (2, 3);
1197
1198 target_xfer_status remote_flash_write (ULONGEST address,
1199 ULONGEST length, ULONGEST *xfered_len,
1200 const gdb_byte *data);
1201
1202 int readchar (int timeout);
1203
1204 void remote_serial_write (const char *str, int len);
1205
1206 int putpkt (const char *buf);
1207 int putpkt_binary (const char *buf, int cnt);
1208
1209 int putpkt (const gdb::char_vector &buf)
1210 {
1211 return putpkt (buf.data ());
1212 }
1213
1214 void skip_frame ();
1215 long read_frame (gdb::char_vector *buf_p);
1216 void getpkt (gdb::char_vector *buf, int forever);
1217 int getpkt_or_notif_sane_1 (gdb::char_vector *buf, int forever,
1218 int expecting_notif, int *is_notif);
1219 int getpkt_sane (gdb::char_vector *buf, int forever);
1220 int getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
1221 int *is_notif);
1222 int remote_vkill (int pid);
1223 void remote_kill_k ();
1224
1225 void extended_remote_disable_randomization (int val);
1226 int extended_remote_run (const std::string &args);
1227
1228 void send_environment_packet (const char *action,
1229 const char *packet,
1230 const char *value);
1231
1232 void extended_remote_environment_support ();
1233 void extended_remote_set_inferior_cwd ();
1234
1235 target_xfer_status remote_write_qxfer (const char *object_name,
1236 const char *annex,
1237 const gdb_byte *writebuf,
1238 ULONGEST offset, LONGEST len,
1239 ULONGEST *xfered_len,
1240 const unsigned int which_packet);
1241
1242 target_xfer_status remote_read_qxfer (const char *object_name,
1243 const char *annex,
1244 gdb_byte *readbuf, ULONGEST offset,
1245 LONGEST len,
1246 ULONGEST *xfered_len,
1247 const unsigned int which_packet);
1248
1249 void push_stop_reply (struct stop_reply *new_event);
1250
1251 bool vcont_r_supported ();
1252
1253 remote_features m_features;
1254
1255 private:
1256
1257 bool start_remote_1 (int from_tty, int extended_p);
1258
1259 /* The remote state. Don't reference this directly. Use the
1260 get_remote_state method instead. */
1261 remote_state m_remote_state;
1262 };
1263
1264 static const target_info extended_remote_target_info = {
1265 "extended-remote",
1266 N_("Extended remote target using gdb-specific protocol"),
1267 remote_doc
1268 };
1269
1270 /* Set up the extended remote target by extending the standard remote
1271 target and adding to it. */
1272
1273 class extended_remote_target final : public remote_target
1274 {
1275 public:
1276 const target_info &info () const override
1277 { return extended_remote_target_info; }
1278
1279 /* Open an extended-remote connection. */
1280 static void open (const char *, int);
1281
1282 bool can_create_inferior () override { return true; }
1283 void create_inferior (const char *, const std::string &,
1284 char **, int) override;
1285
1286 void detach (inferior *, int) override;
1287
1288 bool can_attach () override { return true; }
1289 void attach (const char *, int) override;
1290
1291 void post_attach (int) override;
1292 bool supports_disable_randomization () override;
1293 };
1294
1295 struct stop_reply : public notif_event
1296 {
1297 ~stop_reply ();
1298
1299 /* The identifier of the thread about this event */
1300 ptid_t ptid;
1301
1302 /* The remote state this event is associated with. When the remote
1303 connection, represented by a remote_state object, is closed,
1304 all the associated stop_reply events should be released. */
1305 struct remote_state *rs;
1306
1307 struct target_waitstatus ws;
1308
1309 /* The architecture associated with the expedited registers. */
1310 gdbarch *arch;
1311
1312 /* Expedited registers. This makes remote debugging a bit more
1313 efficient for those targets that provide critical registers as
1314 part of their normal status mechanism (as another roundtrip to
1315 fetch them is avoided). */
1316 std::vector<cached_reg_t> regcache;
1317
1318 enum target_stop_reason stop_reason;
1319
1320 CORE_ADDR watch_data_address;
1321
1322 int core;
1323 };
1324
1325 /* Return TARGET as a remote_target if it is one, else nullptr. */
1326
1327 static remote_target *
1328 as_remote_target (process_stratum_target *target)
1329 {
1330 return dynamic_cast<remote_target *> (target);
1331 }
1332
1333 /* See remote.h. */
1334
1335 bool
1336 is_remote_target (process_stratum_target *target)
1337 {
1338 return as_remote_target (target) != nullptr;
1339 }
1340
1341 /* Per-program-space data key. */
1342 static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
1343 remote_pspace_data;
1344
1345 /* The variable registered as the control variable used by the
1346 remote exec-file commands. While the remote exec-file setting is
1347 per-program-space, the set/show machinery uses this as the
1348 location of the remote exec-file value. */
1349 static std::string remote_exec_file_var;
1350
1351 /* The size to align memory write packets, when practical. The protocol
1352 does not guarantee any alignment, and gdb will generate short
1353 writes and unaligned writes, but even as a best-effort attempt this
1354 can improve bulk transfers. For instance, if a write is misaligned
1355 relative to the target's data bus, the stub may need to make an extra
1356 round trip fetching data from the target. This doesn't make a
1357 huge difference, but it's easy to do, so we try to be helpful.
1358
1359 The alignment chosen is arbitrary; usually data bus width is
1360 important here, not the possibly larger cache line size. */
1361 enum { REMOTE_ALIGN_WRITES = 16 };
1362
1363 /* Prototypes for local functions. */
1364
1365 static int hexnumlen (ULONGEST num);
1366
1367 static int stubhex (int ch);
1368
1369 static int hexnumstr (char *, ULONGEST);
1370
1371 static int hexnumnstr (char *, ULONGEST, int);
1372
1373 static CORE_ADDR remote_address_masked (CORE_ADDR);
1374
1375 static int stub_unpack_int (const char *buff, int fieldlength);
1376
1377 static void set_remote_protocol_packet_cmd (const char *args, int from_tty,
1378 cmd_list_element *c);
1379
1380 static void show_packet_config_cmd (ui_file *file,
1381 const unsigned int which_packet,
1382 remote_target *remote);
1383
1384 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1385 int from_tty,
1386 struct cmd_list_element *c,
1387 const char *value);
1388
1389 static ptid_t read_ptid (const char *buf, const char **obuf);
1390
1391 static void remote_async_inferior_event_handler (gdb_client_data);
1392
1393 static bool remote_read_description_p (struct target_ops *target);
1394
1395 static void remote_console_output (const char *msg);
1396
1397 static void remote_btrace_reset (remote_state *rs);
1398
1399 static void remote_unpush_and_throw (remote_target *target);
1400
1401 /* For "remote". */
1402
1403 static struct cmd_list_element *remote_cmdlist;
1404
1405 /* For "set remote" and "show remote". */
1406
1407 static struct cmd_list_element *remote_set_cmdlist;
1408 static struct cmd_list_element *remote_show_cmdlist;
1409
1410 /* Controls whether GDB is willing to use range stepping. */
1411
1412 static bool use_range_stepping = true;
1413
1414 /* From the remote target's point of view, each thread is in one of these three
1415 states. */
1416 enum class resume_state
1417 {
1418 /* Not resumed - we haven't been asked to resume this thread. */
1419 NOT_RESUMED,
1420
1421 /* We have been asked to resume this thread, but haven't sent a vCont action
1422 for it yet. We'll need to consider it next time commit_resume is
1423 called. */
1424 RESUMED_PENDING_VCONT,
1425
1426 /* We have been asked to resume this thread, and we have sent a vCont action
1427 for it. */
1428 RESUMED,
1429 };
1430
1431 /* Information about a thread's pending vCont-resume. Used when a thread is in
1432 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1433 stores this information which is then picked up by
1434 remote_target::commit_resume to know which is the proper action for this
1435 thread to include in the vCont packet. */
1436 struct resumed_pending_vcont_info
1437 {
1438 /* True if the last resume call for this thread was a step request, false
1439 if a continue request. */
1440 bool step;
1441
1442 /* The signal specified in the last resume call for this thread. */
1443 gdb_signal sig;
1444 };
1445
1446 /* Private data that we'll store in (struct thread_info)->priv. */
1447 struct remote_thread_info : public private_thread_info
1448 {
1449 std::string extra;
1450 std::string name;
1451 int core = -1;
1452
1453 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1454 sequence of bytes. */
1455 gdb::byte_vector thread_handle;
1456
1457 /* Whether the target stopped for a breakpoint/watchpoint. */
1458 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1459
1460 /* This is set to the data address of the access causing the target
1461 to stop for a watchpoint. */
1462 CORE_ADDR watch_data_address = 0;
1463
1464 /* Get the thread's resume state. */
1465 enum resume_state get_resume_state () const
1466 {
1467 return m_resume_state;
1468 }
1469
1470 /* Put the thread in the NOT_RESUMED state. */
1471 void set_not_resumed ()
1472 {
1473 m_resume_state = resume_state::NOT_RESUMED;
1474 }
1475
1476 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1477 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1478 {
1479 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1480 m_resumed_pending_vcont_info.step = step;
1481 m_resumed_pending_vcont_info.sig = sig;
1482 }
1483
1484 /* Get the information this thread's pending vCont-resumption.
1485
1486 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1487 state. */
1488 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1489 {
1490 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1491
1492 return m_resumed_pending_vcont_info;
1493 }
1494
1495 /* Put the thread in the VCONT_RESUMED state. */
1496 void set_resumed ()
1497 {
1498 m_resume_state = resume_state::RESUMED;
1499 }
1500
1501 private:
1502 /* Resume state for this thread. This is used to implement vCont action
1503 coalescing (only when the target operates in non-stop mode).
1504
1505 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1506 which notes that this thread must be considered in the next commit_resume
1507 call.
1508
1509 remote_target::commit_resume sends a vCont packet with actions for the
1510 threads in the RESUMED_PENDING_VCONT state and moves them to the
1511 VCONT_RESUMED state.
1512
1513 When reporting a stop to the core for a thread, that thread is moved back
1514 to the NOT_RESUMED state. */
1515 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1516
1517 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1518 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1519 };
1520
1521 remote_state::remote_state ()
1522 : buf (400)
1523 {
1524 }
1525
1526 remote_state::~remote_state ()
1527 {
1528 xfree (this->last_pass_packet);
1529 xfree (this->last_program_signals_packet);
1530 xfree (this->finished_object);
1531 xfree (this->finished_annex);
1532 }
1533
1534 /* Utility: generate error from an incoming stub packet. */
1535 static void
1536 trace_error (char *buf)
1537 {
1538 if (*buf++ != 'E')
1539 return; /* not an error msg */
1540 switch (*buf)
1541 {
1542 case '1': /* malformed packet error */
1543 if (*++buf == '0') /* general case: */
1544 error (_("remote.c: error in outgoing packet."));
1545 else
1546 error (_("remote.c: error in outgoing packet at field #%ld."),
1547 strtol (buf, NULL, 16));
1548 default:
1549 error (_("Target returns error code '%s'."), buf);
1550 }
1551 }
1552
1553 /* Utility: wait for reply from stub, while accepting "O" packets. */
1554
1555 char *
1556 remote_target::remote_get_noisy_reply ()
1557 {
1558 struct remote_state *rs = get_remote_state ();
1559
1560 do /* Loop on reply from remote stub. */
1561 {
1562 char *buf;
1563
1564 QUIT; /* Allow user to bail out with ^C. */
1565 getpkt (&rs->buf, 0);
1566 buf = rs->buf.data ();
1567 if (buf[0] == 'E')
1568 trace_error (buf);
1569 else if (startswith (buf, "qRelocInsn:"))
1570 {
1571 ULONGEST ul;
1572 CORE_ADDR from, to, org_to;
1573 const char *p, *pp;
1574 int adjusted_size = 0;
1575 int relocated = 0;
1576
1577 p = buf + strlen ("qRelocInsn:");
1578 pp = unpack_varlen_hex (p, &ul);
1579 if (*pp != ';')
1580 error (_("invalid qRelocInsn packet: %s"), buf);
1581 from = ul;
1582
1583 p = pp + 1;
1584 unpack_varlen_hex (p, &ul);
1585 to = ul;
1586
1587 org_to = to;
1588
1589 try
1590 {
1591 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
1592 relocated = 1;
1593 }
1594 catch (const gdb_exception &ex)
1595 {
1596 if (ex.error == MEMORY_ERROR)
1597 {
1598 /* Propagate memory errors silently back to the
1599 target. The stub may have limited the range of
1600 addresses we can write to, for example. */
1601 }
1602 else
1603 {
1604 /* Something unexpectedly bad happened. Be verbose
1605 so we can tell what, and propagate the error back
1606 to the stub, so it doesn't get stuck waiting for
1607 a response. */
1608 exception_fprintf (gdb_stderr, ex,
1609 _("warning: relocating instruction: "));
1610 }
1611 putpkt ("E01");
1612 }
1613
1614 if (relocated)
1615 {
1616 adjusted_size = to - org_to;
1617
1618 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1619 putpkt (buf);
1620 }
1621 }
1622 else if (buf[0] == 'O' && buf[1] != 'K')
1623 remote_console_output (buf + 1); /* 'O' message from stub */
1624 else
1625 return buf; /* Here's the actual reply. */
1626 }
1627 while (1);
1628 }
1629
1630 struct remote_arch_state *
1631 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1632 {
1633 remote_arch_state *rsa;
1634
1635 auto it = this->m_arch_states.find (gdbarch);
1636 if (it == this->m_arch_states.end ())
1637 {
1638 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1639 std::forward_as_tuple (gdbarch),
1640 std::forward_as_tuple (gdbarch));
1641 rsa = &p.first->second;
1642
1643 /* Make sure that the packet buffer is plenty big enough for
1644 this architecture. */
1645 if (this->buf.size () < rsa->remote_packet_size)
1646 this->buf.resize (2 * rsa->remote_packet_size);
1647 }
1648 else
1649 rsa = &it->second;
1650
1651 return rsa;
1652 }
1653
1654 /* Fetch the global remote target state. */
1655
1656 remote_state *
1657 remote_target::get_remote_state ()
1658 {
1659 /* Make sure that the remote architecture state has been
1660 initialized, because doing so might reallocate rs->buf. Any
1661 function which calls getpkt also needs to be mindful of changes
1662 to rs->buf, but this call limits the number of places which run
1663 into trouble. */
1664 m_remote_state.get_remote_arch_state (target_gdbarch ());
1665
1666 return &m_remote_state;
1667 }
1668
1669 /* Fetch the remote exec-file from the current program space. */
1670
1671 static const char *
1672 get_remote_exec_file (void)
1673 {
1674 char *remote_exec_file;
1675
1676 remote_exec_file = remote_pspace_data.get (current_program_space);
1677 if (remote_exec_file == NULL)
1678 return "";
1679
1680 return remote_exec_file;
1681 }
1682
1683 /* Set the remote exec file for PSPACE. */
1684
1685 static void
1686 set_pspace_remote_exec_file (struct program_space *pspace,
1687 const char *remote_exec_file)
1688 {
1689 char *old_file = remote_pspace_data.get (pspace);
1690
1691 xfree (old_file);
1692 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1693 }
1694
1695 /* The "set/show remote exec-file" set command hook. */
1696
1697 static void
1698 set_remote_exec_file (const char *ignored, int from_tty,
1699 struct cmd_list_element *c)
1700 {
1701 set_pspace_remote_exec_file (current_program_space,
1702 remote_exec_file_var.c_str ());
1703 }
1704
1705 /* The "set/show remote exec-file" show command hook. */
1706
1707 static void
1708 show_remote_exec_file (struct ui_file *file, int from_tty,
1709 struct cmd_list_element *cmd, const char *value)
1710 {
1711 gdb_printf (file, "%s\n", get_remote_exec_file ());
1712 }
1713
1714 static int
1715 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1716 {
1717 int regnum, num_remote_regs, offset;
1718 struct packet_reg **remote_regs;
1719
1720 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1721 {
1722 struct packet_reg *r = &regs[regnum];
1723
1724 if (register_size (gdbarch, regnum) == 0)
1725 /* Do not try to fetch zero-sized (placeholder) registers. */
1726 r->pnum = -1;
1727 else
1728 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1729
1730 r->regnum = regnum;
1731 }
1732
1733 /* Define the g/G packet format as the contents of each register
1734 with a remote protocol number, in order of ascending protocol
1735 number. */
1736
1737 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1738 for (num_remote_regs = 0, regnum = 0;
1739 regnum < gdbarch_num_regs (gdbarch);
1740 regnum++)
1741 if (regs[regnum].pnum != -1)
1742 remote_regs[num_remote_regs++] = &regs[regnum];
1743
1744 std::sort (remote_regs, remote_regs + num_remote_regs,
1745 [] (const packet_reg *a, const packet_reg *b)
1746 { return a->pnum < b->pnum; });
1747
1748 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1749 {
1750 remote_regs[regnum]->in_g_packet = 1;
1751 remote_regs[regnum]->offset = offset;
1752 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1753 }
1754
1755 return offset;
1756 }
1757
1758 /* Given the architecture described by GDBARCH, return the remote
1759 protocol register's number and the register's offset in the g/G
1760 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1761 If the target does not have a mapping for REGNUM, return false,
1762 otherwise, return true. */
1763
1764 int
1765 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1766 int *pnum, int *poffset)
1767 {
1768 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1769
1770 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1771
1772 map_regcache_remote_table (gdbarch, regs.data ());
1773
1774 *pnum = regs[regnum].pnum;
1775 *poffset = regs[regnum].offset;
1776
1777 return *pnum != -1;
1778 }
1779
1780 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1781 {
1782 /* Use the architecture to build a regnum<->pnum table, which will be
1783 1:1 unless a feature set specifies otherwise. */
1784 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1785
1786 /* Record the maximum possible size of the g packet - it may turn out
1787 to be smaller. */
1788 this->sizeof_g_packet
1789 = map_regcache_remote_table (gdbarch, this->regs.get ());
1790
1791 /* Default maximum number of characters in a packet body. Many
1792 remote stubs have a hardwired buffer size of 400 bytes
1793 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1794 as the maximum packet-size to ensure that the packet and an extra
1795 NUL character can always fit in the buffer. This stops GDB
1796 trashing stubs that try to squeeze an extra NUL into what is
1797 already a full buffer (As of 1999-12-04 that was most stubs). */
1798 this->remote_packet_size = 400 - 1;
1799
1800 /* This one is filled in when a ``g'' packet is received. */
1801 this->actual_register_packet_size = 0;
1802
1803 /* Should rsa->sizeof_g_packet needs more space than the
1804 default, adjust the size accordingly. Remember that each byte is
1805 encoded as two characters. 32 is the overhead for the packet
1806 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1807 (``$NN:G...#NN'') is a better guess, the below has been padded a
1808 little. */
1809 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1810 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1811 }
1812
1813 /* Get a pointer to the current remote target. If not connected to a
1814 remote target, return NULL. */
1815
1816 static remote_target *
1817 get_current_remote_target ()
1818 {
1819 target_ops *proc_target = current_inferior ()->process_target ();
1820 return dynamic_cast<remote_target *> (proc_target);
1821 }
1822
1823 /* Return the current allowed size of a remote packet. This is
1824 inferred from the current architecture, and should be used to
1825 limit the length of outgoing packets. */
1826 long
1827 remote_target::get_remote_packet_size ()
1828 {
1829 struct remote_state *rs = get_remote_state ();
1830 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1831
1832 if (rs->explicit_packet_size)
1833 return rs->explicit_packet_size;
1834
1835 return rsa->remote_packet_size;
1836 }
1837
1838 static struct packet_reg *
1839 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1840 long regnum)
1841 {
1842 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1843 return NULL;
1844 else
1845 {
1846 struct packet_reg *r = &rsa->regs[regnum];
1847
1848 gdb_assert (r->regnum == regnum);
1849 return r;
1850 }
1851 }
1852
1853 static struct packet_reg *
1854 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1855 LONGEST pnum)
1856 {
1857 int i;
1858
1859 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1860 {
1861 struct packet_reg *r = &rsa->regs[i];
1862
1863 if (r->pnum == pnum)
1864 return r;
1865 }
1866 return NULL;
1867 }
1868
1869 /* Allow the user to specify what sequence to send to the remote
1870 when he requests a program interruption: Although ^C is usually
1871 what remote systems expect (this is the default, here), it is
1872 sometimes preferable to send a break. On other systems such
1873 as the Linux kernel, a break followed by g, which is Magic SysRq g
1874 is required in order to interrupt the execution. */
1875 const char interrupt_sequence_control_c[] = "Ctrl-C";
1876 const char interrupt_sequence_break[] = "BREAK";
1877 const char interrupt_sequence_break_g[] = "BREAK-g";
1878 static const char *const interrupt_sequence_modes[] =
1879 {
1880 interrupt_sequence_control_c,
1881 interrupt_sequence_break,
1882 interrupt_sequence_break_g,
1883 NULL
1884 };
1885 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1886
1887 static void
1888 show_interrupt_sequence (struct ui_file *file, int from_tty,
1889 struct cmd_list_element *c,
1890 const char *value)
1891 {
1892 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1893 gdb_printf (file,
1894 _("Send the ASCII ETX character (Ctrl-c) "
1895 "to the remote target to interrupt the "
1896 "execution of the program.\n"));
1897 else if (interrupt_sequence_mode == interrupt_sequence_break)
1898 gdb_printf (file,
1899 _("send a break signal to the remote target "
1900 "to interrupt the execution of the program.\n"));
1901 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1902 gdb_printf (file,
1903 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1904 "the remote target to interrupt the execution "
1905 "of Linux kernel.\n"));
1906 else
1907 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
1908 interrupt_sequence_mode);
1909 }
1910
1911 /* This boolean variable specifies whether interrupt_sequence is sent
1912 to the remote target when gdb connects to it.
1913 This is mostly needed when you debug the Linux kernel: The Linux kernel
1914 expects BREAK g which is Magic SysRq g for connecting gdb. */
1915 static bool interrupt_on_connect = false;
1916
1917 /* This variable is used to implement the "set/show remotebreak" commands.
1918 Since these commands are now deprecated in favor of "set/show remote
1919 interrupt-sequence", it no longer has any effect on the code. */
1920 static bool remote_break;
1921
1922 static void
1923 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1924 {
1925 if (remote_break)
1926 interrupt_sequence_mode = interrupt_sequence_break;
1927 else
1928 interrupt_sequence_mode = interrupt_sequence_control_c;
1929 }
1930
1931 static void
1932 show_remotebreak (struct ui_file *file, int from_tty,
1933 struct cmd_list_element *c,
1934 const char *value)
1935 {
1936 }
1937
1938 /* This variable sets the number of bits in an address that are to be
1939 sent in a memory ("M" or "m") packet. Normally, after stripping
1940 leading zeros, the entire address would be sent. This variable
1941 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1942 initial implementation of remote.c restricted the address sent in
1943 memory packets to ``host::sizeof long'' bytes - (typically 32
1944 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1945 address was never sent. Since fixing this bug may cause a break in
1946 some remote targets this variable is principally provided to
1947 facilitate backward compatibility. */
1948
1949 static unsigned int remote_address_size;
1950
1951 \f
1952 /* The default max memory-write-packet-size, when the setting is
1953 "fixed". The 16k is historical. (It came from older GDB's using
1954 alloca for buffers and the knowledge (folklore?) that some hosts
1955 don't cope very well with large alloca calls.) */
1956 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1957
1958 /* The minimum remote packet size for memory transfers. Ensures we
1959 can write at least one byte. */
1960 #define MIN_MEMORY_PACKET_SIZE 20
1961
1962 /* Get the memory packet size, assuming it is fixed. */
1963
1964 static long
1965 get_fixed_memory_packet_size (struct memory_packet_config *config)
1966 {
1967 gdb_assert (config->fixed_p);
1968
1969 if (config->size <= 0)
1970 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1971 else
1972 return config->size;
1973 }
1974
1975 /* Compute the current size of a read/write packet. Since this makes
1976 use of ``actual_register_packet_size'' the computation is dynamic. */
1977
1978 long
1979 remote_target::get_memory_packet_size (struct memory_packet_config *config)
1980 {
1981 struct remote_state *rs = get_remote_state ();
1982 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1983
1984 long what_they_get;
1985 if (config->fixed_p)
1986 what_they_get = get_fixed_memory_packet_size (config);
1987 else
1988 {
1989 what_they_get = get_remote_packet_size ();
1990 /* Limit the packet to the size specified by the user. */
1991 if (config->size > 0
1992 && what_they_get > config->size)
1993 what_they_get = config->size;
1994
1995 /* Limit it to the size of the targets ``g'' response unless we have
1996 permission from the stub to use a larger packet size. */
1997 if (rs->explicit_packet_size == 0
1998 && rsa->actual_register_packet_size > 0
1999 && what_they_get > rsa->actual_register_packet_size)
2000 what_they_get = rsa->actual_register_packet_size;
2001 }
2002 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
2003 what_they_get = MIN_MEMORY_PACKET_SIZE;
2004
2005 /* Make sure there is room in the global buffer for this packet
2006 (including its trailing NUL byte). */
2007 if (rs->buf.size () < what_they_get + 1)
2008 rs->buf.resize (2 * what_they_get);
2009
2010 return what_they_get;
2011 }
2012
2013 /* Update the size of a read/write packet. If they user wants
2014 something really big then do a sanity check. */
2015
2016 static void
2017 set_memory_packet_size (const char *args, struct memory_packet_config *config,
2018 bool target_connected)
2019 {
2020 int fixed_p = config->fixed_p;
2021 long size = config->size;
2022
2023 if (args == NULL)
2024 error (_("Argument required (integer, \"fixed\" or \"limit\")."));
2025 else if (strcmp (args, "hard") == 0
2026 || strcmp (args, "fixed") == 0)
2027 fixed_p = 1;
2028 else if (strcmp (args, "soft") == 0
2029 || strcmp (args, "limit") == 0)
2030 fixed_p = 0;
2031 else
2032 {
2033 char *end;
2034
2035 size = strtoul (args, &end, 0);
2036 if (args == end)
2037 error (_("Invalid %s (bad syntax)."), config->name);
2038
2039 /* Instead of explicitly capping the size of a packet to or
2040 disallowing it, the user is allowed to set the size to
2041 something arbitrarily large. */
2042 }
2043
2044 /* Extra checks? */
2045 if (fixed_p && !config->fixed_p)
2046 {
2047 /* So that the query shows the correct value. */
2048 long query_size = (size <= 0
2049 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
2050 : size);
2051
2052 if (target_connected
2053 && !query (_("The target may not be able to correctly handle a %s\n"
2054 "of %ld bytes. Change the packet size? "),
2055 config->name, query_size))
2056 error (_("Packet size not changed."));
2057 else if (!target_connected
2058 && !query (_("Future remote targets may not be able to "
2059 "correctly handle a %s\nof %ld bytes. Change the "
2060 "packet size for future remote targets? "),
2061 config->name, query_size))
2062 error (_("Packet size not changed."));
2063 }
2064 /* Update the config. */
2065 config->fixed_p = fixed_p;
2066 config->size = size;
2067
2068 const char *target_type = get_target_type_name (target_connected);
2069 gdb_printf (_("The %s %s is set to \"%s\".\n"), config->name, target_type,
2070 args);
2071
2072 }
2073
2074 /* Show the memory-read or write-packet size configuration CONFIG of the
2075 target REMOTE. If REMOTE is nullptr, the default configuration for future
2076 remote targets should be passed in CONFIG. */
2077
2078 static void
2079 show_memory_packet_size (memory_packet_config *config, remote_target *remote)
2080 {
2081 const char *target_type = get_target_type_name (remote != nullptr);
2082
2083 if (config->size == 0)
2084 gdb_printf (_("The %s %s is 0 (default). "), config->name, target_type);
2085 else
2086 gdb_printf (_("The %s %s is %ld. "), config->name, target_type,
2087 config->size);
2088
2089 if (config->fixed_p)
2090 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
2091 get_fixed_memory_packet_size (config));
2092 else
2093 {
2094 if (remote != nullptr)
2095 gdb_printf (_("Packets are limited to %ld bytes.\n"),
2096 remote->get_memory_packet_size (config));
2097 else
2098 gdb_puts ("The actual limit will be further reduced "
2099 "dependent on the target.\n");
2100 }
2101 }
2102
2103 /* Configure the memory-write-packet size of the currently selected target. If
2104 no target is available, the default configuration for future remote targets
2105 is configured. */
2106
2107 static void
2108 set_memory_write_packet_size (const char *args, int from_tty)
2109 {
2110 remote_target *remote = get_current_remote_target ();
2111 if (remote != nullptr)
2112 {
2113 set_memory_packet_size
2114 (args, &remote->m_features.m_memory_write_packet_config, true);
2115 }
2116 else
2117 {
2118 memory_packet_config* config = &memory_write_packet_config;
2119 set_memory_packet_size (args, config, false);
2120 }
2121 }
2122
2123 /* Display the memory-write-packet size of the currently selected target. If
2124 no target is available, the default configuration for future remote targets
2125 is shown. */
2126
2127 static void
2128 show_memory_write_packet_size (const char *args, int from_tty)
2129 {
2130 remote_target *remote = get_current_remote_target ();
2131 if (remote != nullptr)
2132 show_memory_packet_size (&remote->m_features.m_memory_write_packet_config,
2133 remote);
2134 else
2135 show_memory_packet_size (&memory_write_packet_config, nullptr);
2136 }
2137
2138 /* Show the number of hardware watchpoints that can be used. */
2139
2140 static void
2141 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
2142 struct cmd_list_element *c,
2143 const char *value)
2144 {
2145 gdb_printf (file, _("The maximum number of target hardware "
2146 "watchpoints is %s.\n"), value);
2147 }
2148
2149 /* Show the length limit (in bytes) for hardware watchpoints. */
2150
2151 static void
2152 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
2153 struct cmd_list_element *c,
2154 const char *value)
2155 {
2156 gdb_printf (file, _("The maximum length (in bytes) of a target "
2157 "hardware watchpoint is %s.\n"), value);
2158 }
2159
2160 /* Show the number of hardware breakpoints that can be used. */
2161
2162 static void
2163 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
2164 struct cmd_list_element *c,
2165 const char *value)
2166 {
2167 gdb_printf (file, _("The maximum number of target hardware "
2168 "breakpoints is %s.\n"), value);
2169 }
2170
2171 /* Controls the maximum number of characters to display in the debug output
2172 for each remote packet. The remaining characters are omitted. */
2173
2174 static int remote_packet_max_chars = 512;
2175
2176 /* Show the maximum number of characters to display for each remote packet
2177 when remote debugging is enabled. */
2178
2179 static void
2180 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
2181 struct cmd_list_element *c,
2182 const char *value)
2183 {
2184 gdb_printf (file, _("Number of remote packet characters to "
2185 "display is %s.\n"), value);
2186 }
2187
2188 long
2189 remote_target::get_memory_write_packet_size ()
2190 {
2191 return get_memory_packet_size (&m_features.m_memory_write_packet_config);
2192 }
2193
2194 /* Configure the memory-read-packet size of the currently selected target. If
2195 no target is available, the default configuration for future remote targets
2196 is adapted. */
2197
2198 static void
2199 set_memory_read_packet_size (const char *args, int from_tty)
2200 {
2201 remote_target *remote = get_current_remote_target ();
2202 if (remote != nullptr)
2203 set_memory_packet_size
2204 (args, &remote->m_features.m_memory_read_packet_config, true);
2205 else
2206 {
2207 memory_packet_config* config = &memory_read_packet_config;
2208 set_memory_packet_size (args, config, false);
2209 }
2210
2211 }
2212
2213 /* Display the memory-read-packet size of the currently selected target. If
2214 no target is available, the default configuration for future remote targets
2215 is shown. */
2216
2217 static void
2218 show_memory_read_packet_size (const char *args, int from_tty)
2219 {
2220 remote_target *remote = get_current_remote_target ();
2221 if (remote != nullptr)
2222 show_memory_packet_size (&remote->m_features.m_memory_read_packet_config,
2223 remote);
2224 else
2225 show_memory_packet_size (&memory_read_packet_config, nullptr);
2226 }
2227
2228 long
2229 remote_target::get_memory_read_packet_size ()
2230 {
2231 long size = get_memory_packet_size (&m_features.m_memory_read_packet_config);
2232
2233 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
2234 extra buffer size argument before the memory read size can be
2235 increased beyond this. */
2236 if (size > get_remote_packet_size ())
2237 size = get_remote_packet_size ();
2238 return size;
2239 }
2240
2241 static enum packet_support packet_config_support (const packet_config *config);
2242
2243
2244 static void
2245 set_remote_protocol_packet_cmd (const char *args, int from_tty,
2246 cmd_list_element *c)
2247 {
2248 remote_target *remote = get_current_remote_target ();
2249 gdb_assert (c->var.has_value ());
2250
2251 auto *default_config = static_cast<packet_config *> (c->context ());
2252 const int packet_idx = std::distance (remote_protocol_packets,
2253 default_config);
2254
2255 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2256 {
2257 const char *name = packets_descriptions[packet_idx].name;
2258 const auto_boolean value = c->var->get<auto_boolean> ();
2259 const char *support = get_packet_support_name (value);
2260 const char *target_type = get_target_type_name (remote != nullptr);
2261
2262 if (remote != nullptr)
2263 remote->m_features.m_protocol_packets[packet_idx].detect = value;
2264 else
2265 remote_protocol_packets[packet_idx].detect = value;
2266
2267 gdb_printf (_("Support for the '%s' packet %s is set to \"%s\".\n"), name,
2268 target_type, support);
2269 return;
2270 }
2271
2272 internal_error (_("Could not find config for %s"), c->name);
2273 }
2274
2275 static void
2276 show_packet_config_cmd (ui_file *file, const unsigned int which_packet,
2277 remote_target *remote)
2278 {
2279 const char *support = "internal-error";
2280 const char *target_type = get_target_type_name (remote != nullptr);
2281
2282 packet_config *config;
2283 if (remote != nullptr)
2284 config = &remote->m_features.m_protocol_packets[which_packet];
2285 else
2286 config = &remote_protocol_packets[which_packet];
2287
2288 switch (packet_config_support (config))
2289 {
2290 case PACKET_ENABLE:
2291 support = "enabled";
2292 break;
2293 case PACKET_DISABLE:
2294 support = "disabled";
2295 break;
2296 case PACKET_SUPPORT_UNKNOWN:
2297 support = "unknown";
2298 break;
2299 }
2300 switch (config->detect)
2301 {
2302 case AUTO_BOOLEAN_AUTO:
2303 gdb_printf (file,
2304 _("Support for the '%s' packet %s is \"auto\", "
2305 "currently %s.\n"),
2306 packets_descriptions[which_packet].name, target_type,
2307 support);
2308 break;
2309 case AUTO_BOOLEAN_TRUE:
2310 case AUTO_BOOLEAN_FALSE:
2311 gdb_printf (file,
2312 _("Support for the '%s' packet %s is \"%s\".\n"),
2313 packets_descriptions[which_packet].name, target_type,
2314 get_packet_support_name (config->detect));
2315 break;
2316 }
2317 }
2318
2319 static void
2320 add_packet_config_cmd (const unsigned int which_packet, const char *name,
2321 const char *title, int legacy)
2322 {
2323 packets_descriptions[which_packet].name = name;
2324 packets_descriptions[which_packet].title = title;
2325
2326 packet_config *config = &remote_protocol_packets[which_packet];
2327
2328 gdb::unique_xmalloc_ptr<char> set_doc
2329 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
2330 name, title);
2331 gdb::unique_xmalloc_ptr<char> show_doc
2332 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
2333 name, title);
2334 /* set/show TITLE-packet {auto,on,off} */
2335 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
2336 set_show_commands cmds
2337 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
2338 &config->detect, set_doc.get (),
2339 show_doc.get (), NULL, /* help_doc */
2340 set_remote_protocol_packet_cmd,
2341 show_remote_protocol_packet_cmd,
2342 &remote_set_cmdlist, &remote_show_cmdlist);
2343 cmds.show->set_context (config);
2344 cmds.set->set_context (config);
2345
2346 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
2347 if (legacy)
2348 {
2349 /* It's not clear who should take ownership of the LEGACY_NAME string
2350 created below, so, for now, place the string into a static vector
2351 which ensures the strings is released when GDB exits. */
2352 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
2353 gdb::unique_xmalloc_ptr<char> legacy_name
2354 = xstrprintf ("%s-packet", name);
2355 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
2356 &remote_set_cmdlist);
2357 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
2358 &remote_show_cmdlist);
2359 legacy_names.emplace_back (std::move (legacy_name));
2360 }
2361 }
2362
2363 static enum packet_result
2364 packet_check_result (const char *buf)
2365 {
2366 if (buf[0] != '\0')
2367 {
2368 /* The stub recognized the packet request. Check that the
2369 operation succeeded. */
2370 if (buf[0] == 'E'
2371 && isxdigit (buf[1]) && isxdigit (buf[2])
2372 && buf[3] == '\0')
2373 /* "Enn" - definitely an error. */
2374 return PACKET_ERROR;
2375
2376 /* Always treat "E." as an error. This will be used for
2377 more verbose error messages, such as E.memtypes. */
2378 if (buf[0] == 'E' && buf[1] == '.')
2379 return PACKET_ERROR;
2380
2381 /* The packet may or may not be OK. Just assume it is. */
2382 return PACKET_OK;
2383 }
2384 else
2385 /* The stub does not support the packet. */
2386 return PACKET_UNKNOWN;
2387 }
2388
2389 static enum packet_result
2390 packet_check_result (const gdb::char_vector &buf)
2391 {
2392 return packet_check_result (buf.data ());
2393 }
2394
2395 packet_result
2396 remote_features::packet_ok (const char *buf, const int which_packet)
2397 {
2398 packet_config *config = &m_protocol_packets[which_packet];
2399 packet_description *descr = &packets_descriptions[which_packet];
2400
2401 enum packet_result result;
2402
2403 if (config->detect != AUTO_BOOLEAN_TRUE
2404 && config->support == PACKET_DISABLE)
2405 internal_error (_("packet_ok: attempt to use a disabled packet"));
2406
2407 result = packet_check_result (buf);
2408 switch (result)
2409 {
2410 case PACKET_OK:
2411 case PACKET_ERROR:
2412 /* The stub recognized the packet request. */
2413 if (config->support == PACKET_SUPPORT_UNKNOWN)
2414 {
2415 remote_debug_printf ("Packet %s (%s) is supported",
2416 descr->name, descr->title);
2417 config->support = PACKET_ENABLE;
2418 }
2419 break;
2420 case PACKET_UNKNOWN:
2421 /* The stub does not support the packet. */
2422 if (config->detect == AUTO_BOOLEAN_AUTO
2423 && config->support == PACKET_ENABLE)
2424 {
2425 /* If the stub previously indicated that the packet was
2426 supported then there is a protocol error. */
2427 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2428 descr->name, descr->title);
2429 }
2430 else if (config->detect == AUTO_BOOLEAN_TRUE)
2431 {
2432 /* The user set it wrong. */
2433 error (_("Enabled packet %s (%s) not recognized by stub"),
2434 descr->name, descr->title);
2435 }
2436
2437 remote_debug_printf ("Packet %s (%s) is NOT supported", descr->name,
2438 descr->title);
2439 config->support = PACKET_DISABLE;
2440 break;
2441 }
2442
2443 return result;
2444 }
2445
2446 packet_result
2447 remote_features::packet_ok (const gdb::char_vector &buf, const int which_packet)
2448 {
2449 return packet_ok (buf.data (), which_packet);
2450 }
2451
2452 /* Returns whether a given packet or feature is supported. This takes
2453 into account the state of the corresponding "set remote foo-packet"
2454 command, which may be used to bypass auto-detection. */
2455
2456 static enum packet_support
2457 packet_config_support (const packet_config *config)
2458 {
2459 switch (config->detect)
2460 {
2461 case AUTO_BOOLEAN_TRUE:
2462 return PACKET_ENABLE;
2463 case AUTO_BOOLEAN_FALSE:
2464 return PACKET_DISABLE;
2465 case AUTO_BOOLEAN_AUTO:
2466 return config->support;
2467 default:
2468 gdb_assert_not_reached ("bad switch");
2469 }
2470 }
2471
2472 packet_support
2473 remote_features::packet_support (int packet) const
2474 {
2475 const packet_config *config = &m_protocol_packets[packet];
2476 return packet_config_support (config);
2477 }
2478
2479 static void
2480 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2481 struct cmd_list_element *c,
2482 const char *value)
2483 {
2484 remote_target *remote = get_current_remote_target ();
2485 gdb_assert (c->var.has_value ());
2486
2487 auto *default_config = static_cast<packet_config *> (c->context ());
2488 const int packet_idx = std::distance (remote_protocol_packets,
2489 default_config);
2490
2491 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2492 {
2493 show_packet_config_cmd (file, packet_idx, remote);
2494 return;
2495 }
2496 internal_error (_("Could not find config for %s"), c->name);
2497 }
2498
2499 /* Should we try one of the 'Z' requests? */
2500
2501 enum Z_packet_type
2502 {
2503 Z_PACKET_SOFTWARE_BP,
2504 Z_PACKET_HARDWARE_BP,
2505 Z_PACKET_WRITE_WP,
2506 Z_PACKET_READ_WP,
2507 Z_PACKET_ACCESS_WP,
2508 NR_Z_PACKET_TYPES
2509 };
2510
2511 /* For compatibility with older distributions. Provide a ``set remote
2512 Z-packet ...'' command that updates all the Z packet types. */
2513
2514 static enum auto_boolean remote_Z_packet_detect;
2515
2516 static void
2517 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2518 struct cmd_list_element *c)
2519 {
2520 remote_target *remote = get_current_remote_target ();
2521 int i;
2522
2523 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2524 {
2525 if (remote != nullptr)
2526 remote->m_features.m_protocol_packets[PACKET_Z0 + i].detect
2527 = remote_Z_packet_detect;
2528 else
2529 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2530 }
2531
2532 const char *support = get_packet_support_name (remote_Z_packet_detect);
2533 const char *target_type = get_target_type_name (remote != nullptr);
2534 gdb_printf (_("Use of Z packets %s is set to \"%s\".\n"), target_type,
2535 support);
2536
2537 }
2538
2539 static void
2540 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2541 struct cmd_list_element *c,
2542 const char *value)
2543 {
2544 remote_target *remote = get_current_remote_target ();
2545 int i;
2546
2547 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2548 show_packet_config_cmd (file, PACKET_Z0 + i, remote);
2549 }
2550
2551 /* Insert fork catchpoint target routine. If fork events are enabled
2552 then return success, nothing more to do. */
2553
2554 int
2555 remote_target::insert_fork_catchpoint (int pid)
2556 {
2557 return !m_features.remote_fork_event_p ();
2558 }
2559
2560 /* Remove fork catchpoint target routine. Nothing to do, just
2561 return success. */
2562
2563 int
2564 remote_target::remove_fork_catchpoint (int pid)
2565 {
2566 return 0;
2567 }
2568
2569 /* Insert vfork catchpoint target routine. If vfork events are enabled
2570 then return success, nothing more to do. */
2571
2572 int
2573 remote_target::insert_vfork_catchpoint (int pid)
2574 {
2575 return !m_features.remote_vfork_event_p ();
2576 }
2577
2578 /* Remove vfork catchpoint target routine. Nothing to do, just
2579 return success. */
2580
2581 int
2582 remote_target::remove_vfork_catchpoint (int pid)
2583 {
2584 return 0;
2585 }
2586
2587 /* Insert exec catchpoint target routine. If exec events are
2588 enabled, just return success. */
2589
2590 int
2591 remote_target::insert_exec_catchpoint (int pid)
2592 {
2593 return !m_features.remote_exec_event_p ();
2594 }
2595
2596 /* Remove exec catchpoint target routine. Nothing to do, just
2597 return success. */
2598
2599 int
2600 remote_target::remove_exec_catchpoint (int pid)
2601 {
2602 return 0;
2603 }
2604
2605 \f
2606
2607 /* Take advantage of the fact that the TID field is not used, to tag
2608 special ptids with it set to != 0. */
2609 static const ptid_t magic_null_ptid (42000, -1, 1);
2610 static const ptid_t not_sent_ptid (42000, -2, 1);
2611 static const ptid_t any_thread_ptid (42000, 0, 1);
2612
2613 /* Find out if the stub attached to PID (and hence GDB should offer to
2614 detach instead of killing it when bailing out). */
2615
2616 int
2617 remote_target::remote_query_attached (int pid)
2618 {
2619 struct remote_state *rs = get_remote_state ();
2620 size_t size = get_remote_packet_size ();
2621
2622 if (m_features.packet_support (PACKET_qAttached) == PACKET_DISABLE)
2623 return 0;
2624
2625 if (m_features.remote_multi_process_p ())
2626 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2627 else
2628 xsnprintf (rs->buf.data (), size, "qAttached");
2629
2630 putpkt (rs->buf);
2631 getpkt (&rs->buf, 0);
2632
2633 switch (m_features.packet_ok (rs->buf, PACKET_qAttached))
2634 {
2635 case PACKET_OK:
2636 if (strcmp (rs->buf.data (), "1") == 0)
2637 return 1;
2638 break;
2639 case PACKET_ERROR:
2640 warning (_("Remote failure reply: %s"), rs->buf.data ());
2641 break;
2642 case PACKET_UNKNOWN:
2643 break;
2644 }
2645
2646 return 0;
2647 }
2648
2649 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2650 has been invented by GDB, instead of reported by the target. Since
2651 we can be connected to a remote system before before knowing about
2652 any inferior, mark the target with execution when we find the first
2653 inferior. If ATTACHED is 1, then we had just attached to this
2654 inferior. If it is 0, then we just created this inferior. If it
2655 is -1, then try querying the remote stub to find out if it had
2656 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2657 attempt to open this inferior's executable as the main executable
2658 if no main executable is open already. */
2659
2660 inferior *
2661 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2662 int try_open_exec)
2663 {
2664 struct inferior *inf;
2665
2666 /* Check whether this process we're learning about is to be
2667 considered attached, or if is to be considered to have been
2668 spawned by the stub. */
2669 if (attached == -1)
2670 attached = remote_query_attached (pid);
2671
2672 if (gdbarch_has_global_solist (target_gdbarch ()))
2673 {
2674 /* If the target shares code across all inferiors, then every
2675 attach adds a new inferior. */
2676 inf = add_inferior (pid);
2677
2678 /* ... and every inferior is bound to the same program space.
2679 However, each inferior may still have its own address
2680 space. */
2681 inf->aspace = maybe_new_address_space ();
2682 inf->pspace = current_program_space;
2683 }
2684 else
2685 {
2686 /* In the traditional debugging scenario, there's a 1-1 match
2687 between program/address spaces. We simply bind the inferior
2688 to the program space's address space. */
2689 inf = current_inferior ();
2690
2691 /* However, if the current inferior is already bound to a
2692 process, find some other empty inferior. */
2693 if (inf->pid != 0)
2694 {
2695 inf = nullptr;
2696 for (inferior *it : all_inferiors ())
2697 if (it->pid == 0)
2698 {
2699 inf = it;
2700 break;
2701 }
2702 }
2703 if (inf == nullptr)
2704 {
2705 /* Since all inferiors were already bound to a process, add
2706 a new inferior. */
2707 inf = add_inferior_with_spaces ();
2708 }
2709 switch_to_inferior_no_thread (inf);
2710 inf->push_target (this);
2711 inferior_appeared (inf, pid);
2712 }
2713
2714 inf->attach_flag = attached;
2715 inf->fake_pid_p = fake_pid_p;
2716
2717 /* If no main executable is currently open then attempt to
2718 open the file that was executed to create this inferior. */
2719 if (try_open_exec && get_exec_file (0) == NULL)
2720 exec_file_locate_attach (pid, 0, 1);
2721
2722 /* Check for exec file mismatch, and let the user solve it. */
2723 validate_exec_file (1);
2724
2725 return inf;
2726 }
2727
2728 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2729 static remote_thread_info *get_remote_thread_info (remote_target *target,
2730 ptid_t ptid);
2731
2732 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2733 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2734 remote_state::starting_up flag) is true then the new thread is added
2735 silently, otherwise the new thread will be announced to the user. */
2736
2737 thread_info *
2738 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2739 bool silent_p)
2740 {
2741 struct remote_state *rs = get_remote_state ();
2742 struct thread_info *thread;
2743
2744 /* GDB historically didn't pull threads in the initial connection
2745 setup. If the remote target doesn't even have a concept of
2746 threads (e.g., a bare-metal target), even if internally we
2747 consider that a single-threaded target, mentioning a new thread
2748 might be confusing to the user. Be silent then, preserving the
2749 age old behavior. */
2750 if (rs->starting_up || silent_p)
2751 thread = add_thread_silent (this, ptid);
2752 else
2753 thread = add_thread (this, ptid);
2754
2755 /* We start by assuming threads are resumed. That state then gets updated
2756 when we process a matching stop reply. */
2757 get_remote_thread_info (thread)->set_resumed ();
2758
2759 set_executing (this, ptid, executing);
2760 set_running (this, ptid, running);
2761
2762 return thread;
2763 }
2764
2765 /* Come here when we learn about a thread id from the remote target.
2766 It may be the first time we hear about such thread, so take the
2767 opportunity to add it to GDB's thread list. In case this is the
2768 first time we're noticing its corresponding inferior, add it to
2769 GDB's inferior list as well. EXECUTING indicates whether the
2770 thread is (internally) executing or stopped. */
2771
2772 void
2773 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2774 {
2775 /* In non-stop mode, we assume new found threads are (externally)
2776 running until proven otherwise with a stop reply. In all-stop,
2777 we can only get here if all threads are stopped. */
2778 bool running = target_is_non_stop_p ();
2779
2780 /* If this is a new thread, add it to GDB's thread list.
2781 If we leave it up to WFI to do this, bad things will happen. */
2782
2783 thread_info *tp = this->find_thread (currthread);
2784 if (tp != NULL && tp->state == THREAD_EXITED)
2785 {
2786 /* We're seeing an event on a thread id we knew had exited.
2787 This has to be a new thread reusing the old id. Add it. */
2788 remote_add_thread (currthread, running, executing, false);
2789 return;
2790 }
2791
2792 if (!in_thread_list (this, currthread))
2793 {
2794 struct inferior *inf = NULL;
2795 int pid = currthread.pid ();
2796
2797 if (inferior_ptid.is_pid ()
2798 && pid == inferior_ptid.pid ())
2799 {
2800 /* inferior_ptid has no thread member yet. This can happen
2801 with the vAttach -> remote_wait,"TAAthread:" path if the
2802 stub doesn't support qC. This is the first stop reported
2803 after an attach, so this is the main thread. Update the
2804 ptid in the thread list. */
2805 if (in_thread_list (this, ptid_t (pid)))
2806 thread_change_ptid (this, inferior_ptid, currthread);
2807 else
2808 {
2809 thread_info *thr
2810 = remote_add_thread (currthread, running, executing, false);
2811 switch_to_thread (thr);
2812 }
2813 return;
2814 }
2815
2816 if (magic_null_ptid == inferior_ptid)
2817 {
2818 /* inferior_ptid is not set yet. This can happen with the
2819 vRun -> remote_wait,"TAAthread:" path if the stub
2820 doesn't support qC. This is the first stop reported
2821 after an attach, so this is the main thread. Update the
2822 ptid in the thread list. */
2823 thread_change_ptid (this, inferior_ptid, currthread);
2824 return;
2825 }
2826
2827 /* When connecting to a target remote, or to a target
2828 extended-remote which already was debugging an inferior, we
2829 may not know about it yet. Add it before adding its child
2830 thread, so notifications are emitted in a sensible order. */
2831 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2832 {
2833 bool fake_pid_p = !m_features.remote_multi_process_p ();
2834
2835 inf = remote_add_inferior (fake_pid_p,
2836 currthread.pid (), -1, 1);
2837 }
2838
2839 /* This is really a new thread. Add it. */
2840 thread_info *new_thr
2841 = remote_add_thread (currthread, running, executing, false);
2842
2843 /* If we found a new inferior, let the common code do whatever
2844 it needs to with it (e.g., read shared libraries, insert
2845 breakpoints), unless we're just setting up an all-stop
2846 connection. */
2847 if (inf != NULL)
2848 {
2849 struct remote_state *rs = get_remote_state ();
2850
2851 if (!rs->starting_up)
2852 notice_new_inferior (new_thr, executing, 0);
2853 }
2854 }
2855 }
2856
2857 /* Return THREAD's private thread data, creating it if necessary. */
2858
2859 static remote_thread_info *
2860 get_remote_thread_info (thread_info *thread)
2861 {
2862 gdb_assert (thread != NULL);
2863
2864 if (thread->priv == NULL)
2865 thread->priv.reset (new remote_thread_info);
2866
2867 return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
2868 }
2869
2870 /* Return PTID's private thread data, creating it if necessary. */
2871
2872 static remote_thread_info *
2873 get_remote_thread_info (remote_target *target, ptid_t ptid)
2874 {
2875 thread_info *thr = target->find_thread (ptid);
2876 return get_remote_thread_info (thr);
2877 }
2878
2879 /* Call this function as a result of
2880 1) A halt indication (T packet) containing a thread id
2881 2) A direct query of currthread
2882 3) Successful execution of set thread */
2883
2884 static void
2885 record_currthread (struct remote_state *rs, ptid_t currthread)
2886 {
2887 rs->general_thread = currthread;
2888 }
2889
2890 /* If 'QPassSignals' is supported, tell the remote stub what signals
2891 it can simply pass through to the inferior without reporting. */
2892
2893 void
2894 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2895 {
2896 if (m_features.packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2897 {
2898 char *pass_packet, *p;
2899 int count = 0;
2900 struct remote_state *rs = get_remote_state ();
2901
2902 gdb_assert (pass_signals.size () < 256);
2903 for (size_t i = 0; i < pass_signals.size (); i++)
2904 {
2905 if (pass_signals[i])
2906 count++;
2907 }
2908 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2909 strcpy (pass_packet, "QPassSignals:");
2910 p = pass_packet + strlen (pass_packet);
2911 for (size_t i = 0; i < pass_signals.size (); i++)
2912 {
2913 if (pass_signals[i])
2914 {
2915 if (i >= 16)
2916 *p++ = tohex (i >> 4);
2917 *p++ = tohex (i & 15);
2918 if (count)
2919 *p++ = ';';
2920 else
2921 break;
2922 count--;
2923 }
2924 }
2925 *p = 0;
2926 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2927 {
2928 putpkt (pass_packet);
2929 getpkt (&rs->buf, 0);
2930 m_features.packet_ok (rs->buf, PACKET_QPassSignals);
2931 xfree (rs->last_pass_packet);
2932 rs->last_pass_packet = pass_packet;
2933 }
2934 else
2935 xfree (pass_packet);
2936 }
2937 }
2938
2939 /* If 'QCatchSyscalls' is supported, tell the remote stub
2940 to report syscalls to GDB. */
2941
2942 int
2943 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2944 gdb::array_view<const int> syscall_counts)
2945 {
2946 const char *catch_packet;
2947 enum packet_result result;
2948 int n_sysno = 0;
2949
2950 if (m_features.packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2951 {
2952 /* Not supported. */
2953 return 1;
2954 }
2955
2956 if (needed && any_count == 0)
2957 {
2958 /* Count how many syscalls are to be caught. */
2959 for (size_t i = 0; i < syscall_counts.size (); i++)
2960 {
2961 if (syscall_counts[i] != 0)
2962 n_sysno++;
2963 }
2964 }
2965
2966 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
2967 pid, needed, any_count, n_sysno);
2968
2969 std::string built_packet;
2970 if (needed)
2971 {
2972 /* Prepare a packet with the sysno list, assuming max 8+1
2973 characters for a sysno. If the resulting packet size is too
2974 big, fallback on the non-selective packet. */
2975 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2976 built_packet.reserve (maxpktsz);
2977 built_packet = "QCatchSyscalls:1";
2978 if (any_count == 0)
2979 {
2980 /* Add in each syscall to be caught. */
2981 for (size_t i = 0; i < syscall_counts.size (); i++)
2982 {
2983 if (syscall_counts[i] != 0)
2984 string_appendf (built_packet, ";%zx", i);
2985 }
2986 }
2987 if (built_packet.size () > get_remote_packet_size ())
2988 {
2989 /* catch_packet too big. Fallback to less efficient
2990 non selective mode, with GDB doing the filtering. */
2991 catch_packet = "QCatchSyscalls:1";
2992 }
2993 else
2994 catch_packet = built_packet.c_str ();
2995 }
2996 else
2997 catch_packet = "QCatchSyscalls:0";
2998
2999 struct remote_state *rs = get_remote_state ();
3000
3001 putpkt (catch_packet);
3002 getpkt (&rs->buf, 0);
3003 result = m_features.packet_ok (rs->buf, PACKET_QCatchSyscalls);
3004 if (result == PACKET_OK)
3005 return 0;
3006 else
3007 return -1;
3008 }
3009
3010 /* If 'QProgramSignals' is supported, tell the remote stub what
3011 signals it should pass through to the inferior when detaching. */
3012
3013 void
3014 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
3015 {
3016 if (m_features.packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
3017 {
3018 char *packet, *p;
3019 int count = 0;
3020 struct remote_state *rs = get_remote_state ();
3021
3022 gdb_assert (signals.size () < 256);
3023 for (size_t i = 0; i < signals.size (); i++)
3024 {
3025 if (signals[i])
3026 count++;
3027 }
3028 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
3029 strcpy (packet, "QProgramSignals:");
3030 p = packet + strlen (packet);
3031 for (size_t i = 0; i < signals.size (); i++)
3032 {
3033 if (signal_pass_state (i))
3034 {
3035 if (i >= 16)
3036 *p++ = tohex (i >> 4);
3037 *p++ = tohex (i & 15);
3038 if (count)
3039 *p++ = ';';
3040 else
3041 break;
3042 count--;
3043 }
3044 }
3045 *p = 0;
3046 if (!rs->last_program_signals_packet
3047 || strcmp (rs->last_program_signals_packet, packet) != 0)
3048 {
3049 putpkt (packet);
3050 getpkt (&rs->buf, 0);
3051 m_features.packet_ok (rs->buf, PACKET_QProgramSignals);
3052 xfree (rs->last_program_signals_packet);
3053 rs->last_program_signals_packet = packet;
3054 }
3055 else
3056 xfree (packet);
3057 }
3058 }
3059
3060 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
3061 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
3062 thread. If GEN is set, set the general thread, if not, then set
3063 the step/continue thread. */
3064 void
3065 remote_target::set_thread (ptid_t ptid, int gen)
3066 {
3067 struct remote_state *rs = get_remote_state ();
3068 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
3069 char *buf = rs->buf.data ();
3070 char *endbuf = buf + get_remote_packet_size ();
3071
3072 if (state == ptid)
3073 return;
3074
3075 *buf++ = 'H';
3076 *buf++ = gen ? 'g' : 'c';
3077 if (ptid == magic_null_ptid)
3078 xsnprintf (buf, endbuf - buf, "0");
3079 else if (ptid == any_thread_ptid)
3080 xsnprintf (buf, endbuf - buf, "0");
3081 else if (ptid == minus_one_ptid)
3082 xsnprintf (buf, endbuf - buf, "-1");
3083 else
3084 write_ptid (buf, endbuf, ptid);
3085 putpkt (rs->buf);
3086 getpkt (&rs->buf, 0);
3087 if (gen)
3088 rs->general_thread = ptid;
3089 else
3090 rs->continue_thread = ptid;
3091 }
3092
3093 void
3094 remote_target::set_general_thread (ptid_t ptid)
3095 {
3096 set_thread (ptid, 1);
3097 }
3098
3099 void
3100 remote_target::set_continue_thread (ptid_t ptid)
3101 {
3102 set_thread (ptid, 0);
3103 }
3104
3105 /* Change the remote current process. Which thread within the process
3106 ends up selected isn't important, as long as it is the same process
3107 as what INFERIOR_PTID points to.
3108
3109 This comes from that fact that there is no explicit notion of
3110 "selected process" in the protocol. The selected process for
3111 general operations is the process the selected general thread
3112 belongs to. */
3113
3114 void
3115 remote_target::set_general_process ()
3116 {
3117 /* If the remote can't handle multiple processes, don't bother. */
3118 if (!m_features.remote_multi_process_p ())
3119 return;
3120
3121 remote_state *rs = get_remote_state ();
3122
3123 /* We only need to change the remote current thread if it's pointing
3124 at some other process. */
3125 if (rs->general_thread.pid () != inferior_ptid.pid ())
3126 set_general_thread (inferior_ptid);
3127 }
3128
3129 \f
3130 /* Return nonzero if this is the main thread that we made up ourselves
3131 to model non-threaded targets as single-threaded. */
3132
3133 static int
3134 remote_thread_always_alive (ptid_t ptid)
3135 {
3136 if (ptid == magic_null_ptid)
3137 /* The main thread is always alive. */
3138 return 1;
3139
3140 if (ptid.pid () != 0 && ptid.lwp () == 0)
3141 /* The main thread is always alive. This can happen after a
3142 vAttach, if the remote side doesn't support
3143 multi-threading. */
3144 return 1;
3145
3146 return 0;
3147 }
3148
3149 /* Return nonzero if the thread PTID is still alive on the remote
3150 system. */
3151
3152 bool
3153 remote_target::thread_alive (ptid_t ptid)
3154 {
3155 struct remote_state *rs = get_remote_state ();
3156 char *p, *endp;
3157
3158 /* Check if this is a thread that we made up ourselves to model
3159 non-threaded targets as single-threaded. */
3160 if (remote_thread_always_alive (ptid))
3161 return 1;
3162
3163 p = rs->buf.data ();
3164 endp = p + get_remote_packet_size ();
3165
3166 *p++ = 'T';
3167 write_ptid (p, endp, ptid);
3168
3169 putpkt (rs->buf);
3170 getpkt (&rs->buf, 0);
3171 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
3172 }
3173
3174 /* Return a pointer to a thread name if we know it and NULL otherwise.
3175 The thread_info object owns the memory for the name. */
3176
3177 const char *
3178 remote_target::thread_name (struct thread_info *info)
3179 {
3180 if (info->priv != NULL)
3181 {
3182 const std::string &name = get_remote_thread_info (info)->name;
3183 return !name.empty () ? name.c_str () : NULL;
3184 }
3185
3186 return NULL;
3187 }
3188
3189 /* About these extended threadlist and threadinfo packets. They are
3190 variable length packets but, the fields within them are often fixed
3191 length. They are redundant enough to send over UDP as is the
3192 remote protocol in general. There is a matching unit test module
3193 in libstub. */
3194
3195 /* WARNING: This threadref data structure comes from the remote O.S.,
3196 libstub protocol encoding, and remote.c. It is not particularly
3197 changeable. */
3198
3199 /* Right now, the internal structure is int. We want it to be bigger.
3200 Plan to fix this. */
3201
3202 typedef int gdb_threadref; /* Internal GDB thread reference. */
3203
3204 /* gdb_ext_thread_info is an internal GDB data structure which is
3205 equivalent to the reply of the remote threadinfo packet. */
3206
3207 struct gdb_ext_thread_info
3208 {
3209 threadref threadid; /* External form of thread reference. */
3210 int active; /* Has state interesting to GDB?
3211 regs, stack. */
3212 char display[256]; /* Brief state display, name,
3213 blocked/suspended. */
3214 char shortname[32]; /* To be used to name threads. */
3215 char more_display[256]; /* Long info, statistics, queue depth,
3216 whatever. */
3217 };
3218
3219 /* The volume of remote transfers can be limited by submitting
3220 a mask containing bits specifying the desired information.
3221 Use a union of these values as the 'selection' parameter to
3222 get_thread_info. FIXME: Make these TAG names more thread specific. */
3223
3224 #define TAG_THREADID 1
3225 #define TAG_EXISTS 2
3226 #define TAG_DISPLAY 4
3227 #define TAG_THREADNAME 8
3228 #define TAG_MOREDISPLAY 16
3229
3230 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3231
3232 static const char *unpack_nibble (const char *buf, int *val);
3233
3234 static const char *unpack_byte (const char *buf, int *value);
3235
3236 static char *pack_int (char *buf, int value);
3237
3238 static const char *unpack_int (const char *buf, int *value);
3239
3240 static const char *unpack_string (const char *src, char *dest, int length);
3241
3242 static char *pack_threadid (char *pkt, threadref *id);
3243
3244 static const char *unpack_threadid (const char *inbuf, threadref *id);
3245
3246 void int_to_threadref (threadref *id, int value);
3247
3248 static int threadref_to_int (threadref *ref);
3249
3250 static void copy_threadref (threadref *dest, threadref *src);
3251
3252 static int threadmatch (threadref *dest, threadref *src);
3253
3254 static char *pack_threadinfo_request (char *pkt, int mode,
3255 threadref *id);
3256
3257 static char *pack_threadlist_request (char *pkt, int startflag,
3258 int threadcount,
3259 threadref *nextthread);
3260
3261 static int remote_newthread_step (threadref *ref, void *context);
3262
3263
3264 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3265 buffer we're allowed to write to. Returns
3266 BUF+CHARACTERS_WRITTEN. */
3267
3268 char *
3269 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3270 {
3271 int pid, tid;
3272
3273 if (m_features.remote_multi_process_p ())
3274 {
3275 pid = ptid.pid ();
3276 if (pid < 0)
3277 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3278 else
3279 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3280 }
3281 tid = ptid.lwp ();
3282 if (tid < 0)
3283 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3284 else
3285 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3286
3287 return buf;
3288 }
3289
3290 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3291 last parsed char. Returns null_ptid if no thread id is found, and
3292 throws an error if the thread id has an invalid format. */
3293
3294 static ptid_t
3295 read_ptid (const char *buf, const char **obuf)
3296 {
3297 const char *p = buf;
3298 const char *pp;
3299 ULONGEST pid = 0, tid = 0;
3300
3301 if (*p == 'p')
3302 {
3303 /* Multi-process ptid. */
3304 pp = unpack_varlen_hex (p + 1, &pid);
3305 if (*pp != '.')
3306 error (_("invalid remote ptid: %s"), p);
3307
3308 p = pp;
3309 pp = unpack_varlen_hex (p + 1, &tid);
3310 if (obuf)
3311 *obuf = pp;
3312 return ptid_t (pid, tid);
3313 }
3314
3315 /* No multi-process. Just a tid. */
3316 pp = unpack_varlen_hex (p, &tid);
3317
3318 /* Return null_ptid when no thread id is found. */
3319 if (p == pp)
3320 {
3321 if (obuf)
3322 *obuf = pp;
3323 return null_ptid;
3324 }
3325
3326 /* Since the stub is not sending a process id, default to what's
3327 current_inferior, unless it doesn't have a PID yet. If so,
3328 then since there's no way to know the pid of the reported
3329 threads, use the magic number. */
3330 inferior *inf = current_inferior ();
3331 if (inf->pid == 0)
3332 pid = magic_null_ptid.pid ();
3333 else
3334 pid = inf->pid;
3335
3336 if (obuf)
3337 *obuf = pp;
3338 return ptid_t (pid, tid);
3339 }
3340
3341 static int
3342 stubhex (int ch)
3343 {
3344 if (ch >= 'a' && ch <= 'f')
3345 return ch - 'a' + 10;
3346 if (ch >= '0' && ch <= '9')
3347 return ch - '0';
3348 if (ch >= 'A' && ch <= 'F')
3349 return ch - 'A' + 10;
3350 return -1;
3351 }
3352
3353 static int
3354 stub_unpack_int (const char *buff, int fieldlength)
3355 {
3356 int nibble;
3357 int retval = 0;
3358
3359 while (fieldlength)
3360 {
3361 nibble = stubhex (*buff++);
3362 retval |= nibble;
3363 fieldlength--;
3364 if (fieldlength)
3365 retval = retval << 4;
3366 }
3367 return retval;
3368 }
3369
3370 static const char *
3371 unpack_nibble (const char *buf, int *val)
3372 {
3373 *val = fromhex (*buf++);
3374 return buf;
3375 }
3376
3377 static const char *
3378 unpack_byte (const char *buf, int *value)
3379 {
3380 *value = stub_unpack_int (buf, 2);
3381 return buf + 2;
3382 }
3383
3384 static char *
3385 pack_int (char *buf, int value)
3386 {
3387 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3388 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3389 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3390 buf = pack_hex_byte (buf, (value & 0xff));
3391 return buf;
3392 }
3393
3394 static const char *
3395 unpack_int (const char *buf, int *value)
3396 {
3397 *value = stub_unpack_int (buf, 8);
3398 return buf + 8;
3399 }
3400
3401 #if 0 /* Currently unused, uncomment when needed. */
3402 static char *pack_string (char *pkt, char *string);
3403
3404 static char *
3405 pack_string (char *pkt, char *string)
3406 {
3407 char ch;
3408 int len;
3409
3410 len = strlen (string);
3411 if (len > 200)
3412 len = 200; /* Bigger than most GDB packets, junk??? */
3413 pkt = pack_hex_byte (pkt, len);
3414 while (len-- > 0)
3415 {
3416 ch = *string++;
3417 if ((ch == '\0') || (ch == '#'))
3418 ch = '*'; /* Protect encapsulation. */
3419 *pkt++ = ch;
3420 }
3421 return pkt;
3422 }
3423 #endif /* 0 (unused) */
3424
3425 static const char *
3426 unpack_string (const char *src, char *dest, int length)
3427 {
3428 while (length--)
3429 *dest++ = *src++;
3430 *dest = '\0';
3431 return src;
3432 }
3433
3434 static char *
3435 pack_threadid (char *pkt, threadref *id)
3436 {
3437 char *limit;
3438 unsigned char *altid;
3439
3440 altid = (unsigned char *) id;
3441 limit = pkt + BUF_THREAD_ID_SIZE;
3442 while (pkt < limit)
3443 pkt = pack_hex_byte (pkt, *altid++);
3444 return pkt;
3445 }
3446
3447
3448 static const char *
3449 unpack_threadid (const char *inbuf, threadref *id)
3450 {
3451 char *altref;
3452 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3453 int x, y;
3454
3455 altref = (char *) id;
3456
3457 while (inbuf < limit)
3458 {
3459 x = stubhex (*inbuf++);
3460 y = stubhex (*inbuf++);
3461 *altref++ = (x << 4) | y;
3462 }
3463 return inbuf;
3464 }
3465
3466 /* Externally, threadrefs are 64 bits but internally, they are still
3467 ints. This is due to a mismatch of specifications. We would like
3468 to use 64bit thread references internally. This is an adapter
3469 function. */
3470
3471 void
3472 int_to_threadref (threadref *id, int value)
3473 {
3474 unsigned char *scan;
3475
3476 scan = (unsigned char *) id;
3477 {
3478 int i = 4;
3479 while (i--)
3480 *scan++ = 0;
3481 }
3482 *scan++ = (value >> 24) & 0xff;
3483 *scan++ = (value >> 16) & 0xff;
3484 *scan++ = (value >> 8) & 0xff;
3485 *scan++ = (value & 0xff);
3486 }
3487
3488 static int
3489 threadref_to_int (threadref *ref)
3490 {
3491 int i, value = 0;
3492 unsigned char *scan;
3493
3494 scan = *ref;
3495 scan += 4;
3496 i = 4;
3497 while (i-- > 0)
3498 value = (value << 8) | ((*scan++) & 0xff);
3499 return value;
3500 }
3501
3502 static void
3503 copy_threadref (threadref *dest, threadref *src)
3504 {
3505 int i;
3506 unsigned char *csrc, *cdest;
3507
3508 csrc = (unsigned char *) src;
3509 cdest = (unsigned char *) dest;
3510 i = 8;
3511 while (i--)
3512 *cdest++ = *csrc++;
3513 }
3514
3515 static int
3516 threadmatch (threadref *dest, threadref *src)
3517 {
3518 /* Things are broken right now, so just assume we got a match. */
3519 #if 0
3520 unsigned char *srcp, *destp;
3521 int i, result;
3522 srcp = (char *) src;
3523 destp = (char *) dest;
3524
3525 result = 1;
3526 while (i-- > 0)
3527 result &= (*srcp++ == *destp++) ? 1 : 0;
3528 return result;
3529 #endif
3530 return 1;
3531 }
3532
3533 /*
3534 threadid:1, # always request threadid
3535 context_exists:2,
3536 display:4,
3537 unique_name:8,
3538 more_display:16
3539 */
3540
3541 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3542
3543 static char *
3544 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3545 {
3546 *pkt++ = 'q'; /* Info Query */
3547 *pkt++ = 'P'; /* process or thread info */
3548 pkt = pack_int (pkt, mode); /* mode */
3549 pkt = pack_threadid (pkt, id); /* threadid */
3550 *pkt = '\0'; /* terminate */
3551 return pkt;
3552 }
3553
3554 /* These values tag the fields in a thread info response packet. */
3555 /* Tagging the fields allows us to request specific fields and to
3556 add more fields as time goes by. */
3557
3558 #define TAG_THREADID 1 /* Echo the thread identifier. */
3559 #define TAG_EXISTS 2 /* Is this process defined enough to
3560 fetch registers and its stack? */
3561 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3562 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3563 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3564 the process. */
3565
3566 int
3567 remote_target::remote_unpack_thread_info_response (const char *pkt,
3568 threadref *expectedref,
3569 gdb_ext_thread_info *info)
3570 {
3571 struct remote_state *rs = get_remote_state ();
3572 int mask, length;
3573 int tag;
3574 threadref ref;
3575 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3576 int retval = 1;
3577
3578 /* info->threadid = 0; FIXME: implement zero_threadref. */
3579 info->active = 0;
3580 info->display[0] = '\0';
3581 info->shortname[0] = '\0';
3582 info->more_display[0] = '\0';
3583
3584 /* Assume the characters indicating the packet type have been
3585 stripped. */
3586 pkt = unpack_int (pkt, &mask); /* arg mask */
3587 pkt = unpack_threadid (pkt, &ref);
3588
3589 if (mask == 0)
3590 warning (_("Incomplete response to threadinfo request."));
3591 if (!threadmatch (&ref, expectedref))
3592 { /* This is an answer to a different request. */
3593 warning (_("ERROR RMT Thread info mismatch."));
3594 return 0;
3595 }
3596 copy_threadref (&info->threadid, &ref);
3597
3598 /* Loop on tagged fields , try to bail if something goes wrong. */
3599
3600 /* Packets are terminated with nulls. */
3601 while ((pkt < limit) && mask && *pkt)
3602 {
3603 pkt = unpack_int (pkt, &tag); /* tag */
3604 pkt = unpack_byte (pkt, &length); /* length */
3605 if (!(tag & mask)) /* Tags out of synch with mask. */
3606 {
3607 warning (_("ERROR RMT: threadinfo tag mismatch."));
3608 retval = 0;
3609 break;
3610 }
3611 if (tag == TAG_THREADID)
3612 {
3613 if (length != 16)
3614 {
3615 warning (_("ERROR RMT: length of threadid is not 16."));
3616 retval = 0;
3617 break;
3618 }
3619 pkt = unpack_threadid (pkt, &ref);
3620 mask = mask & ~TAG_THREADID;
3621 continue;
3622 }
3623 if (tag == TAG_EXISTS)
3624 {
3625 info->active = stub_unpack_int (pkt, length);
3626 pkt += length;
3627 mask = mask & ~(TAG_EXISTS);
3628 if (length > 8)
3629 {
3630 warning (_("ERROR RMT: 'exists' length too long."));
3631 retval = 0;
3632 break;
3633 }
3634 continue;
3635 }
3636 if (tag == TAG_THREADNAME)
3637 {
3638 pkt = unpack_string (pkt, &info->shortname[0], length);
3639 mask = mask & ~TAG_THREADNAME;
3640 continue;
3641 }
3642 if (tag == TAG_DISPLAY)
3643 {
3644 pkt = unpack_string (pkt, &info->display[0], length);
3645 mask = mask & ~TAG_DISPLAY;
3646 continue;
3647 }
3648 if (tag == TAG_MOREDISPLAY)
3649 {
3650 pkt = unpack_string (pkt, &info->more_display[0], length);
3651 mask = mask & ~TAG_MOREDISPLAY;
3652 continue;
3653 }
3654 warning (_("ERROR RMT: unknown thread info tag."));
3655 break; /* Not a tag we know about. */
3656 }
3657 return retval;
3658 }
3659
3660 int
3661 remote_target::remote_get_threadinfo (threadref *threadid,
3662 int fieldset,
3663 gdb_ext_thread_info *info)
3664 {
3665 struct remote_state *rs = get_remote_state ();
3666 int result;
3667
3668 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3669 putpkt (rs->buf);
3670 getpkt (&rs->buf, 0);
3671
3672 if (rs->buf[0] == '\0')
3673 return 0;
3674
3675 result = remote_unpack_thread_info_response (&rs->buf[2],
3676 threadid, info);
3677 return result;
3678 }
3679
3680 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3681
3682 static char *
3683 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3684 threadref *nextthread)
3685 {
3686 *pkt++ = 'q'; /* info query packet */
3687 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3688 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3689 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3690 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3691 *pkt = '\0';
3692 return pkt;
3693 }
3694
3695 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3696
3697 int
3698 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3699 threadref *original_echo,
3700 threadref *resultlist,
3701 int *doneflag)
3702 {
3703 struct remote_state *rs = get_remote_state ();
3704 int count, resultcount, done;
3705
3706 resultcount = 0;
3707 /* Assume the 'q' and 'M chars have been stripped. */
3708 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3709 /* done parse past here */
3710 pkt = unpack_byte (pkt, &count); /* count field */
3711 pkt = unpack_nibble (pkt, &done);
3712 /* The first threadid is the argument threadid. */
3713 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3714 while ((count-- > 0) && (pkt < limit))
3715 {
3716 pkt = unpack_threadid (pkt, resultlist++);
3717 if (resultcount++ >= result_limit)
3718 break;
3719 }
3720 if (doneflag)
3721 *doneflag = done;
3722 return resultcount;
3723 }
3724
3725 /* Fetch the next batch of threads from the remote. Returns -1 if the
3726 qL packet is not supported, 0 on error and 1 on success. */
3727
3728 int
3729 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3730 int result_limit, int *done, int *result_count,
3731 threadref *threadlist)
3732 {
3733 struct remote_state *rs = get_remote_state ();
3734 int result = 1;
3735
3736 /* Truncate result limit to be smaller than the packet size. */
3737 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3738 >= get_remote_packet_size ())
3739 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3740
3741 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3742 nextthread);
3743 putpkt (rs->buf);
3744 getpkt (&rs->buf, 0);
3745 if (rs->buf[0] == '\0')
3746 {
3747 /* Packet not supported. */
3748 return -1;
3749 }
3750
3751 *result_count =
3752 parse_threadlist_response (&rs->buf[2], result_limit,
3753 &rs->echo_nextthread, threadlist, done);
3754
3755 if (!threadmatch (&rs->echo_nextthread, nextthread))
3756 {
3757 /* FIXME: This is a good reason to drop the packet. */
3758 /* Possibly, there is a duplicate response. */
3759 /* Possibilities :
3760 retransmit immediatly - race conditions
3761 retransmit after timeout - yes
3762 exit
3763 wait for packet, then exit
3764 */
3765 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3766 return 0; /* I choose simply exiting. */
3767 }
3768 if (*result_count <= 0)
3769 {
3770 if (*done != 1)
3771 {
3772 warning (_("RMT ERROR : failed to get remote thread list."));
3773 result = 0;
3774 }
3775 return result; /* break; */
3776 }
3777 if (*result_count > result_limit)
3778 {
3779 *result_count = 0;
3780 warning (_("RMT ERROR: threadlist response longer than requested."));
3781 return 0;
3782 }
3783 return result;
3784 }
3785
3786 /* Fetch the list of remote threads, with the qL packet, and call
3787 STEPFUNCTION for each thread found. Stops iterating and returns 1
3788 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3789 STEPFUNCTION returns false. If the packet is not supported,
3790 returns -1. */
3791
3792 int
3793 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3794 void *context, int looplimit)
3795 {
3796 struct remote_state *rs = get_remote_state ();
3797 int done, i, result_count;
3798 int startflag = 1;
3799 int result = 1;
3800 int loopcount = 0;
3801
3802 done = 0;
3803 while (!done)
3804 {
3805 if (loopcount++ > looplimit)
3806 {
3807 result = 0;
3808 warning (_("Remote fetch threadlist -infinite loop-."));
3809 break;
3810 }
3811 result = remote_get_threadlist (startflag, &rs->nextthread,
3812 MAXTHREADLISTRESULTS,
3813 &done, &result_count,
3814 rs->resultthreadlist);
3815 if (result <= 0)
3816 break;
3817 /* Clear for later iterations. */
3818 startflag = 0;
3819 /* Setup to resume next batch of thread references, set nextthread. */
3820 if (result_count >= 1)
3821 copy_threadref (&rs->nextthread,
3822 &rs->resultthreadlist[result_count - 1]);
3823 i = 0;
3824 while (result_count--)
3825 {
3826 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3827 {
3828 result = 0;
3829 break;
3830 }
3831 }
3832 }
3833 return result;
3834 }
3835
3836 /* A thread found on the remote target. */
3837
3838 struct thread_item
3839 {
3840 explicit thread_item (ptid_t ptid_)
3841 : ptid (ptid_)
3842 {}
3843
3844 thread_item (thread_item &&other) = default;
3845 thread_item &operator= (thread_item &&other) = default;
3846
3847 DISABLE_COPY_AND_ASSIGN (thread_item);
3848
3849 /* The thread's PTID. */
3850 ptid_t ptid;
3851
3852 /* The thread's extra info. */
3853 std::string extra;
3854
3855 /* The thread's name. */
3856 std::string name;
3857
3858 /* The core the thread was running on. -1 if not known. */
3859 int core = -1;
3860
3861 /* The thread handle associated with the thread. */
3862 gdb::byte_vector thread_handle;
3863 };
3864
3865 /* Context passed around to the various methods listing remote
3866 threads. As new threads are found, they're added to the ITEMS
3867 vector. */
3868
3869 struct threads_listing_context
3870 {
3871 /* Return true if this object contains an entry for a thread with ptid
3872 PTID. */
3873
3874 bool contains_thread (ptid_t ptid) const
3875 {
3876 auto match_ptid = [&] (const thread_item &item)
3877 {
3878 return item.ptid == ptid;
3879 };
3880
3881 auto it = std::find_if (this->items.begin (),
3882 this->items.end (),
3883 match_ptid);
3884
3885 return it != this->items.end ();
3886 }
3887
3888 /* Remove the thread with ptid PTID. */
3889
3890 void remove_thread (ptid_t ptid)
3891 {
3892 auto match_ptid = [&] (const thread_item &item)
3893 {
3894 return item.ptid == ptid;
3895 };
3896
3897 auto it = std::remove_if (this->items.begin (),
3898 this->items.end (),
3899 match_ptid);
3900
3901 if (it != this->items.end ())
3902 this->items.erase (it);
3903 }
3904
3905 /* The threads found on the remote target. */
3906 std::vector<thread_item> items;
3907 };
3908
3909 static int
3910 remote_newthread_step (threadref *ref, void *data)
3911 {
3912 struct threads_listing_context *context
3913 = (struct threads_listing_context *) data;
3914 int pid = inferior_ptid.pid ();
3915 int lwp = threadref_to_int (ref);
3916 ptid_t ptid (pid, lwp);
3917
3918 context->items.emplace_back (ptid);
3919
3920 return 1; /* continue iterator */
3921 }
3922
3923 #define CRAZY_MAX_THREADS 1000
3924
3925 ptid_t
3926 remote_target::remote_current_thread (ptid_t oldpid)
3927 {
3928 struct remote_state *rs = get_remote_state ();
3929
3930 putpkt ("qC");
3931 getpkt (&rs->buf, 0);
3932 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3933 {
3934 const char *obuf;
3935 ptid_t result;
3936
3937 result = read_ptid (&rs->buf[2], &obuf);
3938 if (*obuf != '\0')
3939 remote_debug_printf ("warning: garbage in qC reply");
3940
3941 return result;
3942 }
3943 else
3944 return oldpid;
3945 }
3946
3947 /* List remote threads using the deprecated qL packet. */
3948
3949 int
3950 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3951 {
3952 if (remote_threadlist_iterator (remote_newthread_step, context,
3953 CRAZY_MAX_THREADS) >= 0)
3954 return 1;
3955
3956 return 0;
3957 }
3958
3959 #if defined(HAVE_LIBEXPAT)
3960
3961 static void
3962 start_thread (struct gdb_xml_parser *parser,
3963 const struct gdb_xml_element *element,
3964 void *user_data,
3965 std::vector<gdb_xml_value> &attributes)
3966 {
3967 struct threads_listing_context *data
3968 = (struct threads_listing_context *) user_data;
3969 struct gdb_xml_value *attr;
3970
3971 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3972 ptid_t ptid = read_ptid (id, NULL);
3973
3974 data->items.emplace_back (ptid);
3975 thread_item &item = data->items.back ();
3976
3977 attr = xml_find_attribute (attributes, "core");
3978 if (attr != NULL)
3979 item.core = *(ULONGEST *) attr->value.get ();
3980
3981 attr = xml_find_attribute (attributes, "name");
3982 if (attr != NULL)
3983 item.name = (const char *) attr->value.get ();
3984
3985 attr = xml_find_attribute (attributes, "handle");
3986 if (attr != NULL)
3987 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3988 }
3989
3990 static void
3991 end_thread (struct gdb_xml_parser *parser,
3992 const struct gdb_xml_element *element,
3993 void *user_data, const char *body_text)
3994 {
3995 struct threads_listing_context *data
3996 = (struct threads_listing_context *) user_data;
3997
3998 if (body_text != NULL && *body_text != '\0')
3999 data->items.back ().extra = body_text;
4000 }
4001
4002 const struct gdb_xml_attribute thread_attributes[] = {
4003 { "id", GDB_XML_AF_NONE, NULL, NULL },
4004 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
4005 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
4006 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
4007 { NULL, GDB_XML_AF_NONE, NULL, NULL }
4008 };
4009
4010 const struct gdb_xml_element thread_children[] = {
4011 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4012 };
4013
4014 const struct gdb_xml_element threads_children[] = {
4015 { "thread", thread_attributes, thread_children,
4016 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
4017 start_thread, end_thread },
4018 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4019 };
4020
4021 const struct gdb_xml_element threads_elements[] = {
4022 { "threads", NULL, threads_children,
4023 GDB_XML_EF_NONE, NULL, NULL },
4024 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4025 };
4026
4027 #endif
4028
4029 /* List remote threads using qXfer:threads:read. */
4030
4031 int
4032 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
4033 {
4034 #if defined(HAVE_LIBEXPAT)
4035 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4036 {
4037 gdb::optional<gdb::char_vector> xml
4038 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
4039
4040 if (xml && (*xml)[0] != '\0')
4041 {
4042 gdb_xml_parse_quick (_("threads"), "threads.dtd",
4043 threads_elements, xml->data (), context);
4044 }
4045
4046 return 1;
4047 }
4048 #endif
4049
4050 return 0;
4051 }
4052
4053 /* List remote threads using qfThreadInfo/qsThreadInfo. */
4054
4055 int
4056 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
4057 {
4058 struct remote_state *rs = get_remote_state ();
4059
4060 if (rs->use_threadinfo_query)
4061 {
4062 const char *bufp;
4063
4064 putpkt ("qfThreadInfo");
4065 getpkt (&rs->buf, 0);
4066 bufp = rs->buf.data ();
4067 if (bufp[0] != '\0') /* q packet recognized */
4068 {
4069 while (*bufp++ == 'm') /* reply contains one or more TID */
4070 {
4071 do
4072 {
4073 ptid_t ptid = read_ptid (bufp, &bufp);
4074 context->items.emplace_back (ptid);
4075 }
4076 while (*bufp++ == ','); /* comma-separated list */
4077 putpkt ("qsThreadInfo");
4078 getpkt (&rs->buf, 0);
4079 bufp = rs->buf.data ();
4080 }
4081 return 1;
4082 }
4083 else
4084 {
4085 /* Packet not recognized. */
4086 rs->use_threadinfo_query = 0;
4087 }
4088 }
4089
4090 return 0;
4091 }
4092
4093 /* Return true if INF only has one non-exited thread. */
4094
4095 static bool
4096 has_single_non_exited_thread (inferior *inf)
4097 {
4098 int count = 0;
4099 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
4100 if (++count > 1)
4101 break;
4102 return count == 1;
4103 }
4104
4105 /* Implement the to_update_thread_list function for the remote
4106 targets. */
4107
4108 void
4109 remote_target::update_thread_list ()
4110 {
4111 struct threads_listing_context context;
4112 int got_list = 0;
4113
4114 /* We have a few different mechanisms to fetch the thread list. Try
4115 them all, starting with the most preferred one first, falling
4116 back to older methods. */
4117 if (remote_get_threads_with_qxfer (&context)
4118 || remote_get_threads_with_qthreadinfo (&context)
4119 || remote_get_threads_with_ql (&context))
4120 {
4121 got_list = 1;
4122
4123 if (context.items.empty ()
4124 && remote_thread_always_alive (inferior_ptid))
4125 {
4126 /* Some targets don't really support threads, but still
4127 reply an (empty) thread list in response to the thread
4128 listing packets, instead of replying "packet not
4129 supported". Exit early so we don't delete the main
4130 thread. */
4131 return;
4132 }
4133
4134 /* CONTEXT now holds the current thread list on the remote
4135 target end. Delete GDB-side threads no longer found on the
4136 target. */
4137 for (thread_info *tp : all_threads_safe ())
4138 {
4139 if (tp->inf->process_target () != this)
4140 continue;
4141
4142 if (!context.contains_thread (tp->ptid))
4143 {
4144 /* Do not remove the thread if it is the last thread in
4145 the inferior. This situation happens when we have a
4146 pending exit process status to process. Otherwise we
4147 may end up with a seemingly live inferior (i.e. pid
4148 != 0) that has no threads. */
4149 if (has_single_non_exited_thread (tp->inf))
4150 continue;
4151
4152 /* Not found. */
4153 delete_thread (tp);
4154 }
4155 }
4156
4157 /* Remove any unreported fork child threads from CONTEXT so
4158 that we don't interfere with follow fork, which is where
4159 creation of such threads is handled. */
4160 remove_new_fork_children (&context);
4161
4162 /* And now add threads we don't know about yet to our list. */
4163 for (thread_item &item : context.items)
4164 {
4165 if (item.ptid != null_ptid)
4166 {
4167 /* In non-stop mode, we assume new found threads are
4168 executing until proven otherwise with a stop reply.
4169 In all-stop, we can only get here if all threads are
4170 stopped. */
4171 bool executing = target_is_non_stop_p ();
4172
4173 remote_notice_new_inferior (item.ptid, executing);
4174
4175 thread_info *tp = this->find_thread (item.ptid);
4176 remote_thread_info *info = get_remote_thread_info (tp);
4177 info->core = item.core;
4178 info->extra = std::move (item.extra);
4179 info->name = std::move (item.name);
4180 info->thread_handle = std::move (item.thread_handle);
4181 }
4182 }
4183 }
4184
4185 if (!got_list)
4186 {
4187 /* If no thread listing method is supported, then query whether
4188 each known thread is alive, one by one, with the T packet.
4189 If the target doesn't support threads at all, then this is a
4190 no-op. See remote_thread_alive. */
4191 prune_threads ();
4192 }
4193 }
4194
4195 /*
4196 * Collect a descriptive string about the given thread.
4197 * The target may say anything it wants to about the thread
4198 * (typically info about its blocked / runnable state, name, etc.).
4199 * This string will appear in the info threads display.
4200 *
4201 * Optional: targets are not required to implement this function.
4202 */
4203
4204 const char *
4205 remote_target::extra_thread_info (thread_info *tp)
4206 {
4207 struct remote_state *rs = get_remote_state ();
4208 int set;
4209 threadref id;
4210 struct gdb_ext_thread_info threadinfo;
4211
4212 if (rs->remote_desc == 0) /* paranoia */
4213 internal_error (_("remote_threads_extra_info"));
4214
4215 if (tp->ptid == magic_null_ptid
4216 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4217 /* This is the main thread which was added by GDB. The remote
4218 server doesn't know about it. */
4219 return NULL;
4220
4221 std::string &extra = get_remote_thread_info (tp)->extra;
4222
4223 /* If already have cached info, use it. */
4224 if (!extra.empty ())
4225 return extra.c_str ();
4226
4227 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4228 {
4229 /* If we're using qXfer:threads:read, then the extra info is
4230 included in the XML. So if we didn't have anything cached,
4231 it's because there's really no extra info. */
4232 return NULL;
4233 }
4234
4235 if (rs->use_threadextra_query)
4236 {
4237 char *b = rs->buf.data ();
4238 char *endb = b + get_remote_packet_size ();
4239
4240 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4241 b += strlen (b);
4242 write_ptid (b, endb, tp->ptid);
4243
4244 putpkt (rs->buf);
4245 getpkt (&rs->buf, 0);
4246 if (rs->buf[0] != 0)
4247 {
4248 extra.resize (strlen (rs->buf.data ()) / 2);
4249 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4250 return extra.c_str ();
4251 }
4252 }
4253
4254 /* If the above query fails, fall back to the old method. */
4255 rs->use_threadextra_query = 0;
4256 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4257 | TAG_MOREDISPLAY | TAG_DISPLAY;
4258 int_to_threadref (&id, tp->ptid.lwp ());
4259 if (remote_get_threadinfo (&id, set, &threadinfo))
4260 if (threadinfo.active)
4261 {
4262 if (*threadinfo.shortname)
4263 string_appendf (extra, " Name: %s", threadinfo.shortname);
4264 if (*threadinfo.display)
4265 {
4266 if (!extra.empty ())
4267 extra += ',';
4268 string_appendf (extra, " State: %s", threadinfo.display);
4269 }
4270 if (*threadinfo.more_display)
4271 {
4272 if (!extra.empty ())
4273 extra += ',';
4274 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4275 }
4276 return extra.c_str ();
4277 }
4278 return NULL;
4279 }
4280 \f
4281
4282 bool
4283 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4284 struct static_tracepoint_marker *marker)
4285 {
4286 struct remote_state *rs = get_remote_state ();
4287 char *p = rs->buf.data ();
4288
4289 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4290 p += strlen (p);
4291 p += hexnumstr (p, addr);
4292 putpkt (rs->buf);
4293 getpkt (&rs->buf, 0);
4294 p = rs->buf.data ();
4295
4296 if (*p == 'E')
4297 error (_("Remote failure reply: %s"), p);
4298
4299 if (*p++ == 'm')
4300 {
4301 parse_static_tracepoint_marker_definition (p, NULL, marker);
4302 return true;
4303 }
4304
4305 return false;
4306 }
4307
4308 std::vector<static_tracepoint_marker>
4309 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4310 {
4311 struct remote_state *rs = get_remote_state ();
4312 std::vector<static_tracepoint_marker> markers;
4313 const char *p;
4314 static_tracepoint_marker marker;
4315
4316 /* Ask for a first packet of static tracepoint marker
4317 definition. */
4318 putpkt ("qTfSTM");
4319 getpkt (&rs->buf, 0);
4320 p = rs->buf.data ();
4321 if (*p == 'E')
4322 error (_("Remote failure reply: %s"), p);
4323
4324 while (*p++ == 'm')
4325 {
4326 do
4327 {
4328 parse_static_tracepoint_marker_definition (p, &p, &marker);
4329
4330 if (strid == NULL || marker.str_id == strid)
4331 markers.push_back (std::move (marker));
4332 }
4333 while (*p++ == ','); /* comma-separated list */
4334 /* Ask for another packet of static tracepoint definition. */
4335 putpkt ("qTsSTM");
4336 getpkt (&rs->buf, 0);
4337 p = rs->buf.data ();
4338 }
4339
4340 return markers;
4341 }
4342
4343 \f
4344 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4345
4346 ptid_t
4347 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4348 {
4349 return ptid_t (inferior_ptid.pid (), lwp);
4350 }
4351 \f
4352
4353 /* Restart the remote side; this is an extended protocol operation. */
4354
4355 void
4356 remote_target::extended_remote_restart ()
4357 {
4358 struct remote_state *rs = get_remote_state ();
4359
4360 /* Send the restart command; for reasons I don't understand the
4361 remote side really expects a number after the "R". */
4362 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4363 putpkt (rs->buf);
4364
4365 remote_fileio_reset ();
4366 }
4367 \f
4368 /* Clean up connection to a remote debugger. */
4369
4370 void
4371 remote_target::close ()
4372 {
4373 /* Make sure we leave stdin registered in the event loop. */
4374 terminal_ours ();
4375
4376 trace_reset_local_state ();
4377
4378 delete this;
4379 }
4380
4381 remote_target::~remote_target ()
4382 {
4383 struct remote_state *rs = get_remote_state ();
4384
4385 /* Check for NULL because we may get here with a partially
4386 constructed target/connection. */
4387 if (rs->remote_desc == nullptr)
4388 return;
4389
4390 serial_close (rs->remote_desc);
4391
4392 /* We are destroying the remote target, so we should discard
4393 everything of this target. */
4394 discard_pending_stop_replies_in_queue ();
4395
4396 if (rs->remote_async_inferior_event_token)
4397 delete_async_event_handler (&rs->remote_async_inferior_event_token);
4398
4399 delete rs->notif_state;
4400 }
4401
4402 /* Query the remote side for the text, data and bss offsets. */
4403
4404 void
4405 remote_target::get_offsets ()
4406 {
4407 struct remote_state *rs = get_remote_state ();
4408 char *buf;
4409 char *ptr;
4410 int lose, num_segments = 0, do_sections, do_segments;
4411 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4412
4413 if (current_program_space->symfile_object_file == NULL)
4414 return;
4415
4416 putpkt ("qOffsets");
4417 getpkt (&rs->buf, 0);
4418 buf = rs->buf.data ();
4419
4420 if (buf[0] == '\000')
4421 return; /* Return silently. Stub doesn't support
4422 this command. */
4423 if (buf[0] == 'E')
4424 {
4425 warning (_("Remote failure reply: %s"), buf);
4426 return;
4427 }
4428
4429 /* Pick up each field in turn. This used to be done with scanf, but
4430 scanf will make trouble if CORE_ADDR size doesn't match
4431 conversion directives correctly. The following code will work
4432 with any size of CORE_ADDR. */
4433 text_addr = data_addr = bss_addr = 0;
4434 ptr = buf;
4435 lose = 0;
4436
4437 if (startswith (ptr, "Text="))
4438 {
4439 ptr += 5;
4440 /* Don't use strtol, could lose on big values. */
4441 while (*ptr && *ptr != ';')
4442 text_addr = (text_addr << 4) + fromhex (*ptr++);
4443
4444 if (startswith (ptr, ";Data="))
4445 {
4446 ptr += 6;
4447 while (*ptr && *ptr != ';')
4448 data_addr = (data_addr << 4) + fromhex (*ptr++);
4449 }
4450 else
4451 lose = 1;
4452
4453 if (!lose && startswith (ptr, ";Bss="))
4454 {
4455 ptr += 5;
4456 while (*ptr && *ptr != ';')
4457 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4458
4459 if (bss_addr != data_addr)
4460 warning (_("Target reported unsupported offsets: %s"), buf);
4461 }
4462 else
4463 lose = 1;
4464 }
4465 else if (startswith (ptr, "TextSeg="))
4466 {
4467 ptr += 8;
4468 /* Don't use strtol, could lose on big values. */
4469 while (*ptr && *ptr != ';')
4470 text_addr = (text_addr << 4) + fromhex (*ptr++);
4471 num_segments = 1;
4472
4473 if (startswith (ptr, ";DataSeg="))
4474 {
4475 ptr += 9;
4476 while (*ptr && *ptr != ';')
4477 data_addr = (data_addr << 4) + fromhex (*ptr++);
4478 num_segments++;
4479 }
4480 }
4481 else
4482 lose = 1;
4483
4484 if (lose)
4485 error (_("Malformed response to offset query, %s"), buf);
4486 else if (*ptr != '\0')
4487 warning (_("Target reported unsupported offsets: %s"), buf);
4488
4489 objfile *objf = current_program_space->symfile_object_file;
4490 section_offsets offs = objf->section_offsets;
4491
4492 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
4493 do_segments = (data != NULL);
4494 do_sections = num_segments == 0;
4495
4496 if (num_segments > 0)
4497 {
4498 segments[0] = text_addr;
4499 segments[1] = data_addr;
4500 }
4501 /* If we have two segments, we can still try to relocate everything
4502 by assuming that the .text and .data offsets apply to the whole
4503 text and data segments. Convert the offsets given in the packet
4504 to base addresses for symfile_map_offsets_to_segments. */
4505 else if (data != nullptr && data->segments.size () == 2)
4506 {
4507 segments[0] = data->segments[0].base + text_addr;
4508 segments[1] = data->segments[1].base + data_addr;
4509 num_segments = 2;
4510 }
4511 /* If the object file has only one segment, assume that it is text
4512 rather than data; main programs with no writable data are rare,
4513 but programs with no code are useless. Of course the code might
4514 have ended up in the data segment... to detect that we would need
4515 the permissions here. */
4516 else if (data && data->segments.size () == 1)
4517 {
4518 segments[0] = data->segments[0].base + text_addr;
4519 num_segments = 1;
4520 }
4521 /* There's no way to relocate by segment. */
4522 else
4523 do_segments = 0;
4524
4525 if (do_segments)
4526 {
4527 int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
4528 data.get (), offs,
4529 num_segments, segments);
4530
4531 if (ret == 0 && !do_sections)
4532 error (_("Can not handle qOffsets TextSeg "
4533 "response with this symbol file"));
4534
4535 if (ret > 0)
4536 do_sections = 0;
4537 }
4538
4539 if (do_sections)
4540 {
4541 offs[SECT_OFF_TEXT (objf)] = text_addr;
4542
4543 /* This is a temporary kludge to force data and bss to use the
4544 same offsets because that's what nlmconv does now. The real
4545 solution requires changes to the stub and remote.c that I
4546 don't have time to do right now. */
4547
4548 offs[SECT_OFF_DATA (objf)] = data_addr;
4549 offs[SECT_OFF_BSS (objf)] = data_addr;
4550 }
4551
4552 objfile_relocate (objf, offs);
4553 }
4554
4555 /* Send interrupt_sequence to remote target. */
4556
4557 void
4558 remote_target::send_interrupt_sequence ()
4559 {
4560 struct remote_state *rs = get_remote_state ();
4561
4562 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4563 remote_serial_write ("\x03", 1);
4564 else if (interrupt_sequence_mode == interrupt_sequence_break)
4565 serial_send_break (rs->remote_desc);
4566 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4567 {
4568 serial_send_break (rs->remote_desc);
4569 remote_serial_write ("g", 1);
4570 }
4571 else
4572 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
4573 interrupt_sequence_mode);
4574 }
4575
4576
4577 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4578 and extract the PTID. Returns NULL_PTID if not found. */
4579
4580 static ptid_t
4581 stop_reply_extract_thread (const char *stop_reply)
4582 {
4583 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4584 {
4585 const char *p;
4586
4587 /* Txx r:val ; r:val (...) */
4588 p = &stop_reply[3];
4589
4590 /* Look for "register" named "thread". */
4591 while (*p != '\0')
4592 {
4593 const char *p1;
4594
4595 p1 = strchr (p, ':');
4596 if (p1 == NULL)
4597 return null_ptid;
4598
4599 if (strncmp (p, "thread", p1 - p) == 0)
4600 return read_ptid (++p1, &p);
4601
4602 p1 = strchr (p, ';');
4603 if (p1 == NULL)
4604 return null_ptid;
4605 p1++;
4606
4607 p = p1;
4608 }
4609 }
4610
4611 return null_ptid;
4612 }
4613
4614 /* Determine the remote side's current thread. If we have a stop
4615 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4616 "thread" register we can extract the current thread from. If not,
4617 ask the remote which is the current thread with qC. The former
4618 method avoids a roundtrip. */
4619
4620 ptid_t
4621 remote_target::get_current_thread (const char *wait_status)
4622 {
4623 ptid_t ptid = null_ptid;
4624
4625 /* Note we don't use remote_parse_stop_reply as that makes use of
4626 the target architecture, which we haven't yet fully determined at
4627 this point. */
4628 if (wait_status != NULL)
4629 ptid = stop_reply_extract_thread (wait_status);
4630 if (ptid == null_ptid)
4631 ptid = remote_current_thread (inferior_ptid);
4632
4633 return ptid;
4634 }
4635
4636 /* Query the remote target for which is the current thread/process,
4637 add it to our tables, and update INFERIOR_PTID. The caller is
4638 responsible for setting the state such that the remote end is ready
4639 to return the current thread.
4640
4641 This function is called after handling the '?' or 'vRun' packets,
4642 whose response is a stop reply from which we can also try
4643 extracting the thread. If the target doesn't support the explicit
4644 qC query, we infer the current thread from that stop reply, passed
4645 in in WAIT_STATUS, which may be NULL.
4646
4647 The function returns pointer to the main thread of the inferior. */
4648
4649 thread_info *
4650 remote_target::add_current_inferior_and_thread (const char *wait_status)
4651 {
4652 bool fake_pid_p = false;
4653
4654 switch_to_no_thread ();
4655
4656 /* Now, if we have thread information, update the current thread's
4657 ptid. */
4658 ptid_t curr_ptid = get_current_thread (wait_status);
4659
4660 if (curr_ptid != null_ptid)
4661 {
4662 if (!m_features.remote_multi_process_p ())
4663 fake_pid_p = true;
4664 }
4665 else
4666 {
4667 /* Without this, some commands which require an active target
4668 (such as kill) won't work. This variable serves (at least)
4669 double duty as both the pid of the target process (if it has
4670 such), and as a flag indicating that a target is active. */
4671 curr_ptid = magic_null_ptid;
4672 fake_pid_p = true;
4673 }
4674
4675 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4676
4677 /* Add the main thread and switch to it. Don't try reading
4678 registers yet, since we haven't fetched the target description
4679 yet. */
4680 thread_info *tp = add_thread_silent (this, curr_ptid);
4681 switch_to_thread_no_regs (tp);
4682
4683 return tp;
4684 }
4685
4686 /* Print info about a thread that was found already stopped on
4687 connection. */
4688
4689 void
4690 remote_target::print_one_stopped_thread (thread_info *thread)
4691 {
4692 target_waitstatus ws;
4693
4694 /* If there is a pending waitstatus, use it. If there isn't it's because
4695 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4696 and process_initial_stop_replies decided it wasn't interesting to save
4697 and report to the core. */
4698 if (thread->has_pending_waitstatus ())
4699 {
4700 ws = thread->pending_waitstatus ();
4701 thread->clear_pending_waitstatus ();
4702 }
4703 else
4704 {
4705 ws.set_stopped (GDB_SIGNAL_0);
4706 }
4707
4708 switch_to_thread (thread);
4709 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4710 set_current_sal_from_frame (get_current_frame ());
4711
4712 /* For "info program". */
4713 set_last_target_status (this, thread->ptid, ws);
4714
4715 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4716 {
4717 enum gdb_signal sig = ws.sig ();
4718
4719 if (signal_print_state (sig))
4720 notify_signal_received (sig);
4721 }
4722
4723 notify_normal_stop (nullptr, 1);
4724 }
4725
4726 /* Process all initial stop replies the remote side sent in response
4727 to the ? packet. These indicate threads that were already stopped
4728 on initial connection. We mark these threads as stopped and print
4729 their current frame before giving the user the prompt. */
4730
4731 void
4732 remote_target::process_initial_stop_replies (int from_tty)
4733 {
4734 int pending_stop_replies = stop_reply_queue_length ();
4735 struct thread_info *selected = NULL;
4736 struct thread_info *lowest_stopped = NULL;
4737 struct thread_info *first = NULL;
4738
4739 /* This is only used when the target is non-stop. */
4740 gdb_assert (target_is_non_stop_p ());
4741
4742 /* Consume the initial pending events. */
4743 while (pending_stop_replies-- > 0)
4744 {
4745 ptid_t waiton_ptid = minus_one_ptid;
4746 ptid_t event_ptid;
4747 struct target_waitstatus ws;
4748 int ignore_event = 0;
4749
4750 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4751 if (remote_debug)
4752 print_target_wait_results (waiton_ptid, event_ptid, ws);
4753
4754 switch (ws.kind ())
4755 {
4756 case TARGET_WAITKIND_IGNORE:
4757 case TARGET_WAITKIND_NO_RESUMED:
4758 case TARGET_WAITKIND_SIGNALLED:
4759 case TARGET_WAITKIND_EXITED:
4760 /* We shouldn't see these, but if we do, just ignore. */
4761 remote_debug_printf ("event ignored");
4762 ignore_event = 1;
4763 break;
4764
4765 default:
4766 break;
4767 }
4768
4769 if (ignore_event)
4770 continue;
4771
4772 thread_info *evthread = this->find_thread (event_ptid);
4773
4774 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4775 {
4776 enum gdb_signal sig = ws.sig ();
4777
4778 /* Stubs traditionally report SIGTRAP as initial signal,
4779 instead of signal 0. Suppress it. */
4780 if (sig == GDB_SIGNAL_TRAP)
4781 sig = GDB_SIGNAL_0;
4782 evthread->set_stop_signal (sig);
4783 ws.set_stopped (sig);
4784 }
4785
4786 if (ws.kind () != TARGET_WAITKIND_STOPPED
4787 || ws.sig () != GDB_SIGNAL_0)
4788 evthread->set_pending_waitstatus (ws);
4789
4790 set_executing (this, event_ptid, false);
4791 set_running (this, event_ptid, false);
4792 get_remote_thread_info (evthread)->set_not_resumed ();
4793 }
4794
4795 /* "Notice" the new inferiors before anything related to
4796 registers/memory. */
4797 for (inferior *inf : all_non_exited_inferiors (this))
4798 {
4799 inf->needs_setup = true;
4800
4801 if (non_stop)
4802 {
4803 thread_info *thread = any_live_thread_of_inferior (inf);
4804 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4805 from_tty);
4806 }
4807 }
4808
4809 /* If all-stop on top of non-stop, pause all threads. Note this
4810 records the threads' stop pc, so must be done after "noticing"
4811 the inferiors. */
4812 if (!non_stop)
4813 {
4814 {
4815 /* At this point, the remote target is not async. It needs to be for
4816 the poll in stop_all_threads to consider events from it, so enable
4817 it temporarily. */
4818 gdb_assert (!this->is_async_p ());
4819 SCOPE_EXIT { target_async (false); };
4820 target_async (true);
4821 stop_all_threads ("remote connect in all-stop");
4822 }
4823
4824 /* If all threads of an inferior were already stopped, we
4825 haven't setup the inferior yet. */
4826 for (inferior *inf : all_non_exited_inferiors (this))
4827 {
4828 if (inf->needs_setup)
4829 {
4830 thread_info *thread = any_live_thread_of_inferior (inf);
4831 switch_to_thread_no_regs (thread);
4832 setup_inferior (0);
4833 }
4834 }
4835 }
4836
4837 /* Now go over all threads that are stopped, and print their current
4838 frame. If all-stop, then if there's a signalled thread, pick
4839 that as current. */
4840 for (thread_info *thread : all_non_exited_threads (this))
4841 {
4842 if (first == NULL)
4843 first = thread;
4844
4845 if (!non_stop)
4846 thread->set_running (false);
4847 else if (thread->state != THREAD_STOPPED)
4848 continue;
4849
4850 if (selected == nullptr && thread->has_pending_waitstatus ())
4851 selected = thread;
4852
4853 if (lowest_stopped == NULL
4854 || thread->inf->num < lowest_stopped->inf->num
4855 || thread->per_inf_num < lowest_stopped->per_inf_num)
4856 lowest_stopped = thread;
4857
4858 if (non_stop)
4859 print_one_stopped_thread (thread);
4860 }
4861
4862 /* In all-stop, we only print the status of one thread, and leave
4863 others with their status pending. */
4864 if (!non_stop)
4865 {
4866 thread_info *thread = selected;
4867 if (thread == NULL)
4868 thread = lowest_stopped;
4869 if (thread == NULL)
4870 thread = first;
4871
4872 print_one_stopped_thread (thread);
4873 }
4874 }
4875
4876 /* Mark a remote_target as starting (by setting the starting_up flag within
4877 its remote_state) for the lifetime of this object. The reference count
4878 on the remote target is temporarily incremented, to prevent the target
4879 being deleted under our feet. */
4880
4881 struct scoped_mark_target_starting
4882 {
4883 /* Constructor, TARGET is the target to be marked as starting, its
4884 reference count will be incremented. */
4885 scoped_mark_target_starting (remote_target *target)
4886 : m_remote_target (remote_target_ref::new_reference (target)),
4887 m_restore_starting_up (set_starting_up_flag (target))
4888 { /* Nothing. */ }
4889
4890 private:
4891
4892 /* Helper function, set the starting_up flag on TARGET and return an
4893 object which, when it goes out of scope, will restore the previous
4894 value of the starting_up flag. */
4895 static scoped_restore_tmpl<bool>
4896 set_starting_up_flag (remote_target *target)
4897 {
4898 remote_state *rs = target->get_remote_state ();
4899 gdb_assert (!rs->starting_up);
4900 return make_scoped_restore (&rs->starting_up, true);
4901 }
4902
4903 /* A gdb::ref_ptr pointer to a remote_target. */
4904 using remote_target_ref = gdb::ref_ptr<remote_target, target_ops_ref_policy>;
4905
4906 /* A reference to the target on which we are operating. */
4907 remote_target_ref m_remote_target;
4908
4909 /* An object which restores the previous value of the starting_up flag
4910 when it goes out of scope. */
4911 scoped_restore_tmpl<bool> m_restore_starting_up;
4912 };
4913
4914 /* Helper for remote_target::start_remote, start the remote connection and
4915 sync state. Return true if everything goes OK, otherwise, return false.
4916 This function exists so that the scoped_restore created within it will
4917 expire before we return to remote_target::start_remote. */
4918
4919 bool
4920 remote_target::start_remote_1 (int from_tty, int extended_p)
4921 {
4922 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4923
4924 struct remote_state *rs = get_remote_state ();
4925
4926 /* Signal other parts that we're going through the initial setup,
4927 and so things may not be stable yet. E.g., we don't try to
4928 install tracepoints until we've relocated symbols. Also, a
4929 Ctrl-C before we're connected and synced up can't interrupt the
4930 target. Instead, it offers to drop the (potentially wedged)
4931 connection. */
4932 scoped_mark_target_starting target_is_starting (this);
4933
4934 QUIT;
4935
4936 if (interrupt_on_connect)
4937 send_interrupt_sequence ();
4938
4939 /* Ack any packet which the remote side has already sent. */
4940 remote_serial_write ("+", 1);
4941
4942 /* The first packet we send to the target is the optional "supported
4943 packets" request. If the target can answer this, it will tell us
4944 which later probes to skip. */
4945 remote_query_supported ();
4946
4947 /* Check vCont support and set the remote state's vCont_action_support
4948 attribute. */
4949 remote_vcont_probe ();
4950
4951 /* If the stub wants to get a QAllow, compose one and send it. */
4952 if (m_features.packet_support (PACKET_QAllow) != PACKET_DISABLE)
4953 set_permissions ();
4954
4955 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4956 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4957 as a reply to known packet. For packet "vFile:setfs:" it is an
4958 invalid reply and GDB would return error in
4959 remote_hostio_set_filesystem, making remote files access impossible.
4960 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4961 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4962 {
4963 const char v_mustreplyempty[] = "vMustReplyEmpty";
4964
4965 putpkt (v_mustreplyempty);
4966 getpkt (&rs->buf, 0);
4967 if (strcmp (rs->buf.data (), "OK") == 0)
4968 {
4969 m_features.m_protocol_packets[PACKET_vFile_setfs].support
4970 = PACKET_DISABLE;
4971 }
4972 else if (strcmp (rs->buf.data (), "") != 0)
4973 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4974 rs->buf.data ());
4975 }
4976
4977 /* Next, we possibly activate noack mode.
4978
4979 If the QStartNoAckMode packet configuration is set to AUTO,
4980 enable noack mode if the stub reported a wish for it with
4981 qSupported.
4982
4983 If set to TRUE, then enable noack mode even if the stub didn't
4984 report it in qSupported. If the stub doesn't reply OK, the
4985 session ends with an error.
4986
4987 If FALSE, then don't activate noack mode, regardless of what the
4988 stub claimed should be the default with qSupported. */
4989
4990 if (m_features.packet_support (PACKET_QStartNoAckMode) != PACKET_DISABLE)
4991 {
4992 putpkt ("QStartNoAckMode");
4993 getpkt (&rs->buf, 0);
4994 if (m_features.packet_ok (rs->buf, PACKET_QStartNoAckMode) == PACKET_OK)
4995 rs->noack_mode = 1;
4996 }
4997
4998 if (extended_p)
4999 {
5000 /* Tell the remote that we are using the extended protocol. */
5001 putpkt ("!");
5002 getpkt (&rs->buf, 0);
5003 }
5004
5005 /* Let the target know which signals it is allowed to pass down to
5006 the program. */
5007 update_signals_program_target ();
5008
5009 /* Next, if the target can specify a description, read it. We do
5010 this before anything involving memory or registers. */
5011 target_find_description ();
5012
5013 /* Next, now that we know something about the target, update the
5014 address spaces in the program spaces. */
5015 update_address_spaces ();
5016
5017 /* On OSs where the list of libraries is global to all
5018 processes, we fetch them early. */
5019 if (gdbarch_has_global_solist (target_gdbarch ()))
5020 solib_add (NULL, from_tty, auto_solib_add);
5021
5022 if (target_is_non_stop_p ())
5023 {
5024 if (m_features.packet_support (PACKET_QNonStop) != PACKET_ENABLE)
5025 error (_("Non-stop mode requested, but remote "
5026 "does not support non-stop"));
5027
5028 putpkt ("QNonStop:1");
5029 getpkt (&rs->buf, 0);
5030
5031 if (strcmp (rs->buf.data (), "OK") != 0)
5032 error (_("Remote refused setting non-stop mode with: %s"),
5033 rs->buf.data ());
5034
5035 /* Find about threads and processes the stub is already
5036 controlling. We default to adding them in the running state.
5037 The '?' query below will then tell us about which threads are
5038 stopped. */
5039 this->update_thread_list ();
5040 }
5041 else if (m_features.packet_support (PACKET_QNonStop) == PACKET_ENABLE)
5042 {
5043 /* Don't assume that the stub can operate in all-stop mode.
5044 Request it explicitly. */
5045 putpkt ("QNonStop:0");
5046 getpkt (&rs->buf, 0);
5047
5048 if (strcmp (rs->buf.data (), "OK") != 0)
5049 error (_("Remote refused setting all-stop mode with: %s"),
5050 rs->buf.data ());
5051 }
5052
5053 /* Upload TSVs regardless of whether the target is running or not. The
5054 remote stub, such as GDBserver, may have some predefined or builtin
5055 TSVs, even if the target is not running. */
5056 if (get_trace_status (current_trace_status ()) != -1)
5057 {
5058 struct uploaded_tsv *uploaded_tsvs = NULL;
5059
5060 upload_trace_state_variables (&uploaded_tsvs);
5061 merge_uploaded_trace_state_variables (&uploaded_tsvs);
5062 }
5063
5064 /* Check whether the target is running now. */
5065 putpkt ("?");
5066 getpkt (&rs->buf, 0);
5067
5068 if (!target_is_non_stop_p ())
5069 {
5070 char *wait_status = NULL;
5071
5072 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
5073 {
5074 if (!extended_p)
5075 error (_("The target is not running (try extended-remote?)"));
5076 return false;
5077 }
5078 else
5079 {
5080 /* Save the reply for later. */
5081 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
5082 strcpy (wait_status, rs->buf.data ());
5083 }
5084
5085 /* Fetch thread list. */
5086 target_update_thread_list ();
5087
5088 /* Let the stub know that we want it to return the thread. */
5089 set_continue_thread (minus_one_ptid);
5090
5091 if (thread_count (this) == 0)
5092 {
5093 /* Target has no concept of threads at all. GDB treats
5094 non-threaded target as single-threaded; add a main
5095 thread. */
5096 thread_info *tp = add_current_inferior_and_thread (wait_status);
5097 get_remote_thread_info (tp)->set_resumed ();
5098 }
5099 else
5100 {
5101 /* We have thread information; select the thread the target
5102 says should be current. If we're reconnecting to a
5103 multi-threaded program, this will ideally be the thread
5104 that last reported an event before GDB disconnected. */
5105 ptid_t curr_thread = get_current_thread (wait_status);
5106 if (curr_thread == null_ptid)
5107 {
5108 /* Odd... The target was able to list threads, but not
5109 tell us which thread was current (no "thread"
5110 register in T stop reply?). Just pick the first
5111 thread in the thread list then. */
5112
5113 remote_debug_printf ("warning: couldn't determine remote "
5114 "current thread; picking first in list.");
5115
5116 for (thread_info *tp : all_non_exited_threads (this,
5117 minus_one_ptid))
5118 {
5119 switch_to_thread (tp);
5120 break;
5121 }
5122 }
5123 else
5124 switch_to_thread (this->find_thread (curr_thread));
5125 }
5126
5127 /* init_wait_for_inferior should be called before get_offsets in order
5128 to manage `inserted' flag in bp loc in a correct state.
5129 breakpoint_init_inferior, called from init_wait_for_inferior, set
5130 `inserted' flag to 0, while before breakpoint_re_set, called from
5131 start_remote, set `inserted' flag to 1. In the initialization of
5132 inferior, breakpoint_init_inferior should be called first, and then
5133 breakpoint_re_set can be called. If this order is broken, state of
5134 `inserted' flag is wrong, and cause some problems on breakpoint
5135 manipulation. */
5136 init_wait_for_inferior ();
5137
5138 get_offsets (); /* Get text, data & bss offsets. */
5139
5140 /* If we could not find a description using qXfer, and we know
5141 how to do it some other way, try again. This is not
5142 supported for non-stop; it could be, but it is tricky if
5143 there are no stopped threads when we connect. */
5144 if (remote_read_description_p (this)
5145 && gdbarch_target_desc (target_gdbarch ()) == NULL)
5146 {
5147 target_clear_description ();
5148 target_find_description ();
5149 }
5150
5151 /* Use the previously fetched status. */
5152 gdb_assert (wait_status != NULL);
5153 struct notif_event *reply
5154 = remote_notif_parse (this, &notif_client_stop, wait_status);
5155 push_stop_reply ((struct stop_reply *) reply);
5156
5157 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
5158 }
5159 else
5160 {
5161 /* Clear WFI global state. Do this before finding about new
5162 threads and inferiors, and setting the current inferior.
5163 Otherwise we would clear the proceed status of the current
5164 inferior when we want its stop_soon state to be preserved
5165 (see notice_new_inferior). */
5166 init_wait_for_inferior ();
5167
5168 /* In non-stop, we will either get an "OK", meaning that there
5169 are no stopped threads at this time; or, a regular stop
5170 reply. In the latter case, there may be more than one thread
5171 stopped --- we pull them all out using the vStopped
5172 mechanism. */
5173 if (strcmp (rs->buf.data (), "OK") != 0)
5174 {
5175 const notif_client *notif = &notif_client_stop;
5176
5177 /* remote_notif_get_pending_replies acks this one, and gets
5178 the rest out. */
5179 rs->notif_state->pending_event[notif_client_stop.id]
5180 = remote_notif_parse (this, notif, rs->buf.data ());
5181 remote_notif_get_pending_events (notif);
5182 }
5183
5184 if (thread_count (this) == 0)
5185 {
5186 if (!extended_p)
5187 error (_("The target is not running (try extended-remote?)"));
5188 return false;
5189 }
5190
5191 /* Report all signals during attach/startup. */
5192 pass_signals ({});
5193
5194 /* If there are already stopped threads, mark them stopped and
5195 report their stops before giving the prompt to the user. */
5196 process_initial_stop_replies (from_tty);
5197
5198 if (target_can_async_p ())
5199 target_async (true);
5200 }
5201
5202 /* Give the target a chance to look up symbols. */
5203 for (inferior *inf : all_inferiors (this))
5204 {
5205 /* The inferiors that exist at this point were created from what
5206 was found already running on the remote side, so we know they
5207 have execution. */
5208 gdb_assert (this->has_execution (inf));
5209
5210 /* No use without a symbol-file. */
5211 if (inf->pspace->symfile_object_file == nullptr)
5212 continue;
5213
5214 /* Need to switch to a specific thread, because remote_check_symbols
5215 uses INFERIOR_PTID to set the general thread. */
5216 scoped_restore_current_thread restore_thread;
5217 thread_info *thread = any_thread_of_inferior (inf);
5218 switch_to_thread (thread);
5219 this->remote_check_symbols ();
5220 }
5221
5222 /* Possibly the target has been engaged in a trace run started
5223 previously; find out where things are at. */
5224 if (get_trace_status (current_trace_status ()) != -1)
5225 {
5226 struct uploaded_tp *uploaded_tps = NULL;
5227
5228 if (current_trace_status ()->running)
5229 gdb_printf (_("Trace is already running on the target.\n"));
5230
5231 upload_tracepoints (&uploaded_tps);
5232
5233 merge_uploaded_tracepoints (&uploaded_tps);
5234 }
5235
5236 /* Possibly the target has been engaged in a btrace record started
5237 previously; find out where things are at. */
5238 remote_btrace_maybe_reopen ();
5239
5240 return true;
5241 }
5242
5243 /* Start the remote connection and sync state. */
5244
5245 void
5246 remote_target::start_remote (int from_tty, int extended_p)
5247 {
5248 if (start_remote_1 (from_tty, extended_p)
5249 && breakpoints_should_be_inserted_now ())
5250 insert_breakpoints ();
5251 }
5252
5253 const char *
5254 remote_target::connection_string ()
5255 {
5256 remote_state *rs = get_remote_state ();
5257
5258 if (rs->remote_desc->name != NULL)
5259 return rs->remote_desc->name;
5260 else
5261 return NULL;
5262 }
5263
5264 /* Open a connection to a remote debugger.
5265 NAME is the filename used for communication. */
5266
5267 void
5268 remote_target::open (const char *name, int from_tty)
5269 {
5270 open_1 (name, from_tty, 0);
5271 }
5272
5273 /* Open a connection to a remote debugger using the extended
5274 remote gdb protocol. NAME is the filename used for communication. */
5275
5276 void
5277 extended_remote_target::open (const char *name, int from_tty)
5278 {
5279 open_1 (name, from_tty, 1 /*extended_p */);
5280 }
5281
5282 void
5283 remote_features::reset_all_packet_configs_support ()
5284 {
5285 int i;
5286
5287 for (i = 0; i < PACKET_MAX; i++)
5288 m_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5289 }
5290
5291 /* Initialize all packet configs. */
5292
5293 static void
5294 init_all_packet_configs (void)
5295 {
5296 int i;
5297
5298 for (i = 0; i < PACKET_MAX; i++)
5299 {
5300 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5301 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5302 }
5303 }
5304
5305 /* Symbol look-up. */
5306
5307 void
5308 remote_target::remote_check_symbols ()
5309 {
5310 char *tmp;
5311 int end;
5312
5313 /* It doesn't make sense to send a qSymbol packet for an inferior that
5314 doesn't have execution, because the remote side doesn't know about
5315 inferiors without execution. */
5316 gdb_assert (target_has_execution ());
5317
5318 if (m_features.packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5319 return;
5320
5321 /* Make sure the remote is pointing at the right process. Note
5322 there's no way to select "no process". */
5323 set_general_process ();
5324
5325 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5326 because we need both at the same time. */
5327 gdb::char_vector msg (get_remote_packet_size ());
5328 gdb::char_vector reply (get_remote_packet_size ());
5329
5330 /* Invite target to request symbol lookups. */
5331
5332 putpkt ("qSymbol::");
5333 getpkt (&reply, 0);
5334 m_features.packet_ok (reply, PACKET_qSymbol);
5335
5336 while (startswith (reply.data (), "qSymbol:"))
5337 {
5338 struct bound_minimal_symbol sym;
5339
5340 tmp = &reply[8];
5341 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5342 strlen (tmp) / 2);
5343 msg[end] = '\0';
5344 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5345 if (sym.minsym == NULL)
5346 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5347 &reply[8]);
5348 else
5349 {
5350 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5351 CORE_ADDR sym_addr = sym.value_address ();
5352
5353 /* If this is a function address, return the start of code
5354 instead of any data function descriptor. */
5355 sym_addr = gdbarch_convert_from_func_ptr_addr
5356 (target_gdbarch (), sym_addr, current_inferior ()->top_target ());
5357
5358 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5359 phex_nz (sym_addr, addr_size), &reply[8]);
5360 }
5361
5362 putpkt (msg.data ());
5363 getpkt (&reply, 0);
5364 }
5365 }
5366
5367 static struct serial *
5368 remote_serial_open (const char *name)
5369 {
5370 static int udp_warning = 0;
5371
5372 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5373 of in ser-tcp.c, because it is the remote protocol assuming that the
5374 serial connection is reliable and not the serial connection promising
5375 to be. */
5376 if (!udp_warning && startswith (name, "udp:"))
5377 {
5378 warning (_("The remote protocol may be unreliable over UDP.\n"
5379 "Some events may be lost, rendering further debugging "
5380 "impossible."));
5381 udp_warning = 1;
5382 }
5383
5384 return serial_open (name);
5385 }
5386
5387 /* Inform the target of our permission settings. The permission flags
5388 work without this, but if the target knows the settings, it can do
5389 a couple things. First, it can add its own check, to catch cases
5390 that somehow manage to get by the permissions checks in target
5391 methods. Second, if the target is wired to disallow particular
5392 settings (for instance, a system in the field that is not set up to
5393 be able to stop at a breakpoint), it can object to any unavailable
5394 permissions. */
5395
5396 void
5397 remote_target::set_permissions ()
5398 {
5399 struct remote_state *rs = get_remote_state ();
5400
5401 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5402 "WriteReg:%x;WriteMem:%x;"
5403 "InsertBreak:%x;InsertTrace:%x;"
5404 "InsertFastTrace:%x;Stop:%x",
5405 may_write_registers, may_write_memory,
5406 may_insert_breakpoints, may_insert_tracepoints,
5407 may_insert_fast_tracepoints, may_stop);
5408 putpkt (rs->buf);
5409 getpkt (&rs->buf, 0);
5410
5411 /* If the target didn't like the packet, warn the user. Do not try
5412 to undo the user's settings, that would just be maddening. */
5413 if (strcmp (rs->buf.data (), "OK") != 0)
5414 warning (_("Remote refused setting permissions with: %s"),
5415 rs->buf.data ());
5416 }
5417
5418 /* This type describes each known response to the qSupported
5419 packet. */
5420 struct protocol_feature
5421 {
5422 /* The name of this protocol feature. */
5423 const char *name;
5424
5425 /* The default for this protocol feature. */
5426 enum packet_support default_support;
5427
5428 /* The function to call when this feature is reported, or after
5429 qSupported processing if the feature is not supported.
5430 The first argument points to this structure. The second
5431 argument indicates whether the packet requested support be
5432 enabled, disabled, or probed (or the default, if this function
5433 is being called at the end of processing and this feature was
5434 not reported). The third argument may be NULL; if not NULL, it
5435 is a NUL-terminated string taken from the packet following
5436 this feature's name and an equals sign. */
5437 void (*func) (remote_target *remote, const struct protocol_feature *,
5438 enum packet_support, const char *);
5439
5440 /* The corresponding packet for this feature. Only used if
5441 FUNC is remote_supported_packet. */
5442 int packet;
5443 };
5444
5445 static void
5446 remote_supported_packet (remote_target *remote,
5447 const struct protocol_feature *feature,
5448 enum packet_support support,
5449 const char *argument)
5450 {
5451 if (argument)
5452 {
5453 warning (_("Remote qSupported response supplied an unexpected value for"
5454 " \"%s\"."), feature->name);
5455 return;
5456 }
5457
5458 remote->m_features.m_protocol_packets[feature->packet].support = support;
5459 }
5460
5461 void
5462 remote_target::remote_packet_size (const protocol_feature *feature,
5463 enum packet_support support, const char *value)
5464 {
5465 struct remote_state *rs = get_remote_state ();
5466
5467 int packet_size;
5468 char *value_end;
5469
5470 if (support != PACKET_ENABLE)
5471 return;
5472
5473 if (value == NULL || *value == '\0')
5474 {
5475 warning (_("Remote target reported \"%s\" without a size."),
5476 feature->name);
5477 return;
5478 }
5479
5480 errno = 0;
5481 packet_size = strtol (value, &value_end, 16);
5482 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5483 {
5484 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5485 feature->name, value);
5486 return;
5487 }
5488
5489 /* Record the new maximum packet size. */
5490 rs->explicit_packet_size = packet_size;
5491 }
5492
5493 static void
5494 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5495 enum packet_support support, const char *value)
5496 {
5497 remote->remote_packet_size (feature, support, value);
5498 }
5499
5500 static const struct protocol_feature remote_protocol_features[] = {
5501 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5502 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5503 PACKET_qXfer_auxv },
5504 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5505 PACKET_qXfer_exec_file },
5506 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5507 PACKET_qXfer_features },
5508 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5509 PACKET_qXfer_libraries },
5510 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5511 PACKET_qXfer_libraries_svr4 },
5512 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5513 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5514 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5515 PACKET_qXfer_memory_map },
5516 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5517 PACKET_qXfer_osdata },
5518 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5519 PACKET_qXfer_threads },
5520 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5521 PACKET_qXfer_traceframe_info },
5522 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5523 PACKET_QPassSignals },
5524 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5525 PACKET_QCatchSyscalls },
5526 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5527 PACKET_QProgramSignals },
5528 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5529 PACKET_QSetWorkingDir },
5530 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5531 PACKET_QStartupWithShell },
5532 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5533 PACKET_QEnvironmentHexEncoded },
5534 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5535 PACKET_QEnvironmentReset },
5536 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5537 PACKET_QEnvironmentUnset },
5538 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5539 PACKET_QStartNoAckMode },
5540 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5541 PACKET_multiprocess_feature },
5542 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5543 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5544 PACKET_qXfer_siginfo_read },
5545 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5546 PACKET_qXfer_siginfo_write },
5547 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5548 PACKET_ConditionalTracepoints },
5549 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5550 PACKET_ConditionalBreakpoints },
5551 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5552 PACKET_BreakpointCommands },
5553 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5554 PACKET_FastTracepoints },
5555 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5556 PACKET_StaticTracepoints },
5557 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5558 PACKET_InstallInTrace},
5559 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5560 PACKET_DisconnectedTracing_feature },
5561 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5562 PACKET_bc },
5563 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5564 PACKET_bs },
5565 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5566 PACKET_TracepointSource },
5567 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5568 PACKET_QAllow },
5569 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5570 PACKET_EnableDisableTracepoints_feature },
5571 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5572 PACKET_qXfer_fdpic },
5573 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5574 PACKET_qXfer_uib },
5575 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5576 PACKET_QDisableRandomization },
5577 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5578 { "QTBuffer:size", PACKET_DISABLE,
5579 remote_supported_packet, PACKET_QTBuffer_size},
5580 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5581 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5582 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5583 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5584 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5585 PACKET_qXfer_btrace },
5586 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5587 PACKET_qXfer_btrace_conf },
5588 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5589 PACKET_Qbtrace_conf_bts_size },
5590 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5591 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5592 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5593 PACKET_fork_event_feature },
5594 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5595 PACKET_vfork_event_feature },
5596 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5597 PACKET_exec_event_feature },
5598 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5599 PACKET_Qbtrace_conf_pt_size },
5600 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5601 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5602 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5603 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5604 PACKET_memory_tagging_feature },
5605 };
5606
5607 static char *remote_support_xml;
5608
5609 /* Register string appended to "xmlRegisters=" in qSupported query. */
5610
5611 void
5612 register_remote_support_xml (const char *xml)
5613 {
5614 #if defined(HAVE_LIBEXPAT)
5615 if (remote_support_xml == NULL)
5616 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5617 else
5618 {
5619 char *copy = xstrdup (remote_support_xml + 13);
5620 char *saveptr;
5621 char *p = strtok_r (copy, ",", &saveptr);
5622
5623 do
5624 {
5625 if (strcmp (p, xml) == 0)
5626 {
5627 /* already there */
5628 xfree (copy);
5629 return;
5630 }
5631 }
5632 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5633 xfree (copy);
5634
5635 remote_support_xml = reconcat (remote_support_xml,
5636 remote_support_xml, ",", xml,
5637 (char *) NULL);
5638 }
5639 #endif
5640 }
5641
5642 static void
5643 remote_query_supported_append (std::string *msg, const char *append)
5644 {
5645 if (!msg->empty ())
5646 msg->append (";");
5647 msg->append (append);
5648 }
5649
5650 void
5651 remote_target::remote_query_supported ()
5652 {
5653 struct remote_state *rs = get_remote_state ();
5654 char *next;
5655 int i;
5656 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5657
5658 /* The packet support flags are handled differently for this packet
5659 than for most others. We treat an error, a disabled packet, and
5660 an empty response identically: any features which must be reported
5661 to be used will be automatically disabled. An empty buffer
5662 accomplishes this, since that is also the representation for a list
5663 containing no features. */
5664
5665 rs->buf[0] = 0;
5666 if (m_features.packet_support (PACKET_qSupported) != PACKET_DISABLE)
5667 {
5668 std::string q;
5669
5670 if (m_features.packet_set_cmd_state (PACKET_multiprocess_feature)
5671 != AUTO_BOOLEAN_FALSE)
5672 remote_query_supported_append (&q, "multiprocess+");
5673
5674 if (m_features.packet_set_cmd_state (PACKET_swbreak_feature)
5675 != AUTO_BOOLEAN_FALSE)
5676 remote_query_supported_append (&q, "swbreak+");
5677
5678 if (m_features.packet_set_cmd_state (PACKET_hwbreak_feature)
5679 != AUTO_BOOLEAN_FALSE)
5680 remote_query_supported_append (&q, "hwbreak+");
5681
5682 remote_query_supported_append (&q, "qRelocInsn+");
5683
5684 if (m_features.packet_set_cmd_state (PACKET_fork_event_feature)
5685 != AUTO_BOOLEAN_FALSE)
5686 remote_query_supported_append (&q, "fork-events+");
5687
5688 if (m_features.packet_set_cmd_state (PACKET_vfork_event_feature)
5689 != AUTO_BOOLEAN_FALSE)
5690 remote_query_supported_append (&q, "vfork-events+");
5691
5692 if (m_features.packet_set_cmd_state (PACKET_exec_event_feature)
5693 != AUTO_BOOLEAN_FALSE)
5694 remote_query_supported_append (&q, "exec-events+");
5695
5696 if (m_features.packet_set_cmd_state (PACKET_vContSupported)
5697 != AUTO_BOOLEAN_FALSE)
5698 remote_query_supported_append (&q, "vContSupported+");
5699
5700 if (m_features.packet_set_cmd_state (PACKET_QThreadEvents)
5701 != AUTO_BOOLEAN_FALSE)
5702 remote_query_supported_append (&q, "QThreadEvents+");
5703
5704 if (m_features.packet_set_cmd_state (PACKET_no_resumed)
5705 != AUTO_BOOLEAN_FALSE)
5706 remote_query_supported_append (&q, "no-resumed+");
5707
5708 if (m_features.packet_set_cmd_state (PACKET_memory_tagging_feature)
5709 != AUTO_BOOLEAN_FALSE)
5710 remote_query_supported_append (&q, "memory-tagging+");
5711
5712 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5713 the qSupported:xmlRegisters=i386 handling. */
5714 if (remote_support_xml != NULL
5715 && (m_features.packet_support (PACKET_qXfer_features)
5716 != PACKET_DISABLE))
5717 remote_query_supported_append (&q, remote_support_xml);
5718
5719 q = "qSupported:" + q;
5720 putpkt (q.c_str ());
5721
5722 getpkt (&rs->buf, 0);
5723
5724 /* If an error occurred, warn, but do not return - just reset the
5725 buffer to empty and go on to disable features. */
5726 if (m_features.packet_ok (rs->buf, PACKET_qSupported) == PACKET_ERROR)
5727 {
5728 warning (_("Remote failure reply: %s"), rs->buf.data ());
5729 rs->buf[0] = 0;
5730 }
5731 }
5732
5733 memset (seen, 0, sizeof (seen));
5734
5735 next = rs->buf.data ();
5736 while (*next)
5737 {
5738 enum packet_support is_supported;
5739 char *p, *end, *name_end, *value;
5740
5741 /* First separate out this item from the rest of the packet. If
5742 there's another item after this, we overwrite the separator
5743 (terminated strings are much easier to work with). */
5744 p = next;
5745 end = strchr (p, ';');
5746 if (end == NULL)
5747 {
5748 end = p + strlen (p);
5749 next = end;
5750 }
5751 else
5752 {
5753 *end = '\0';
5754 next = end + 1;
5755
5756 if (end == p)
5757 {
5758 warning (_("empty item in \"qSupported\" response"));
5759 continue;
5760 }
5761 }
5762
5763 name_end = strchr (p, '=');
5764 if (name_end)
5765 {
5766 /* This is a name=value entry. */
5767 is_supported = PACKET_ENABLE;
5768 value = name_end + 1;
5769 *name_end = '\0';
5770 }
5771 else
5772 {
5773 value = NULL;
5774 switch (end[-1])
5775 {
5776 case '+':
5777 is_supported = PACKET_ENABLE;
5778 break;
5779
5780 case '-':
5781 is_supported = PACKET_DISABLE;
5782 break;
5783
5784 case '?':
5785 is_supported = PACKET_SUPPORT_UNKNOWN;
5786 break;
5787
5788 default:
5789 warning (_("unrecognized item \"%s\" "
5790 "in \"qSupported\" response"), p);
5791 continue;
5792 }
5793 end[-1] = '\0';
5794 }
5795
5796 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5797 if (strcmp (remote_protocol_features[i].name, p) == 0)
5798 {
5799 const struct protocol_feature *feature;
5800
5801 seen[i] = 1;
5802 feature = &remote_protocol_features[i];
5803 feature->func (this, feature, is_supported, value);
5804 break;
5805 }
5806 }
5807
5808 /* If we increased the packet size, make sure to increase the global
5809 buffer size also. We delay this until after parsing the entire
5810 qSupported packet, because this is the same buffer we were
5811 parsing. */
5812 if (rs->buf.size () < rs->explicit_packet_size)
5813 rs->buf.resize (rs->explicit_packet_size);
5814
5815 /* Handle the defaults for unmentioned features. */
5816 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5817 if (!seen[i])
5818 {
5819 const struct protocol_feature *feature;
5820
5821 feature = &remote_protocol_features[i];
5822 feature->func (this, feature, feature->default_support, NULL);
5823 }
5824 }
5825
5826 /* Serial QUIT handler for the remote serial descriptor.
5827
5828 Defers handling a Ctrl-C until we're done with the current
5829 command/response packet sequence, unless:
5830
5831 - We're setting up the connection. Don't send a remote interrupt
5832 request, as we're not fully synced yet. Quit immediately
5833 instead.
5834
5835 - The target has been resumed in the foreground
5836 (target_terminal::is_ours is false) with a synchronous resume
5837 packet, and we're blocked waiting for the stop reply, thus a
5838 Ctrl-C should be immediately sent to the target.
5839
5840 - We get a second Ctrl-C while still within the same serial read or
5841 write. In that case the serial is seemingly wedged --- offer to
5842 quit/disconnect.
5843
5844 - We see a second Ctrl-C without target response, after having
5845 previously interrupted the target. In that case the target/stub
5846 is probably wedged --- offer to quit/disconnect.
5847 */
5848
5849 void
5850 remote_target::remote_serial_quit_handler ()
5851 {
5852 struct remote_state *rs = get_remote_state ();
5853
5854 if (check_quit_flag ())
5855 {
5856 /* If we're starting up, we're not fully synced yet. Quit
5857 immediately. */
5858 if (rs->starting_up)
5859 quit ();
5860 else if (rs->got_ctrlc_during_io)
5861 {
5862 if (query (_("The target is not responding to GDB commands.\n"
5863 "Stop debugging it? ")))
5864 remote_unpush_and_throw (this);
5865 }
5866 /* If ^C has already been sent once, offer to disconnect. */
5867 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5868 interrupt_query ();
5869 /* All-stop protocol, and blocked waiting for stop reply. Send
5870 an interrupt request. */
5871 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5872 target_interrupt ();
5873 else
5874 rs->got_ctrlc_during_io = 1;
5875 }
5876 }
5877
5878 /* The remote_target that is current while the quit handler is
5879 overridden with remote_serial_quit_handler. */
5880 static remote_target *curr_quit_handler_target;
5881
5882 static void
5883 remote_serial_quit_handler ()
5884 {
5885 curr_quit_handler_target->remote_serial_quit_handler ();
5886 }
5887
5888 /* Remove the remote target from the target stack of each inferior
5889 that is using it. Upper targets depend on it so remove them
5890 first. */
5891
5892 static void
5893 remote_unpush_target (remote_target *target)
5894 {
5895 /* We have to unpush the target from all inferiors, even those that
5896 aren't running. */
5897 scoped_restore_current_inferior restore_current_inferior;
5898
5899 for (inferior *inf : all_inferiors (target))
5900 {
5901 switch_to_inferior_no_thread (inf);
5902 inf->pop_all_targets_at_and_above (process_stratum);
5903 generic_mourn_inferior ();
5904 }
5905
5906 /* Don't rely on target_close doing this when the target is popped
5907 from the last remote inferior above, because something may be
5908 holding a reference to the target higher up on the stack, meaning
5909 target_close won't be called yet. We lost the connection to the
5910 target, so clear these now, otherwise we may later throw
5911 TARGET_CLOSE_ERROR while trying to tell the remote target to
5912 close the file. */
5913 fileio_handles_invalidate_target (target);
5914 }
5915
5916 static void
5917 remote_unpush_and_throw (remote_target *target)
5918 {
5919 remote_unpush_target (target);
5920 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5921 }
5922
5923 void
5924 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5925 {
5926 remote_target *curr_remote = get_current_remote_target ();
5927
5928 if (name == 0)
5929 error (_("To open a remote debug connection, you need to specify what\n"
5930 "serial device is attached to the remote system\n"
5931 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5932
5933 /* If we're connected to a running target, target_preopen will kill it.
5934 Ask this question first, before target_preopen has a chance to kill
5935 anything. */
5936 if (curr_remote != NULL && !target_has_execution ())
5937 {
5938 if (from_tty
5939 && !query (_("Already connected to a remote target. Disconnect? ")))
5940 error (_("Still connected."));
5941 }
5942
5943 /* Here the possibly existing remote target gets unpushed. */
5944 target_preopen (from_tty);
5945
5946 remote_fileio_reset ();
5947 reopen_exec_file ();
5948 reread_symbols (from_tty);
5949
5950 remote_target *remote
5951 = (extended_p ? new extended_remote_target () : new remote_target ());
5952 target_ops_up target_holder (remote);
5953
5954 remote_state *rs = remote->get_remote_state ();
5955
5956 /* See FIXME above. */
5957 if (!target_async_permitted)
5958 rs->wait_forever_enabled_p = 1;
5959
5960 rs->remote_desc = remote_serial_open (name);
5961 if (!rs->remote_desc)
5962 perror_with_name (name);
5963
5964 if (baud_rate != -1)
5965 {
5966 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5967 {
5968 /* The requested speed could not be set. Error out to
5969 top level after closing remote_desc. Take care to
5970 set remote_desc to NULL to avoid closing remote_desc
5971 more than once. */
5972 serial_close (rs->remote_desc);
5973 rs->remote_desc = NULL;
5974 perror_with_name (name);
5975 }
5976 }
5977
5978 serial_setparity (rs->remote_desc, serial_parity);
5979 serial_raw (rs->remote_desc);
5980
5981 /* If there is something sitting in the buffer we might take it as a
5982 response to a command, which would be bad. */
5983 serial_flush_input (rs->remote_desc);
5984
5985 if (from_tty)
5986 {
5987 gdb_puts ("Remote debugging using ");
5988 gdb_puts (name);
5989 gdb_puts ("\n");
5990 }
5991
5992 /* Switch to using the remote target now. */
5993 current_inferior ()->push_target (std::move (target_holder));
5994
5995 /* Register extra event sources in the event loop. */
5996 rs->remote_async_inferior_event_token
5997 = create_async_event_handler (remote_async_inferior_event_handler, nullptr,
5998 "remote");
5999 rs->notif_state = remote_notif_state_allocate (remote);
6000
6001 /* Reset the target state; these things will be queried either by
6002 remote_query_supported or as they are needed. */
6003 remote->m_features.reset_all_packet_configs_support ();
6004 rs->explicit_packet_size = 0;
6005 rs->noack_mode = 0;
6006 rs->extended = extended_p;
6007 rs->waiting_for_stop_reply = 0;
6008 rs->ctrlc_pending_p = 0;
6009 rs->got_ctrlc_during_io = 0;
6010
6011 rs->general_thread = not_sent_ptid;
6012 rs->continue_thread = not_sent_ptid;
6013 rs->remote_traceframe_number = -1;
6014
6015 rs->last_resume_exec_dir = EXEC_FORWARD;
6016
6017 /* Probe for ability to use "ThreadInfo" query, as required. */
6018 rs->use_threadinfo_query = 1;
6019 rs->use_threadextra_query = 1;
6020
6021 rs->readahead_cache.invalidate ();
6022
6023 if (target_async_permitted)
6024 {
6025 /* FIXME: cagney/1999-09-23: During the initial connection it is
6026 assumed that the target is already ready and able to respond to
6027 requests. Unfortunately remote_start_remote() eventually calls
6028 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
6029 around this. Eventually a mechanism that allows
6030 wait_for_inferior() to expect/get timeouts will be
6031 implemented. */
6032 rs->wait_forever_enabled_p = 0;
6033 }
6034
6035 /* First delete any symbols previously loaded from shared libraries. */
6036 no_shared_libraries (NULL, 0);
6037
6038 /* Start the remote connection. If error() or QUIT, discard this
6039 target (we'd otherwise be in an inconsistent state) and then
6040 propogate the error on up the exception chain. This ensures that
6041 the caller doesn't stumble along blindly assuming that the
6042 function succeeded. The CLI doesn't have this problem but other
6043 UI's, such as MI do.
6044
6045 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
6046 this function should return an error indication letting the
6047 caller restore the previous state. Unfortunately the command
6048 ``target remote'' is directly wired to this function making that
6049 impossible. On a positive note, the CLI side of this problem has
6050 been fixed - the function set_cmd_context() makes it possible for
6051 all the ``target ....'' commands to share a common callback
6052 function. See cli-dump.c. */
6053 {
6054
6055 try
6056 {
6057 remote->start_remote (from_tty, extended_p);
6058 }
6059 catch (const gdb_exception &ex)
6060 {
6061 /* Pop the partially set up target - unless something else did
6062 already before throwing the exception. */
6063 if (ex.error != TARGET_CLOSE_ERROR)
6064 remote_unpush_target (remote);
6065 throw;
6066 }
6067 }
6068
6069 remote_btrace_reset (rs);
6070
6071 if (target_async_permitted)
6072 rs->wait_forever_enabled_p = 1;
6073 }
6074
6075 /* Determine if WS represents a fork status. */
6076
6077 static bool
6078 is_fork_status (target_waitkind kind)
6079 {
6080 return (kind == TARGET_WAITKIND_FORKED
6081 || kind == TARGET_WAITKIND_VFORKED);
6082 }
6083
6084 /* Return THREAD's pending status if it is a pending fork parent, else
6085 return nullptr. */
6086
6087 static const target_waitstatus *
6088 thread_pending_fork_status (struct thread_info *thread)
6089 {
6090 const target_waitstatus &ws
6091 = (thread->has_pending_waitstatus ()
6092 ? thread->pending_waitstatus ()
6093 : thread->pending_follow);
6094
6095 if (!is_fork_status (ws.kind ()))
6096 return nullptr;
6097
6098 return &ws;
6099 }
6100
6101 /* Detach the specified process. */
6102
6103 void
6104 remote_target::remote_detach_pid (int pid)
6105 {
6106 struct remote_state *rs = get_remote_state ();
6107
6108 /* This should not be necessary, but the handling for D;PID in
6109 GDBserver versions prior to 8.2 incorrectly assumes that the
6110 selected process points to the same process we're detaching,
6111 leading to misbehavior (and possibly GDBserver crashing) when it
6112 does not. Since it's easy and cheap, work around it by forcing
6113 GDBserver to select GDB's current process. */
6114 set_general_process ();
6115
6116 if (m_features.remote_multi_process_p ())
6117 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
6118 else
6119 strcpy (rs->buf.data (), "D");
6120
6121 putpkt (rs->buf);
6122 getpkt (&rs->buf, 0);
6123
6124 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
6125 ;
6126 else if (rs->buf[0] == '\0')
6127 error (_("Remote doesn't know how to detach"));
6128 else
6129 error (_("Can't detach process."));
6130 }
6131
6132 /* This detaches a program to which we previously attached, using
6133 inferior_ptid to identify the process. After this is done, GDB
6134 can be used to debug some other program. We better not have left
6135 any breakpoints in the target program or it'll die when it hits
6136 one. */
6137
6138 void
6139 remote_target::remote_detach_1 (inferior *inf, int from_tty)
6140 {
6141 int pid = inferior_ptid.pid ();
6142 struct remote_state *rs = get_remote_state ();
6143 int is_fork_parent;
6144
6145 if (!target_has_execution ())
6146 error (_("No process to detach from."));
6147
6148 target_announce_detach (from_tty);
6149
6150 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
6151 {
6152 /* If we're in breakpoints-always-inserted mode, or the inferior
6153 is running, we have to remove breakpoints before detaching.
6154 We don't do this in common code instead because not all
6155 targets support removing breakpoints while the target is
6156 running. The remote target / gdbserver does, though. */
6157 remove_breakpoints_inf (current_inferior ());
6158 }
6159
6160 /* Tell the remote target to detach. */
6161 remote_detach_pid (pid);
6162
6163 /* Exit only if this is the only active inferior. */
6164 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
6165 gdb_puts (_("Ending remote debugging.\n"));
6166
6167 /* See if any thread of the inferior we are detaching has a pending fork
6168 status. In that case, we must detach from the child resulting from
6169 that fork. */
6170 for (thread_info *thread : inf->non_exited_threads ())
6171 {
6172 const target_waitstatus *ws = thread_pending_fork_status (thread);
6173
6174 if (ws == nullptr)
6175 continue;
6176
6177 remote_detach_pid (ws->child_ptid ().pid ());
6178 }
6179
6180 /* Check also for any pending fork events in the stop reply queue. */
6181 remote_notif_get_pending_events (&notif_client_stop);
6182 for (stop_reply_up &reply : rs->stop_reply_queue)
6183 {
6184 if (reply->ptid.pid () != pid)
6185 continue;
6186
6187 if (!is_fork_status (reply->ws.kind ()))
6188 continue;
6189
6190 remote_detach_pid (reply->ws.child_ptid ().pid ());
6191 }
6192
6193 thread_info *tp = this->find_thread (inferior_ptid);
6194
6195 /* Check to see if we are detaching a fork parent. Note that if we
6196 are detaching a fork child, tp == NULL. */
6197 is_fork_parent = (tp != NULL
6198 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
6199
6200 /* If doing detach-on-fork, we don't mourn, because that will delete
6201 breakpoints that should be available for the followed inferior. */
6202 if (!is_fork_parent)
6203 {
6204 /* Save the pid as a string before mourning, since that will
6205 unpush the remote target, and we need the string after. */
6206 std::string infpid = target_pid_to_str (ptid_t (pid));
6207
6208 target_mourn_inferior (inferior_ptid);
6209 if (print_inferior_events)
6210 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6211 inf->num, infpid.c_str ());
6212 }
6213 else
6214 {
6215 switch_to_no_thread ();
6216 detach_inferior (current_inferior ());
6217 }
6218 }
6219
6220 void
6221 remote_target::detach (inferior *inf, int from_tty)
6222 {
6223 remote_detach_1 (inf, from_tty);
6224 }
6225
6226 void
6227 extended_remote_target::detach (inferior *inf, int from_tty)
6228 {
6229 remote_detach_1 (inf, from_tty);
6230 }
6231
6232 /* Target follow-fork function for remote targets. On entry, and
6233 at return, the current inferior is the fork parent.
6234
6235 Note that although this is currently only used for extended-remote,
6236 it is named remote_follow_fork in anticipation of using it for the
6237 remote target as well. */
6238
6239 void
6240 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6241 target_waitkind fork_kind, bool follow_child,
6242 bool detach_fork)
6243 {
6244 process_stratum_target::follow_fork (child_inf, child_ptid,
6245 fork_kind, follow_child, detach_fork);
6246
6247 if ((fork_kind == TARGET_WAITKIND_FORKED
6248 && m_features.remote_fork_event_p ())
6249 || (fork_kind == TARGET_WAITKIND_VFORKED
6250 && m_features.remote_vfork_event_p ()))
6251 {
6252 /* When following the parent and detaching the child, we detach
6253 the child here. For the case of following the child and
6254 detaching the parent, the detach is done in the target-
6255 independent follow fork code in infrun.c. We can't use
6256 target_detach when detaching an unfollowed child because
6257 the client side doesn't know anything about the child. */
6258 if (detach_fork && !follow_child)
6259 {
6260 /* Detach the fork child. */
6261 remote_detach_pid (child_ptid.pid ());
6262 }
6263 }
6264 }
6265
6266 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6267 in the program space of the new inferior. */
6268
6269 void
6270 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6271 const char *execd_pathname)
6272 {
6273 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6274
6275 /* We know that this is a target file name, so if it has the "target:"
6276 prefix we strip it off before saving it in the program space. */
6277 if (is_target_filename (execd_pathname))
6278 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6279
6280 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6281 }
6282
6283 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6284
6285 void
6286 remote_target::disconnect (const char *args, int from_tty)
6287 {
6288 if (args)
6289 error (_("Argument given to \"disconnect\" when remotely debugging."));
6290
6291 /* Make sure we unpush even the extended remote targets. Calling
6292 target_mourn_inferior won't unpush, and
6293 remote_target::mourn_inferior won't unpush if there is more than
6294 one inferior left. */
6295 remote_unpush_target (this);
6296
6297 if (from_tty)
6298 gdb_puts ("Ending remote debugging.\n");
6299 }
6300
6301 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6302 be chatty about it. */
6303
6304 void
6305 extended_remote_target::attach (const char *args, int from_tty)
6306 {
6307 struct remote_state *rs = get_remote_state ();
6308 int pid;
6309 char *wait_status = NULL;
6310
6311 pid = parse_pid_to_attach (args);
6312
6313 /* Remote PID can be freely equal to getpid, do not check it here the same
6314 way as in other targets. */
6315
6316 if (m_features.packet_support (PACKET_vAttach) == PACKET_DISABLE)
6317 error (_("This target does not support attaching to a process"));
6318
6319 target_announce_attach (from_tty, pid);
6320
6321 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6322 putpkt (rs->buf);
6323 getpkt (&rs->buf, 0);
6324
6325 switch (m_features.packet_ok (rs->buf, PACKET_vAttach))
6326 {
6327 case PACKET_OK:
6328 if (!target_is_non_stop_p ())
6329 {
6330 /* Save the reply for later. */
6331 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6332 strcpy (wait_status, rs->buf.data ());
6333 }
6334 else if (strcmp (rs->buf.data (), "OK") != 0)
6335 error (_("Attaching to %s failed with: %s"),
6336 target_pid_to_str (ptid_t (pid)).c_str (),
6337 rs->buf.data ());
6338 break;
6339 case PACKET_UNKNOWN:
6340 error (_("This target does not support attaching to a process"));
6341 default:
6342 error (_("Attaching to %s failed"),
6343 target_pid_to_str (ptid_t (pid)).c_str ());
6344 }
6345
6346 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6347
6348 inferior_ptid = ptid_t (pid);
6349
6350 if (target_is_non_stop_p ())
6351 {
6352 /* Get list of threads. */
6353 update_thread_list ();
6354
6355 thread_info *thread = first_thread_of_inferior (current_inferior ());
6356 if (thread != nullptr)
6357 switch_to_thread (thread);
6358
6359 /* Invalidate our notion of the remote current thread. */
6360 record_currthread (rs, minus_one_ptid);
6361 }
6362 else
6363 {
6364 /* Now, if we have thread information, update the main thread's
6365 ptid. */
6366 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6367
6368 /* Add the main thread to the thread list. We add the thread
6369 silently in this case (the final true parameter). */
6370 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
6371
6372 switch_to_thread (thr);
6373 }
6374
6375 /* Next, if the target can specify a description, read it. We do
6376 this before anything involving memory or registers. */
6377 target_find_description ();
6378
6379 if (!target_is_non_stop_p ())
6380 {
6381 /* Use the previously fetched status. */
6382 gdb_assert (wait_status != NULL);
6383
6384 struct notif_event *reply
6385 = remote_notif_parse (this, &notif_client_stop, wait_status);
6386
6387 push_stop_reply ((struct stop_reply *) reply);
6388 }
6389 else
6390 {
6391 gdb_assert (wait_status == NULL);
6392
6393 gdb_assert (target_can_async_p ());
6394 }
6395 }
6396
6397 /* Implementation of the to_post_attach method. */
6398
6399 void
6400 extended_remote_target::post_attach (int pid)
6401 {
6402 /* Get text, data & bss offsets. */
6403 get_offsets ();
6404
6405 /* In certain cases GDB might not have had the chance to start
6406 symbol lookup up until now. This could happen if the debugged
6407 binary is not using shared libraries, the vsyscall page is not
6408 present (on Linux) and the binary itself hadn't changed since the
6409 debugging process was started. */
6410 if (current_program_space->symfile_object_file != NULL)
6411 remote_check_symbols();
6412 }
6413
6414 \f
6415 /* Check for the availability of vCont. This function should also check
6416 the response. */
6417
6418 void
6419 remote_target::remote_vcont_probe ()
6420 {
6421 remote_state *rs = get_remote_state ();
6422 char *buf;
6423
6424 strcpy (rs->buf.data (), "vCont?");
6425 putpkt (rs->buf);
6426 getpkt (&rs->buf, 0);
6427 buf = rs->buf.data ();
6428
6429 /* Make sure that the features we assume are supported. */
6430 if (startswith (buf, "vCont"))
6431 {
6432 char *p = &buf[5];
6433 int support_c, support_C;
6434
6435 rs->supports_vCont.s = 0;
6436 rs->supports_vCont.S = 0;
6437 support_c = 0;
6438 support_C = 0;
6439 rs->supports_vCont.t = 0;
6440 rs->supports_vCont.r = 0;
6441 while (p && *p == ';')
6442 {
6443 p++;
6444 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6445 rs->supports_vCont.s = 1;
6446 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6447 rs->supports_vCont.S = 1;
6448 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6449 support_c = 1;
6450 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6451 support_C = 1;
6452 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6453 rs->supports_vCont.t = 1;
6454 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6455 rs->supports_vCont.r = 1;
6456
6457 p = strchr (p, ';');
6458 }
6459
6460 /* If c, and C are not all supported, we can't use vCont. Clearing
6461 BUF will make packet_ok disable the packet. */
6462 if (!support_c || !support_C)
6463 buf[0] = 0;
6464 }
6465
6466 m_features.packet_ok (rs->buf, PACKET_vCont);
6467 }
6468
6469 /* Helper function for building "vCont" resumptions. Write a
6470 resumption to P. ENDP points to one-passed-the-end of the buffer
6471 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6472 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6473 resumed thread should be single-stepped and/or signalled. If PTID
6474 equals minus_one_ptid, then all threads are resumed; if PTID
6475 represents a process, then all threads of the process are
6476 resumed. */
6477
6478 char *
6479 remote_target::append_resumption (char *p, char *endp,
6480 ptid_t ptid, int step, gdb_signal siggnal)
6481 {
6482 struct remote_state *rs = get_remote_state ();
6483
6484 if (step && siggnal != GDB_SIGNAL_0)
6485 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6486 else if (step
6487 /* GDB is willing to range step. */
6488 && use_range_stepping
6489 /* Target supports range stepping. */
6490 && rs->supports_vCont.r
6491 /* We don't currently support range stepping multiple
6492 threads with a wildcard (though the protocol allows it,
6493 so stubs shouldn't make an active effort to forbid
6494 it). */
6495 && !(m_features.remote_multi_process_p () && ptid.is_pid ()))
6496 {
6497 struct thread_info *tp;
6498
6499 if (ptid == minus_one_ptid)
6500 {
6501 /* If we don't know about the target thread's tid, then
6502 we're resuming magic_null_ptid (see caller). */
6503 tp = this->find_thread (magic_null_ptid);
6504 }
6505 else
6506 tp = this->find_thread (ptid);
6507 gdb_assert (tp != NULL);
6508
6509 if (tp->control.may_range_step)
6510 {
6511 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6512
6513 p += xsnprintf (p, endp - p, ";r%s,%s",
6514 phex_nz (tp->control.step_range_start,
6515 addr_size),
6516 phex_nz (tp->control.step_range_end,
6517 addr_size));
6518 }
6519 else
6520 p += xsnprintf (p, endp - p, ";s");
6521 }
6522 else if (step)
6523 p += xsnprintf (p, endp - p, ";s");
6524 else if (siggnal != GDB_SIGNAL_0)
6525 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6526 else
6527 p += xsnprintf (p, endp - p, ";c");
6528
6529 if (m_features.remote_multi_process_p () && ptid.is_pid ())
6530 {
6531 ptid_t nptid;
6532
6533 /* All (-1) threads of process. */
6534 nptid = ptid_t (ptid.pid (), -1);
6535
6536 p += xsnprintf (p, endp - p, ":");
6537 p = write_ptid (p, endp, nptid);
6538 }
6539 else if (ptid != minus_one_ptid)
6540 {
6541 p += xsnprintf (p, endp - p, ":");
6542 p = write_ptid (p, endp, ptid);
6543 }
6544
6545 return p;
6546 }
6547
6548 /* Clear the thread's private info on resume. */
6549
6550 static void
6551 resume_clear_thread_private_info (struct thread_info *thread)
6552 {
6553 if (thread->priv != NULL)
6554 {
6555 remote_thread_info *priv = get_remote_thread_info (thread);
6556
6557 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6558 priv->watch_data_address = 0;
6559 }
6560 }
6561
6562 /* Append a vCont continue-with-signal action for threads that have a
6563 non-zero stop signal. */
6564
6565 char *
6566 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6567 ptid_t ptid)
6568 {
6569 for (thread_info *thread : all_non_exited_threads (this, ptid))
6570 if (inferior_ptid != thread->ptid
6571 && thread->stop_signal () != GDB_SIGNAL_0)
6572 {
6573 p = append_resumption (p, endp, thread->ptid,
6574 0, thread->stop_signal ());
6575 thread->set_stop_signal (GDB_SIGNAL_0);
6576 resume_clear_thread_private_info (thread);
6577 }
6578
6579 return p;
6580 }
6581
6582 /* Set the target running, using the packets that use Hc
6583 (c/s/C/S). */
6584
6585 void
6586 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6587 gdb_signal siggnal)
6588 {
6589 struct remote_state *rs = get_remote_state ();
6590 char *buf;
6591
6592 rs->last_sent_signal = siggnal;
6593 rs->last_sent_step = step;
6594
6595 /* The c/s/C/S resume packets use Hc, so set the continue
6596 thread. */
6597 if (ptid == minus_one_ptid)
6598 set_continue_thread (any_thread_ptid);
6599 else
6600 set_continue_thread (ptid);
6601
6602 for (thread_info *thread : all_non_exited_threads (this))
6603 resume_clear_thread_private_info (thread);
6604
6605 buf = rs->buf.data ();
6606 if (::execution_direction == EXEC_REVERSE)
6607 {
6608 /* We don't pass signals to the target in reverse exec mode. */
6609 if (info_verbose && siggnal != GDB_SIGNAL_0)
6610 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6611 siggnal);
6612
6613 if (step && m_features.packet_support (PACKET_bs) == PACKET_DISABLE)
6614 error (_("Remote reverse-step not supported."));
6615 if (!step && m_features.packet_support (PACKET_bc) == PACKET_DISABLE)
6616 error (_("Remote reverse-continue not supported."));
6617
6618 strcpy (buf, step ? "bs" : "bc");
6619 }
6620 else if (siggnal != GDB_SIGNAL_0)
6621 {
6622 buf[0] = step ? 'S' : 'C';
6623 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6624 buf[2] = tohex (((int) siggnal) & 0xf);
6625 buf[3] = '\0';
6626 }
6627 else
6628 strcpy (buf, step ? "s" : "c");
6629
6630 putpkt (buf);
6631 }
6632
6633 /* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6634 STEP, and SIGGNAL have the same meaning as in target_resume. This
6635 function returns non-zero iff it resumes the inferior.
6636
6637 This function issues a strict subset of all possible vCont commands
6638 at the moment. */
6639
6640 int
6641 remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6642 enum gdb_signal siggnal)
6643 {
6644 struct remote_state *rs = get_remote_state ();
6645 char *p;
6646 char *endp;
6647
6648 /* No reverse execution actions defined for vCont. */
6649 if (::execution_direction == EXEC_REVERSE)
6650 return 0;
6651
6652 if (m_features.packet_support (PACKET_vCont) == PACKET_DISABLE)
6653 return 0;
6654
6655 p = rs->buf.data ();
6656 endp = p + get_remote_packet_size ();
6657
6658 /* If we could generate a wider range of packets, we'd have to worry
6659 about overflowing BUF. Should there be a generic
6660 "multi-part-packet" packet? */
6661
6662 p += xsnprintf (p, endp - p, "vCont");
6663
6664 if (scope_ptid == magic_null_ptid)
6665 {
6666 /* MAGIC_NULL_PTID means that we don't have any active threads,
6667 so we don't have any TID numbers the inferior will
6668 understand. Make sure to only send forms that do not specify
6669 a TID. */
6670 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6671 }
6672 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
6673 {
6674 /* Resume all threads (of all processes, or of a single
6675 process), with preference for INFERIOR_PTID. This assumes
6676 inferior_ptid belongs to the set of all threads we are about
6677 to resume. */
6678 if (step || siggnal != GDB_SIGNAL_0)
6679 {
6680 /* Step inferior_ptid, with or without signal. */
6681 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6682 }
6683
6684 /* Also pass down any pending signaled resumption for other
6685 threads not the current. */
6686 p = append_pending_thread_resumptions (p, endp, scope_ptid);
6687
6688 /* And continue others without a signal. */
6689 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
6690 }
6691 else
6692 {
6693 /* Scheduler locking; resume only SCOPE_PTID. */
6694 append_resumption (p, endp, scope_ptid, step, siggnal);
6695 }
6696
6697 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6698 putpkt (rs->buf);
6699
6700 if (target_is_non_stop_p ())
6701 {
6702 /* In non-stop, the stub replies to vCont with "OK". The stop
6703 reply will be reported asynchronously by means of a `%Stop'
6704 notification. */
6705 getpkt (&rs->buf, 0);
6706 if (strcmp (rs->buf.data (), "OK") != 0)
6707 error (_("Unexpected vCont reply in non-stop mode: %s"),
6708 rs->buf.data ());
6709 }
6710
6711 return 1;
6712 }
6713
6714 /* Tell the remote machine to resume. */
6715
6716 void
6717 remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
6718 {
6719 struct remote_state *rs = get_remote_state ();
6720
6721 /* When connected in non-stop mode, the core resumes threads
6722 individually. Resuming remote threads directly in target_resume
6723 would thus result in sending one packet per thread. Instead, to
6724 minimize roundtrip latency, here we just store the resume
6725 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6726 resumption will be done in remote_target::commit_resume, where we'll be
6727 able to do vCont action coalescing. */
6728 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6729 {
6730 remote_thread_info *remote_thr
6731 = get_remote_thread_info (inferior_thread ());
6732
6733 /* We don't expect the core to ask to resume an already resumed (from
6734 its point of view) thread. */
6735 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6736
6737 remote_thr->set_resumed_pending_vcont (step, siggnal);
6738
6739 /* There's actually nothing that says that the core can't
6740 request a wildcard resume in non-stop mode, though. It's
6741 just that we know it doesn't currently, so we don't bother
6742 with it. */
6743 gdb_assert (scope_ptid == inferior_ptid);
6744 return;
6745 }
6746
6747 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6748 (explained in remote-notif.c:handle_notification) so
6749 remote_notif_process is not called. We need find a place where
6750 it is safe to start a 'vNotif' sequence. It is good to do it
6751 before resuming inferior, because inferior was stopped and no RSP
6752 traffic at that moment. */
6753 if (!target_is_non_stop_p ())
6754 remote_notif_process (rs->notif_state, &notif_client_stop);
6755
6756 rs->last_resume_exec_dir = ::execution_direction;
6757
6758 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6759 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
6760 remote_resume_with_hc (scope_ptid, step, siggnal);
6761
6762 /* Update resumed state tracked by the remote target. */
6763 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
6764 get_remote_thread_info (tp)->set_resumed ();
6765
6766 /* We've just told the target to resume. The remote server will
6767 wait for the inferior to stop, and then send a stop reply. In
6768 the mean time, we can't start another command/query ourselves
6769 because the stub wouldn't be ready to process it. This applies
6770 only to the base all-stop protocol, however. In non-stop (which
6771 only supports vCont), the stub replies with an "OK", and is
6772 immediate able to process further serial input. */
6773 if (!target_is_non_stop_p ())
6774 rs->waiting_for_stop_reply = 1;
6775 }
6776
6777 /* Private per-inferior info for target remote processes. */
6778
6779 struct remote_inferior : public private_inferior
6780 {
6781 /* Whether we can send a wildcard vCont for this process. */
6782 bool may_wildcard_vcont = true;
6783 };
6784
6785 /* Get the remote private inferior data associated to INF. */
6786
6787 static remote_inferior *
6788 get_remote_inferior (inferior *inf)
6789 {
6790 if (inf->priv == NULL)
6791 inf->priv.reset (new remote_inferior);
6792
6793 return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
6794 }
6795
6796 /* Class used to track the construction of a vCont packet in the
6797 outgoing packet buffer. This is used to send multiple vCont
6798 packets if we have more actions than would fit a single packet. */
6799
6800 class vcont_builder
6801 {
6802 public:
6803 explicit vcont_builder (remote_target *remote)
6804 : m_remote (remote)
6805 {
6806 restart ();
6807 }
6808
6809 void flush ();
6810 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6811
6812 private:
6813 void restart ();
6814
6815 /* The remote target. */
6816 remote_target *m_remote;
6817
6818 /* Pointer to the first action. P points here if no action has been
6819 appended yet. */
6820 char *m_first_action;
6821
6822 /* Where the next action will be appended. */
6823 char *m_p;
6824
6825 /* The end of the buffer. Must never write past this. */
6826 char *m_endp;
6827 };
6828
6829 /* Prepare the outgoing buffer for a new vCont packet. */
6830
6831 void
6832 vcont_builder::restart ()
6833 {
6834 struct remote_state *rs = m_remote->get_remote_state ();
6835
6836 m_p = rs->buf.data ();
6837 m_endp = m_p + m_remote->get_remote_packet_size ();
6838 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6839 m_first_action = m_p;
6840 }
6841
6842 /* If the vCont packet being built has any action, send it to the
6843 remote end. */
6844
6845 void
6846 vcont_builder::flush ()
6847 {
6848 struct remote_state *rs;
6849
6850 if (m_p == m_first_action)
6851 return;
6852
6853 rs = m_remote->get_remote_state ();
6854 m_remote->putpkt (rs->buf);
6855 m_remote->getpkt (&rs->buf, 0);
6856 if (strcmp (rs->buf.data (), "OK") != 0)
6857 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
6858 }
6859
6860 /* The largest action is range-stepping, with its two addresses. This
6861 is more than sufficient. If a new, bigger action is created, it'll
6862 quickly trigger a failed assertion in append_resumption (and we'll
6863 just bump this). */
6864 #define MAX_ACTION_SIZE 200
6865
6866 /* Append a new vCont action in the outgoing packet being built. If
6867 the action doesn't fit the packet along with previous actions, push
6868 what we've got so far to the remote end and start over a new vCont
6869 packet (with the new action). */
6870
6871 void
6872 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6873 {
6874 char buf[MAX_ACTION_SIZE + 1];
6875
6876 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6877 ptid, step, siggnal);
6878
6879 /* Check whether this new action would fit in the vCont packet along
6880 with previous actions. If not, send what we've got so far and
6881 start a new vCont packet. */
6882 size_t rsize = endp - buf;
6883 if (rsize > m_endp - m_p)
6884 {
6885 flush ();
6886 restart ();
6887
6888 /* Should now fit. */
6889 gdb_assert (rsize <= m_endp - m_p);
6890 }
6891
6892 memcpy (m_p, buf, rsize);
6893 m_p += rsize;
6894 *m_p = '\0';
6895 }
6896
6897 /* to_commit_resume implementation. */
6898
6899 void
6900 remote_target::commit_resumed ()
6901 {
6902 /* If connected in all-stop mode, we'd send the remote resume
6903 request directly from remote_resume. Likewise if
6904 reverse-debugging, as there are no defined vCont actions for
6905 reverse execution. */
6906 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6907 return;
6908
6909 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6910 instead of resuming all threads of each process individually.
6911 However, if any thread of a process must remain halted, we can't
6912 send wildcard resumes and must send one action per thread.
6913
6914 Care must be taken to not resume threads/processes the server
6915 side already told us are stopped, but the core doesn't know about
6916 yet, because the events are still in the vStopped notification
6917 queue. For example:
6918
6919 #1 => vCont s:p1.1;c
6920 #2 <= OK
6921 #3 <= %Stopped T05 p1.1
6922 #4 => vStopped
6923 #5 <= T05 p1.2
6924 #6 => vStopped
6925 #7 <= OK
6926 #8 (infrun handles the stop for p1.1 and continues stepping)
6927 #9 => vCont s:p1.1;c
6928
6929 The last vCont above would resume thread p1.2 by mistake, because
6930 the server has no idea that the event for p1.2 had not been
6931 handled yet.
6932
6933 The server side must similarly ignore resume actions for the
6934 thread that has a pending %Stopped notification (and any other
6935 threads with events pending), until GDB acks the notification
6936 with vStopped. Otherwise, e.g., the following case is
6937 mishandled:
6938
6939 #1 => g (or any other packet)
6940 #2 <= [registers]
6941 #3 <= %Stopped T05 p1.2
6942 #4 => vCont s:p1.1;c
6943 #5 <= OK
6944
6945 Above, the server must not resume thread p1.2. GDB can't know
6946 that p1.2 stopped until it acks the %Stopped notification, and
6947 since from GDB's perspective all threads should be running, it
6948 sends a "c" action.
6949
6950 Finally, special care must also be given to handling fork/vfork
6951 events. A (v)fork event actually tells us that two processes
6952 stopped -- the parent and the child. Until we follow the fork,
6953 we must not resume the child. Therefore, if we have a pending
6954 fork follow, we must not send a global wildcard resume action
6955 (vCont;c). We can still send process-wide wildcards though. */
6956
6957 /* Start by assuming a global wildcard (vCont;c) is possible. */
6958 bool may_global_wildcard_vcont = true;
6959
6960 /* And assume every process is individually wildcard-able too. */
6961 for (inferior *inf : all_non_exited_inferiors (this))
6962 {
6963 remote_inferior *priv = get_remote_inferior (inf);
6964
6965 priv->may_wildcard_vcont = true;
6966 }
6967
6968 /* Check for any pending events (not reported or processed yet) and
6969 disable process and global wildcard resumes appropriately. */
6970 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6971
6972 bool any_pending_vcont_resume = false;
6973
6974 for (thread_info *tp : all_non_exited_threads (this))
6975 {
6976 remote_thread_info *priv = get_remote_thread_info (tp);
6977
6978 /* If a thread of a process is not meant to be resumed, then we
6979 can't wildcard that process. */
6980 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
6981 {
6982 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6983
6984 /* And if we can't wildcard a process, we can't wildcard
6985 everything either. */
6986 may_global_wildcard_vcont = false;
6987 continue;
6988 }
6989
6990 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
6991 any_pending_vcont_resume = true;
6992
6993 /* If a thread is the parent of an unfollowed fork, then we
6994 can't do a global wildcard, as that would resume the fork
6995 child. */
6996 if (thread_pending_fork_status (tp) != nullptr)
6997 may_global_wildcard_vcont = false;
6998 }
6999
7000 /* We didn't have any resumed thread pending a vCont resume, so nothing to
7001 do. */
7002 if (!any_pending_vcont_resume)
7003 return;
7004
7005 /* Now let's build the vCont packet(s). Actions must be appended
7006 from narrower to wider scopes (thread -> process -> global). If
7007 we end up with too many actions for a single packet vcont_builder
7008 flushes the current vCont packet to the remote side and starts a
7009 new one. */
7010 struct vcont_builder vcont_builder (this);
7011
7012 /* Threads first. */
7013 for (thread_info *tp : all_non_exited_threads (this))
7014 {
7015 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7016
7017 /* If the thread was previously vCont-resumed, no need to send a specific
7018 action for it. If we didn't receive a resume request for it, don't
7019 send an action for it either. */
7020 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
7021 continue;
7022
7023 gdb_assert (!thread_is_in_step_over_chain (tp));
7024
7025 /* We should never be commit-resuming a thread that has a stop reply.
7026 Otherwise, we would end up reporting a stop event for a thread while
7027 it is running on the remote target. */
7028 remote_state *rs = get_remote_state ();
7029 for (const auto &stop_reply : rs->stop_reply_queue)
7030 gdb_assert (stop_reply->ptid != tp->ptid);
7031
7032 const resumed_pending_vcont_info &info
7033 = remote_thr->resumed_pending_vcont_info ();
7034
7035 /* Check if we need to send a specific action for this thread. If not,
7036 it will be included in a wildcard resume instead. */
7037 if (info.step || info.sig != GDB_SIGNAL_0
7038 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
7039 vcont_builder.push_action (tp->ptid, info.step, info.sig);
7040
7041 remote_thr->set_resumed ();
7042 }
7043
7044 /* Now check whether we can send any process-wide wildcard. This is
7045 to avoid sending a global wildcard in the case nothing is
7046 supposed to be resumed. */
7047 bool any_process_wildcard = false;
7048
7049 for (inferior *inf : all_non_exited_inferiors (this))
7050 {
7051 if (get_remote_inferior (inf)->may_wildcard_vcont)
7052 {
7053 any_process_wildcard = true;
7054 break;
7055 }
7056 }
7057
7058 if (any_process_wildcard)
7059 {
7060 /* If all processes are wildcard-able, then send a single "c"
7061 action, otherwise, send an "all (-1) threads of process"
7062 continue action for each running process, if any. */
7063 if (may_global_wildcard_vcont)
7064 {
7065 vcont_builder.push_action (minus_one_ptid,
7066 false, GDB_SIGNAL_0);
7067 }
7068 else
7069 {
7070 for (inferior *inf : all_non_exited_inferiors (this))
7071 {
7072 if (get_remote_inferior (inf)->may_wildcard_vcont)
7073 {
7074 vcont_builder.push_action (ptid_t (inf->pid),
7075 false, GDB_SIGNAL_0);
7076 }
7077 }
7078 }
7079 }
7080
7081 vcont_builder.flush ();
7082 }
7083
7084 /* Implementation of target_has_pending_events. */
7085
7086 bool
7087 remote_target::has_pending_events ()
7088 {
7089 if (target_can_async_p ())
7090 {
7091 remote_state *rs = get_remote_state ();
7092
7093 if (async_event_handler_marked (rs->remote_async_inferior_event_token))
7094 return true;
7095
7096 /* Note that BUFCNT can be negative, indicating sticky
7097 error. */
7098 if (rs->remote_desc->bufcnt != 0)
7099 return true;
7100 }
7101 return false;
7102 }
7103
7104 \f
7105
7106 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
7107 thread, all threads of a remote process, or all threads of all
7108 processes. */
7109
7110 void
7111 remote_target::remote_stop_ns (ptid_t ptid)
7112 {
7113 struct remote_state *rs = get_remote_state ();
7114 char *p = rs->buf.data ();
7115 char *endp = p + get_remote_packet_size ();
7116
7117 /* If any thread that needs to stop was resumed but pending a vCont
7118 resume, generate a phony stop_reply. However, first check
7119 whether the thread wasn't resumed with a signal. Generating a
7120 phony stop in that case would result in losing the signal. */
7121 bool needs_commit = false;
7122 for (thread_info *tp : all_non_exited_threads (this, ptid))
7123 {
7124 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7125
7126 if (remote_thr->get_resume_state ()
7127 == resume_state::RESUMED_PENDING_VCONT)
7128 {
7129 const resumed_pending_vcont_info &info
7130 = remote_thr->resumed_pending_vcont_info ();
7131 if (info.sig != GDB_SIGNAL_0)
7132 {
7133 /* This signal must be forwarded to the inferior. We
7134 could commit-resume just this thread, but its simpler
7135 to just commit-resume everything. */
7136 needs_commit = true;
7137 break;
7138 }
7139 }
7140 }
7141
7142 if (needs_commit)
7143 commit_resumed ();
7144 else
7145 for (thread_info *tp : all_non_exited_threads (this, ptid))
7146 {
7147 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7148
7149 if (remote_thr->get_resume_state ()
7150 == resume_state::RESUMED_PENDING_VCONT)
7151 {
7152 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
7153 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
7154 tp->ptid.lwp (),
7155 pulongest (tp->ptid.tid ()));
7156
7157 /* Check that the thread wasn't resumed with a signal.
7158 Generating a phony stop would result in losing the
7159 signal. */
7160 const resumed_pending_vcont_info &info
7161 = remote_thr->resumed_pending_vcont_info ();
7162 gdb_assert (info.sig == GDB_SIGNAL_0);
7163
7164 stop_reply *sr = new stop_reply ();
7165 sr->ptid = tp->ptid;
7166 sr->rs = rs;
7167 sr->ws.set_stopped (GDB_SIGNAL_0);
7168 sr->arch = tp->inf->gdbarch;
7169 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7170 sr->watch_data_address = 0;
7171 sr->core = 0;
7172 this->push_stop_reply (sr);
7173
7174 /* Pretend that this thread was actually resumed on the
7175 remote target, then stopped. If we leave it in the
7176 RESUMED_PENDING_VCONT state and the commit_resumed
7177 method is called while the stop reply is still in the
7178 queue, we'll end up reporting a stop event to the core
7179 for that thread while it is running on the remote
7180 target... that would be bad. */
7181 remote_thr->set_resumed ();
7182 }
7183 }
7184
7185 if (!rs->supports_vCont.t)
7186 error (_("Remote server does not support stopping threads"));
7187
7188 if (ptid == minus_one_ptid
7189 || (!m_features.remote_multi_process_p () && ptid.is_pid ()))
7190 p += xsnprintf (p, endp - p, "vCont;t");
7191 else
7192 {
7193 ptid_t nptid;
7194
7195 p += xsnprintf (p, endp - p, "vCont;t:");
7196
7197 if (ptid.is_pid ())
7198 /* All (-1) threads of process. */
7199 nptid = ptid_t (ptid.pid (), -1);
7200 else
7201 {
7202 /* Small optimization: if we already have a stop reply for
7203 this thread, no use in telling the stub we want this
7204 stopped. */
7205 if (peek_stop_reply (ptid))
7206 return;
7207
7208 nptid = ptid;
7209 }
7210
7211 write_ptid (p, endp, nptid);
7212 }
7213
7214 /* In non-stop, we get an immediate OK reply. The stop reply will
7215 come in asynchronously by notification. */
7216 putpkt (rs->buf);
7217 getpkt (&rs->buf, 0);
7218 if (strcmp (rs->buf.data (), "OK") != 0)
7219 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7220 rs->buf.data ());
7221 }
7222
7223 /* All-stop version of target_interrupt. Sends a break or a ^C to
7224 interrupt the remote target. It is undefined which thread of which
7225 process reports the interrupt. */
7226
7227 void
7228 remote_target::remote_interrupt_as ()
7229 {
7230 struct remote_state *rs = get_remote_state ();
7231
7232 rs->ctrlc_pending_p = 1;
7233
7234 /* If the inferior is stopped already, but the core didn't know
7235 about it yet, just ignore the request. The pending stop events
7236 will be collected in remote_wait. */
7237 if (stop_reply_queue_length () > 0)
7238 return;
7239
7240 /* Send interrupt_sequence to remote target. */
7241 send_interrupt_sequence ();
7242 }
7243
7244 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7245 the remote target. It is undefined which thread of which process
7246 reports the interrupt. Throws an error if the packet is not
7247 supported by the server. */
7248
7249 void
7250 remote_target::remote_interrupt_ns ()
7251 {
7252 struct remote_state *rs = get_remote_state ();
7253 char *p = rs->buf.data ();
7254 char *endp = p + get_remote_packet_size ();
7255
7256 xsnprintf (p, endp - p, "vCtrlC");
7257
7258 /* In non-stop, we get an immediate OK reply. The stop reply will
7259 come in asynchronously by notification. */
7260 putpkt (rs->buf);
7261 getpkt (&rs->buf, 0);
7262
7263 switch (m_features.packet_ok (rs->buf, PACKET_vCtrlC))
7264 {
7265 case PACKET_OK:
7266 break;
7267 case PACKET_UNKNOWN:
7268 error (_("No support for interrupting the remote target."));
7269 case PACKET_ERROR:
7270 error (_("Interrupting target failed: %s"), rs->buf.data ());
7271 }
7272 }
7273
7274 /* Implement the to_stop function for the remote targets. */
7275
7276 void
7277 remote_target::stop (ptid_t ptid)
7278 {
7279 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7280
7281 if (target_is_non_stop_p ())
7282 remote_stop_ns (ptid);
7283 else
7284 {
7285 /* We don't currently have a way to transparently pause the
7286 remote target in all-stop mode. Interrupt it instead. */
7287 remote_interrupt_as ();
7288 }
7289 }
7290
7291 /* Implement the to_interrupt function for the remote targets. */
7292
7293 void
7294 remote_target::interrupt ()
7295 {
7296 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7297
7298 if (target_is_non_stop_p ())
7299 remote_interrupt_ns ();
7300 else
7301 remote_interrupt_as ();
7302 }
7303
7304 /* Implement the to_pass_ctrlc function for the remote targets. */
7305
7306 void
7307 remote_target::pass_ctrlc ()
7308 {
7309 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7310
7311 struct remote_state *rs = get_remote_state ();
7312
7313 /* If we're starting up, we're not fully synced yet. Quit
7314 immediately. */
7315 if (rs->starting_up)
7316 quit ();
7317 /* If ^C has already been sent once, offer to disconnect. */
7318 else if (rs->ctrlc_pending_p)
7319 interrupt_query ();
7320 else
7321 target_interrupt ();
7322 }
7323
7324 /* Ask the user what to do when an interrupt is received. */
7325
7326 void
7327 remote_target::interrupt_query ()
7328 {
7329 struct remote_state *rs = get_remote_state ();
7330
7331 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7332 {
7333 if (query (_("The target is not responding to interrupt requests.\n"
7334 "Stop debugging it? ")))
7335 {
7336 remote_unpush_target (this);
7337 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7338 }
7339 }
7340 else
7341 {
7342 if (query (_("Interrupted while waiting for the program.\n"
7343 "Give up waiting? ")))
7344 quit ();
7345 }
7346 }
7347
7348 /* Enable/disable target terminal ownership. Most targets can use
7349 terminal groups to control terminal ownership. Remote targets are
7350 different in that explicit transfer of ownership to/from GDB/target
7351 is required. */
7352
7353 void
7354 remote_target::terminal_inferior ()
7355 {
7356 /* NOTE: At this point we could also register our selves as the
7357 recipient of all input. Any characters typed could then be
7358 passed on down to the target. */
7359 }
7360
7361 void
7362 remote_target::terminal_ours ()
7363 {
7364 }
7365
7366 static void
7367 remote_console_output (const char *msg)
7368 {
7369 const char *p;
7370
7371 for (p = msg; p[0] && p[1]; p += 2)
7372 {
7373 char tb[2];
7374 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7375
7376 tb[0] = c;
7377 tb[1] = 0;
7378 gdb_stdtarg->puts (tb);
7379 }
7380 gdb_stdtarg->flush ();
7381 }
7382
7383 /* Return the length of the stop reply queue. */
7384
7385 int
7386 remote_target::stop_reply_queue_length ()
7387 {
7388 remote_state *rs = get_remote_state ();
7389 return rs->stop_reply_queue.size ();
7390 }
7391
7392 static void
7393 remote_notif_stop_parse (remote_target *remote,
7394 const notif_client *self, const char *buf,
7395 struct notif_event *event)
7396 {
7397 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7398 }
7399
7400 static void
7401 remote_notif_stop_ack (remote_target *remote,
7402 const notif_client *self, const char *buf,
7403 struct notif_event *event)
7404 {
7405 struct stop_reply *stop_reply = (struct stop_reply *) event;
7406
7407 /* acknowledge */
7408 putpkt (remote, self->ack_command);
7409
7410 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7411 the notification. It was left in the queue because we need to
7412 acknowledge it and pull the rest of the notifications out. */
7413 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7414 remote->push_stop_reply (stop_reply);
7415 }
7416
7417 static int
7418 remote_notif_stop_can_get_pending_events (remote_target *remote,
7419 const notif_client *self)
7420 {
7421 /* We can't get pending events in remote_notif_process for
7422 notification stop, and we have to do this in remote_wait_ns
7423 instead. If we fetch all queued events from stub, remote stub
7424 may exit and we have no chance to process them back in
7425 remote_wait_ns. */
7426 remote_state *rs = remote->get_remote_state ();
7427 mark_async_event_handler (rs->remote_async_inferior_event_token);
7428 return 0;
7429 }
7430
7431 stop_reply::~stop_reply ()
7432 {
7433 for (cached_reg_t &reg : regcache)
7434 xfree (reg.data);
7435 }
7436
7437 static notif_event_up
7438 remote_notif_stop_alloc_reply ()
7439 {
7440 return notif_event_up (new struct stop_reply ());
7441 }
7442
7443 /* A client of notification Stop. */
7444
7445 const notif_client notif_client_stop =
7446 {
7447 "Stop",
7448 "vStopped",
7449 remote_notif_stop_parse,
7450 remote_notif_stop_ack,
7451 remote_notif_stop_can_get_pending_events,
7452 remote_notif_stop_alloc_reply,
7453 REMOTE_NOTIF_STOP,
7454 };
7455
7456 /* If CONTEXT contains any fork child threads that have not been
7457 reported yet, remove them from the CONTEXT list. If such a
7458 thread exists it is because we are stopped at a fork catchpoint
7459 and have not yet called follow_fork, which will set up the
7460 host-side data structures for the new process. */
7461
7462 void
7463 remote_target::remove_new_fork_children (threads_listing_context *context)
7464 {
7465 const notif_client *notif = &notif_client_stop;
7466
7467 /* For any threads stopped at a fork event, remove the corresponding
7468 fork child threads from the CONTEXT list. */
7469 for (thread_info *thread : all_non_exited_threads (this))
7470 {
7471 const target_waitstatus *ws = thread_pending_fork_status (thread);
7472
7473 if (ws == nullptr)
7474 continue;
7475
7476 context->remove_thread (ws->child_ptid ());
7477 }
7478
7479 /* Check for any pending fork events (not reported or processed yet)
7480 in process PID and remove those fork child threads from the
7481 CONTEXT list as well. */
7482 remote_notif_get_pending_events (notif);
7483 for (auto &event : get_remote_state ()->stop_reply_queue)
7484 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7485 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7486 context->remove_thread (event->ws.child_ptid ());
7487 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7488 context->remove_thread (event->ptid);
7489 }
7490
7491 /* Check whether any event pending in the vStopped queue would prevent a
7492 global or process wildcard vCont action. Set *may_global_wildcard to
7493 false if we can't do a global wildcard (vCont;c), and clear the event
7494 inferior's may_wildcard_vcont flag if we can't do a process-wide
7495 wildcard resume (vCont;c:pPID.-1). */
7496
7497 void
7498 remote_target::check_pending_events_prevent_wildcard_vcont
7499 (bool *may_global_wildcard)
7500 {
7501 const notif_client *notif = &notif_client_stop;
7502
7503 remote_notif_get_pending_events (notif);
7504 for (auto &event : get_remote_state ()->stop_reply_queue)
7505 {
7506 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7507 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7508 continue;
7509
7510 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7511 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7512 *may_global_wildcard = false;
7513
7514 /* This may be the first time we heard about this process.
7515 Regardless, we must not do a global wildcard resume, otherwise
7516 we'd resume this process too. */
7517 *may_global_wildcard = false;
7518 if (event->ptid != null_ptid)
7519 {
7520 inferior *inf = find_inferior_ptid (this, event->ptid);
7521 if (inf != NULL)
7522 get_remote_inferior (inf)->may_wildcard_vcont = false;
7523 }
7524 }
7525 }
7526
7527 /* Discard all pending stop replies of inferior INF. */
7528
7529 void
7530 remote_target::discard_pending_stop_replies (struct inferior *inf)
7531 {
7532 struct stop_reply *reply;
7533 struct remote_state *rs = get_remote_state ();
7534 struct remote_notif_state *rns = rs->notif_state;
7535
7536 /* This function can be notified when an inferior exists. When the
7537 target is not remote, the notification state is NULL. */
7538 if (rs->remote_desc == NULL)
7539 return;
7540
7541 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7542
7543 /* Discard the in-flight notification. */
7544 if (reply != NULL && reply->ptid.pid () == inf->pid)
7545 {
7546 /* Leave the notification pending, since the server expects that
7547 we acknowledge it with vStopped. But clear its contents, so
7548 that later on when we acknowledge it, we also discard it. */
7549 remote_debug_printf
7550 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7551 reply->ptid.to_string().c_str(),
7552 reply->ws.to_string ().c_str ());
7553 reply->ws.set_ignore ();
7554 }
7555
7556 /* Discard the stop replies we have already pulled with
7557 vStopped. */
7558 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7559 rs->stop_reply_queue.end (),
7560 [=] (const stop_reply_up &event)
7561 {
7562 return event->ptid.pid () == inf->pid;
7563 });
7564 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7565 remote_debug_printf
7566 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7567 reply->ptid.to_string().c_str(),
7568 reply->ws.to_string ().c_str ());
7569 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7570 }
7571
7572 /* Discard the stop replies for RS in stop_reply_queue. */
7573
7574 void
7575 remote_target::discard_pending_stop_replies_in_queue ()
7576 {
7577 remote_state *rs = get_remote_state ();
7578
7579 /* Discard the stop replies we have already pulled with
7580 vStopped. */
7581 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7582 rs->stop_reply_queue.end (),
7583 [=] (const stop_reply_up &event)
7584 {
7585 return event->rs == rs;
7586 });
7587 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7588 }
7589
7590 /* Remove the first reply in 'stop_reply_queue' which matches
7591 PTID. */
7592
7593 struct stop_reply *
7594 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7595 {
7596 remote_state *rs = get_remote_state ();
7597
7598 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7599 rs->stop_reply_queue.end (),
7600 [=] (const stop_reply_up &event)
7601 {
7602 return event->ptid.matches (ptid);
7603 });
7604 struct stop_reply *result;
7605 if (iter == rs->stop_reply_queue.end ())
7606 result = nullptr;
7607 else
7608 {
7609 result = iter->release ();
7610 rs->stop_reply_queue.erase (iter);
7611 }
7612
7613 if (notif_debug)
7614 gdb_printf (gdb_stdlog,
7615 "notif: discard queued event: 'Stop' in %s\n",
7616 ptid.to_string ().c_str ());
7617
7618 return result;
7619 }
7620
7621 /* Look for a queued stop reply belonging to PTID. If one is found,
7622 remove it from the queue, and return it. Returns NULL if none is
7623 found. If there are still queued events left to process, tell the
7624 event loop to get back to target_wait soon. */
7625
7626 struct stop_reply *
7627 remote_target::queued_stop_reply (ptid_t ptid)
7628 {
7629 remote_state *rs = get_remote_state ();
7630 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7631
7632 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7633 {
7634 /* There's still at least an event left. */
7635 mark_async_event_handler (rs->remote_async_inferior_event_token);
7636 }
7637
7638 return r;
7639 }
7640
7641 /* Push a fully parsed stop reply in the stop reply queue. Since we
7642 know that we now have at least one queued event left to pass to the
7643 core side, tell the event loop to get back to target_wait soon. */
7644
7645 void
7646 remote_target::push_stop_reply (struct stop_reply *new_event)
7647 {
7648 remote_state *rs = get_remote_state ();
7649 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7650
7651 if (notif_debug)
7652 gdb_printf (gdb_stdlog,
7653 "notif: push 'Stop' %s to queue %d\n",
7654 new_event->ptid.to_string ().c_str (),
7655 int (rs->stop_reply_queue.size ()));
7656
7657 /* Mark the pending event queue only if async mode is currently enabled.
7658 If async mode is not currently enabled, then, if it later becomes
7659 enabled, and there are events in this queue, we will mark the event
7660 token at that point, see remote_target::async. */
7661 if (target_is_async_p ())
7662 mark_async_event_handler (rs->remote_async_inferior_event_token);
7663 }
7664
7665 /* Returns true if we have a stop reply for PTID. */
7666
7667 int
7668 remote_target::peek_stop_reply (ptid_t ptid)
7669 {
7670 remote_state *rs = get_remote_state ();
7671 for (auto &event : rs->stop_reply_queue)
7672 if (ptid == event->ptid
7673 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7674 return 1;
7675 return 0;
7676 }
7677
7678 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7679 starting with P and ending with PEND matches PREFIX. */
7680
7681 static int
7682 strprefix (const char *p, const char *pend, const char *prefix)
7683 {
7684 for ( ; p < pend; p++, prefix++)
7685 if (*p != *prefix)
7686 return 0;
7687 return *prefix == '\0';
7688 }
7689
7690 /* Parse the stop reply in BUF. Either the function succeeds, and the
7691 result is stored in EVENT, or throws an error. */
7692
7693 void
7694 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7695 {
7696 remote_arch_state *rsa = NULL;
7697 ULONGEST addr;
7698 const char *p;
7699 int skipregs = 0;
7700
7701 event->ptid = null_ptid;
7702 event->rs = get_remote_state ();
7703 event->ws.set_ignore ();
7704 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7705 event->regcache.clear ();
7706 event->core = -1;
7707
7708 switch (buf[0])
7709 {
7710 case 'T': /* Status with PC, SP, FP, ... */
7711 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7712 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7713 ss = signal number
7714 n... = register number
7715 r... = register contents
7716 */
7717
7718 p = &buf[3]; /* after Txx */
7719 while (*p)
7720 {
7721 const char *p1;
7722 int fieldsize;
7723
7724 p1 = strchr (p, ':');
7725 if (p1 == NULL)
7726 error (_("Malformed packet(a) (missing colon): %s\n\
7727 Packet: '%s'\n"),
7728 p, buf);
7729 if (p == p1)
7730 error (_("Malformed packet(a) (missing register number): %s\n\
7731 Packet: '%s'\n"),
7732 p, buf);
7733
7734 /* Some "registers" are actually extended stop information.
7735 Note if you're adding a new entry here: GDB 7.9 and
7736 earlier assume that all register "numbers" that start
7737 with an hex digit are real register numbers. Make sure
7738 the server only sends such a packet if it knows the
7739 client understands it. */
7740
7741 if (strprefix (p, p1, "thread"))
7742 event->ptid = read_ptid (++p1, &p);
7743 else if (strprefix (p, p1, "syscall_entry"))
7744 {
7745 ULONGEST sysno;
7746
7747 p = unpack_varlen_hex (++p1, &sysno);
7748 event->ws.set_syscall_entry ((int) sysno);
7749 }
7750 else if (strprefix (p, p1, "syscall_return"))
7751 {
7752 ULONGEST sysno;
7753
7754 p = unpack_varlen_hex (++p1, &sysno);
7755 event->ws.set_syscall_return ((int) sysno);
7756 }
7757 else if (strprefix (p, p1, "watch")
7758 || strprefix (p, p1, "rwatch")
7759 || strprefix (p, p1, "awatch"))
7760 {
7761 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7762 p = unpack_varlen_hex (++p1, &addr);
7763 event->watch_data_address = (CORE_ADDR) addr;
7764 }
7765 else if (strprefix (p, p1, "swbreak"))
7766 {
7767 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7768
7769 /* Make sure the stub doesn't forget to indicate support
7770 with qSupported. */
7771 if (m_features.packet_support (PACKET_swbreak_feature)
7772 != PACKET_ENABLE)
7773 error (_("Unexpected swbreak stop reason"));
7774
7775 /* The value part is documented as "must be empty",
7776 though we ignore it, in case we ever decide to make
7777 use of it in a backward compatible way. */
7778 p = strchrnul (p1 + 1, ';');
7779 }
7780 else if (strprefix (p, p1, "hwbreak"))
7781 {
7782 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7783
7784 /* Make sure the stub doesn't forget to indicate support
7785 with qSupported. */
7786 if (m_features.packet_support (PACKET_hwbreak_feature)
7787 != PACKET_ENABLE)
7788 error (_("Unexpected hwbreak stop reason"));
7789
7790 /* See above. */
7791 p = strchrnul (p1 + 1, ';');
7792 }
7793 else if (strprefix (p, p1, "library"))
7794 {
7795 event->ws.set_loaded ();
7796 p = strchrnul (p1 + 1, ';');
7797 }
7798 else if (strprefix (p, p1, "replaylog"))
7799 {
7800 event->ws.set_no_history ();
7801 /* p1 will indicate "begin" or "end", but it makes
7802 no difference for now, so ignore it. */
7803 p = strchrnul (p1 + 1, ';');
7804 }
7805 else if (strprefix (p, p1, "core"))
7806 {
7807 ULONGEST c;
7808
7809 p = unpack_varlen_hex (++p1, &c);
7810 event->core = c;
7811 }
7812 else if (strprefix (p, p1, "fork"))
7813 event->ws.set_forked (read_ptid (++p1, &p));
7814 else if (strprefix (p, p1, "vfork"))
7815 event->ws.set_vforked (read_ptid (++p1, &p));
7816 else if (strprefix (p, p1, "vforkdone"))
7817 {
7818 event->ws.set_vfork_done ();
7819 p = strchrnul (p1 + 1, ';');
7820 }
7821 else if (strprefix (p, p1, "exec"))
7822 {
7823 ULONGEST ignored;
7824 int pathlen;
7825
7826 /* Determine the length of the execd pathname. */
7827 p = unpack_varlen_hex (++p1, &ignored);
7828 pathlen = (p - p1) / 2;
7829
7830 /* Save the pathname for event reporting and for
7831 the next run command. */
7832 gdb::unique_xmalloc_ptr<char> pathname
7833 ((char *) xmalloc (pathlen + 1));
7834 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
7835 pathname.get ()[pathlen] = '\0';
7836
7837 /* This is freed during event handling. */
7838 event->ws.set_execd (std::move (pathname));
7839
7840 /* Skip the registers included in this packet, since
7841 they may be for an architecture different from the
7842 one used by the original program. */
7843 skipregs = 1;
7844 }
7845 else if (strprefix (p, p1, "create"))
7846 {
7847 event->ws.set_thread_created ();
7848 p = strchrnul (p1 + 1, ';');
7849 }
7850 else
7851 {
7852 ULONGEST pnum;
7853 const char *p_temp;
7854
7855 if (skipregs)
7856 {
7857 p = strchrnul (p1 + 1, ';');
7858 p++;
7859 continue;
7860 }
7861
7862 /* Maybe a real ``P'' register number. */
7863 p_temp = unpack_varlen_hex (p, &pnum);
7864 /* If the first invalid character is the colon, we got a
7865 register number. Otherwise, it's an unknown stop
7866 reason. */
7867 if (p_temp == p1)
7868 {
7869 /* If we haven't parsed the event's thread yet, find
7870 it now, in order to find the architecture of the
7871 reported expedited registers. */
7872 if (event->ptid == null_ptid)
7873 {
7874 /* If there is no thread-id information then leave
7875 the event->ptid as null_ptid. Later in
7876 process_stop_reply we will pick a suitable
7877 thread. */
7878 const char *thr = strstr (p1 + 1, ";thread:");
7879 if (thr != NULL)
7880 event->ptid = read_ptid (thr + strlen (";thread:"),
7881 NULL);
7882 }
7883
7884 if (rsa == NULL)
7885 {
7886 inferior *inf
7887 = (event->ptid == null_ptid
7888 ? NULL
7889 : find_inferior_ptid (this, event->ptid));
7890 /* If this is the first time we learn anything
7891 about this process, skip the registers
7892 included in this packet, since we don't yet
7893 know which architecture to use to parse them.
7894 We'll determine the architecture later when
7895 we process the stop reply and retrieve the
7896 target description, via
7897 remote_notice_new_inferior ->
7898 post_create_inferior. */
7899 if (inf == NULL)
7900 {
7901 p = strchrnul (p1 + 1, ';');
7902 p++;
7903 continue;
7904 }
7905
7906 event->arch = inf->gdbarch;
7907 rsa = event->rs->get_remote_arch_state (event->arch);
7908 }
7909
7910 packet_reg *reg
7911 = packet_reg_from_pnum (event->arch, rsa, pnum);
7912 cached_reg_t cached_reg;
7913
7914 if (reg == NULL)
7915 error (_("Remote sent bad register number %s: %s\n\
7916 Packet: '%s'\n"),
7917 hex_string (pnum), p, buf);
7918
7919 cached_reg.num = reg->regnum;
7920 cached_reg.data = (gdb_byte *)
7921 xmalloc (register_size (event->arch, reg->regnum));
7922
7923 p = p1 + 1;
7924 fieldsize = hex2bin (p, cached_reg.data,
7925 register_size (event->arch, reg->regnum));
7926 p += 2 * fieldsize;
7927 if (fieldsize < register_size (event->arch, reg->regnum))
7928 warning (_("Remote reply is too short: %s"), buf);
7929
7930 event->regcache.push_back (cached_reg);
7931 }
7932 else
7933 {
7934 /* Not a number. Silently skip unknown optional
7935 info. */
7936 p = strchrnul (p1 + 1, ';');
7937 }
7938 }
7939
7940 if (*p != ';')
7941 error (_("Remote register badly formatted: %s\nhere: %s"),
7942 buf, p);
7943 ++p;
7944 }
7945
7946 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
7947 break;
7948
7949 /* fall through */
7950 case 'S': /* Old style status, just signal only. */
7951 {
7952 int sig;
7953
7954 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7955 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7956 event->ws.set_stopped ((enum gdb_signal) sig);
7957 else
7958 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
7959 }
7960 break;
7961 case 'w': /* Thread exited. */
7962 {
7963 ULONGEST value;
7964
7965 p = unpack_varlen_hex (&buf[1], &value);
7966 event->ws.set_thread_exited (value);
7967 if (*p != ';')
7968 error (_("stop reply packet badly formatted: %s"), buf);
7969 event->ptid = read_ptid (++p, NULL);
7970 break;
7971 }
7972 case 'W': /* Target exited. */
7973 case 'X':
7974 {
7975 ULONGEST value;
7976
7977 /* GDB used to accept only 2 hex chars here. Stubs should
7978 only send more if they detect GDB supports multi-process
7979 support. */
7980 p = unpack_varlen_hex (&buf[1], &value);
7981
7982 if (buf[0] == 'W')
7983 {
7984 /* The remote process exited. */
7985 event->ws.set_exited (value);
7986 }
7987 else
7988 {
7989 /* The remote process exited with a signal. */
7990 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7991 event->ws.set_signalled ((enum gdb_signal) value);
7992 else
7993 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
7994 }
7995
7996 /* If no process is specified, return null_ptid, and let the
7997 caller figure out the right process to use. */
7998 int pid = 0;
7999 if (*p == '\0')
8000 ;
8001 else if (*p == ';')
8002 {
8003 p++;
8004
8005 if (*p == '\0')
8006 ;
8007 else if (startswith (p, "process:"))
8008 {
8009 ULONGEST upid;
8010
8011 p += sizeof ("process:") - 1;
8012 unpack_varlen_hex (p, &upid);
8013 pid = upid;
8014 }
8015 else
8016 error (_("unknown stop reply packet: %s"), buf);
8017 }
8018 else
8019 error (_("unknown stop reply packet: %s"), buf);
8020 event->ptid = ptid_t (pid);
8021 }
8022 break;
8023 case 'N':
8024 event->ws.set_no_resumed ();
8025 event->ptid = minus_one_ptid;
8026 break;
8027 }
8028 }
8029
8030 /* When the stub wants to tell GDB about a new notification reply, it
8031 sends a notification (%Stop, for example). Those can come it at
8032 any time, hence, we have to make sure that any pending
8033 putpkt/getpkt sequence we're making is finished, before querying
8034 the stub for more events with the corresponding ack command
8035 (vStopped, for example). E.g., if we started a vStopped sequence
8036 immediately upon receiving the notification, something like this
8037 could happen:
8038
8039 1.1) --> Hg 1
8040 1.2) <-- OK
8041 1.3) --> g
8042 1.4) <-- %Stop
8043 1.5) --> vStopped
8044 1.6) <-- (registers reply to step #1.3)
8045
8046 Obviously, the reply in step #1.6 would be unexpected to a vStopped
8047 query.
8048
8049 To solve this, whenever we parse a %Stop notification successfully,
8050 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
8051 doing whatever we were doing:
8052
8053 2.1) --> Hg 1
8054 2.2) <-- OK
8055 2.3) --> g
8056 2.4) <-- %Stop
8057 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
8058 2.5) <-- (registers reply to step #2.3)
8059
8060 Eventually after step #2.5, we return to the event loop, which
8061 notices there's an event on the
8062 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
8063 associated callback --- the function below. At this point, we're
8064 always safe to start a vStopped sequence. :
8065
8066 2.6) --> vStopped
8067 2.7) <-- T05 thread:2
8068 2.8) --> vStopped
8069 2.9) --> OK
8070 */
8071
8072 void
8073 remote_target::remote_notif_get_pending_events (const notif_client *nc)
8074 {
8075 struct remote_state *rs = get_remote_state ();
8076
8077 if (rs->notif_state->pending_event[nc->id] != NULL)
8078 {
8079 if (notif_debug)
8080 gdb_printf (gdb_stdlog,
8081 "notif: process: '%s' ack pending event\n",
8082 nc->name);
8083
8084 /* acknowledge */
8085 nc->ack (this, nc, rs->buf.data (),
8086 rs->notif_state->pending_event[nc->id]);
8087 rs->notif_state->pending_event[nc->id] = NULL;
8088
8089 while (1)
8090 {
8091 getpkt (&rs->buf, 0);
8092 if (strcmp (rs->buf.data (), "OK") == 0)
8093 break;
8094 else
8095 remote_notif_ack (this, nc, rs->buf.data ());
8096 }
8097 }
8098 else
8099 {
8100 if (notif_debug)
8101 gdb_printf (gdb_stdlog,
8102 "notif: process: '%s' no pending reply\n",
8103 nc->name);
8104 }
8105 }
8106
8107 /* Wrapper around remote_target::remote_notif_get_pending_events to
8108 avoid having to export the whole remote_target class. */
8109
8110 void
8111 remote_notif_get_pending_events (remote_target *remote, const notif_client *nc)
8112 {
8113 remote->remote_notif_get_pending_events (nc);
8114 }
8115
8116 /* Called from process_stop_reply when the stop packet we are responding
8117 to didn't include a process-id or thread-id. STATUS is the stop event
8118 we are responding to.
8119
8120 It is the task of this function to select a suitable thread (or process)
8121 and return its ptid, this is the thread (or process) we will assume the
8122 stop event came from.
8123
8124 In some cases there isn't really any choice about which thread (or
8125 process) is selected, a basic remote with a single process containing a
8126 single thread might choose not to send any process-id or thread-id in
8127 its stop packets, this function will select and return the one and only
8128 thread.
8129
8130 However, if a target supports multiple threads (or processes) and still
8131 doesn't include a thread-id (or process-id) in its stop packet then
8132 first, this is a badly behaving target, and second, we're going to have
8133 to select a thread (or process) at random and use that. This function
8134 will print a warning to the user if it detects that there is the
8135 possibility that GDB is guessing which thread (or process) to
8136 report.
8137
8138 Note that this is called before GDB fetches the updated thread list from the
8139 target. So it's possible for the stop reply to be ambiguous and for GDB to
8140 not realize it. For example, if there's initially one thread, the target
8141 spawns a second thread, and then sends a stop reply without an id that
8142 concerns the first thread. GDB will assume the stop reply is about the
8143 first thread - the only thread it knows about - without printing a warning.
8144 Anyway, if the remote meant for the stop reply to be about the second thread,
8145 then it would be really broken, because GDB doesn't know about that thread
8146 yet. */
8147
8148 ptid_t
8149 remote_target::select_thread_for_ambiguous_stop_reply
8150 (const target_waitstatus &status)
8151 {
8152 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8153
8154 /* Some stop events apply to all threads in an inferior, while others
8155 only apply to a single thread. */
8156 bool process_wide_stop
8157 = (status.kind () == TARGET_WAITKIND_EXITED
8158 || status.kind () == TARGET_WAITKIND_SIGNALLED);
8159
8160 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
8161
8162 thread_info *first_resumed_thread = nullptr;
8163 bool ambiguous = false;
8164
8165 /* Consider all non-exited threads of the target, find the first resumed
8166 one. */
8167 for (thread_info *thr : all_non_exited_threads (this))
8168 {
8169 remote_thread_info *remote_thr = get_remote_thread_info (thr);
8170
8171 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8172 continue;
8173
8174 if (first_resumed_thread == nullptr)
8175 first_resumed_thread = thr;
8176 else if (!process_wide_stop
8177 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8178 ambiguous = true;
8179 }
8180
8181 gdb_assert (first_resumed_thread != nullptr);
8182
8183 remote_debug_printf ("first resumed thread is %s",
8184 pid_to_str (first_resumed_thread->ptid).c_str ());
8185 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8186
8187 /* Warn if the remote target is sending ambiguous stop replies. */
8188 if (ambiguous)
8189 {
8190 static bool warned = false;
8191
8192 if (!warned)
8193 {
8194 /* If you are seeing this warning then the remote target has
8195 stopped without specifying a thread-id, but the target
8196 does have multiple threads (or inferiors), and so GDB is
8197 having to guess which thread stopped.
8198
8199 Examples of what might cause this are the target sending
8200 and 'S' stop packet, or a 'T' stop packet and not
8201 including a thread-id.
8202
8203 Additionally, the target might send a 'W' or 'X packet
8204 without including a process-id, when the target has
8205 multiple running inferiors. */
8206 if (process_wide_stop)
8207 warning (_("multi-inferior target stopped without "
8208 "sending a process-id, using first "
8209 "non-exited inferior"));
8210 else
8211 warning (_("multi-threaded target stopped without "
8212 "sending a thread-id, using first "
8213 "non-exited thread"));
8214 warned = true;
8215 }
8216 }
8217
8218 /* If this is a stop for all threads then don't use a particular threads
8219 ptid, instead create a new ptid where only the pid field is set. */
8220 if (process_wide_stop)
8221 return ptid_t (first_resumed_thread->ptid.pid ());
8222 else
8223 return first_resumed_thread->ptid;
8224 }
8225
8226 /* Called when it is decided that STOP_REPLY holds the info of the
8227 event that is to be returned to the core. This function always
8228 destroys STOP_REPLY. */
8229
8230 ptid_t
8231 remote_target::process_stop_reply (struct stop_reply *stop_reply,
8232 struct target_waitstatus *status)
8233 {
8234 *status = stop_reply->ws;
8235 ptid_t ptid = stop_reply->ptid;
8236
8237 /* If no thread/process was reported by the stub then select a suitable
8238 thread/process. */
8239 if (ptid == null_ptid)
8240 ptid = select_thread_for_ambiguous_stop_reply (*status);
8241 gdb_assert (ptid != null_ptid);
8242
8243 if (status->kind () != TARGET_WAITKIND_EXITED
8244 && status->kind () != TARGET_WAITKIND_SIGNALLED
8245 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8246 {
8247 /* Expedited registers. */
8248 if (!stop_reply->regcache.empty ())
8249 {
8250 struct regcache *regcache
8251 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
8252
8253 for (cached_reg_t &reg : stop_reply->regcache)
8254 {
8255 regcache->raw_supply (reg.num, reg.data);
8256 xfree (reg.data);
8257 }
8258
8259 stop_reply->regcache.clear ();
8260 }
8261
8262 remote_notice_new_inferior (ptid, false);
8263 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8264 remote_thr->core = stop_reply->core;
8265 remote_thr->stop_reason = stop_reply->stop_reason;
8266 remote_thr->watch_data_address = stop_reply->watch_data_address;
8267
8268 if (target_is_non_stop_p ())
8269 {
8270 /* If the target works in non-stop mode, a stop-reply indicates that
8271 only this thread stopped. */
8272 remote_thr->set_not_resumed ();
8273 }
8274 else
8275 {
8276 /* If the target works in all-stop mode, a stop-reply indicates that
8277 all the target's threads stopped. */
8278 for (thread_info *tp : all_non_exited_threads (this))
8279 get_remote_thread_info (tp)->set_not_resumed ();
8280 }
8281 }
8282
8283 delete stop_reply;
8284 return ptid;
8285 }
8286
8287 /* The non-stop mode version of target_wait. */
8288
8289 ptid_t
8290 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8291 target_wait_flags options)
8292 {
8293 struct remote_state *rs = get_remote_state ();
8294 struct stop_reply *stop_reply;
8295 int ret;
8296 int is_notif = 0;
8297
8298 /* If in non-stop mode, get out of getpkt even if a
8299 notification is received. */
8300
8301 ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
8302 while (1)
8303 {
8304 if (ret != -1 && !is_notif)
8305 switch (rs->buf[0])
8306 {
8307 case 'E': /* Error of some sort. */
8308 /* We're out of sync with the target now. Did it continue
8309 or not? We can't tell which thread it was in non-stop,
8310 so just ignore this. */
8311 warning (_("Remote failure reply: %s"), rs->buf.data ());
8312 break;
8313 case 'O': /* Console output. */
8314 remote_console_output (&rs->buf[1]);
8315 break;
8316 default:
8317 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8318 break;
8319 }
8320
8321 /* Acknowledge a pending stop reply that may have arrived in the
8322 mean time. */
8323 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8324 remote_notif_get_pending_events (&notif_client_stop);
8325
8326 /* If indeed we noticed a stop reply, we're done. */
8327 stop_reply = queued_stop_reply (ptid);
8328 if (stop_reply != NULL)
8329 return process_stop_reply (stop_reply, status);
8330
8331 /* Still no event. If we're just polling for an event, then
8332 return to the event loop. */
8333 if (options & TARGET_WNOHANG)
8334 {
8335 status->set_ignore ();
8336 return minus_one_ptid;
8337 }
8338
8339 /* Otherwise do a blocking wait. */
8340 ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
8341 }
8342 }
8343
8344 /* Return the first resumed thread. */
8345
8346 static ptid_t
8347 first_remote_resumed_thread (remote_target *target)
8348 {
8349 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8350 if (tp->resumed ())
8351 return tp->ptid;
8352 return null_ptid;
8353 }
8354
8355 /* Wait until the remote machine stops, then return, storing status in
8356 STATUS just as `wait' would. */
8357
8358 ptid_t
8359 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8360 target_wait_flags options)
8361 {
8362 struct remote_state *rs = get_remote_state ();
8363 ptid_t event_ptid = null_ptid;
8364 char *buf;
8365 struct stop_reply *stop_reply;
8366
8367 again:
8368
8369 status->set_ignore ();
8370
8371 stop_reply = queued_stop_reply (ptid);
8372 if (stop_reply != NULL)
8373 {
8374 /* None of the paths that push a stop reply onto the queue should
8375 have set the waiting_for_stop_reply flag. */
8376 gdb_assert (!rs->waiting_for_stop_reply);
8377 event_ptid = process_stop_reply (stop_reply, status);
8378 }
8379 else
8380 {
8381 int forever = ((options & TARGET_WNOHANG) == 0
8382 && rs->wait_forever_enabled_p);
8383
8384 if (!rs->waiting_for_stop_reply)
8385 {
8386 status->set_no_resumed ();
8387 return minus_one_ptid;
8388 }
8389
8390 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8391 _never_ wait for ever -> test on target_is_async_p().
8392 However, before we do that we need to ensure that the caller
8393 knows how to take the target into/out of async mode. */
8394 int is_notif;
8395 int ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
8396
8397 /* GDB gets a notification. Return to core as this event is
8398 not interesting. */
8399 if (ret != -1 && is_notif)
8400 return minus_one_ptid;
8401
8402 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8403 return minus_one_ptid;
8404
8405 buf = rs->buf.data ();
8406
8407 /* Assume that the target has acknowledged Ctrl-C unless we receive
8408 an 'F' or 'O' packet. */
8409 if (buf[0] != 'F' && buf[0] != 'O')
8410 rs->ctrlc_pending_p = 0;
8411
8412 switch (buf[0])
8413 {
8414 case 'E': /* Error of some sort. */
8415 /* We're out of sync with the target now. Did it continue or
8416 not? Not is more likely, so report a stop. */
8417 rs->waiting_for_stop_reply = 0;
8418
8419 warning (_("Remote failure reply: %s"), buf);
8420 status->set_stopped (GDB_SIGNAL_0);
8421 break;
8422 case 'F': /* File-I/O request. */
8423 /* GDB may access the inferior memory while handling the File-I/O
8424 request, but we don't want GDB accessing memory while waiting
8425 for a stop reply. See the comments in putpkt_binary. Set
8426 waiting_for_stop_reply to 0 temporarily. */
8427 rs->waiting_for_stop_reply = 0;
8428 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8429 rs->ctrlc_pending_p = 0;
8430 /* GDB handled the File-I/O request, and the target is running
8431 again. Keep waiting for events. */
8432 rs->waiting_for_stop_reply = 1;
8433 break;
8434 case 'N': case 'T': case 'S': case 'X': case 'W':
8435 {
8436 /* There is a stop reply to handle. */
8437 rs->waiting_for_stop_reply = 0;
8438
8439 stop_reply
8440 = (struct stop_reply *) remote_notif_parse (this,
8441 &notif_client_stop,
8442 rs->buf.data ());
8443
8444 event_ptid = process_stop_reply (stop_reply, status);
8445 break;
8446 }
8447 case 'O': /* Console output. */
8448 remote_console_output (buf + 1);
8449 break;
8450 case '\0':
8451 if (rs->last_sent_signal != GDB_SIGNAL_0)
8452 {
8453 /* Zero length reply means that we tried 'S' or 'C' and the
8454 remote system doesn't support it. */
8455 target_terminal::ours_for_output ();
8456 gdb_printf
8457 ("Can't send signals to this remote system. %s not sent.\n",
8458 gdb_signal_to_name (rs->last_sent_signal));
8459 rs->last_sent_signal = GDB_SIGNAL_0;
8460 target_terminal::inferior ();
8461
8462 strcpy (buf, rs->last_sent_step ? "s" : "c");
8463 putpkt (buf);
8464 break;
8465 }
8466 /* fallthrough */
8467 default:
8468 warning (_("Invalid remote reply: %s"), buf);
8469 break;
8470 }
8471 }
8472
8473 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8474 return minus_one_ptid;
8475 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8476 {
8477 /* Nothing interesting happened. If we're doing a non-blocking
8478 poll, we're done. Otherwise, go back to waiting. */
8479 if (options & TARGET_WNOHANG)
8480 return minus_one_ptid;
8481 else
8482 goto again;
8483 }
8484 else if (status->kind () != TARGET_WAITKIND_EXITED
8485 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8486 {
8487 if (event_ptid != null_ptid)
8488 record_currthread (rs, event_ptid);
8489 else
8490 event_ptid = first_remote_resumed_thread (this);
8491 }
8492 else
8493 {
8494 /* A process exit. Invalidate our notion of current thread. */
8495 record_currthread (rs, minus_one_ptid);
8496 /* It's possible that the packet did not include a pid. */
8497 if (event_ptid == null_ptid)
8498 event_ptid = first_remote_resumed_thread (this);
8499 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8500 if (event_ptid == null_ptid)
8501 event_ptid = magic_null_ptid;
8502 }
8503
8504 return event_ptid;
8505 }
8506
8507 /* Wait until the remote machine stops, then return, storing status in
8508 STATUS just as `wait' would. */
8509
8510 ptid_t
8511 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8512 target_wait_flags options)
8513 {
8514 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8515
8516 remote_state *rs = get_remote_state ();
8517
8518 /* Start by clearing the flag that asks for our wait method to be called,
8519 we'll mark it again at the end if needed. If the target is not in
8520 async mode then the async token should not be marked. */
8521 if (target_is_async_p ())
8522 clear_async_event_handler (rs->remote_async_inferior_event_token);
8523 else
8524 gdb_assert (!async_event_handler_marked
8525 (rs->remote_async_inferior_event_token));
8526
8527 ptid_t event_ptid;
8528
8529 if (target_is_non_stop_p ())
8530 event_ptid = wait_ns (ptid, status, options);
8531 else
8532 event_ptid = wait_as (ptid, status, options);
8533
8534 if (target_is_async_p ())
8535 {
8536 /* If there are events left in the queue, or unacknowledged
8537 notifications, then tell the event loop to call us again. */
8538 if (!rs->stop_reply_queue.empty ()
8539 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8540 mark_async_event_handler (rs->remote_async_inferior_event_token);
8541 }
8542
8543 return event_ptid;
8544 }
8545
8546 /* Fetch a single register using a 'p' packet. */
8547
8548 int
8549 remote_target::fetch_register_using_p (struct regcache *regcache,
8550 packet_reg *reg)
8551 {
8552 struct gdbarch *gdbarch = regcache->arch ();
8553 struct remote_state *rs = get_remote_state ();
8554 char *buf, *p;
8555 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8556 int i;
8557
8558 if (m_features.packet_support (PACKET_p) == PACKET_DISABLE)
8559 return 0;
8560
8561 if (reg->pnum == -1)
8562 return 0;
8563
8564 p = rs->buf.data ();
8565 *p++ = 'p';
8566 p += hexnumstr (p, reg->pnum);
8567 *p++ = '\0';
8568 putpkt (rs->buf);
8569 getpkt (&rs->buf, 0);
8570
8571 buf = rs->buf.data ();
8572
8573 switch (m_features.packet_ok (rs->buf, PACKET_p))
8574 {
8575 case PACKET_OK:
8576 break;
8577 case PACKET_UNKNOWN:
8578 return 0;
8579 case PACKET_ERROR:
8580 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8581 gdbarch_register_name (regcache->arch (),
8582 reg->regnum),
8583 buf);
8584 }
8585
8586 /* If this register is unfetchable, tell the regcache. */
8587 if (buf[0] == 'x')
8588 {
8589 regcache->raw_supply (reg->regnum, NULL);
8590 return 1;
8591 }
8592
8593 /* Otherwise, parse and supply the value. */
8594 p = buf;
8595 i = 0;
8596 while (p[0] != 0)
8597 {
8598 if (p[1] == 0)
8599 error (_("fetch_register_using_p: early buf termination"));
8600
8601 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8602 p += 2;
8603 }
8604 regcache->raw_supply (reg->regnum, regp);
8605 return 1;
8606 }
8607
8608 /* Fetch the registers included in the target's 'g' packet. */
8609
8610 int
8611 remote_target::send_g_packet ()
8612 {
8613 struct remote_state *rs = get_remote_state ();
8614 int buf_len;
8615
8616 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8617 putpkt (rs->buf);
8618 getpkt (&rs->buf, 0);
8619 if (packet_check_result (rs->buf) == PACKET_ERROR)
8620 error (_("Could not read registers; remote failure reply '%s'"),
8621 rs->buf.data ());
8622
8623 /* We can get out of synch in various cases. If the first character
8624 in the buffer is not a hex character, assume that has happened
8625 and try to fetch another packet to read. */
8626 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8627 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8628 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8629 && rs->buf[0] != 'x') /* New: unavailable register value. */
8630 {
8631 remote_debug_printf ("Bad register packet; fetching a new packet");
8632 getpkt (&rs->buf, 0);
8633 }
8634
8635 buf_len = strlen (rs->buf.data ());
8636
8637 /* Sanity check the received packet. */
8638 if (buf_len % 2 != 0)
8639 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8640
8641 return buf_len / 2;
8642 }
8643
8644 void
8645 remote_target::process_g_packet (struct regcache *regcache)
8646 {
8647 struct gdbarch *gdbarch = regcache->arch ();
8648 struct remote_state *rs = get_remote_state ();
8649 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8650 int i, buf_len;
8651 char *p;
8652 char *regs;
8653
8654 buf_len = strlen (rs->buf.data ());
8655
8656 /* Further sanity checks, with knowledge of the architecture. */
8657 if (buf_len > 2 * rsa->sizeof_g_packet)
8658 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8659 "bytes): %s"),
8660 rsa->sizeof_g_packet, buf_len / 2,
8661 rs->buf.data ());
8662
8663 /* Save the size of the packet sent to us by the target. It is used
8664 as a heuristic when determining the max size of packets that the
8665 target can safely receive. */
8666 if (rsa->actual_register_packet_size == 0)
8667 rsa->actual_register_packet_size = buf_len;
8668
8669 /* If this is smaller than we guessed the 'g' packet would be,
8670 update our records. A 'g' reply that doesn't include a register's
8671 value implies either that the register is not available, or that
8672 the 'p' packet must be used. */
8673 if (buf_len < 2 * rsa->sizeof_g_packet)
8674 {
8675 long sizeof_g_packet = buf_len / 2;
8676
8677 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8678 {
8679 long offset = rsa->regs[i].offset;
8680 long reg_size = register_size (gdbarch, i);
8681
8682 if (rsa->regs[i].pnum == -1)
8683 continue;
8684
8685 if (offset >= sizeof_g_packet)
8686 rsa->regs[i].in_g_packet = 0;
8687 else if (offset + reg_size > sizeof_g_packet)
8688 error (_("Truncated register %d in remote 'g' packet"), i);
8689 else
8690 rsa->regs[i].in_g_packet = 1;
8691 }
8692
8693 /* Looks valid enough, we can assume this is the correct length
8694 for a 'g' packet. It's important not to adjust
8695 rsa->sizeof_g_packet if we have truncated registers otherwise
8696 this "if" won't be run the next time the method is called
8697 with a packet of the same size and one of the internal errors
8698 below will trigger instead. */
8699 rsa->sizeof_g_packet = sizeof_g_packet;
8700 }
8701
8702 regs = (char *) alloca (rsa->sizeof_g_packet);
8703
8704 /* Unimplemented registers read as all bits zero. */
8705 memset (regs, 0, rsa->sizeof_g_packet);
8706
8707 /* Reply describes registers byte by byte, each byte encoded as two
8708 hex characters. Suck them all up, then supply them to the
8709 register cacheing/storage mechanism. */
8710
8711 p = rs->buf.data ();
8712 for (i = 0; i < rsa->sizeof_g_packet; i++)
8713 {
8714 if (p[0] == 0 || p[1] == 0)
8715 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8716 internal_error (_("unexpected end of 'g' packet reply"));
8717
8718 if (p[0] == 'x' && p[1] == 'x')
8719 regs[i] = 0; /* 'x' */
8720 else
8721 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8722 p += 2;
8723 }
8724
8725 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8726 {
8727 struct packet_reg *r = &rsa->regs[i];
8728 long reg_size = register_size (gdbarch, i);
8729
8730 if (r->in_g_packet)
8731 {
8732 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8733 /* This shouldn't happen - we adjusted in_g_packet above. */
8734 internal_error (_("unexpected end of 'g' packet reply"));
8735 else if (rs->buf[r->offset * 2] == 'x')
8736 {
8737 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8738 /* The register isn't available, mark it as such (at
8739 the same time setting the value to zero). */
8740 regcache->raw_supply (r->regnum, NULL);
8741 }
8742 else
8743 regcache->raw_supply (r->regnum, regs + r->offset);
8744 }
8745 }
8746 }
8747
8748 void
8749 remote_target::fetch_registers_using_g (struct regcache *regcache)
8750 {
8751 send_g_packet ();
8752 process_g_packet (regcache);
8753 }
8754
8755 /* Make the remote selected traceframe match GDB's selected
8756 traceframe. */
8757
8758 void
8759 remote_target::set_remote_traceframe ()
8760 {
8761 int newnum;
8762 struct remote_state *rs = get_remote_state ();
8763
8764 if (rs->remote_traceframe_number == get_traceframe_number ())
8765 return;
8766
8767 /* Avoid recursion, remote_trace_find calls us again. */
8768 rs->remote_traceframe_number = get_traceframe_number ();
8769
8770 newnum = target_trace_find (tfind_number,
8771 get_traceframe_number (), 0, 0, NULL);
8772
8773 /* Should not happen. If it does, all bets are off. */
8774 if (newnum != get_traceframe_number ())
8775 warning (_("could not set remote traceframe"));
8776 }
8777
8778 void
8779 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8780 {
8781 struct gdbarch *gdbarch = regcache->arch ();
8782 struct remote_state *rs = get_remote_state ();
8783 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8784 int i;
8785
8786 set_remote_traceframe ();
8787 set_general_thread (regcache->ptid ());
8788
8789 if (regnum >= 0)
8790 {
8791 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8792
8793 gdb_assert (reg != NULL);
8794
8795 /* If this register might be in the 'g' packet, try that first -
8796 we are likely to read more than one register. If this is the
8797 first 'g' packet, we might be overly optimistic about its
8798 contents, so fall back to 'p'. */
8799 if (reg->in_g_packet)
8800 {
8801 fetch_registers_using_g (regcache);
8802 if (reg->in_g_packet)
8803 return;
8804 }
8805
8806 if (fetch_register_using_p (regcache, reg))
8807 return;
8808
8809 /* This register is not available. */
8810 regcache->raw_supply (reg->regnum, NULL);
8811
8812 return;
8813 }
8814
8815 fetch_registers_using_g (regcache);
8816
8817 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8818 if (!rsa->regs[i].in_g_packet)
8819 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8820 {
8821 /* This register is not available. */
8822 regcache->raw_supply (i, NULL);
8823 }
8824 }
8825
8826 /* Prepare to store registers. Since we may send them all (using a
8827 'G' request), we have to read out the ones we don't want to change
8828 first. */
8829
8830 void
8831 remote_target::prepare_to_store (struct regcache *regcache)
8832 {
8833 struct remote_state *rs = get_remote_state ();
8834 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8835 int i;
8836
8837 /* Make sure the entire registers array is valid. */
8838 switch (m_features.packet_support (PACKET_P))
8839 {
8840 case PACKET_DISABLE:
8841 case PACKET_SUPPORT_UNKNOWN:
8842 /* Make sure all the necessary registers are cached. */
8843 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8844 if (rsa->regs[i].in_g_packet)
8845 regcache->raw_update (rsa->regs[i].regnum);
8846 break;
8847 case PACKET_ENABLE:
8848 break;
8849 }
8850 }
8851
8852 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8853 packet was not recognized. */
8854
8855 int
8856 remote_target::store_register_using_P (const struct regcache *regcache,
8857 packet_reg *reg)
8858 {
8859 struct gdbarch *gdbarch = regcache->arch ();
8860 struct remote_state *rs = get_remote_state ();
8861 /* Try storing a single register. */
8862 char *buf = rs->buf.data ();
8863 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8864 char *p;
8865
8866 if (m_features.packet_support (PACKET_P) == PACKET_DISABLE)
8867 return 0;
8868
8869 if (reg->pnum == -1)
8870 return 0;
8871
8872 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8873 p = buf + strlen (buf);
8874 regcache->raw_collect (reg->regnum, regp);
8875 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8876 putpkt (rs->buf);
8877 getpkt (&rs->buf, 0);
8878
8879 switch (m_features.packet_ok (rs->buf, PACKET_P))
8880 {
8881 case PACKET_OK:
8882 return 1;
8883 case PACKET_ERROR:
8884 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8885 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
8886 case PACKET_UNKNOWN:
8887 return 0;
8888 default:
8889 internal_error (_("Bad result from packet_ok"));
8890 }
8891 }
8892
8893 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8894 contents of the register cache buffer. FIXME: ignores errors. */
8895
8896 void
8897 remote_target::store_registers_using_G (const struct regcache *regcache)
8898 {
8899 struct remote_state *rs = get_remote_state ();
8900 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8901 gdb_byte *regs;
8902 char *p;
8903
8904 /* Extract all the registers in the regcache copying them into a
8905 local buffer. */
8906 {
8907 int i;
8908
8909 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8910 memset (regs, 0, rsa->sizeof_g_packet);
8911 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8912 {
8913 struct packet_reg *r = &rsa->regs[i];
8914
8915 if (r->in_g_packet)
8916 regcache->raw_collect (r->regnum, regs + r->offset);
8917 }
8918 }
8919
8920 /* Command describes registers byte by byte,
8921 each byte encoded as two hex characters. */
8922 p = rs->buf.data ();
8923 *p++ = 'G';
8924 bin2hex (regs, p, rsa->sizeof_g_packet);
8925 putpkt (rs->buf);
8926 getpkt (&rs->buf, 0);
8927 if (packet_check_result (rs->buf) == PACKET_ERROR)
8928 error (_("Could not write registers; remote failure reply '%s'"),
8929 rs->buf.data ());
8930 }
8931
8932 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8933 of the register cache buffer. FIXME: ignores errors. */
8934
8935 void
8936 remote_target::store_registers (struct regcache *regcache, int regnum)
8937 {
8938 struct gdbarch *gdbarch = regcache->arch ();
8939 struct remote_state *rs = get_remote_state ();
8940 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8941 int i;
8942
8943 set_remote_traceframe ();
8944 set_general_thread (regcache->ptid ());
8945
8946 if (regnum >= 0)
8947 {
8948 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8949
8950 gdb_assert (reg != NULL);
8951
8952 /* Always prefer to store registers using the 'P' packet if
8953 possible; we often change only a small number of registers.
8954 Sometimes we change a larger number; we'd need help from a
8955 higher layer to know to use 'G'. */
8956 if (store_register_using_P (regcache, reg))
8957 return;
8958
8959 /* For now, don't complain if we have no way to write the
8960 register. GDB loses track of unavailable registers too
8961 easily. Some day, this may be an error. We don't have
8962 any way to read the register, either... */
8963 if (!reg->in_g_packet)
8964 return;
8965
8966 store_registers_using_G (regcache);
8967 return;
8968 }
8969
8970 store_registers_using_G (regcache);
8971
8972 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8973 if (!rsa->regs[i].in_g_packet)
8974 if (!store_register_using_P (regcache, &rsa->regs[i]))
8975 /* See above for why we do not issue an error here. */
8976 continue;
8977 }
8978 \f
8979
8980 /* Return the number of hex digits in num. */
8981
8982 static int
8983 hexnumlen (ULONGEST num)
8984 {
8985 int i;
8986
8987 for (i = 0; num != 0; i++)
8988 num >>= 4;
8989
8990 return std::max (i, 1);
8991 }
8992
8993 /* Set BUF to the minimum number of hex digits representing NUM. */
8994
8995 static int
8996 hexnumstr (char *buf, ULONGEST num)
8997 {
8998 int len = hexnumlen (num);
8999
9000 return hexnumnstr (buf, num, len);
9001 }
9002
9003
9004 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
9005
9006 static int
9007 hexnumnstr (char *buf, ULONGEST num, int width)
9008 {
9009 int i;
9010
9011 buf[width] = '\0';
9012
9013 for (i = width - 1; i >= 0; i--)
9014 {
9015 buf[i] = "0123456789abcdef"[(num & 0xf)];
9016 num >>= 4;
9017 }
9018
9019 return width;
9020 }
9021
9022 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
9023
9024 static CORE_ADDR
9025 remote_address_masked (CORE_ADDR addr)
9026 {
9027 unsigned int address_size = remote_address_size;
9028
9029 /* If "remoteaddresssize" was not set, default to target address size. */
9030 if (!address_size)
9031 address_size = gdbarch_addr_bit (target_gdbarch ());
9032
9033 if (address_size > 0
9034 && address_size < (sizeof (ULONGEST) * 8))
9035 {
9036 /* Only create a mask when that mask can safely be constructed
9037 in a ULONGEST variable. */
9038 ULONGEST mask = 1;
9039
9040 mask = (mask << address_size) - 1;
9041 addr &= mask;
9042 }
9043 return addr;
9044 }
9045
9046 /* Determine whether the remote target supports binary downloading.
9047 This is accomplished by sending a no-op memory write of zero length
9048 to the target at the specified address. It does not suffice to send
9049 the whole packet, since many stubs strip the eighth bit and
9050 subsequently compute a wrong checksum, which causes real havoc with
9051 remote_write_bytes.
9052
9053 NOTE: This can still lose if the serial line is not eight-bit
9054 clean. In cases like this, the user should clear "remote
9055 X-packet". */
9056
9057 void
9058 remote_target::check_binary_download (CORE_ADDR addr)
9059 {
9060 struct remote_state *rs = get_remote_state ();
9061
9062 switch (m_features.packet_support (PACKET_X))
9063 {
9064 case PACKET_DISABLE:
9065 break;
9066 case PACKET_ENABLE:
9067 break;
9068 case PACKET_SUPPORT_UNKNOWN:
9069 {
9070 char *p;
9071
9072 p = rs->buf.data ();
9073 *p++ = 'X';
9074 p += hexnumstr (p, (ULONGEST) addr);
9075 *p++ = ',';
9076 p += hexnumstr (p, (ULONGEST) 0);
9077 *p++ = ':';
9078 *p = '\0';
9079
9080 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9081 getpkt (&rs->buf, 0);
9082
9083 if (rs->buf[0] == '\0')
9084 {
9085 remote_debug_printf ("binary downloading NOT supported by target");
9086 m_features.m_protocol_packets[PACKET_X].support = PACKET_DISABLE;
9087 }
9088 else
9089 {
9090 remote_debug_printf ("binary downloading supported by target");
9091 m_features.m_protocol_packets[PACKET_X].support = PACKET_ENABLE;
9092 }
9093 break;
9094 }
9095 }
9096 }
9097
9098 /* Helper function to resize the payload in order to try to get a good
9099 alignment. We try to write an amount of data such that the next write will
9100 start on an address aligned on REMOTE_ALIGN_WRITES. */
9101
9102 static int
9103 align_for_efficient_write (int todo, CORE_ADDR memaddr)
9104 {
9105 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
9106 }
9107
9108 /* Write memory data directly to the remote machine.
9109 This does not inform the data cache; the data cache uses this.
9110 HEADER is the starting part of the packet.
9111 MEMADDR is the address in the remote memory space.
9112 MYADDR is the address of the buffer in our space.
9113 LEN_UNITS is the number of addressable units to write.
9114 UNIT_SIZE is the length in bytes of an addressable unit.
9115 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9116 should send data as binary ('X'), or hex-encoded ('M').
9117
9118 The function creates packet of the form
9119 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9120
9121 where encoding of <DATA> is terminated by PACKET_FORMAT.
9122
9123 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9124 are omitted.
9125
9126 Return the transferred status, error or OK (an
9127 'enum target_xfer_status' value). Save the number of addressable units
9128 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9129
9130 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9131 exchange between gdb and the stub could look like (?? in place of the
9132 checksum):
9133
9134 -> $m1000,4#??
9135 <- aaaabbbbccccdddd
9136
9137 -> $M1000,3:eeeeffffeeee#??
9138 <- OK
9139
9140 -> $m1000,4#??
9141 <- eeeeffffeeeedddd */
9142
9143 target_xfer_status
9144 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
9145 const gdb_byte *myaddr,
9146 ULONGEST len_units,
9147 int unit_size,
9148 ULONGEST *xfered_len_units,
9149 char packet_format, int use_length)
9150 {
9151 struct remote_state *rs = get_remote_state ();
9152 char *p;
9153 char *plen = NULL;
9154 int plenlen = 0;
9155 int todo_units;
9156 int units_written;
9157 int payload_capacity_bytes;
9158 int payload_length_bytes;
9159
9160 if (packet_format != 'X' && packet_format != 'M')
9161 internal_error (_("remote_write_bytes_aux: bad packet format"));
9162
9163 if (len_units == 0)
9164 return TARGET_XFER_EOF;
9165
9166 payload_capacity_bytes = get_memory_write_packet_size ();
9167
9168 /* The packet buffer will be large enough for the payload;
9169 get_memory_packet_size ensures this. */
9170 rs->buf[0] = '\0';
9171
9172 /* Compute the size of the actual payload by subtracting out the
9173 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9174
9175 payload_capacity_bytes -= strlen ("$,:#NN");
9176 if (!use_length)
9177 /* The comma won't be used. */
9178 payload_capacity_bytes += 1;
9179 payload_capacity_bytes -= strlen (header);
9180 payload_capacity_bytes -= hexnumlen (memaddr);
9181
9182 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9183
9184 strcat (rs->buf.data (), header);
9185 p = rs->buf.data () + strlen (header);
9186
9187 /* Compute a best guess of the number of bytes actually transfered. */
9188 if (packet_format == 'X')
9189 {
9190 /* Best guess at number of bytes that will fit. */
9191 todo_units = std::min (len_units,
9192 (ULONGEST) payload_capacity_bytes / unit_size);
9193 if (use_length)
9194 payload_capacity_bytes -= hexnumlen (todo_units);
9195 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9196 }
9197 else
9198 {
9199 /* Number of bytes that will fit. */
9200 todo_units
9201 = std::min (len_units,
9202 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9203 if (use_length)
9204 payload_capacity_bytes -= hexnumlen (todo_units);
9205 todo_units = std::min (todo_units,
9206 (payload_capacity_bytes / unit_size) / 2);
9207 }
9208
9209 if (todo_units <= 0)
9210 internal_error (_("minimum packet size too small to write data"));
9211
9212 /* If we already need another packet, then try to align the end
9213 of this packet to a useful boundary. */
9214 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9215 todo_units = align_for_efficient_write (todo_units, memaddr);
9216
9217 /* Append "<memaddr>". */
9218 memaddr = remote_address_masked (memaddr);
9219 p += hexnumstr (p, (ULONGEST) memaddr);
9220
9221 if (use_length)
9222 {
9223 /* Append ",". */
9224 *p++ = ',';
9225
9226 /* Append the length and retain its location and size. It may need to be
9227 adjusted once the packet body has been created. */
9228 plen = p;
9229 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9230 p += plenlen;
9231 }
9232
9233 /* Append ":". */
9234 *p++ = ':';
9235 *p = '\0';
9236
9237 /* Append the packet body. */
9238 if (packet_format == 'X')
9239 {
9240 /* Binary mode. Send target system values byte by byte, in
9241 increasing byte addresses. Only escape certain critical
9242 characters. */
9243 payload_length_bytes =
9244 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9245 &units_written, payload_capacity_bytes);
9246
9247 /* If not all TODO units fit, then we'll need another packet. Make
9248 a second try to keep the end of the packet aligned. Don't do
9249 this if the packet is tiny. */
9250 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9251 {
9252 int new_todo_units;
9253
9254 new_todo_units = align_for_efficient_write (units_written, memaddr);
9255
9256 if (new_todo_units != units_written)
9257 payload_length_bytes =
9258 remote_escape_output (myaddr, new_todo_units, unit_size,
9259 (gdb_byte *) p, &units_written,
9260 payload_capacity_bytes);
9261 }
9262
9263 p += payload_length_bytes;
9264 if (use_length && units_written < todo_units)
9265 {
9266 /* Escape chars have filled up the buffer prematurely,
9267 and we have actually sent fewer units than planned.
9268 Fix-up the length field of the packet. Use the same
9269 number of characters as before. */
9270 plen += hexnumnstr (plen, (ULONGEST) units_written,
9271 plenlen);
9272 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9273 }
9274 }
9275 else
9276 {
9277 /* Normal mode: Send target system values byte by byte, in
9278 increasing byte addresses. Each byte is encoded as a two hex
9279 value. */
9280 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9281 units_written = todo_units;
9282 }
9283
9284 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9285 getpkt (&rs->buf, 0);
9286
9287 if (rs->buf[0] == 'E')
9288 return TARGET_XFER_E_IO;
9289
9290 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9291 send fewer units than we'd planned. */
9292 *xfered_len_units = (ULONGEST) units_written;
9293 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9294 }
9295
9296 /* Write memory data directly to the remote machine.
9297 This does not inform the data cache; the data cache uses this.
9298 MEMADDR is the address in the remote memory space.
9299 MYADDR is the address of the buffer in our space.
9300 LEN is the number of bytes.
9301
9302 Return the transferred status, error or OK (an
9303 'enum target_xfer_status' value). Save the number of bytes
9304 transferred in *XFERED_LEN. Only transfer a single packet. */
9305
9306 target_xfer_status
9307 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9308 ULONGEST len, int unit_size,
9309 ULONGEST *xfered_len)
9310 {
9311 const char *packet_format = NULL;
9312
9313 /* Check whether the target supports binary download. */
9314 check_binary_download (memaddr);
9315
9316 switch (m_features.packet_support (PACKET_X))
9317 {
9318 case PACKET_ENABLE:
9319 packet_format = "X";
9320 break;
9321 case PACKET_DISABLE:
9322 packet_format = "M";
9323 break;
9324 case PACKET_SUPPORT_UNKNOWN:
9325 internal_error (_("remote_write_bytes: bad internal state"));
9326 default:
9327 internal_error (_("bad switch"));
9328 }
9329
9330 return remote_write_bytes_aux (packet_format,
9331 memaddr, myaddr, len, unit_size, xfered_len,
9332 packet_format[0], 1);
9333 }
9334
9335 /* Read memory data directly from the remote machine.
9336 This does not use the data cache; the data cache uses this.
9337 MEMADDR is the address in the remote memory space.
9338 MYADDR is the address of the buffer in our space.
9339 LEN_UNITS is the number of addressable memory units to read..
9340 UNIT_SIZE is the length in bytes of an addressable unit.
9341
9342 Return the transferred status, error or OK (an
9343 'enum target_xfer_status' value). Save the number of bytes
9344 transferred in *XFERED_LEN_UNITS.
9345
9346 See the comment of remote_write_bytes_aux for an example of
9347 memory read/write exchange between gdb and the stub. */
9348
9349 target_xfer_status
9350 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9351 ULONGEST len_units,
9352 int unit_size, ULONGEST *xfered_len_units)
9353 {
9354 struct remote_state *rs = get_remote_state ();
9355 int buf_size_bytes; /* Max size of packet output buffer. */
9356 char *p;
9357 int todo_units;
9358 int decoded_bytes;
9359
9360 buf_size_bytes = get_memory_read_packet_size ();
9361 /* The packet buffer will be large enough for the payload;
9362 get_memory_packet_size ensures this. */
9363
9364 /* Number of units that will fit. */
9365 todo_units = std::min (len_units,
9366 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9367
9368 /* Construct "m"<memaddr>","<len>". */
9369 memaddr = remote_address_masked (memaddr);
9370 p = rs->buf.data ();
9371 *p++ = 'm';
9372 p += hexnumstr (p, (ULONGEST) memaddr);
9373 *p++ = ',';
9374 p += hexnumstr (p, (ULONGEST) todo_units);
9375 *p = '\0';
9376 putpkt (rs->buf);
9377 getpkt (&rs->buf, 0);
9378 if (rs->buf[0] == 'E'
9379 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9380 && rs->buf[3] == '\0')
9381 return TARGET_XFER_E_IO;
9382 /* Reply describes memory byte by byte, each byte encoded as two hex
9383 characters. */
9384 p = rs->buf.data ();
9385 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9386 /* Return what we have. Let higher layers handle partial reads. */
9387 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9388 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9389 }
9390
9391 /* Using the set of read-only target sections of remote, read live
9392 read-only memory.
9393
9394 For interface/parameters/return description see target.h,
9395 to_xfer_partial. */
9396
9397 target_xfer_status
9398 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9399 ULONGEST memaddr,
9400 ULONGEST len,
9401 int unit_size,
9402 ULONGEST *xfered_len)
9403 {
9404 const struct target_section *secp;
9405
9406 secp = target_section_by_addr (this, memaddr);
9407 if (secp != NULL
9408 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9409 {
9410 ULONGEST memend = memaddr + len;
9411
9412 const target_section_table *table = target_get_section_table (this);
9413 for (const target_section &p : *table)
9414 {
9415 if (memaddr >= p.addr)
9416 {
9417 if (memend <= p.endaddr)
9418 {
9419 /* Entire transfer is within this section. */
9420 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9421 xfered_len);
9422 }
9423 else if (memaddr >= p.endaddr)
9424 {
9425 /* This section ends before the transfer starts. */
9426 continue;
9427 }
9428 else
9429 {
9430 /* This section overlaps the transfer. Just do half. */
9431 len = p.endaddr - memaddr;
9432 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9433 xfered_len);
9434 }
9435 }
9436 }
9437 }
9438
9439 return TARGET_XFER_EOF;
9440 }
9441
9442 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9443 first if the requested memory is unavailable in traceframe.
9444 Otherwise, fall back to remote_read_bytes_1. */
9445
9446 target_xfer_status
9447 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9448 gdb_byte *myaddr, ULONGEST len, int unit_size,
9449 ULONGEST *xfered_len)
9450 {
9451 if (len == 0)
9452 return TARGET_XFER_EOF;
9453
9454 if (get_traceframe_number () != -1)
9455 {
9456 std::vector<mem_range> available;
9457
9458 /* If we fail to get the set of available memory, then the
9459 target does not support querying traceframe info, and so we
9460 attempt reading from the traceframe anyway (assuming the
9461 target implements the old QTro packet then). */
9462 if (traceframe_available_memory (&available, memaddr, len))
9463 {
9464 if (available.empty () || available[0].start != memaddr)
9465 {
9466 enum target_xfer_status res;
9467
9468 /* Don't read into the traceframe's available
9469 memory. */
9470 if (!available.empty ())
9471 {
9472 LONGEST oldlen = len;
9473
9474 len = available[0].start - memaddr;
9475 gdb_assert (len <= oldlen);
9476 }
9477
9478 /* This goes through the topmost target again. */
9479 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9480 len, unit_size, xfered_len);
9481 if (res == TARGET_XFER_OK)
9482 return TARGET_XFER_OK;
9483 else
9484 {
9485 /* No use trying further, we know some memory starting
9486 at MEMADDR isn't available. */
9487 *xfered_len = len;
9488 return (*xfered_len != 0) ?
9489 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9490 }
9491 }
9492
9493 /* Don't try to read more than how much is available, in
9494 case the target implements the deprecated QTro packet to
9495 cater for older GDBs (the target's knowledge of read-only
9496 sections may be outdated by now). */
9497 len = available[0].length;
9498 }
9499 }
9500
9501 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9502 }
9503
9504 \f
9505
9506 /* Sends a packet with content determined by the printf format string
9507 FORMAT and the remaining arguments, then gets the reply. Returns
9508 whether the packet was a success, a failure, or unknown. */
9509
9510 packet_result
9511 remote_target::remote_send_printf (const char *format, ...)
9512 {
9513 struct remote_state *rs = get_remote_state ();
9514 int max_size = get_remote_packet_size ();
9515 va_list ap;
9516
9517 va_start (ap, format);
9518
9519 rs->buf[0] = '\0';
9520 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9521
9522 va_end (ap);
9523
9524 if (size >= max_size)
9525 internal_error (_("Too long remote packet."));
9526
9527 if (putpkt (rs->buf) < 0)
9528 error (_("Communication problem with target."));
9529
9530 rs->buf[0] = '\0';
9531 getpkt (&rs->buf, 0);
9532
9533 return packet_check_result (rs->buf);
9534 }
9535
9536 /* Flash writing can take quite some time. We'll set
9537 effectively infinite timeout for flash operations.
9538 In future, we'll need to decide on a better approach. */
9539 static const int remote_flash_timeout = 1000;
9540
9541 void
9542 remote_target::flash_erase (ULONGEST address, LONGEST length)
9543 {
9544 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9545 enum packet_result ret;
9546 scoped_restore restore_timeout
9547 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9548
9549 ret = remote_send_printf ("vFlashErase:%s,%s",
9550 phex (address, addr_size),
9551 phex (length, 4));
9552 switch (ret)
9553 {
9554 case PACKET_UNKNOWN:
9555 error (_("Remote target does not support flash erase"));
9556 case PACKET_ERROR:
9557 error (_("Error erasing flash with vFlashErase packet"));
9558 default:
9559 break;
9560 }
9561 }
9562
9563 target_xfer_status
9564 remote_target::remote_flash_write (ULONGEST address,
9565 ULONGEST length, ULONGEST *xfered_len,
9566 const gdb_byte *data)
9567 {
9568 scoped_restore restore_timeout
9569 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9570 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9571 xfered_len,'X', 0);
9572 }
9573
9574 void
9575 remote_target::flash_done ()
9576 {
9577 int ret;
9578
9579 scoped_restore restore_timeout
9580 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9581
9582 ret = remote_send_printf ("vFlashDone");
9583
9584 switch (ret)
9585 {
9586 case PACKET_UNKNOWN:
9587 error (_("Remote target does not support vFlashDone"));
9588 case PACKET_ERROR:
9589 error (_("Error finishing flash operation"));
9590 default:
9591 break;
9592 }
9593 }
9594
9595 \f
9596 /* Stuff for dealing with the packets which are part of this protocol.
9597 See comment at top of file for details. */
9598
9599 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9600 error to higher layers. Called when a serial error is detected.
9601 The exception message is STRING, followed by a colon and a blank,
9602 the system error message for errno at function entry and final dot
9603 for output compatibility with throw_perror_with_name. */
9604
9605 static void
9606 unpush_and_perror (remote_target *target, const char *string)
9607 {
9608 int saved_errno = errno;
9609
9610 remote_unpush_target (target);
9611 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9612 safe_strerror (saved_errno));
9613 }
9614
9615 /* Read a single character from the remote end. The current quit
9616 handler is overridden to avoid quitting in the middle of packet
9617 sequence, as that would break communication with the remote server.
9618 See remote_serial_quit_handler for more detail. */
9619
9620 int
9621 remote_target::readchar (int timeout)
9622 {
9623 int ch;
9624 struct remote_state *rs = get_remote_state ();
9625
9626 {
9627 scoped_restore restore_quit_target
9628 = make_scoped_restore (&curr_quit_handler_target, this);
9629 scoped_restore restore_quit
9630 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9631
9632 rs->got_ctrlc_during_io = 0;
9633
9634 ch = serial_readchar (rs->remote_desc, timeout);
9635
9636 if (rs->got_ctrlc_during_io)
9637 set_quit_flag ();
9638 }
9639
9640 if (ch >= 0)
9641 return ch;
9642
9643 switch ((enum serial_rc) ch)
9644 {
9645 case SERIAL_EOF:
9646 remote_unpush_target (this);
9647 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9648 /* no return */
9649 case SERIAL_ERROR:
9650 unpush_and_perror (this, _("Remote communication error. "
9651 "Target disconnected."));
9652 /* no return */
9653 case SERIAL_TIMEOUT:
9654 break;
9655 }
9656 return ch;
9657 }
9658
9659 /* Wrapper for serial_write that closes the target and throws if
9660 writing fails. The current quit handler is overridden to avoid
9661 quitting in the middle of packet sequence, as that would break
9662 communication with the remote server. See
9663 remote_serial_quit_handler for more detail. */
9664
9665 void
9666 remote_target::remote_serial_write (const char *str, int len)
9667 {
9668 struct remote_state *rs = get_remote_state ();
9669
9670 scoped_restore restore_quit_target
9671 = make_scoped_restore (&curr_quit_handler_target, this);
9672 scoped_restore restore_quit
9673 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9674
9675 rs->got_ctrlc_during_io = 0;
9676
9677 if (serial_write (rs->remote_desc, str, len))
9678 {
9679 unpush_and_perror (this, _("Remote communication error. "
9680 "Target disconnected."));
9681 }
9682
9683 if (rs->got_ctrlc_during_io)
9684 set_quit_flag ();
9685 }
9686
9687 /* Return a string representing an escaped version of BUF, of len N.
9688 E.g. \n is converted to \\n, \t to \\t, etc. */
9689
9690 static std::string
9691 escape_buffer (const char *buf, int n)
9692 {
9693 string_file stb;
9694
9695 stb.putstrn (buf, n, '\\');
9696 return stb.release ();
9697 }
9698
9699 int
9700 remote_target::putpkt (const char *buf)
9701 {
9702 return putpkt_binary (buf, strlen (buf));
9703 }
9704
9705 /* Wrapper around remote_target::putpkt to avoid exporting
9706 remote_target. */
9707
9708 int
9709 putpkt (remote_target *remote, const char *buf)
9710 {
9711 return remote->putpkt (buf);
9712 }
9713
9714 /* Send a packet to the remote machine, with error checking. The data
9715 of the packet is in BUF. The string in BUF can be at most
9716 get_remote_packet_size () - 5 to account for the $, # and checksum,
9717 and for a possible /0 if we are debugging (remote_debug) and want
9718 to print the sent packet as a string. */
9719
9720 int
9721 remote_target::putpkt_binary (const char *buf, int cnt)
9722 {
9723 struct remote_state *rs = get_remote_state ();
9724 int i;
9725 unsigned char csum = 0;
9726 gdb::def_vector<char> data (cnt + 6);
9727 char *buf2 = data.data ();
9728
9729 int ch;
9730 int tcount = 0;
9731 char *p;
9732
9733 /* Catch cases like trying to read memory or listing threads while
9734 we're waiting for a stop reply. The remote server wouldn't be
9735 ready to handle this request, so we'd hang and timeout. We don't
9736 have to worry about this in synchronous mode, because in that
9737 case it's not possible to issue a command while the target is
9738 running. This is not a problem in non-stop mode, because in that
9739 case, the stub is always ready to process serial input. */
9740 if (!target_is_non_stop_p ()
9741 && target_is_async_p ()
9742 && rs->waiting_for_stop_reply)
9743 {
9744 error (_("Cannot execute this command while the target is running.\n"
9745 "Use the \"interrupt\" command to stop the target\n"
9746 "and then try again."));
9747 }
9748
9749 /* Copy the packet into buffer BUF2, encapsulating it
9750 and giving it a checksum. */
9751
9752 p = buf2;
9753 *p++ = '$';
9754
9755 for (i = 0; i < cnt; i++)
9756 {
9757 csum += buf[i];
9758 *p++ = buf[i];
9759 }
9760 *p++ = '#';
9761 *p++ = tohex ((csum >> 4) & 0xf);
9762 *p++ = tohex (csum & 0xf);
9763
9764 /* Send it over and over until we get a positive ack. */
9765
9766 while (1)
9767 {
9768 if (remote_debug)
9769 {
9770 *p = '\0';
9771
9772 int len = (int) (p - buf2);
9773 int max_chars;
9774
9775 if (remote_packet_max_chars < 0)
9776 max_chars = len;
9777 else
9778 max_chars = remote_packet_max_chars;
9779
9780 std::string str
9781 = escape_buffer (buf2, std::min (len, max_chars));
9782
9783 if (len > max_chars)
9784 remote_debug_printf_nofunc
9785 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9786 len - max_chars);
9787 else
9788 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9789 }
9790 remote_serial_write (buf2, p - buf2);
9791
9792 /* If this is a no acks version of the remote protocol, send the
9793 packet and move on. */
9794 if (rs->noack_mode)
9795 break;
9796
9797 /* Read until either a timeout occurs (-2) or '+' is read.
9798 Handle any notification that arrives in the mean time. */
9799 while (1)
9800 {
9801 ch = readchar (remote_timeout);
9802
9803 switch (ch)
9804 {
9805 case '+':
9806 remote_debug_printf_nofunc ("Received Ack");
9807 return 1;
9808 case '-':
9809 remote_debug_printf_nofunc ("Received Nak");
9810 /* FALLTHROUGH */
9811 case SERIAL_TIMEOUT:
9812 tcount++;
9813 if (tcount > 3)
9814 return 0;
9815 break; /* Retransmit buffer. */
9816 case '$':
9817 {
9818 remote_debug_printf ("Packet instead of Ack, ignoring it");
9819 /* It's probably an old response sent because an ACK
9820 was lost. Gobble up the packet and ack it so it
9821 doesn't get retransmitted when we resend this
9822 packet. */
9823 skip_frame ();
9824 remote_serial_write ("+", 1);
9825 continue; /* Now, go look for +. */
9826 }
9827
9828 case '%':
9829 {
9830 int val;
9831
9832 /* If we got a notification, handle it, and go back to looking
9833 for an ack. */
9834 /* We've found the start of a notification. Now
9835 collect the data. */
9836 val = read_frame (&rs->buf);
9837 if (val >= 0)
9838 {
9839 remote_debug_printf_nofunc
9840 (" Notification received: %s",
9841 escape_buffer (rs->buf.data (), val).c_str ());
9842
9843 handle_notification (rs->notif_state, rs->buf.data ());
9844 /* We're in sync now, rewait for the ack. */
9845 tcount = 0;
9846 }
9847 else
9848 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9849 rs->buf.data ());
9850 continue;
9851 }
9852 /* fall-through */
9853 default:
9854 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9855 rs->buf.data ());
9856 continue;
9857 }
9858 break; /* Here to retransmit. */
9859 }
9860
9861 #if 0
9862 /* This is wrong. If doing a long backtrace, the user should be
9863 able to get out next time we call QUIT, without anything as
9864 violent as interrupt_query. If we want to provide a way out of
9865 here without getting to the next QUIT, it should be based on
9866 hitting ^C twice as in remote_wait. */
9867 if (quit_flag)
9868 {
9869 quit_flag = 0;
9870 interrupt_query ();
9871 }
9872 #endif
9873 }
9874
9875 return 0;
9876 }
9877
9878 /* Come here after finding the start of a frame when we expected an
9879 ack. Do our best to discard the rest of this packet. */
9880
9881 void
9882 remote_target::skip_frame ()
9883 {
9884 int c;
9885
9886 while (1)
9887 {
9888 c = readchar (remote_timeout);
9889 switch (c)
9890 {
9891 case SERIAL_TIMEOUT:
9892 /* Nothing we can do. */
9893 return;
9894 case '#':
9895 /* Discard the two bytes of checksum and stop. */
9896 c = readchar (remote_timeout);
9897 if (c >= 0)
9898 c = readchar (remote_timeout);
9899
9900 return;
9901 case '*': /* Run length encoding. */
9902 /* Discard the repeat count. */
9903 c = readchar (remote_timeout);
9904 if (c < 0)
9905 return;
9906 break;
9907 default:
9908 /* A regular character. */
9909 break;
9910 }
9911 }
9912 }
9913
9914 /* Come here after finding the start of the frame. Collect the rest
9915 into *BUF, verifying the checksum, length, and handling run-length
9916 compression. NUL terminate the buffer. If there is not enough room,
9917 expand *BUF.
9918
9919 Returns -1 on error, number of characters in buffer (ignoring the
9920 trailing NULL) on success. (could be extended to return one of the
9921 SERIAL status indications). */
9922
9923 long
9924 remote_target::read_frame (gdb::char_vector *buf_p)
9925 {
9926 unsigned char csum;
9927 long bc;
9928 int c;
9929 char *buf = buf_p->data ();
9930 struct remote_state *rs = get_remote_state ();
9931
9932 csum = 0;
9933 bc = 0;
9934
9935 while (1)
9936 {
9937 c = readchar (remote_timeout);
9938 switch (c)
9939 {
9940 case SERIAL_TIMEOUT:
9941 remote_debug_printf ("Timeout in mid-packet, retrying");
9942 return -1;
9943
9944 case '$':
9945 remote_debug_printf ("Saw new packet start in middle of old one");
9946 return -1; /* Start a new packet, count retries. */
9947
9948 case '#':
9949 {
9950 unsigned char pktcsum;
9951 int check_0 = 0;
9952 int check_1 = 0;
9953
9954 buf[bc] = '\0';
9955
9956 check_0 = readchar (remote_timeout);
9957 if (check_0 >= 0)
9958 check_1 = readchar (remote_timeout);
9959
9960 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9961 {
9962 remote_debug_printf ("Timeout in checksum, retrying");
9963 return -1;
9964 }
9965 else if (check_0 < 0 || check_1 < 0)
9966 {
9967 remote_debug_printf ("Communication error in checksum");
9968 return -1;
9969 }
9970
9971 /* Don't recompute the checksum; with no ack packets we
9972 don't have any way to indicate a packet retransmission
9973 is necessary. */
9974 if (rs->noack_mode)
9975 return bc;
9976
9977 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9978 if (csum == pktcsum)
9979 return bc;
9980
9981 remote_debug_printf
9982 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
9983 pktcsum, csum, escape_buffer (buf, bc).c_str ());
9984
9985 /* Number of characters in buffer ignoring trailing
9986 NULL. */
9987 return -1;
9988 }
9989 case '*': /* Run length encoding. */
9990 {
9991 int repeat;
9992
9993 csum += c;
9994 c = readchar (remote_timeout);
9995 csum += c;
9996 repeat = c - ' ' + 3; /* Compute repeat count. */
9997
9998 /* The character before ``*'' is repeated. */
9999
10000 if (repeat > 0 && repeat <= 255 && bc > 0)
10001 {
10002 if (bc + repeat - 1 >= buf_p->size () - 1)
10003 {
10004 /* Make some more room in the buffer. */
10005 buf_p->resize (buf_p->size () + repeat);
10006 buf = buf_p->data ();
10007 }
10008
10009 memset (&buf[bc], buf[bc - 1], repeat);
10010 bc += repeat;
10011 continue;
10012 }
10013
10014 buf[bc] = '\0';
10015 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
10016 return -1;
10017 }
10018 default:
10019 if (bc >= buf_p->size () - 1)
10020 {
10021 /* Make some more room in the buffer. */
10022 buf_p->resize (buf_p->size () * 2);
10023 buf = buf_p->data ();
10024 }
10025
10026 buf[bc++] = c;
10027 csum += c;
10028 continue;
10029 }
10030 }
10031 }
10032
10033 /* Set this to the maximum number of seconds to wait instead of waiting forever
10034 in target_wait(). If this timer times out, then it generates an error and
10035 the command is aborted. This replaces most of the need for timeouts in the
10036 GDB test suite, and makes it possible to distinguish between a hung target
10037 and one with slow communications. */
10038
10039 static int watchdog = 0;
10040 static void
10041 show_watchdog (struct ui_file *file, int from_tty,
10042 struct cmd_list_element *c, const char *value)
10043 {
10044 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
10045 }
10046
10047 /* Read a packet from the remote machine, with error checking, and
10048 store it in *BUF. Resize *BUF if necessary to hold the result. If
10049 FOREVER, wait forever rather than timing out; this is used (in
10050 synchronous mode) to wait for a target that is is executing user
10051 code to stop. */
10052 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
10053 don't have to change all the calls to getpkt to deal with the
10054 return value, because at the moment I don't know what the right
10055 thing to do it for those. */
10056
10057 void
10058 remote_target::getpkt (gdb::char_vector *buf, int forever)
10059 {
10060 getpkt_sane (buf, forever);
10061 }
10062
10063
10064 /* Read a packet from the remote machine, with error checking, and
10065 store it in *BUF. Resize *BUF if necessary to hold the result. If
10066 FOREVER, wait forever rather than timing out; this is used (in
10067 synchronous mode) to wait for a target that is is executing user
10068 code to stop. If FOREVER == 0, this function is allowed to time
10069 out gracefully and return an indication of this to the caller.
10070 Otherwise return the number of bytes read. If EXPECTING_NOTIF,
10071 consider receiving a notification enough reason to return to the
10072 caller. *IS_NOTIF is an output boolean that indicates whether *BUF
10073 holds a notification or not (a regular packet). */
10074
10075 int
10076 remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
10077 int forever, int expecting_notif,
10078 int *is_notif)
10079 {
10080 struct remote_state *rs = get_remote_state ();
10081 int c;
10082 int tries;
10083 int timeout;
10084 int val = -1;
10085
10086 strcpy (buf->data (), "timeout");
10087
10088 if (forever)
10089 timeout = watchdog > 0 ? watchdog : -1;
10090 else if (expecting_notif)
10091 timeout = 0; /* There should already be a char in the buffer. If
10092 not, bail out. */
10093 else
10094 timeout = remote_timeout;
10095
10096 #define MAX_TRIES 3
10097
10098 /* Process any number of notifications, and then return when
10099 we get a packet. */
10100 for (;;)
10101 {
10102 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
10103 times. */
10104 for (tries = 1; tries <= MAX_TRIES; tries++)
10105 {
10106 /* This can loop forever if the remote side sends us
10107 characters continuously, but if it pauses, we'll get
10108 SERIAL_TIMEOUT from readchar because of timeout. Then
10109 we'll count that as a retry.
10110
10111 Note that even when forever is set, we will only wait
10112 forever prior to the start of a packet. After that, we
10113 expect characters to arrive at a brisk pace. They should
10114 show up within remote_timeout intervals. */
10115 do
10116 c = readchar (timeout);
10117 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
10118
10119 if (c == SERIAL_TIMEOUT)
10120 {
10121 if (expecting_notif)
10122 return -1; /* Don't complain, it's normal to not get
10123 anything in this case. */
10124
10125 if (forever) /* Watchdog went off? Kill the target. */
10126 {
10127 remote_unpush_target (this);
10128 throw_error (TARGET_CLOSE_ERROR,
10129 _("Watchdog timeout has expired. "
10130 "Target detached."));
10131 }
10132
10133 remote_debug_printf ("Timed out.");
10134 }
10135 else
10136 {
10137 /* We've found the start of a packet or notification.
10138 Now collect the data. */
10139 val = read_frame (buf);
10140 if (val >= 0)
10141 break;
10142 }
10143
10144 remote_serial_write ("-", 1);
10145 }
10146
10147 if (tries > MAX_TRIES)
10148 {
10149 /* We have tried hard enough, and just can't receive the
10150 packet/notification. Give up. */
10151 gdb_printf (_("Ignoring packet error, continuing...\n"));
10152
10153 /* Skip the ack char if we're in no-ack mode. */
10154 if (!rs->noack_mode)
10155 remote_serial_write ("+", 1);
10156 return -1;
10157 }
10158
10159 /* If we got an ordinary packet, return that to our caller. */
10160 if (c == '$')
10161 {
10162 if (remote_debug)
10163 {
10164 int max_chars;
10165
10166 if (remote_packet_max_chars < 0)
10167 max_chars = val;
10168 else
10169 max_chars = remote_packet_max_chars;
10170
10171 std::string str
10172 = escape_buffer (buf->data (),
10173 std::min (val, max_chars));
10174
10175 if (val > max_chars)
10176 remote_debug_printf_nofunc
10177 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10178 val - max_chars);
10179 else
10180 remote_debug_printf_nofunc ("Packet received: %s",
10181 str.c_str ());
10182 }
10183
10184 /* Skip the ack char if we're in no-ack mode. */
10185 if (!rs->noack_mode)
10186 remote_serial_write ("+", 1);
10187 if (is_notif != NULL)
10188 *is_notif = 0;
10189 return val;
10190 }
10191
10192 /* If we got a notification, handle it, and go back to looking
10193 for a packet. */
10194 else
10195 {
10196 gdb_assert (c == '%');
10197
10198 remote_debug_printf_nofunc
10199 (" Notification received: %s",
10200 escape_buffer (buf->data (), val).c_str ());
10201
10202 if (is_notif != NULL)
10203 *is_notif = 1;
10204
10205 handle_notification (rs->notif_state, buf->data ());
10206
10207 /* Notifications require no acknowledgement. */
10208
10209 if (expecting_notif)
10210 return val;
10211 }
10212 }
10213 }
10214
10215 int
10216 remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
10217 {
10218 return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
10219 }
10220
10221 int
10222 remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
10223 int *is_notif)
10224 {
10225 return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
10226 }
10227
10228 /* Kill any new fork children of inferior INF that haven't been
10229 processed by follow_fork. */
10230
10231 void
10232 remote_target::kill_new_fork_children (inferior *inf)
10233 {
10234 remote_state *rs = get_remote_state ();
10235 const notif_client *notif = &notif_client_stop;
10236
10237 /* Kill the fork child threads of any threads in inferior INF that are stopped
10238 at a fork event. */
10239 for (thread_info *thread : inf->non_exited_threads ())
10240 {
10241 const target_waitstatus *ws = thread_pending_fork_status (thread);
10242
10243 if (ws == nullptr)
10244 continue;
10245
10246 int child_pid = ws->child_ptid ().pid ();
10247 int res = remote_vkill (child_pid);
10248
10249 if (res != 0)
10250 error (_("Can't kill fork child process %d"), child_pid);
10251 }
10252
10253 /* Check for any pending fork events (not reported or processed yet)
10254 in inferior INF and kill those fork child threads as well. */
10255 remote_notif_get_pending_events (notif);
10256 for (auto &event : rs->stop_reply_queue)
10257 {
10258 if (event->ptid.pid () != inf->pid)
10259 continue;
10260
10261 if (!is_fork_status (event->ws.kind ()))
10262 continue;
10263
10264 int child_pid = event->ws.child_ptid ().pid ();
10265 int res = remote_vkill (child_pid);
10266
10267 if (res != 0)
10268 error (_("Can't kill fork child process %d"), child_pid);
10269 }
10270 }
10271
10272 \f
10273 /* Target hook to kill the current inferior. */
10274
10275 void
10276 remote_target::kill ()
10277 {
10278 int res = -1;
10279 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10280
10281 gdb_assert (inf != nullptr);
10282
10283 if (m_features.packet_support (PACKET_vKill) != PACKET_DISABLE)
10284 {
10285 /* If we're stopped while forking and we haven't followed yet,
10286 kill the child task. We need to do this before killing the
10287 parent task because if this is a vfork then the parent will
10288 be sleeping. */
10289 kill_new_fork_children (inf);
10290
10291 res = remote_vkill (inf->pid);
10292 if (res == 0)
10293 {
10294 target_mourn_inferior (inferior_ptid);
10295 return;
10296 }
10297 }
10298
10299 /* If we are in 'target remote' mode and we are killing the only
10300 inferior, then we will tell gdbserver to exit and unpush the
10301 target. */
10302 if (res == -1 && !m_features.remote_multi_process_p ()
10303 && number_of_live_inferiors (this) == 1)
10304 {
10305 remote_kill_k ();
10306
10307 /* We've killed the remote end, we get to mourn it. If we are
10308 not in extended mode, mourning the inferior also unpushes
10309 remote_ops from the target stack, which closes the remote
10310 connection. */
10311 target_mourn_inferior (inferior_ptid);
10312
10313 return;
10314 }
10315
10316 error (_("Can't kill process"));
10317 }
10318
10319 /* Send a kill request to the target using the 'vKill' packet. */
10320
10321 int
10322 remote_target::remote_vkill (int pid)
10323 {
10324 if (m_features.packet_support (PACKET_vKill) == PACKET_DISABLE)
10325 return -1;
10326
10327 remote_state *rs = get_remote_state ();
10328
10329 /* Tell the remote target to detach. */
10330 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10331 putpkt (rs->buf);
10332 getpkt (&rs->buf, 0);
10333
10334 switch (m_features.packet_ok (rs->buf, PACKET_vKill))
10335 {
10336 case PACKET_OK:
10337 return 0;
10338 case PACKET_ERROR:
10339 return 1;
10340 case PACKET_UNKNOWN:
10341 return -1;
10342 default:
10343 internal_error (_("Bad result from packet_ok"));
10344 }
10345 }
10346
10347 /* Send a kill request to the target using the 'k' packet. */
10348
10349 void
10350 remote_target::remote_kill_k ()
10351 {
10352 /* Catch errors so the user can quit from gdb even when we
10353 aren't on speaking terms with the remote system. */
10354 try
10355 {
10356 putpkt ("k");
10357 }
10358 catch (const gdb_exception_error &ex)
10359 {
10360 if (ex.error == TARGET_CLOSE_ERROR)
10361 {
10362 /* If we got an (EOF) error that caused the target
10363 to go away, then we're done, that's what we wanted.
10364 "k" is susceptible to cause a premature EOF, given
10365 that the remote server isn't actually required to
10366 reply to "k", and it can happen that it doesn't
10367 even get to reply ACK to the "k". */
10368 return;
10369 }
10370
10371 /* Otherwise, something went wrong. We didn't actually kill
10372 the target. Just propagate the exception, and let the
10373 user or higher layers decide what to do. */
10374 throw;
10375 }
10376 }
10377
10378 void
10379 remote_target::mourn_inferior ()
10380 {
10381 struct remote_state *rs = get_remote_state ();
10382
10383 /* We're no longer interested in notification events of an inferior
10384 that exited or was killed/detached. */
10385 discard_pending_stop_replies (current_inferior ());
10386
10387 /* In 'target remote' mode with one inferior, we close the connection. */
10388 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10389 {
10390 remote_unpush_target (this);
10391 return;
10392 }
10393
10394 /* In case we got here due to an error, but we're going to stay
10395 connected. */
10396 rs->waiting_for_stop_reply = 0;
10397
10398 /* If the current general thread belonged to the process we just
10399 detached from or has exited, the remote side current general
10400 thread becomes undefined. Considering a case like this:
10401
10402 - We just got here due to a detach.
10403 - The process that we're detaching from happens to immediately
10404 report a global breakpoint being hit in non-stop mode, in the
10405 same thread we had selected before.
10406 - GDB attaches to this process again.
10407 - This event happens to be the next event we handle.
10408
10409 GDB would consider that the current general thread didn't need to
10410 be set on the stub side (with Hg), since for all it knew,
10411 GENERAL_THREAD hadn't changed.
10412
10413 Notice that although in all-stop mode, the remote server always
10414 sets the current thread to the thread reporting the stop event,
10415 that doesn't happen in non-stop mode; in non-stop, the stub *must
10416 not* change the current thread when reporting a breakpoint hit,
10417 due to the decoupling of event reporting and event handling.
10418
10419 To keep things simple, we always invalidate our notion of the
10420 current thread. */
10421 record_currthread (rs, minus_one_ptid);
10422
10423 /* Call common code to mark the inferior as not running. */
10424 generic_mourn_inferior ();
10425 }
10426
10427 bool
10428 extended_remote_target::supports_disable_randomization ()
10429 {
10430 return (m_features.packet_support (PACKET_QDisableRandomization)
10431 == PACKET_ENABLE);
10432 }
10433
10434 void
10435 remote_target::extended_remote_disable_randomization (int val)
10436 {
10437 struct remote_state *rs = get_remote_state ();
10438 char *reply;
10439
10440 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10441 "QDisableRandomization:%x", val);
10442 putpkt (rs->buf);
10443 reply = remote_get_noisy_reply ();
10444 if (*reply == '\0')
10445 error (_("Target does not support QDisableRandomization."));
10446 if (strcmp (reply, "OK") != 0)
10447 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10448 }
10449
10450 int
10451 remote_target::extended_remote_run (const std::string &args)
10452 {
10453 struct remote_state *rs = get_remote_state ();
10454 int len;
10455 const char *remote_exec_file = get_remote_exec_file ();
10456
10457 /* If the user has disabled vRun support, or we have detected that
10458 support is not available, do not try it. */
10459 if (m_features.packet_support (PACKET_vRun) == PACKET_DISABLE)
10460 return -1;
10461
10462 strcpy (rs->buf.data (), "vRun;");
10463 len = strlen (rs->buf.data ());
10464
10465 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10466 error (_("Remote file name too long for run packet"));
10467 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10468 strlen (remote_exec_file));
10469
10470 if (!args.empty ())
10471 {
10472 int i;
10473
10474 gdb_argv argv (args.c_str ());
10475 for (i = 0; argv[i] != NULL; i++)
10476 {
10477 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10478 error (_("Argument list too long for run packet"));
10479 rs->buf[len++] = ';';
10480 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10481 strlen (argv[i]));
10482 }
10483 }
10484
10485 rs->buf[len++] = '\0';
10486
10487 putpkt (rs->buf);
10488 getpkt (&rs->buf, 0);
10489
10490 switch (m_features.packet_ok (rs->buf, PACKET_vRun))
10491 {
10492 case PACKET_OK:
10493 /* We have a wait response. All is well. */
10494 return 0;
10495 case PACKET_UNKNOWN:
10496 return -1;
10497 case PACKET_ERROR:
10498 if (remote_exec_file[0] == '\0')
10499 error (_("Running the default executable on the remote target failed; "
10500 "try \"set remote exec-file\"?"));
10501 else
10502 error (_("Running \"%s\" on the remote target failed"),
10503 remote_exec_file);
10504 default:
10505 gdb_assert_not_reached ("bad switch");
10506 }
10507 }
10508
10509 /* Helper function to send set/unset environment packets. ACTION is
10510 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10511 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10512 sent. */
10513
10514 void
10515 remote_target::send_environment_packet (const char *action,
10516 const char *packet,
10517 const char *value)
10518 {
10519 remote_state *rs = get_remote_state ();
10520
10521 /* Convert the environment variable to an hex string, which
10522 is the best format to be transmitted over the wire. */
10523 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10524 strlen (value));
10525
10526 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10527 "%s:%s", packet, encoded_value.c_str ());
10528
10529 putpkt (rs->buf);
10530 getpkt (&rs->buf, 0);
10531 if (strcmp (rs->buf.data (), "OK") != 0)
10532 warning (_("Unable to %s environment variable '%s' on remote."),
10533 action, value);
10534 }
10535
10536 /* Helper function to handle the QEnvironment* packets. */
10537
10538 void
10539 remote_target::extended_remote_environment_support ()
10540 {
10541 remote_state *rs = get_remote_state ();
10542
10543 if (m_features.packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10544 {
10545 putpkt ("QEnvironmentReset");
10546 getpkt (&rs->buf, 0);
10547 if (strcmp (rs->buf.data (), "OK") != 0)
10548 warning (_("Unable to reset environment on remote."));
10549 }
10550
10551 gdb_environ *e = &current_inferior ()->environment;
10552
10553 if (m_features.packet_support (PACKET_QEnvironmentHexEncoded)
10554 != PACKET_DISABLE)
10555 {
10556 for (const std::string &el : e->user_set_env ())
10557 send_environment_packet ("set", "QEnvironmentHexEncoded",
10558 el.c_str ());
10559 }
10560
10561
10562 if (m_features.packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10563 for (const std::string &el : e->user_unset_env ())
10564 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10565 }
10566
10567 /* Helper function to set the current working directory for the
10568 inferior in the remote target. */
10569
10570 void
10571 remote_target::extended_remote_set_inferior_cwd ()
10572 {
10573 if (m_features.packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10574 {
10575 const std::string &inferior_cwd = current_inferior ()->cwd ();
10576 remote_state *rs = get_remote_state ();
10577
10578 if (!inferior_cwd.empty ())
10579 {
10580 std::string hexpath
10581 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10582 inferior_cwd.size ());
10583
10584 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10585 "QSetWorkingDir:%s", hexpath.c_str ());
10586 }
10587 else
10588 {
10589 /* An empty inferior_cwd means that the user wants us to
10590 reset the remote server's inferior's cwd. */
10591 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10592 "QSetWorkingDir:");
10593 }
10594
10595 putpkt (rs->buf);
10596 getpkt (&rs->buf, 0);
10597 if (m_features.packet_ok (rs->buf, PACKET_QSetWorkingDir) != PACKET_OK)
10598 error (_("\
10599 Remote replied unexpectedly while setting the inferior's working\n\
10600 directory: %s"),
10601 rs->buf.data ());
10602
10603 }
10604 }
10605
10606 /* In the extended protocol we want to be able to do things like
10607 "run" and have them basically work as expected. So we need
10608 a special create_inferior function. We support changing the
10609 executable file and the command line arguments, but not the
10610 environment. */
10611
10612 void
10613 extended_remote_target::create_inferior (const char *exec_file,
10614 const std::string &args,
10615 char **env, int from_tty)
10616 {
10617 int run_worked;
10618 char *stop_reply;
10619 struct remote_state *rs = get_remote_state ();
10620 const char *remote_exec_file = get_remote_exec_file ();
10621
10622 /* If running asynchronously, register the target file descriptor
10623 with the event loop. */
10624 if (target_can_async_p ())
10625 target_async (true);
10626
10627 /* Disable address space randomization if requested (and supported). */
10628 if (supports_disable_randomization ())
10629 extended_remote_disable_randomization (disable_randomization);
10630
10631 /* If startup-with-shell is on, we inform gdbserver to start the
10632 remote inferior using a shell. */
10633 if (m_features.packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10634 {
10635 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10636 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10637 putpkt (rs->buf);
10638 getpkt (&rs->buf, 0);
10639 if (strcmp (rs->buf.data (), "OK") != 0)
10640 error (_("\
10641 Remote replied unexpectedly while setting startup-with-shell: %s"),
10642 rs->buf.data ());
10643 }
10644
10645 extended_remote_environment_support ();
10646
10647 extended_remote_set_inferior_cwd ();
10648
10649 /* Now restart the remote server. */
10650 run_worked = extended_remote_run (args) != -1;
10651 if (!run_worked)
10652 {
10653 /* vRun was not supported. Fail if we need it to do what the
10654 user requested. */
10655 if (remote_exec_file[0])
10656 error (_("Remote target does not support \"set remote exec-file\""));
10657 if (!args.empty ())
10658 error (_("Remote target does not support \"set args\" or run ARGS"));
10659
10660 /* Fall back to "R". */
10661 extended_remote_restart ();
10662 }
10663
10664 /* vRun's success return is a stop reply. */
10665 stop_reply = run_worked ? rs->buf.data () : NULL;
10666 add_current_inferior_and_thread (stop_reply);
10667
10668 /* Get updated offsets, if the stub uses qOffsets. */
10669 get_offsets ();
10670 }
10671 \f
10672
10673 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10674 the list of conditions (in agent expression bytecode format), if any, the
10675 target needs to evaluate. The output is placed into the packet buffer
10676 started from BUF and ended at BUF_END. */
10677
10678 static int
10679 remote_add_target_side_condition (struct gdbarch *gdbarch,
10680 struct bp_target_info *bp_tgt, char *buf,
10681 char *buf_end)
10682 {
10683 if (bp_tgt->conditions.empty ())
10684 return 0;
10685
10686 buf += strlen (buf);
10687 xsnprintf (buf, buf_end - buf, "%s", ";");
10688 buf++;
10689
10690 /* Send conditions to the target. */
10691 for (agent_expr *aexpr : bp_tgt->conditions)
10692 {
10693 xsnprintf (buf, buf_end - buf, "X%x,", (int) aexpr->buf.size ());
10694 buf += strlen (buf);
10695 for (int i = 0; i < aexpr->buf.size (); ++i)
10696 buf = pack_hex_byte (buf, aexpr->buf[i]);
10697 *buf = '\0';
10698 }
10699 return 0;
10700 }
10701
10702 static void
10703 remote_add_target_side_commands (struct gdbarch *gdbarch,
10704 struct bp_target_info *bp_tgt, char *buf)
10705 {
10706 if (bp_tgt->tcommands.empty ())
10707 return;
10708
10709 buf += strlen (buf);
10710
10711 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10712 buf += strlen (buf);
10713
10714 /* Concatenate all the agent expressions that are commands into the
10715 cmds parameter. */
10716 for (agent_expr *aexpr : bp_tgt->tcommands)
10717 {
10718 sprintf (buf, "X%x,", (int) aexpr->buf.size ());
10719 buf += strlen (buf);
10720 for (int i = 0; i < aexpr->buf.size (); ++i)
10721 buf = pack_hex_byte (buf, aexpr->buf[i]);
10722 *buf = '\0';
10723 }
10724 }
10725
10726 /* Insert a breakpoint. On targets that have software breakpoint
10727 support, we ask the remote target to do the work; on targets
10728 which don't, we insert a traditional memory breakpoint. */
10729
10730 int
10731 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10732 struct bp_target_info *bp_tgt)
10733 {
10734 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10735 If it succeeds, then set the support to PACKET_ENABLE. If it
10736 fails, and the user has explicitly requested the Z support then
10737 report an error, otherwise, mark it disabled and go on. */
10738
10739 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
10740 {
10741 CORE_ADDR addr = bp_tgt->reqstd_address;
10742 struct remote_state *rs;
10743 char *p, *endbuf;
10744
10745 /* Make sure the remote is pointing at the right process, if
10746 necessary. */
10747 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10748 set_general_process ();
10749
10750 rs = get_remote_state ();
10751 p = rs->buf.data ();
10752 endbuf = p + get_remote_packet_size ();
10753
10754 *(p++) = 'Z';
10755 *(p++) = '0';
10756 *(p++) = ',';
10757 addr = (ULONGEST) remote_address_masked (addr);
10758 p += hexnumstr (p, addr);
10759 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10760
10761 if (supports_evaluation_of_breakpoint_conditions ())
10762 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10763
10764 if (can_run_breakpoint_commands ())
10765 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10766
10767 putpkt (rs->buf);
10768 getpkt (&rs->buf, 0);
10769
10770 switch (m_features.packet_ok (rs->buf, PACKET_Z0))
10771 {
10772 case PACKET_ERROR:
10773 return -1;
10774 case PACKET_OK:
10775 return 0;
10776 case PACKET_UNKNOWN:
10777 break;
10778 }
10779 }
10780
10781 /* If this breakpoint has target-side commands but this stub doesn't
10782 support Z0 packets, throw error. */
10783 if (!bp_tgt->tcommands.empty ())
10784 throw_error (NOT_SUPPORTED_ERROR, _("\
10785 Target doesn't support breakpoints that have target side commands."));
10786
10787 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10788 }
10789
10790 int
10791 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10792 struct bp_target_info *bp_tgt,
10793 enum remove_bp_reason reason)
10794 {
10795 CORE_ADDR addr = bp_tgt->placed_address;
10796 struct remote_state *rs = get_remote_state ();
10797
10798 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
10799 {
10800 char *p = rs->buf.data ();
10801 char *endbuf = p + get_remote_packet_size ();
10802
10803 /* Make sure the remote is pointing at the right process, if
10804 necessary. */
10805 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10806 set_general_process ();
10807
10808 *(p++) = 'z';
10809 *(p++) = '0';
10810 *(p++) = ',';
10811
10812 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10813 p += hexnumstr (p, addr);
10814 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10815
10816 putpkt (rs->buf);
10817 getpkt (&rs->buf, 0);
10818
10819 return (rs->buf[0] == 'E');
10820 }
10821
10822 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10823 }
10824
10825 static enum Z_packet_type
10826 watchpoint_to_Z_packet (int type)
10827 {
10828 switch (type)
10829 {
10830 case hw_write:
10831 return Z_PACKET_WRITE_WP;
10832 break;
10833 case hw_read:
10834 return Z_PACKET_READ_WP;
10835 break;
10836 case hw_access:
10837 return Z_PACKET_ACCESS_WP;
10838 break;
10839 default:
10840 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
10841 }
10842 }
10843
10844 int
10845 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10846 enum target_hw_bp_type type, struct expression *cond)
10847 {
10848 struct remote_state *rs = get_remote_state ();
10849 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10850 char *p;
10851 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10852
10853 if (m_features.packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10854 return 1;
10855
10856 /* Make sure the remote is pointing at the right process, if
10857 necessary. */
10858 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10859 set_general_process ();
10860
10861 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10862 p = strchr (rs->buf.data (), '\0');
10863 addr = remote_address_masked (addr);
10864 p += hexnumstr (p, (ULONGEST) addr);
10865 xsnprintf (p, endbuf - p, ",%x", len);
10866
10867 putpkt (rs->buf);
10868 getpkt (&rs->buf, 0);
10869
10870 switch (m_features.packet_ok (rs->buf, PACKET_Z0 + packet))
10871 {
10872 case PACKET_ERROR:
10873 return -1;
10874 case PACKET_UNKNOWN:
10875 return 1;
10876 case PACKET_OK:
10877 return 0;
10878 }
10879 internal_error (_("remote_insert_watchpoint: reached end of function"));
10880 }
10881
10882 bool
10883 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10884 CORE_ADDR start, int length)
10885 {
10886 CORE_ADDR diff = remote_address_masked (addr - start);
10887
10888 return diff < length;
10889 }
10890
10891
10892 int
10893 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10894 enum target_hw_bp_type type, struct expression *cond)
10895 {
10896 struct remote_state *rs = get_remote_state ();
10897 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10898 char *p;
10899 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10900
10901 if (m_features.packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10902 return -1;
10903
10904 /* Make sure the remote is pointing at the right process, if
10905 necessary. */
10906 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10907 set_general_process ();
10908
10909 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10910 p = strchr (rs->buf.data (), '\0');
10911 addr = remote_address_masked (addr);
10912 p += hexnumstr (p, (ULONGEST) addr);
10913 xsnprintf (p, endbuf - p, ",%x", len);
10914 putpkt (rs->buf);
10915 getpkt (&rs->buf, 0);
10916
10917 switch (m_features.packet_ok (rs->buf, PACKET_Z0 + packet))
10918 {
10919 case PACKET_ERROR:
10920 case PACKET_UNKNOWN:
10921 return -1;
10922 case PACKET_OK:
10923 return 0;
10924 }
10925 internal_error (_("remote_remove_watchpoint: reached end of function"));
10926 }
10927
10928
10929 static int remote_hw_watchpoint_limit = -1;
10930 static int remote_hw_watchpoint_length_limit = -1;
10931 static int remote_hw_breakpoint_limit = -1;
10932
10933 int
10934 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10935 {
10936 if (remote_hw_watchpoint_length_limit == 0)
10937 return 0;
10938 else if (remote_hw_watchpoint_length_limit < 0)
10939 return 1;
10940 else if (len <= remote_hw_watchpoint_length_limit)
10941 return 1;
10942 else
10943 return 0;
10944 }
10945
10946 int
10947 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10948 {
10949 if (type == bp_hardware_breakpoint)
10950 {
10951 if (remote_hw_breakpoint_limit == 0)
10952 return 0;
10953 else if (remote_hw_breakpoint_limit < 0)
10954 return 1;
10955 else if (cnt <= remote_hw_breakpoint_limit)
10956 return 1;
10957 }
10958 else
10959 {
10960 if (remote_hw_watchpoint_limit == 0)
10961 return 0;
10962 else if (remote_hw_watchpoint_limit < 0)
10963 return 1;
10964 else if (ot)
10965 return -1;
10966 else if (cnt <= remote_hw_watchpoint_limit)
10967 return 1;
10968 }
10969 return -1;
10970 }
10971
10972 /* The to_stopped_by_sw_breakpoint method of target remote. */
10973
10974 bool
10975 remote_target::stopped_by_sw_breakpoint ()
10976 {
10977 struct thread_info *thread = inferior_thread ();
10978
10979 return (thread->priv != NULL
10980 && (get_remote_thread_info (thread)->stop_reason
10981 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10982 }
10983
10984 /* The to_supports_stopped_by_sw_breakpoint method of target
10985 remote. */
10986
10987 bool
10988 remote_target::supports_stopped_by_sw_breakpoint ()
10989 {
10990 return (m_features.packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10991 }
10992
10993 /* The to_stopped_by_hw_breakpoint method of target remote. */
10994
10995 bool
10996 remote_target::stopped_by_hw_breakpoint ()
10997 {
10998 struct thread_info *thread = inferior_thread ();
10999
11000 return (thread->priv != NULL
11001 && (get_remote_thread_info (thread)->stop_reason
11002 == TARGET_STOPPED_BY_HW_BREAKPOINT));
11003 }
11004
11005 /* The to_supports_stopped_by_hw_breakpoint method of target
11006 remote. */
11007
11008 bool
11009 remote_target::supports_stopped_by_hw_breakpoint ()
11010 {
11011 return (m_features.packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
11012 }
11013
11014 bool
11015 remote_target::stopped_by_watchpoint ()
11016 {
11017 struct thread_info *thread = inferior_thread ();
11018
11019 return (thread->priv != NULL
11020 && (get_remote_thread_info (thread)->stop_reason
11021 == TARGET_STOPPED_BY_WATCHPOINT));
11022 }
11023
11024 bool
11025 remote_target::stopped_data_address (CORE_ADDR *addr_p)
11026 {
11027 struct thread_info *thread = inferior_thread ();
11028
11029 if (thread->priv != NULL
11030 && (get_remote_thread_info (thread)->stop_reason
11031 == TARGET_STOPPED_BY_WATCHPOINT))
11032 {
11033 *addr_p = get_remote_thread_info (thread)->watch_data_address;
11034 return true;
11035 }
11036
11037 return false;
11038 }
11039
11040
11041 int
11042 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
11043 struct bp_target_info *bp_tgt)
11044 {
11045 CORE_ADDR addr = bp_tgt->reqstd_address;
11046 struct remote_state *rs;
11047 char *p, *endbuf;
11048 char *message;
11049
11050 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11051 return -1;
11052
11053 /* Make sure the remote is pointing at the right process, if
11054 necessary. */
11055 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
11056 set_general_process ();
11057
11058 rs = get_remote_state ();
11059 p = rs->buf.data ();
11060 endbuf = p + get_remote_packet_size ();
11061
11062 *(p++) = 'Z';
11063 *(p++) = '1';
11064 *(p++) = ',';
11065
11066 addr = remote_address_masked (addr);
11067 p += hexnumstr (p, (ULONGEST) addr);
11068 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11069
11070 if (supports_evaluation_of_breakpoint_conditions ())
11071 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
11072
11073 if (can_run_breakpoint_commands ())
11074 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11075
11076 putpkt (rs->buf);
11077 getpkt (&rs->buf, 0);
11078
11079 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
11080 {
11081 case PACKET_ERROR:
11082 if (rs->buf[1] == '.')
11083 {
11084 message = strchr (&rs->buf[2], '.');
11085 if (message)
11086 error (_("Remote failure reply: %s"), message + 1);
11087 }
11088 return -1;
11089 case PACKET_UNKNOWN:
11090 return -1;
11091 case PACKET_OK:
11092 return 0;
11093 }
11094 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
11095 }
11096
11097
11098 int
11099 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
11100 struct bp_target_info *bp_tgt)
11101 {
11102 CORE_ADDR addr;
11103 struct remote_state *rs = get_remote_state ();
11104 char *p = rs->buf.data ();
11105 char *endbuf = p + get_remote_packet_size ();
11106
11107 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11108 return -1;
11109
11110 /* Make sure the remote is pointing at the right process, if
11111 necessary. */
11112 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
11113 set_general_process ();
11114
11115 *(p++) = 'z';
11116 *(p++) = '1';
11117 *(p++) = ',';
11118
11119 addr = remote_address_masked (bp_tgt->placed_address);
11120 p += hexnumstr (p, (ULONGEST) addr);
11121 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11122
11123 putpkt (rs->buf);
11124 getpkt (&rs->buf, 0);
11125
11126 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
11127 {
11128 case PACKET_ERROR:
11129 case PACKET_UNKNOWN:
11130 return -1;
11131 case PACKET_OK:
11132 return 0;
11133 }
11134 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
11135 }
11136
11137 /* Verify memory using the "qCRC:" request. */
11138
11139 int
11140 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
11141 {
11142 struct remote_state *rs = get_remote_state ();
11143 unsigned long host_crc, target_crc;
11144 char *tmp;
11145
11146 /* It doesn't make sense to use qCRC if the remote target is
11147 connected but not running. */
11148 if (target_has_execution ()
11149 && m_features.packet_support (PACKET_qCRC) != PACKET_DISABLE)
11150 {
11151 enum packet_result result;
11152
11153 /* Make sure the remote is pointing at the right process. */
11154 set_general_process ();
11155
11156 /* FIXME: assumes lma can fit into long. */
11157 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
11158 (long) lma, (long) size);
11159 putpkt (rs->buf);
11160
11161 /* Be clever; compute the host_crc before waiting for target
11162 reply. */
11163 host_crc = xcrc32 (data, size, 0xffffffff);
11164
11165 getpkt (&rs->buf, 0);
11166
11167 result = m_features.packet_ok (rs->buf, PACKET_qCRC);
11168 if (result == PACKET_ERROR)
11169 return -1;
11170 else if (result == PACKET_OK)
11171 {
11172 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11173 target_crc = target_crc * 16 + fromhex (*tmp);
11174
11175 return (host_crc == target_crc);
11176 }
11177 }
11178
11179 return simple_verify_memory (this, data, lma, size);
11180 }
11181
11182 /* compare-sections command
11183
11184 With no arguments, compares each loadable section in the exec bfd
11185 with the same memory range on the target, and reports mismatches.
11186 Useful for verifying the image on the target against the exec file. */
11187
11188 static void
11189 compare_sections_command (const char *args, int from_tty)
11190 {
11191 asection *s;
11192 const char *sectname;
11193 bfd_size_type size;
11194 bfd_vma lma;
11195 int matched = 0;
11196 int mismatched = 0;
11197 int res;
11198 int read_only = 0;
11199
11200 if (!current_program_space->exec_bfd ())
11201 error (_("command cannot be used without an exec file"));
11202
11203 if (args != NULL && strcmp (args, "-r") == 0)
11204 {
11205 read_only = 1;
11206 args = NULL;
11207 }
11208
11209 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11210 {
11211 if (!(s->flags & SEC_LOAD))
11212 continue; /* Skip non-loadable section. */
11213
11214 if (read_only && (s->flags & SEC_READONLY) == 0)
11215 continue; /* Skip writeable sections */
11216
11217 size = bfd_section_size (s);
11218 if (size == 0)
11219 continue; /* Skip zero-length section. */
11220
11221 sectname = bfd_section_name (s);
11222 if (args && strcmp (args, sectname) != 0)
11223 continue; /* Not the section selected by user. */
11224
11225 matched = 1; /* Do this section. */
11226 lma = s->lma;
11227
11228 gdb::byte_vector sectdata (size);
11229 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11230 sectdata.data (), 0, size);
11231
11232 res = target_verify_memory (sectdata.data (), lma, size);
11233
11234 if (res == -1)
11235 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11236 paddress (target_gdbarch (), lma),
11237 paddress (target_gdbarch (), lma + size));
11238
11239 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11240 paddress (target_gdbarch (), lma),
11241 paddress (target_gdbarch (), lma + size));
11242 if (res)
11243 gdb_printf ("matched.\n");
11244 else
11245 {
11246 gdb_printf ("MIS-MATCHED!\n");
11247 mismatched++;
11248 }
11249 }
11250 if (mismatched > 0)
11251 warning (_("One or more sections of the target image does "
11252 "not match the loaded file"));
11253 if (args && !matched)
11254 gdb_printf (_("No loaded section named '%s'.\n"), args);
11255 }
11256
11257 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11258 into remote target. The number of bytes written to the remote
11259 target is returned, or -1 for error. */
11260
11261 target_xfer_status
11262 remote_target::remote_write_qxfer (const char *object_name,
11263 const char *annex, const gdb_byte *writebuf,
11264 ULONGEST offset, LONGEST len,
11265 ULONGEST *xfered_len,
11266 const unsigned int which_packet)
11267 {
11268 int i, buf_len;
11269 ULONGEST n;
11270 struct remote_state *rs = get_remote_state ();
11271 int max_size = get_memory_write_packet_size ();
11272
11273 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11274 return TARGET_XFER_E_IO;
11275
11276 /* Insert header. */
11277 i = snprintf (rs->buf.data (), max_size,
11278 "qXfer:%s:write:%s:%s:",
11279 object_name, annex ? annex : "",
11280 phex_nz (offset, sizeof offset));
11281 max_size -= (i + 1);
11282
11283 /* Escape as much data as fits into rs->buf. */
11284 buf_len = remote_escape_output
11285 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11286
11287 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11288 || getpkt_sane (&rs->buf, 0) < 0
11289 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
11290 return TARGET_XFER_E_IO;
11291
11292 unpack_varlen_hex (rs->buf.data (), &n);
11293
11294 *xfered_len = n;
11295 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11296 }
11297
11298 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11299 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11300 number of bytes read is returned, or 0 for EOF, or -1 for error.
11301 The number of bytes read may be less than LEN without indicating an
11302 EOF. PACKET is checked and updated to indicate whether the remote
11303 target supports this object. */
11304
11305 target_xfer_status
11306 remote_target::remote_read_qxfer (const char *object_name,
11307 const char *annex,
11308 gdb_byte *readbuf, ULONGEST offset,
11309 LONGEST len,
11310 ULONGEST *xfered_len,
11311 const unsigned int which_packet)
11312 {
11313 struct remote_state *rs = get_remote_state ();
11314 LONGEST i, n, packet_len;
11315
11316 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11317 return TARGET_XFER_E_IO;
11318
11319 /* Check whether we've cached an end-of-object packet that matches
11320 this request. */
11321 if (rs->finished_object)
11322 {
11323 if (strcmp (object_name, rs->finished_object) == 0
11324 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11325 && offset == rs->finished_offset)
11326 return TARGET_XFER_EOF;
11327
11328
11329 /* Otherwise, we're now reading something different. Discard
11330 the cache. */
11331 xfree (rs->finished_object);
11332 xfree (rs->finished_annex);
11333 rs->finished_object = NULL;
11334 rs->finished_annex = NULL;
11335 }
11336
11337 /* Request only enough to fit in a single packet. The actual data
11338 may not, since we don't know how much of it will need to be escaped;
11339 the target is free to respond with slightly less data. We subtract
11340 five to account for the response type and the protocol frame. */
11341 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11342 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11343 "qXfer:%s:read:%s:%s,%s",
11344 object_name, annex ? annex : "",
11345 phex_nz (offset, sizeof offset),
11346 phex_nz (n, sizeof n));
11347 i = putpkt (rs->buf);
11348 if (i < 0)
11349 return TARGET_XFER_E_IO;
11350
11351 rs->buf[0] = '\0';
11352 packet_len = getpkt_sane (&rs->buf, 0);
11353 if (packet_len < 0
11354 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
11355 return TARGET_XFER_E_IO;
11356
11357 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11358 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11359
11360 /* 'm' means there is (or at least might be) more data after this
11361 batch. That does not make sense unless there's at least one byte
11362 of data in this reply. */
11363 if (rs->buf[0] == 'm' && packet_len == 1)
11364 error (_("Remote qXfer reply contained no data."));
11365
11366 /* Got some data. */
11367 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11368 packet_len - 1, readbuf, n);
11369
11370 /* 'l' is an EOF marker, possibly including a final block of data,
11371 or possibly empty. If we have the final block of a non-empty
11372 object, record this fact to bypass a subsequent partial read. */
11373 if (rs->buf[0] == 'l' && offset + i > 0)
11374 {
11375 rs->finished_object = xstrdup (object_name);
11376 rs->finished_annex = xstrdup (annex ? annex : "");
11377 rs->finished_offset = offset + i;
11378 }
11379
11380 if (i == 0)
11381 return TARGET_XFER_EOF;
11382 else
11383 {
11384 *xfered_len = i;
11385 return TARGET_XFER_OK;
11386 }
11387 }
11388
11389 enum target_xfer_status
11390 remote_target::xfer_partial (enum target_object object,
11391 const char *annex, gdb_byte *readbuf,
11392 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11393 ULONGEST *xfered_len)
11394 {
11395 struct remote_state *rs;
11396 int i;
11397 char *p2;
11398 char query_type;
11399 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
11400
11401 set_remote_traceframe ();
11402 set_general_thread (inferior_ptid);
11403
11404 rs = get_remote_state ();
11405
11406 /* Handle memory using the standard memory routines. */
11407 if (object == TARGET_OBJECT_MEMORY)
11408 {
11409 /* If the remote target is connected but not running, we should
11410 pass this request down to a lower stratum (e.g. the executable
11411 file). */
11412 if (!target_has_execution ())
11413 return TARGET_XFER_EOF;
11414
11415 if (writebuf != NULL)
11416 return remote_write_bytes (offset, writebuf, len, unit_size,
11417 xfered_len);
11418 else
11419 return remote_read_bytes (offset, readbuf, len, unit_size,
11420 xfered_len);
11421 }
11422
11423 /* Handle extra signal info using qxfer packets. */
11424 if (object == TARGET_OBJECT_SIGNAL_INFO)
11425 {
11426 if (readbuf)
11427 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11428 xfered_len, PACKET_qXfer_siginfo_read);
11429 else
11430 return remote_write_qxfer ("siginfo", annex, writebuf, offset, len,
11431 xfered_len, PACKET_qXfer_siginfo_write);
11432 }
11433
11434 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11435 {
11436 if (readbuf)
11437 return remote_read_qxfer ("statictrace", annex,
11438 readbuf, offset, len, xfered_len,
11439 PACKET_qXfer_statictrace_read);
11440 else
11441 return TARGET_XFER_E_IO;
11442 }
11443
11444 /* Only handle flash writes. */
11445 if (writebuf != NULL)
11446 {
11447 switch (object)
11448 {
11449 case TARGET_OBJECT_FLASH:
11450 return remote_flash_write (offset, len, xfered_len,
11451 writebuf);
11452
11453 default:
11454 return TARGET_XFER_E_IO;
11455 }
11456 }
11457
11458 /* Map pre-existing objects onto letters. DO NOT do this for new
11459 objects!!! Instead specify new query packets. */
11460 switch (object)
11461 {
11462 case TARGET_OBJECT_AVR:
11463 query_type = 'R';
11464 break;
11465
11466 case TARGET_OBJECT_AUXV:
11467 gdb_assert (annex == NULL);
11468 return remote_read_qxfer
11469 ("auxv", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_auxv);
11470
11471 case TARGET_OBJECT_AVAILABLE_FEATURES:
11472 return remote_read_qxfer
11473 ("features", annex, readbuf, offset, len, xfered_len,
11474 PACKET_qXfer_features);
11475
11476 case TARGET_OBJECT_LIBRARIES:
11477 return remote_read_qxfer
11478 ("libraries", annex, readbuf, offset, len, xfered_len,
11479 PACKET_qXfer_libraries);
11480
11481 case TARGET_OBJECT_LIBRARIES_SVR4:
11482 return remote_read_qxfer
11483 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11484 PACKET_qXfer_libraries_svr4);
11485
11486 case TARGET_OBJECT_MEMORY_MAP:
11487 gdb_assert (annex == NULL);
11488 return remote_read_qxfer
11489 ("memory-map", annex, readbuf, offset, len, xfered_len,
11490 PACKET_qXfer_memory_map);
11491
11492 case TARGET_OBJECT_OSDATA:
11493 /* Should only get here if we're connected. */
11494 gdb_assert (rs->remote_desc);
11495 return remote_read_qxfer
11496 ("osdata", annex, readbuf, offset, len, xfered_len,
11497 PACKET_qXfer_osdata);
11498
11499 case TARGET_OBJECT_THREADS:
11500 gdb_assert (annex == NULL);
11501 return remote_read_qxfer
11502 ("threads", annex, readbuf, offset, len, xfered_len,
11503 PACKET_qXfer_threads);
11504
11505 case TARGET_OBJECT_TRACEFRAME_INFO:
11506 gdb_assert (annex == NULL);
11507 return remote_read_qxfer
11508 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11509 PACKET_qXfer_traceframe_info);
11510
11511 case TARGET_OBJECT_FDPIC:
11512 return remote_read_qxfer
11513 ("fdpic", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_fdpic);
11514
11515 case TARGET_OBJECT_OPENVMS_UIB:
11516 return remote_read_qxfer
11517 ("uib", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_uib);
11518
11519 case TARGET_OBJECT_BTRACE:
11520 return remote_read_qxfer
11521 ("btrace", annex, readbuf, offset, len, xfered_len,
11522 PACKET_qXfer_btrace);
11523
11524 case TARGET_OBJECT_BTRACE_CONF:
11525 return remote_read_qxfer
11526 ("btrace-conf", annex, readbuf, offset, len, xfered_len,
11527 PACKET_qXfer_btrace_conf);
11528
11529 case TARGET_OBJECT_EXEC_FILE:
11530 return remote_read_qxfer
11531 ("exec-file", annex, readbuf, offset, len, xfered_len,
11532 PACKET_qXfer_exec_file);
11533
11534 default:
11535 return TARGET_XFER_E_IO;
11536 }
11537
11538 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11539 large enough let the caller deal with it. */
11540 if (len < get_remote_packet_size ())
11541 return TARGET_XFER_E_IO;
11542 len = get_remote_packet_size ();
11543
11544 /* Except for querying the minimum buffer size, target must be open. */
11545 if (!rs->remote_desc)
11546 error (_("remote query is only available after target open"));
11547
11548 gdb_assert (annex != NULL);
11549 gdb_assert (readbuf != NULL);
11550
11551 p2 = rs->buf.data ();
11552 *p2++ = 'q';
11553 *p2++ = query_type;
11554
11555 /* We used one buffer char for the remote protocol q command and
11556 another for the query type. As the remote protocol encapsulation
11557 uses 4 chars plus one extra in case we are debugging
11558 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11559 string. */
11560 i = 0;
11561 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11562 {
11563 /* Bad caller may have sent forbidden characters. */
11564 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11565 *p2++ = annex[i];
11566 i++;
11567 }
11568 *p2 = '\0';
11569 gdb_assert (annex[i] == '\0');
11570
11571 i = putpkt (rs->buf);
11572 if (i < 0)
11573 return TARGET_XFER_E_IO;
11574
11575 getpkt (&rs->buf, 0);
11576 strcpy ((char *) readbuf, rs->buf.data ());
11577
11578 *xfered_len = strlen ((char *) readbuf);
11579 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11580 }
11581
11582 /* Implementation of to_get_memory_xfer_limit. */
11583
11584 ULONGEST
11585 remote_target::get_memory_xfer_limit ()
11586 {
11587 return get_memory_write_packet_size ();
11588 }
11589
11590 int
11591 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11592 const gdb_byte *pattern, ULONGEST pattern_len,
11593 CORE_ADDR *found_addrp)
11594 {
11595 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11596 struct remote_state *rs = get_remote_state ();
11597 int max_size = get_memory_write_packet_size ();
11598
11599 /* Number of packet bytes used to encode the pattern;
11600 this could be more than PATTERN_LEN due to escape characters. */
11601 int escaped_pattern_len;
11602 /* Amount of pattern that was encodable in the packet. */
11603 int used_pattern_len;
11604 int i;
11605 int found;
11606 ULONGEST found_addr;
11607
11608 auto read_memory = [=] (CORE_ADDR addr, gdb_byte *result, size_t len)
11609 {
11610 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11611 == len);
11612 };
11613
11614 /* Don't go to the target if we don't have to. This is done before
11615 checking packet_support to avoid the possibility that a success for this
11616 edge case means the facility works in general. */
11617 if (pattern_len > search_space_len)
11618 return 0;
11619 if (pattern_len == 0)
11620 {
11621 *found_addrp = start_addr;
11622 return 1;
11623 }
11624
11625 /* If we already know the packet isn't supported, fall back to the simple
11626 way of searching memory. */
11627
11628 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11629 {
11630 /* Target doesn't provided special support, fall back and use the
11631 standard support (copy memory and do the search here). */
11632 return simple_search_memory (read_memory, start_addr, search_space_len,
11633 pattern, pattern_len, found_addrp);
11634 }
11635
11636 /* Make sure the remote is pointing at the right process. */
11637 set_general_process ();
11638
11639 /* Insert header. */
11640 i = snprintf (rs->buf.data (), max_size,
11641 "qSearch:memory:%s;%s;",
11642 phex_nz (start_addr, addr_size),
11643 phex_nz (search_space_len, sizeof (search_space_len)));
11644 max_size -= (i + 1);
11645
11646 /* Escape as much data as fits into rs->buf. */
11647 escaped_pattern_len =
11648 remote_escape_output (pattern, pattern_len, 1,
11649 (gdb_byte *) rs->buf.data () + i,
11650 &used_pattern_len, max_size);
11651
11652 /* Bail if the pattern is too large. */
11653 if (used_pattern_len != pattern_len)
11654 error (_("Pattern is too large to transmit to remote target."));
11655
11656 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11657 || getpkt_sane (&rs->buf, 0) < 0
11658 || m_features.packet_ok (rs->buf, PACKET_qSearch_memory) != PACKET_OK)
11659 {
11660 /* The request may not have worked because the command is not
11661 supported. If so, fall back to the simple way. */
11662 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11663 {
11664 return simple_search_memory (read_memory, start_addr, search_space_len,
11665 pattern, pattern_len, found_addrp);
11666 }
11667 return -1;
11668 }
11669
11670 if (rs->buf[0] == '0')
11671 found = 0;
11672 else if (rs->buf[0] == '1')
11673 {
11674 found = 1;
11675 if (rs->buf[1] != ',')
11676 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11677 unpack_varlen_hex (&rs->buf[2], &found_addr);
11678 *found_addrp = found_addr;
11679 }
11680 else
11681 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11682
11683 return found;
11684 }
11685
11686 void
11687 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11688 {
11689 struct remote_state *rs = get_remote_state ();
11690 char *p = rs->buf.data ();
11691
11692 if (!rs->remote_desc)
11693 error (_("remote rcmd is only available after target open"));
11694
11695 /* Send a NULL command across as an empty command. */
11696 if (command == NULL)
11697 command = "";
11698
11699 /* The query prefix. */
11700 strcpy (rs->buf.data (), "qRcmd,");
11701 p = strchr (rs->buf.data (), '\0');
11702
11703 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11704 > get_remote_packet_size ())
11705 error (_("\"monitor\" command ``%s'' is too long."), command);
11706
11707 /* Encode the actual command. */
11708 bin2hex ((const gdb_byte *) command, p, strlen (command));
11709
11710 if (putpkt (rs->buf) < 0)
11711 error (_("Communication problem with target."));
11712
11713 /* get/display the response */
11714 while (1)
11715 {
11716 char *buf;
11717
11718 /* XXX - see also remote_get_noisy_reply(). */
11719 QUIT; /* Allow user to bail out with ^C. */
11720 rs->buf[0] = '\0';
11721 if (getpkt_sane (&rs->buf, 0) == -1)
11722 {
11723 /* Timeout. Continue to (try to) read responses.
11724 This is better than stopping with an error, assuming the stub
11725 is still executing the (long) monitor command.
11726 If needed, the user can interrupt gdb using C-c, obtaining
11727 an effect similar to stop on timeout. */
11728 continue;
11729 }
11730 buf = rs->buf.data ();
11731 if (buf[0] == '\0')
11732 error (_("Target does not support this command."));
11733 if (buf[0] == 'O' && buf[1] != 'K')
11734 {
11735 remote_console_output (buf + 1); /* 'O' message from stub. */
11736 continue;
11737 }
11738 if (strcmp (buf, "OK") == 0)
11739 break;
11740 if (strlen (buf) == 3 && buf[0] == 'E'
11741 && isxdigit (buf[1]) && isxdigit (buf[2]))
11742 {
11743 error (_("Protocol error with Rcmd"));
11744 }
11745 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11746 {
11747 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11748
11749 gdb_putc (c, outbuf);
11750 }
11751 break;
11752 }
11753 }
11754
11755 std::vector<mem_region>
11756 remote_target::memory_map ()
11757 {
11758 std::vector<mem_region> result;
11759 gdb::optional<gdb::char_vector> text
11760 = target_read_stralloc (current_inferior ()->top_target (),
11761 TARGET_OBJECT_MEMORY_MAP, NULL);
11762
11763 if (text)
11764 result = parse_memory_map (text->data ());
11765
11766 return result;
11767 }
11768
11769 /* Set of callbacks used to implement the 'maint packet' command. */
11770
11771 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
11772 {
11773 /* Called before the packet is sent. BUF is the packet content before
11774 the protocol specific prefix, suffix, and escaping is added. */
11775
11776 void sending (gdb::array_view<const char> &buf) override
11777 {
11778 gdb_puts ("sending: ");
11779 print_packet (buf);
11780 gdb_puts ("\n");
11781 }
11782
11783 /* Called with BUF, the reply from the remote target. */
11784
11785 void received (gdb::array_view<const char> &buf) override
11786 {
11787 gdb_puts ("received: \"");
11788 print_packet (buf);
11789 gdb_puts ("\"\n");
11790 }
11791
11792 private:
11793
11794 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11795 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11796
11797 static void
11798 print_packet (gdb::array_view<const char> &buf)
11799 {
11800 string_file stb;
11801
11802 for (int i = 0; i < buf.size (); ++i)
11803 {
11804 gdb_byte c = buf[i];
11805 if (isprint (c))
11806 gdb_putc (c, &stb);
11807 else
11808 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
11809 }
11810
11811 gdb_puts (stb.string ().c_str ());
11812 }
11813 };
11814
11815 /* See remote.h. */
11816
11817 void
11818 send_remote_packet (gdb::array_view<const char> &buf,
11819 send_remote_packet_callbacks *callbacks)
11820 {
11821 if (buf.size () == 0 || buf.data ()[0] == '\0')
11822 error (_("a remote packet must not be empty"));
11823
11824 remote_target *remote = get_current_remote_target ();
11825 if (remote == nullptr)
11826 error (_("packets can only be sent to a remote target"));
11827
11828 callbacks->sending (buf);
11829
11830 remote->putpkt_binary (buf.data (), buf.size ());
11831 remote_state *rs = remote->get_remote_state ();
11832 int bytes = remote->getpkt_sane (&rs->buf, 0);
11833
11834 if (bytes < 0)
11835 error (_("error while fetching packet from remote target"));
11836
11837 gdb::array_view<const char> view (&rs->buf[0], bytes);
11838 callbacks->received (view);
11839 }
11840
11841 /* Entry point for the 'maint packet' command. */
11842
11843 static void
11844 cli_packet_command (const char *args, int from_tty)
11845 {
11846 cli_packet_command_callbacks cb;
11847 gdb::array_view<const char> view
11848 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11849 send_remote_packet (view, &cb);
11850 }
11851
11852 #if 0
11853 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11854
11855 static void display_thread_info (struct gdb_ext_thread_info *info);
11856
11857 static void threadset_test_cmd (char *cmd, int tty);
11858
11859 static void threadalive_test (char *cmd, int tty);
11860
11861 static void threadlist_test_cmd (char *cmd, int tty);
11862
11863 int get_and_display_threadinfo (threadref *ref);
11864
11865 static void threadinfo_test_cmd (char *cmd, int tty);
11866
11867 static int thread_display_step (threadref *ref, void *context);
11868
11869 static void threadlist_update_test_cmd (char *cmd, int tty);
11870
11871 static void init_remote_threadtests (void);
11872
11873 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11874
11875 static void
11876 threadset_test_cmd (const char *cmd, int tty)
11877 {
11878 int sample_thread = SAMPLE_THREAD;
11879
11880 gdb_printf (_("Remote threadset test\n"));
11881 set_general_thread (sample_thread);
11882 }
11883
11884
11885 static void
11886 threadalive_test (const char *cmd, int tty)
11887 {
11888 int sample_thread = SAMPLE_THREAD;
11889 int pid = inferior_ptid.pid ();
11890 ptid_t ptid = ptid_t (pid, sample_thread, 0);
11891
11892 if (remote_thread_alive (ptid))
11893 gdb_printf ("PASS: Thread alive test\n");
11894 else
11895 gdb_printf ("FAIL: Thread alive test\n");
11896 }
11897
11898 void output_threadid (char *title, threadref *ref);
11899
11900 void
11901 output_threadid (char *title, threadref *ref)
11902 {
11903 char hexid[20];
11904
11905 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
11906 hexid[16] = 0;
11907 gdb_printf ("%s %s\n", title, (&hexid[0]));
11908 }
11909
11910 static void
11911 threadlist_test_cmd (const char *cmd, int tty)
11912 {
11913 int startflag = 1;
11914 threadref nextthread;
11915 int done, result_count;
11916 threadref threadlist[3];
11917
11918 gdb_printf ("Remote Threadlist test\n");
11919 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11920 &result_count, &threadlist[0]))
11921 gdb_printf ("FAIL: threadlist test\n");
11922 else
11923 {
11924 threadref *scan = threadlist;
11925 threadref *limit = scan + result_count;
11926
11927 while (scan < limit)
11928 output_threadid (" thread ", scan++);
11929 }
11930 }
11931
11932 void
11933 display_thread_info (struct gdb_ext_thread_info *info)
11934 {
11935 output_threadid ("Threadid: ", &info->threadid);
11936 gdb_printf ("Name: %s\n ", info->shortname);
11937 gdb_printf ("State: %s\n", info->display);
11938 gdb_printf ("other: %s\n\n", info->more_display);
11939 }
11940
11941 int
11942 get_and_display_threadinfo (threadref *ref)
11943 {
11944 int result;
11945 int set;
11946 struct gdb_ext_thread_info threadinfo;
11947
11948 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11949 | TAG_MOREDISPLAY | TAG_DISPLAY;
11950 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11951 display_thread_info (&threadinfo);
11952 return result;
11953 }
11954
11955 static void
11956 threadinfo_test_cmd (const char *cmd, int tty)
11957 {
11958 int athread = SAMPLE_THREAD;
11959 threadref thread;
11960 int set;
11961
11962 int_to_threadref (&thread, athread);
11963 gdb_printf ("Remote Threadinfo test\n");
11964 if (!get_and_display_threadinfo (&thread))
11965 gdb_printf ("FAIL cannot get thread info\n");
11966 }
11967
11968 static int
11969 thread_display_step (threadref *ref, void *context)
11970 {
11971 /* output_threadid(" threadstep ",ref); *//* simple test */
11972 return get_and_display_threadinfo (ref);
11973 }
11974
11975 static void
11976 threadlist_update_test_cmd (const char *cmd, int tty)
11977 {
11978 gdb_printf ("Remote Threadlist update test\n");
11979 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11980 }
11981
11982 static void
11983 init_remote_threadtests (void)
11984 {
11985 add_com ("tlist", class_obscure, threadlist_test_cmd,
11986 _("Fetch and print the remote list of "
11987 "thread identifiers, one pkt only."));
11988 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11989 _("Fetch and display info about one thread."));
11990 add_com ("tset", class_obscure, threadset_test_cmd,
11991 _("Test setting to a different thread."));
11992 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11993 _("Iterate through updating all remote thread info."));
11994 add_com ("talive", class_obscure, threadalive_test,
11995 _("Remote thread alive test."));
11996 }
11997
11998 #endif /* 0 */
11999
12000 /* Convert a thread ID to a string. */
12001
12002 std::string
12003 remote_target::pid_to_str (ptid_t ptid)
12004 {
12005 if (ptid == null_ptid)
12006 return normal_pid_to_str (ptid);
12007 else if (ptid.is_pid ())
12008 {
12009 /* Printing an inferior target id. */
12010
12011 /* When multi-process extensions are off, there's no way in the
12012 remote protocol to know the remote process id, if there's any
12013 at all. There's one exception --- when we're connected with
12014 target extended-remote, and we manually attached to a process
12015 with "attach PID". We don't record anywhere a flag that
12016 allows us to distinguish that case from the case of
12017 connecting with extended-remote and the stub already being
12018 attached to a process, and reporting yes to qAttached, hence
12019 no smart special casing here. */
12020 if (!m_features.remote_multi_process_p ())
12021 return "Remote target";
12022
12023 return normal_pid_to_str (ptid);
12024 }
12025 else
12026 {
12027 if (magic_null_ptid == ptid)
12028 return "Thread <main>";
12029 else if (m_features.remote_multi_process_p ())
12030 if (ptid.lwp () == 0)
12031 return normal_pid_to_str (ptid);
12032 else
12033 return string_printf ("Thread %d.%ld",
12034 ptid.pid (), ptid.lwp ());
12035 else
12036 return string_printf ("Thread %ld", ptid.lwp ());
12037 }
12038 }
12039
12040 /* Get the address of the thread local variable in OBJFILE which is
12041 stored at OFFSET within the thread local storage for thread PTID. */
12042
12043 CORE_ADDR
12044 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
12045 CORE_ADDR offset)
12046 {
12047 if (m_features.packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
12048 {
12049 struct remote_state *rs = get_remote_state ();
12050 char *p = rs->buf.data ();
12051 char *endp = p + get_remote_packet_size ();
12052 enum packet_result result;
12053
12054 strcpy (p, "qGetTLSAddr:");
12055 p += strlen (p);
12056 p = write_ptid (p, endp, ptid);
12057 *p++ = ',';
12058 p += hexnumstr (p, offset);
12059 *p++ = ',';
12060 p += hexnumstr (p, lm);
12061 *p++ = '\0';
12062
12063 putpkt (rs->buf);
12064 getpkt (&rs->buf, 0);
12065 result = m_features.packet_ok (rs->buf, PACKET_qGetTLSAddr);
12066 if (result == PACKET_OK)
12067 {
12068 ULONGEST addr;
12069
12070 unpack_varlen_hex (rs->buf.data (), &addr);
12071 return addr;
12072 }
12073 else if (result == PACKET_UNKNOWN)
12074 throw_error (TLS_GENERIC_ERROR,
12075 _("Remote target doesn't support qGetTLSAddr packet"));
12076 else
12077 throw_error (TLS_GENERIC_ERROR,
12078 _("Remote target failed to process qGetTLSAddr request"));
12079 }
12080 else
12081 throw_error (TLS_GENERIC_ERROR,
12082 _("TLS not supported or disabled on this target"));
12083 /* Not reached. */
12084 return 0;
12085 }
12086
12087 /* Provide thread local base, i.e. Thread Information Block address.
12088 Returns 1 if ptid is found and thread_local_base is non zero. */
12089
12090 bool
12091 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
12092 {
12093 if (m_features.packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
12094 {
12095 struct remote_state *rs = get_remote_state ();
12096 char *p = rs->buf.data ();
12097 char *endp = p + get_remote_packet_size ();
12098 enum packet_result result;
12099
12100 strcpy (p, "qGetTIBAddr:");
12101 p += strlen (p);
12102 p = write_ptid (p, endp, ptid);
12103 *p++ = '\0';
12104
12105 putpkt (rs->buf);
12106 getpkt (&rs->buf, 0);
12107 result = m_features.packet_ok (rs->buf, PACKET_qGetTIBAddr);
12108 if (result == PACKET_OK)
12109 {
12110 ULONGEST val;
12111 unpack_varlen_hex (rs->buf.data (), &val);
12112 if (addr)
12113 *addr = (CORE_ADDR) val;
12114 return true;
12115 }
12116 else if (result == PACKET_UNKNOWN)
12117 error (_("Remote target doesn't support qGetTIBAddr packet"));
12118 else
12119 error (_("Remote target failed to process qGetTIBAddr request"));
12120 }
12121 else
12122 error (_("qGetTIBAddr not supported or disabled on this target"));
12123 /* Not reached. */
12124 return false;
12125 }
12126
12127 /* Support for inferring a target description based on the current
12128 architecture and the size of a 'g' packet. While the 'g' packet
12129 can have any size (since optional registers can be left off the
12130 end), some sizes are easily recognizable given knowledge of the
12131 approximate architecture. */
12132
12133 struct remote_g_packet_guess
12134 {
12135 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
12136 : bytes (bytes_),
12137 tdesc (tdesc_)
12138 {
12139 }
12140
12141 int bytes;
12142 const struct target_desc *tdesc;
12143 };
12144
12145 struct remote_g_packet_data
12146 {
12147 std::vector<remote_g_packet_guess> guesses;
12148 };
12149
12150 static const registry<gdbarch>::key<struct remote_g_packet_data>
12151 remote_g_packet_data_handle;
12152
12153 static struct remote_g_packet_data *
12154 get_g_packet_data (struct gdbarch *gdbarch)
12155 {
12156 struct remote_g_packet_data *data
12157 = remote_g_packet_data_handle.get (gdbarch);
12158 if (data == nullptr)
12159 data = remote_g_packet_data_handle.emplace (gdbarch);
12160 return data;
12161 }
12162
12163 void
12164 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12165 const struct target_desc *tdesc)
12166 {
12167 struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
12168
12169 gdb_assert (tdesc != NULL);
12170
12171 for (const remote_g_packet_guess &guess : data->guesses)
12172 if (guess.bytes == bytes)
12173 internal_error (_("Duplicate g packet description added for size %d"),
12174 bytes);
12175
12176 data->guesses.emplace_back (bytes, tdesc);
12177 }
12178
12179 /* Return true if remote_read_description would do anything on this target
12180 and architecture, false otherwise. */
12181
12182 static bool
12183 remote_read_description_p (struct target_ops *target)
12184 {
12185 struct remote_g_packet_data *data = get_g_packet_data (target_gdbarch ());
12186
12187 return !data->guesses.empty ();
12188 }
12189
12190 const struct target_desc *
12191 remote_target::read_description ()
12192 {
12193 struct remote_g_packet_data *data = get_g_packet_data (target_gdbarch ());
12194
12195 /* Do not try this during initial connection, when we do not know
12196 whether there is a running but stopped thread. */
12197 if (!target_has_execution () || inferior_ptid == null_ptid)
12198 return beneath ()->read_description ();
12199
12200 if (!data->guesses.empty ())
12201 {
12202 int bytes = send_g_packet ();
12203
12204 for (const remote_g_packet_guess &guess : data->guesses)
12205 if (guess.bytes == bytes)
12206 return guess.tdesc;
12207
12208 /* We discard the g packet. A minor optimization would be to
12209 hold on to it, and fill the register cache once we have selected
12210 an architecture, but it's too tricky to do safely. */
12211 }
12212
12213 return beneath ()->read_description ();
12214 }
12215
12216 /* Remote file transfer support. This is host-initiated I/O, not
12217 target-initiated; for target-initiated, see remote-fileio.c. */
12218
12219 /* If *LEFT is at least the length of STRING, copy STRING to
12220 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12221 decrease *LEFT. Otherwise raise an error. */
12222
12223 static void
12224 remote_buffer_add_string (char **buffer, int *left, const char *string)
12225 {
12226 int len = strlen (string);
12227
12228 if (len > *left)
12229 error (_("Packet too long for target."));
12230
12231 memcpy (*buffer, string, len);
12232 *buffer += len;
12233 *left -= len;
12234
12235 /* NUL-terminate the buffer as a convenience, if there is
12236 room. */
12237 if (*left)
12238 **buffer = '\0';
12239 }
12240
12241 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12242 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12243 decrease *LEFT. Otherwise raise an error. */
12244
12245 static void
12246 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12247 int len)
12248 {
12249 if (2 * len > *left)
12250 error (_("Packet too long for target."));
12251
12252 bin2hex (bytes, *buffer, len);
12253 *buffer += 2 * len;
12254 *left -= 2 * len;
12255
12256 /* NUL-terminate the buffer as a convenience, if there is
12257 room. */
12258 if (*left)
12259 **buffer = '\0';
12260 }
12261
12262 /* If *LEFT is large enough, convert VALUE to hex and add it to
12263 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12264 decrease *LEFT. Otherwise raise an error. */
12265
12266 static void
12267 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12268 {
12269 int len = hexnumlen (value);
12270
12271 if (len > *left)
12272 error (_("Packet too long for target."));
12273
12274 hexnumstr (*buffer, value);
12275 *buffer += len;
12276 *left -= len;
12277
12278 /* NUL-terminate the buffer as a convenience, if there is
12279 room. */
12280 if (*left)
12281 **buffer = '\0';
12282 }
12283
12284 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12285 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
12286 was included, and *ATTACHMENT to point to the start of the annex
12287 if any. The length of the packet isn't needed here; there may
12288 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12289
12290 Return 0 if the packet could be parsed, -1 if it could not. If
12291 -1 is returned, the other variables may not be initialized. */
12292
12293 static int
12294 remote_hostio_parse_result (const char *buffer, int *retcode,
12295 fileio_error *remote_errno, const char **attachment)
12296 {
12297 char *p, *p2;
12298
12299 *remote_errno = FILEIO_SUCCESS;
12300 *attachment = NULL;
12301
12302 if (buffer[0] != 'F')
12303 return -1;
12304
12305 errno = 0;
12306 *retcode = strtol (&buffer[1], &p, 16);
12307 if (errno != 0 || p == &buffer[1])
12308 return -1;
12309
12310 /* Check for ",errno". */
12311 if (*p == ',')
12312 {
12313 errno = 0;
12314 *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
12315 if (errno != 0 || p + 1 == p2)
12316 return -1;
12317 p = p2;
12318 }
12319
12320 /* Check for ";attachment". If there is no attachment, the
12321 packet should end here. */
12322 if (*p == ';')
12323 {
12324 *attachment = p + 1;
12325 return 0;
12326 }
12327 else if (*p == '\0')
12328 return 0;
12329 else
12330 return -1;
12331 }
12332
12333 /* Send a prepared I/O packet to the target and read its response.
12334 The prepared packet is in the global RS->BUF before this function
12335 is called, and the answer is there when we return.
12336
12337 COMMAND_BYTES is the length of the request to send, which may include
12338 binary data. WHICH_PACKET is the packet configuration to check
12339 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12340 is set to the error number and -1 is returned. Otherwise the value
12341 returned by the function is returned.
12342
12343 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12344 attachment is expected; an error will be reported if there's a
12345 mismatch. If one is found, *ATTACHMENT will be set to point into
12346 the packet buffer and *ATTACHMENT_LEN will be set to the
12347 attachment's length. */
12348
12349 int
12350 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12351 fileio_error *remote_errno, const char **attachment,
12352 int *attachment_len)
12353 {
12354 struct remote_state *rs = get_remote_state ();
12355 int ret, bytes_read;
12356 const char *attachment_tmp;
12357
12358 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
12359 {
12360 *remote_errno = FILEIO_ENOSYS;
12361 return -1;
12362 }
12363
12364 putpkt_binary (rs->buf.data (), command_bytes);
12365 bytes_read = getpkt_sane (&rs->buf, 0);
12366
12367 /* If it timed out, something is wrong. Don't try to parse the
12368 buffer. */
12369 if (bytes_read < 0)
12370 {
12371 *remote_errno = FILEIO_EINVAL;
12372 return -1;
12373 }
12374
12375 switch (m_features.packet_ok (rs->buf, which_packet))
12376 {
12377 case PACKET_ERROR:
12378 *remote_errno = FILEIO_EINVAL;
12379 return -1;
12380 case PACKET_UNKNOWN:
12381 *remote_errno = FILEIO_ENOSYS;
12382 return -1;
12383 case PACKET_OK:
12384 break;
12385 }
12386
12387 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12388 &attachment_tmp))
12389 {
12390 *remote_errno = FILEIO_EINVAL;
12391 return -1;
12392 }
12393
12394 /* Make sure we saw an attachment if and only if we expected one. */
12395 if ((attachment_tmp == NULL && attachment != NULL)
12396 || (attachment_tmp != NULL && attachment == NULL))
12397 {
12398 *remote_errno = FILEIO_EINVAL;
12399 return -1;
12400 }
12401
12402 /* If an attachment was found, it must point into the packet buffer;
12403 work out how many bytes there were. */
12404 if (attachment_tmp != NULL)
12405 {
12406 *attachment = attachment_tmp;
12407 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12408 }
12409
12410 return ret;
12411 }
12412
12413 /* See declaration.h. */
12414
12415 void
12416 readahead_cache::invalidate ()
12417 {
12418 this->fd = -1;
12419 }
12420
12421 /* See declaration.h. */
12422
12423 void
12424 readahead_cache::invalidate_fd (int fd)
12425 {
12426 if (this->fd == fd)
12427 this->fd = -1;
12428 }
12429
12430 /* Set the filesystem remote_hostio functions that take FILENAME
12431 arguments will use. Return 0 on success, or -1 if an error
12432 occurs (and set *REMOTE_ERRNO). */
12433
12434 int
12435 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12436 fileio_error *remote_errno)
12437 {
12438 struct remote_state *rs = get_remote_state ();
12439 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12440 char *p = rs->buf.data ();
12441 int left = get_remote_packet_size () - 1;
12442 char arg[9];
12443 int ret;
12444
12445 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12446 return 0;
12447
12448 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12449 return 0;
12450
12451 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12452
12453 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12454 remote_buffer_add_string (&p, &left, arg);
12455
12456 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12457 remote_errno, NULL, NULL);
12458
12459 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12460 return 0;
12461
12462 if (ret == 0)
12463 rs->fs_pid = required_pid;
12464
12465 return ret;
12466 }
12467
12468 /* Implementation of to_fileio_open. */
12469
12470 int
12471 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12472 int flags, int mode, int warn_if_slow,
12473 fileio_error *remote_errno)
12474 {
12475 struct remote_state *rs = get_remote_state ();
12476 char *p = rs->buf.data ();
12477 int left = get_remote_packet_size () - 1;
12478
12479 if (warn_if_slow)
12480 {
12481 static int warning_issued = 0;
12482
12483 gdb_printf (_("Reading %s from remote target...\n"),
12484 filename);
12485
12486 if (!warning_issued)
12487 {
12488 warning (_("File transfers from remote targets can be slow."
12489 " Use \"set sysroot\" to access files locally"
12490 " instead."));
12491 warning_issued = 1;
12492 }
12493 }
12494
12495 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12496 return -1;
12497
12498 remote_buffer_add_string (&p, &left, "vFile:open:");
12499
12500 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12501 strlen (filename));
12502 remote_buffer_add_string (&p, &left, ",");
12503
12504 remote_buffer_add_int (&p, &left, flags);
12505 remote_buffer_add_string (&p, &left, ",");
12506
12507 remote_buffer_add_int (&p, &left, mode);
12508
12509 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12510 remote_errno, NULL, NULL);
12511 }
12512
12513 int
12514 remote_target::fileio_open (struct inferior *inf, const char *filename,
12515 int flags, int mode, int warn_if_slow,
12516 fileio_error *remote_errno)
12517 {
12518 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12519 remote_errno);
12520 }
12521
12522 /* Implementation of to_fileio_pwrite. */
12523
12524 int
12525 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12526 ULONGEST offset, fileio_error *remote_errno)
12527 {
12528 struct remote_state *rs = get_remote_state ();
12529 char *p = rs->buf.data ();
12530 int left = get_remote_packet_size ();
12531 int out_len;
12532
12533 rs->readahead_cache.invalidate_fd (fd);
12534
12535 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12536
12537 remote_buffer_add_int (&p, &left, fd);
12538 remote_buffer_add_string (&p, &left, ",");
12539
12540 remote_buffer_add_int (&p, &left, offset);
12541 remote_buffer_add_string (&p, &left, ",");
12542
12543 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12544 (get_remote_packet_size ()
12545 - (p - rs->buf.data ())));
12546
12547 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12548 remote_errno, NULL, NULL);
12549 }
12550
12551 int
12552 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12553 ULONGEST offset, fileio_error *remote_errno)
12554 {
12555 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12556 }
12557
12558 /* Helper for the implementation of to_fileio_pread. Read the file
12559 from the remote side with vFile:pread. */
12560
12561 int
12562 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12563 ULONGEST offset, fileio_error *remote_errno)
12564 {
12565 struct remote_state *rs = get_remote_state ();
12566 char *p = rs->buf.data ();
12567 const char *attachment;
12568 int left = get_remote_packet_size ();
12569 int ret, attachment_len;
12570 int read_len;
12571
12572 remote_buffer_add_string (&p, &left, "vFile:pread:");
12573
12574 remote_buffer_add_int (&p, &left, fd);
12575 remote_buffer_add_string (&p, &left, ",");
12576
12577 remote_buffer_add_int (&p, &left, len);
12578 remote_buffer_add_string (&p, &left, ",");
12579
12580 remote_buffer_add_int (&p, &left, offset);
12581
12582 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12583 remote_errno, &attachment,
12584 &attachment_len);
12585
12586 if (ret < 0)
12587 return ret;
12588
12589 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12590 read_buf, len);
12591 if (read_len != ret)
12592 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12593
12594 return ret;
12595 }
12596
12597 /* See declaration.h. */
12598
12599 int
12600 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12601 ULONGEST offset)
12602 {
12603 if (this->fd == fd
12604 && this->offset <= offset
12605 && offset < this->offset + this->buf.size ())
12606 {
12607 ULONGEST max = this->offset + this->buf.size ();
12608
12609 if (offset + len > max)
12610 len = max - offset;
12611
12612 memcpy (read_buf, &this->buf[offset - this->offset], len);
12613 return len;
12614 }
12615
12616 return 0;
12617 }
12618
12619 /* Implementation of to_fileio_pread. */
12620
12621 int
12622 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12623 ULONGEST offset, fileio_error *remote_errno)
12624 {
12625 int ret;
12626 struct remote_state *rs = get_remote_state ();
12627 readahead_cache *cache = &rs->readahead_cache;
12628
12629 ret = cache->pread (fd, read_buf, len, offset);
12630 if (ret > 0)
12631 {
12632 cache->hit_count++;
12633
12634 remote_debug_printf ("readahead cache hit %s",
12635 pulongest (cache->hit_count));
12636 return ret;
12637 }
12638
12639 cache->miss_count++;
12640
12641 remote_debug_printf ("readahead cache miss %s",
12642 pulongest (cache->miss_count));
12643
12644 cache->fd = fd;
12645 cache->offset = offset;
12646 cache->buf.resize (get_remote_packet_size ());
12647
12648 ret = remote_hostio_pread_vFile (cache->fd, &cache->buf[0],
12649 cache->buf.size (),
12650 cache->offset, remote_errno);
12651 if (ret <= 0)
12652 {
12653 cache->invalidate_fd (fd);
12654 return ret;
12655 }
12656
12657 cache->buf.resize (ret);
12658 return cache->pread (fd, read_buf, len, offset);
12659 }
12660
12661 int
12662 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12663 ULONGEST offset, fileio_error *remote_errno)
12664 {
12665 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12666 }
12667
12668 /* Implementation of to_fileio_close. */
12669
12670 int
12671 remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
12672 {
12673 struct remote_state *rs = get_remote_state ();
12674 char *p = rs->buf.data ();
12675 int left = get_remote_packet_size () - 1;
12676
12677 rs->readahead_cache.invalidate_fd (fd);
12678
12679 remote_buffer_add_string (&p, &left, "vFile:close:");
12680
12681 remote_buffer_add_int (&p, &left, fd);
12682
12683 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12684 remote_errno, NULL, NULL);
12685 }
12686
12687 int
12688 remote_target::fileio_close (int fd, fileio_error *remote_errno)
12689 {
12690 return remote_hostio_close (fd, remote_errno);
12691 }
12692
12693 /* Implementation of to_fileio_unlink. */
12694
12695 int
12696 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12697 fileio_error *remote_errno)
12698 {
12699 struct remote_state *rs = get_remote_state ();
12700 char *p = rs->buf.data ();
12701 int left = get_remote_packet_size () - 1;
12702
12703 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12704 return -1;
12705
12706 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12707
12708 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12709 strlen (filename));
12710
12711 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12712 remote_errno, NULL, NULL);
12713 }
12714
12715 int
12716 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12717 fileio_error *remote_errno)
12718 {
12719 return remote_hostio_unlink (inf, filename, remote_errno);
12720 }
12721
12722 /* Implementation of to_fileio_readlink. */
12723
12724 gdb::optional<std::string>
12725 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12726 fileio_error *remote_errno)
12727 {
12728 struct remote_state *rs = get_remote_state ();
12729 char *p = rs->buf.data ();
12730 const char *attachment;
12731 int left = get_remote_packet_size ();
12732 int len, attachment_len;
12733 int read_len;
12734
12735 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12736 return {};
12737
12738 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12739
12740 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12741 strlen (filename));
12742
12743 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12744 remote_errno, &attachment,
12745 &attachment_len);
12746
12747 if (len < 0)
12748 return {};
12749
12750 std::string ret (len, '\0');
12751
12752 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12753 (gdb_byte *) &ret[0], len);
12754 if (read_len != len)
12755 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12756
12757 return ret;
12758 }
12759
12760 /* Implementation of to_fileio_fstat. */
12761
12762 int
12763 remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
12764 {
12765 struct remote_state *rs = get_remote_state ();
12766 char *p = rs->buf.data ();
12767 int left = get_remote_packet_size ();
12768 int attachment_len, ret;
12769 const char *attachment;
12770 struct fio_stat fst;
12771 int read_len;
12772
12773 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12774
12775 remote_buffer_add_int (&p, &left, fd);
12776
12777 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12778 remote_errno, &attachment,
12779 &attachment_len);
12780 if (ret < 0)
12781 {
12782 if (*remote_errno != FILEIO_ENOSYS)
12783 return ret;
12784
12785 /* Strictly we should return -1, ENOSYS here, but when
12786 "set sysroot remote:" was implemented in August 2008
12787 BFD's need for a stat function was sidestepped with
12788 this hack. This was not remedied until March 2015
12789 so we retain the previous behavior to avoid breaking
12790 compatibility.
12791
12792 Note that the memset is a March 2015 addition; older
12793 GDBs set st_size *and nothing else* so the structure
12794 would have garbage in all other fields. This might
12795 break something but retaining the previous behavior
12796 here would be just too wrong. */
12797
12798 memset (st, 0, sizeof (struct stat));
12799 st->st_size = INT_MAX;
12800 return 0;
12801 }
12802
12803 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12804 (gdb_byte *) &fst, sizeof (fst));
12805
12806 if (read_len != ret)
12807 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12808
12809 if (read_len != sizeof (fst))
12810 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12811 read_len, (int) sizeof (fst));
12812
12813 remote_fileio_to_host_stat (&fst, st);
12814
12815 return 0;
12816 }
12817
12818 /* Implementation of to_filesystem_is_local. */
12819
12820 bool
12821 remote_target::filesystem_is_local ()
12822 {
12823 /* Valgrind GDB presents itself as a remote target but works
12824 on the local filesystem: it does not implement remote get
12825 and users are not expected to set a sysroot. To handle
12826 this case we treat the remote filesystem as local if the
12827 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12828 does not support vFile:open. */
12829 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
12830 {
12831 packet_support ps = m_features.packet_support (PACKET_vFile_open);
12832
12833 if (ps == PACKET_SUPPORT_UNKNOWN)
12834 {
12835 int fd;
12836 fileio_error remote_errno;
12837
12838 /* Try opening a file to probe support. The supplied
12839 filename is irrelevant, we only care about whether
12840 the stub recognizes the packet or not. */
12841 fd = remote_hostio_open (NULL, "just probing",
12842 FILEIO_O_RDONLY, 0700, 0,
12843 &remote_errno);
12844
12845 if (fd >= 0)
12846 remote_hostio_close (fd, &remote_errno);
12847
12848 ps = m_features.packet_support (PACKET_vFile_open);
12849 }
12850
12851 if (ps == PACKET_DISABLE)
12852 {
12853 static int warning_issued = 0;
12854
12855 if (!warning_issued)
12856 {
12857 warning (_("remote target does not support file"
12858 " transfer, attempting to access files"
12859 " from local filesystem."));
12860 warning_issued = 1;
12861 }
12862
12863 return true;
12864 }
12865 }
12866
12867 return false;
12868 }
12869
12870 static char *
12871 remote_hostio_error (fileio_error errnum)
12872 {
12873 int host_error = fileio_error_to_host (errnum);
12874
12875 if (host_error == -1)
12876 error (_("Unknown remote I/O error %d"), errnum);
12877 else
12878 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12879 }
12880
12881 /* A RAII wrapper around a remote file descriptor. */
12882
12883 class scoped_remote_fd
12884 {
12885 public:
12886 scoped_remote_fd (remote_target *remote, int fd)
12887 : m_remote (remote), m_fd (fd)
12888 {
12889 }
12890
12891 ~scoped_remote_fd ()
12892 {
12893 if (m_fd != -1)
12894 {
12895 try
12896 {
12897 fileio_error remote_errno;
12898 m_remote->remote_hostio_close (m_fd, &remote_errno);
12899 }
12900 catch (...)
12901 {
12902 /* Swallow exception before it escapes the dtor. If
12903 something goes wrong, likely the connection is gone,
12904 and there's nothing else that can be done. */
12905 }
12906 }
12907 }
12908
12909 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12910
12911 /* Release ownership of the file descriptor, and return it. */
12912 ATTRIBUTE_UNUSED_RESULT int release () noexcept
12913 {
12914 int fd = m_fd;
12915 m_fd = -1;
12916 return fd;
12917 }
12918
12919 /* Return the owned file descriptor. */
12920 int get () const noexcept
12921 {
12922 return m_fd;
12923 }
12924
12925 private:
12926 /* The remote target. */
12927 remote_target *m_remote;
12928
12929 /* The owned remote I/O file descriptor. */
12930 int m_fd;
12931 };
12932
12933 void
12934 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12935 {
12936 remote_target *remote = get_current_remote_target ();
12937
12938 if (remote == nullptr)
12939 error (_("command can only be used with remote target"));
12940
12941 remote->remote_file_put (local_file, remote_file, from_tty);
12942 }
12943
12944 void
12945 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12946 int from_tty)
12947 {
12948 int retcode, bytes, io_size;
12949 fileio_error remote_errno;
12950 int bytes_in_buffer;
12951 int saw_eof;
12952 ULONGEST offset;
12953
12954 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12955 if (file == NULL)
12956 perror_with_name (local_file);
12957
12958 scoped_remote_fd fd
12959 (this, remote_hostio_open (NULL,
12960 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12961 | FILEIO_O_TRUNC),
12962 0700, 0, &remote_errno));
12963 if (fd.get () == -1)
12964 remote_hostio_error (remote_errno);
12965
12966 /* Send up to this many bytes at once. They won't all fit in the
12967 remote packet limit, so we'll transfer slightly fewer. */
12968 io_size = get_remote_packet_size ();
12969 gdb::byte_vector buffer (io_size);
12970
12971 bytes_in_buffer = 0;
12972 saw_eof = 0;
12973 offset = 0;
12974 while (bytes_in_buffer || !saw_eof)
12975 {
12976 if (!saw_eof)
12977 {
12978 bytes = fread (buffer.data () + bytes_in_buffer, 1,
12979 io_size - bytes_in_buffer,
12980 file.get ());
12981 if (bytes == 0)
12982 {
12983 if (ferror (file.get ()))
12984 error (_("Error reading %s."), local_file);
12985 else
12986 {
12987 /* EOF. Unless there is something still in the
12988 buffer from the last iteration, we are done. */
12989 saw_eof = 1;
12990 if (bytes_in_buffer == 0)
12991 break;
12992 }
12993 }
12994 }
12995 else
12996 bytes = 0;
12997
12998 bytes += bytes_in_buffer;
12999 bytes_in_buffer = 0;
13000
13001 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
13002 offset, &remote_errno);
13003
13004 if (retcode < 0)
13005 remote_hostio_error (remote_errno);
13006 else if (retcode == 0)
13007 error (_("Remote write of %d bytes returned 0!"), bytes);
13008 else if (retcode < bytes)
13009 {
13010 /* Short write. Save the rest of the read data for the next
13011 write. */
13012 bytes_in_buffer = bytes - retcode;
13013 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
13014 }
13015
13016 offset += retcode;
13017 }
13018
13019 if (remote_hostio_close (fd.release (), &remote_errno))
13020 remote_hostio_error (remote_errno);
13021
13022 if (from_tty)
13023 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
13024 }
13025
13026 void
13027 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
13028 {
13029 remote_target *remote = get_current_remote_target ();
13030
13031 if (remote == nullptr)
13032 error (_("command can only be used with remote target"));
13033
13034 remote->remote_file_get (remote_file, local_file, from_tty);
13035 }
13036
13037 void
13038 remote_target::remote_file_get (const char *remote_file, const char *local_file,
13039 int from_tty)
13040 {
13041 fileio_error remote_errno;
13042 int bytes, io_size;
13043 ULONGEST offset;
13044
13045 scoped_remote_fd fd
13046 (this, remote_hostio_open (NULL,
13047 remote_file, FILEIO_O_RDONLY, 0, 0,
13048 &remote_errno));
13049 if (fd.get () == -1)
13050 remote_hostio_error (remote_errno);
13051
13052 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
13053 if (file == NULL)
13054 perror_with_name (local_file);
13055
13056 /* Send up to this many bytes at once. They won't all fit in the
13057 remote packet limit, so we'll transfer slightly fewer. */
13058 io_size = get_remote_packet_size ();
13059 gdb::byte_vector buffer (io_size);
13060
13061 offset = 0;
13062 while (1)
13063 {
13064 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
13065 &remote_errno);
13066 if (bytes == 0)
13067 /* Success, but no bytes, means end-of-file. */
13068 break;
13069 if (bytes == -1)
13070 remote_hostio_error (remote_errno);
13071
13072 offset += bytes;
13073
13074 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
13075 if (bytes == 0)
13076 perror_with_name (local_file);
13077 }
13078
13079 if (remote_hostio_close (fd.release (), &remote_errno))
13080 remote_hostio_error (remote_errno);
13081
13082 if (from_tty)
13083 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
13084 }
13085
13086 void
13087 remote_file_delete (const char *remote_file, int from_tty)
13088 {
13089 remote_target *remote = get_current_remote_target ();
13090
13091 if (remote == nullptr)
13092 error (_("command can only be used with remote target"));
13093
13094 remote->remote_file_delete (remote_file, from_tty);
13095 }
13096
13097 void
13098 remote_target::remote_file_delete (const char *remote_file, int from_tty)
13099 {
13100 int retcode;
13101 fileio_error remote_errno;
13102
13103 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
13104 if (retcode == -1)
13105 remote_hostio_error (remote_errno);
13106
13107 if (from_tty)
13108 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
13109 }
13110
13111 static void
13112 remote_put_command (const char *args, int from_tty)
13113 {
13114 if (args == NULL)
13115 error_no_arg (_("file to put"));
13116
13117 gdb_argv argv (args);
13118 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13119 error (_("Invalid parameters to remote put"));
13120
13121 remote_file_put (argv[0], argv[1], from_tty);
13122 }
13123
13124 static void
13125 remote_get_command (const char *args, int from_tty)
13126 {
13127 if (args == NULL)
13128 error_no_arg (_("file to get"));
13129
13130 gdb_argv argv (args);
13131 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13132 error (_("Invalid parameters to remote get"));
13133
13134 remote_file_get (argv[0], argv[1], from_tty);
13135 }
13136
13137 static void
13138 remote_delete_command (const char *args, int from_tty)
13139 {
13140 if (args == NULL)
13141 error_no_arg (_("file to delete"));
13142
13143 gdb_argv argv (args);
13144 if (argv[0] == NULL || argv[1] != NULL)
13145 error (_("Invalid parameters to remote delete"));
13146
13147 remote_file_delete (argv[0], from_tty);
13148 }
13149
13150 bool
13151 remote_target::can_execute_reverse ()
13152 {
13153 if (m_features.packet_support (PACKET_bs) == PACKET_ENABLE
13154 || m_features.packet_support (PACKET_bc) == PACKET_ENABLE)
13155 return true;
13156 else
13157 return false;
13158 }
13159
13160 bool
13161 remote_target::supports_non_stop ()
13162 {
13163 return true;
13164 }
13165
13166 bool
13167 remote_target::supports_disable_randomization ()
13168 {
13169 /* Only supported in extended mode. */
13170 return false;
13171 }
13172
13173 bool
13174 remote_target::supports_multi_process ()
13175 {
13176 return m_features.remote_multi_process_p ();
13177 }
13178
13179 int
13180 remote_target::remote_supports_cond_tracepoints ()
13181 {
13182 return (m_features.packet_support (PACKET_ConditionalTracepoints)
13183 == PACKET_ENABLE);
13184 }
13185
13186 bool
13187 remote_target::supports_evaluation_of_breakpoint_conditions ()
13188 {
13189 return (m_features.packet_support (PACKET_ConditionalBreakpoints)
13190 == PACKET_ENABLE);
13191 }
13192
13193 int
13194 remote_target::remote_supports_fast_tracepoints ()
13195 {
13196 return m_features.packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13197 }
13198
13199 int
13200 remote_target::remote_supports_static_tracepoints ()
13201 {
13202 return m_features.packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13203 }
13204
13205 int
13206 remote_target::remote_supports_install_in_trace ()
13207 {
13208 return m_features.packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13209 }
13210
13211 bool
13212 remote_target::supports_enable_disable_tracepoint ()
13213 {
13214 return (m_features.packet_support (PACKET_EnableDisableTracepoints_feature)
13215 == PACKET_ENABLE);
13216 }
13217
13218 bool
13219 remote_target::supports_string_tracing ()
13220 {
13221 return m_features.packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13222 }
13223
13224 bool
13225 remote_target::can_run_breakpoint_commands ()
13226 {
13227 return m_features.packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13228 }
13229
13230 void
13231 remote_target::trace_init ()
13232 {
13233 struct remote_state *rs = get_remote_state ();
13234
13235 putpkt ("QTinit");
13236 remote_get_noisy_reply ();
13237 if (strcmp (rs->buf.data (), "OK") != 0)
13238 error (_("Target does not support this command."));
13239 }
13240
13241 /* Recursive routine to walk through command list including loops, and
13242 download packets for each command. */
13243
13244 void
13245 remote_target::remote_download_command_source (int num, ULONGEST addr,
13246 struct command_line *cmds)
13247 {
13248 struct remote_state *rs = get_remote_state ();
13249 struct command_line *cmd;
13250
13251 for (cmd = cmds; cmd; cmd = cmd->next)
13252 {
13253 QUIT; /* Allow user to bail out with ^C. */
13254 strcpy (rs->buf.data (), "QTDPsrc:");
13255 encode_source_string (num, addr, "cmd", cmd->line,
13256 rs->buf.data () + strlen (rs->buf.data ()),
13257 rs->buf.size () - strlen (rs->buf.data ()));
13258 putpkt (rs->buf);
13259 remote_get_noisy_reply ();
13260 if (strcmp (rs->buf.data (), "OK"))
13261 warning (_("Target does not support source download."));
13262
13263 if (cmd->control_type == while_control
13264 || cmd->control_type == while_stepping_control)
13265 {
13266 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13267
13268 QUIT; /* Allow user to bail out with ^C. */
13269 strcpy (rs->buf.data (), "QTDPsrc:");
13270 encode_source_string (num, addr, "cmd", "end",
13271 rs->buf.data () + strlen (rs->buf.data ()),
13272 rs->buf.size () - strlen (rs->buf.data ()));
13273 putpkt (rs->buf);
13274 remote_get_noisy_reply ();
13275 if (strcmp (rs->buf.data (), "OK"))
13276 warning (_("Target does not support source download."));
13277 }
13278 }
13279 }
13280
13281 void
13282 remote_target::download_tracepoint (struct bp_location *loc)
13283 {
13284 CORE_ADDR tpaddr;
13285 char addrbuf[40];
13286 std::vector<std::string> tdp_actions;
13287 std::vector<std::string> stepping_actions;
13288 char *pkt;
13289 struct breakpoint *b = loc->owner;
13290 struct tracepoint *t = (struct tracepoint *) b;
13291 struct remote_state *rs = get_remote_state ();
13292 int ret;
13293 const char *err_msg = _("Tracepoint packet too large for target.");
13294 size_t size_left;
13295
13296 /* We use a buffer other than rs->buf because we'll build strings
13297 across multiple statements, and other statements in between could
13298 modify rs->buf. */
13299 gdb::char_vector buf (get_remote_packet_size ());
13300
13301 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13302
13303 tpaddr = loc->address;
13304 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13305 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13306 b->number, addrbuf, /* address */
13307 (b->enable_state == bp_enabled ? 'E' : 'D'),
13308 t->step_count, t->pass_count);
13309
13310 if (ret < 0 || ret >= buf.size ())
13311 error ("%s", err_msg);
13312
13313 /* Fast tracepoints are mostly handled by the target, but we can
13314 tell the target how big of an instruction block should be moved
13315 around. */
13316 if (b->type == bp_fast_tracepoint)
13317 {
13318 /* Only test for support at download time; we may not know
13319 target capabilities at definition time. */
13320 if (remote_supports_fast_tracepoints ())
13321 {
13322 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13323 NULL))
13324 {
13325 size_left = buf.size () - strlen (buf.data ());
13326 ret = snprintf (buf.data () + strlen (buf.data ()),
13327 size_left, ":F%x",
13328 gdb_insn_length (loc->gdbarch, tpaddr));
13329
13330 if (ret < 0 || ret >= size_left)
13331 error ("%s", err_msg);
13332 }
13333 else
13334 /* If it passed validation at definition but fails now,
13335 something is very wrong. */
13336 internal_error (_("Fast tracepoint not valid during download"));
13337 }
13338 else
13339 /* Fast tracepoints are functionally identical to regular
13340 tracepoints, so don't take lack of support as a reason to
13341 give up on the trace run. */
13342 warning (_("Target does not support fast tracepoints, "
13343 "downloading %d as regular tracepoint"), b->number);
13344 }
13345 else if (b->type == bp_static_tracepoint
13346 || b->type == bp_static_marker_tracepoint)
13347 {
13348 /* Only test for support at download time; we may not know
13349 target capabilities at definition time. */
13350 if (remote_supports_static_tracepoints ())
13351 {
13352 struct static_tracepoint_marker marker;
13353
13354 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13355 {
13356 size_left = buf.size () - strlen (buf.data ());
13357 ret = snprintf (buf.data () + strlen (buf.data ()),
13358 size_left, ":S");
13359
13360 if (ret < 0 || ret >= size_left)
13361 error ("%s", err_msg);
13362 }
13363 else
13364 error (_("Static tracepoint not valid during download"));
13365 }
13366 else
13367 /* Fast tracepoints are functionally identical to regular
13368 tracepoints, so don't take lack of support as a reason
13369 to give up on the trace run. */
13370 error (_("Target does not support static tracepoints"));
13371 }
13372 /* If the tracepoint has a conditional, make it into an agent
13373 expression and append to the definition. */
13374 if (loc->cond)
13375 {
13376 /* Only test support at download time, we may not know target
13377 capabilities at definition time. */
13378 if (remote_supports_cond_tracepoints ())
13379 {
13380 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13381 loc->cond.get ());
13382
13383 size_left = buf.size () - strlen (buf.data ());
13384
13385 ret = snprintf (buf.data () + strlen (buf.data ()),
13386 size_left, ":X%x,", (int) aexpr->buf.size ());
13387
13388 if (ret < 0 || ret >= size_left)
13389 error ("%s", err_msg);
13390
13391 size_left = buf.size () - strlen (buf.data ());
13392
13393 /* Two bytes to encode each aexpr byte, plus the terminating
13394 null byte. */
13395 if (aexpr->buf.size () * 2 + 1 > size_left)
13396 error ("%s", err_msg);
13397
13398 pkt = buf.data () + strlen (buf.data ());
13399
13400 for (int ndx = 0; ndx < aexpr->buf.size (); ++ndx)
13401 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13402 *pkt = '\0';
13403 }
13404 else
13405 warning (_("Target does not support conditional tracepoints, "
13406 "ignoring tp %d cond"), b->number);
13407 }
13408
13409 if (b->commands || !default_collect.empty ())
13410 {
13411 size_left = buf.size () - strlen (buf.data ());
13412
13413 ret = snprintf (buf.data () + strlen (buf.data ()),
13414 size_left, "-");
13415
13416 if (ret < 0 || ret >= size_left)
13417 error ("%s", err_msg);
13418 }
13419
13420 putpkt (buf.data ());
13421 remote_get_noisy_reply ();
13422 if (strcmp (rs->buf.data (), "OK"))
13423 error (_("Target does not support tracepoints."));
13424
13425 /* do_single_steps (t); */
13426 for (auto action_it = tdp_actions.begin ();
13427 action_it != tdp_actions.end (); action_it++)
13428 {
13429 QUIT; /* Allow user to bail out with ^C. */
13430
13431 bool has_more = ((action_it + 1) != tdp_actions.end ()
13432 || !stepping_actions.empty ());
13433
13434 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13435 b->number, addrbuf, /* address */
13436 action_it->c_str (),
13437 has_more ? '-' : 0);
13438
13439 if (ret < 0 || ret >= buf.size ())
13440 error ("%s", err_msg);
13441
13442 putpkt (buf.data ());
13443 remote_get_noisy_reply ();
13444 if (strcmp (rs->buf.data (), "OK"))
13445 error (_("Error on target while setting tracepoints."));
13446 }
13447
13448 for (auto action_it = stepping_actions.begin ();
13449 action_it != stepping_actions.end (); action_it++)
13450 {
13451 QUIT; /* Allow user to bail out with ^C. */
13452
13453 bool is_first = action_it == stepping_actions.begin ();
13454 bool has_more = (action_it + 1) != stepping_actions.end ();
13455
13456 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13457 b->number, addrbuf, /* address */
13458 is_first ? "S" : "",
13459 action_it->c_str (),
13460 has_more ? "-" : "");
13461
13462 if (ret < 0 || ret >= buf.size ())
13463 error ("%s", err_msg);
13464
13465 putpkt (buf.data ());
13466 remote_get_noisy_reply ();
13467 if (strcmp (rs->buf.data (), "OK"))
13468 error (_("Error on target while setting tracepoints."));
13469 }
13470
13471 if (m_features.packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13472 {
13473 if (b->locspec != nullptr)
13474 {
13475 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13476
13477 if (ret < 0 || ret >= buf.size ())
13478 error ("%s", err_msg);
13479
13480 const char *str = b->locspec->to_string ();
13481 encode_source_string (b->number, loc->address, "at", str,
13482 buf.data () + strlen (buf.data ()),
13483 buf.size () - strlen (buf.data ()));
13484 putpkt (buf.data ());
13485 remote_get_noisy_reply ();
13486 if (strcmp (rs->buf.data (), "OK"))
13487 warning (_("Target does not support source download."));
13488 }
13489 if (b->cond_string)
13490 {
13491 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13492
13493 if (ret < 0 || ret >= buf.size ())
13494 error ("%s", err_msg);
13495
13496 encode_source_string (b->number, loc->address,
13497 "cond", b->cond_string.get (),
13498 buf.data () + strlen (buf.data ()),
13499 buf.size () - strlen (buf.data ()));
13500 putpkt (buf.data ());
13501 remote_get_noisy_reply ();
13502 if (strcmp (rs->buf.data (), "OK"))
13503 warning (_("Target does not support source download."));
13504 }
13505 remote_download_command_source (b->number, loc->address,
13506 breakpoint_commands (b));
13507 }
13508 }
13509
13510 bool
13511 remote_target::can_download_tracepoint ()
13512 {
13513 struct remote_state *rs = get_remote_state ();
13514 struct trace_status *ts;
13515 int status;
13516
13517 /* Don't try to install tracepoints until we've relocated our
13518 symbols, and fetched and merged the target's tracepoint list with
13519 ours. */
13520 if (rs->starting_up)
13521 return false;
13522
13523 ts = current_trace_status ();
13524 status = get_trace_status (ts);
13525
13526 if (status == -1 || !ts->running_known || !ts->running)
13527 return false;
13528
13529 /* If we are in a tracing experiment, but remote stub doesn't support
13530 installing tracepoint in trace, we have to return. */
13531 if (!remote_supports_install_in_trace ())
13532 return false;
13533
13534 return true;
13535 }
13536
13537
13538 void
13539 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13540 {
13541 struct remote_state *rs = get_remote_state ();
13542 char *p;
13543
13544 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13545 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13546 tsv.builtin);
13547 p = rs->buf.data () + strlen (rs->buf.data ());
13548 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13549 >= get_remote_packet_size ())
13550 error (_("Trace state variable name too long for tsv definition packet"));
13551 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13552 *p++ = '\0';
13553 putpkt (rs->buf);
13554 remote_get_noisy_reply ();
13555 if (rs->buf[0] == '\0')
13556 error (_("Target does not support this command."));
13557 if (strcmp (rs->buf.data (), "OK") != 0)
13558 error (_("Error on target while downloading trace state variable."));
13559 }
13560
13561 void
13562 remote_target::enable_tracepoint (struct bp_location *location)
13563 {
13564 struct remote_state *rs = get_remote_state ();
13565
13566 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13567 location->owner->number,
13568 phex (location->address, sizeof (CORE_ADDR)));
13569 putpkt (rs->buf);
13570 remote_get_noisy_reply ();
13571 if (rs->buf[0] == '\0')
13572 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13573 if (strcmp (rs->buf.data (), "OK") != 0)
13574 error (_("Error on target while enabling tracepoint."));
13575 }
13576
13577 void
13578 remote_target::disable_tracepoint (struct bp_location *location)
13579 {
13580 struct remote_state *rs = get_remote_state ();
13581
13582 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13583 location->owner->number,
13584 phex (location->address, sizeof (CORE_ADDR)));
13585 putpkt (rs->buf);
13586 remote_get_noisy_reply ();
13587 if (rs->buf[0] == '\0')
13588 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13589 if (strcmp (rs->buf.data (), "OK") != 0)
13590 error (_("Error on target while disabling tracepoint."));
13591 }
13592
13593 void
13594 remote_target::trace_set_readonly_regions ()
13595 {
13596 asection *s;
13597 bfd_size_type size;
13598 bfd_vma vma;
13599 int anysecs = 0;
13600 int offset = 0;
13601 bfd *abfd = current_program_space->exec_bfd ();
13602
13603 if (!abfd)
13604 return; /* No information to give. */
13605
13606 struct remote_state *rs = get_remote_state ();
13607
13608 strcpy (rs->buf.data (), "QTro");
13609 offset = strlen (rs->buf.data ());
13610 for (s = abfd->sections; s; s = s->next)
13611 {
13612 char tmp1[40], tmp2[40];
13613 int sec_length;
13614
13615 if ((s->flags & SEC_LOAD) == 0
13616 /* || (s->flags & SEC_CODE) == 0 */
13617 || (s->flags & SEC_READONLY) == 0)
13618 continue;
13619
13620 anysecs = 1;
13621 vma = bfd_section_vma (s);
13622 size = bfd_section_size (s);
13623 bfd_sprintf_vma (abfd, tmp1, vma);
13624 bfd_sprintf_vma (abfd, tmp2, vma + size);
13625 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13626 if (offset + sec_length + 1 > rs->buf.size ())
13627 {
13628 if (m_features.packet_support (PACKET_qXfer_traceframe_info)
13629 != PACKET_ENABLE)
13630 warning (_("\
13631 Too many sections for read-only sections definition packet."));
13632 break;
13633 }
13634 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13635 tmp1, tmp2);
13636 offset += sec_length;
13637 }
13638 if (anysecs)
13639 {
13640 putpkt (rs->buf);
13641 getpkt (&rs->buf, 0);
13642 }
13643 }
13644
13645 void
13646 remote_target::trace_start ()
13647 {
13648 struct remote_state *rs = get_remote_state ();
13649
13650 putpkt ("QTStart");
13651 remote_get_noisy_reply ();
13652 if (rs->buf[0] == '\0')
13653 error (_("Target does not support this command."));
13654 if (strcmp (rs->buf.data (), "OK") != 0)
13655 error (_("Bogus reply from target: %s"), rs->buf.data ());
13656 }
13657
13658 int
13659 remote_target::get_trace_status (struct trace_status *ts)
13660 {
13661 /* Initialize it just to avoid a GCC false warning. */
13662 char *p = NULL;
13663 enum packet_result result;
13664 struct remote_state *rs = get_remote_state ();
13665
13666 if (m_features.packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13667 return -1;
13668
13669 /* FIXME we need to get register block size some other way. */
13670 trace_regblock_size
13671 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13672
13673 putpkt ("qTStatus");
13674
13675 try
13676 {
13677 p = remote_get_noisy_reply ();
13678 }
13679 catch (const gdb_exception_error &ex)
13680 {
13681 if (ex.error != TARGET_CLOSE_ERROR)
13682 {
13683 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13684 return -1;
13685 }
13686 throw;
13687 }
13688
13689 result = m_features.packet_ok (p, PACKET_qTStatus);
13690
13691 /* If the remote target doesn't do tracing, flag it. */
13692 if (result == PACKET_UNKNOWN)
13693 return -1;
13694
13695 /* We're working with a live target. */
13696 ts->filename = NULL;
13697
13698 if (*p++ != 'T')
13699 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13700
13701 /* Function 'parse_trace_status' sets default value of each field of
13702 'ts' at first, so we don't have to do it here. */
13703 parse_trace_status (p, ts);
13704
13705 return ts->running;
13706 }
13707
13708 void
13709 remote_target::get_tracepoint_status (struct breakpoint *bp,
13710 struct uploaded_tp *utp)
13711 {
13712 struct remote_state *rs = get_remote_state ();
13713 char *reply;
13714 struct tracepoint *tp = (struct tracepoint *) bp;
13715 size_t size = get_remote_packet_size ();
13716
13717 if (tp)
13718 {
13719 tp->hit_count = 0;
13720 tp->traceframe_usage = 0;
13721 for (bp_location &loc : tp->locations ())
13722 {
13723 /* If the tracepoint was never downloaded, don't go asking for
13724 any status. */
13725 if (tp->number_on_target == 0)
13726 continue;
13727 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13728 phex_nz (loc.address, 0));
13729 putpkt (rs->buf);
13730 reply = remote_get_noisy_reply ();
13731 if (reply && *reply)
13732 {
13733 if (*reply == 'V')
13734 parse_tracepoint_status (reply + 1, bp, utp);
13735 }
13736 }
13737 }
13738 else if (utp)
13739 {
13740 utp->hit_count = 0;
13741 utp->traceframe_usage = 0;
13742 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13743 phex_nz (utp->addr, 0));
13744 putpkt (rs->buf);
13745 reply = remote_get_noisy_reply ();
13746 if (reply && *reply)
13747 {
13748 if (*reply == 'V')
13749 parse_tracepoint_status (reply + 1, bp, utp);
13750 }
13751 }
13752 }
13753
13754 void
13755 remote_target::trace_stop ()
13756 {
13757 struct remote_state *rs = get_remote_state ();
13758
13759 putpkt ("QTStop");
13760 remote_get_noisy_reply ();
13761 if (rs->buf[0] == '\0')
13762 error (_("Target does not support this command."));
13763 if (strcmp (rs->buf.data (), "OK") != 0)
13764 error (_("Bogus reply from target: %s"), rs->buf.data ());
13765 }
13766
13767 int
13768 remote_target::trace_find (enum trace_find_type type, int num,
13769 CORE_ADDR addr1, CORE_ADDR addr2,
13770 int *tpp)
13771 {
13772 struct remote_state *rs = get_remote_state ();
13773 char *endbuf = rs->buf.data () + get_remote_packet_size ();
13774 char *p, *reply;
13775 int target_frameno = -1, target_tracept = -1;
13776
13777 /* Lookups other than by absolute frame number depend on the current
13778 trace selected, so make sure it is correct on the remote end
13779 first. */
13780 if (type != tfind_number)
13781 set_remote_traceframe ();
13782
13783 p = rs->buf.data ();
13784 strcpy (p, "QTFrame:");
13785 p = strchr (p, '\0');
13786 switch (type)
13787 {
13788 case tfind_number:
13789 xsnprintf (p, endbuf - p, "%x", num);
13790 break;
13791 case tfind_pc:
13792 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13793 break;
13794 case tfind_tp:
13795 xsnprintf (p, endbuf - p, "tdp:%x", num);
13796 break;
13797 case tfind_range:
13798 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13799 phex_nz (addr2, 0));
13800 break;
13801 case tfind_outside:
13802 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13803 phex_nz (addr2, 0));
13804 break;
13805 default:
13806 error (_("Unknown trace find type %d"), type);
13807 }
13808
13809 putpkt (rs->buf);
13810 reply = remote_get_noisy_reply ();
13811 if (*reply == '\0')
13812 error (_("Target does not support this command."));
13813
13814 while (reply && *reply)
13815 switch (*reply)
13816 {
13817 case 'F':
13818 p = ++reply;
13819 target_frameno = (int) strtol (p, &reply, 16);
13820 if (reply == p)
13821 error (_("Unable to parse trace frame number"));
13822 /* Don't update our remote traceframe number cache on failure
13823 to select a remote traceframe. */
13824 if (target_frameno == -1)
13825 return -1;
13826 break;
13827 case 'T':
13828 p = ++reply;
13829 target_tracept = (int) strtol (p, &reply, 16);
13830 if (reply == p)
13831 error (_("Unable to parse tracepoint number"));
13832 break;
13833 case 'O': /* "OK"? */
13834 if (reply[1] == 'K' && reply[2] == '\0')
13835 reply += 2;
13836 else
13837 error (_("Bogus reply from target: %s"), reply);
13838 break;
13839 default:
13840 error (_("Bogus reply from target: %s"), reply);
13841 }
13842 if (tpp)
13843 *tpp = target_tracept;
13844
13845 rs->remote_traceframe_number = target_frameno;
13846 return target_frameno;
13847 }
13848
13849 bool
13850 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13851 {
13852 struct remote_state *rs = get_remote_state ();
13853 char *reply;
13854 ULONGEST uval;
13855
13856 set_remote_traceframe ();
13857
13858 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
13859 putpkt (rs->buf);
13860 reply = remote_get_noisy_reply ();
13861 if (reply && *reply)
13862 {
13863 if (*reply == 'V')
13864 {
13865 unpack_varlen_hex (reply + 1, &uval);
13866 *val = (LONGEST) uval;
13867 return true;
13868 }
13869 }
13870 return false;
13871 }
13872
13873 int
13874 remote_target::save_trace_data (const char *filename)
13875 {
13876 struct remote_state *rs = get_remote_state ();
13877 char *p, *reply;
13878
13879 p = rs->buf.data ();
13880 strcpy (p, "QTSave:");
13881 p += strlen (p);
13882 if ((p - rs->buf.data ()) + strlen (filename) * 2
13883 >= get_remote_packet_size ())
13884 error (_("Remote file name too long for trace save packet"));
13885 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13886 *p++ = '\0';
13887 putpkt (rs->buf);
13888 reply = remote_get_noisy_reply ();
13889 if (*reply == '\0')
13890 error (_("Target does not support this command."));
13891 if (strcmp (reply, "OK") != 0)
13892 error (_("Bogus reply from target: %s"), reply);
13893 return 0;
13894 }
13895
13896 /* This is basically a memory transfer, but needs to be its own packet
13897 because we don't know how the target actually organizes its trace
13898 memory, plus we want to be able to ask for as much as possible, but
13899 not be unhappy if we don't get as much as we ask for. */
13900
13901 LONGEST
13902 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13903 {
13904 struct remote_state *rs = get_remote_state ();
13905 char *reply;
13906 char *p;
13907 int rslt;
13908
13909 p = rs->buf.data ();
13910 strcpy (p, "qTBuffer:");
13911 p += strlen (p);
13912 p += hexnumstr (p, offset);
13913 *p++ = ',';
13914 p += hexnumstr (p, len);
13915 *p++ = '\0';
13916
13917 putpkt (rs->buf);
13918 reply = remote_get_noisy_reply ();
13919 if (reply && *reply)
13920 {
13921 /* 'l' by itself means we're at the end of the buffer and
13922 there is nothing more to get. */
13923 if (*reply == 'l')
13924 return 0;
13925
13926 /* Convert the reply into binary. Limit the number of bytes to
13927 convert according to our passed-in buffer size, rather than
13928 what was returned in the packet; if the target is
13929 unexpectedly generous and gives us a bigger reply than we
13930 asked for, we don't want to crash. */
13931 rslt = hex2bin (reply, buf, len);
13932 return rslt;
13933 }
13934
13935 /* Something went wrong, flag as an error. */
13936 return -1;
13937 }
13938
13939 void
13940 remote_target::set_disconnected_tracing (int val)
13941 {
13942 struct remote_state *rs = get_remote_state ();
13943
13944 if (m_features.packet_support (PACKET_DisconnectedTracing_feature)
13945 == PACKET_ENABLE)
13946 {
13947 char *reply;
13948
13949 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13950 "QTDisconnected:%x", val);
13951 putpkt (rs->buf);
13952 reply = remote_get_noisy_reply ();
13953 if (*reply == '\0')
13954 error (_("Target does not support this command."));
13955 if (strcmp (reply, "OK") != 0)
13956 error (_("Bogus reply from target: %s"), reply);
13957 }
13958 else if (val)
13959 warning (_("Target does not support disconnected tracing."));
13960 }
13961
13962 int
13963 remote_target::core_of_thread (ptid_t ptid)
13964 {
13965 thread_info *info = this->find_thread (ptid);
13966
13967 if (info != NULL && info->priv != NULL)
13968 return get_remote_thread_info (info)->core;
13969
13970 return -1;
13971 }
13972
13973 void
13974 remote_target::set_circular_trace_buffer (int val)
13975 {
13976 struct remote_state *rs = get_remote_state ();
13977 char *reply;
13978
13979 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13980 "QTBuffer:circular:%x", val);
13981 putpkt (rs->buf);
13982 reply = remote_get_noisy_reply ();
13983 if (*reply == '\0')
13984 error (_("Target does not support this command."));
13985 if (strcmp (reply, "OK") != 0)
13986 error (_("Bogus reply from target: %s"), reply);
13987 }
13988
13989 traceframe_info_up
13990 remote_target::traceframe_info ()
13991 {
13992 gdb::optional<gdb::char_vector> text
13993 = target_read_stralloc (current_inferior ()->top_target (),
13994 TARGET_OBJECT_TRACEFRAME_INFO,
13995 NULL);
13996 if (text)
13997 return parse_traceframe_info (text->data ());
13998
13999 return NULL;
14000 }
14001
14002 /* Handle the qTMinFTPILen packet. Returns the minimum length of
14003 instruction on which a fast tracepoint may be placed. Returns -1
14004 if the packet is not supported, and 0 if the minimum instruction
14005 length is unknown. */
14006
14007 int
14008 remote_target::get_min_fast_tracepoint_insn_len ()
14009 {
14010 struct remote_state *rs = get_remote_state ();
14011 char *reply;
14012
14013 /* If we're not debugging a process yet, the IPA can't be
14014 loaded. */
14015 if (!target_has_execution ())
14016 return 0;
14017
14018 /* Make sure the remote is pointing at the right process. */
14019 set_general_process ();
14020
14021 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
14022 putpkt (rs->buf);
14023 reply = remote_get_noisy_reply ();
14024 if (*reply == '\0')
14025 return -1;
14026 else
14027 {
14028 ULONGEST min_insn_len;
14029
14030 unpack_varlen_hex (reply, &min_insn_len);
14031
14032 return (int) min_insn_len;
14033 }
14034 }
14035
14036 void
14037 remote_target::set_trace_buffer_size (LONGEST val)
14038 {
14039 if (m_features.packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
14040 {
14041 struct remote_state *rs = get_remote_state ();
14042 char *buf = rs->buf.data ();
14043 char *endbuf = buf + get_remote_packet_size ();
14044 enum packet_result result;
14045
14046 gdb_assert (val >= 0 || val == -1);
14047 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
14048 /* Send -1 as literal "-1" to avoid host size dependency. */
14049 if (val < 0)
14050 {
14051 *buf++ = '-';
14052 buf += hexnumstr (buf, (ULONGEST) -val);
14053 }
14054 else
14055 buf += hexnumstr (buf, (ULONGEST) val);
14056
14057 putpkt (rs->buf);
14058 remote_get_noisy_reply ();
14059 result = m_features.packet_ok (rs->buf, PACKET_QTBuffer_size);
14060
14061 if (result != PACKET_OK)
14062 warning (_("Bogus reply from target: %s"), rs->buf.data ());
14063 }
14064 }
14065
14066 bool
14067 remote_target::set_trace_notes (const char *user, const char *notes,
14068 const char *stop_notes)
14069 {
14070 struct remote_state *rs = get_remote_state ();
14071 char *reply;
14072 char *buf = rs->buf.data ();
14073 char *endbuf = buf + get_remote_packet_size ();
14074 int nbytes;
14075
14076 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
14077 if (user)
14078 {
14079 buf += xsnprintf (buf, endbuf - buf, "user:");
14080 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
14081 buf += 2 * nbytes;
14082 *buf++ = ';';
14083 }
14084 if (notes)
14085 {
14086 buf += xsnprintf (buf, endbuf - buf, "notes:");
14087 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
14088 buf += 2 * nbytes;
14089 *buf++ = ';';
14090 }
14091 if (stop_notes)
14092 {
14093 buf += xsnprintf (buf, endbuf - buf, "tstop:");
14094 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
14095 buf += 2 * nbytes;
14096 *buf++ = ';';
14097 }
14098 /* Ensure the buffer is terminated. */
14099 *buf = '\0';
14100
14101 putpkt (rs->buf);
14102 reply = remote_get_noisy_reply ();
14103 if (*reply == '\0')
14104 return false;
14105
14106 if (strcmp (reply, "OK") != 0)
14107 error (_("Bogus reply from target: %s"), reply);
14108
14109 return true;
14110 }
14111
14112 bool
14113 remote_target::use_agent (bool use)
14114 {
14115 if (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE)
14116 {
14117 struct remote_state *rs = get_remote_state ();
14118
14119 /* If the stub supports QAgent. */
14120 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
14121 putpkt (rs->buf);
14122 getpkt (&rs->buf, 0);
14123
14124 if (strcmp (rs->buf.data (), "OK") == 0)
14125 {
14126 ::use_agent = use;
14127 return true;
14128 }
14129 }
14130
14131 return false;
14132 }
14133
14134 bool
14135 remote_target::can_use_agent ()
14136 {
14137 return (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE);
14138 }
14139
14140 struct btrace_target_info
14141 {
14142 /* The ptid of the traced thread. */
14143 ptid_t ptid;
14144
14145 /* The obtained branch trace configuration. */
14146 struct btrace_config conf;
14147 };
14148
14149 /* Reset our idea of our target's btrace configuration. */
14150
14151 static void
14152 remote_btrace_reset (remote_state *rs)
14153 {
14154 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14155 }
14156
14157 /* Synchronize the configuration with the target. */
14158
14159 void
14160 remote_target::btrace_sync_conf (const btrace_config *conf)
14161 {
14162 struct remote_state *rs;
14163 char *buf, *pos, *endbuf;
14164
14165 rs = get_remote_state ();
14166 buf = rs->buf.data ();
14167 endbuf = buf + get_remote_packet_size ();
14168
14169 if (m_features.packet_support (PACKET_Qbtrace_conf_bts_size) == PACKET_ENABLE
14170 && conf->bts.size != rs->btrace_config.bts.size)
14171 {
14172 pos = buf;
14173 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14174 packets_descriptions[PACKET_Qbtrace_conf_bts_size].name,
14175 conf->bts.size);
14176
14177 putpkt (buf);
14178 getpkt (&rs->buf, 0);
14179
14180 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_bts_size)
14181 == PACKET_ERROR)
14182 {
14183 if (buf[0] == 'E' && buf[1] == '.')
14184 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14185 else
14186 error (_("Failed to configure the BTS buffer size."));
14187 }
14188
14189 rs->btrace_config.bts.size = conf->bts.size;
14190 }
14191
14192 if (m_features.packet_support (PACKET_Qbtrace_conf_pt_size) == PACKET_ENABLE
14193 && conf->pt.size != rs->btrace_config.pt.size)
14194 {
14195 pos = buf;
14196 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14197 packets_descriptions[PACKET_Qbtrace_conf_pt_size].name,
14198 conf->pt.size);
14199
14200 putpkt (buf);
14201 getpkt (&rs->buf, 0);
14202
14203 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_size)
14204 == PACKET_ERROR)
14205 {
14206 if (buf[0] == 'E' && buf[1] == '.')
14207 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14208 else
14209 error (_("Failed to configure the trace buffer size."));
14210 }
14211
14212 rs->btrace_config.pt.size = conf->pt.size;
14213 }
14214 }
14215
14216 /* Read TP's btrace configuration from the target and store it into CONF. */
14217
14218 static void
14219 btrace_read_config (thread_info *tp, struct btrace_config *conf)
14220 {
14221 /* target_read_stralloc relies on INFERIOR_PTID. */
14222 scoped_restore_current_thread restore_thread;
14223 switch_to_thread (tp);
14224
14225 gdb::optional<gdb::char_vector> xml
14226 = target_read_stralloc (current_inferior ()->top_target (),
14227 TARGET_OBJECT_BTRACE_CONF, "");
14228 if (xml)
14229 parse_xml_btrace_conf (conf, xml->data ());
14230 }
14231
14232 /* Maybe reopen target btrace. */
14233
14234 void
14235 remote_target::remote_btrace_maybe_reopen ()
14236 {
14237 struct remote_state *rs = get_remote_state ();
14238 int btrace_target_pushed = 0;
14239 #if !defined (HAVE_LIBIPT)
14240 int warned = 0;
14241 #endif
14242
14243 /* Don't bother walking the entirety of the remote thread list when
14244 we know the feature isn't supported by the remote. */
14245 if (m_features.packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14246 return;
14247
14248 for (thread_info *tp : all_non_exited_threads (this))
14249 {
14250 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14251 btrace_read_config (tp, &rs->btrace_config);
14252
14253 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14254 continue;
14255
14256 #if !defined (HAVE_LIBIPT)
14257 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14258 {
14259 if (!warned)
14260 {
14261 warned = 1;
14262 warning (_("Target is recording using Intel Processor Trace "
14263 "but support was disabled at compile time."));
14264 }
14265
14266 continue;
14267 }
14268 #endif /* !defined (HAVE_LIBIPT) */
14269
14270 /* Push target, once, but before anything else happens. This way our
14271 changes to the threads will be cleaned up by unpushing the target
14272 in case btrace_read_config () throws. */
14273 if (!btrace_target_pushed)
14274 {
14275 btrace_target_pushed = 1;
14276 record_btrace_push_target ();
14277 gdb_printf (_("Target is recording using %s.\n"),
14278 btrace_format_string (rs->btrace_config.format));
14279 }
14280
14281 tp->btrace.target = XCNEW (struct btrace_target_info);
14282 tp->btrace.target->ptid = tp->ptid;
14283 tp->btrace.target->conf = rs->btrace_config;
14284 }
14285 }
14286
14287 /* Enable branch tracing. */
14288
14289 struct btrace_target_info *
14290 remote_target::enable_btrace (thread_info *tp,
14291 const struct btrace_config *conf)
14292 {
14293 struct btrace_target_info *tinfo = NULL;
14294 struct packet_config *packet = NULL;
14295 struct remote_state *rs = get_remote_state ();
14296 char *buf = rs->buf.data ();
14297 char *endbuf = buf + get_remote_packet_size ();
14298
14299 unsigned int which_packet;
14300 switch (conf->format)
14301 {
14302 case BTRACE_FORMAT_BTS:
14303 which_packet = PACKET_Qbtrace_bts;
14304 break;
14305 case BTRACE_FORMAT_PT:
14306 which_packet = PACKET_Qbtrace_pt;
14307 break;
14308 default:
14309 internal_error (_("Bad branch btrace format: %u."),
14310 (unsigned int) conf->format);
14311 }
14312
14313 packet = &m_features.m_protocol_packets[which_packet];
14314 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14315 error (_("Target does not support branch tracing."));
14316
14317 btrace_sync_conf (conf);
14318
14319 ptid_t ptid = tp->ptid;
14320 set_general_thread (ptid);
14321
14322 buf += xsnprintf (buf, endbuf - buf, "%s",
14323 packets_descriptions[which_packet].name);
14324 putpkt (rs->buf);
14325 getpkt (&rs->buf, 0);
14326
14327 if (m_features.packet_ok (rs->buf, which_packet) == PACKET_ERROR)
14328 {
14329 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14330 error (_("Could not enable branch tracing for %s: %s"),
14331 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14332 else
14333 error (_("Could not enable branch tracing for %s."),
14334 target_pid_to_str (ptid).c_str ());
14335 }
14336
14337 tinfo = XCNEW (struct btrace_target_info);
14338 tinfo->ptid = ptid;
14339
14340 /* If we fail to read the configuration, we lose some information, but the
14341 tracing itself is not impacted. */
14342 try
14343 {
14344 btrace_read_config (tp, &tinfo->conf);
14345 }
14346 catch (const gdb_exception_error &err)
14347 {
14348 if (err.message != NULL)
14349 warning ("%s", err.what ());
14350 }
14351
14352 return tinfo;
14353 }
14354
14355 /* Disable branch tracing. */
14356
14357 void
14358 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14359 {
14360 struct remote_state *rs = get_remote_state ();
14361 char *buf = rs->buf.data ();
14362 char *endbuf = buf + get_remote_packet_size ();
14363
14364 if (m_features.packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
14365 error (_("Target does not support branch tracing."));
14366
14367 set_general_thread (tinfo->ptid);
14368
14369 buf += xsnprintf (buf, endbuf - buf, "%s",
14370 packets_descriptions[PACKET_Qbtrace_off].name);
14371 putpkt (rs->buf);
14372 getpkt (&rs->buf, 0);
14373
14374 if (m_features.packet_ok (rs->buf, PACKET_Qbtrace_off) == PACKET_ERROR)
14375 {
14376 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14377 error (_("Could not disable branch tracing for %s: %s"),
14378 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14379 else
14380 error (_("Could not disable branch tracing for %s."),
14381 target_pid_to_str (tinfo->ptid).c_str ());
14382 }
14383
14384 xfree (tinfo);
14385 }
14386
14387 /* Teardown branch tracing. */
14388
14389 void
14390 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14391 {
14392 /* We must not talk to the target during teardown. */
14393 xfree (tinfo);
14394 }
14395
14396 /* Read the branch trace. */
14397
14398 enum btrace_error
14399 remote_target::read_btrace (struct btrace_data *btrace,
14400 struct btrace_target_info *tinfo,
14401 enum btrace_read_type type)
14402 {
14403 const char *annex;
14404
14405 if (m_features.packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
14406 error (_("Target does not support branch tracing."));
14407
14408 #if !defined(HAVE_LIBEXPAT)
14409 error (_("Cannot process branch tracing result. XML parsing not supported."));
14410 #endif
14411
14412 switch (type)
14413 {
14414 case BTRACE_READ_ALL:
14415 annex = "all";
14416 break;
14417 case BTRACE_READ_NEW:
14418 annex = "new";
14419 break;
14420 case BTRACE_READ_DELTA:
14421 annex = "delta";
14422 break;
14423 default:
14424 internal_error (_("Bad branch tracing read type: %u."),
14425 (unsigned int) type);
14426 }
14427
14428 gdb::optional<gdb::char_vector> xml
14429 = target_read_stralloc (current_inferior ()->top_target (),
14430 TARGET_OBJECT_BTRACE, annex);
14431 if (!xml)
14432 return BTRACE_ERR_UNKNOWN;
14433
14434 parse_xml_btrace (btrace, xml->data ());
14435
14436 return BTRACE_ERR_NONE;
14437 }
14438
14439 const struct btrace_config *
14440 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14441 {
14442 return &tinfo->conf;
14443 }
14444
14445 bool
14446 remote_target::augmented_libraries_svr4_read ()
14447 {
14448 return
14449 (m_features.packet_support (PACKET_augmented_libraries_svr4_read_feature)
14450 == PACKET_ENABLE);
14451 }
14452
14453 /* Implementation of to_load. */
14454
14455 void
14456 remote_target::load (const char *name, int from_tty)
14457 {
14458 generic_load (name, from_tty);
14459 }
14460
14461 /* Accepts an integer PID; returns a string representing a file that
14462 can be opened on the remote side to get the symbols for the child
14463 process. Returns NULL if the operation is not supported. */
14464
14465 const char *
14466 remote_target::pid_to_exec_file (int pid)
14467 {
14468 static gdb::optional<gdb::char_vector> filename;
14469 char *annex = NULL;
14470
14471 if (m_features.packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14472 return NULL;
14473
14474 inferior *inf = find_inferior_pid (this, pid);
14475 if (inf == NULL)
14476 internal_error (_("not currently attached to process %d"), pid);
14477
14478 if (!inf->fake_pid_p)
14479 {
14480 const int annex_size = 9;
14481
14482 annex = (char *) alloca (annex_size);
14483 xsnprintf (annex, annex_size, "%x", pid);
14484 }
14485
14486 filename = target_read_stralloc (current_inferior ()->top_target (),
14487 TARGET_OBJECT_EXEC_FILE, annex);
14488
14489 return filename ? filename->data () : nullptr;
14490 }
14491
14492 /* Implement the to_can_do_single_step target_ops method. */
14493
14494 int
14495 remote_target::can_do_single_step ()
14496 {
14497 /* We can only tell whether target supports single step or not by
14498 supported s and S vCont actions if the stub supports vContSupported
14499 feature. If the stub doesn't support vContSupported feature,
14500 we have conservatively to think target doesn't supports single
14501 step. */
14502 if (m_features.packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14503 {
14504 struct remote_state *rs = get_remote_state ();
14505
14506 return rs->supports_vCont.s && rs->supports_vCont.S;
14507 }
14508 else
14509 return 0;
14510 }
14511
14512 /* Implementation of the to_execution_direction method for the remote
14513 target. */
14514
14515 enum exec_direction_kind
14516 remote_target::execution_direction ()
14517 {
14518 struct remote_state *rs = get_remote_state ();
14519
14520 return rs->last_resume_exec_dir;
14521 }
14522
14523 /* Return pointer to the thread_info struct which corresponds to
14524 THREAD_HANDLE (having length HANDLE_LEN). */
14525
14526 thread_info *
14527 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14528 int handle_len,
14529 inferior *inf)
14530 {
14531 for (thread_info *tp : all_non_exited_threads (this))
14532 {
14533 remote_thread_info *priv = get_remote_thread_info (tp);
14534
14535 if (tp->inf == inf && priv != NULL)
14536 {
14537 if (handle_len != priv->thread_handle.size ())
14538 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14539 handle_len, priv->thread_handle.size ());
14540 if (memcmp (thread_handle, priv->thread_handle.data (),
14541 handle_len) == 0)
14542 return tp;
14543 }
14544 }
14545
14546 return NULL;
14547 }
14548
14549 gdb::byte_vector
14550 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14551 {
14552 remote_thread_info *priv = get_remote_thread_info (tp);
14553 return priv->thread_handle;
14554 }
14555
14556 bool
14557 remote_target::can_async_p ()
14558 {
14559 /* This flag should be checked in the common target.c code. */
14560 gdb_assert (target_async_permitted);
14561
14562 /* We're async whenever the serial device can. */
14563 struct remote_state *rs = get_remote_state ();
14564 return serial_can_async_p (rs->remote_desc);
14565 }
14566
14567 bool
14568 remote_target::is_async_p ()
14569 {
14570 /* We're async whenever the serial device is. */
14571 struct remote_state *rs = get_remote_state ();
14572 return serial_is_async_p (rs->remote_desc);
14573 }
14574
14575 /* Pass the SERIAL event on and up to the client. One day this code
14576 will be able to delay notifying the client of an event until the
14577 point where an entire packet has been received. */
14578
14579 static serial_event_ftype remote_async_serial_handler;
14580
14581 static void
14582 remote_async_serial_handler (struct serial *scb, void *context)
14583 {
14584 /* Don't propogate error information up to the client. Instead let
14585 the client find out about the error by querying the target. */
14586 inferior_event_handler (INF_REG_EVENT);
14587 }
14588
14589 static void
14590 remote_async_inferior_event_handler (gdb_client_data data)
14591 {
14592 inferior_event_handler (INF_REG_EVENT);
14593 }
14594
14595 int
14596 remote_target::async_wait_fd ()
14597 {
14598 struct remote_state *rs = get_remote_state ();
14599 return rs->remote_desc->fd;
14600 }
14601
14602 void
14603 remote_target::async (bool enable)
14604 {
14605 struct remote_state *rs = get_remote_state ();
14606
14607 if (enable)
14608 {
14609 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14610
14611 /* If there are pending events in the stop reply queue tell the
14612 event loop to process them. */
14613 if (!rs->stop_reply_queue.empty ())
14614 mark_async_event_handler (rs->remote_async_inferior_event_token);
14615 /* For simplicity, below we clear the pending events token
14616 without remembering whether it is marked, so here we always
14617 mark it. If there's actually no pending notification to
14618 process, this ends up being a no-op (other than a spurious
14619 event-loop wakeup). */
14620 if (target_is_non_stop_p ())
14621 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14622 }
14623 else
14624 {
14625 serial_async (rs->remote_desc, NULL, NULL);
14626 /* If the core is disabling async, it doesn't want to be
14627 disturbed with target events. Clear all async event sources
14628 too. */
14629 clear_async_event_handler (rs->remote_async_inferior_event_token);
14630 if (target_is_non_stop_p ())
14631 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14632 }
14633 }
14634
14635 /* Implementation of the to_thread_events method. */
14636
14637 void
14638 remote_target::thread_events (int enable)
14639 {
14640 struct remote_state *rs = get_remote_state ();
14641 size_t size = get_remote_packet_size ();
14642
14643 if (m_features.packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14644 return;
14645
14646 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
14647 putpkt (rs->buf);
14648 getpkt (&rs->buf, 0);
14649
14650 switch (m_features.packet_ok (rs->buf, PACKET_QThreadEvents))
14651 {
14652 case PACKET_OK:
14653 if (strcmp (rs->buf.data (), "OK") != 0)
14654 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
14655 break;
14656 case PACKET_ERROR:
14657 warning (_("Remote failure reply: %s"), rs->buf.data ());
14658 break;
14659 case PACKET_UNKNOWN:
14660 break;
14661 }
14662 }
14663
14664 static void
14665 show_remote_cmd (const char *args, int from_tty)
14666 {
14667 /* We can't just use cmd_show_list here, because we want to skip
14668 the redundant "show remote Z-packet" and the legacy aliases. */
14669 struct cmd_list_element *list = remote_show_cmdlist;
14670 struct ui_out *uiout = current_uiout;
14671
14672 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14673 for (; list != NULL; list = list->next)
14674 if (strcmp (list->name, "Z-packet") == 0)
14675 continue;
14676 else if (list->type == not_set_cmd)
14677 /* Alias commands are exactly like the original, except they
14678 don't have the normal type. */
14679 continue;
14680 else
14681 {
14682 ui_out_emit_tuple option_emitter (uiout, "option");
14683
14684 uiout->field_string ("name", list->name);
14685 uiout->text (": ");
14686 if (list->type == show_cmd)
14687 do_show_command (NULL, from_tty, list);
14688 else
14689 cmd_func (list, NULL, from_tty);
14690 }
14691 }
14692
14693
14694 /* Function to be called whenever a new objfile (shlib) is detected. */
14695 static void
14696 remote_new_objfile (struct objfile *objfile)
14697 {
14698 /* The objfile change happened in that program space. */
14699 program_space *pspace = current_program_space;
14700
14701 /* The affected program space is possibly shared by multiple inferiors.
14702 Consider sending a qSymbol packet for each of the inferiors using that
14703 program space. */
14704 for (inferior *inf : all_inferiors ())
14705 {
14706 if (inf->pspace != pspace)
14707 continue;
14708
14709 /* Check whether the inferior's process target is a remote target. */
14710 remote_target *remote = as_remote_target (inf->process_target ());
14711 if (remote == nullptr)
14712 continue;
14713
14714 /* When we are attaching or handling a fork child and the shared library
14715 subsystem reads the list of loaded libraries, we receive new objfile
14716 events in between each found library. The libraries are read in an
14717 undefined order, so if we gave the remote side a chance to look up
14718 symbols between each objfile, we might give it an inconsistent picture
14719 of the inferior. It could appear that a library A appears loaded but
14720 a library B does not, even though library A requires library B. That
14721 would present a state that couldn't normally exist in the inferior.
14722
14723 So, skip these events, we'll give the remote a chance to look up
14724 symbols once all the loaded libraries and their symbols are known to
14725 GDB. */
14726 if (inf->in_initial_library_scan)
14727 continue;
14728
14729 if (!remote->has_execution (inf))
14730 continue;
14731
14732 /* Need to switch to a specific thread, because remote_check_symbols will
14733 set the general thread using INFERIOR_PTID.
14734
14735 It's possible to have inferiors with no thread here, because we are
14736 called very early in the connection process, while the inferior is
14737 being set up, before threads are added. Just skip it, start_remote_1
14738 also calls remote_check_symbols when it's done setting things up. */
14739 thread_info *thread = any_thread_of_inferior (inf);
14740 if (thread != nullptr)
14741 {
14742 scoped_restore_current_thread restore_thread;
14743 switch_to_thread (thread);
14744 remote->remote_check_symbols ();
14745 }
14746 }
14747 }
14748
14749 /* Pull all the tracepoints defined on the target and create local
14750 data structures representing them. We don't want to create real
14751 tracepoints yet, we don't want to mess up the user's existing
14752 collection. */
14753
14754 int
14755 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14756 {
14757 struct remote_state *rs = get_remote_state ();
14758 char *p;
14759
14760 /* Ask for a first packet of tracepoint definition. */
14761 putpkt ("qTfP");
14762 getpkt (&rs->buf, 0);
14763 p = rs->buf.data ();
14764 while (*p && *p != 'l')
14765 {
14766 parse_tracepoint_definition (p, utpp);
14767 /* Ask for another packet of tracepoint definition. */
14768 putpkt ("qTsP");
14769 getpkt (&rs->buf, 0);
14770 p = rs->buf.data ();
14771 }
14772 return 0;
14773 }
14774
14775 int
14776 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14777 {
14778 struct remote_state *rs = get_remote_state ();
14779 char *p;
14780
14781 /* Ask for a first packet of variable definition. */
14782 putpkt ("qTfV");
14783 getpkt (&rs->buf, 0);
14784 p = rs->buf.data ();
14785 while (*p && *p != 'l')
14786 {
14787 parse_tsv_definition (p, utsvp);
14788 /* Ask for another packet of variable definition. */
14789 putpkt ("qTsV");
14790 getpkt (&rs->buf, 0);
14791 p = rs->buf.data ();
14792 }
14793 return 0;
14794 }
14795
14796 /* The "set/show range-stepping" show hook. */
14797
14798 static void
14799 show_range_stepping (struct ui_file *file, int from_tty,
14800 struct cmd_list_element *c,
14801 const char *value)
14802 {
14803 gdb_printf (file,
14804 _("Debugger's willingness to use range stepping "
14805 "is %s.\n"), value);
14806 }
14807
14808 /* Return true if the vCont;r action is supported by the remote
14809 stub. */
14810
14811 bool
14812 remote_target::vcont_r_supported ()
14813 {
14814 return (m_features.packet_support (PACKET_vCont) == PACKET_ENABLE
14815 && get_remote_state ()->supports_vCont.r);
14816 }
14817
14818 /* The "set/show range-stepping" set hook. */
14819
14820 static void
14821 set_range_stepping (const char *ignore_args, int from_tty,
14822 struct cmd_list_element *c)
14823 {
14824 /* When enabling, check whether range stepping is actually supported
14825 by the target, and warn if not. */
14826 if (use_range_stepping)
14827 {
14828 remote_target *remote = get_current_remote_target ();
14829 if (remote == NULL
14830 || !remote->vcont_r_supported ())
14831 warning (_("Range stepping is not supported by the current target"));
14832 }
14833 }
14834
14835 static void
14836 show_remote_debug (struct ui_file *file, int from_tty,
14837 struct cmd_list_element *c, const char *value)
14838 {
14839 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
14840 value);
14841 }
14842
14843 static void
14844 show_remote_timeout (struct ui_file *file, int from_tty,
14845 struct cmd_list_element *c, const char *value)
14846 {
14847 gdb_printf (file,
14848 _("Timeout limit to wait for target to respond is %s.\n"),
14849 value);
14850 }
14851
14852 /* Implement the "supports_memory_tagging" target_ops method. */
14853
14854 bool
14855 remote_target::supports_memory_tagging ()
14856 {
14857 return m_features.remote_memory_tagging_p ();
14858 }
14859
14860 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
14861
14862 static void
14863 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14864 size_t len, int type)
14865 {
14866 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14867
14868 std::string request = string_printf ("qMemTags:%s,%s:%s",
14869 phex_nz (address, addr_size),
14870 phex_nz (len, sizeof (len)),
14871 phex_nz (type, sizeof (type)));
14872
14873 strcpy (packet.data (), request.c_str ());
14874 }
14875
14876 /* Parse the qMemTags packet reply into TAGS.
14877
14878 Return true if successful, false otherwise. */
14879
14880 static bool
14881 parse_fetch_memtags_reply (const gdb::char_vector &reply,
14882 gdb::byte_vector &tags)
14883 {
14884 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
14885 return false;
14886
14887 /* Copy the tag data. */
14888 tags = hex2bin (reply.data () + 1);
14889
14890 return true;
14891 }
14892
14893 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
14894
14895 static void
14896 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14897 size_t len, int type,
14898 const gdb::byte_vector &tags)
14899 {
14900 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14901
14902 /* Put together the main packet, address and length. */
14903 std::string request = string_printf ("QMemTags:%s,%s:%s:",
14904 phex_nz (address, addr_size),
14905 phex_nz (len, sizeof (len)),
14906 phex_nz (type, sizeof (type)));
14907 request += bin2hex (tags.data (), tags.size ());
14908
14909 /* Check if we have exceeded the maximum packet size. */
14910 if (packet.size () < request.length ())
14911 error (_("Contents too big for packet QMemTags."));
14912
14913 strcpy (packet.data (), request.c_str ());
14914 }
14915
14916 /* Implement the "fetch_memtags" target_ops method. */
14917
14918 bool
14919 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
14920 gdb::byte_vector &tags, int type)
14921 {
14922 /* Make sure the qMemTags packet is supported. */
14923 if (!m_features.remote_memory_tagging_p ())
14924 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
14925
14926 struct remote_state *rs = get_remote_state ();
14927
14928 create_fetch_memtags_request (rs->buf, address, len, type);
14929
14930 putpkt (rs->buf);
14931 getpkt (&rs->buf, 0);
14932
14933 return parse_fetch_memtags_reply (rs->buf, tags);
14934 }
14935
14936 /* Implement the "store_memtags" target_ops method. */
14937
14938 bool
14939 remote_target::store_memtags (CORE_ADDR address, size_t len,
14940 const gdb::byte_vector &tags, int type)
14941 {
14942 /* Make sure the QMemTags packet is supported. */
14943 if (!m_features.remote_memory_tagging_p ())
14944 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
14945
14946 struct remote_state *rs = get_remote_state ();
14947
14948 create_store_memtags_request (rs->buf, address, len, type, tags);
14949
14950 putpkt (rs->buf);
14951 getpkt (&rs->buf, 0);
14952
14953 /* Verify if the request was successful. */
14954 return packet_check_result (rs->buf.data ()) == PACKET_OK;
14955 }
14956
14957 /* Return true if remote target T is non-stop. */
14958
14959 bool
14960 remote_target_is_non_stop_p (remote_target *t)
14961 {
14962 scoped_restore_current_thread restore_thread;
14963 switch_to_target_no_thread (t);
14964
14965 return target_is_non_stop_p ();
14966 }
14967
14968 #if GDB_SELF_TEST
14969
14970 namespace selftests {
14971
14972 static void
14973 test_memory_tagging_functions ()
14974 {
14975 remote_target remote;
14976
14977 struct packet_config *config
14978 = &remote.m_features.m_protocol_packets[PACKET_memory_tagging_feature];
14979
14980 scoped_restore restore_memtag_support_
14981 = make_scoped_restore (&config->support);
14982
14983 /* Test memory tagging packet support. */
14984 config->support = PACKET_SUPPORT_UNKNOWN;
14985 SELF_CHECK (remote.supports_memory_tagging () == false);
14986 config->support = PACKET_DISABLE;
14987 SELF_CHECK (remote.supports_memory_tagging () == false);
14988 config->support = PACKET_ENABLE;
14989 SELF_CHECK (remote.supports_memory_tagging () == true);
14990
14991 /* Setup testing. */
14992 gdb::char_vector packet;
14993 gdb::byte_vector tags, bv;
14994 std::string expected, reply;
14995 packet.resize (32000);
14996
14997 /* Test creating a qMemTags request. */
14998
14999 expected = "qMemTags:0,0:0";
15000 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
15001 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15002
15003 expected = "qMemTags:deadbeef,10:1";
15004 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
15005 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15006
15007 /* Test parsing a qMemTags reply. */
15008
15009 /* Error reply, tags vector unmodified. */
15010 reply = "E00";
15011 strcpy (packet.data (), reply.c_str ());
15012 tags.resize (0);
15013 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
15014 SELF_CHECK (tags.size () == 0);
15015
15016 /* Valid reply, tags vector updated. */
15017 tags.resize (0);
15018 bv.resize (0);
15019
15020 for (int i = 0; i < 5; i++)
15021 bv.push_back (i);
15022
15023 reply = "m" + bin2hex (bv.data (), bv.size ());
15024 strcpy (packet.data (), reply.c_str ());
15025
15026 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
15027 SELF_CHECK (tags.size () == 5);
15028
15029 for (int i = 0; i < 5; i++)
15030 SELF_CHECK (tags[i] == i);
15031
15032 /* Test creating a QMemTags request. */
15033
15034 /* Empty tag data. */
15035 tags.resize (0);
15036 expected = "QMemTags:0,0:0:";
15037 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
15038 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15039 expected.length ()) == 0);
15040
15041 /* Non-empty tag data. */
15042 tags.resize (0);
15043 for (int i = 0; i < 5; i++)
15044 tags.push_back (i);
15045 expected = "QMemTags:deadbeef,ff:1:0001020304";
15046 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
15047 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15048 expected.length ()) == 0);
15049 }
15050
15051 } // namespace selftests
15052 #endif /* GDB_SELF_TEST */
15053
15054 void _initialize_remote ();
15055 void
15056 _initialize_remote ()
15057 {
15058 add_target (remote_target_info, remote_target::open);
15059 add_target (extended_remote_target_info, extended_remote_target::open);
15060
15061 /* Hook into new objfile notification. */
15062 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
15063
15064 #if 0
15065 init_remote_threadtests ();
15066 #endif
15067
15068 /* set/show remote ... */
15069
15070 add_basic_prefix_cmd ("remote", class_maintenance, _("\
15071 Remote protocol specific variables.\n\
15072 Configure various remote-protocol specific variables such as\n\
15073 the packets being used."),
15074 &remote_set_cmdlist,
15075 0 /* allow-unknown */, &setlist);
15076 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
15077 Remote protocol specific variables.\n\
15078 Configure various remote-protocol specific variables such as\n\
15079 the packets being used."),
15080 &remote_show_cmdlist,
15081 0 /* allow-unknown */, &showlist);
15082
15083 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
15084 Compare section data on target to the exec file.\n\
15085 Argument is a single section name (default: all loaded sections).\n\
15086 To compare only read-only loaded sections, specify the -r option."),
15087 &cmdlist);
15088
15089 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
15090 Send an arbitrary packet to a remote target.\n\
15091 maintenance packet TEXT\n\
15092 If GDB is talking to an inferior via the GDB serial protocol, then\n\
15093 this command sends the string TEXT to the inferior, and displays the\n\
15094 response packet. GDB supplies the initial `$' character, and the\n\
15095 terminating `#' character and checksum."),
15096 &maintenancelist);
15097
15098 set_show_commands remotebreak_cmds
15099 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
15100 Set whether to send break if interrupted."), _("\
15101 Show whether to send break if interrupted."), _("\
15102 If set, a break, instead of a cntrl-c, is sent to the remote target."),
15103 set_remotebreak, show_remotebreak,
15104 &setlist, &showlist);
15105 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
15106 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
15107
15108 add_setshow_enum_cmd ("interrupt-sequence", class_support,
15109 interrupt_sequence_modes, &interrupt_sequence_mode,
15110 _("\
15111 Set interrupt sequence to remote target."), _("\
15112 Show interrupt sequence to remote target."), _("\
15113 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
15114 NULL, show_interrupt_sequence,
15115 &remote_set_cmdlist,
15116 &remote_show_cmdlist);
15117
15118 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
15119 &interrupt_on_connect, _("\
15120 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15121 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15122 If set, interrupt sequence is sent to remote target."),
15123 NULL, NULL,
15124 &remote_set_cmdlist, &remote_show_cmdlist);
15125
15126 /* Install commands for configuring memory read/write packets. */
15127
15128 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
15129 Set the maximum number of bytes per memory write packet (deprecated)."),
15130 &setlist);
15131 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
15132 Show the maximum number of bytes per memory write packet (deprecated)."),
15133 &showlist);
15134 add_cmd ("memory-write-packet-size", no_class,
15135 set_memory_write_packet_size, _("\
15136 Set the maximum number of bytes per memory-write packet.\n\
15137 Specify the number of bytes in a packet or 0 (zero) for the\n\
15138 default packet size. The actual limit is further reduced\n\
15139 dependent on the target. Specify \"fixed\" to disable the\n\
15140 further restriction and \"limit\" to enable that restriction."),
15141 &remote_set_cmdlist);
15142 add_cmd ("memory-read-packet-size", no_class,
15143 set_memory_read_packet_size, _("\
15144 Set the maximum number of bytes per memory-read packet.\n\
15145 Specify the number of bytes in a packet or 0 (zero) for the\n\
15146 default packet size. The actual limit is further reduced\n\
15147 dependent on the target. Specify \"fixed\" to disable the\n\
15148 further restriction and \"limit\" to enable that restriction."),
15149 &remote_set_cmdlist);
15150 add_cmd ("memory-write-packet-size", no_class,
15151 show_memory_write_packet_size,
15152 _("Show the maximum number of bytes per memory-write packet."),
15153 &remote_show_cmdlist);
15154 add_cmd ("memory-read-packet-size", no_class,
15155 show_memory_read_packet_size,
15156 _("Show the maximum number of bytes per memory-read packet."),
15157 &remote_show_cmdlist);
15158
15159 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
15160 &remote_hw_watchpoint_limit, _("\
15161 Set the maximum number of target hardware watchpoints."), _("\
15162 Show the maximum number of target hardware watchpoints."), _("\
15163 Specify \"unlimited\" for unlimited hardware watchpoints."),
15164 NULL, show_hardware_watchpoint_limit,
15165 &remote_set_cmdlist,
15166 &remote_show_cmdlist);
15167 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15168 no_class,
15169 &remote_hw_watchpoint_length_limit, _("\
15170 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15171 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15172 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15173 NULL, show_hardware_watchpoint_length_limit,
15174 &remote_set_cmdlist, &remote_show_cmdlist);
15175 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
15176 &remote_hw_breakpoint_limit, _("\
15177 Set the maximum number of target hardware breakpoints."), _("\
15178 Show the maximum number of target hardware breakpoints."), _("\
15179 Specify \"unlimited\" for unlimited hardware breakpoints."),
15180 NULL, show_hardware_breakpoint_limit,
15181 &remote_set_cmdlist, &remote_show_cmdlist);
15182
15183 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15184 &remote_address_size, _("\
15185 Set the maximum size of the address (in bits) in a memory packet."), _("\
15186 Show the maximum size of the address (in bits) in a memory packet."), NULL,
15187 NULL,
15188 NULL, /* FIXME: i18n: */
15189 &setlist, &showlist);
15190
15191 init_all_packet_configs ();
15192
15193 add_packet_config_cmd (PACKET_X, "X", "binary-download", 1);
15194
15195 add_packet_config_cmd (PACKET_vCont, "vCont", "verbose-resume", 0);
15196
15197 add_packet_config_cmd (PACKET_QPassSignals, "QPassSignals", "pass-signals",
15198 0);
15199
15200 add_packet_config_cmd (PACKET_QCatchSyscalls, "QCatchSyscalls",
15201 "catch-syscalls", 0);
15202
15203 add_packet_config_cmd (PACKET_QProgramSignals, "QProgramSignals",
15204 "program-signals", 0);
15205
15206 add_packet_config_cmd (PACKET_QSetWorkingDir, "QSetWorkingDir",
15207 "set-working-dir", 0);
15208
15209 add_packet_config_cmd (PACKET_QStartupWithShell, "QStartupWithShell",
15210 "startup-with-shell", 0);
15211
15212 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded,"QEnvironmentHexEncoded",
15213 "environment-hex-encoded", 0);
15214
15215 add_packet_config_cmd (PACKET_QEnvironmentReset, "QEnvironmentReset",
15216 "environment-reset", 0);
15217
15218 add_packet_config_cmd (PACKET_QEnvironmentUnset, "QEnvironmentUnset",
15219 "environment-unset", 0);
15220
15221 add_packet_config_cmd (PACKET_qSymbol, "qSymbol", "symbol-lookup", 0);
15222
15223 add_packet_config_cmd (PACKET_P, "P", "set-register", 1);
15224
15225 add_packet_config_cmd (PACKET_p, "p", "fetch-register", 1);
15226
15227 add_packet_config_cmd (PACKET_Z0, "Z0", "software-breakpoint", 0);
15228
15229 add_packet_config_cmd (PACKET_Z1, "Z1", "hardware-breakpoint", 0);
15230
15231 add_packet_config_cmd (PACKET_Z2, "Z2", "write-watchpoint", 0);
15232
15233 add_packet_config_cmd (PACKET_Z3, "Z3", "read-watchpoint", 0);
15234
15235 add_packet_config_cmd (PACKET_Z4, "Z4", "access-watchpoint", 0);
15236
15237 add_packet_config_cmd (PACKET_qXfer_auxv, "qXfer:auxv:read",
15238 "read-aux-vector", 0);
15239
15240 add_packet_config_cmd (PACKET_qXfer_exec_file, "qXfer:exec-file:read",
15241 "pid-to-exec-file", 0);
15242
15243 add_packet_config_cmd (PACKET_qXfer_features,
15244 "qXfer:features:read", "target-features", 0);
15245
15246 add_packet_config_cmd (PACKET_qXfer_libraries, "qXfer:libraries:read",
15247 "library-info", 0);
15248
15249 add_packet_config_cmd (PACKET_qXfer_libraries_svr4,
15250 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15251
15252 add_packet_config_cmd (PACKET_qXfer_memory_map, "qXfer:memory-map:read",
15253 "memory-map", 0);
15254
15255 add_packet_config_cmd (PACKET_qXfer_osdata, "qXfer:osdata:read", "osdata", 0);
15256
15257 add_packet_config_cmd (PACKET_qXfer_threads, "qXfer:threads:read", "threads",
15258 0);
15259
15260 add_packet_config_cmd (PACKET_qXfer_siginfo_read, "qXfer:siginfo:read",
15261 "read-siginfo-object", 0);
15262
15263 add_packet_config_cmd (PACKET_qXfer_siginfo_write, "qXfer:siginfo:write",
15264 "write-siginfo-object", 0);
15265
15266 add_packet_config_cmd (PACKET_qXfer_traceframe_info,
15267 "qXfer:traceframe-info:read", "traceframe-info", 0);
15268
15269 add_packet_config_cmd (PACKET_qXfer_uib, "qXfer:uib:read",
15270 "unwind-info-block", 0);
15271
15272 add_packet_config_cmd (PACKET_qGetTLSAddr, "qGetTLSAddr",
15273 "get-thread-local-storage-address", 0);
15274
15275 add_packet_config_cmd (PACKET_qGetTIBAddr, "qGetTIBAddr",
15276 "get-thread-information-block-address", 0);
15277
15278 add_packet_config_cmd (PACKET_bc, "bc", "reverse-continue", 0);
15279
15280 add_packet_config_cmd (PACKET_bs, "bs", "reverse-step", 0);
15281
15282 add_packet_config_cmd (PACKET_qSupported, "qSupported", "supported-packets",
15283 0);
15284
15285 add_packet_config_cmd (PACKET_qSearch_memory, "qSearch:memory",
15286 "search-memory", 0);
15287
15288 add_packet_config_cmd (PACKET_qTStatus, "qTStatus", "trace-status", 0);
15289
15290 add_packet_config_cmd (PACKET_vFile_setfs, "vFile:setfs", "hostio-setfs", 0);
15291
15292 add_packet_config_cmd (PACKET_vFile_open, "vFile:open", "hostio-open", 0);
15293
15294 add_packet_config_cmd (PACKET_vFile_pread, "vFile:pread", "hostio-pread", 0);
15295
15296 add_packet_config_cmd (PACKET_vFile_pwrite, "vFile:pwrite", "hostio-pwrite",
15297 0);
15298
15299 add_packet_config_cmd (PACKET_vFile_close, "vFile:close", "hostio-close", 0);
15300
15301 add_packet_config_cmd (PACKET_vFile_unlink, "vFile:unlink", "hostio-unlink",
15302 0);
15303
15304 add_packet_config_cmd (PACKET_vFile_readlink, "vFile:readlink",
15305 "hostio-readlink", 0);
15306
15307 add_packet_config_cmd (PACKET_vFile_fstat, "vFile:fstat", "hostio-fstat", 0);
15308
15309 add_packet_config_cmd (PACKET_vAttach, "vAttach", "attach", 0);
15310
15311 add_packet_config_cmd (PACKET_vRun, "vRun", "run", 0);
15312
15313 add_packet_config_cmd (PACKET_QStartNoAckMode, "QStartNoAckMode", "noack", 0);
15314
15315 add_packet_config_cmd (PACKET_vKill, "vKill", "kill", 0);
15316
15317 add_packet_config_cmd (PACKET_qAttached, "qAttached", "query-attached", 0);
15318
15319 add_packet_config_cmd (PACKET_ConditionalTracepoints,
15320 "ConditionalTracepoints", "conditional-tracepoints",
15321 0);
15322
15323 add_packet_config_cmd (PACKET_ConditionalBreakpoints,
15324 "ConditionalBreakpoints", "conditional-breakpoints",
15325 0);
15326
15327 add_packet_config_cmd (PACKET_BreakpointCommands, "BreakpointCommands",
15328 "breakpoint-commands", 0);
15329
15330 add_packet_config_cmd (PACKET_FastTracepoints, "FastTracepoints",
15331 "fast-tracepoints", 0);
15332
15333 add_packet_config_cmd (PACKET_TracepointSource, "TracepointSource",
15334 "TracepointSource", 0);
15335
15336 add_packet_config_cmd (PACKET_QAllow, "QAllow", "allow", 0);
15337
15338 add_packet_config_cmd (PACKET_StaticTracepoints, "StaticTracepoints",
15339 "static-tracepoints", 0);
15340
15341 add_packet_config_cmd (PACKET_InstallInTrace, "InstallInTrace",
15342 "install-in-trace", 0);
15343
15344 add_packet_config_cmd (PACKET_qXfer_statictrace_read,
15345 "qXfer:statictrace:read", "read-sdata-object", 0);
15346
15347 add_packet_config_cmd (PACKET_qXfer_fdpic, "qXfer:fdpic:read",
15348 "read-fdpic-loadmap", 0);
15349
15350 add_packet_config_cmd (PACKET_QDisableRandomization, "QDisableRandomization",
15351 "disable-randomization", 0);
15352
15353 add_packet_config_cmd (PACKET_QAgent, "QAgent", "agent", 0);
15354
15355 add_packet_config_cmd (PACKET_QTBuffer_size, "QTBuffer:size",
15356 "trace-buffer-size", 0);
15357
15358 add_packet_config_cmd (PACKET_Qbtrace_off, "Qbtrace:off", "disable-btrace",
15359 0);
15360
15361 add_packet_config_cmd (PACKET_Qbtrace_bts, "Qbtrace:bts", "enable-btrace-bts",
15362 0);
15363
15364 add_packet_config_cmd (PACKET_Qbtrace_pt, "Qbtrace:pt", "enable-btrace-pt",
15365 0);
15366
15367 add_packet_config_cmd (PACKET_qXfer_btrace, "qXfer:btrace", "read-btrace", 0);
15368
15369 add_packet_config_cmd (PACKET_qXfer_btrace_conf, "qXfer:btrace-conf",
15370 "read-btrace-conf", 0);
15371
15372 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size, "Qbtrace-conf:bts:size",
15373 "btrace-conf-bts-size", 0);
15374
15375 add_packet_config_cmd (PACKET_multiprocess_feature, "multiprocess-feature",
15376 "multiprocess-feature", 0);
15377
15378 add_packet_config_cmd (PACKET_swbreak_feature, "swbreak-feature",
15379 "swbreak-feature", 0);
15380
15381 add_packet_config_cmd (PACKET_hwbreak_feature, "hwbreak-feature",
15382 "hwbreak-feature", 0);
15383
15384 add_packet_config_cmd (PACKET_fork_event_feature, "fork-event-feature",
15385 "fork-event-feature", 0);
15386
15387 add_packet_config_cmd (PACKET_vfork_event_feature, "vfork-event-feature",
15388 "vfork-event-feature", 0);
15389
15390 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size, "Qbtrace-conf:pt:size",
15391 "btrace-conf-pt-size", 0);
15392
15393 add_packet_config_cmd (PACKET_vContSupported, "vContSupported",
15394 "verbose-resume-supported", 0);
15395
15396 add_packet_config_cmd (PACKET_exec_event_feature, "exec-event-feature",
15397 "exec-event-feature", 0);
15398
15399 add_packet_config_cmd (PACKET_vCtrlC, "vCtrlC", "ctrl-c", 0);
15400
15401 add_packet_config_cmd (PACKET_QThreadEvents, "QThreadEvents", "thread-events",
15402 0);
15403
15404 add_packet_config_cmd (PACKET_no_resumed, "N stop reply",
15405 "no-resumed-stop-reply", 0);
15406
15407 add_packet_config_cmd (PACKET_memory_tagging_feature,
15408 "memory-tagging-feature", "memory-tagging-feature", 0);
15409
15410 /* Assert that we've registered "set remote foo-packet" commands
15411 for all packet configs. */
15412 {
15413 int i;
15414
15415 for (i = 0; i < PACKET_MAX; i++)
15416 {
15417 /* Ideally all configs would have a command associated. Some
15418 still don't though. */
15419 int excepted;
15420
15421 switch (i)
15422 {
15423 case PACKET_QNonStop:
15424 case PACKET_EnableDisableTracepoints_feature:
15425 case PACKET_tracenz_feature:
15426 case PACKET_DisconnectedTracing_feature:
15427 case PACKET_augmented_libraries_svr4_read_feature:
15428 case PACKET_qCRC:
15429 /* Additions to this list need to be well justified:
15430 pre-existing packets are OK; new packets are not. */
15431 excepted = 1;
15432 break;
15433 default:
15434 excepted = 0;
15435 break;
15436 }
15437
15438 /* This catches both forgetting to add a config command, and
15439 forgetting to remove a packet from the exception list. */
15440 gdb_assert (excepted == (packets_descriptions[i].name == NULL));
15441 }
15442 }
15443
15444 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15445 Z sub-packet has its own set and show commands, but users may
15446 have sets to this variable in their .gdbinit files (or in their
15447 documentation). */
15448 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
15449 &remote_Z_packet_detect, _("\
15450 Set use of remote protocol `Z' packets."), _("\
15451 Show use of remote protocol `Z' packets."), _("\
15452 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
15453 packets."),
15454 set_remote_protocol_Z_packet_cmd,
15455 show_remote_protocol_Z_packet_cmd,
15456 /* FIXME: i18n: Use of remote protocol
15457 `Z' packets is %s. */
15458 &remote_set_cmdlist, &remote_show_cmdlist);
15459
15460 add_basic_prefix_cmd ("remote", class_files, _("\
15461 Manipulate files on the remote system.\n\
15462 Transfer files to and from the remote target system."),
15463 &remote_cmdlist,
15464 0 /* allow-unknown */, &cmdlist);
15465
15466 add_cmd ("put", class_files, remote_put_command,
15467 _("Copy a local file to the remote system."),
15468 &remote_cmdlist);
15469
15470 add_cmd ("get", class_files, remote_get_command,
15471 _("Copy a remote file to the local system."),
15472 &remote_cmdlist);
15473
15474 add_cmd ("delete", class_files, remote_delete_command,
15475 _("Delete a remote file."),
15476 &remote_cmdlist);
15477
15478 add_setshow_string_noescape_cmd ("exec-file", class_files,
15479 &remote_exec_file_var, _("\
15480 Set the remote pathname for \"run\"."), _("\
15481 Show the remote pathname for \"run\"."), NULL,
15482 set_remote_exec_file,
15483 show_remote_exec_file,
15484 &remote_set_cmdlist,
15485 &remote_show_cmdlist);
15486
15487 add_setshow_boolean_cmd ("range-stepping", class_run,
15488 &use_range_stepping, _("\
15489 Enable or disable range stepping."), _("\
15490 Show whether target-assisted range stepping is enabled."), _("\
15491 If on, and the target supports it, when stepping a source line, GDB\n\
15492 tells the target to step the corresponding range of addresses itself instead\n\
15493 of issuing multiple single-steps. This speeds up source level\n\
15494 stepping. If off, GDB always issues single-steps, even if range\n\
15495 stepping is supported by the target. The default is on."),
15496 set_range_stepping,
15497 show_range_stepping,
15498 &setlist,
15499 &showlist);
15500
15501 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15502 Set watchdog timer."), _("\
15503 Show watchdog timer."), _("\
15504 When non-zero, this timeout is used instead of waiting forever for a target\n\
15505 to finish a low-level step or continue operation. If the specified amount\n\
15506 of time passes without a response from the target, an error occurs."),
15507 NULL,
15508 show_watchdog,
15509 &setlist, &showlist);
15510
15511 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15512 &remote_packet_max_chars, _("\
15513 Set the maximum number of characters to display for each remote packet."), _("\
15514 Show the maximum number of characters to display for each remote packet."), _("\
15515 Specify \"unlimited\" to display all the characters."),
15516 NULL, show_remote_packet_max_chars,
15517 &setdebuglist, &showdebuglist);
15518
15519 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15520 _("Set debugging of remote protocol."),
15521 _("Show debugging of remote protocol."),
15522 _("\
15523 When enabled, each packet sent or received with the remote target\n\
15524 is displayed."),
15525 NULL,
15526 show_remote_debug,
15527 &setdebuglist, &showdebuglist);
15528
15529 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15530 &remote_timeout, _("\
15531 Set timeout limit to wait for target to respond."), _("\
15532 Show timeout limit to wait for target to respond."), _("\
15533 This value is used to set the time limit for gdb to wait for a response\n\
15534 from the target."),
15535 NULL,
15536 show_remote_timeout,
15537 &setlist, &showlist);
15538
15539 /* Eventually initialize fileio. See fileio.c */
15540 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
15541
15542 #if GDB_SELF_TEST
15543 selftests::register_test ("remote_memory_tagging",
15544 selftests::test_memory_tagging_functions);
15545 #endif
15546 }