gdb: remove BLOCK_NAMESPACE macro
[binutils-gdb.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3 Copyright (C) 1988-2022 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 "gdb-stabs.h"
34 #include "gdbthread.h"
35 #include "remote.h"
36 #include "remote-notif.h"
37 #include "regcache.h"
38 #include "value.h"
39 #include "observable.h"
40 #include "solib.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
44 #include "gdb_bfd.h"
45 #include "gdbsupport/filestuff.h"
46 #include "gdbsupport/rsp-low.h"
47 #include "disasm.h"
48 #include "location.h"
49
50 #include "gdbsupport/gdb_sys_time.h"
51
52 #include "gdbsupport/event-loop.h"
53 #include "event-top.h"
54 #include "inf-loop.h"
55
56 #include <signal.h>
57 #include "serial.h"
58
59 #include "gdbcore.h"
60
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
63 #include <sys/stat.h>
64 #include "xml-support.h"
65
66 #include "memory-map.h"
67
68 #include "tracepoint.h"
69 #include "ax.h"
70 #include "ax-gdb.h"
71 #include "gdbsupport/agent.h"
72 #include "btrace.h"
73 #include "record-btrace.h"
74 #include <algorithm>
75 #include "gdbsupport/scoped_restore.h"
76 #include "gdbsupport/environ.h"
77 #include "gdbsupport/byte-vector.h"
78 #include "gdbsupport/search.h"
79 #include <algorithm>
80 #include <unordered_map>
81 #include "async-event.h"
82 #include "gdbsupport/selftest.h"
83
84 /* The remote target. */
85
86 static const char remote_doc[] = N_("\
87 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
88 Specify the serial device it is connected to\n\
89 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
90
91 /* See remote.h */
92
93 bool remote_debug = false;
94
95 #define OPAQUETHREADBYTES 8
96
97 /* a 64 bit opaque identifier */
98 typedef unsigned char threadref[OPAQUETHREADBYTES];
99
100 struct gdb_ext_thread_info;
101 struct threads_listing_context;
102 typedef int (*rmt_thread_action) (threadref *ref, void *context);
103 struct protocol_feature;
104 struct packet_reg;
105
106 struct stop_reply;
107 typedef std::unique_ptr<stop_reply> stop_reply_up;
108
109 /* Generic configuration support for packets the stub optionally
110 supports. Allows the user to specify the use of the packet as well
111 as allowing GDB to auto-detect support in the remote stub. */
112
113 enum packet_support
114 {
115 PACKET_SUPPORT_UNKNOWN = 0,
116 PACKET_ENABLE,
117 PACKET_DISABLE
118 };
119
120 /* Analyze a packet's return value and update the packet config
121 accordingly. */
122
123 enum packet_result
124 {
125 PACKET_ERROR,
126 PACKET_OK,
127 PACKET_UNKNOWN
128 };
129
130 struct threads_listing_context;
131
132 /* Stub vCont actions support.
133
134 Each field is a boolean flag indicating whether the stub reports
135 support for the corresponding action. */
136
137 struct vCont_action_support
138 {
139 /* vCont;t */
140 bool t = false;
141
142 /* vCont;r */
143 bool r = false;
144
145 /* vCont;s */
146 bool s = false;
147
148 /* vCont;S */
149 bool S = false;
150 };
151
152 /* About this many threadids fit in a packet. */
153
154 #define MAXTHREADLISTRESULTS 32
155
156 /* Data for the vFile:pread readahead cache. */
157
158 struct readahead_cache
159 {
160 /* Invalidate the readahead cache. */
161 void invalidate ();
162
163 /* Invalidate the readahead cache if it is holding data for FD. */
164 void invalidate_fd (int fd);
165
166 /* Serve pread from the readahead cache. Returns number of bytes
167 read, or 0 if the request can't be served from the cache. */
168 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
169
170 /* The file descriptor for the file that is being cached. -1 if the
171 cache is invalid. */
172 int fd = -1;
173
174 /* The offset into the file that the cache buffer corresponds
175 to. */
176 ULONGEST offset = 0;
177
178 /* The buffer holding the cache contents. */
179 gdb_byte *buf = nullptr;
180 /* The buffer's size. We try to read as much as fits into a packet
181 at a time. */
182 size_t bufsize = 0;
183
184 /* Cache hit and miss counters. */
185 ULONGEST hit_count = 0;
186 ULONGEST miss_count = 0;
187 };
188
189 /* Description of the remote protocol for a given architecture. */
190
191 struct packet_reg
192 {
193 long offset; /* Offset into G packet. */
194 long regnum; /* GDB's internal register number. */
195 LONGEST pnum; /* Remote protocol register number. */
196 int in_g_packet; /* Always part of G packet. */
197 /* long size in bytes; == register_size (target_gdbarch (), regnum);
198 at present. */
199 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
200 at present. */
201 };
202
203 struct remote_arch_state
204 {
205 explicit remote_arch_state (struct gdbarch *gdbarch);
206
207 /* Description of the remote protocol registers. */
208 long sizeof_g_packet;
209
210 /* Description of the remote protocol registers indexed by REGNUM
211 (making an array gdbarch_num_regs in size). */
212 std::unique_ptr<packet_reg[]> regs;
213
214 /* This is the size (in chars) of the first response to the ``g''
215 packet. It is used as a heuristic when determining the maximum
216 size of memory-read and memory-write packets. A target will
217 typically only reserve a buffer large enough to hold the ``g''
218 packet. The size does not include packet overhead (headers and
219 trailers). */
220 long actual_register_packet_size;
221
222 /* This is the maximum size (in chars) of a non read/write packet.
223 It is also used as a cap on the size of read/write packets. */
224 long remote_packet_size;
225 };
226
227 /* Description of the remote protocol state for the currently
228 connected target. This is per-target state, and independent of the
229 selected architecture. */
230
231 class remote_state
232 {
233 public:
234
235 remote_state ();
236 ~remote_state ();
237
238 /* Get the remote arch state for GDBARCH. */
239 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
240
241 public: /* data */
242
243 /* A buffer to use for incoming packets, and its current size. The
244 buffer is grown dynamically for larger incoming packets.
245 Outgoing packets may also be constructed in this buffer.
246 The size of the buffer is always at least REMOTE_PACKET_SIZE;
247 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
248 packets. */
249 gdb::char_vector buf;
250
251 /* True if we're going through initial connection setup (finding out
252 about the remote side's threads, relocating symbols, etc.). */
253 bool starting_up = false;
254
255 /* If we negotiated packet size explicitly (and thus can bypass
256 heuristics for the largest packet size that will not overflow
257 a buffer in the stub), this will be set to that packet size.
258 Otherwise zero, meaning to use the guessed size. */
259 long explicit_packet_size = 0;
260
261 /* True, if in no ack mode. That is, neither GDB nor the stub will
262 expect acks from each other. The connection is assumed to be
263 reliable. */
264 bool noack_mode = false;
265
266 /* True if we're connected in extended remote mode. */
267 bool extended = false;
268
269 /* True if we resumed the target and we're waiting for the target to
270 stop. In the mean time, we can't start another command/query.
271 The remote server wouldn't be ready to process it, so we'd
272 timeout waiting for a reply that would never come and eventually
273 we'd close the connection. This can happen in asynchronous mode
274 because we allow GDB commands while the target is running. */
275 bool waiting_for_stop_reply = false;
276
277 /* The status of the stub support for the various vCont actions. */
278 vCont_action_support supports_vCont;
279 /* Whether vCont support was probed already. This is a workaround
280 until packet_support is per-connection. */
281 bool supports_vCont_probed;
282
283 /* True if the user has pressed Ctrl-C, but the target hasn't
284 responded to that. */
285 bool ctrlc_pending_p = false;
286
287 /* True if we saw a Ctrl-C while reading or writing from/to the
288 remote descriptor. At that point it is not safe to send a remote
289 interrupt packet, so we instead remember we saw the Ctrl-C and
290 process it once we're done with sending/receiving the current
291 packet, which should be shortly. If however that takes too long,
292 and the user presses Ctrl-C again, we offer to disconnect. */
293 bool got_ctrlc_during_io = false;
294
295 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
296 remote_open knows that we don't have a file open when the program
297 starts. */
298 struct serial *remote_desc = nullptr;
299
300 /* These are the threads which we last sent to the remote system. The
301 TID member will be -1 for all or -2 for not sent yet. */
302 ptid_t general_thread = null_ptid;
303 ptid_t continue_thread = null_ptid;
304
305 /* This is the traceframe which we last selected on the remote system.
306 It will be -1 if no traceframe is selected. */
307 int remote_traceframe_number = -1;
308
309 char *last_pass_packet = nullptr;
310
311 /* The last QProgramSignals packet sent to the target. We bypass
312 sending a new program signals list down to the target if the new
313 packet is exactly the same as the last we sent. IOW, we only let
314 the target know about program signals list changes. */
315 char *last_program_signals_packet = nullptr;
316
317 gdb_signal last_sent_signal = GDB_SIGNAL_0;
318
319 bool last_sent_step = false;
320
321 /* The execution direction of the last resume we got. */
322 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
323
324 char *finished_object = nullptr;
325 char *finished_annex = nullptr;
326 ULONGEST finished_offset = 0;
327
328 /* Should we try the 'ThreadInfo' query packet?
329
330 This variable (NOT available to the user: auto-detect only!)
331 determines whether GDB will use the new, simpler "ThreadInfo"
332 query or the older, more complex syntax for thread queries.
333 This is an auto-detect variable (set to true at each connect,
334 and set to false when the target fails to recognize it). */
335 bool use_threadinfo_query = false;
336 bool use_threadextra_query = false;
337
338 threadref echo_nextthread {};
339 threadref nextthread {};
340 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
341
342 /* The state of remote notification. */
343 struct remote_notif_state *notif_state = nullptr;
344
345 /* The branch trace configuration. */
346 struct btrace_config btrace_config {};
347
348 /* The argument to the last "vFile:setfs:" packet we sent, used
349 to avoid sending repeated unnecessary "vFile:setfs:" packets.
350 Initialized to -1 to indicate that no "vFile:setfs:" packet
351 has yet been sent. */
352 int fs_pid = -1;
353
354 /* A readahead cache for vFile:pread. Often, reading a binary
355 involves a sequence of small reads. E.g., when parsing an ELF
356 file. A readahead cache helps mostly the case of remote
357 debugging on a connection with higher latency, due to the
358 request/reply nature of the RSP. We only cache data for a single
359 file descriptor at a time. */
360 struct readahead_cache readahead_cache;
361
362 /* The list of already fetched and acknowledged stop events. This
363 queue is used for notification Stop, and other notifications
364 don't need queue for their events, because the notification
365 events of Stop can't be consumed immediately, so that events
366 should be queued first, and be consumed by remote_wait_{ns,as}
367 one per time. Other notifications can consume their events
368 immediately, so queue is not needed for them. */
369 std::vector<stop_reply_up> stop_reply_queue;
370
371 /* Asynchronous signal handle registered as event loop source for
372 when we have pending events ready to be passed to the core. */
373 struct async_event_handler *remote_async_inferior_event_token = nullptr;
374
375 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
376 ``forever'' still use the normal timeout mechanism. This is
377 currently used by the ASYNC code to guarentee that target reads
378 during the initial connect always time-out. Once getpkt has been
379 modified to return a timeout indication and, in turn
380 remote_wait()/wait_for_inferior() have gained a timeout parameter
381 this can go away. */
382 int wait_forever_enabled_p = 1;
383
384 private:
385 /* Mapping of remote protocol data for each gdbarch. Usually there
386 is only one entry here, though we may see more with stubs that
387 support multi-process. */
388 std::unordered_map<struct gdbarch *, remote_arch_state>
389 m_arch_states;
390 };
391
392 static const target_info remote_target_info = {
393 "remote",
394 N_("Remote target using gdb-specific protocol"),
395 remote_doc
396 };
397
398 class remote_target : public process_stratum_target
399 {
400 public:
401 remote_target () = default;
402 ~remote_target () override;
403
404 const target_info &info () const override
405 { return remote_target_info; }
406
407 const char *connection_string () override;
408
409 thread_control_capabilities get_thread_control_capabilities () override
410 { return tc_schedlock; }
411
412 /* Open a remote connection. */
413 static void open (const char *, int);
414
415 void close () override;
416
417 void detach (inferior *, int) override;
418 void disconnect (const char *, int) override;
419
420 void commit_resumed () override;
421 void resume (ptid_t, int, enum gdb_signal) override;
422 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
423 bool has_pending_events () override;
424
425 void fetch_registers (struct regcache *, int) override;
426 void store_registers (struct regcache *, int) override;
427 void prepare_to_store (struct regcache *) override;
428
429 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
430
431 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
432 enum remove_bp_reason) override;
433
434
435 bool stopped_by_sw_breakpoint () override;
436 bool supports_stopped_by_sw_breakpoint () override;
437
438 bool stopped_by_hw_breakpoint () override;
439
440 bool supports_stopped_by_hw_breakpoint () override;
441
442 bool stopped_by_watchpoint () override;
443
444 bool stopped_data_address (CORE_ADDR *) override;
445
446 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
447
448 int can_use_hw_breakpoint (enum bptype, int, int) override;
449
450 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
451
452 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
453
454 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
455
456 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
457 struct expression *) override;
458
459 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
460 struct expression *) override;
461
462 void kill () override;
463
464 void load (const char *, int) override;
465
466 void mourn_inferior () override;
467
468 void pass_signals (gdb::array_view<const unsigned char>) override;
469
470 int set_syscall_catchpoint (int, bool, int,
471 gdb::array_view<const int>) override;
472
473 void program_signals (gdb::array_view<const unsigned char>) override;
474
475 bool thread_alive (ptid_t ptid) override;
476
477 const char *thread_name (struct thread_info *) override;
478
479 void update_thread_list () override;
480
481 std::string pid_to_str (ptid_t) override;
482
483 const char *extra_thread_info (struct thread_info *) override;
484
485 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
486
487 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
488 int handle_len,
489 inferior *inf) override;
490
491 gdb::byte_vector thread_info_to_thread_handle (struct thread_info *tp)
492 override;
493
494 void stop (ptid_t) override;
495
496 void interrupt () override;
497
498 void pass_ctrlc () override;
499
500 enum target_xfer_status xfer_partial (enum target_object object,
501 const char *annex,
502 gdb_byte *readbuf,
503 const gdb_byte *writebuf,
504 ULONGEST offset, ULONGEST len,
505 ULONGEST *xfered_len) override;
506
507 ULONGEST get_memory_xfer_limit () override;
508
509 void rcmd (const char *command, struct ui_file *output) override;
510
511 char *pid_to_exec_file (int pid) override;
512
513 void log_command (const char *cmd) override
514 {
515 serial_log_command (this, cmd);
516 }
517
518 CORE_ADDR get_thread_local_address (ptid_t ptid,
519 CORE_ADDR load_module_addr,
520 CORE_ADDR offset) override;
521
522 bool can_execute_reverse () override;
523
524 std::vector<mem_region> memory_map () override;
525
526 void flash_erase (ULONGEST address, LONGEST length) override;
527
528 void flash_done () override;
529
530 const struct target_desc *read_description () override;
531
532 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
533 const gdb_byte *pattern, ULONGEST pattern_len,
534 CORE_ADDR *found_addrp) override;
535
536 bool can_async_p () override;
537
538 bool is_async_p () override;
539
540 void async (int) override;
541
542 int async_wait_fd () override;
543
544 void thread_events (int) override;
545
546 int can_do_single_step () override;
547
548 void terminal_inferior () override;
549
550 void terminal_ours () override;
551
552 bool supports_non_stop () override;
553
554 bool supports_multi_process () override;
555
556 bool supports_disable_randomization () override;
557
558 bool filesystem_is_local () override;
559
560
561 int fileio_open (struct inferior *inf, const char *filename,
562 int flags, int mode, int warn_if_slow,
563 int *target_errno) override;
564
565 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
566 ULONGEST offset, int *target_errno) override;
567
568 int fileio_pread (int fd, gdb_byte *read_buf, int len,
569 ULONGEST offset, int *target_errno) override;
570
571 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
572
573 int fileio_close (int fd, int *target_errno) override;
574
575 int fileio_unlink (struct inferior *inf,
576 const char *filename,
577 int *target_errno) override;
578
579 gdb::optional<std::string>
580 fileio_readlink (struct inferior *inf,
581 const char *filename,
582 int *target_errno) override;
583
584 bool supports_enable_disable_tracepoint () override;
585
586 bool supports_string_tracing () override;
587
588 bool supports_evaluation_of_breakpoint_conditions () override;
589
590 bool can_run_breakpoint_commands () override;
591
592 void trace_init () override;
593
594 void download_tracepoint (struct bp_location *location) override;
595
596 bool can_download_tracepoint () override;
597
598 void download_trace_state_variable (const trace_state_variable &tsv) override;
599
600 void enable_tracepoint (struct bp_location *location) override;
601
602 void disable_tracepoint (struct bp_location *location) override;
603
604 void trace_set_readonly_regions () override;
605
606 void trace_start () override;
607
608 int get_trace_status (struct trace_status *ts) override;
609
610 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
611 override;
612
613 void trace_stop () override;
614
615 int trace_find (enum trace_find_type type, int num,
616 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
617
618 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
619
620 int save_trace_data (const char *filename) override;
621
622 int upload_tracepoints (struct uploaded_tp **utpp) override;
623
624 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
625
626 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
627
628 int get_min_fast_tracepoint_insn_len () override;
629
630 void set_disconnected_tracing (int val) override;
631
632 void set_circular_trace_buffer (int val) override;
633
634 void set_trace_buffer_size (LONGEST val) override;
635
636 bool set_trace_notes (const char *user, const char *notes,
637 const char *stopnotes) override;
638
639 int core_of_thread (ptid_t ptid) override;
640
641 int verify_memory (const gdb_byte *data,
642 CORE_ADDR memaddr, ULONGEST size) override;
643
644
645 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
646
647 void set_permissions () override;
648
649 bool static_tracepoint_marker_at (CORE_ADDR,
650 struct static_tracepoint_marker *marker)
651 override;
652
653 std::vector<static_tracepoint_marker>
654 static_tracepoint_markers_by_strid (const char *id) override;
655
656 traceframe_info_up traceframe_info () override;
657
658 bool use_agent (bool use) override;
659 bool can_use_agent () override;
660
661 struct btrace_target_info *
662 enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
663
664 void disable_btrace (struct btrace_target_info *tinfo) override;
665
666 void teardown_btrace (struct btrace_target_info *tinfo) override;
667
668 enum btrace_error read_btrace (struct btrace_data *data,
669 struct btrace_target_info *btinfo,
670 enum btrace_read_type type) override;
671
672 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
673 bool augmented_libraries_svr4_read () override;
674 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
675 void follow_exec (inferior *, ptid_t, const char *) override;
676 int insert_fork_catchpoint (int) override;
677 int remove_fork_catchpoint (int) override;
678 int insert_vfork_catchpoint (int) override;
679 int remove_vfork_catchpoint (int) override;
680 int insert_exec_catchpoint (int) override;
681 int remove_exec_catchpoint (int) override;
682 enum exec_direction_kind execution_direction () override;
683
684 bool supports_memory_tagging () override;
685
686 bool fetch_memtags (CORE_ADDR address, size_t len,
687 gdb::byte_vector &tags, int type) override;
688
689 bool store_memtags (CORE_ADDR address, size_t len,
690 const gdb::byte_vector &tags, int type) override;
691
692 public: /* Remote specific methods. */
693
694 void remote_download_command_source (int num, ULONGEST addr,
695 struct command_line *cmds);
696
697 void remote_file_put (const char *local_file, const char *remote_file,
698 int from_tty);
699 void remote_file_get (const char *remote_file, const char *local_file,
700 int from_tty);
701 void remote_file_delete (const char *remote_file, int from_tty);
702
703 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
704 ULONGEST offset, int *remote_errno);
705 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
706 ULONGEST offset, int *remote_errno);
707 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
708 ULONGEST offset, int *remote_errno);
709
710 int remote_hostio_send_command (int command_bytes, int which_packet,
711 int *remote_errno, const char **attachment,
712 int *attachment_len);
713 int remote_hostio_set_filesystem (struct inferior *inf,
714 int *remote_errno);
715 /* We should get rid of this and use fileio_open directly. */
716 int remote_hostio_open (struct inferior *inf, const char *filename,
717 int flags, int mode, int warn_if_slow,
718 int *remote_errno);
719 int remote_hostio_close (int fd, int *remote_errno);
720
721 int remote_hostio_unlink (inferior *inf, const char *filename,
722 int *remote_errno);
723
724 struct remote_state *get_remote_state ();
725
726 long get_remote_packet_size (void);
727 long get_memory_packet_size (struct memory_packet_config *config);
728
729 long get_memory_write_packet_size ();
730 long get_memory_read_packet_size ();
731
732 char *append_pending_thread_resumptions (char *p, char *endp,
733 ptid_t ptid);
734 static void open_1 (const char *name, int from_tty, int extended_p);
735 void start_remote (int from_tty, int extended_p);
736 void remote_detach_1 (struct inferior *inf, int from_tty);
737
738 char *append_resumption (char *p, char *endp,
739 ptid_t ptid, int step, gdb_signal siggnal);
740 int remote_resume_with_vcont (ptid_t ptid, int step,
741 gdb_signal siggnal);
742
743 thread_info *add_current_inferior_and_thread (const char *wait_status);
744
745 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
746 target_wait_flags options);
747 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
748 target_wait_flags options);
749
750 ptid_t process_stop_reply (struct stop_reply *stop_reply,
751 target_waitstatus *status);
752
753 ptid_t select_thread_for_ambiguous_stop_reply
754 (const struct target_waitstatus &status);
755
756 void remote_notice_new_inferior (ptid_t currthread, bool executing);
757
758 void print_one_stopped_thread (thread_info *thread);
759 void process_initial_stop_replies (int from_tty);
760
761 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
762 bool silent_p);
763
764 void btrace_sync_conf (const btrace_config *conf);
765
766 void remote_btrace_maybe_reopen ();
767
768 void remove_new_fork_children (threads_listing_context *context);
769 void kill_new_fork_children (inferior *inf);
770 void discard_pending_stop_replies (struct inferior *inf);
771 int stop_reply_queue_length ();
772
773 void check_pending_events_prevent_wildcard_vcont
774 (bool *may_global_wildcard_vcont);
775
776 void discard_pending_stop_replies_in_queue ();
777 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
778 struct stop_reply *queued_stop_reply (ptid_t ptid);
779 int peek_stop_reply (ptid_t ptid);
780 void remote_parse_stop_reply (const char *buf, stop_reply *event);
781
782 void remote_stop_ns (ptid_t ptid);
783 void remote_interrupt_as ();
784 void remote_interrupt_ns ();
785
786 char *remote_get_noisy_reply ();
787 int remote_query_attached (int pid);
788 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
789 int try_open_exec);
790
791 ptid_t remote_current_thread (ptid_t oldpid);
792 ptid_t get_current_thread (const char *wait_status);
793
794 void set_thread (ptid_t ptid, int gen);
795 void set_general_thread (ptid_t ptid);
796 void set_continue_thread (ptid_t ptid);
797 void set_general_process ();
798
799 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
800
801 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
802 gdb_ext_thread_info *info);
803 int remote_get_threadinfo (threadref *threadid, int fieldset,
804 gdb_ext_thread_info *info);
805
806 int parse_threadlist_response (const char *pkt, int result_limit,
807 threadref *original_echo,
808 threadref *resultlist,
809 int *doneflag);
810 int remote_get_threadlist (int startflag, threadref *nextthread,
811 int result_limit, int *done, int *result_count,
812 threadref *threadlist);
813
814 int remote_threadlist_iterator (rmt_thread_action stepfunction,
815 void *context, int looplimit);
816
817 int remote_get_threads_with_ql (threads_listing_context *context);
818 int remote_get_threads_with_qxfer (threads_listing_context *context);
819 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
820
821 void extended_remote_restart ();
822
823 void get_offsets ();
824
825 void remote_check_symbols ();
826
827 void remote_supported_packet (const struct protocol_feature *feature,
828 enum packet_support support,
829 const char *argument);
830
831 void remote_query_supported ();
832
833 void remote_packet_size (const protocol_feature *feature,
834 packet_support support, const char *value);
835
836 void remote_serial_quit_handler ();
837
838 void remote_detach_pid (int pid);
839
840 void remote_vcont_probe ();
841
842 void remote_resume_with_hc (ptid_t ptid, int step,
843 gdb_signal siggnal);
844
845 void send_interrupt_sequence ();
846 void interrupt_query ();
847
848 void remote_notif_get_pending_events (notif_client *nc);
849
850 int fetch_register_using_p (struct regcache *regcache,
851 packet_reg *reg);
852 int send_g_packet ();
853 void process_g_packet (struct regcache *regcache);
854 void fetch_registers_using_g (struct regcache *regcache);
855 int store_register_using_P (const struct regcache *regcache,
856 packet_reg *reg);
857 void store_registers_using_G (const struct regcache *regcache);
858
859 void set_remote_traceframe ();
860
861 void check_binary_download (CORE_ADDR addr);
862
863 target_xfer_status remote_write_bytes_aux (const char *header,
864 CORE_ADDR memaddr,
865 const gdb_byte *myaddr,
866 ULONGEST len_units,
867 int unit_size,
868 ULONGEST *xfered_len_units,
869 char packet_format,
870 int use_length);
871
872 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
873 const gdb_byte *myaddr, ULONGEST len,
874 int unit_size, ULONGEST *xfered_len);
875
876 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
877 ULONGEST len_units,
878 int unit_size, ULONGEST *xfered_len_units);
879
880 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
881 ULONGEST memaddr,
882 ULONGEST len,
883 int unit_size,
884 ULONGEST *xfered_len);
885
886 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
887 gdb_byte *myaddr, ULONGEST len,
888 int unit_size,
889 ULONGEST *xfered_len);
890
891 packet_result remote_send_printf (const char *format, ...)
892 ATTRIBUTE_PRINTF (2, 3);
893
894 target_xfer_status remote_flash_write (ULONGEST address,
895 ULONGEST length, ULONGEST *xfered_len,
896 const gdb_byte *data);
897
898 int readchar (int timeout);
899
900 void remote_serial_write (const char *str, int len);
901
902 int putpkt (const char *buf);
903 int putpkt_binary (const char *buf, int cnt);
904
905 int putpkt (const gdb::char_vector &buf)
906 {
907 return putpkt (buf.data ());
908 }
909
910 void skip_frame ();
911 long read_frame (gdb::char_vector *buf_p);
912 void getpkt (gdb::char_vector *buf, int forever);
913 int getpkt_or_notif_sane_1 (gdb::char_vector *buf, int forever,
914 int expecting_notif, int *is_notif);
915 int getpkt_sane (gdb::char_vector *buf, int forever);
916 int getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
917 int *is_notif);
918 int remote_vkill (int pid);
919 void remote_kill_k ();
920
921 void extended_remote_disable_randomization (int val);
922 int extended_remote_run (const std::string &args);
923
924 void send_environment_packet (const char *action,
925 const char *packet,
926 const char *value);
927
928 void extended_remote_environment_support ();
929 void extended_remote_set_inferior_cwd ();
930
931 target_xfer_status remote_write_qxfer (const char *object_name,
932 const char *annex,
933 const gdb_byte *writebuf,
934 ULONGEST offset, LONGEST len,
935 ULONGEST *xfered_len,
936 struct packet_config *packet);
937
938 target_xfer_status remote_read_qxfer (const char *object_name,
939 const char *annex,
940 gdb_byte *readbuf, ULONGEST offset,
941 LONGEST len,
942 ULONGEST *xfered_len,
943 struct packet_config *packet);
944
945 void push_stop_reply (struct stop_reply *new_event);
946
947 bool vcont_r_supported ();
948
949 private:
950
951 bool start_remote_1 (int from_tty, int extended_p);
952
953 /* The remote state. Don't reference this directly. Use the
954 get_remote_state method instead. */
955 remote_state m_remote_state;
956 };
957
958 static const target_info extended_remote_target_info = {
959 "extended-remote",
960 N_("Extended remote target using gdb-specific protocol"),
961 remote_doc
962 };
963
964 /* Set up the extended remote target by extending the standard remote
965 target and adding to it. */
966
967 class extended_remote_target final : public remote_target
968 {
969 public:
970 const target_info &info () const override
971 { return extended_remote_target_info; }
972
973 /* Open an extended-remote connection. */
974 static void open (const char *, int);
975
976 bool can_create_inferior () override { return true; }
977 void create_inferior (const char *, const std::string &,
978 char **, int) override;
979
980 void detach (inferior *, int) override;
981
982 bool can_attach () override { return true; }
983 void attach (const char *, int) override;
984
985 void post_attach (int) override;
986 bool supports_disable_randomization () override;
987 };
988
989 struct stop_reply : public notif_event
990 {
991 ~stop_reply ();
992
993 /* The identifier of the thread about this event */
994 ptid_t ptid;
995
996 /* The remote state this event is associated with. When the remote
997 connection, represented by a remote_state object, is closed,
998 all the associated stop_reply events should be released. */
999 struct remote_state *rs;
1000
1001 struct target_waitstatus ws;
1002
1003 /* The architecture associated with the expedited registers. */
1004 gdbarch *arch;
1005
1006 /* Expedited registers. This makes remote debugging a bit more
1007 efficient for those targets that provide critical registers as
1008 part of their normal status mechanism (as another roundtrip to
1009 fetch them is avoided). */
1010 std::vector<cached_reg_t> regcache;
1011
1012 enum target_stop_reason stop_reason;
1013
1014 CORE_ADDR watch_data_address;
1015
1016 int core;
1017 };
1018
1019 /* See remote.h. */
1020
1021 bool
1022 is_remote_target (process_stratum_target *target)
1023 {
1024 remote_target *rt = dynamic_cast<remote_target *> (target);
1025 return rt != nullptr;
1026 }
1027
1028 /* Per-program-space data key. */
1029 static const struct program_space_key<char, gdb::xfree_deleter<char>>
1030 remote_pspace_data;
1031
1032 /* The variable registered as the control variable used by the
1033 remote exec-file commands. While the remote exec-file setting is
1034 per-program-space, the set/show machinery uses this as the
1035 location of the remote exec-file value. */
1036 static std::string remote_exec_file_var;
1037
1038 /* The size to align memory write packets, when practical. The protocol
1039 does not guarantee any alignment, and gdb will generate short
1040 writes and unaligned writes, but even as a best-effort attempt this
1041 can improve bulk transfers. For instance, if a write is misaligned
1042 relative to the target's data bus, the stub may need to make an extra
1043 round trip fetching data from the target. This doesn't make a
1044 huge difference, but it's easy to do, so we try to be helpful.
1045
1046 The alignment chosen is arbitrary; usually data bus width is
1047 important here, not the possibly larger cache line size. */
1048 enum { REMOTE_ALIGN_WRITES = 16 };
1049
1050 /* Prototypes for local functions. */
1051
1052 static int hexnumlen (ULONGEST num);
1053
1054 static int stubhex (int ch);
1055
1056 static int hexnumstr (char *, ULONGEST);
1057
1058 static int hexnumnstr (char *, ULONGEST, int);
1059
1060 static CORE_ADDR remote_address_masked (CORE_ADDR);
1061
1062 static int stub_unpack_int (const char *buff, int fieldlength);
1063
1064 struct packet_config;
1065
1066 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1067 int from_tty,
1068 struct cmd_list_element *c,
1069 const char *value);
1070
1071 static ptid_t read_ptid (const char *buf, const char **obuf);
1072
1073 static void remote_async_inferior_event_handler (gdb_client_data);
1074
1075 static bool remote_read_description_p (struct target_ops *target);
1076
1077 static void remote_console_output (const char *msg);
1078
1079 static void remote_btrace_reset (remote_state *rs);
1080
1081 static void remote_unpush_and_throw (remote_target *target);
1082
1083 /* For "remote". */
1084
1085 static struct cmd_list_element *remote_cmdlist;
1086
1087 /* For "set remote" and "show remote". */
1088
1089 static struct cmd_list_element *remote_set_cmdlist;
1090 static struct cmd_list_element *remote_show_cmdlist;
1091
1092 /* Controls whether GDB is willing to use range stepping. */
1093
1094 static bool use_range_stepping = true;
1095
1096 /* From the remote target's point of view, each thread is in one of these three
1097 states. */
1098 enum class resume_state
1099 {
1100 /* Not resumed - we haven't been asked to resume this thread. */
1101 NOT_RESUMED,
1102
1103 /* We have been asked to resume this thread, but haven't sent a vCont action
1104 for it yet. We'll need to consider it next time commit_resume is
1105 called. */
1106 RESUMED_PENDING_VCONT,
1107
1108 /* We have been asked to resume this thread, and we have sent a vCont action
1109 for it. */
1110 RESUMED,
1111 };
1112
1113 /* Information about a thread's pending vCont-resume. Used when a thread is in
1114 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1115 stores this information which is then picked up by
1116 remote_target::commit_resume to know which is the proper action for this
1117 thread to include in the vCont packet. */
1118 struct resumed_pending_vcont_info
1119 {
1120 /* True if the last resume call for this thread was a step request, false
1121 if a continue request. */
1122 bool step;
1123
1124 /* The signal specified in the last resume call for this thread. */
1125 gdb_signal sig;
1126 };
1127
1128 /* Private data that we'll store in (struct thread_info)->priv. */
1129 struct remote_thread_info : public private_thread_info
1130 {
1131 std::string extra;
1132 std::string name;
1133 int core = -1;
1134
1135 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1136 sequence of bytes. */
1137 gdb::byte_vector thread_handle;
1138
1139 /* Whether the target stopped for a breakpoint/watchpoint. */
1140 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1141
1142 /* This is set to the data address of the access causing the target
1143 to stop for a watchpoint. */
1144 CORE_ADDR watch_data_address = 0;
1145
1146 /* Get the thread's resume state. */
1147 enum resume_state get_resume_state () const
1148 {
1149 return m_resume_state;
1150 }
1151
1152 /* Put the thread in the NOT_RESUMED state. */
1153 void set_not_resumed ()
1154 {
1155 m_resume_state = resume_state::NOT_RESUMED;
1156 }
1157
1158 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1159 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1160 {
1161 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1162 m_resumed_pending_vcont_info.step = step;
1163 m_resumed_pending_vcont_info.sig = sig;
1164 }
1165
1166 /* Get the information this thread's pending vCont-resumption.
1167
1168 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1169 state. */
1170 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1171 {
1172 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1173
1174 return m_resumed_pending_vcont_info;
1175 }
1176
1177 /* Put the thread in the VCONT_RESUMED state. */
1178 void set_resumed ()
1179 {
1180 m_resume_state = resume_state::RESUMED;
1181 }
1182
1183 private:
1184 /* Resume state for this thread. This is used to implement vCont action
1185 coalescing (only when the target operates in non-stop mode).
1186
1187 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1188 which notes that this thread must be considered in the next commit_resume
1189 call.
1190
1191 remote_target::commit_resume sends a vCont packet with actions for the
1192 threads in the RESUMED_PENDING_VCONT state and moves them to the
1193 VCONT_RESUMED state.
1194
1195 When reporting a stop to the core for a thread, that thread is moved back
1196 to the NOT_RESUMED state. */
1197 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1198
1199 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1200 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1201 };
1202
1203 remote_state::remote_state ()
1204 : buf (400)
1205 {
1206 }
1207
1208 remote_state::~remote_state ()
1209 {
1210 xfree (this->last_pass_packet);
1211 xfree (this->last_program_signals_packet);
1212 xfree (this->finished_object);
1213 xfree (this->finished_annex);
1214 }
1215
1216 /* Utility: generate error from an incoming stub packet. */
1217 static void
1218 trace_error (char *buf)
1219 {
1220 if (*buf++ != 'E')
1221 return; /* not an error msg */
1222 switch (*buf)
1223 {
1224 case '1': /* malformed packet error */
1225 if (*++buf == '0') /* general case: */
1226 error (_("remote.c: error in outgoing packet."));
1227 else
1228 error (_("remote.c: error in outgoing packet at field #%ld."),
1229 strtol (buf, NULL, 16));
1230 default:
1231 error (_("Target returns error code '%s'."), buf);
1232 }
1233 }
1234
1235 /* Utility: wait for reply from stub, while accepting "O" packets. */
1236
1237 char *
1238 remote_target::remote_get_noisy_reply ()
1239 {
1240 struct remote_state *rs = get_remote_state ();
1241
1242 do /* Loop on reply from remote stub. */
1243 {
1244 char *buf;
1245
1246 QUIT; /* Allow user to bail out with ^C. */
1247 getpkt (&rs->buf, 0);
1248 buf = rs->buf.data ();
1249 if (buf[0] == 'E')
1250 trace_error (buf);
1251 else if (startswith (buf, "qRelocInsn:"))
1252 {
1253 ULONGEST ul;
1254 CORE_ADDR from, to, org_to;
1255 const char *p, *pp;
1256 int adjusted_size = 0;
1257 int relocated = 0;
1258
1259 p = buf + strlen ("qRelocInsn:");
1260 pp = unpack_varlen_hex (p, &ul);
1261 if (*pp != ';')
1262 error (_("invalid qRelocInsn packet: %s"), buf);
1263 from = ul;
1264
1265 p = pp + 1;
1266 unpack_varlen_hex (p, &ul);
1267 to = ul;
1268
1269 org_to = to;
1270
1271 try
1272 {
1273 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
1274 relocated = 1;
1275 }
1276 catch (const gdb_exception &ex)
1277 {
1278 if (ex.error == MEMORY_ERROR)
1279 {
1280 /* Propagate memory errors silently back to the
1281 target. The stub may have limited the range of
1282 addresses we can write to, for example. */
1283 }
1284 else
1285 {
1286 /* Something unexpectedly bad happened. Be verbose
1287 so we can tell what, and propagate the error back
1288 to the stub, so it doesn't get stuck waiting for
1289 a response. */
1290 exception_fprintf (gdb_stderr, ex,
1291 _("warning: relocating instruction: "));
1292 }
1293 putpkt ("E01");
1294 }
1295
1296 if (relocated)
1297 {
1298 adjusted_size = to - org_to;
1299
1300 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1301 putpkt (buf);
1302 }
1303 }
1304 else if (buf[0] == 'O' && buf[1] != 'K')
1305 remote_console_output (buf + 1); /* 'O' message from stub */
1306 else
1307 return buf; /* Here's the actual reply. */
1308 }
1309 while (1);
1310 }
1311
1312 struct remote_arch_state *
1313 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1314 {
1315 remote_arch_state *rsa;
1316
1317 auto it = this->m_arch_states.find (gdbarch);
1318 if (it == this->m_arch_states.end ())
1319 {
1320 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1321 std::forward_as_tuple (gdbarch),
1322 std::forward_as_tuple (gdbarch));
1323 rsa = &p.first->second;
1324
1325 /* Make sure that the packet buffer is plenty big enough for
1326 this architecture. */
1327 if (this->buf.size () < rsa->remote_packet_size)
1328 this->buf.resize (2 * rsa->remote_packet_size);
1329 }
1330 else
1331 rsa = &it->second;
1332
1333 return rsa;
1334 }
1335
1336 /* Fetch the global remote target state. */
1337
1338 remote_state *
1339 remote_target::get_remote_state ()
1340 {
1341 /* Make sure that the remote architecture state has been
1342 initialized, because doing so might reallocate rs->buf. Any
1343 function which calls getpkt also needs to be mindful of changes
1344 to rs->buf, but this call limits the number of places which run
1345 into trouble. */
1346 m_remote_state.get_remote_arch_state (target_gdbarch ());
1347
1348 return &m_remote_state;
1349 }
1350
1351 /* Fetch the remote exec-file from the current program space. */
1352
1353 static const char *
1354 get_remote_exec_file (void)
1355 {
1356 char *remote_exec_file;
1357
1358 remote_exec_file = remote_pspace_data.get (current_program_space);
1359 if (remote_exec_file == NULL)
1360 return "";
1361
1362 return remote_exec_file;
1363 }
1364
1365 /* Set the remote exec file for PSPACE. */
1366
1367 static void
1368 set_pspace_remote_exec_file (struct program_space *pspace,
1369 const char *remote_exec_file)
1370 {
1371 char *old_file = remote_pspace_data.get (pspace);
1372
1373 xfree (old_file);
1374 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1375 }
1376
1377 /* The "set/show remote exec-file" set command hook. */
1378
1379 static void
1380 set_remote_exec_file (const char *ignored, int from_tty,
1381 struct cmd_list_element *c)
1382 {
1383 set_pspace_remote_exec_file (current_program_space,
1384 remote_exec_file_var.c_str ());
1385 }
1386
1387 /* The "set/show remote exec-file" show command hook. */
1388
1389 static void
1390 show_remote_exec_file (struct ui_file *file, int from_tty,
1391 struct cmd_list_element *cmd, const char *value)
1392 {
1393 gdb_printf (file, "%s\n", get_remote_exec_file ());
1394 }
1395
1396 static int
1397 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1398 {
1399 int regnum, num_remote_regs, offset;
1400 struct packet_reg **remote_regs;
1401
1402 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1403 {
1404 struct packet_reg *r = &regs[regnum];
1405
1406 if (register_size (gdbarch, regnum) == 0)
1407 /* Do not try to fetch zero-sized (placeholder) registers. */
1408 r->pnum = -1;
1409 else
1410 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1411
1412 r->regnum = regnum;
1413 }
1414
1415 /* Define the g/G packet format as the contents of each register
1416 with a remote protocol number, in order of ascending protocol
1417 number. */
1418
1419 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1420 for (num_remote_regs = 0, regnum = 0;
1421 regnum < gdbarch_num_regs (gdbarch);
1422 regnum++)
1423 if (regs[regnum].pnum != -1)
1424 remote_regs[num_remote_regs++] = &regs[regnum];
1425
1426 std::sort (remote_regs, remote_regs + num_remote_regs,
1427 [] (const packet_reg *a, const packet_reg *b)
1428 { return a->pnum < b->pnum; });
1429
1430 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1431 {
1432 remote_regs[regnum]->in_g_packet = 1;
1433 remote_regs[regnum]->offset = offset;
1434 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1435 }
1436
1437 return offset;
1438 }
1439
1440 /* Given the architecture described by GDBARCH, return the remote
1441 protocol register's number and the register's offset in the g/G
1442 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1443 If the target does not have a mapping for REGNUM, return false,
1444 otherwise, return true. */
1445
1446 int
1447 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1448 int *pnum, int *poffset)
1449 {
1450 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1451
1452 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1453
1454 map_regcache_remote_table (gdbarch, regs.data ());
1455
1456 *pnum = regs[regnum].pnum;
1457 *poffset = regs[regnum].offset;
1458
1459 return *pnum != -1;
1460 }
1461
1462 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1463 {
1464 /* Use the architecture to build a regnum<->pnum table, which will be
1465 1:1 unless a feature set specifies otherwise. */
1466 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1467
1468 /* Record the maximum possible size of the g packet - it may turn out
1469 to be smaller. */
1470 this->sizeof_g_packet
1471 = map_regcache_remote_table (gdbarch, this->regs.get ());
1472
1473 /* Default maximum number of characters in a packet body. Many
1474 remote stubs have a hardwired buffer size of 400 bytes
1475 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1476 as the maximum packet-size to ensure that the packet and an extra
1477 NUL character can always fit in the buffer. This stops GDB
1478 trashing stubs that try to squeeze an extra NUL into what is
1479 already a full buffer (As of 1999-12-04 that was most stubs). */
1480 this->remote_packet_size = 400 - 1;
1481
1482 /* This one is filled in when a ``g'' packet is received. */
1483 this->actual_register_packet_size = 0;
1484
1485 /* Should rsa->sizeof_g_packet needs more space than the
1486 default, adjust the size accordingly. Remember that each byte is
1487 encoded as two characters. 32 is the overhead for the packet
1488 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1489 (``$NN:G...#NN'') is a better guess, the below has been padded a
1490 little. */
1491 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1492 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1493 }
1494
1495 /* Get a pointer to the current remote target. If not connected to a
1496 remote target, return NULL. */
1497
1498 static remote_target *
1499 get_current_remote_target ()
1500 {
1501 target_ops *proc_target = current_inferior ()->process_target ();
1502 return dynamic_cast<remote_target *> (proc_target);
1503 }
1504
1505 /* Return the current allowed size of a remote packet. This is
1506 inferred from the current architecture, and should be used to
1507 limit the length of outgoing packets. */
1508 long
1509 remote_target::get_remote_packet_size ()
1510 {
1511 struct remote_state *rs = get_remote_state ();
1512 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1513
1514 if (rs->explicit_packet_size)
1515 return rs->explicit_packet_size;
1516
1517 return rsa->remote_packet_size;
1518 }
1519
1520 static struct packet_reg *
1521 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1522 long regnum)
1523 {
1524 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1525 return NULL;
1526 else
1527 {
1528 struct packet_reg *r = &rsa->regs[regnum];
1529
1530 gdb_assert (r->regnum == regnum);
1531 return r;
1532 }
1533 }
1534
1535 static struct packet_reg *
1536 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1537 LONGEST pnum)
1538 {
1539 int i;
1540
1541 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1542 {
1543 struct packet_reg *r = &rsa->regs[i];
1544
1545 if (r->pnum == pnum)
1546 return r;
1547 }
1548 return NULL;
1549 }
1550
1551 /* Allow the user to specify what sequence to send to the remote
1552 when he requests a program interruption: Although ^C is usually
1553 what remote systems expect (this is the default, here), it is
1554 sometimes preferable to send a break. On other systems such
1555 as the Linux kernel, a break followed by g, which is Magic SysRq g
1556 is required in order to interrupt the execution. */
1557 const char interrupt_sequence_control_c[] = "Ctrl-C";
1558 const char interrupt_sequence_break[] = "BREAK";
1559 const char interrupt_sequence_break_g[] = "BREAK-g";
1560 static const char *const interrupt_sequence_modes[] =
1561 {
1562 interrupt_sequence_control_c,
1563 interrupt_sequence_break,
1564 interrupt_sequence_break_g,
1565 NULL
1566 };
1567 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1568
1569 static void
1570 show_interrupt_sequence (struct ui_file *file, int from_tty,
1571 struct cmd_list_element *c,
1572 const char *value)
1573 {
1574 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1575 gdb_printf (file,
1576 _("Send the ASCII ETX character (Ctrl-c) "
1577 "to the remote target to interrupt the "
1578 "execution of the program.\n"));
1579 else if (interrupt_sequence_mode == interrupt_sequence_break)
1580 gdb_printf (file,
1581 _("send a break signal to the remote target "
1582 "to interrupt the execution of the program.\n"));
1583 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1584 gdb_printf (file,
1585 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1586 "the remote target to interrupt the execution "
1587 "of Linux kernel.\n"));
1588 else
1589 internal_error (__FILE__, __LINE__,
1590 _("Invalid value for interrupt_sequence_mode: %s."),
1591 interrupt_sequence_mode);
1592 }
1593
1594 /* This boolean variable specifies whether interrupt_sequence is sent
1595 to the remote target when gdb connects to it.
1596 This is mostly needed when you debug the Linux kernel: The Linux kernel
1597 expects BREAK g which is Magic SysRq g for connecting gdb. */
1598 static bool interrupt_on_connect = false;
1599
1600 /* This variable is used to implement the "set/show remotebreak" commands.
1601 Since these commands are now deprecated in favor of "set/show remote
1602 interrupt-sequence", it no longer has any effect on the code. */
1603 static bool remote_break;
1604
1605 static void
1606 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1607 {
1608 if (remote_break)
1609 interrupt_sequence_mode = interrupt_sequence_break;
1610 else
1611 interrupt_sequence_mode = interrupt_sequence_control_c;
1612 }
1613
1614 static void
1615 show_remotebreak (struct ui_file *file, int from_tty,
1616 struct cmd_list_element *c,
1617 const char *value)
1618 {
1619 }
1620
1621 /* This variable sets the number of bits in an address that are to be
1622 sent in a memory ("M" or "m") packet. Normally, after stripping
1623 leading zeros, the entire address would be sent. This variable
1624 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1625 initial implementation of remote.c restricted the address sent in
1626 memory packets to ``host::sizeof long'' bytes - (typically 32
1627 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1628 address was never sent. Since fixing this bug may cause a break in
1629 some remote targets this variable is principally provided to
1630 facilitate backward compatibility. */
1631
1632 static unsigned int remote_address_size;
1633
1634 \f
1635 /* User configurable variables for the number of characters in a
1636 memory read/write packet. MIN (rsa->remote_packet_size,
1637 rsa->sizeof_g_packet) is the default. Some targets need smaller
1638 values (fifo overruns, et.al.) and some users need larger values
1639 (speed up transfers). The variables ``preferred_*'' (the user
1640 request), ``current_*'' (what was actually set) and ``forced_*''
1641 (Positive - a soft limit, negative - a hard limit). */
1642
1643 struct memory_packet_config
1644 {
1645 const char *name;
1646 long size;
1647 int fixed_p;
1648 };
1649
1650 /* The default max memory-write-packet-size, when the setting is
1651 "fixed". The 16k is historical. (It came from older GDB's using
1652 alloca for buffers and the knowledge (folklore?) that some hosts
1653 don't cope very well with large alloca calls.) */
1654 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1655
1656 /* The minimum remote packet size for memory transfers. Ensures we
1657 can write at least one byte. */
1658 #define MIN_MEMORY_PACKET_SIZE 20
1659
1660 /* Get the memory packet size, assuming it is fixed. */
1661
1662 static long
1663 get_fixed_memory_packet_size (struct memory_packet_config *config)
1664 {
1665 gdb_assert (config->fixed_p);
1666
1667 if (config->size <= 0)
1668 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1669 else
1670 return config->size;
1671 }
1672
1673 /* Compute the current size of a read/write packet. Since this makes
1674 use of ``actual_register_packet_size'' the computation is dynamic. */
1675
1676 long
1677 remote_target::get_memory_packet_size (struct memory_packet_config *config)
1678 {
1679 struct remote_state *rs = get_remote_state ();
1680 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1681
1682 long what_they_get;
1683 if (config->fixed_p)
1684 what_they_get = get_fixed_memory_packet_size (config);
1685 else
1686 {
1687 what_they_get = get_remote_packet_size ();
1688 /* Limit the packet to the size specified by the user. */
1689 if (config->size > 0
1690 && what_they_get > config->size)
1691 what_they_get = config->size;
1692
1693 /* Limit it to the size of the targets ``g'' response unless we have
1694 permission from the stub to use a larger packet size. */
1695 if (rs->explicit_packet_size == 0
1696 && rsa->actual_register_packet_size > 0
1697 && what_they_get > rsa->actual_register_packet_size)
1698 what_they_get = rsa->actual_register_packet_size;
1699 }
1700 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1701 what_they_get = MIN_MEMORY_PACKET_SIZE;
1702
1703 /* Make sure there is room in the global buffer for this packet
1704 (including its trailing NUL byte). */
1705 if (rs->buf.size () < what_they_get + 1)
1706 rs->buf.resize (2 * what_they_get);
1707
1708 return what_they_get;
1709 }
1710
1711 /* Update the size of a read/write packet. If they user wants
1712 something really big then do a sanity check. */
1713
1714 static void
1715 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1716 {
1717 int fixed_p = config->fixed_p;
1718 long size = config->size;
1719
1720 if (args == NULL)
1721 error (_("Argument required (integer, `fixed' or `limited')."));
1722 else if (strcmp (args, "hard") == 0
1723 || strcmp (args, "fixed") == 0)
1724 fixed_p = 1;
1725 else if (strcmp (args, "soft") == 0
1726 || strcmp (args, "limit") == 0)
1727 fixed_p = 0;
1728 else
1729 {
1730 char *end;
1731
1732 size = strtoul (args, &end, 0);
1733 if (args == end)
1734 error (_("Invalid %s (bad syntax)."), config->name);
1735
1736 /* Instead of explicitly capping the size of a packet to or
1737 disallowing it, the user is allowed to set the size to
1738 something arbitrarily large. */
1739 }
1740
1741 /* Extra checks? */
1742 if (fixed_p && !config->fixed_p)
1743 {
1744 /* So that the query shows the correct value. */
1745 long query_size = (size <= 0
1746 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1747 : size);
1748
1749 if (! query (_("The target may not be able to correctly handle a %s\n"
1750 "of %ld bytes. Change the packet size? "),
1751 config->name, query_size))
1752 error (_("Packet size not changed."));
1753 }
1754 /* Update the config. */
1755 config->fixed_p = fixed_p;
1756 config->size = size;
1757 }
1758
1759 static void
1760 show_memory_packet_size (struct memory_packet_config *config)
1761 {
1762 if (config->size == 0)
1763 gdb_printf (_("The %s is 0 (default). "), config->name);
1764 else
1765 gdb_printf (_("The %s is %ld. "), config->name, config->size);
1766 if (config->fixed_p)
1767 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
1768 get_fixed_memory_packet_size (config));
1769 else
1770 {
1771 remote_target *remote = get_current_remote_target ();
1772
1773 if (remote != NULL)
1774 gdb_printf (_("Packets are limited to %ld bytes.\n"),
1775 remote->get_memory_packet_size (config));
1776 else
1777 gdb_puts ("The actual limit will be further reduced "
1778 "dependent on the target.\n");
1779 }
1780 }
1781
1782 /* FIXME: needs to be per-remote-target. */
1783 static struct memory_packet_config memory_write_packet_config =
1784 {
1785 "memory-write-packet-size",
1786 };
1787
1788 static void
1789 set_memory_write_packet_size (const char *args, int from_tty)
1790 {
1791 set_memory_packet_size (args, &memory_write_packet_config);
1792 }
1793
1794 static void
1795 show_memory_write_packet_size (const char *args, int from_tty)
1796 {
1797 show_memory_packet_size (&memory_write_packet_config);
1798 }
1799
1800 /* Show the number of hardware watchpoints that can be used. */
1801
1802 static void
1803 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
1804 struct cmd_list_element *c,
1805 const char *value)
1806 {
1807 gdb_printf (file, _("The maximum number of target hardware "
1808 "watchpoints is %s.\n"), value);
1809 }
1810
1811 /* Show the length limit (in bytes) for hardware watchpoints. */
1812
1813 static void
1814 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
1815 struct cmd_list_element *c,
1816 const char *value)
1817 {
1818 gdb_printf (file, _("The maximum length (in bytes) of a target "
1819 "hardware watchpoint is %s.\n"), value);
1820 }
1821
1822 /* Show the number of hardware breakpoints that can be used. */
1823
1824 static void
1825 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
1826 struct cmd_list_element *c,
1827 const char *value)
1828 {
1829 gdb_printf (file, _("The maximum number of target hardware "
1830 "breakpoints is %s.\n"), value);
1831 }
1832
1833 /* Controls the maximum number of characters to display in the debug output
1834 for each remote packet. The remaining characters are omitted. */
1835
1836 static int remote_packet_max_chars = 512;
1837
1838 /* Show the maximum number of characters to display for each remote packet
1839 when remote debugging is enabled. */
1840
1841 static void
1842 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
1843 struct cmd_list_element *c,
1844 const char *value)
1845 {
1846 gdb_printf (file, _("Number of remote packet characters to "
1847 "display is %s.\n"), value);
1848 }
1849
1850 long
1851 remote_target::get_memory_write_packet_size ()
1852 {
1853 return get_memory_packet_size (&memory_write_packet_config);
1854 }
1855
1856 /* FIXME: needs to be per-remote-target. */
1857 static struct memory_packet_config memory_read_packet_config =
1858 {
1859 "memory-read-packet-size",
1860 };
1861
1862 static void
1863 set_memory_read_packet_size (const char *args, int from_tty)
1864 {
1865 set_memory_packet_size (args, &memory_read_packet_config);
1866 }
1867
1868 static void
1869 show_memory_read_packet_size (const char *args, int from_tty)
1870 {
1871 show_memory_packet_size (&memory_read_packet_config);
1872 }
1873
1874 long
1875 remote_target::get_memory_read_packet_size ()
1876 {
1877 long size = get_memory_packet_size (&memory_read_packet_config);
1878
1879 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1880 extra buffer size argument before the memory read size can be
1881 increased beyond this. */
1882 if (size > get_remote_packet_size ())
1883 size = get_remote_packet_size ();
1884 return size;
1885 }
1886
1887 \f
1888
1889 struct packet_config
1890 {
1891 const char *name;
1892 const char *title;
1893
1894 /* If auto, GDB auto-detects support for this packet or feature,
1895 either through qSupported, or by trying the packet and looking
1896 at the response. If true, GDB assumes the target supports this
1897 packet. If false, the packet is disabled. Configs that don't
1898 have an associated command always have this set to auto. */
1899 enum auto_boolean detect;
1900
1901 /* The "show remote foo-packet" command created for this packet. */
1902 cmd_list_element *show_cmd;
1903
1904 /* Does the target support this packet? */
1905 enum packet_support support;
1906 };
1907
1908 static enum packet_support packet_config_support (struct packet_config *config);
1909 static enum packet_support packet_support (int packet);
1910
1911 static void
1912 show_packet_config_cmd (ui_file *file, struct packet_config *config)
1913 {
1914 const char *support = "internal-error";
1915
1916 switch (packet_config_support (config))
1917 {
1918 case PACKET_ENABLE:
1919 support = "enabled";
1920 break;
1921 case PACKET_DISABLE:
1922 support = "disabled";
1923 break;
1924 case PACKET_SUPPORT_UNKNOWN:
1925 support = "unknown";
1926 break;
1927 }
1928 switch (config->detect)
1929 {
1930 case AUTO_BOOLEAN_AUTO:
1931 gdb_printf (file,
1932 _("Support for the `%s' packet "
1933 "is auto-detected, currently %s.\n"),
1934 config->name, support);
1935 break;
1936 case AUTO_BOOLEAN_TRUE:
1937 case AUTO_BOOLEAN_FALSE:
1938 gdb_printf (file,
1939 _("Support for the `%s' packet is currently %s.\n"),
1940 config->name, support);
1941 break;
1942 }
1943 }
1944
1945 static void
1946 add_packet_config_cmd (struct packet_config *config, const char *name,
1947 const char *title, int legacy)
1948 {
1949 config->name = name;
1950 config->title = title;
1951 gdb::unique_xmalloc_ptr<char> set_doc
1952 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
1953 name, title);
1954 gdb::unique_xmalloc_ptr<char> show_doc
1955 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
1956 name, title);
1957 /* set/show TITLE-packet {auto,on,off} */
1958 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
1959 set_show_commands cmds
1960 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
1961 &config->detect, set_doc.get (),
1962 show_doc.get (), NULL, /* help_doc */
1963 NULL,
1964 show_remote_protocol_packet_cmd,
1965 &remote_set_cmdlist, &remote_show_cmdlist);
1966 config->show_cmd = cmds.show;
1967
1968 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1969 if (legacy)
1970 {
1971 /* It's not clear who should take ownership of the LEGACY_NAME string
1972 created below, so, for now, place the string into a static vector
1973 which ensures the strings is released when GDB exits. */
1974 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
1975 gdb::unique_xmalloc_ptr<char> legacy_name
1976 = xstrprintf ("%s-packet", name);
1977 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
1978 &remote_set_cmdlist);
1979 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
1980 &remote_show_cmdlist);
1981 legacy_names.emplace_back (std::move (legacy_name));
1982 }
1983 }
1984
1985 static enum packet_result
1986 packet_check_result (const char *buf)
1987 {
1988 if (buf[0] != '\0')
1989 {
1990 /* The stub recognized the packet request. Check that the
1991 operation succeeded. */
1992 if (buf[0] == 'E'
1993 && isxdigit (buf[1]) && isxdigit (buf[2])
1994 && buf[3] == '\0')
1995 /* "Enn" - definitely an error. */
1996 return PACKET_ERROR;
1997
1998 /* Always treat "E." as an error. This will be used for
1999 more verbose error messages, such as E.memtypes. */
2000 if (buf[0] == 'E' && buf[1] == '.')
2001 return PACKET_ERROR;
2002
2003 /* The packet may or may not be OK. Just assume it is. */
2004 return PACKET_OK;
2005 }
2006 else
2007 /* The stub does not support the packet. */
2008 return PACKET_UNKNOWN;
2009 }
2010
2011 static enum packet_result
2012 packet_check_result (const gdb::char_vector &buf)
2013 {
2014 return packet_check_result (buf.data ());
2015 }
2016
2017 static enum packet_result
2018 packet_ok (const char *buf, struct packet_config *config)
2019 {
2020 enum packet_result result;
2021
2022 if (config->detect != AUTO_BOOLEAN_TRUE
2023 && config->support == PACKET_DISABLE)
2024 internal_error (__FILE__, __LINE__,
2025 _("packet_ok: attempt to use a disabled packet"));
2026
2027 result = packet_check_result (buf);
2028 switch (result)
2029 {
2030 case PACKET_OK:
2031 case PACKET_ERROR:
2032 /* The stub recognized the packet request. */
2033 if (config->support == PACKET_SUPPORT_UNKNOWN)
2034 {
2035 remote_debug_printf ("Packet %s (%s) is supported",
2036 config->name, config->title);
2037 config->support = PACKET_ENABLE;
2038 }
2039 break;
2040 case PACKET_UNKNOWN:
2041 /* The stub does not support the packet. */
2042 if (config->detect == AUTO_BOOLEAN_AUTO
2043 && config->support == PACKET_ENABLE)
2044 {
2045 /* If the stub previously indicated that the packet was
2046 supported then there is a protocol error. */
2047 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2048 config->name, config->title);
2049 }
2050 else if (config->detect == AUTO_BOOLEAN_TRUE)
2051 {
2052 /* The user set it wrong. */
2053 error (_("Enabled packet %s (%s) not recognized by stub"),
2054 config->name, config->title);
2055 }
2056
2057 remote_debug_printf ("Packet %s (%s) is NOT supported",
2058 config->name, config->title);
2059 config->support = PACKET_DISABLE;
2060 break;
2061 }
2062
2063 return result;
2064 }
2065
2066 static enum packet_result
2067 packet_ok (const gdb::char_vector &buf, struct packet_config *config)
2068 {
2069 return packet_ok (buf.data (), config);
2070 }
2071
2072 enum {
2073 PACKET_vCont = 0,
2074 PACKET_X,
2075 PACKET_qSymbol,
2076 PACKET_P,
2077 PACKET_p,
2078 PACKET_Z0,
2079 PACKET_Z1,
2080 PACKET_Z2,
2081 PACKET_Z3,
2082 PACKET_Z4,
2083 PACKET_vFile_setfs,
2084 PACKET_vFile_open,
2085 PACKET_vFile_pread,
2086 PACKET_vFile_pwrite,
2087 PACKET_vFile_close,
2088 PACKET_vFile_unlink,
2089 PACKET_vFile_readlink,
2090 PACKET_vFile_fstat,
2091 PACKET_qXfer_auxv,
2092 PACKET_qXfer_features,
2093 PACKET_qXfer_exec_file,
2094 PACKET_qXfer_libraries,
2095 PACKET_qXfer_libraries_svr4,
2096 PACKET_qXfer_memory_map,
2097 PACKET_qXfer_osdata,
2098 PACKET_qXfer_threads,
2099 PACKET_qXfer_statictrace_read,
2100 PACKET_qXfer_traceframe_info,
2101 PACKET_qXfer_uib,
2102 PACKET_qGetTIBAddr,
2103 PACKET_qGetTLSAddr,
2104 PACKET_qSupported,
2105 PACKET_qTStatus,
2106 PACKET_QPassSignals,
2107 PACKET_QCatchSyscalls,
2108 PACKET_QProgramSignals,
2109 PACKET_QSetWorkingDir,
2110 PACKET_QStartupWithShell,
2111 PACKET_QEnvironmentHexEncoded,
2112 PACKET_QEnvironmentReset,
2113 PACKET_QEnvironmentUnset,
2114 PACKET_qCRC,
2115 PACKET_qSearch_memory,
2116 PACKET_vAttach,
2117 PACKET_vRun,
2118 PACKET_QStartNoAckMode,
2119 PACKET_vKill,
2120 PACKET_qXfer_siginfo_read,
2121 PACKET_qXfer_siginfo_write,
2122 PACKET_qAttached,
2123
2124 /* Support for conditional tracepoints. */
2125 PACKET_ConditionalTracepoints,
2126
2127 /* Support for target-side breakpoint conditions. */
2128 PACKET_ConditionalBreakpoints,
2129
2130 /* Support for target-side breakpoint commands. */
2131 PACKET_BreakpointCommands,
2132
2133 /* Support for fast tracepoints. */
2134 PACKET_FastTracepoints,
2135
2136 /* Support for static tracepoints. */
2137 PACKET_StaticTracepoints,
2138
2139 /* Support for installing tracepoints while a trace experiment is
2140 running. */
2141 PACKET_InstallInTrace,
2142
2143 PACKET_bc,
2144 PACKET_bs,
2145 PACKET_TracepointSource,
2146 PACKET_QAllow,
2147 PACKET_qXfer_fdpic,
2148 PACKET_QDisableRandomization,
2149 PACKET_QAgent,
2150 PACKET_QTBuffer_size,
2151 PACKET_Qbtrace_off,
2152 PACKET_Qbtrace_bts,
2153 PACKET_Qbtrace_pt,
2154 PACKET_qXfer_btrace,
2155
2156 /* Support for the QNonStop packet. */
2157 PACKET_QNonStop,
2158
2159 /* Support for the QThreadEvents packet. */
2160 PACKET_QThreadEvents,
2161
2162 /* Support for multi-process extensions. */
2163 PACKET_multiprocess_feature,
2164
2165 /* Support for enabling and disabling tracepoints while a trace
2166 experiment is running. */
2167 PACKET_EnableDisableTracepoints_feature,
2168
2169 /* Support for collecting strings using the tracenz bytecode. */
2170 PACKET_tracenz_feature,
2171
2172 /* Support for continuing to run a trace experiment while GDB is
2173 disconnected. */
2174 PACKET_DisconnectedTracing_feature,
2175
2176 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2177 PACKET_augmented_libraries_svr4_read_feature,
2178
2179 /* Support for the qXfer:btrace-conf:read packet. */
2180 PACKET_qXfer_btrace_conf,
2181
2182 /* Support for the Qbtrace-conf:bts:size packet. */
2183 PACKET_Qbtrace_conf_bts_size,
2184
2185 /* Support for swbreak+ feature. */
2186 PACKET_swbreak_feature,
2187
2188 /* Support for hwbreak+ feature. */
2189 PACKET_hwbreak_feature,
2190
2191 /* Support for fork events. */
2192 PACKET_fork_event_feature,
2193
2194 /* Support for vfork events. */
2195 PACKET_vfork_event_feature,
2196
2197 /* Support for the Qbtrace-conf:pt:size packet. */
2198 PACKET_Qbtrace_conf_pt_size,
2199
2200 /* Support for exec events. */
2201 PACKET_exec_event_feature,
2202
2203 /* Support for query supported vCont actions. */
2204 PACKET_vContSupported,
2205
2206 /* Support remote CTRL-C. */
2207 PACKET_vCtrlC,
2208
2209 /* Support TARGET_WAITKIND_NO_RESUMED. */
2210 PACKET_no_resumed,
2211
2212 /* Support for memory tagging, allocation tag fetch/store
2213 packets and the tag violation stop replies. */
2214 PACKET_memory_tagging_feature,
2215
2216 PACKET_MAX
2217 };
2218
2219 /* FIXME: needs to be per-remote-target. Ignoring this for now,
2220 assuming all remote targets are the same server (thus all support
2221 the same packets). */
2222 static struct packet_config remote_protocol_packets[PACKET_MAX];
2223
2224 /* Returns the packet's corresponding "set remote foo-packet" command
2225 state. See struct packet_config for more details. */
2226
2227 static enum auto_boolean
2228 packet_set_cmd_state (int packet)
2229 {
2230 return remote_protocol_packets[packet].detect;
2231 }
2232
2233 /* Returns whether a given packet or feature is supported. This takes
2234 into account the state of the corresponding "set remote foo-packet"
2235 command, which may be used to bypass auto-detection. */
2236
2237 static enum packet_support
2238 packet_config_support (struct packet_config *config)
2239 {
2240 switch (config->detect)
2241 {
2242 case AUTO_BOOLEAN_TRUE:
2243 return PACKET_ENABLE;
2244 case AUTO_BOOLEAN_FALSE:
2245 return PACKET_DISABLE;
2246 case AUTO_BOOLEAN_AUTO:
2247 return config->support;
2248 default:
2249 gdb_assert_not_reached ("bad switch");
2250 }
2251 }
2252
2253 /* Same as packet_config_support, but takes the packet's enum value as
2254 argument. */
2255
2256 static enum packet_support
2257 packet_support (int packet)
2258 {
2259 struct packet_config *config = &remote_protocol_packets[packet];
2260
2261 return packet_config_support (config);
2262 }
2263
2264 static void
2265 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2266 struct cmd_list_element *c,
2267 const char *value)
2268 {
2269 struct packet_config *packet;
2270 gdb_assert (c->var.has_value ());
2271
2272 for (packet = remote_protocol_packets;
2273 packet < &remote_protocol_packets[PACKET_MAX];
2274 packet++)
2275 {
2276 if (c == packet->show_cmd)
2277 {
2278 show_packet_config_cmd (file, packet);
2279 return;
2280 }
2281 }
2282 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
2283 c->name);
2284 }
2285
2286 /* Should we try one of the 'Z' requests? */
2287
2288 enum Z_packet_type
2289 {
2290 Z_PACKET_SOFTWARE_BP,
2291 Z_PACKET_HARDWARE_BP,
2292 Z_PACKET_WRITE_WP,
2293 Z_PACKET_READ_WP,
2294 Z_PACKET_ACCESS_WP,
2295 NR_Z_PACKET_TYPES
2296 };
2297
2298 /* For compatibility with older distributions. Provide a ``set remote
2299 Z-packet ...'' command that updates all the Z packet types. */
2300
2301 static enum auto_boolean remote_Z_packet_detect;
2302
2303 static void
2304 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2305 struct cmd_list_element *c)
2306 {
2307 int i;
2308
2309 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2310 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2311 }
2312
2313 static void
2314 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2315 struct cmd_list_element *c,
2316 const char *value)
2317 {
2318 int i;
2319
2320 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2321 {
2322 show_packet_config_cmd (file, &remote_protocol_packets[PACKET_Z0 + i]);
2323 }
2324 }
2325
2326 /* Returns true if the multi-process extensions are in effect. */
2327
2328 static int
2329 remote_multi_process_p (struct remote_state *rs)
2330 {
2331 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2332 }
2333
2334 /* Returns true if fork events are supported. */
2335
2336 static int
2337 remote_fork_event_p (struct remote_state *rs)
2338 {
2339 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2340 }
2341
2342 /* Returns true if vfork events are supported. */
2343
2344 static int
2345 remote_vfork_event_p (struct remote_state *rs)
2346 {
2347 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2348 }
2349
2350 /* Returns true if exec events are supported. */
2351
2352 static int
2353 remote_exec_event_p (struct remote_state *rs)
2354 {
2355 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2356 }
2357
2358 /* Returns true if memory tagging is supported, false otherwise. */
2359
2360 static bool
2361 remote_memory_tagging_p ()
2362 {
2363 return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE;
2364 }
2365
2366 /* Insert fork catchpoint target routine. If fork events are enabled
2367 then return success, nothing more to do. */
2368
2369 int
2370 remote_target::insert_fork_catchpoint (int pid)
2371 {
2372 struct remote_state *rs = get_remote_state ();
2373
2374 return !remote_fork_event_p (rs);
2375 }
2376
2377 /* Remove fork catchpoint target routine. Nothing to do, just
2378 return success. */
2379
2380 int
2381 remote_target::remove_fork_catchpoint (int pid)
2382 {
2383 return 0;
2384 }
2385
2386 /* Insert vfork catchpoint target routine. If vfork events are enabled
2387 then return success, nothing more to do. */
2388
2389 int
2390 remote_target::insert_vfork_catchpoint (int pid)
2391 {
2392 struct remote_state *rs = get_remote_state ();
2393
2394 return !remote_vfork_event_p (rs);
2395 }
2396
2397 /* Remove vfork catchpoint target routine. Nothing to do, just
2398 return success. */
2399
2400 int
2401 remote_target::remove_vfork_catchpoint (int pid)
2402 {
2403 return 0;
2404 }
2405
2406 /* Insert exec catchpoint target routine. If exec events are
2407 enabled, just return success. */
2408
2409 int
2410 remote_target::insert_exec_catchpoint (int pid)
2411 {
2412 struct remote_state *rs = get_remote_state ();
2413
2414 return !remote_exec_event_p (rs);
2415 }
2416
2417 /* Remove exec catchpoint target routine. Nothing to do, just
2418 return success. */
2419
2420 int
2421 remote_target::remove_exec_catchpoint (int pid)
2422 {
2423 return 0;
2424 }
2425
2426 \f
2427
2428 /* Take advantage of the fact that the TID field is not used, to tag
2429 special ptids with it set to != 0. */
2430 static const ptid_t magic_null_ptid (42000, -1, 1);
2431 static const ptid_t not_sent_ptid (42000, -2, 1);
2432 static const ptid_t any_thread_ptid (42000, 0, 1);
2433
2434 /* Find out if the stub attached to PID (and hence GDB should offer to
2435 detach instead of killing it when bailing out). */
2436
2437 int
2438 remote_target::remote_query_attached (int pid)
2439 {
2440 struct remote_state *rs = get_remote_state ();
2441 size_t size = get_remote_packet_size ();
2442
2443 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2444 return 0;
2445
2446 if (remote_multi_process_p (rs))
2447 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2448 else
2449 xsnprintf (rs->buf.data (), size, "qAttached");
2450
2451 putpkt (rs->buf);
2452 getpkt (&rs->buf, 0);
2453
2454 switch (packet_ok (rs->buf,
2455 &remote_protocol_packets[PACKET_qAttached]))
2456 {
2457 case PACKET_OK:
2458 if (strcmp (rs->buf.data (), "1") == 0)
2459 return 1;
2460 break;
2461 case PACKET_ERROR:
2462 warning (_("Remote failure reply: %s"), rs->buf.data ());
2463 break;
2464 case PACKET_UNKNOWN:
2465 break;
2466 }
2467
2468 return 0;
2469 }
2470
2471 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2472 has been invented by GDB, instead of reported by the target. Since
2473 we can be connected to a remote system before before knowing about
2474 any inferior, mark the target with execution when we find the first
2475 inferior. If ATTACHED is 1, then we had just attached to this
2476 inferior. If it is 0, then we just created this inferior. If it
2477 is -1, then try querying the remote stub to find out if it had
2478 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2479 attempt to open this inferior's executable as the main executable
2480 if no main executable is open already. */
2481
2482 inferior *
2483 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2484 int try_open_exec)
2485 {
2486 struct inferior *inf;
2487
2488 /* Check whether this process we're learning about is to be
2489 considered attached, or if is to be considered to have been
2490 spawned by the stub. */
2491 if (attached == -1)
2492 attached = remote_query_attached (pid);
2493
2494 if (gdbarch_has_global_solist (target_gdbarch ()))
2495 {
2496 /* If the target shares code across all inferiors, then every
2497 attach adds a new inferior. */
2498 inf = add_inferior (pid);
2499
2500 /* ... and every inferior is bound to the same program space.
2501 However, each inferior may still have its own address
2502 space. */
2503 inf->aspace = maybe_new_address_space ();
2504 inf->pspace = current_program_space;
2505 }
2506 else
2507 {
2508 /* In the traditional debugging scenario, there's a 1-1 match
2509 between program/address spaces. We simply bind the inferior
2510 to the program space's address space. */
2511 inf = current_inferior ();
2512
2513 /* However, if the current inferior is already bound to a
2514 process, find some other empty inferior. */
2515 if (inf->pid != 0)
2516 {
2517 inf = nullptr;
2518 for (inferior *it : all_inferiors ())
2519 if (it->pid == 0)
2520 {
2521 inf = it;
2522 break;
2523 }
2524 }
2525 if (inf == nullptr)
2526 {
2527 /* Since all inferiors were already bound to a process, add
2528 a new inferior. */
2529 inf = add_inferior_with_spaces ();
2530 }
2531 switch_to_inferior_no_thread (inf);
2532 inf->push_target (this);
2533 inferior_appeared (inf, pid);
2534 }
2535
2536 inf->attach_flag = attached;
2537 inf->fake_pid_p = fake_pid_p;
2538
2539 /* If no main executable is currently open then attempt to
2540 open the file that was executed to create this inferior. */
2541 if (try_open_exec && get_exec_file (0) == NULL)
2542 exec_file_locate_attach (pid, 0, 1);
2543
2544 /* Check for exec file mismatch, and let the user solve it. */
2545 validate_exec_file (1);
2546
2547 return inf;
2548 }
2549
2550 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2551 static remote_thread_info *get_remote_thread_info (remote_target *target,
2552 ptid_t ptid);
2553
2554 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2555 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2556 remote_state::starting_up flag) is true then the new thread is added
2557 silently, otherwise the new thread will be announced to the user. */
2558
2559 thread_info *
2560 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2561 bool silent_p)
2562 {
2563 struct remote_state *rs = get_remote_state ();
2564 struct thread_info *thread;
2565
2566 /* GDB historically didn't pull threads in the initial connection
2567 setup. If the remote target doesn't even have a concept of
2568 threads (e.g., a bare-metal target), even if internally we
2569 consider that a single-threaded target, mentioning a new thread
2570 might be confusing to the user. Be silent then, preserving the
2571 age old behavior. */
2572 if (rs->starting_up || silent_p)
2573 thread = add_thread_silent (this, ptid);
2574 else
2575 thread = add_thread (this, ptid);
2576
2577 /* We start by assuming threads are resumed. That state then gets updated
2578 when we process a matching stop reply. */
2579 get_remote_thread_info (thread)->set_resumed ();
2580
2581 set_executing (this, ptid, executing);
2582 set_running (this, ptid, running);
2583
2584 return thread;
2585 }
2586
2587 /* Come here when we learn about a thread id from the remote target.
2588 It may be the first time we hear about such thread, so take the
2589 opportunity to add it to GDB's thread list. In case this is the
2590 first time we're noticing its corresponding inferior, add it to
2591 GDB's inferior list as well. EXECUTING indicates whether the
2592 thread is (internally) executing or stopped. */
2593
2594 void
2595 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2596 {
2597 /* In non-stop mode, we assume new found threads are (externally)
2598 running until proven otherwise with a stop reply. In all-stop,
2599 we can only get here if all threads are stopped. */
2600 bool running = target_is_non_stop_p ();
2601
2602 /* If this is a new thread, add it to GDB's thread list.
2603 If we leave it up to WFI to do this, bad things will happen. */
2604
2605 thread_info *tp = find_thread_ptid (this, currthread);
2606 if (tp != NULL && tp->state == THREAD_EXITED)
2607 {
2608 /* We're seeing an event on a thread id we knew had exited.
2609 This has to be a new thread reusing the old id. Add it. */
2610 remote_add_thread (currthread, running, executing, false);
2611 return;
2612 }
2613
2614 if (!in_thread_list (this, currthread))
2615 {
2616 struct inferior *inf = NULL;
2617 int pid = currthread.pid ();
2618
2619 if (inferior_ptid.is_pid ()
2620 && pid == inferior_ptid.pid ())
2621 {
2622 /* inferior_ptid has no thread member yet. This can happen
2623 with the vAttach -> remote_wait,"TAAthread:" path if the
2624 stub doesn't support qC. This is the first stop reported
2625 after an attach, so this is the main thread. Update the
2626 ptid in the thread list. */
2627 if (in_thread_list (this, ptid_t (pid)))
2628 thread_change_ptid (this, inferior_ptid, currthread);
2629 else
2630 {
2631 thread_info *thr
2632 = remote_add_thread (currthread, running, executing, false);
2633 switch_to_thread (thr);
2634 }
2635 return;
2636 }
2637
2638 if (magic_null_ptid == inferior_ptid)
2639 {
2640 /* inferior_ptid is not set yet. This can happen with the
2641 vRun -> remote_wait,"TAAthread:" path if the stub
2642 doesn't support qC. This is the first stop reported
2643 after an attach, so this is the main thread. Update the
2644 ptid in the thread list. */
2645 thread_change_ptid (this, inferior_ptid, currthread);
2646 return;
2647 }
2648
2649 /* When connecting to a target remote, or to a target
2650 extended-remote which already was debugging an inferior, we
2651 may not know about it yet. Add it before adding its child
2652 thread, so notifications are emitted in a sensible order. */
2653 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2654 {
2655 struct remote_state *rs = get_remote_state ();
2656 bool fake_pid_p = !remote_multi_process_p (rs);
2657
2658 inf = remote_add_inferior (fake_pid_p,
2659 currthread.pid (), -1, 1);
2660 }
2661
2662 /* This is really a new thread. Add it. */
2663 thread_info *new_thr
2664 = remote_add_thread (currthread, running, executing, false);
2665
2666 /* If we found a new inferior, let the common code do whatever
2667 it needs to with it (e.g., read shared libraries, insert
2668 breakpoints), unless we're just setting up an all-stop
2669 connection. */
2670 if (inf != NULL)
2671 {
2672 struct remote_state *rs = get_remote_state ();
2673
2674 if (!rs->starting_up)
2675 notice_new_inferior (new_thr, executing, 0);
2676 }
2677 }
2678 }
2679
2680 /* Return THREAD's private thread data, creating it if necessary. */
2681
2682 static remote_thread_info *
2683 get_remote_thread_info (thread_info *thread)
2684 {
2685 gdb_assert (thread != NULL);
2686
2687 if (thread->priv == NULL)
2688 thread->priv.reset (new remote_thread_info);
2689
2690 return static_cast<remote_thread_info *> (thread->priv.get ());
2691 }
2692
2693 /* Return PTID's private thread data, creating it if necessary. */
2694
2695 static remote_thread_info *
2696 get_remote_thread_info (remote_target *target, ptid_t ptid)
2697 {
2698 thread_info *thr = find_thread_ptid (target, ptid);
2699 return get_remote_thread_info (thr);
2700 }
2701
2702 /* Call this function as a result of
2703 1) A halt indication (T packet) containing a thread id
2704 2) A direct query of currthread
2705 3) Successful execution of set thread */
2706
2707 static void
2708 record_currthread (struct remote_state *rs, ptid_t currthread)
2709 {
2710 rs->general_thread = currthread;
2711 }
2712
2713 /* If 'QPassSignals' is supported, tell the remote stub what signals
2714 it can simply pass through to the inferior without reporting. */
2715
2716 void
2717 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2718 {
2719 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2720 {
2721 char *pass_packet, *p;
2722 int count = 0;
2723 struct remote_state *rs = get_remote_state ();
2724
2725 gdb_assert (pass_signals.size () < 256);
2726 for (size_t i = 0; i < pass_signals.size (); i++)
2727 {
2728 if (pass_signals[i])
2729 count++;
2730 }
2731 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2732 strcpy (pass_packet, "QPassSignals:");
2733 p = pass_packet + strlen (pass_packet);
2734 for (size_t i = 0; i < pass_signals.size (); i++)
2735 {
2736 if (pass_signals[i])
2737 {
2738 if (i >= 16)
2739 *p++ = tohex (i >> 4);
2740 *p++ = tohex (i & 15);
2741 if (count)
2742 *p++ = ';';
2743 else
2744 break;
2745 count--;
2746 }
2747 }
2748 *p = 0;
2749 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2750 {
2751 putpkt (pass_packet);
2752 getpkt (&rs->buf, 0);
2753 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2754 xfree (rs->last_pass_packet);
2755 rs->last_pass_packet = pass_packet;
2756 }
2757 else
2758 xfree (pass_packet);
2759 }
2760 }
2761
2762 /* If 'QCatchSyscalls' is supported, tell the remote stub
2763 to report syscalls to GDB. */
2764
2765 int
2766 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2767 gdb::array_view<const int> syscall_counts)
2768 {
2769 const char *catch_packet;
2770 enum packet_result result;
2771 int n_sysno = 0;
2772
2773 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2774 {
2775 /* Not supported. */
2776 return 1;
2777 }
2778
2779 if (needed && any_count == 0)
2780 {
2781 /* Count how many syscalls are to be caught. */
2782 for (size_t i = 0; i < syscall_counts.size (); i++)
2783 {
2784 if (syscall_counts[i] != 0)
2785 n_sysno++;
2786 }
2787 }
2788
2789 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
2790 pid, needed, any_count, n_sysno);
2791
2792 std::string built_packet;
2793 if (needed)
2794 {
2795 /* Prepare a packet with the sysno list, assuming max 8+1
2796 characters for a sysno. If the resulting packet size is too
2797 big, fallback on the non-selective packet. */
2798 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2799 built_packet.reserve (maxpktsz);
2800 built_packet = "QCatchSyscalls:1";
2801 if (any_count == 0)
2802 {
2803 /* Add in each syscall to be caught. */
2804 for (size_t i = 0; i < syscall_counts.size (); i++)
2805 {
2806 if (syscall_counts[i] != 0)
2807 string_appendf (built_packet, ";%zx", i);
2808 }
2809 }
2810 if (built_packet.size () > get_remote_packet_size ())
2811 {
2812 /* catch_packet too big. Fallback to less efficient
2813 non selective mode, with GDB doing the filtering. */
2814 catch_packet = "QCatchSyscalls:1";
2815 }
2816 else
2817 catch_packet = built_packet.c_str ();
2818 }
2819 else
2820 catch_packet = "QCatchSyscalls:0";
2821
2822 struct remote_state *rs = get_remote_state ();
2823
2824 putpkt (catch_packet);
2825 getpkt (&rs->buf, 0);
2826 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2827 if (result == PACKET_OK)
2828 return 0;
2829 else
2830 return -1;
2831 }
2832
2833 /* If 'QProgramSignals' is supported, tell the remote stub what
2834 signals it should pass through to the inferior when detaching. */
2835
2836 void
2837 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
2838 {
2839 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2840 {
2841 char *packet, *p;
2842 int count = 0;
2843 struct remote_state *rs = get_remote_state ();
2844
2845 gdb_assert (signals.size () < 256);
2846 for (size_t i = 0; i < signals.size (); i++)
2847 {
2848 if (signals[i])
2849 count++;
2850 }
2851 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2852 strcpy (packet, "QProgramSignals:");
2853 p = packet + strlen (packet);
2854 for (size_t i = 0; i < signals.size (); i++)
2855 {
2856 if (signal_pass_state (i))
2857 {
2858 if (i >= 16)
2859 *p++ = tohex (i >> 4);
2860 *p++ = tohex (i & 15);
2861 if (count)
2862 *p++ = ';';
2863 else
2864 break;
2865 count--;
2866 }
2867 }
2868 *p = 0;
2869 if (!rs->last_program_signals_packet
2870 || strcmp (rs->last_program_signals_packet, packet) != 0)
2871 {
2872 putpkt (packet);
2873 getpkt (&rs->buf, 0);
2874 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2875 xfree (rs->last_program_signals_packet);
2876 rs->last_program_signals_packet = packet;
2877 }
2878 else
2879 xfree (packet);
2880 }
2881 }
2882
2883 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2884 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2885 thread. If GEN is set, set the general thread, if not, then set
2886 the step/continue thread. */
2887 void
2888 remote_target::set_thread (ptid_t ptid, int gen)
2889 {
2890 struct remote_state *rs = get_remote_state ();
2891 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2892 char *buf = rs->buf.data ();
2893 char *endbuf = buf + get_remote_packet_size ();
2894
2895 if (state == ptid)
2896 return;
2897
2898 *buf++ = 'H';
2899 *buf++ = gen ? 'g' : 'c';
2900 if (ptid == magic_null_ptid)
2901 xsnprintf (buf, endbuf - buf, "0");
2902 else if (ptid == any_thread_ptid)
2903 xsnprintf (buf, endbuf - buf, "0");
2904 else if (ptid == minus_one_ptid)
2905 xsnprintf (buf, endbuf - buf, "-1");
2906 else
2907 write_ptid (buf, endbuf, ptid);
2908 putpkt (rs->buf);
2909 getpkt (&rs->buf, 0);
2910 if (gen)
2911 rs->general_thread = ptid;
2912 else
2913 rs->continue_thread = ptid;
2914 }
2915
2916 void
2917 remote_target::set_general_thread (ptid_t ptid)
2918 {
2919 set_thread (ptid, 1);
2920 }
2921
2922 void
2923 remote_target::set_continue_thread (ptid_t ptid)
2924 {
2925 set_thread (ptid, 0);
2926 }
2927
2928 /* Change the remote current process. Which thread within the process
2929 ends up selected isn't important, as long as it is the same process
2930 as what INFERIOR_PTID points to.
2931
2932 This comes from that fact that there is no explicit notion of
2933 "selected process" in the protocol. The selected process for
2934 general operations is the process the selected general thread
2935 belongs to. */
2936
2937 void
2938 remote_target::set_general_process ()
2939 {
2940 struct remote_state *rs = get_remote_state ();
2941
2942 /* If the remote can't handle multiple processes, don't bother. */
2943 if (!remote_multi_process_p (rs))
2944 return;
2945
2946 /* We only need to change the remote current thread if it's pointing
2947 at some other process. */
2948 if (rs->general_thread.pid () != inferior_ptid.pid ())
2949 set_general_thread (inferior_ptid);
2950 }
2951
2952 \f
2953 /* Return nonzero if this is the main thread that we made up ourselves
2954 to model non-threaded targets as single-threaded. */
2955
2956 static int
2957 remote_thread_always_alive (ptid_t ptid)
2958 {
2959 if (ptid == magic_null_ptid)
2960 /* The main thread is always alive. */
2961 return 1;
2962
2963 if (ptid.pid () != 0 && ptid.lwp () == 0)
2964 /* The main thread is always alive. This can happen after a
2965 vAttach, if the remote side doesn't support
2966 multi-threading. */
2967 return 1;
2968
2969 return 0;
2970 }
2971
2972 /* Return nonzero if the thread PTID is still alive on the remote
2973 system. */
2974
2975 bool
2976 remote_target::thread_alive (ptid_t ptid)
2977 {
2978 struct remote_state *rs = get_remote_state ();
2979 char *p, *endp;
2980
2981 /* Check if this is a thread that we made up ourselves to model
2982 non-threaded targets as single-threaded. */
2983 if (remote_thread_always_alive (ptid))
2984 return 1;
2985
2986 p = rs->buf.data ();
2987 endp = p + get_remote_packet_size ();
2988
2989 *p++ = 'T';
2990 write_ptid (p, endp, ptid);
2991
2992 putpkt (rs->buf);
2993 getpkt (&rs->buf, 0);
2994 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2995 }
2996
2997 /* Return a pointer to a thread name if we know it and NULL otherwise.
2998 The thread_info object owns the memory for the name. */
2999
3000 const char *
3001 remote_target::thread_name (struct thread_info *info)
3002 {
3003 if (info->priv != NULL)
3004 {
3005 const std::string &name = get_remote_thread_info (info)->name;
3006 return !name.empty () ? name.c_str () : NULL;
3007 }
3008
3009 return NULL;
3010 }
3011
3012 /* About these extended threadlist and threadinfo packets. They are
3013 variable length packets but, the fields within them are often fixed
3014 length. They are redundant enough to send over UDP as is the
3015 remote protocol in general. There is a matching unit test module
3016 in libstub. */
3017
3018 /* WARNING: This threadref data structure comes from the remote O.S.,
3019 libstub protocol encoding, and remote.c. It is not particularly
3020 changable. */
3021
3022 /* Right now, the internal structure is int. We want it to be bigger.
3023 Plan to fix this. */
3024
3025 typedef int gdb_threadref; /* Internal GDB thread reference. */
3026
3027 /* gdb_ext_thread_info is an internal GDB data structure which is
3028 equivalent to the reply of the remote threadinfo packet. */
3029
3030 struct gdb_ext_thread_info
3031 {
3032 threadref threadid; /* External form of thread reference. */
3033 int active; /* Has state interesting to GDB?
3034 regs, stack. */
3035 char display[256]; /* Brief state display, name,
3036 blocked/suspended. */
3037 char shortname[32]; /* To be used to name threads. */
3038 char more_display[256]; /* Long info, statistics, queue depth,
3039 whatever. */
3040 };
3041
3042 /* The volume of remote transfers can be limited by submitting
3043 a mask containing bits specifying the desired information.
3044 Use a union of these values as the 'selection' parameter to
3045 get_thread_info. FIXME: Make these TAG names more thread specific. */
3046
3047 #define TAG_THREADID 1
3048 #define TAG_EXISTS 2
3049 #define TAG_DISPLAY 4
3050 #define TAG_THREADNAME 8
3051 #define TAG_MOREDISPLAY 16
3052
3053 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3054
3055 static const char *unpack_nibble (const char *buf, int *val);
3056
3057 static const char *unpack_byte (const char *buf, int *value);
3058
3059 static char *pack_int (char *buf, int value);
3060
3061 static const char *unpack_int (const char *buf, int *value);
3062
3063 static const char *unpack_string (const char *src, char *dest, int length);
3064
3065 static char *pack_threadid (char *pkt, threadref *id);
3066
3067 static const char *unpack_threadid (const char *inbuf, threadref *id);
3068
3069 void int_to_threadref (threadref *id, int value);
3070
3071 static int threadref_to_int (threadref *ref);
3072
3073 static void copy_threadref (threadref *dest, threadref *src);
3074
3075 static int threadmatch (threadref *dest, threadref *src);
3076
3077 static char *pack_threadinfo_request (char *pkt, int mode,
3078 threadref *id);
3079
3080 static char *pack_threadlist_request (char *pkt, int startflag,
3081 int threadcount,
3082 threadref *nextthread);
3083
3084 static int remote_newthread_step (threadref *ref, void *context);
3085
3086
3087 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3088 buffer we're allowed to write to. Returns
3089 BUF+CHARACTERS_WRITTEN. */
3090
3091 char *
3092 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3093 {
3094 int pid, tid;
3095 struct remote_state *rs = get_remote_state ();
3096
3097 if (remote_multi_process_p (rs))
3098 {
3099 pid = ptid.pid ();
3100 if (pid < 0)
3101 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3102 else
3103 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3104 }
3105 tid = ptid.lwp ();
3106 if (tid < 0)
3107 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3108 else
3109 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3110
3111 return buf;
3112 }
3113
3114 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3115 last parsed char. Returns null_ptid if no thread id is found, and
3116 throws an error if the thread id has an invalid format. */
3117
3118 static ptid_t
3119 read_ptid (const char *buf, const char **obuf)
3120 {
3121 const char *p = buf;
3122 const char *pp;
3123 ULONGEST pid = 0, tid = 0;
3124
3125 if (*p == 'p')
3126 {
3127 /* Multi-process ptid. */
3128 pp = unpack_varlen_hex (p + 1, &pid);
3129 if (*pp != '.')
3130 error (_("invalid remote ptid: %s"), p);
3131
3132 p = pp;
3133 pp = unpack_varlen_hex (p + 1, &tid);
3134 if (obuf)
3135 *obuf = pp;
3136 return ptid_t (pid, tid);
3137 }
3138
3139 /* No multi-process. Just a tid. */
3140 pp = unpack_varlen_hex (p, &tid);
3141
3142 /* Return null_ptid when no thread id is found. */
3143 if (p == pp)
3144 {
3145 if (obuf)
3146 *obuf = pp;
3147 return null_ptid;
3148 }
3149
3150 /* Since the stub is not sending a process id, default to what's
3151 current_inferior, unless it doesn't have a PID yet. If so,
3152 then since there's no way to know the pid of the reported
3153 threads, use the magic number. */
3154 inferior *inf = current_inferior ();
3155 if (inf->pid == 0)
3156 pid = magic_null_ptid.pid ();
3157 else
3158 pid = inf->pid;
3159
3160 if (obuf)
3161 *obuf = pp;
3162 return ptid_t (pid, tid);
3163 }
3164
3165 static int
3166 stubhex (int ch)
3167 {
3168 if (ch >= 'a' && ch <= 'f')
3169 return ch - 'a' + 10;
3170 if (ch >= '0' && ch <= '9')
3171 return ch - '0';
3172 if (ch >= 'A' && ch <= 'F')
3173 return ch - 'A' + 10;
3174 return -1;
3175 }
3176
3177 static int
3178 stub_unpack_int (const char *buff, int fieldlength)
3179 {
3180 int nibble;
3181 int retval = 0;
3182
3183 while (fieldlength)
3184 {
3185 nibble = stubhex (*buff++);
3186 retval |= nibble;
3187 fieldlength--;
3188 if (fieldlength)
3189 retval = retval << 4;
3190 }
3191 return retval;
3192 }
3193
3194 static const char *
3195 unpack_nibble (const char *buf, int *val)
3196 {
3197 *val = fromhex (*buf++);
3198 return buf;
3199 }
3200
3201 static const char *
3202 unpack_byte (const char *buf, int *value)
3203 {
3204 *value = stub_unpack_int (buf, 2);
3205 return buf + 2;
3206 }
3207
3208 static char *
3209 pack_int (char *buf, int value)
3210 {
3211 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3212 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3213 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3214 buf = pack_hex_byte (buf, (value & 0xff));
3215 return buf;
3216 }
3217
3218 static const char *
3219 unpack_int (const char *buf, int *value)
3220 {
3221 *value = stub_unpack_int (buf, 8);
3222 return buf + 8;
3223 }
3224
3225 #if 0 /* Currently unused, uncomment when needed. */
3226 static char *pack_string (char *pkt, char *string);
3227
3228 static char *
3229 pack_string (char *pkt, char *string)
3230 {
3231 char ch;
3232 int len;
3233
3234 len = strlen (string);
3235 if (len > 200)
3236 len = 200; /* Bigger than most GDB packets, junk??? */
3237 pkt = pack_hex_byte (pkt, len);
3238 while (len-- > 0)
3239 {
3240 ch = *string++;
3241 if ((ch == '\0') || (ch == '#'))
3242 ch = '*'; /* Protect encapsulation. */
3243 *pkt++ = ch;
3244 }
3245 return pkt;
3246 }
3247 #endif /* 0 (unused) */
3248
3249 static const char *
3250 unpack_string (const char *src, char *dest, int length)
3251 {
3252 while (length--)
3253 *dest++ = *src++;
3254 *dest = '\0';
3255 return src;
3256 }
3257
3258 static char *
3259 pack_threadid (char *pkt, threadref *id)
3260 {
3261 char *limit;
3262 unsigned char *altid;
3263
3264 altid = (unsigned char *) id;
3265 limit = pkt + BUF_THREAD_ID_SIZE;
3266 while (pkt < limit)
3267 pkt = pack_hex_byte (pkt, *altid++);
3268 return pkt;
3269 }
3270
3271
3272 static const char *
3273 unpack_threadid (const char *inbuf, threadref *id)
3274 {
3275 char *altref;
3276 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3277 int x, y;
3278
3279 altref = (char *) id;
3280
3281 while (inbuf < limit)
3282 {
3283 x = stubhex (*inbuf++);
3284 y = stubhex (*inbuf++);
3285 *altref++ = (x << 4) | y;
3286 }
3287 return inbuf;
3288 }
3289
3290 /* Externally, threadrefs are 64 bits but internally, they are still
3291 ints. This is due to a mismatch of specifications. We would like
3292 to use 64bit thread references internally. This is an adapter
3293 function. */
3294
3295 void
3296 int_to_threadref (threadref *id, int value)
3297 {
3298 unsigned char *scan;
3299
3300 scan = (unsigned char *) id;
3301 {
3302 int i = 4;
3303 while (i--)
3304 *scan++ = 0;
3305 }
3306 *scan++ = (value >> 24) & 0xff;
3307 *scan++ = (value >> 16) & 0xff;
3308 *scan++ = (value >> 8) & 0xff;
3309 *scan++ = (value & 0xff);
3310 }
3311
3312 static int
3313 threadref_to_int (threadref *ref)
3314 {
3315 int i, value = 0;
3316 unsigned char *scan;
3317
3318 scan = *ref;
3319 scan += 4;
3320 i = 4;
3321 while (i-- > 0)
3322 value = (value << 8) | ((*scan++) & 0xff);
3323 return value;
3324 }
3325
3326 static void
3327 copy_threadref (threadref *dest, threadref *src)
3328 {
3329 int i;
3330 unsigned char *csrc, *cdest;
3331
3332 csrc = (unsigned char *) src;
3333 cdest = (unsigned char *) dest;
3334 i = 8;
3335 while (i--)
3336 *cdest++ = *csrc++;
3337 }
3338
3339 static int
3340 threadmatch (threadref *dest, threadref *src)
3341 {
3342 /* Things are broken right now, so just assume we got a match. */
3343 #if 0
3344 unsigned char *srcp, *destp;
3345 int i, result;
3346 srcp = (char *) src;
3347 destp = (char *) dest;
3348
3349 result = 1;
3350 while (i-- > 0)
3351 result &= (*srcp++ == *destp++) ? 1 : 0;
3352 return result;
3353 #endif
3354 return 1;
3355 }
3356
3357 /*
3358 threadid:1, # always request threadid
3359 context_exists:2,
3360 display:4,
3361 unique_name:8,
3362 more_display:16
3363 */
3364
3365 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3366
3367 static char *
3368 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3369 {
3370 *pkt++ = 'q'; /* Info Query */
3371 *pkt++ = 'P'; /* process or thread info */
3372 pkt = pack_int (pkt, mode); /* mode */
3373 pkt = pack_threadid (pkt, id); /* threadid */
3374 *pkt = '\0'; /* terminate */
3375 return pkt;
3376 }
3377
3378 /* These values tag the fields in a thread info response packet. */
3379 /* Tagging the fields allows us to request specific fields and to
3380 add more fields as time goes by. */
3381
3382 #define TAG_THREADID 1 /* Echo the thread identifier. */
3383 #define TAG_EXISTS 2 /* Is this process defined enough to
3384 fetch registers and its stack? */
3385 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3386 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3387 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3388 the process. */
3389
3390 int
3391 remote_target::remote_unpack_thread_info_response (const char *pkt,
3392 threadref *expectedref,
3393 gdb_ext_thread_info *info)
3394 {
3395 struct remote_state *rs = get_remote_state ();
3396 int mask, length;
3397 int tag;
3398 threadref ref;
3399 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3400 int retval = 1;
3401
3402 /* info->threadid = 0; FIXME: implement zero_threadref. */
3403 info->active = 0;
3404 info->display[0] = '\0';
3405 info->shortname[0] = '\0';
3406 info->more_display[0] = '\0';
3407
3408 /* Assume the characters indicating the packet type have been
3409 stripped. */
3410 pkt = unpack_int (pkt, &mask); /* arg mask */
3411 pkt = unpack_threadid (pkt, &ref);
3412
3413 if (mask == 0)
3414 warning (_("Incomplete response to threadinfo request."));
3415 if (!threadmatch (&ref, expectedref))
3416 { /* This is an answer to a different request. */
3417 warning (_("ERROR RMT Thread info mismatch."));
3418 return 0;
3419 }
3420 copy_threadref (&info->threadid, &ref);
3421
3422 /* Loop on tagged fields , try to bail if something goes wrong. */
3423
3424 /* Packets are terminated with nulls. */
3425 while ((pkt < limit) && mask && *pkt)
3426 {
3427 pkt = unpack_int (pkt, &tag); /* tag */
3428 pkt = unpack_byte (pkt, &length); /* length */
3429 if (!(tag & mask)) /* Tags out of synch with mask. */
3430 {
3431 warning (_("ERROR RMT: threadinfo tag mismatch."));
3432 retval = 0;
3433 break;
3434 }
3435 if (tag == TAG_THREADID)
3436 {
3437 if (length != 16)
3438 {
3439 warning (_("ERROR RMT: length of threadid is not 16."));
3440 retval = 0;
3441 break;
3442 }
3443 pkt = unpack_threadid (pkt, &ref);
3444 mask = mask & ~TAG_THREADID;
3445 continue;
3446 }
3447 if (tag == TAG_EXISTS)
3448 {
3449 info->active = stub_unpack_int (pkt, length);
3450 pkt += length;
3451 mask = mask & ~(TAG_EXISTS);
3452 if (length > 8)
3453 {
3454 warning (_("ERROR RMT: 'exists' length too long."));
3455 retval = 0;
3456 break;
3457 }
3458 continue;
3459 }
3460 if (tag == TAG_THREADNAME)
3461 {
3462 pkt = unpack_string (pkt, &info->shortname[0], length);
3463 mask = mask & ~TAG_THREADNAME;
3464 continue;
3465 }
3466 if (tag == TAG_DISPLAY)
3467 {
3468 pkt = unpack_string (pkt, &info->display[0], length);
3469 mask = mask & ~TAG_DISPLAY;
3470 continue;
3471 }
3472 if (tag == TAG_MOREDISPLAY)
3473 {
3474 pkt = unpack_string (pkt, &info->more_display[0], length);
3475 mask = mask & ~TAG_MOREDISPLAY;
3476 continue;
3477 }
3478 warning (_("ERROR RMT: unknown thread info tag."));
3479 break; /* Not a tag we know about. */
3480 }
3481 return retval;
3482 }
3483
3484 int
3485 remote_target::remote_get_threadinfo (threadref *threadid,
3486 int fieldset,
3487 gdb_ext_thread_info *info)
3488 {
3489 struct remote_state *rs = get_remote_state ();
3490 int result;
3491
3492 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3493 putpkt (rs->buf);
3494 getpkt (&rs->buf, 0);
3495
3496 if (rs->buf[0] == '\0')
3497 return 0;
3498
3499 result = remote_unpack_thread_info_response (&rs->buf[2],
3500 threadid, info);
3501 return result;
3502 }
3503
3504 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3505
3506 static char *
3507 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3508 threadref *nextthread)
3509 {
3510 *pkt++ = 'q'; /* info query packet */
3511 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3512 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3513 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3514 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3515 *pkt = '\0';
3516 return pkt;
3517 }
3518
3519 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3520
3521 int
3522 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3523 threadref *original_echo,
3524 threadref *resultlist,
3525 int *doneflag)
3526 {
3527 struct remote_state *rs = get_remote_state ();
3528 int count, resultcount, done;
3529
3530 resultcount = 0;
3531 /* Assume the 'q' and 'M chars have been stripped. */
3532 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3533 /* done parse past here */
3534 pkt = unpack_byte (pkt, &count); /* count field */
3535 pkt = unpack_nibble (pkt, &done);
3536 /* The first threadid is the argument threadid. */
3537 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3538 while ((count-- > 0) && (pkt < limit))
3539 {
3540 pkt = unpack_threadid (pkt, resultlist++);
3541 if (resultcount++ >= result_limit)
3542 break;
3543 }
3544 if (doneflag)
3545 *doneflag = done;
3546 return resultcount;
3547 }
3548
3549 /* Fetch the next batch of threads from the remote. Returns -1 if the
3550 qL packet is not supported, 0 on error and 1 on success. */
3551
3552 int
3553 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3554 int result_limit, int *done, int *result_count,
3555 threadref *threadlist)
3556 {
3557 struct remote_state *rs = get_remote_state ();
3558 int result = 1;
3559
3560 /* Truncate result limit to be smaller than the packet size. */
3561 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3562 >= get_remote_packet_size ())
3563 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3564
3565 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3566 nextthread);
3567 putpkt (rs->buf);
3568 getpkt (&rs->buf, 0);
3569 if (rs->buf[0] == '\0')
3570 {
3571 /* Packet not supported. */
3572 return -1;
3573 }
3574
3575 *result_count =
3576 parse_threadlist_response (&rs->buf[2], result_limit,
3577 &rs->echo_nextthread, threadlist, done);
3578
3579 if (!threadmatch (&rs->echo_nextthread, nextthread))
3580 {
3581 /* FIXME: This is a good reason to drop the packet. */
3582 /* Possibly, there is a duplicate response. */
3583 /* Possibilities :
3584 retransmit immediatly - race conditions
3585 retransmit after timeout - yes
3586 exit
3587 wait for packet, then exit
3588 */
3589 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3590 return 0; /* I choose simply exiting. */
3591 }
3592 if (*result_count <= 0)
3593 {
3594 if (*done != 1)
3595 {
3596 warning (_("RMT ERROR : failed to get remote thread list."));
3597 result = 0;
3598 }
3599 return result; /* break; */
3600 }
3601 if (*result_count > result_limit)
3602 {
3603 *result_count = 0;
3604 warning (_("RMT ERROR: threadlist response longer than requested."));
3605 return 0;
3606 }
3607 return result;
3608 }
3609
3610 /* Fetch the list of remote threads, with the qL packet, and call
3611 STEPFUNCTION for each thread found. Stops iterating and returns 1
3612 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3613 STEPFUNCTION returns false. If the packet is not supported,
3614 returns -1. */
3615
3616 int
3617 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3618 void *context, int looplimit)
3619 {
3620 struct remote_state *rs = get_remote_state ();
3621 int done, i, result_count;
3622 int startflag = 1;
3623 int result = 1;
3624 int loopcount = 0;
3625
3626 done = 0;
3627 while (!done)
3628 {
3629 if (loopcount++ > looplimit)
3630 {
3631 result = 0;
3632 warning (_("Remote fetch threadlist -infinite loop-."));
3633 break;
3634 }
3635 result = remote_get_threadlist (startflag, &rs->nextthread,
3636 MAXTHREADLISTRESULTS,
3637 &done, &result_count,
3638 rs->resultthreadlist);
3639 if (result <= 0)
3640 break;
3641 /* Clear for later iterations. */
3642 startflag = 0;
3643 /* Setup to resume next batch of thread references, set nextthread. */
3644 if (result_count >= 1)
3645 copy_threadref (&rs->nextthread,
3646 &rs->resultthreadlist[result_count - 1]);
3647 i = 0;
3648 while (result_count--)
3649 {
3650 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3651 {
3652 result = 0;
3653 break;
3654 }
3655 }
3656 }
3657 return result;
3658 }
3659
3660 /* A thread found on the remote target. */
3661
3662 struct thread_item
3663 {
3664 explicit thread_item (ptid_t ptid_)
3665 : ptid (ptid_)
3666 {}
3667
3668 thread_item (thread_item &&other) = default;
3669 thread_item &operator= (thread_item &&other) = default;
3670
3671 DISABLE_COPY_AND_ASSIGN (thread_item);
3672
3673 /* The thread's PTID. */
3674 ptid_t ptid;
3675
3676 /* The thread's extra info. */
3677 std::string extra;
3678
3679 /* The thread's name. */
3680 std::string name;
3681
3682 /* The core the thread was running on. -1 if not known. */
3683 int core = -1;
3684
3685 /* The thread handle associated with the thread. */
3686 gdb::byte_vector thread_handle;
3687 };
3688
3689 /* Context passed around to the various methods listing remote
3690 threads. As new threads are found, they're added to the ITEMS
3691 vector. */
3692
3693 struct threads_listing_context
3694 {
3695 /* Return true if this object contains an entry for a thread with ptid
3696 PTID. */
3697
3698 bool contains_thread (ptid_t ptid) const
3699 {
3700 auto match_ptid = [&] (const thread_item &item)
3701 {
3702 return item.ptid == ptid;
3703 };
3704
3705 auto it = std::find_if (this->items.begin (),
3706 this->items.end (),
3707 match_ptid);
3708
3709 return it != this->items.end ();
3710 }
3711
3712 /* Remove the thread with ptid PTID. */
3713
3714 void remove_thread (ptid_t ptid)
3715 {
3716 auto match_ptid = [&] (const thread_item &item)
3717 {
3718 return item.ptid == ptid;
3719 };
3720
3721 auto it = std::remove_if (this->items.begin (),
3722 this->items.end (),
3723 match_ptid);
3724
3725 if (it != this->items.end ())
3726 this->items.erase (it);
3727 }
3728
3729 /* The threads found on the remote target. */
3730 std::vector<thread_item> items;
3731 };
3732
3733 static int
3734 remote_newthread_step (threadref *ref, void *data)
3735 {
3736 struct threads_listing_context *context
3737 = (struct threads_listing_context *) data;
3738 int pid = inferior_ptid.pid ();
3739 int lwp = threadref_to_int (ref);
3740 ptid_t ptid (pid, lwp);
3741
3742 context->items.emplace_back (ptid);
3743
3744 return 1; /* continue iterator */
3745 }
3746
3747 #define CRAZY_MAX_THREADS 1000
3748
3749 ptid_t
3750 remote_target::remote_current_thread (ptid_t oldpid)
3751 {
3752 struct remote_state *rs = get_remote_state ();
3753
3754 putpkt ("qC");
3755 getpkt (&rs->buf, 0);
3756 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3757 {
3758 const char *obuf;
3759 ptid_t result;
3760
3761 result = read_ptid (&rs->buf[2], &obuf);
3762 if (*obuf != '\0')
3763 remote_debug_printf ("warning: garbage in qC reply");
3764
3765 return result;
3766 }
3767 else
3768 return oldpid;
3769 }
3770
3771 /* List remote threads using the deprecated qL packet. */
3772
3773 int
3774 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3775 {
3776 if (remote_threadlist_iterator (remote_newthread_step, context,
3777 CRAZY_MAX_THREADS) >= 0)
3778 return 1;
3779
3780 return 0;
3781 }
3782
3783 #if defined(HAVE_LIBEXPAT)
3784
3785 static void
3786 start_thread (struct gdb_xml_parser *parser,
3787 const struct gdb_xml_element *element,
3788 void *user_data,
3789 std::vector<gdb_xml_value> &attributes)
3790 {
3791 struct threads_listing_context *data
3792 = (struct threads_listing_context *) user_data;
3793 struct gdb_xml_value *attr;
3794
3795 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3796 ptid_t ptid = read_ptid (id, NULL);
3797
3798 data->items.emplace_back (ptid);
3799 thread_item &item = data->items.back ();
3800
3801 attr = xml_find_attribute (attributes, "core");
3802 if (attr != NULL)
3803 item.core = *(ULONGEST *) attr->value.get ();
3804
3805 attr = xml_find_attribute (attributes, "name");
3806 if (attr != NULL)
3807 item.name = (const char *) attr->value.get ();
3808
3809 attr = xml_find_attribute (attributes, "handle");
3810 if (attr != NULL)
3811 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3812 }
3813
3814 static void
3815 end_thread (struct gdb_xml_parser *parser,
3816 const struct gdb_xml_element *element,
3817 void *user_data, const char *body_text)
3818 {
3819 struct threads_listing_context *data
3820 = (struct threads_listing_context *) user_data;
3821
3822 if (body_text != NULL && *body_text != '\0')
3823 data->items.back ().extra = body_text;
3824 }
3825
3826 const struct gdb_xml_attribute thread_attributes[] = {
3827 { "id", GDB_XML_AF_NONE, NULL, NULL },
3828 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3829 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3830 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3831 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3832 };
3833
3834 const struct gdb_xml_element thread_children[] = {
3835 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3836 };
3837
3838 const struct gdb_xml_element threads_children[] = {
3839 { "thread", thread_attributes, thread_children,
3840 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3841 start_thread, end_thread },
3842 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3843 };
3844
3845 const struct gdb_xml_element threads_elements[] = {
3846 { "threads", NULL, threads_children,
3847 GDB_XML_EF_NONE, NULL, NULL },
3848 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3849 };
3850
3851 #endif
3852
3853 /* List remote threads using qXfer:threads:read. */
3854
3855 int
3856 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
3857 {
3858 #if defined(HAVE_LIBEXPAT)
3859 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3860 {
3861 gdb::optional<gdb::char_vector> xml
3862 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
3863
3864 if (xml && (*xml)[0] != '\0')
3865 {
3866 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3867 threads_elements, xml->data (), context);
3868 }
3869
3870 return 1;
3871 }
3872 #endif
3873
3874 return 0;
3875 }
3876
3877 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3878
3879 int
3880 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
3881 {
3882 struct remote_state *rs = get_remote_state ();
3883
3884 if (rs->use_threadinfo_query)
3885 {
3886 const char *bufp;
3887
3888 putpkt ("qfThreadInfo");
3889 getpkt (&rs->buf, 0);
3890 bufp = rs->buf.data ();
3891 if (bufp[0] != '\0') /* q packet recognized */
3892 {
3893 while (*bufp++ == 'm') /* reply contains one or more TID */
3894 {
3895 do
3896 {
3897 ptid_t ptid = read_ptid (bufp, &bufp);
3898 context->items.emplace_back (ptid);
3899 }
3900 while (*bufp++ == ','); /* comma-separated list */
3901 putpkt ("qsThreadInfo");
3902 getpkt (&rs->buf, 0);
3903 bufp = rs->buf.data ();
3904 }
3905 return 1;
3906 }
3907 else
3908 {
3909 /* Packet not recognized. */
3910 rs->use_threadinfo_query = 0;
3911 }
3912 }
3913
3914 return 0;
3915 }
3916
3917 /* Return true if INF only has one non-exited thread. */
3918
3919 static bool
3920 has_single_non_exited_thread (inferior *inf)
3921 {
3922 int count = 0;
3923 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
3924 if (++count > 1)
3925 break;
3926 return count == 1;
3927 }
3928
3929 /* Implement the to_update_thread_list function for the remote
3930 targets. */
3931
3932 void
3933 remote_target::update_thread_list ()
3934 {
3935 struct threads_listing_context context;
3936 int got_list = 0;
3937
3938 /* We have a few different mechanisms to fetch the thread list. Try
3939 them all, starting with the most preferred one first, falling
3940 back to older methods. */
3941 if (remote_get_threads_with_qxfer (&context)
3942 || remote_get_threads_with_qthreadinfo (&context)
3943 || remote_get_threads_with_ql (&context))
3944 {
3945 got_list = 1;
3946
3947 if (context.items.empty ()
3948 && remote_thread_always_alive (inferior_ptid))
3949 {
3950 /* Some targets don't really support threads, but still
3951 reply an (empty) thread list in response to the thread
3952 listing packets, instead of replying "packet not
3953 supported". Exit early so we don't delete the main
3954 thread. */
3955 return;
3956 }
3957
3958 /* CONTEXT now holds the current thread list on the remote
3959 target end. Delete GDB-side threads no longer found on the
3960 target. */
3961 for (thread_info *tp : all_threads_safe ())
3962 {
3963 if (tp->inf->process_target () != this)
3964 continue;
3965
3966 if (!context.contains_thread (tp->ptid))
3967 {
3968 /* Do not remove the thread if it is the last thread in
3969 the inferior. This situation happens when we have a
3970 pending exit process status to process. Otherwise we
3971 may end up with a seemingly live inferior (i.e. pid
3972 != 0) that has no threads. */
3973 if (has_single_non_exited_thread (tp->inf))
3974 continue;
3975
3976 /* Not found. */
3977 delete_thread (tp);
3978 }
3979 }
3980
3981 /* Remove any unreported fork child threads from CONTEXT so
3982 that we don't interfere with follow fork, which is where
3983 creation of such threads is handled. */
3984 remove_new_fork_children (&context);
3985
3986 /* And now add threads we don't know about yet to our list. */
3987 for (thread_item &item : context.items)
3988 {
3989 if (item.ptid != null_ptid)
3990 {
3991 /* In non-stop mode, we assume new found threads are
3992 executing until proven otherwise with a stop reply.
3993 In all-stop, we can only get here if all threads are
3994 stopped. */
3995 bool executing = target_is_non_stop_p ();
3996
3997 remote_notice_new_inferior (item.ptid, executing);
3998
3999 thread_info *tp = find_thread_ptid (this, item.ptid);
4000 remote_thread_info *info = get_remote_thread_info (tp);
4001 info->core = item.core;
4002 info->extra = std::move (item.extra);
4003 info->name = std::move (item.name);
4004 info->thread_handle = std::move (item.thread_handle);
4005 }
4006 }
4007 }
4008
4009 if (!got_list)
4010 {
4011 /* If no thread listing method is supported, then query whether
4012 each known thread is alive, one by one, with the T packet.
4013 If the target doesn't support threads at all, then this is a
4014 no-op. See remote_thread_alive. */
4015 prune_threads ();
4016 }
4017 }
4018
4019 /*
4020 * Collect a descriptive string about the given thread.
4021 * The target may say anything it wants to about the thread
4022 * (typically info about its blocked / runnable state, name, etc.).
4023 * This string will appear in the info threads display.
4024 *
4025 * Optional: targets are not required to implement this function.
4026 */
4027
4028 const char *
4029 remote_target::extra_thread_info (thread_info *tp)
4030 {
4031 struct remote_state *rs = get_remote_state ();
4032 int set;
4033 threadref id;
4034 struct gdb_ext_thread_info threadinfo;
4035
4036 if (rs->remote_desc == 0) /* paranoia */
4037 internal_error (__FILE__, __LINE__,
4038 _("remote_threads_extra_info"));
4039
4040 if (tp->ptid == magic_null_ptid
4041 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4042 /* This is the main thread which was added by GDB. The remote
4043 server doesn't know about it. */
4044 return NULL;
4045
4046 std::string &extra = get_remote_thread_info (tp)->extra;
4047
4048 /* If already have cached info, use it. */
4049 if (!extra.empty ())
4050 return extra.c_str ();
4051
4052 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4053 {
4054 /* If we're using qXfer:threads:read, then the extra info is
4055 included in the XML. So if we didn't have anything cached,
4056 it's because there's really no extra info. */
4057 return NULL;
4058 }
4059
4060 if (rs->use_threadextra_query)
4061 {
4062 char *b = rs->buf.data ();
4063 char *endb = b + get_remote_packet_size ();
4064
4065 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4066 b += strlen (b);
4067 write_ptid (b, endb, tp->ptid);
4068
4069 putpkt (rs->buf);
4070 getpkt (&rs->buf, 0);
4071 if (rs->buf[0] != 0)
4072 {
4073 extra.resize (strlen (rs->buf.data ()) / 2);
4074 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4075 return extra.c_str ();
4076 }
4077 }
4078
4079 /* If the above query fails, fall back to the old method. */
4080 rs->use_threadextra_query = 0;
4081 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4082 | TAG_MOREDISPLAY | TAG_DISPLAY;
4083 int_to_threadref (&id, tp->ptid.lwp ());
4084 if (remote_get_threadinfo (&id, set, &threadinfo))
4085 if (threadinfo.active)
4086 {
4087 if (*threadinfo.shortname)
4088 string_appendf (extra, " Name: %s", threadinfo.shortname);
4089 if (*threadinfo.display)
4090 {
4091 if (!extra.empty ())
4092 extra += ',';
4093 string_appendf (extra, " State: %s", threadinfo.display);
4094 }
4095 if (*threadinfo.more_display)
4096 {
4097 if (!extra.empty ())
4098 extra += ',';
4099 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4100 }
4101 return extra.c_str ();
4102 }
4103 return NULL;
4104 }
4105 \f
4106
4107 bool
4108 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4109 struct static_tracepoint_marker *marker)
4110 {
4111 struct remote_state *rs = get_remote_state ();
4112 char *p = rs->buf.data ();
4113
4114 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4115 p += strlen (p);
4116 p += hexnumstr (p, addr);
4117 putpkt (rs->buf);
4118 getpkt (&rs->buf, 0);
4119 p = rs->buf.data ();
4120
4121 if (*p == 'E')
4122 error (_("Remote failure reply: %s"), p);
4123
4124 if (*p++ == 'm')
4125 {
4126 parse_static_tracepoint_marker_definition (p, NULL, marker);
4127 return true;
4128 }
4129
4130 return false;
4131 }
4132
4133 std::vector<static_tracepoint_marker>
4134 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4135 {
4136 struct remote_state *rs = get_remote_state ();
4137 std::vector<static_tracepoint_marker> markers;
4138 const char *p;
4139 static_tracepoint_marker marker;
4140
4141 /* Ask for a first packet of static tracepoint marker
4142 definition. */
4143 putpkt ("qTfSTM");
4144 getpkt (&rs->buf, 0);
4145 p = rs->buf.data ();
4146 if (*p == 'E')
4147 error (_("Remote failure reply: %s"), p);
4148
4149 while (*p++ == 'm')
4150 {
4151 do
4152 {
4153 parse_static_tracepoint_marker_definition (p, &p, &marker);
4154
4155 if (strid == NULL || marker.str_id == strid)
4156 markers.push_back (std::move (marker));
4157 }
4158 while (*p++ == ','); /* comma-separated list */
4159 /* Ask for another packet of static tracepoint definition. */
4160 putpkt ("qTsSTM");
4161 getpkt (&rs->buf, 0);
4162 p = rs->buf.data ();
4163 }
4164
4165 return markers;
4166 }
4167
4168 \f
4169 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4170
4171 ptid_t
4172 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4173 {
4174 return ptid_t (inferior_ptid.pid (), lwp);
4175 }
4176 \f
4177
4178 /* Restart the remote side; this is an extended protocol operation. */
4179
4180 void
4181 remote_target::extended_remote_restart ()
4182 {
4183 struct remote_state *rs = get_remote_state ();
4184
4185 /* Send the restart command; for reasons I don't understand the
4186 remote side really expects a number after the "R". */
4187 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4188 putpkt (rs->buf);
4189
4190 remote_fileio_reset ();
4191 }
4192 \f
4193 /* Clean up connection to a remote debugger. */
4194
4195 void
4196 remote_target::close ()
4197 {
4198 /* Make sure we leave stdin registered in the event loop. */
4199 terminal_ours ();
4200
4201 trace_reset_local_state ();
4202
4203 delete this;
4204 }
4205
4206 remote_target::~remote_target ()
4207 {
4208 struct remote_state *rs = get_remote_state ();
4209
4210 /* Check for NULL because we may get here with a partially
4211 constructed target/connection. */
4212 if (rs->remote_desc == nullptr)
4213 return;
4214
4215 serial_close (rs->remote_desc);
4216
4217 /* We are destroying the remote target, so we should discard
4218 everything of this target. */
4219 discard_pending_stop_replies_in_queue ();
4220
4221 if (rs->remote_async_inferior_event_token)
4222 delete_async_event_handler (&rs->remote_async_inferior_event_token);
4223
4224 delete rs->notif_state;
4225 }
4226
4227 /* Query the remote side for the text, data and bss offsets. */
4228
4229 void
4230 remote_target::get_offsets ()
4231 {
4232 struct remote_state *rs = get_remote_state ();
4233 char *buf;
4234 char *ptr;
4235 int lose, num_segments = 0, do_sections, do_segments;
4236 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4237
4238 if (current_program_space->symfile_object_file == NULL)
4239 return;
4240
4241 putpkt ("qOffsets");
4242 getpkt (&rs->buf, 0);
4243 buf = rs->buf.data ();
4244
4245 if (buf[0] == '\000')
4246 return; /* Return silently. Stub doesn't support
4247 this command. */
4248 if (buf[0] == 'E')
4249 {
4250 warning (_("Remote failure reply: %s"), buf);
4251 return;
4252 }
4253
4254 /* Pick up each field in turn. This used to be done with scanf, but
4255 scanf will make trouble if CORE_ADDR size doesn't match
4256 conversion directives correctly. The following code will work
4257 with any size of CORE_ADDR. */
4258 text_addr = data_addr = bss_addr = 0;
4259 ptr = buf;
4260 lose = 0;
4261
4262 if (startswith (ptr, "Text="))
4263 {
4264 ptr += 5;
4265 /* Don't use strtol, could lose on big values. */
4266 while (*ptr && *ptr != ';')
4267 text_addr = (text_addr << 4) + fromhex (*ptr++);
4268
4269 if (startswith (ptr, ";Data="))
4270 {
4271 ptr += 6;
4272 while (*ptr && *ptr != ';')
4273 data_addr = (data_addr << 4) + fromhex (*ptr++);
4274 }
4275 else
4276 lose = 1;
4277
4278 if (!lose && startswith (ptr, ";Bss="))
4279 {
4280 ptr += 5;
4281 while (*ptr && *ptr != ';')
4282 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4283
4284 if (bss_addr != data_addr)
4285 warning (_("Target reported unsupported offsets: %s"), buf);
4286 }
4287 else
4288 lose = 1;
4289 }
4290 else if (startswith (ptr, "TextSeg="))
4291 {
4292 ptr += 8;
4293 /* Don't use strtol, could lose on big values. */
4294 while (*ptr && *ptr != ';')
4295 text_addr = (text_addr << 4) + fromhex (*ptr++);
4296 num_segments = 1;
4297
4298 if (startswith (ptr, ";DataSeg="))
4299 {
4300 ptr += 9;
4301 while (*ptr && *ptr != ';')
4302 data_addr = (data_addr << 4) + fromhex (*ptr++);
4303 num_segments++;
4304 }
4305 }
4306 else
4307 lose = 1;
4308
4309 if (lose)
4310 error (_("Malformed response to offset query, %s"), buf);
4311 else if (*ptr != '\0')
4312 warning (_("Target reported unsupported offsets: %s"), buf);
4313
4314 objfile *objf = current_program_space->symfile_object_file;
4315 section_offsets offs = objf->section_offsets;
4316
4317 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd);
4318 do_segments = (data != NULL);
4319 do_sections = num_segments == 0;
4320
4321 if (num_segments > 0)
4322 {
4323 segments[0] = text_addr;
4324 segments[1] = data_addr;
4325 }
4326 /* If we have two segments, we can still try to relocate everything
4327 by assuming that the .text and .data offsets apply to the whole
4328 text and data segments. Convert the offsets given in the packet
4329 to base addresses for symfile_map_offsets_to_segments. */
4330 else if (data != nullptr && data->segments.size () == 2)
4331 {
4332 segments[0] = data->segments[0].base + text_addr;
4333 segments[1] = data->segments[1].base + data_addr;
4334 num_segments = 2;
4335 }
4336 /* If the object file has only one segment, assume that it is text
4337 rather than data; main programs with no writable data are rare,
4338 but programs with no code are useless. Of course the code might
4339 have ended up in the data segment... to detect that we would need
4340 the permissions here. */
4341 else if (data && data->segments.size () == 1)
4342 {
4343 segments[0] = data->segments[0].base + text_addr;
4344 num_segments = 1;
4345 }
4346 /* There's no way to relocate by segment. */
4347 else
4348 do_segments = 0;
4349
4350 if (do_segments)
4351 {
4352 int ret = symfile_map_offsets_to_segments (objf->obfd,
4353 data.get (), offs,
4354 num_segments, segments);
4355
4356 if (ret == 0 && !do_sections)
4357 error (_("Can not handle qOffsets TextSeg "
4358 "response with this symbol file"));
4359
4360 if (ret > 0)
4361 do_sections = 0;
4362 }
4363
4364 if (do_sections)
4365 {
4366 offs[SECT_OFF_TEXT (objf)] = text_addr;
4367
4368 /* This is a temporary kludge to force data and bss to use the
4369 same offsets because that's what nlmconv does now. The real
4370 solution requires changes to the stub and remote.c that I
4371 don't have time to do right now. */
4372
4373 offs[SECT_OFF_DATA (objf)] = data_addr;
4374 offs[SECT_OFF_BSS (objf)] = data_addr;
4375 }
4376
4377 objfile_relocate (objf, offs);
4378 }
4379
4380 /* Send interrupt_sequence to remote target. */
4381
4382 void
4383 remote_target::send_interrupt_sequence ()
4384 {
4385 struct remote_state *rs = get_remote_state ();
4386
4387 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4388 remote_serial_write ("\x03", 1);
4389 else if (interrupt_sequence_mode == interrupt_sequence_break)
4390 serial_send_break (rs->remote_desc);
4391 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4392 {
4393 serial_send_break (rs->remote_desc);
4394 remote_serial_write ("g", 1);
4395 }
4396 else
4397 internal_error (__FILE__, __LINE__,
4398 _("Invalid value for interrupt_sequence_mode: %s."),
4399 interrupt_sequence_mode);
4400 }
4401
4402
4403 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4404 and extract the PTID. Returns NULL_PTID if not found. */
4405
4406 static ptid_t
4407 stop_reply_extract_thread (const char *stop_reply)
4408 {
4409 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4410 {
4411 const char *p;
4412
4413 /* Txx r:val ; r:val (...) */
4414 p = &stop_reply[3];
4415
4416 /* Look for "register" named "thread". */
4417 while (*p != '\0')
4418 {
4419 const char *p1;
4420
4421 p1 = strchr (p, ':');
4422 if (p1 == NULL)
4423 return null_ptid;
4424
4425 if (strncmp (p, "thread", p1 - p) == 0)
4426 return read_ptid (++p1, &p);
4427
4428 p1 = strchr (p, ';');
4429 if (p1 == NULL)
4430 return null_ptid;
4431 p1++;
4432
4433 p = p1;
4434 }
4435 }
4436
4437 return null_ptid;
4438 }
4439
4440 /* Determine the remote side's current thread. If we have a stop
4441 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4442 "thread" register we can extract the current thread from. If not,
4443 ask the remote which is the current thread with qC. The former
4444 method avoids a roundtrip. */
4445
4446 ptid_t
4447 remote_target::get_current_thread (const char *wait_status)
4448 {
4449 ptid_t ptid = null_ptid;
4450
4451 /* Note we don't use remote_parse_stop_reply as that makes use of
4452 the target architecture, which we haven't yet fully determined at
4453 this point. */
4454 if (wait_status != NULL)
4455 ptid = stop_reply_extract_thread (wait_status);
4456 if (ptid == null_ptid)
4457 ptid = remote_current_thread (inferior_ptid);
4458
4459 return ptid;
4460 }
4461
4462 /* Query the remote target for which is the current thread/process,
4463 add it to our tables, and update INFERIOR_PTID. The caller is
4464 responsible for setting the state such that the remote end is ready
4465 to return the current thread.
4466
4467 This function is called after handling the '?' or 'vRun' packets,
4468 whose response is a stop reply from which we can also try
4469 extracting the thread. If the target doesn't support the explicit
4470 qC query, we infer the current thread from that stop reply, passed
4471 in in WAIT_STATUS, which may be NULL.
4472
4473 The function returns pointer to the main thread of the inferior. */
4474
4475 thread_info *
4476 remote_target::add_current_inferior_and_thread (const char *wait_status)
4477 {
4478 struct remote_state *rs = get_remote_state ();
4479 bool fake_pid_p = false;
4480
4481 switch_to_no_thread ();
4482
4483 /* Now, if we have thread information, update the current thread's
4484 ptid. */
4485 ptid_t curr_ptid = get_current_thread (wait_status);
4486
4487 if (curr_ptid != null_ptid)
4488 {
4489 if (!remote_multi_process_p (rs))
4490 fake_pid_p = true;
4491 }
4492 else
4493 {
4494 /* Without this, some commands which require an active target
4495 (such as kill) won't work. This variable serves (at least)
4496 double duty as both the pid of the target process (if it has
4497 such), and as a flag indicating that a target is active. */
4498 curr_ptid = magic_null_ptid;
4499 fake_pid_p = true;
4500 }
4501
4502 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4503
4504 /* Add the main thread and switch to it. Don't try reading
4505 registers yet, since we haven't fetched the target description
4506 yet. */
4507 thread_info *tp = add_thread_silent (this, curr_ptid);
4508 switch_to_thread_no_regs (tp);
4509
4510 return tp;
4511 }
4512
4513 /* Print info about a thread that was found already stopped on
4514 connection. */
4515
4516 void
4517 remote_target::print_one_stopped_thread (thread_info *thread)
4518 {
4519 target_waitstatus ws;
4520
4521 /* If there is a pending waitstatus, use it. If there isn't it's because
4522 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4523 and process_initial_stop_replies decided it wasn't interesting to save
4524 and report to the core. */
4525 if (thread->has_pending_waitstatus ())
4526 {
4527 ws = thread->pending_waitstatus ();
4528 thread->clear_pending_waitstatus ();
4529 }
4530 else
4531 {
4532 ws.set_stopped (GDB_SIGNAL_0);
4533 }
4534
4535 switch_to_thread (thread);
4536 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4537 set_current_sal_from_frame (get_current_frame ());
4538
4539 /* For "info program". */
4540 set_last_target_status (this, thread->ptid, ws);
4541
4542 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4543 {
4544 enum gdb_signal sig = ws.sig ();
4545
4546 if (signal_print_state (sig))
4547 gdb::observers::signal_received.notify (sig);
4548 }
4549 gdb::observers::normal_stop.notify (NULL, 1);
4550 }
4551
4552 /* Process all initial stop replies the remote side sent in response
4553 to the ? packet. These indicate threads that were already stopped
4554 on initial connection. We mark these threads as stopped and print
4555 their current frame before giving the user the prompt. */
4556
4557 void
4558 remote_target::process_initial_stop_replies (int from_tty)
4559 {
4560 int pending_stop_replies = stop_reply_queue_length ();
4561 struct thread_info *selected = NULL;
4562 struct thread_info *lowest_stopped = NULL;
4563 struct thread_info *first = NULL;
4564
4565 /* This is only used when the target is non-stop. */
4566 gdb_assert (target_is_non_stop_p ());
4567
4568 /* Consume the initial pending events. */
4569 while (pending_stop_replies-- > 0)
4570 {
4571 ptid_t waiton_ptid = minus_one_ptid;
4572 ptid_t event_ptid;
4573 struct target_waitstatus ws;
4574 int ignore_event = 0;
4575
4576 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4577 if (remote_debug)
4578 print_target_wait_results (waiton_ptid, event_ptid, ws);
4579
4580 switch (ws.kind ())
4581 {
4582 case TARGET_WAITKIND_IGNORE:
4583 case TARGET_WAITKIND_NO_RESUMED:
4584 case TARGET_WAITKIND_SIGNALLED:
4585 case TARGET_WAITKIND_EXITED:
4586 /* We shouldn't see these, but if we do, just ignore. */
4587 remote_debug_printf ("event ignored");
4588 ignore_event = 1;
4589 break;
4590
4591 default:
4592 break;
4593 }
4594
4595 if (ignore_event)
4596 continue;
4597
4598 thread_info *evthread = find_thread_ptid (this, event_ptid);
4599
4600 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4601 {
4602 enum gdb_signal sig = ws.sig ();
4603
4604 /* Stubs traditionally report SIGTRAP as initial signal,
4605 instead of signal 0. Suppress it. */
4606 if (sig == GDB_SIGNAL_TRAP)
4607 sig = GDB_SIGNAL_0;
4608 evthread->set_stop_signal (sig);
4609 ws.set_stopped (sig);
4610 }
4611
4612 if (ws.kind () != TARGET_WAITKIND_STOPPED
4613 || ws.sig () != GDB_SIGNAL_0)
4614 evthread->set_pending_waitstatus (ws);
4615
4616 set_executing (this, event_ptid, false);
4617 set_running (this, event_ptid, false);
4618 get_remote_thread_info (evthread)->set_not_resumed ();
4619 }
4620
4621 /* "Notice" the new inferiors before anything related to
4622 registers/memory. */
4623 for (inferior *inf : all_non_exited_inferiors (this))
4624 {
4625 inf->needs_setup = 1;
4626
4627 if (non_stop)
4628 {
4629 thread_info *thread = any_live_thread_of_inferior (inf);
4630 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4631 from_tty);
4632 }
4633 }
4634
4635 /* If all-stop on top of non-stop, pause all threads. Note this
4636 records the threads' stop pc, so must be done after "noticing"
4637 the inferiors. */
4638 if (!non_stop)
4639 {
4640 {
4641 /* At this point, the remote target is not async. It needs to be for
4642 the poll in stop_all_threads to consider events from it, so enable
4643 it temporarily. */
4644 gdb_assert (!this->is_async_p ());
4645 SCOPE_EXIT { target_async (0); };
4646 target_async (1);
4647 stop_all_threads ("remote connect in all-stop");
4648 }
4649
4650 /* If all threads of an inferior were already stopped, we
4651 haven't setup the inferior yet. */
4652 for (inferior *inf : all_non_exited_inferiors (this))
4653 {
4654 if (inf->needs_setup)
4655 {
4656 thread_info *thread = any_live_thread_of_inferior (inf);
4657 switch_to_thread_no_regs (thread);
4658 setup_inferior (0);
4659 }
4660 }
4661 }
4662
4663 /* Now go over all threads that are stopped, and print their current
4664 frame. If all-stop, then if there's a signalled thread, pick
4665 that as current. */
4666 for (thread_info *thread : all_non_exited_threads (this))
4667 {
4668 if (first == NULL)
4669 first = thread;
4670
4671 if (!non_stop)
4672 thread->set_running (false);
4673 else if (thread->state != THREAD_STOPPED)
4674 continue;
4675
4676 if (selected == nullptr && thread->has_pending_waitstatus ())
4677 selected = thread;
4678
4679 if (lowest_stopped == NULL
4680 || thread->inf->num < lowest_stopped->inf->num
4681 || thread->per_inf_num < lowest_stopped->per_inf_num)
4682 lowest_stopped = thread;
4683
4684 if (non_stop)
4685 print_one_stopped_thread (thread);
4686 }
4687
4688 /* In all-stop, we only print the status of one thread, and leave
4689 others with their status pending. */
4690 if (!non_stop)
4691 {
4692 thread_info *thread = selected;
4693 if (thread == NULL)
4694 thread = lowest_stopped;
4695 if (thread == NULL)
4696 thread = first;
4697
4698 print_one_stopped_thread (thread);
4699 }
4700 }
4701
4702 /* Mark a remote_target as marking (by setting the starting_up flag within
4703 its remote_state) for the lifetime of this object. The reference count
4704 on the remote target is temporarily incremented, to prevent the target
4705 being deleted under our feet. */
4706
4707 struct scoped_mark_target_starting
4708 {
4709 /* Constructor, TARGET is the target to be marked as starting, its
4710 reference count will be incremented. */
4711 scoped_mark_target_starting (remote_target *target)
4712 : m_remote_target (target)
4713 {
4714 m_remote_target->incref ();
4715 remote_state *rs = m_remote_target->get_remote_state ();
4716 rs->starting_up = true;
4717 }
4718
4719 /* Destructor, mark the target being worked on as no longer starting, and
4720 decrement the reference count. */
4721 ~scoped_mark_target_starting ()
4722 {
4723 remote_state *rs = m_remote_target->get_remote_state ();
4724 rs->starting_up = false;
4725 decref_target (m_remote_target);
4726 }
4727
4728 private:
4729
4730 /* The target on which we are operating. */
4731 remote_target *m_remote_target;
4732 };
4733
4734 /* Helper for remote_target::start_remote, start the remote connection and
4735 sync state. Return true if everything goes OK, otherwise, return false.
4736 This function exists so that the scoped_restore created within it will
4737 expire before we return to remote_target::start_remote. */
4738
4739 bool
4740 remote_target::start_remote_1 (int from_tty, int extended_p)
4741 {
4742 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4743
4744 struct remote_state *rs = get_remote_state ();
4745 struct packet_config *noack_config;
4746
4747 /* Signal other parts that we're going through the initial setup,
4748 and so things may not be stable yet. E.g., we don't try to
4749 install tracepoints until we've relocated symbols. Also, a
4750 Ctrl-C before we're connected and synced up can't interrupt the
4751 target. Instead, it offers to drop the (potentially wedged)
4752 connection. */
4753 scoped_mark_target_starting target_is_starting (this);
4754
4755 QUIT;
4756
4757 if (interrupt_on_connect)
4758 send_interrupt_sequence ();
4759
4760 /* Ack any packet which the remote side has already sent. */
4761 remote_serial_write ("+", 1);
4762
4763 /* The first packet we send to the target is the optional "supported
4764 packets" request. If the target can answer this, it will tell us
4765 which later probes to skip. */
4766 remote_query_supported ();
4767
4768 /* If the stub wants to get a QAllow, compose one and send it. */
4769 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4770 set_permissions ();
4771
4772 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4773 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4774 as a reply to known packet. For packet "vFile:setfs:" it is an
4775 invalid reply and GDB would return error in
4776 remote_hostio_set_filesystem, making remote files access impossible.
4777 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4778 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4779 {
4780 const char v_mustreplyempty[] = "vMustReplyEmpty";
4781
4782 putpkt (v_mustreplyempty);
4783 getpkt (&rs->buf, 0);
4784 if (strcmp (rs->buf.data (), "OK") == 0)
4785 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4786 else if (strcmp (rs->buf.data (), "") != 0)
4787 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4788 rs->buf.data ());
4789 }
4790
4791 /* Next, we possibly activate noack mode.
4792
4793 If the QStartNoAckMode packet configuration is set to AUTO,
4794 enable noack mode if the stub reported a wish for it with
4795 qSupported.
4796
4797 If set to TRUE, then enable noack mode even if the stub didn't
4798 report it in qSupported. If the stub doesn't reply OK, the
4799 session ends with an error.
4800
4801 If FALSE, then don't activate noack mode, regardless of what the
4802 stub claimed should be the default with qSupported. */
4803
4804 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4805 if (packet_config_support (noack_config) != PACKET_DISABLE)
4806 {
4807 putpkt ("QStartNoAckMode");
4808 getpkt (&rs->buf, 0);
4809 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4810 rs->noack_mode = 1;
4811 }
4812
4813 if (extended_p)
4814 {
4815 /* Tell the remote that we are using the extended protocol. */
4816 putpkt ("!");
4817 getpkt (&rs->buf, 0);
4818 }
4819
4820 /* Let the target know which signals it is allowed to pass down to
4821 the program. */
4822 update_signals_program_target ();
4823
4824 /* Next, if the target can specify a description, read it. We do
4825 this before anything involving memory or registers. */
4826 target_find_description ();
4827
4828 /* Next, now that we know something about the target, update the
4829 address spaces in the program spaces. */
4830 update_address_spaces ();
4831
4832 /* On OSs where the list of libraries is global to all
4833 processes, we fetch them early. */
4834 if (gdbarch_has_global_solist (target_gdbarch ()))
4835 solib_add (NULL, from_tty, auto_solib_add);
4836
4837 if (target_is_non_stop_p ())
4838 {
4839 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4840 error (_("Non-stop mode requested, but remote "
4841 "does not support non-stop"));
4842
4843 putpkt ("QNonStop:1");
4844 getpkt (&rs->buf, 0);
4845
4846 if (strcmp (rs->buf.data (), "OK") != 0)
4847 error (_("Remote refused setting non-stop mode with: %s"),
4848 rs->buf.data ());
4849
4850 /* Find about threads and processes the stub is already
4851 controlling. We default to adding them in the running state.
4852 The '?' query below will then tell us about which threads are
4853 stopped. */
4854 this->update_thread_list ();
4855 }
4856 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4857 {
4858 /* Don't assume that the stub can operate in all-stop mode.
4859 Request it explicitly. */
4860 putpkt ("QNonStop:0");
4861 getpkt (&rs->buf, 0);
4862
4863 if (strcmp (rs->buf.data (), "OK") != 0)
4864 error (_("Remote refused setting all-stop mode with: %s"),
4865 rs->buf.data ());
4866 }
4867
4868 /* Upload TSVs regardless of whether the target is running or not. The
4869 remote stub, such as GDBserver, may have some predefined or builtin
4870 TSVs, even if the target is not running. */
4871 if (get_trace_status (current_trace_status ()) != -1)
4872 {
4873 struct uploaded_tsv *uploaded_tsvs = NULL;
4874
4875 upload_trace_state_variables (&uploaded_tsvs);
4876 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4877 }
4878
4879 /* Check whether the target is running now. */
4880 putpkt ("?");
4881 getpkt (&rs->buf, 0);
4882
4883 if (!target_is_non_stop_p ())
4884 {
4885 char *wait_status = NULL;
4886
4887 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4888 {
4889 if (!extended_p)
4890 error (_("The target is not running (try extended-remote?)"));
4891 return false;
4892 }
4893 else
4894 {
4895 /* Save the reply for later. */
4896 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
4897 strcpy (wait_status, rs->buf.data ());
4898 }
4899
4900 /* Fetch thread list. */
4901 target_update_thread_list ();
4902
4903 /* Let the stub know that we want it to return the thread. */
4904 set_continue_thread (minus_one_ptid);
4905
4906 if (thread_count (this) == 0)
4907 {
4908 /* Target has no concept of threads at all. GDB treats
4909 non-threaded target as single-threaded; add a main
4910 thread. */
4911 thread_info *tp = add_current_inferior_and_thread (wait_status);
4912 get_remote_thread_info (tp)->set_resumed ();
4913 }
4914 else
4915 {
4916 /* We have thread information; select the thread the target
4917 says should be current. If we're reconnecting to a
4918 multi-threaded program, this will ideally be the thread
4919 that last reported an event before GDB disconnected. */
4920 ptid_t curr_thread = get_current_thread (wait_status);
4921 if (curr_thread == null_ptid)
4922 {
4923 /* Odd... The target was able to list threads, but not
4924 tell us which thread was current (no "thread"
4925 register in T stop reply?). Just pick the first
4926 thread in the thread list then. */
4927
4928 remote_debug_printf ("warning: couldn't determine remote "
4929 "current thread; picking first in list.");
4930
4931 for (thread_info *tp : all_non_exited_threads (this,
4932 minus_one_ptid))
4933 {
4934 switch_to_thread (tp);
4935 break;
4936 }
4937 }
4938 else
4939 switch_to_thread (find_thread_ptid (this, curr_thread));
4940 }
4941
4942 /* init_wait_for_inferior should be called before get_offsets in order
4943 to manage `inserted' flag in bp loc in a correct state.
4944 breakpoint_init_inferior, called from init_wait_for_inferior, set
4945 `inserted' flag to 0, while before breakpoint_re_set, called from
4946 start_remote, set `inserted' flag to 1. In the initialization of
4947 inferior, breakpoint_init_inferior should be called first, and then
4948 breakpoint_re_set can be called. If this order is broken, state of
4949 `inserted' flag is wrong, and cause some problems on breakpoint
4950 manipulation. */
4951 init_wait_for_inferior ();
4952
4953 get_offsets (); /* Get text, data & bss offsets. */
4954
4955 /* If we could not find a description using qXfer, and we know
4956 how to do it some other way, try again. This is not
4957 supported for non-stop; it could be, but it is tricky if
4958 there are no stopped threads when we connect. */
4959 if (remote_read_description_p (this)
4960 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4961 {
4962 target_clear_description ();
4963 target_find_description ();
4964 }
4965
4966 /* Use the previously fetched status. */
4967 gdb_assert (wait_status != NULL);
4968 struct notif_event *reply
4969 = remote_notif_parse (this, &notif_client_stop, wait_status);
4970 push_stop_reply ((struct stop_reply *) reply);
4971
4972 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
4973 }
4974 else
4975 {
4976 /* Clear WFI global state. Do this before finding about new
4977 threads and inferiors, and setting the current inferior.
4978 Otherwise we would clear the proceed status of the current
4979 inferior when we want its stop_soon state to be preserved
4980 (see notice_new_inferior). */
4981 init_wait_for_inferior ();
4982
4983 /* In non-stop, we will either get an "OK", meaning that there
4984 are no stopped threads at this time; or, a regular stop
4985 reply. In the latter case, there may be more than one thread
4986 stopped --- we pull them all out using the vStopped
4987 mechanism. */
4988 if (strcmp (rs->buf.data (), "OK") != 0)
4989 {
4990 struct notif_client *notif = &notif_client_stop;
4991
4992 /* remote_notif_get_pending_replies acks this one, and gets
4993 the rest out. */
4994 rs->notif_state->pending_event[notif_client_stop.id]
4995 = remote_notif_parse (this, notif, rs->buf.data ());
4996 remote_notif_get_pending_events (notif);
4997 }
4998
4999 if (thread_count (this) == 0)
5000 {
5001 if (!extended_p)
5002 error (_("The target is not running (try extended-remote?)"));
5003 return false;
5004 }
5005
5006 /* Report all signals during attach/startup. */
5007 pass_signals ({});
5008
5009 /* If there are already stopped threads, mark them stopped and
5010 report their stops before giving the prompt to the user. */
5011 process_initial_stop_replies (from_tty);
5012
5013 if (target_can_async_p ())
5014 target_async (1);
5015 }
5016
5017 /* If we connected to a live target, do some additional setup. */
5018 if (target_has_execution ())
5019 {
5020 /* No use without a symbol-file. */
5021 if (current_program_space->symfile_object_file)
5022 remote_check_symbols ();
5023 }
5024
5025 /* Possibly the target has been engaged in a trace run started
5026 previously; find out where things are at. */
5027 if (get_trace_status (current_trace_status ()) != -1)
5028 {
5029 struct uploaded_tp *uploaded_tps = NULL;
5030
5031 if (current_trace_status ()->running)
5032 gdb_printf (_("Trace is already running on the target.\n"));
5033
5034 upload_tracepoints (&uploaded_tps);
5035
5036 merge_uploaded_tracepoints (&uploaded_tps);
5037 }
5038
5039 /* Possibly the target has been engaged in a btrace record started
5040 previously; find out where things are at. */
5041 remote_btrace_maybe_reopen ();
5042
5043 return true;
5044 }
5045
5046 /* Start the remote connection and sync state. */
5047
5048 void
5049 remote_target::start_remote (int from_tty, int extended_p)
5050 {
5051 if (start_remote_1 (from_tty, extended_p)
5052 && breakpoints_should_be_inserted_now ())
5053 insert_breakpoints ();
5054 }
5055
5056 const char *
5057 remote_target::connection_string ()
5058 {
5059 remote_state *rs = get_remote_state ();
5060
5061 if (rs->remote_desc->name != NULL)
5062 return rs->remote_desc->name;
5063 else
5064 return NULL;
5065 }
5066
5067 /* Open a connection to a remote debugger.
5068 NAME is the filename used for communication. */
5069
5070 void
5071 remote_target::open (const char *name, int from_tty)
5072 {
5073 open_1 (name, from_tty, 0);
5074 }
5075
5076 /* Open a connection to a remote debugger using the extended
5077 remote gdb protocol. NAME is the filename used for communication. */
5078
5079 void
5080 extended_remote_target::open (const char *name, int from_tty)
5081 {
5082 open_1 (name, from_tty, 1 /*extended_p */);
5083 }
5084
5085 /* Reset all packets back to "unknown support". Called when opening a
5086 new connection to a remote target. */
5087
5088 static void
5089 reset_all_packet_configs_support (void)
5090 {
5091 int i;
5092
5093 for (i = 0; i < PACKET_MAX; i++)
5094 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5095 }
5096
5097 /* Initialize all packet configs. */
5098
5099 static void
5100 init_all_packet_configs (void)
5101 {
5102 int i;
5103
5104 for (i = 0; i < PACKET_MAX; i++)
5105 {
5106 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5107 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5108 }
5109 }
5110
5111 /* Symbol look-up. */
5112
5113 void
5114 remote_target::remote_check_symbols ()
5115 {
5116 char *tmp;
5117 int end;
5118
5119 /* The remote side has no concept of inferiors that aren't running
5120 yet, it only knows about running processes. If we're connected
5121 but our current inferior is not running, we should not invite the
5122 remote target to request symbol lookups related to its
5123 (unrelated) current process. */
5124 if (!target_has_execution ())
5125 return;
5126
5127 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5128 return;
5129
5130 /* Make sure the remote is pointing at the right process. Note
5131 there's no way to select "no process". */
5132 set_general_process ();
5133
5134 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5135 because we need both at the same time. */
5136 gdb::char_vector msg (get_remote_packet_size ());
5137 gdb::char_vector reply (get_remote_packet_size ());
5138
5139 /* Invite target to request symbol lookups. */
5140
5141 putpkt ("qSymbol::");
5142 getpkt (&reply, 0);
5143 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
5144
5145 while (startswith (reply.data (), "qSymbol:"))
5146 {
5147 struct bound_minimal_symbol sym;
5148
5149 tmp = &reply[8];
5150 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5151 strlen (tmp) / 2);
5152 msg[end] = '\0';
5153 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5154 if (sym.minsym == NULL)
5155 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5156 &reply[8]);
5157 else
5158 {
5159 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5160 CORE_ADDR sym_addr = sym.value_address ();
5161
5162 /* If this is a function address, return the start of code
5163 instead of any data function descriptor. */
5164 sym_addr = gdbarch_convert_from_func_ptr_addr
5165 (target_gdbarch (), sym_addr, current_inferior ()->top_target ());
5166
5167 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5168 phex_nz (sym_addr, addr_size), &reply[8]);
5169 }
5170
5171 putpkt (msg.data ());
5172 getpkt (&reply, 0);
5173 }
5174 }
5175
5176 static struct serial *
5177 remote_serial_open (const char *name)
5178 {
5179 static int udp_warning = 0;
5180
5181 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5182 of in ser-tcp.c, because it is the remote protocol assuming that the
5183 serial connection is reliable and not the serial connection promising
5184 to be. */
5185 if (!udp_warning && startswith (name, "udp:"))
5186 {
5187 warning (_("The remote protocol may be unreliable over UDP.\n"
5188 "Some events may be lost, rendering further debugging "
5189 "impossible."));
5190 udp_warning = 1;
5191 }
5192
5193 return serial_open (name);
5194 }
5195
5196 /* Inform the target of our permission settings. The permission flags
5197 work without this, but if the target knows the settings, it can do
5198 a couple things. First, it can add its own check, to catch cases
5199 that somehow manage to get by the permissions checks in target
5200 methods. Second, if the target is wired to disallow particular
5201 settings (for instance, a system in the field that is not set up to
5202 be able to stop at a breakpoint), it can object to any unavailable
5203 permissions. */
5204
5205 void
5206 remote_target::set_permissions ()
5207 {
5208 struct remote_state *rs = get_remote_state ();
5209
5210 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5211 "WriteReg:%x;WriteMem:%x;"
5212 "InsertBreak:%x;InsertTrace:%x;"
5213 "InsertFastTrace:%x;Stop:%x",
5214 may_write_registers, may_write_memory,
5215 may_insert_breakpoints, may_insert_tracepoints,
5216 may_insert_fast_tracepoints, may_stop);
5217 putpkt (rs->buf);
5218 getpkt (&rs->buf, 0);
5219
5220 /* If the target didn't like the packet, warn the user. Do not try
5221 to undo the user's settings, that would just be maddening. */
5222 if (strcmp (rs->buf.data (), "OK") != 0)
5223 warning (_("Remote refused setting permissions with: %s"),
5224 rs->buf.data ());
5225 }
5226
5227 /* This type describes each known response to the qSupported
5228 packet. */
5229 struct protocol_feature
5230 {
5231 /* The name of this protocol feature. */
5232 const char *name;
5233
5234 /* The default for this protocol feature. */
5235 enum packet_support default_support;
5236
5237 /* The function to call when this feature is reported, or after
5238 qSupported processing if the feature is not supported.
5239 The first argument points to this structure. The second
5240 argument indicates whether the packet requested support be
5241 enabled, disabled, or probed (or the default, if this function
5242 is being called at the end of processing and this feature was
5243 not reported). The third argument may be NULL; if not NULL, it
5244 is a NUL-terminated string taken from the packet following
5245 this feature's name and an equals sign. */
5246 void (*func) (remote_target *remote, const struct protocol_feature *,
5247 enum packet_support, const char *);
5248
5249 /* The corresponding packet for this feature. Only used if
5250 FUNC is remote_supported_packet. */
5251 int packet;
5252 };
5253
5254 static void
5255 remote_supported_packet (remote_target *remote,
5256 const struct protocol_feature *feature,
5257 enum packet_support support,
5258 const char *argument)
5259 {
5260 if (argument)
5261 {
5262 warning (_("Remote qSupported response supplied an unexpected value for"
5263 " \"%s\"."), feature->name);
5264 return;
5265 }
5266
5267 remote_protocol_packets[feature->packet].support = support;
5268 }
5269
5270 void
5271 remote_target::remote_packet_size (const protocol_feature *feature,
5272 enum packet_support support, const char *value)
5273 {
5274 struct remote_state *rs = get_remote_state ();
5275
5276 int packet_size;
5277 char *value_end;
5278
5279 if (support != PACKET_ENABLE)
5280 return;
5281
5282 if (value == NULL || *value == '\0')
5283 {
5284 warning (_("Remote target reported \"%s\" without a size."),
5285 feature->name);
5286 return;
5287 }
5288
5289 errno = 0;
5290 packet_size = strtol (value, &value_end, 16);
5291 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5292 {
5293 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5294 feature->name, value);
5295 return;
5296 }
5297
5298 /* Record the new maximum packet size. */
5299 rs->explicit_packet_size = packet_size;
5300 }
5301
5302 static void
5303 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5304 enum packet_support support, const char *value)
5305 {
5306 remote->remote_packet_size (feature, support, value);
5307 }
5308
5309 static const struct protocol_feature remote_protocol_features[] = {
5310 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5311 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5312 PACKET_qXfer_auxv },
5313 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5314 PACKET_qXfer_exec_file },
5315 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5316 PACKET_qXfer_features },
5317 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5318 PACKET_qXfer_libraries },
5319 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5320 PACKET_qXfer_libraries_svr4 },
5321 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5322 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5323 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5324 PACKET_qXfer_memory_map },
5325 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5326 PACKET_qXfer_osdata },
5327 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5328 PACKET_qXfer_threads },
5329 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5330 PACKET_qXfer_traceframe_info },
5331 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5332 PACKET_QPassSignals },
5333 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5334 PACKET_QCatchSyscalls },
5335 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5336 PACKET_QProgramSignals },
5337 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5338 PACKET_QSetWorkingDir },
5339 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5340 PACKET_QStartupWithShell },
5341 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5342 PACKET_QEnvironmentHexEncoded },
5343 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5344 PACKET_QEnvironmentReset },
5345 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5346 PACKET_QEnvironmentUnset },
5347 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5348 PACKET_QStartNoAckMode },
5349 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5350 PACKET_multiprocess_feature },
5351 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5352 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5353 PACKET_qXfer_siginfo_read },
5354 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5355 PACKET_qXfer_siginfo_write },
5356 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5357 PACKET_ConditionalTracepoints },
5358 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5359 PACKET_ConditionalBreakpoints },
5360 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5361 PACKET_BreakpointCommands },
5362 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5363 PACKET_FastTracepoints },
5364 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5365 PACKET_StaticTracepoints },
5366 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5367 PACKET_InstallInTrace},
5368 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5369 PACKET_DisconnectedTracing_feature },
5370 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5371 PACKET_bc },
5372 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5373 PACKET_bs },
5374 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5375 PACKET_TracepointSource },
5376 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5377 PACKET_QAllow },
5378 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5379 PACKET_EnableDisableTracepoints_feature },
5380 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5381 PACKET_qXfer_fdpic },
5382 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5383 PACKET_qXfer_uib },
5384 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5385 PACKET_QDisableRandomization },
5386 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5387 { "QTBuffer:size", PACKET_DISABLE,
5388 remote_supported_packet, PACKET_QTBuffer_size},
5389 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5390 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5391 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5392 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5393 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5394 PACKET_qXfer_btrace },
5395 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5396 PACKET_qXfer_btrace_conf },
5397 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5398 PACKET_Qbtrace_conf_bts_size },
5399 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5400 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5401 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5402 PACKET_fork_event_feature },
5403 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5404 PACKET_vfork_event_feature },
5405 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5406 PACKET_exec_event_feature },
5407 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5408 PACKET_Qbtrace_conf_pt_size },
5409 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5410 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5411 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5412 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5413 PACKET_memory_tagging_feature },
5414 };
5415
5416 static char *remote_support_xml;
5417
5418 /* Register string appended to "xmlRegisters=" in qSupported query. */
5419
5420 void
5421 register_remote_support_xml (const char *xml)
5422 {
5423 #if defined(HAVE_LIBEXPAT)
5424 if (remote_support_xml == NULL)
5425 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5426 else
5427 {
5428 char *copy = xstrdup (remote_support_xml + 13);
5429 char *saveptr;
5430 char *p = strtok_r (copy, ",", &saveptr);
5431
5432 do
5433 {
5434 if (strcmp (p, xml) == 0)
5435 {
5436 /* already there */
5437 xfree (copy);
5438 return;
5439 }
5440 }
5441 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5442 xfree (copy);
5443
5444 remote_support_xml = reconcat (remote_support_xml,
5445 remote_support_xml, ",", xml,
5446 (char *) NULL);
5447 }
5448 #endif
5449 }
5450
5451 static void
5452 remote_query_supported_append (std::string *msg, const char *append)
5453 {
5454 if (!msg->empty ())
5455 msg->append (";");
5456 msg->append (append);
5457 }
5458
5459 void
5460 remote_target::remote_query_supported ()
5461 {
5462 struct remote_state *rs = get_remote_state ();
5463 char *next;
5464 int i;
5465 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5466
5467 /* The packet support flags are handled differently for this packet
5468 than for most others. We treat an error, a disabled packet, and
5469 an empty response identically: any features which must be reported
5470 to be used will be automatically disabled. An empty buffer
5471 accomplishes this, since that is also the representation for a list
5472 containing no features. */
5473
5474 rs->buf[0] = 0;
5475 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5476 {
5477 std::string q;
5478
5479 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5480 remote_query_supported_append (&q, "multiprocess+");
5481
5482 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5483 remote_query_supported_append (&q, "swbreak+");
5484 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5485 remote_query_supported_append (&q, "hwbreak+");
5486
5487 remote_query_supported_append (&q, "qRelocInsn+");
5488
5489 if (packet_set_cmd_state (PACKET_fork_event_feature)
5490 != AUTO_BOOLEAN_FALSE)
5491 remote_query_supported_append (&q, "fork-events+");
5492 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5493 != AUTO_BOOLEAN_FALSE)
5494 remote_query_supported_append (&q, "vfork-events+");
5495 if (packet_set_cmd_state (PACKET_exec_event_feature)
5496 != AUTO_BOOLEAN_FALSE)
5497 remote_query_supported_append (&q, "exec-events+");
5498
5499 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5500 remote_query_supported_append (&q, "vContSupported+");
5501
5502 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5503 remote_query_supported_append (&q, "QThreadEvents+");
5504
5505 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5506 remote_query_supported_append (&q, "no-resumed+");
5507
5508 if (packet_set_cmd_state (PACKET_memory_tagging_feature)
5509 != AUTO_BOOLEAN_FALSE)
5510 remote_query_supported_append (&q, "memory-tagging+");
5511
5512 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5513 the qSupported:xmlRegisters=i386 handling. */
5514 if (remote_support_xml != NULL
5515 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5516 remote_query_supported_append (&q, remote_support_xml);
5517
5518 q = "qSupported:" + q;
5519 putpkt (q.c_str ());
5520
5521 getpkt (&rs->buf, 0);
5522
5523 /* If an error occured, warn, but do not return - just reset the
5524 buffer to empty and go on to disable features. */
5525 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5526 == PACKET_ERROR)
5527 {
5528 warning (_("Remote failure reply: %s"), rs->buf.data ());
5529 rs->buf[0] = 0;
5530 }
5531 }
5532
5533 memset (seen, 0, sizeof (seen));
5534
5535 next = rs->buf.data ();
5536 while (*next)
5537 {
5538 enum packet_support is_supported;
5539 char *p, *end, *name_end, *value;
5540
5541 /* First separate out this item from the rest of the packet. If
5542 there's another item after this, we overwrite the separator
5543 (terminated strings are much easier to work with). */
5544 p = next;
5545 end = strchr (p, ';');
5546 if (end == NULL)
5547 {
5548 end = p + strlen (p);
5549 next = end;
5550 }
5551 else
5552 {
5553 *end = '\0';
5554 next = end + 1;
5555
5556 if (end == p)
5557 {
5558 warning (_("empty item in \"qSupported\" response"));
5559 continue;
5560 }
5561 }
5562
5563 name_end = strchr (p, '=');
5564 if (name_end)
5565 {
5566 /* This is a name=value entry. */
5567 is_supported = PACKET_ENABLE;
5568 value = name_end + 1;
5569 *name_end = '\0';
5570 }
5571 else
5572 {
5573 value = NULL;
5574 switch (end[-1])
5575 {
5576 case '+':
5577 is_supported = PACKET_ENABLE;
5578 break;
5579
5580 case '-':
5581 is_supported = PACKET_DISABLE;
5582 break;
5583
5584 case '?':
5585 is_supported = PACKET_SUPPORT_UNKNOWN;
5586 break;
5587
5588 default:
5589 warning (_("unrecognized item \"%s\" "
5590 "in \"qSupported\" response"), p);
5591 continue;
5592 }
5593 end[-1] = '\0';
5594 }
5595
5596 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5597 if (strcmp (remote_protocol_features[i].name, p) == 0)
5598 {
5599 const struct protocol_feature *feature;
5600
5601 seen[i] = 1;
5602 feature = &remote_protocol_features[i];
5603 feature->func (this, feature, is_supported, value);
5604 break;
5605 }
5606 }
5607
5608 /* If we increased the packet size, make sure to increase the global
5609 buffer size also. We delay this until after parsing the entire
5610 qSupported packet, because this is the same buffer we were
5611 parsing. */
5612 if (rs->buf.size () < rs->explicit_packet_size)
5613 rs->buf.resize (rs->explicit_packet_size);
5614
5615 /* Handle the defaults for unmentioned features. */
5616 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5617 if (!seen[i])
5618 {
5619 const struct protocol_feature *feature;
5620
5621 feature = &remote_protocol_features[i];
5622 feature->func (this, feature, feature->default_support, NULL);
5623 }
5624 }
5625
5626 /* Serial QUIT handler for the remote serial descriptor.
5627
5628 Defers handling a Ctrl-C until we're done with the current
5629 command/response packet sequence, unless:
5630
5631 - We're setting up the connection. Don't send a remote interrupt
5632 request, as we're not fully synced yet. Quit immediately
5633 instead.
5634
5635 - The target has been resumed in the foreground
5636 (target_terminal::is_ours is false) with a synchronous resume
5637 packet, and we're blocked waiting for the stop reply, thus a
5638 Ctrl-C should be immediately sent to the target.
5639
5640 - We get a second Ctrl-C while still within the same serial read or
5641 write. In that case the serial is seemingly wedged --- offer to
5642 quit/disconnect.
5643
5644 - We see a second Ctrl-C without target response, after having
5645 previously interrupted the target. In that case the target/stub
5646 is probably wedged --- offer to quit/disconnect.
5647 */
5648
5649 void
5650 remote_target::remote_serial_quit_handler ()
5651 {
5652 struct remote_state *rs = get_remote_state ();
5653
5654 if (check_quit_flag ())
5655 {
5656 /* If we're starting up, we're not fully synced yet. Quit
5657 immediately. */
5658 if (rs->starting_up)
5659 quit ();
5660 else if (rs->got_ctrlc_during_io)
5661 {
5662 if (query (_("The target is not responding to GDB commands.\n"
5663 "Stop debugging it? ")))
5664 remote_unpush_and_throw (this);
5665 }
5666 /* If ^C has already been sent once, offer to disconnect. */
5667 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5668 interrupt_query ();
5669 /* All-stop protocol, and blocked waiting for stop reply. Send
5670 an interrupt request. */
5671 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5672 target_interrupt ();
5673 else
5674 rs->got_ctrlc_during_io = 1;
5675 }
5676 }
5677
5678 /* The remote_target that is current while the quit handler is
5679 overridden with remote_serial_quit_handler. */
5680 static remote_target *curr_quit_handler_target;
5681
5682 static void
5683 remote_serial_quit_handler ()
5684 {
5685 curr_quit_handler_target->remote_serial_quit_handler ();
5686 }
5687
5688 /* Remove the remote target from the target stack of each inferior
5689 that is using it. Upper targets depend on it so remove them
5690 first. */
5691
5692 static void
5693 remote_unpush_target (remote_target *target)
5694 {
5695 /* We have to unpush the target from all inferiors, even those that
5696 aren't running. */
5697 scoped_restore_current_inferior restore_current_inferior;
5698
5699 for (inferior *inf : all_inferiors (target))
5700 {
5701 switch_to_inferior_no_thread (inf);
5702 pop_all_targets_at_and_above (process_stratum);
5703 generic_mourn_inferior ();
5704 }
5705
5706 /* Don't rely on target_close doing this when the target is popped
5707 from the last remote inferior above, because something may be
5708 holding a reference to the target higher up on the stack, meaning
5709 target_close won't be called yet. We lost the connection to the
5710 target, so clear these now, otherwise we may later throw
5711 TARGET_CLOSE_ERROR while trying to tell the remote target to
5712 close the file. */
5713 fileio_handles_invalidate_target (target);
5714 }
5715
5716 static void
5717 remote_unpush_and_throw (remote_target *target)
5718 {
5719 remote_unpush_target (target);
5720 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5721 }
5722
5723 void
5724 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5725 {
5726 remote_target *curr_remote = get_current_remote_target ();
5727
5728 if (name == 0)
5729 error (_("To open a remote debug connection, you need to specify what\n"
5730 "serial device is attached to the remote system\n"
5731 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5732
5733 /* If we're connected to a running target, target_preopen will kill it.
5734 Ask this question first, before target_preopen has a chance to kill
5735 anything. */
5736 if (curr_remote != NULL && !target_has_execution ())
5737 {
5738 if (from_tty
5739 && !query (_("Already connected to a remote target. Disconnect? ")))
5740 error (_("Still connected."));
5741 }
5742
5743 /* Here the possibly existing remote target gets unpushed. */
5744 target_preopen (from_tty);
5745
5746 remote_fileio_reset ();
5747 reopen_exec_file ();
5748 reread_symbols (from_tty);
5749
5750 remote_target *remote
5751 = (extended_p ? new extended_remote_target () : new remote_target ());
5752 target_ops_up target_holder (remote);
5753
5754 remote_state *rs = remote->get_remote_state ();
5755
5756 /* See FIXME above. */
5757 if (!target_async_permitted)
5758 rs->wait_forever_enabled_p = 1;
5759
5760 rs->remote_desc = remote_serial_open (name);
5761 if (!rs->remote_desc)
5762 perror_with_name (name);
5763
5764 if (baud_rate != -1)
5765 {
5766 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5767 {
5768 /* The requested speed could not be set. Error out to
5769 top level after closing remote_desc. Take care to
5770 set remote_desc to NULL to avoid closing remote_desc
5771 more than once. */
5772 serial_close (rs->remote_desc);
5773 rs->remote_desc = NULL;
5774 perror_with_name (name);
5775 }
5776 }
5777
5778 serial_setparity (rs->remote_desc, serial_parity);
5779 serial_raw (rs->remote_desc);
5780
5781 /* If there is something sitting in the buffer we might take it as a
5782 response to a command, which would be bad. */
5783 serial_flush_input (rs->remote_desc);
5784
5785 if (from_tty)
5786 {
5787 gdb_puts ("Remote debugging using ");
5788 gdb_puts (name);
5789 gdb_puts ("\n");
5790 }
5791
5792 /* Switch to using the remote target now. */
5793 current_inferior ()->push_target (std::move (target_holder));
5794
5795 /* Register extra event sources in the event loop. */
5796 rs->remote_async_inferior_event_token
5797 = create_async_event_handler (remote_async_inferior_event_handler, nullptr,
5798 "remote");
5799 rs->notif_state = remote_notif_state_allocate (remote);
5800
5801 /* Reset the target state; these things will be queried either by
5802 remote_query_supported or as they are needed. */
5803 reset_all_packet_configs_support ();
5804 rs->explicit_packet_size = 0;
5805 rs->noack_mode = 0;
5806 rs->extended = extended_p;
5807 rs->waiting_for_stop_reply = 0;
5808 rs->ctrlc_pending_p = 0;
5809 rs->got_ctrlc_during_io = 0;
5810
5811 rs->general_thread = not_sent_ptid;
5812 rs->continue_thread = not_sent_ptid;
5813 rs->remote_traceframe_number = -1;
5814
5815 rs->last_resume_exec_dir = EXEC_FORWARD;
5816
5817 /* Probe for ability to use "ThreadInfo" query, as required. */
5818 rs->use_threadinfo_query = 1;
5819 rs->use_threadextra_query = 1;
5820
5821 rs->readahead_cache.invalidate ();
5822
5823 if (target_async_permitted)
5824 {
5825 /* FIXME: cagney/1999-09-23: During the initial connection it is
5826 assumed that the target is already ready and able to respond to
5827 requests. Unfortunately remote_start_remote() eventually calls
5828 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5829 around this. Eventually a mechanism that allows
5830 wait_for_inferior() to expect/get timeouts will be
5831 implemented. */
5832 rs->wait_forever_enabled_p = 0;
5833 }
5834
5835 /* First delete any symbols previously loaded from shared libraries. */
5836 no_shared_libraries (NULL, 0);
5837
5838 /* Start the remote connection. If error() or QUIT, discard this
5839 target (we'd otherwise be in an inconsistent state) and then
5840 propogate the error on up the exception chain. This ensures that
5841 the caller doesn't stumble along blindly assuming that the
5842 function succeeded. The CLI doesn't have this problem but other
5843 UI's, such as MI do.
5844
5845 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5846 this function should return an error indication letting the
5847 caller restore the previous state. Unfortunately the command
5848 ``target remote'' is directly wired to this function making that
5849 impossible. On a positive note, the CLI side of this problem has
5850 been fixed - the function set_cmd_context() makes it possible for
5851 all the ``target ....'' commands to share a common callback
5852 function. See cli-dump.c. */
5853 {
5854
5855 try
5856 {
5857 remote->start_remote (from_tty, extended_p);
5858 }
5859 catch (const gdb_exception &ex)
5860 {
5861 /* Pop the partially set up target - unless something else did
5862 already before throwing the exception. */
5863 if (ex.error != TARGET_CLOSE_ERROR)
5864 remote_unpush_target (remote);
5865 throw;
5866 }
5867 }
5868
5869 remote_btrace_reset (rs);
5870
5871 if (target_async_permitted)
5872 rs->wait_forever_enabled_p = 1;
5873 }
5874
5875 /* Determine if WS represents a fork status. */
5876
5877 static bool
5878 is_fork_status (target_waitkind kind)
5879 {
5880 return (kind == TARGET_WAITKIND_FORKED
5881 || kind == TARGET_WAITKIND_VFORKED);
5882 }
5883
5884 /* Return THREAD's pending status if it is a pending fork parent, else
5885 return nullptr. */
5886
5887 static const target_waitstatus *
5888 thread_pending_fork_status (struct thread_info *thread)
5889 {
5890 const target_waitstatus &ws
5891 = (thread->has_pending_waitstatus ()
5892 ? thread->pending_waitstatus ()
5893 : thread->pending_follow);
5894
5895 if (!is_fork_status (ws.kind ()))
5896 return nullptr;
5897
5898 return &ws;
5899 }
5900
5901 /* Detach the specified process. */
5902
5903 void
5904 remote_target::remote_detach_pid (int pid)
5905 {
5906 struct remote_state *rs = get_remote_state ();
5907
5908 /* This should not be necessary, but the handling for D;PID in
5909 GDBserver versions prior to 8.2 incorrectly assumes that the
5910 selected process points to the same process we're detaching,
5911 leading to misbehavior (and possibly GDBserver crashing) when it
5912 does not. Since it's easy and cheap, work around it by forcing
5913 GDBserver to select GDB's current process. */
5914 set_general_process ();
5915
5916 if (remote_multi_process_p (rs))
5917 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
5918 else
5919 strcpy (rs->buf.data (), "D");
5920
5921 putpkt (rs->buf);
5922 getpkt (&rs->buf, 0);
5923
5924 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5925 ;
5926 else if (rs->buf[0] == '\0')
5927 error (_("Remote doesn't know how to detach"));
5928 else
5929 error (_("Can't detach process."));
5930 }
5931
5932 /* This detaches a program to which we previously attached, using
5933 inferior_ptid to identify the process. After this is done, GDB
5934 can be used to debug some other program. We better not have left
5935 any breakpoints in the target program or it'll die when it hits
5936 one. */
5937
5938 void
5939 remote_target::remote_detach_1 (inferior *inf, int from_tty)
5940 {
5941 int pid = inferior_ptid.pid ();
5942 struct remote_state *rs = get_remote_state ();
5943 int is_fork_parent;
5944
5945 if (!target_has_execution ())
5946 error (_("No process to detach from."));
5947
5948 target_announce_detach (from_tty);
5949
5950 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
5951 {
5952 /* If we're in breakpoints-always-inserted mode, or the inferior
5953 is running, we have to remove breakpoints before detaching.
5954 We don't do this in common code instead because not all
5955 targets support removing breakpoints while the target is
5956 running. The remote target / gdbserver does, though. */
5957 remove_breakpoints_inf (current_inferior ());
5958 }
5959
5960 /* Tell the remote target to detach. */
5961 remote_detach_pid (pid);
5962
5963 /* Exit only if this is the only active inferior. */
5964 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
5965 gdb_puts (_("Ending remote debugging.\n"));
5966
5967 /* See if any thread of the inferior we are detaching has a pending fork
5968 status. In that case, we must detach from the child resulting from
5969 that fork. */
5970 for (thread_info *thread : inf->non_exited_threads ())
5971 {
5972 const target_waitstatus *ws = thread_pending_fork_status (thread);
5973
5974 if (ws == nullptr)
5975 continue;
5976
5977 remote_detach_pid (ws->child_ptid ().pid ());
5978 }
5979
5980 /* Check also for any pending fork events in the stop reply queue. */
5981 remote_notif_get_pending_events (&notif_client_stop);
5982 for (stop_reply_up &reply : rs->stop_reply_queue)
5983 {
5984 if (reply->ptid.pid () != pid)
5985 continue;
5986
5987 if (!is_fork_status (reply->ws.kind ()))
5988 continue;
5989
5990 remote_detach_pid (reply->ws.child_ptid ().pid ());
5991 }
5992
5993 thread_info *tp = find_thread_ptid (this, inferior_ptid);
5994
5995 /* Check to see if we are detaching a fork parent. Note that if we
5996 are detaching a fork child, tp == NULL. */
5997 is_fork_parent = (tp != NULL
5998 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
5999
6000 /* If doing detach-on-fork, we don't mourn, because that will delete
6001 breakpoints that should be available for the followed inferior. */
6002 if (!is_fork_parent)
6003 {
6004 /* Save the pid as a string before mourning, since that will
6005 unpush the remote target, and we need the string after. */
6006 std::string infpid = target_pid_to_str (ptid_t (pid));
6007
6008 target_mourn_inferior (inferior_ptid);
6009 if (print_inferior_events)
6010 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6011 inf->num, infpid.c_str ());
6012 }
6013 else
6014 {
6015 switch_to_no_thread ();
6016 detach_inferior (current_inferior ());
6017 }
6018 }
6019
6020 void
6021 remote_target::detach (inferior *inf, int from_tty)
6022 {
6023 remote_detach_1 (inf, from_tty);
6024 }
6025
6026 void
6027 extended_remote_target::detach (inferior *inf, int from_tty)
6028 {
6029 remote_detach_1 (inf, from_tty);
6030 }
6031
6032 /* Target follow-fork function for remote targets. On entry, and
6033 at return, the current inferior is the fork parent.
6034
6035 Note that although this is currently only used for extended-remote,
6036 it is named remote_follow_fork in anticipation of using it for the
6037 remote target as well. */
6038
6039 void
6040 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6041 target_waitkind fork_kind, bool follow_child,
6042 bool detach_fork)
6043 {
6044 process_stratum_target::follow_fork (child_inf, child_ptid,
6045 fork_kind, follow_child, detach_fork);
6046
6047 struct remote_state *rs = get_remote_state ();
6048
6049 if ((fork_kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
6050 || (fork_kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
6051 {
6052 /* When following the parent and detaching the child, we detach
6053 the child here. For the case of following the child and
6054 detaching the parent, the detach is done in the target-
6055 independent follow fork code in infrun.c. We can't use
6056 target_detach when detaching an unfollowed child because
6057 the client side doesn't know anything about the child. */
6058 if (detach_fork && !follow_child)
6059 {
6060 /* Detach the fork child. */
6061 remote_detach_pid (child_ptid.pid ());
6062 }
6063 }
6064 }
6065
6066 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6067 in the program space of the new inferior. */
6068
6069 void
6070 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6071 const char *execd_pathname)
6072 {
6073 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6074
6075 /* We know that this is a target file name, so if it has the "target:"
6076 prefix we strip it off before saving it in the program space. */
6077 if (is_target_filename (execd_pathname))
6078 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6079
6080 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6081 }
6082
6083 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6084
6085 void
6086 remote_target::disconnect (const char *args, int from_tty)
6087 {
6088 if (args)
6089 error (_("Argument given to \"disconnect\" when remotely debugging."));
6090
6091 /* Make sure we unpush even the extended remote targets. Calling
6092 target_mourn_inferior won't unpush, and
6093 remote_target::mourn_inferior won't unpush if there is more than
6094 one inferior left. */
6095 remote_unpush_target (this);
6096
6097 if (from_tty)
6098 gdb_puts ("Ending remote debugging.\n");
6099 }
6100
6101 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6102 be chatty about it. */
6103
6104 void
6105 extended_remote_target::attach (const char *args, int from_tty)
6106 {
6107 struct remote_state *rs = get_remote_state ();
6108 int pid;
6109 char *wait_status = NULL;
6110
6111 pid = parse_pid_to_attach (args);
6112
6113 /* Remote PID can be freely equal to getpid, do not check it here the same
6114 way as in other targets. */
6115
6116 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
6117 error (_("This target does not support attaching to a process"));
6118
6119 target_announce_attach (from_tty, pid);
6120
6121 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6122 putpkt (rs->buf);
6123 getpkt (&rs->buf, 0);
6124
6125 switch (packet_ok (rs->buf,
6126 &remote_protocol_packets[PACKET_vAttach]))
6127 {
6128 case PACKET_OK:
6129 if (!target_is_non_stop_p ())
6130 {
6131 /* Save the reply for later. */
6132 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6133 strcpy (wait_status, rs->buf.data ());
6134 }
6135 else if (strcmp (rs->buf.data (), "OK") != 0)
6136 error (_("Attaching to %s failed with: %s"),
6137 target_pid_to_str (ptid_t (pid)).c_str (),
6138 rs->buf.data ());
6139 break;
6140 case PACKET_UNKNOWN:
6141 error (_("This target does not support attaching to a process"));
6142 default:
6143 error (_("Attaching to %s failed"),
6144 target_pid_to_str (ptid_t (pid)).c_str ());
6145 }
6146
6147 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6148
6149 inferior_ptid = ptid_t (pid);
6150
6151 if (target_is_non_stop_p ())
6152 {
6153 /* Get list of threads. */
6154 update_thread_list ();
6155
6156 thread_info *thread = first_thread_of_inferior (current_inferior ());
6157 if (thread != nullptr)
6158 switch_to_thread (thread);
6159
6160 /* Invalidate our notion of the remote current thread. */
6161 record_currthread (rs, minus_one_ptid);
6162 }
6163 else
6164 {
6165 /* Now, if we have thread information, update the main thread's
6166 ptid. */
6167 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6168
6169 /* Add the main thread to the thread list. We add the thread
6170 silently in this case (the final true parameter). */
6171 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
6172
6173 switch_to_thread (thr);
6174 }
6175
6176 /* Next, if the target can specify a description, read it. We do
6177 this before anything involving memory or registers. */
6178 target_find_description ();
6179
6180 if (!target_is_non_stop_p ())
6181 {
6182 /* Use the previously fetched status. */
6183 gdb_assert (wait_status != NULL);
6184
6185 struct notif_event *reply
6186 = remote_notif_parse (this, &notif_client_stop, wait_status);
6187
6188 push_stop_reply ((struct stop_reply *) reply);
6189 }
6190 else
6191 {
6192 gdb_assert (wait_status == NULL);
6193
6194 gdb_assert (target_can_async_p ());
6195 }
6196 }
6197
6198 /* Implementation of the to_post_attach method. */
6199
6200 void
6201 extended_remote_target::post_attach (int pid)
6202 {
6203 /* Get text, data & bss offsets. */
6204 get_offsets ();
6205
6206 /* In certain cases GDB might not have had the chance to start
6207 symbol lookup up until now. This could happen if the debugged
6208 binary is not using shared libraries, the vsyscall page is not
6209 present (on Linux) and the binary itself hadn't changed since the
6210 debugging process was started. */
6211 if (current_program_space->symfile_object_file != NULL)
6212 remote_check_symbols();
6213 }
6214
6215 \f
6216 /* Check for the availability of vCont. This function should also check
6217 the response. */
6218
6219 void
6220 remote_target::remote_vcont_probe ()
6221 {
6222 remote_state *rs = get_remote_state ();
6223 char *buf;
6224
6225 strcpy (rs->buf.data (), "vCont?");
6226 putpkt (rs->buf);
6227 getpkt (&rs->buf, 0);
6228 buf = rs->buf.data ();
6229
6230 /* Make sure that the features we assume are supported. */
6231 if (startswith (buf, "vCont"))
6232 {
6233 char *p = &buf[5];
6234 int support_c, support_C;
6235
6236 rs->supports_vCont.s = 0;
6237 rs->supports_vCont.S = 0;
6238 support_c = 0;
6239 support_C = 0;
6240 rs->supports_vCont.t = 0;
6241 rs->supports_vCont.r = 0;
6242 while (p && *p == ';')
6243 {
6244 p++;
6245 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6246 rs->supports_vCont.s = 1;
6247 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6248 rs->supports_vCont.S = 1;
6249 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6250 support_c = 1;
6251 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6252 support_C = 1;
6253 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6254 rs->supports_vCont.t = 1;
6255 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6256 rs->supports_vCont.r = 1;
6257
6258 p = strchr (p, ';');
6259 }
6260
6261 /* If c, and C are not all supported, we can't use vCont. Clearing
6262 BUF will make packet_ok disable the packet. */
6263 if (!support_c || !support_C)
6264 buf[0] = 0;
6265 }
6266
6267 packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCont]);
6268 rs->supports_vCont_probed = true;
6269 }
6270
6271 /* Helper function for building "vCont" resumptions. Write a
6272 resumption to P. ENDP points to one-passed-the-end of the buffer
6273 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6274 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6275 resumed thread should be single-stepped and/or signalled. If PTID
6276 equals minus_one_ptid, then all threads are resumed; if PTID
6277 represents a process, then all threads of the process are resumed;
6278 the thread to be stepped and/or signalled is given in the global
6279 INFERIOR_PTID. */
6280
6281 char *
6282 remote_target::append_resumption (char *p, char *endp,
6283 ptid_t ptid, int step, gdb_signal siggnal)
6284 {
6285 struct remote_state *rs = get_remote_state ();
6286
6287 if (step && siggnal != GDB_SIGNAL_0)
6288 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6289 else if (step
6290 /* GDB is willing to range step. */
6291 && use_range_stepping
6292 /* Target supports range stepping. */
6293 && rs->supports_vCont.r
6294 /* We don't currently support range stepping multiple
6295 threads with a wildcard (though the protocol allows it,
6296 so stubs shouldn't make an active effort to forbid
6297 it). */
6298 && !(remote_multi_process_p (rs) && ptid.is_pid ()))
6299 {
6300 struct thread_info *tp;
6301
6302 if (ptid == minus_one_ptid)
6303 {
6304 /* If we don't know about the target thread's tid, then
6305 we're resuming magic_null_ptid (see caller). */
6306 tp = find_thread_ptid (this, magic_null_ptid);
6307 }
6308 else
6309 tp = find_thread_ptid (this, ptid);
6310 gdb_assert (tp != NULL);
6311
6312 if (tp->control.may_range_step)
6313 {
6314 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6315
6316 p += xsnprintf (p, endp - p, ";r%s,%s",
6317 phex_nz (tp->control.step_range_start,
6318 addr_size),
6319 phex_nz (tp->control.step_range_end,
6320 addr_size));
6321 }
6322 else
6323 p += xsnprintf (p, endp - p, ";s");
6324 }
6325 else if (step)
6326 p += xsnprintf (p, endp - p, ";s");
6327 else if (siggnal != GDB_SIGNAL_0)
6328 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6329 else
6330 p += xsnprintf (p, endp - p, ";c");
6331
6332 if (remote_multi_process_p (rs) && ptid.is_pid ())
6333 {
6334 ptid_t nptid;
6335
6336 /* All (-1) threads of process. */
6337 nptid = ptid_t (ptid.pid (), -1);
6338
6339 p += xsnprintf (p, endp - p, ":");
6340 p = write_ptid (p, endp, nptid);
6341 }
6342 else if (ptid != minus_one_ptid)
6343 {
6344 p += xsnprintf (p, endp - p, ":");
6345 p = write_ptid (p, endp, ptid);
6346 }
6347
6348 return p;
6349 }
6350
6351 /* Clear the thread's private info on resume. */
6352
6353 static void
6354 resume_clear_thread_private_info (struct thread_info *thread)
6355 {
6356 if (thread->priv != NULL)
6357 {
6358 remote_thread_info *priv = get_remote_thread_info (thread);
6359
6360 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6361 priv->watch_data_address = 0;
6362 }
6363 }
6364
6365 /* Append a vCont continue-with-signal action for threads that have a
6366 non-zero stop signal. */
6367
6368 char *
6369 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6370 ptid_t ptid)
6371 {
6372 for (thread_info *thread : all_non_exited_threads (this, ptid))
6373 if (inferior_ptid != thread->ptid
6374 && thread->stop_signal () != GDB_SIGNAL_0)
6375 {
6376 p = append_resumption (p, endp, thread->ptid,
6377 0, thread->stop_signal ());
6378 thread->set_stop_signal (GDB_SIGNAL_0);
6379 resume_clear_thread_private_info (thread);
6380 }
6381
6382 return p;
6383 }
6384
6385 /* Set the target running, using the packets that use Hc
6386 (c/s/C/S). */
6387
6388 void
6389 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6390 gdb_signal siggnal)
6391 {
6392 struct remote_state *rs = get_remote_state ();
6393 char *buf;
6394
6395 rs->last_sent_signal = siggnal;
6396 rs->last_sent_step = step;
6397
6398 /* The c/s/C/S resume packets use Hc, so set the continue
6399 thread. */
6400 if (ptid == minus_one_ptid)
6401 set_continue_thread (any_thread_ptid);
6402 else
6403 set_continue_thread (ptid);
6404
6405 for (thread_info *thread : all_non_exited_threads (this))
6406 resume_clear_thread_private_info (thread);
6407
6408 buf = rs->buf.data ();
6409 if (::execution_direction == EXEC_REVERSE)
6410 {
6411 /* We don't pass signals to the target in reverse exec mode. */
6412 if (info_verbose && siggnal != GDB_SIGNAL_0)
6413 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6414 siggnal);
6415
6416 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6417 error (_("Remote reverse-step not supported."));
6418 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6419 error (_("Remote reverse-continue not supported."));
6420
6421 strcpy (buf, step ? "bs" : "bc");
6422 }
6423 else if (siggnal != GDB_SIGNAL_0)
6424 {
6425 buf[0] = step ? 'S' : 'C';
6426 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6427 buf[2] = tohex (((int) siggnal) & 0xf);
6428 buf[3] = '\0';
6429 }
6430 else
6431 strcpy (buf, step ? "s" : "c");
6432
6433 putpkt (buf);
6434 }
6435
6436 /* Resume the remote inferior by using a "vCont" packet. The thread
6437 to be resumed is PTID; STEP and SIGGNAL indicate whether the
6438 resumed thread should be single-stepped and/or signalled. If PTID
6439 equals minus_one_ptid, then all threads are resumed; the thread to
6440 be stepped and/or signalled is given in the global INFERIOR_PTID.
6441 This function returns non-zero iff it resumes the inferior.
6442
6443 This function issues a strict subset of all possible vCont commands
6444 at the moment. */
6445
6446 int
6447 remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6448 enum gdb_signal siggnal)
6449 {
6450 struct remote_state *rs = get_remote_state ();
6451 char *p;
6452 char *endp;
6453
6454 /* No reverse execution actions defined for vCont. */
6455 if (::execution_direction == EXEC_REVERSE)
6456 return 0;
6457
6458 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6459 remote_vcont_probe ();
6460
6461 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6462 return 0;
6463
6464 p = rs->buf.data ();
6465 endp = p + get_remote_packet_size ();
6466
6467 /* If we could generate a wider range of packets, we'd have to worry
6468 about overflowing BUF. Should there be a generic
6469 "multi-part-packet" packet? */
6470
6471 p += xsnprintf (p, endp - p, "vCont");
6472
6473 if (ptid == magic_null_ptid)
6474 {
6475 /* MAGIC_NULL_PTID means that we don't have any active threads,
6476 so we don't have any TID numbers the inferior will
6477 understand. Make sure to only send forms that do not specify
6478 a TID. */
6479 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6480 }
6481 else if (ptid == minus_one_ptid || ptid.is_pid ())
6482 {
6483 /* Resume all threads (of all processes, or of a single
6484 process), with preference for INFERIOR_PTID. This assumes
6485 inferior_ptid belongs to the set of all threads we are about
6486 to resume. */
6487 if (step || siggnal != GDB_SIGNAL_0)
6488 {
6489 /* Step inferior_ptid, with or without signal. */
6490 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6491 }
6492
6493 /* Also pass down any pending signaled resumption for other
6494 threads not the current. */
6495 p = append_pending_thread_resumptions (p, endp, ptid);
6496
6497 /* And continue others without a signal. */
6498 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
6499 }
6500 else
6501 {
6502 /* Scheduler locking; resume only PTID. */
6503 append_resumption (p, endp, ptid, step, siggnal);
6504 }
6505
6506 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6507 putpkt (rs->buf);
6508
6509 if (target_is_non_stop_p ())
6510 {
6511 /* In non-stop, the stub replies to vCont with "OK". The stop
6512 reply will be reported asynchronously by means of a `%Stop'
6513 notification. */
6514 getpkt (&rs->buf, 0);
6515 if (strcmp (rs->buf.data (), "OK") != 0)
6516 error (_("Unexpected vCont reply in non-stop mode: %s"),
6517 rs->buf.data ());
6518 }
6519
6520 return 1;
6521 }
6522
6523 /* Tell the remote machine to resume. */
6524
6525 void
6526 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
6527 {
6528 struct remote_state *rs = get_remote_state ();
6529
6530 /* When connected in non-stop mode, the core resumes threads
6531 individually. Resuming remote threads directly in target_resume
6532 would thus result in sending one packet per thread. Instead, to
6533 minimize roundtrip latency, here we just store the resume
6534 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6535 resumption will be done in remote_target::commit_resume, where we'll be
6536 able to do vCont action coalescing. */
6537 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6538 {
6539 remote_thread_info *remote_thr;
6540
6541 if (minus_one_ptid == ptid || ptid.is_pid ())
6542 remote_thr = get_remote_thread_info (this, inferior_ptid);
6543 else
6544 remote_thr = get_remote_thread_info (this, ptid);
6545
6546 /* We don't expect the core to ask to resume an already resumed (from
6547 its point of view) thread. */
6548 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6549
6550 remote_thr->set_resumed_pending_vcont (step, siggnal);
6551 return;
6552 }
6553
6554 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6555 (explained in remote-notif.c:handle_notification) so
6556 remote_notif_process is not called. We need find a place where
6557 it is safe to start a 'vNotif' sequence. It is good to do it
6558 before resuming inferior, because inferior was stopped and no RSP
6559 traffic at that moment. */
6560 if (!target_is_non_stop_p ())
6561 remote_notif_process (rs->notif_state, &notif_client_stop);
6562
6563 rs->last_resume_exec_dir = ::execution_direction;
6564
6565 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6566 if (!remote_resume_with_vcont (ptid, step, siggnal))
6567 remote_resume_with_hc (ptid, step, siggnal);
6568
6569 /* Update resumed state tracked by the remote target. */
6570 for (thread_info *tp : all_non_exited_threads (this, ptid))
6571 get_remote_thread_info (tp)->set_resumed ();
6572
6573 /* We've just told the target to resume. The remote server will
6574 wait for the inferior to stop, and then send a stop reply. In
6575 the mean time, we can't start another command/query ourselves
6576 because the stub wouldn't be ready to process it. This applies
6577 only to the base all-stop protocol, however. In non-stop (which
6578 only supports vCont), the stub replies with an "OK", and is
6579 immediate able to process further serial input. */
6580 if (!target_is_non_stop_p ())
6581 rs->waiting_for_stop_reply = 1;
6582 }
6583
6584 /* Private per-inferior info for target remote processes. */
6585
6586 struct remote_inferior : public private_inferior
6587 {
6588 /* Whether we can send a wildcard vCont for this process. */
6589 bool may_wildcard_vcont = true;
6590 };
6591
6592 /* Get the remote private inferior data associated to INF. */
6593
6594 static remote_inferior *
6595 get_remote_inferior (inferior *inf)
6596 {
6597 if (inf->priv == NULL)
6598 inf->priv.reset (new remote_inferior);
6599
6600 return static_cast<remote_inferior *> (inf->priv.get ());
6601 }
6602
6603 /* Class used to track the construction of a vCont packet in the
6604 outgoing packet buffer. This is used to send multiple vCont
6605 packets if we have more actions than would fit a single packet. */
6606
6607 class vcont_builder
6608 {
6609 public:
6610 explicit vcont_builder (remote_target *remote)
6611 : m_remote (remote)
6612 {
6613 restart ();
6614 }
6615
6616 void flush ();
6617 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6618
6619 private:
6620 void restart ();
6621
6622 /* The remote target. */
6623 remote_target *m_remote;
6624
6625 /* Pointer to the first action. P points here if no action has been
6626 appended yet. */
6627 char *m_first_action;
6628
6629 /* Where the next action will be appended. */
6630 char *m_p;
6631
6632 /* The end of the buffer. Must never write past this. */
6633 char *m_endp;
6634 };
6635
6636 /* Prepare the outgoing buffer for a new vCont packet. */
6637
6638 void
6639 vcont_builder::restart ()
6640 {
6641 struct remote_state *rs = m_remote->get_remote_state ();
6642
6643 m_p = rs->buf.data ();
6644 m_endp = m_p + m_remote->get_remote_packet_size ();
6645 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6646 m_first_action = m_p;
6647 }
6648
6649 /* If the vCont packet being built has any action, send it to the
6650 remote end. */
6651
6652 void
6653 vcont_builder::flush ()
6654 {
6655 struct remote_state *rs;
6656
6657 if (m_p == m_first_action)
6658 return;
6659
6660 rs = m_remote->get_remote_state ();
6661 m_remote->putpkt (rs->buf);
6662 m_remote->getpkt (&rs->buf, 0);
6663 if (strcmp (rs->buf.data (), "OK") != 0)
6664 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
6665 }
6666
6667 /* The largest action is range-stepping, with its two addresses. This
6668 is more than sufficient. If a new, bigger action is created, it'll
6669 quickly trigger a failed assertion in append_resumption (and we'll
6670 just bump this). */
6671 #define MAX_ACTION_SIZE 200
6672
6673 /* Append a new vCont action in the outgoing packet being built. If
6674 the action doesn't fit the packet along with previous actions, push
6675 what we've got so far to the remote end and start over a new vCont
6676 packet (with the new action). */
6677
6678 void
6679 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6680 {
6681 char buf[MAX_ACTION_SIZE + 1];
6682
6683 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6684 ptid, step, siggnal);
6685
6686 /* Check whether this new action would fit in the vCont packet along
6687 with previous actions. If not, send what we've got so far and
6688 start a new vCont packet. */
6689 size_t rsize = endp - buf;
6690 if (rsize > m_endp - m_p)
6691 {
6692 flush ();
6693 restart ();
6694
6695 /* Should now fit. */
6696 gdb_assert (rsize <= m_endp - m_p);
6697 }
6698
6699 memcpy (m_p, buf, rsize);
6700 m_p += rsize;
6701 *m_p = '\0';
6702 }
6703
6704 /* to_commit_resume implementation. */
6705
6706 void
6707 remote_target::commit_resumed ()
6708 {
6709 /* If connected in all-stop mode, we'd send the remote resume
6710 request directly from remote_resume. Likewise if
6711 reverse-debugging, as there are no defined vCont actions for
6712 reverse execution. */
6713 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6714 return;
6715
6716 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6717 instead of resuming all threads of each process individually.
6718 However, if any thread of a process must remain halted, we can't
6719 send wildcard resumes and must send one action per thread.
6720
6721 Care must be taken to not resume threads/processes the server
6722 side already told us are stopped, but the core doesn't know about
6723 yet, because the events are still in the vStopped notification
6724 queue. For example:
6725
6726 #1 => vCont s:p1.1;c
6727 #2 <= OK
6728 #3 <= %Stopped T05 p1.1
6729 #4 => vStopped
6730 #5 <= T05 p1.2
6731 #6 => vStopped
6732 #7 <= OK
6733 #8 (infrun handles the stop for p1.1 and continues stepping)
6734 #9 => vCont s:p1.1;c
6735
6736 The last vCont above would resume thread p1.2 by mistake, because
6737 the server has no idea that the event for p1.2 had not been
6738 handled yet.
6739
6740 The server side must similarly ignore resume actions for the
6741 thread that has a pending %Stopped notification (and any other
6742 threads with events pending), until GDB acks the notification
6743 with vStopped. Otherwise, e.g., the following case is
6744 mishandled:
6745
6746 #1 => g (or any other packet)
6747 #2 <= [registers]
6748 #3 <= %Stopped T05 p1.2
6749 #4 => vCont s:p1.1;c
6750 #5 <= OK
6751
6752 Above, the server must not resume thread p1.2. GDB can't know
6753 that p1.2 stopped until it acks the %Stopped notification, and
6754 since from GDB's perspective all threads should be running, it
6755 sends a "c" action.
6756
6757 Finally, special care must also be given to handling fork/vfork
6758 events. A (v)fork event actually tells us that two processes
6759 stopped -- the parent and the child. Until we follow the fork,
6760 we must not resume the child. Therefore, if we have a pending
6761 fork follow, we must not send a global wildcard resume action
6762 (vCont;c). We can still send process-wide wildcards though. */
6763
6764 /* Start by assuming a global wildcard (vCont;c) is possible. */
6765 bool may_global_wildcard_vcont = true;
6766
6767 /* And assume every process is individually wildcard-able too. */
6768 for (inferior *inf : all_non_exited_inferiors (this))
6769 {
6770 remote_inferior *priv = get_remote_inferior (inf);
6771
6772 priv->may_wildcard_vcont = true;
6773 }
6774
6775 /* Check for any pending events (not reported or processed yet) and
6776 disable process and global wildcard resumes appropriately. */
6777 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6778
6779 bool any_pending_vcont_resume = false;
6780
6781 for (thread_info *tp : all_non_exited_threads (this))
6782 {
6783 remote_thread_info *priv = get_remote_thread_info (tp);
6784
6785 /* If a thread of a process is not meant to be resumed, then we
6786 can't wildcard that process. */
6787 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
6788 {
6789 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6790
6791 /* And if we can't wildcard a process, we can't wildcard
6792 everything either. */
6793 may_global_wildcard_vcont = false;
6794 continue;
6795 }
6796
6797 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
6798 any_pending_vcont_resume = true;
6799
6800 /* If a thread is the parent of an unfollowed fork, then we
6801 can't do a global wildcard, as that would resume the fork
6802 child. */
6803 if (thread_pending_fork_status (tp) != nullptr)
6804 may_global_wildcard_vcont = false;
6805 }
6806
6807 /* We didn't have any resumed thread pending a vCont resume, so nothing to
6808 do. */
6809 if (!any_pending_vcont_resume)
6810 return;
6811
6812 /* Now let's build the vCont packet(s). Actions must be appended
6813 from narrower to wider scopes (thread -> process -> global). If
6814 we end up with too many actions for a single packet vcont_builder
6815 flushes the current vCont packet to the remote side and starts a
6816 new one. */
6817 struct vcont_builder vcont_builder (this);
6818
6819 /* Threads first. */
6820 for (thread_info *tp : all_non_exited_threads (this))
6821 {
6822 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6823
6824 /* If the thread was previously vCont-resumed, no need to send a specific
6825 action for it. If we didn't receive a resume request for it, don't
6826 send an action for it either. */
6827 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
6828 continue;
6829
6830 gdb_assert (!thread_is_in_step_over_chain (tp));
6831
6832 /* We should never be commit-resuming a thread that has a stop reply.
6833 Otherwise, we would end up reporting a stop event for a thread while
6834 it is running on the remote target. */
6835 remote_state *rs = get_remote_state ();
6836 for (const auto &stop_reply : rs->stop_reply_queue)
6837 gdb_assert (stop_reply->ptid != tp->ptid);
6838
6839 const resumed_pending_vcont_info &info
6840 = remote_thr->resumed_pending_vcont_info ();
6841
6842 /* Check if we need to send a specific action for this thread. If not,
6843 it will be included in a wildcard resume instead. */
6844 if (info.step || info.sig != GDB_SIGNAL_0
6845 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
6846 vcont_builder.push_action (tp->ptid, info.step, info.sig);
6847
6848 remote_thr->set_resumed ();
6849 }
6850
6851 /* Now check whether we can send any process-wide wildcard. This is
6852 to avoid sending a global wildcard in the case nothing is
6853 supposed to be resumed. */
6854 bool any_process_wildcard = false;
6855
6856 for (inferior *inf : all_non_exited_inferiors (this))
6857 {
6858 if (get_remote_inferior (inf)->may_wildcard_vcont)
6859 {
6860 any_process_wildcard = true;
6861 break;
6862 }
6863 }
6864
6865 if (any_process_wildcard)
6866 {
6867 /* If all processes are wildcard-able, then send a single "c"
6868 action, otherwise, send an "all (-1) threads of process"
6869 continue action for each running process, if any. */
6870 if (may_global_wildcard_vcont)
6871 {
6872 vcont_builder.push_action (minus_one_ptid,
6873 false, GDB_SIGNAL_0);
6874 }
6875 else
6876 {
6877 for (inferior *inf : all_non_exited_inferiors (this))
6878 {
6879 if (get_remote_inferior (inf)->may_wildcard_vcont)
6880 {
6881 vcont_builder.push_action (ptid_t (inf->pid),
6882 false, GDB_SIGNAL_0);
6883 }
6884 }
6885 }
6886 }
6887
6888 vcont_builder.flush ();
6889 }
6890
6891 /* Implementation of target_has_pending_events. */
6892
6893 bool
6894 remote_target::has_pending_events ()
6895 {
6896 if (target_can_async_p ())
6897 {
6898 remote_state *rs = get_remote_state ();
6899
6900 if (async_event_handler_marked (rs->remote_async_inferior_event_token))
6901 return true;
6902
6903 /* Note that BUFCNT can be negative, indicating sticky
6904 error. */
6905 if (rs->remote_desc->bufcnt != 0)
6906 return true;
6907 }
6908 return false;
6909 }
6910
6911 \f
6912
6913 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6914 thread, all threads of a remote process, or all threads of all
6915 processes. */
6916
6917 void
6918 remote_target::remote_stop_ns (ptid_t ptid)
6919 {
6920 struct remote_state *rs = get_remote_state ();
6921 char *p = rs->buf.data ();
6922 char *endp = p + get_remote_packet_size ();
6923
6924 /* If any thread that needs to stop was resumed but pending a vCont
6925 resume, generate a phony stop_reply. However, first check
6926 whether the thread wasn't resumed with a signal. Generating a
6927 phony stop in that case would result in losing the signal. */
6928 bool needs_commit = false;
6929 for (thread_info *tp : all_non_exited_threads (this, ptid))
6930 {
6931 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6932
6933 if (remote_thr->get_resume_state ()
6934 == resume_state::RESUMED_PENDING_VCONT)
6935 {
6936 const resumed_pending_vcont_info &info
6937 = remote_thr->resumed_pending_vcont_info ();
6938 if (info.sig != GDB_SIGNAL_0)
6939 {
6940 /* This signal must be forwarded to the inferior. We
6941 could commit-resume just this thread, but its simpler
6942 to just commit-resume everything. */
6943 needs_commit = true;
6944 break;
6945 }
6946 }
6947 }
6948
6949 if (needs_commit)
6950 commit_resumed ();
6951 else
6952 for (thread_info *tp : all_non_exited_threads (this, ptid))
6953 {
6954 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6955
6956 if (remote_thr->get_resume_state ()
6957 == resume_state::RESUMED_PENDING_VCONT)
6958 {
6959 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
6960 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
6961 tp->ptid.lwp (),
6962 pulongest (tp->ptid.tid ()));
6963
6964 /* Check that the thread wasn't resumed with a signal.
6965 Generating a phony stop would result in losing the
6966 signal. */
6967 const resumed_pending_vcont_info &info
6968 = remote_thr->resumed_pending_vcont_info ();
6969 gdb_assert (info.sig == GDB_SIGNAL_0);
6970
6971 stop_reply *sr = new stop_reply ();
6972 sr->ptid = tp->ptid;
6973 sr->rs = rs;
6974 sr->ws.set_stopped (GDB_SIGNAL_0);
6975 sr->arch = tp->inf->gdbarch;
6976 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6977 sr->watch_data_address = 0;
6978 sr->core = 0;
6979 this->push_stop_reply (sr);
6980
6981 /* Pretend that this thread was actually resumed on the
6982 remote target, then stopped. If we leave it in the
6983 RESUMED_PENDING_VCONT state and the commit_resumed
6984 method is called while the stop reply is still in the
6985 queue, we'll end up reporting a stop event to the core
6986 for that thread while it is running on the remote
6987 target... that would be bad. */
6988 remote_thr->set_resumed ();
6989 }
6990 }
6991
6992 /* FIXME: This supports_vCont_probed check is a workaround until
6993 packet_support is per-connection. */
6994 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN
6995 || !rs->supports_vCont_probed)
6996 remote_vcont_probe ();
6997
6998 if (!rs->supports_vCont.t)
6999 error (_("Remote server does not support stopping threads"));
7000
7001 if (ptid == minus_one_ptid
7002 || (!remote_multi_process_p (rs) && ptid.is_pid ()))
7003 p += xsnprintf (p, endp - p, "vCont;t");
7004 else
7005 {
7006 ptid_t nptid;
7007
7008 p += xsnprintf (p, endp - p, "vCont;t:");
7009
7010 if (ptid.is_pid ())
7011 /* All (-1) threads of process. */
7012 nptid = ptid_t (ptid.pid (), -1);
7013 else
7014 {
7015 /* Small optimization: if we already have a stop reply for
7016 this thread, no use in telling the stub we want this
7017 stopped. */
7018 if (peek_stop_reply (ptid))
7019 return;
7020
7021 nptid = ptid;
7022 }
7023
7024 write_ptid (p, endp, nptid);
7025 }
7026
7027 /* In non-stop, we get an immediate OK reply. The stop reply will
7028 come in asynchronously by notification. */
7029 putpkt (rs->buf);
7030 getpkt (&rs->buf, 0);
7031 if (strcmp (rs->buf.data (), "OK") != 0)
7032 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7033 rs->buf.data ());
7034 }
7035
7036 /* All-stop version of target_interrupt. Sends a break or a ^C to
7037 interrupt the remote target. It is undefined which thread of which
7038 process reports the interrupt. */
7039
7040 void
7041 remote_target::remote_interrupt_as ()
7042 {
7043 struct remote_state *rs = get_remote_state ();
7044
7045 rs->ctrlc_pending_p = 1;
7046
7047 /* If the inferior is stopped already, but the core didn't know
7048 about it yet, just ignore the request. The pending stop events
7049 will be collected in remote_wait. */
7050 if (stop_reply_queue_length () > 0)
7051 return;
7052
7053 /* Send interrupt_sequence to remote target. */
7054 send_interrupt_sequence ();
7055 }
7056
7057 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7058 the remote target. It is undefined which thread of which process
7059 reports the interrupt. Throws an error if the packet is not
7060 supported by the server. */
7061
7062 void
7063 remote_target::remote_interrupt_ns ()
7064 {
7065 struct remote_state *rs = get_remote_state ();
7066 char *p = rs->buf.data ();
7067 char *endp = p + get_remote_packet_size ();
7068
7069 xsnprintf (p, endp - p, "vCtrlC");
7070
7071 /* In non-stop, we get an immediate OK reply. The stop reply will
7072 come in asynchronously by notification. */
7073 putpkt (rs->buf);
7074 getpkt (&rs->buf, 0);
7075
7076 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
7077 {
7078 case PACKET_OK:
7079 break;
7080 case PACKET_UNKNOWN:
7081 error (_("No support for interrupting the remote target."));
7082 case PACKET_ERROR:
7083 error (_("Interrupting target failed: %s"), rs->buf.data ());
7084 }
7085 }
7086
7087 /* Implement the to_stop function for the remote targets. */
7088
7089 void
7090 remote_target::stop (ptid_t ptid)
7091 {
7092 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7093
7094 if (target_is_non_stop_p ())
7095 remote_stop_ns (ptid);
7096 else
7097 {
7098 /* We don't currently have a way to transparently pause the
7099 remote target in all-stop mode. Interrupt it instead. */
7100 remote_interrupt_as ();
7101 }
7102 }
7103
7104 /* Implement the to_interrupt function for the remote targets. */
7105
7106 void
7107 remote_target::interrupt ()
7108 {
7109 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7110
7111 if (target_is_non_stop_p ())
7112 remote_interrupt_ns ();
7113 else
7114 remote_interrupt_as ();
7115 }
7116
7117 /* Implement the to_pass_ctrlc function for the remote targets. */
7118
7119 void
7120 remote_target::pass_ctrlc ()
7121 {
7122 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7123
7124 struct remote_state *rs = get_remote_state ();
7125
7126 /* If we're starting up, we're not fully synced yet. Quit
7127 immediately. */
7128 if (rs->starting_up)
7129 quit ();
7130 /* If ^C has already been sent once, offer to disconnect. */
7131 else if (rs->ctrlc_pending_p)
7132 interrupt_query ();
7133 else
7134 target_interrupt ();
7135 }
7136
7137 /* Ask the user what to do when an interrupt is received. */
7138
7139 void
7140 remote_target::interrupt_query ()
7141 {
7142 struct remote_state *rs = get_remote_state ();
7143
7144 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7145 {
7146 if (query (_("The target is not responding to interrupt requests.\n"
7147 "Stop debugging it? ")))
7148 {
7149 remote_unpush_target (this);
7150 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7151 }
7152 }
7153 else
7154 {
7155 if (query (_("Interrupted while waiting for the program.\n"
7156 "Give up waiting? ")))
7157 quit ();
7158 }
7159 }
7160
7161 /* Enable/disable target terminal ownership. Most targets can use
7162 terminal groups to control terminal ownership. Remote targets are
7163 different in that explicit transfer of ownership to/from GDB/target
7164 is required. */
7165
7166 void
7167 remote_target::terminal_inferior ()
7168 {
7169 /* NOTE: At this point we could also register our selves as the
7170 recipient of all input. Any characters typed could then be
7171 passed on down to the target. */
7172 }
7173
7174 void
7175 remote_target::terminal_ours ()
7176 {
7177 }
7178
7179 static void
7180 remote_console_output (const char *msg)
7181 {
7182 const char *p;
7183
7184 for (p = msg; p[0] && p[1]; p += 2)
7185 {
7186 char tb[2];
7187 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7188
7189 tb[0] = c;
7190 tb[1] = 0;
7191 gdb_stdtarg->puts (tb);
7192 }
7193 gdb_stdtarg->flush ();
7194 }
7195
7196 /* Return the length of the stop reply queue. */
7197
7198 int
7199 remote_target::stop_reply_queue_length ()
7200 {
7201 remote_state *rs = get_remote_state ();
7202 return rs->stop_reply_queue.size ();
7203 }
7204
7205 static void
7206 remote_notif_stop_parse (remote_target *remote,
7207 struct notif_client *self, const char *buf,
7208 struct notif_event *event)
7209 {
7210 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7211 }
7212
7213 static void
7214 remote_notif_stop_ack (remote_target *remote,
7215 struct notif_client *self, const char *buf,
7216 struct notif_event *event)
7217 {
7218 struct stop_reply *stop_reply = (struct stop_reply *) event;
7219
7220 /* acknowledge */
7221 putpkt (remote, self->ack_command);
7222
7223 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7224 the notification. It was left in the queue because we need to
7225 acknowledge it and pull the rest of the notifications out. */
7226 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7227 remote->push_stop_reply (stop_reply);
7228 }
7229
7230 static int
7231 remote_notif_stop_can_get_pending_events (remote_target *remote,
7232 struct notif_client *self)
7233 {
7234 /* We can't get pending events in remote_notif_process for
7235 notification stop, and we have to do this in remote_wait_ns
7236 instead. If we fetch all queued events from stub, remote stub
7237 may exit and we have no chance to process them back in
7238 remote_wait_ns. */
7239 remote_state *rs = remote->get_remote_state ();
7240 mark_async_event_handler (rs->remote_async_inferior_event_token);
7241 return 0;
7242 }
7243
7244 stop_reply::~stop_reply ()
7245 {
7246 for (cached_reg_t &reg : regcache)
7247 xfree (reg.data);
7248 }
7249
7250 static notif_event_up
7251 remote_notif_stop_alloc_reply ()
7252 {
7253 return notif_event_up (new struct stop_reply ());
7254 }
7255
7256 /* A client of notification Stop. */
7257
7258 struct notif_client notif_client_stop =
7259 {
7260 "Stop",
7261 "vStopped",
7262 remote_notif_stop_parse,
7263 remote_notif_stop_ack,
7264 remote_notif_stop_can_get_pending_events,
7265 remote_notif_stop_alloc_reply,
7266 REMOTE_NOTIF_STOP,
7267 };
7268
7269 /* If CONTEXT contains any fork child threads that have not been
7270 reported yet, remove them from the CONTEXT list. If such a
7271 thread exists it is because we are stopped at a fork catchpoint
7272 and have not yet called follow_fork, which will set up the
7273 host-side data structures for the new process. */
7274
7275 void
7276 remote_target::remove_new_fork_children (threads_listing_context *context)
7277 {
7278 struct notif_client *notif = &notif_client_stop;
7279
7280 /* For any threads stopped at a fork event, remove the corresponding
7281 fork child threads from the CONTEXT list. */
7282 for (thread_info *thread : all_non_exited_threads (this))
7283 {
7284 const target_waitstatus *ws = thread_pending_fork_status (thread);
7285
7286 if (ws == nullptr)
7287 continue;
7288
7289 context->remove_thread (ws->child_ptid ());
7290 }
7291
7292 /* Check for any pending fork events (not reported or processed yet)
7293 in process PID and remove those fork child threads from the
7294 CONTEXT list as well. */
7295 remote_notif_get_pending_events (notif);
7296 for (auto &event : get_remote_state ()->stop_reply_queue)
7297 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7298 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7299 context->remove_thread (event->ws.child_ptid ());
7300 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7301 context->remove_thread (event->ptid);
7302 }
7303
7304 /* Check whether any event pending in the vStopped queue would prevent a
7305 global or process wildcard vCont action. Set *may_global_wildcard to
7306 false if we can't do a global wildcard (vCont;c), and clear the event
7307 inferior's may_wildcard_vcont flag if we can't do a process-wide
7308 wildcard resume (vCont;c:pPID.-1). */
7309
7310 void
7311 remote_target::check_pending_events_prevent_wildcard_vcont
7312 (bool *may_global_wildcard)
7313 {
7314 struct notif_client *notif = &notif_client_stop;
7315
7316 remote_notif_get_pending_events (notif);
7317 for (auto &event : get_remote_state ()->stop_reply_queue)
7318 {
7319 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7320 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7321 continue;
7322
7323 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7324 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7325 *may_global_wildcard = false;
7326
7327 /* This may be the first time we heard about this process.
7328 Regardless, we must not do a global wildcard resume, otherwise
7329 we'd resume this process too. */
7330 *may_global_wildcard = false;
7331 if (event->ptid != null_ptid)
7332 {
7333 inferior *inf = find_inferior_ptid (this, event->ptid);
7334 if (inf != NULL)
7335 get_remote_inferior (inf)->may_wildcard_vcont = false;
7336 }
7337 }
7338 }
7339
7340 /* Discard all pending stop replies of inferior INF. */
7341
7342 void
7343 remote_target::discard_pending_stop_replies (struct inferior *inf)
7344 {
7345 struct stop_reply *reply;
7346 struct remote_state *rs = get_remote_state ();
7347 struct remote_notif_state *rns = rs->notif_state;
7348
7349 /* This function can be notified when an inferior exists. When the
7350 target is not remote, the notification state is NULL. */
7351 if (rs->remote_desc == NULL)
7352 return;
7353
7354 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7355
7356 /* Discard the in-flight notification. */
7357 if (reply != NULL && reply->ptid.pid () == inf->pid)
7358 {
7359 /* Leave the notification pending, since the server expects that
7360 we acknowledge it with vStopped. But clear its contents, so
7361 that later on when we acknowledge it, we also discard it. */
7362 remote_debug_printf
7363 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7364 reply->ptid.to_string().c_str(),
7365 reply->ws.to_string ().c_str ());
7366 reply->ws.set_ignore ();
7367 }
7368
7369 /* Discard the stop replies we have already pulled with
7370 vStopped. */
7371 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7372 rs->stop_reply_queue.end (),
7373 [=] (const stop_reply_up &event)
7374 {
7375 return event->ptid.pid () == inf->pid;
7376 });
7377 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7378 remote_debug_printf
7379 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7380 reply->ptid.to_string().c_str(),
7381 reply->ws.to_string ().c_str ());
7382 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7383 }
7384
7385 /* Discard the stop replies for RS in stop_reply_queue. */
7386
7387 void
7388 remote_target::discard_pending_stop_replies_in_queue ()
7389 {
7390 remote_state *rs = get_remote_state ();
7391
7392 /* Discard the stop replies we have already pulled with
7393 vStopped. */
7394 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7395 rs->stop_reply_queue.end (),
7396 [=] (const stop_reply_up &event)
7397 {
7398 return event->rs == rs;
7399 });
7400 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7401 }
7402
7403 /* Remove the first reply in 'stop_reply_queue' which matches
7404 PTID. */
7405
7406 struct stop_reply *
7407 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7408 {
7409 remote_state *rs = get_remote_state ();
7410
7411 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7412 rs->stop_reply_queue.end (),
7413 [=] (const stop_reply_up &event)
7414 {
7415 return event->ptid.matches (ptid);
7416 });
7417 struct stop_reply *result;
7418 if (iter == rs->stop_reply_queue.end ())
7419 result = nullptr;
7420 else
7421 {
7422 result = iter->release ();
7423 rs->stop_reply_queue.erase (iter);
7424 }
7425
7426 if (notif_debug)
7427 gdb_printf (gdb_stdlog,
7428 "notif: discard queued event: 'Stop' in %s\n",
7429 ptid.to_string ().c_str ());
7430
7431 return result;
7432 }
7433
7434 /* Look for a queued stop reply belonging to PTID. If one is found,
7435 remove it from the queue, and return it. Returns NULL if none is
7436 found. If there are still queued events left to process, tell the
7437 event loop to get back to target_wait soon. */
7438
7439 struct stop_reply *
7440 remote_target::queued_stop_reply (ptid_t ptid)
7441 {
7442 remote_state *rs = get_remote_state ();
7443 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7444
7445 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7446 {
7447 /* There's still at least an event left. */
7448 mark_async_event_handler (rs->remote_async_inferior_event_token);
7449 }
7450
7451 return r;
7452 }
7453
7454 /* Push a fully parsed stop reply in the stop reply queue. Since we
7455 know that we now have at least one queued event left to pass to the
7456 core side, tell the event loop to get back to target_wait soon. */
7457
7458 void
7459 remote_target::push_stop_reply (struct stop_reply *new_event)
7460 {
7461 remote_state *rs = get_remote_state ();
7462 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7463
7464 if (notif_debug)
7465 gdb_printf (gdb_stdlog,
7466 "notif: push 'Stop' %s to queue %d\n",
7467 new_event->ptid.to_string ().c_str (),
7468 int (rs->stop_reply_queue.size ()));
7469
7470 /* Mark the pending event queue only if async mode is currently enabled.
7471 If async mode is not currently enabled, then, if it later becomes
7472 enabled, and there are events in this queue, we will mark the event
7473 token at that point, see remote_target::async. */
7474 if (target_is_async_p ())
7475 mark_async_event_handler (rs->remote_async_inferior_event_token);
7476 }
7477
7478 /* Returns true if we have a stop reply for PTID. */
7479
7480 int
7481 remote_target::peek_stop_reply (ptid_t ptid)
7482 {
7483 remote_state *rs = get_remote_state ();
7484 for (auto &event : rs->stop_reply_queue)
7485 if (ptid == event->ptid
7486 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7487 return 1;
7488 return 0;
7489 }
7490
7491 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7492 starting with P and ending with PEND matches PREFIX. */
7493
7494 static int
7495 strprefix (const char *p, const char *pend, const char *prefix)
7496 {
7497 for ( ; p < pend; p++, prefix++)
7498 if (*p != *prefix)
7499 return 0;
7500 return *prefix == '\0';
7501 }
7502
7503 /* Parse the stop reply in BUF. Either the function succeeds, and the
7504 result is stored in EVENT, or throws an error. */
7505
7506 void
7507 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7508 {
7509 remote_arch_state *rsa = NULL;
7510 ULONGEST addr;
7511 const char *p;
7512 int skipregs = 0;
7513
7514 event->ptid = null_ptid;
7515 event->rs = get_remote_state ();
7516 event->ws.set_ignore ();
7517 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7518 event->regcache.clear ();
7519 event->core = -1;
7520
7521 switch (buf[0])
7522 {
7523 case 'T': /* Status with PC, SP, FP, ... */
7524 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7525 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7526 ss = signal number
7527 n... = register number
7528 r... = register contents
7529 */
7530
7531 p = &buf[3]; /* after Txx */
7532 while (*p)
7533 {
7534 const char *p1;
7535 int fieldsize;
7536
7537 p1 = strchr (p, ':');
7538 if (p1 == NULL)
7539 error (_("Malformed packet(a) (missing colon): %s\n\
7540 Packet: '%s'\n"),
7541 p, buf);
7542 if (p == p1)
7543 error (_("Malformed packet(a) (missing register number): %s\n\
7544 Packet: '%s'\n"),
7545 p, buf);
7546
7547 /* Some "registers" are actually extended stop information.
7548 Note if you're adding a new entry here: GDB 7.9 and
7549 earlier assume that all register "numbers" that start
7550 with an hex digit are real register numbers. Make sure
7551 the server only sends such a packet if it knows the
7552 client understands it. */
7553
7554 if (strprefix (p, p1, "thread"))
7555 event->ptid = read_ptid (++p1, &p);
7556 else if (strprefix (p, p1, "syscall_entry"))
7557 {
7558 ULONGEST sysno;
7559
7560 p = unpack_varlen_hex (++p1, &sysno);
7561 event->ws.set_syscall_entry ((int) sysno);
7562 }
7563 else if (strprefix (p, p1, "syscall_return"))
7564 {
7565 ULONGEST sysno;
7566
7567 p = unpack_varlen_hex (++p1, &sysno);
7568 event->ws.set_syscall_return ((int) sysno);
7569 }
7570 else if (strprefix (p, p1, "watch")
7571 || strprefix (p, p1, "rwatch")
7572 || strprefix (p, p1, "awatch"))
7573 {
7574 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7575 p = unpack_varlen_hex (++p1, &addr);
7576 event->watch_data_address = (CORE_ADDR) addr;
7577 }
7578 else if (strprefix (p, p1, "swbreak"))
7579 {
7580 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7581
7582 /* Make sure the stub doesn't forget to indicate support
7583 with qSupported. */
7584 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7585 error (_("Unexpected swbreak stop reason"));
7586
7587 /* The value part is documented as "must be empty",
7588 though we ignore it, in case we ever decide to make
7589 use of it in a backward compatible way. */
7590 p = strchrnul (p1 + 1, ';');
7591 }
7592 else if (strprefix (p, p1, "hwbreak"))
7593 {
7594 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7595
7596 /* Make sure the stub doesn't forget to indicate support
7597 with qSupported. */
7598 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7599 error (_("Unexpected hwbreak stop reason"));
7600
7601 /* See above. */
7602 p = strchrnul (p1 + 1, ';');
7603 }
7604 else if (strprefix (p, p1, "library"))
7605 {
7606 event->ws.set_loaded ();
7607 p = strchrnul (p1 + 1, ';');
7608 }
7609 else if (strprefix (p, p1, "replaylog"))
7610 {
7611 event->ws.set_no_history ();
7612 /* p1 will indicate "begin" or "end", but it makes
7613 no difference for now, so ignore it. */
7614 p = strchrnul (p1 + 1, ';');
7615 }
7616 else if (strprefix (p, p1, "core"))
7617 {
7618 ULONGEST c;
7619
7620 p = unpack_varlen_hex (++p1, &c);
7621 event->core = c;
7622 }
7623 else if (strprefix (p, p1, "fork"))
7624 event->ws.set_forked (read_ptid (++p1, &p));
7625 else if (strprefix (p, p1, "vfork"))
7626 event->ws.set_vforked (read_ptid (++p1, &p));
7627 else if (strprefix (p, p1, "vforkdone"))
7628 {
7629 event->ws.set_vfork_done ();
7630 p = strchrnul (p1 + 1, ';');
7631 }
7632 else if (strprefix (p, p1, "exec"))
7633 {
7634 ULONGEST ignored;
7635 int pathlen;
7636
7637 /* Determine the length of the execd pathname. */
7638 p = unpack_varlen_hex (++p1, &ignored);
7639 pathlen = (p - p1) / 2;
7640
7641 /* Save the pathname for event reporting and for
7642 the next run command. */
7643 gdb::unique_xmalloc_ptr<char> pathname
7644 ((char *) xmalloc (pathlen + 1));
7645 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
7646 pathname.get ()[pathlen] = '\0';
7647
7648 /* This is freed during event handling. */
7649 event->ws.set_execd (std::move (pathname));
7650
7651 /* Skip the registers included in this packet, since
7652 they may be for an architecture different from the
7653 one used by the original program. */
7654 skipregs = 1;
7655 }
7656 else if (strprefix (p, p1, "create"))
7657 {
7658 event->ws.set_thread_created ();
7659 p = strchrnul (p1 + 1, ';');
7660 }
7661 else
7662 {
7663 ULONGEST pnum;
7664 const char *p_temp;
7665
7666 if (skipregs)
7667 {
7668 p = strchrnul (p1 + 1, ';');
7669 p++;
7670 continue;
7671 }
7672
7673 /* Maybe a real ``P'' register number. */
7674 p_temp = unpack_varlen_hex (p, &pnum);
7675 /* If the first invalid character is the colon, we got a
7676 register number. Otherwise, it's an unknown stop
7677 reason. */
7678 if (p_temp == p1)
7679 {
7680 /* If we haven't parsed the event's thread yet, find
7681 it now, in order to find the architecture of the
7682 reported expedited registers. */
7683 if (event->ptid == null_ptid)
7684 {
7685 /* If there is no thread-id information then leave
7686 the event->ptid as null_ptid. Later in
7687 process_stop_reply we will pick a suitable
7688 thread. */
7689 const char *thr = strstr (p1 + 1, ";thread:");
7690 if (thr != NULL)
7691 event->ptid = read_ptid (thr + strlen (";thread:"),
7692 NULL);
7693 }
7694
7695 if (rsa == NULL)
7696 {
7697 inferior *inf
7698 = (event->ptid == null_ptid
7699 ? NULL
7700 : find_inferior_ptid (this, event->ptid));
7701 /* If this is the first time we learn anything
7702 about this process, skip the registers
7703 included in this packet, since we don't yet
7704 know which architecture to use to parse them.
7705 We'll determine the architecture later when
7706 we process the stop reply and retrieve the
7707 target description, via
7708 remote_notice_new_inferior ->
7709 post_create_inferior. */
7710 if (inf == NULL)
7711 {
7712 p = strchrnul (p1 + 1, ';');
7713 p++;
7714 continue;
7715 }
7716
7717 event->arch = inf->gdbarch;
7718 rsa = event->rs->get_remote_arch_state (event->arch);
7719 }
7720
7721 packet_reg *reg
7722 = packet_reg_from_pnum (event->arch, rsa, pnum);
7723 cached_reg_t cached_reg;
7724
7725 if (reg == NULL)
7726 error (_("Remote sent bad register number %s: %s\n\
7727 Packet: '%s'\n"),
7728 hex_string (pnum), p, buf);
7729
7730 cached_reg.num = reg->regnum;
7731 cached_reg.data = (gdb_byte *)
7732 xmalloc (register_size (event->arch, reg->regnum));
7733
7734 p = p1 + 1;
7735 fieldsize = hex2bin (p, cached_reg.data,
7736 register_size (event->arch, reg->regnum));
7737 p += 2 * fieldsize;
7738 if (fieldsize < register_size (event->arch, reg->regnum))
7739 warning (_("Remote reply is too short: %s"), buf);
7740
7741 event->regcache.push_back (cached_reg);
7742 }
7743 else
7744 {
7745 /* Not a number. Silently skip unknown optional
7746 info. */
7747 p = strchrnul (p1 + 1, ';');
7748 }
7749 }
7750
7751 if (*p != ';')
7752 error (_("Remote register badly formatted: %s\nhere: %s"),
7753 buf, p);
7754 ++p;
7755 }
7756
7757 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
7758 break;
7759
7760 /* fall through */
7761 case 'S': /* Old style status, just signal only. */
7762 {
7763 int sig;
7764
7765 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7766 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7767 event->ws.set_stopped ((enum gdb_signal) sig);
7768 else
7769 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
7770 }
7771 break;
7772 case 'w': /* Thread exited. */
7773 {
7774 ULONGEST value;
7775
7776 p = unpack_varlen_hex (&buf[1], &value);
7777 event->ws.set_thread_exited (value);
7778 if (*p != ';')
7779 error (_("stop reply packet badly formatted: %s"), buf);
7780 event->ptid = read_ptid (++p, NULL);
7781 break;
7782 }
7783 case 'W': /* Target exited. */
7784 case 'X':
7785 {
7786 ULONGEST value;
7787
7788 /* GDB used to accept only 2 hex chars here. Stubs should
7789 only send more if they detect GDB supports multi-process
7790 support. */
7791 p = unpack_varlen_hex (&buf[1], &value);
7792
7793 if (buf[0] == 'W')
7794 {
7795 /* The remote process exited. */
7796 event->ws.set_exited (value);
7797 }
7798 else
7799 {
7800 /* The remote process exited with a signal. */
7801 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7802 event->ws.set_signalled ((enum gdb_signal) value);
7803 else
7804 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
7805 }
7806
7807 /* If no process is specified, return null_ptid, and let the
7808 caller figure out the right process to use. */
7809 int pid = 0;
7810 if (*p == '\0')
7811 ;
7812 else if (*p == ';')
7813 {
7814 p++;
7815
7816 if (*p == '\0')
7817 ;
7818 else if (startswith (p, "process:"))
7819 {
7820 ULONGEST upid;
7821
7822 p += sizeof ("process:") - 1;
7823 unpack_varlen_hex (p, &upid);
7824 pid = upid;
7825 }
7826 else
7827 error (_("unknown stop reply packet: %s"), buf);
7828 }
7829 else
7830 error (_("unknown stop reply packet: %s"), buf);
7831 event->ptid = ptid_t (pid);
7832 }
7833 break;
7834 case 'N':
7835 event->ws.set_no_resumed ();
7836 event->ptid = minus_one_ptid;
7837 break;
7838 }
7839 }
7840
7841 /* When the stub wants to tell GDB about a new notification reply, it
7842 sends a notification (%Stop, for example). Those can come it at
7843 any time, hence, we have to make sure that any pending
7844 putpkt/getpkt sequence we're making is finished, before querying
7845 the stub for more events with the corresponding ack command
7846 (vStopped, for example). E.g., if we started a vStopped sequence
7847 immediately upon receiving the notification, something like this
7848 could happen:
7849
7850 1.1) --> Hg 1
7851 1.2) <-- OK
7852 1.3) --> g
7853 1.4) <-- %Stop
7854 1.5) --> vStopped
7855 1.6) <-- (registers reply to step #1.3)
7856
7857 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7858 query.
7859
7860 To solve this, whenever we parse a %Stop notification successfully,
7861 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7862 doing whatever we were doing:
7863
7864 2.1) --> Hg 1
7865 2.2) <-- OK
7866 2.3) --> g
7867 2.4) <-- %Stop
7868 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7869 2.5) <-- (registers reply to step #2.3)
7870
7871 Eventually after step #2.5, we return to the event loop, which
7872 notices there's an event on the
7873 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7874 associated callback --- the function below. At this point, we're
7875 always safe to start a vStopped sequence. :
7876
7877 2.6) --> vStopped
7878 2.7) <-- T05 thread:2
7879 2.8) --> vStopped
7880 2.9) --> OK
7881 */
7882
7883 void
7884 remote_target::remote_notif_get_pending_events (notif_client *nc)
7885 {
7886 struct remote_state *rs = get_remote_state ();
7887
7888 if (rs->notif_state->pending_event[nc->id] != NULL)
7889 {
7890 if (notif_debug)
7891 gdb_printf (gdb_stdlog,
7892 "notif: process: '%s' ack pending event\n",
7893 nc->name);
7894
7895 /* acknowledge */
7896 nc->ack (this, nc, rs->buf.data (),
7897 rs->notif_state->pending_event[nc->id]);
7898 rs->notif_state->pending_event[nc->id] = NULL;
7899
7900 while (1)
7901 {
7902 getpkt (&rs->buf, 0);
7903 if (strcmp (rs->buf.data (), "OK") == 0)
7904 break;
7905 else
7906 remote_notif_ack (this, nc, rs->buf.data ());
7907 }
7908 }
7909 else
7910 {
7911 if (notif_debug)
7912 gdb_printf (gdb_stdlog,
7913 "notif: process: '%s' no pending reply\n",
7914 nc->name);
7915 }
7916 }
7917
7918 /* Wrapper around remote_target::remote_notif_get_pending_events to
7919 avoid having to export the whole remote_target class. */
7920
7921 void
7922 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7923 {
7924 remote->remote_notif_get_pending_events (nc);
7925 }
7926
7927 /* Called from process_stop_reply when the stop packet we are responding
7928 to didn't include a process-id or thread-id. STATUS is the stop event
7929 we are responding to.
7930
7931 It is the task of this function to select a suitable thread (or process)
7932 and return its ptid, this is the thread (or process) we will assume the
7933 stop event came from.
7934
7935 In some cases there isn't really any choice about which thread (or
7936 process) is selected, a basic remote with a single process containing a
7937 single thread might choose not to send any process-id or thread-id in
7938 its stop packets, this function will select and return the one and only
7939 thread.
7940
7941 However, if a target supports multiple threads (or processes) and still
7942 doesn't include a thread-id (or process-id) in its stop packet then
7943 first, this is a badly behaving target, and second, we're going to have
7944 to select a thread (or process) at random and use that. This function
7945 will print a warning to the user if it detects that there is the
7946 possibility that GDB is guessing which thread (or process) to
7947 report.
7948
7949 Note that this is called before GDB fetches the updated thread list from the
7950 target. So it's possible for the stop reply to be ambiguous and for GDB to
7951 not realize it. For example, if there's initially one thread, the target
7952 spawns a second thread, and then sends a stop reply without an id that
7953 concerns the first thread. GDB will assume the stop reply is about the
7954 first thread - the only thread it knows about - without printing a warning.
7955 Anyway, if the remote meant for the stop reply to be about the second thread,
7956 then it would be really broken, because GDB doesn't know about that thread
7957 yet. */
7958
7959 ptid_t
7960 remote_target::select_thread_for_ambiguous_stop_reply
7961 (const target_waitstatus &status)
7962 {
7963 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7964
7965 /* Some stop events apply to all threads in an inferior, while others
7966 only apply to a single thread. */
7967 bool process_wide_stop
7968 = (status.kind () == TARGET_WAITKIND_EXITED
7969 || status.kind () == TARGET_WAITKIND_SIGNALLED);
7970
7971 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
7972
7973 thread_info *first_resumed_thread = nullptr;
7974 bool ambiguous = false;
7975
7976 /* Consider all non-exited threads of the target, find the first resumed
7977 one. */
7978 for (thread_info *thr : all_non_exited_threads (this))
7979 {
7980 remote_thread_info *remote_thr = get_remote_thread_info (thr);
7981
7982 if (remote_thr->get_resume_state () != resume_state::RESUMED)
7983 continue;
7984
7985 if (first_resumed_thread == nullptr)
7986 first_resumed_thread = thr;
7987 else if (!process_wide_stop
7988 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
7989 ambiguous = true;
7990 }
7991
7992 gdb_assert (first_resumed_thread != nullptr);
7993
7994 remote_debug_printf ("first resumed thread is %s",
7995 pid_to_str (first_resumed_thread->ptid).c_str ());
7996 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
7997
7998 /* Warn if the remote target is sending ambiguous stop replies. */
7999 if (ambiguous)
8000 {
8001 static bool warned = false;
8002
8003 if (!warned)
8004 {
8005 /* If you are seeing this warning then the remote target has
8006 stopped without specifying a thread-id, but the target
8007 does have multiple threads (or inferiors), and so GDB is
8008 having to guess which thread stopped.
8009
8010 Examples of what might cause this are the target sending
8011 and 'S' stop packet, or a 'T' stop packet and not
8012 including a thread-id.
8013
8014 Additionally, the target might send a 'W' or 'X packet
8015 without including a process-id, when the target has
8016 multiple running inferiors. */
8017 if (process_wide_stop)
8018 warning (_("multi-inferior target stopped without "
8019 "sending a process-id, using first "
8020 "non-exited inferior"));
8021 else
8022 warning (_("multi-threaded target stopped without "
8023 "sending a thread-id, using first "
8024 "non-exited thread"));
8025 warned = true;
8026 }
8027 }
8028
8029 /* If this is a stop for all threads then don't use a particular threads
8030 ptid, instead create a new ptid where only the pid field is set. */
8031 if (process_wide_stop)
8032 return ptid_t (first_resumed_thread->ptid.pid ());
8033 else
8034 return first_resumed_thread->ptid;
8035 }
8036
8037 /* Called when it is decided that STOP_REPLY holds the info of the
8038 event that is to be returned to the core. This function always
8039 destroys STOP_REPLY. */
8040
8041 ptid_t
8042 remote_target::process_stop_reply (struct stop_reply *stop_reply,
8043 struct target_waitstatus *status)
8044 {
8045 *status = stop_reply->ws;
8046 ptid_t ptid = stop_reply->ptid;
8047
8048 /* If no thread/process was reported by the stub then select a suitable
8049 thread/process. */
8050 if (ptid == null_ptid)
8051 ptid = select_thread_for_ambiguous_stop_reply (*status);
8052 gdb_assert (ptid != null_ptid);
8053
8054 if (status->kind () != TARGET_WAITKIND_EXITED
8055 && status->kind () != TARGET_WAITKIND_SIGNALLED
8056 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8057 {
8058 /* Expedited registers. */
8059 if (!stop_reply->regcache.empty ())
8060 {
8061 struct regcache *regcache
8062 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
8063
8064 for (cached_reg_t &reg : stop_reply->regcache)
8065 {
8066 regcache->raw_supply (reg.num, reg.data);
8067 xfree (reg.data);
8068 }
8069
8070 stop_reply->regcache.clear ();
8071 }
8072
8073 remote_notice_new_inferior (ptid, false);
8074 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8075 remote_thr->core = stop_reply->core;
8076 remote_thr->stop_reason = stop_reply->stop_reason;
8077 remote_thr->watch_data_address = stop_reply->watch_data_address;
8078
8079 if (target_is_non_stop_p ())
8080 {
8081 /* If the target works in non-stop mode, a stop-reply indicates that
8082 only this thread stopped. */
8083 remote_thr->set_not_resumed ();
8084 }
8085 else
8086 {
8087 /* If the target works in all-stop mode, a stop-reply indicates that
8088 all the target's threads stopped. */
8089 for (thread_info *tp : all_non_exited_threads (this))
8090 get_remote_thread_info (tp)->set_not_resumed ();
8091 }
8092 }
8093
8094 delete stop_reply;
8095 return ptid;
8096 }
8097
8098 /* The non-stop mode version of target_wait. */
8099
8100 ptid_t
8101 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8102 target_wait_flags options)
8103 {
8104 struct remote_state *rs = get_remote_state ();
8105 struct stop_reply *stop_reply;
8106 int ret;
8107 int is_notif = 0;
8108
8109 /* If in non-stop mode, get out of getpkt even if a
8110 notification is received. */
8111
8112 ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
8113 while (1)
8114 {
8115 if (ret != -1 && !is_notif)
8116 switch (rs->buf[0])
8117 {
8118 case 'E': /* Error of some sort. */
8119 /* We're out of sync with the target now. Did it continue
8120 or not? We can't tell which thread it was in non-stop,
8121 so just ignore this. */
8122 warning (_("Remote failure reply: %s"), rs->buf.data ());
8123 break;
8124 case 'O': /* Console output. */
8125 remote_console_output (&rs->buf[1]);
8126 break;
8127 default:
8128 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8129 break;
8130 }
8131
8132 /* Acknowledge a pending stop reply that may have arrived in the
8133 mean time. */
8134 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8135 remote_notif_get_pending_events (&notif_client_stop);
8136
8137 /* If indeed we noticed a stop reply, we're done. */
8138 stop_reply = queued_stop_reply (ptid);
8139 if (stop_reply != NULL)
8140 return process_stop_reply (stop_reply, status);
8141
8142 /* Still no event. If we're just polling for an event, then
8143 return to the event loop. */
8144 if (options & TARGET_WNOHANG)
8145 {
8146 status->set_ignore ();
8147 return minus_one_ptid;
8148 }
8149
8150 /* Otherwise do a blocking wait. */
8151 ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
8152 }
8153 }
8154
8155 /* Return the first resumed thread. */
8156
8157 static ptid_t
8158 first_remote_resumed_thread (remote_target *target)
8159 {
8160 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8161 if (tp->resumed ())
8162 return tp->ptid;
8163 return null_ptid;
8164 }
8165
8166 /* Wait until the remote machine stops, then return, storing status in
8167 STATUS just as `wait' would. */
8168
8169 ptid_t
8170 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8171 target_wait_flags options)
8172 {
8173 struct remote_state *rs = get_remote_state ();
8174 ptid_t event_ptid = null_ptid;
8175 char *buf;
8176 struct stop_reply *stop_reply;
8177
8178 again:
8179
8180 status->set_ignore ();
8181
8182 stop_reply = queued_stop_reply (ptid);
8183 if (stop_reply != NULL)
8184 {
8185 /* None of the paths that push a stop reply onto the queue should
8186 have set the waiting_for_stop_reply flag. */
8187 gdb_assert (!rs->waiting_for_stop_reply);
8188 event_ptid = process_stop_reply (stop_reply, status);
8189 }
8190 else
8191 {
8192 int forever = ((options & TARGET_WNOHANG) == 0
8193 && rs->wait_forever_enabled_p);
8194
8195 if (!rs->waiting_for_stop_reply)
8196 {
8197 status->set_no_resumed ();
8198 return minus_one_ptid;
8199 }
8200
8201 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8202 _never_ wait for ever -> test on target_is_async_p().
8203 However, before we do that we need to ensure that the caller
8204 knows how to take the target into/out of async mode. */
8205 int is_notif;
8206 int ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
8207
8208 /* GDB gets a notification. Return to core as this event is
8209 not interesting. */
8210 if (ret != -1 && is_notif)
8211 return minus_one_ptid;
8212
8213 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8214 return minus_one_ptid;
8215
8216 buf = rs->buf.data ();
8217
8218 /* Assume that the target has acknowledged Ctrl-C unless we receive
8219 an 'F' or 'O' packet. */
8220 if (buf[0] != 'F' && buf[0] != 'O')
8221 rs->ctrlc_pending_p = 0;
8222
8223 switch (buf[0])
8224 {
8225 case 'E': /* Error of some sort. */
8226 /* We're out of sync with the target now. Did it continue or
8227 not? Not is more likely, so report a stop. */
8228 rs->waiting_for_stop_reply = 0;
8229
8230 warning (_("Remote failure reply: %s"), buf);
8231 status->set_stopped (GDB_SIGNAL_0);
8232 break;
8233 case 'F': /* File-I/O request. */
8234 /* GDB may access the inferior memory while handling the File-I/O
8235 request, but we don't want GDB accessing memory while waiting
8236 for a stop reply. See the comments in putpkt_binary. Set
8237 waiting_for_stop_reply to 0 temporarily. */
8238 rs->waiting_for_stop_reply = 0;
8239 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8240 rs->ctrlc_pending_p = 0;
8241 /* GDB handled the File-I/O request, and the target is running
8242 again. Keep waiting for events. */
8243 rs->waiting_for_stop_reply = 1;
8244 break;
8245 case 'N': case 'T': case 'S': case 'X': case 'W':
8246 {
8247 /* There is a stop reply to handle. */
8248 rs->waiting_for_stop_reply = 0;
8249
8250 stop_reply
8251 = (struct stop_reply *) remote_notif_parse (this,
8252 &notif_client_stop,
8253 rs->buf.data ());
8254
8255 event_ptid = process_stop_reply (stop_reply, status);
8256 break;
8257 }
8258 case 'O': /* Console output. */
8259 remote_console_output (buf + 1);
8260 break;
8261 case '\0':
8262 if (rs->last_sent_signal != GDB_SIGNAL_0)
8263 {
8264 /* Zero length reply means that we tried 'S' or 'C' and the
8265 remote system doesn't support it. */
8266 target_terminal::ours_for_output ();
8267 gdb_printf
8268 ("Can't send signals to this remote system. %s not sent.\n",
8269 gdb_signal_to_name (rs->last_sent_signal));
8270 rs->last_sent_signal = GDB_SIGNAL_0;
8271 target_terminal::inferior ();
8272
8273 strcpy (buf, rs->last_sent_step ? "s" : "c");
8274 putpkt (buf);
8275 break;
8276 }
8277 /* fallthrough */
8278 default:
8279 warning (_("Invalid remote reply: %s"), buf);
8280 break;
8281 }
8282 }
8283
8284 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8285 return minus_one_ptid;
8286 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8287 {
8288 /* Nothing interesting happened. If we're doing a non-blocking
8289 poll, we're done. Otherwise, go back to waiting. */
8290 if (options & TARGET_WNOHANG)
8291 return minus_one_ptid;
8292 else
8293 goto again;
8294 }
8295 else if (status->kind () != TARGET_WAITKIND_EXITED
8296 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8297 {
8298 if (event_ptid != null_ptid)
8299 record_currthread (rs, event_ptid);
8300 else
8301 event_ptid = first_remote_resumed_thread (this);
8302 }
8303 else
8304 {
8305 /* A process exit. Invalidate our notion of current thread. */
8306 record_currthread (rs, minus_one_ptid);
8307 /* It's possible that the packet did not include a pid. */
8308 if (event_ptid == null_ptid)
8309 event_ptid = first_remote_resumed_thread (this);
8310 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8311 if (event_ptid == null_ptid)
8312 event_ptid = magic_null_ptid;
8313 }
8314
8315 return event_ptid;
8316 }
8317
8318 /* Wait until the remote machine stops, then return, storing status in
8319 STATUS just as `wait' would. */
8320
8321 ptid_t
8322 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8323 target_wait_flags options)
8324 {
8325 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8326
8327 remote_state *rs = get_remote_state ();
8328
8329 /* Start by clearing the flag that asks for our wait method to be called,
8330 we'll mark it again at the end if needed. If the target is not in
8331 async mode then the async token should not be marked. */
8332 if (target_is_async_p ())
8333 clear_async_event_handler (rs->remote_async_inferior_event_token);
8334 else
8335 gdb_assert (!async_event_handler_marked
8336 (rs->remote_async_inferior_event_token));
8337
8338 ptid_t event_ptid;
8339
8340 if (target_is_non_stop_p ())
8341 event_ptid = wait_ns (ptid, status, options);
8342 else
8343 event_ptid = wait_as (ptid, status, options);
8344
8345 if (target_is_async_p ())
8346 {
8347 /* If there are events left in the queue, or unacknowledged
8348 notifications, then tell the event loop to call us again. */
8349 if (!rs->stop_reply_queue.empty ()
8350 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8351 mark_async_event_handler (rs->remote_async_inferior_event_token);
8352 }
8353
8354 return event_ptid;
8355 }
8356
8357 /* Fetch a single register using a 'p' packet. */
8358
8359 int
8360 remote_target::fetch_register_using_p (struct regcache *regcache,
8361 packet_reg *reg)
8362 {
8363 struct gdbarch *gdbarch = regcache->arch ();
8364 struct remote_state *rs = get_remote_state ();
8365 char *buf, *p;
8366 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8367 int i;
8368
8369 if (packet_support (PACKET_p) == PACKET_DISABLE)
8370 return 0;
8371
8372 if (reg->pnum == -1)
8373 return 0;
8374
8375 p = rs->buf.data ();
8376 *p++ = 'p';
8377 p += hexnumstr (p, reg->pnum);
8378 *p++ = '\0';
8379 putpkt (rs->buf);
8380 getpkt (&rs->buf, 0);
8381
8382 buf = rs->buf.data ();
8383
8384 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_p]))
8385 {
8386 case PACKET_OK:
8387 break;
8388 case PACKET_UNKNOWN:
8389 return 0;
8390 case PACKET_ERROR:
8391 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8392 gdbarch_register_name (regcache->arch (),
8393 reg->regnum),
8394 buf);
8395 }
8396
8397 /* If this register is unfetchable, tell the regcache. */
8398 if (buf[0] == 'x')
8399 {
8400 regcache->raw_supply (reg->regnum, NULL);
8401 return 1;
8402 }
8403
8404 /* Otherwise, parse and supply the value. */
8405 p = buf;
8406 i = 0;
8407 while (p[0] != 0)
8408 {
8409 if (p[1] == 0)
8410 error (_("fetch_register_using_p: early buf termination"));
8411
8412 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8413 p += 2;
8414 }
8415 regcache->raw_supply (reg->regnum, regp);
8416 return 1;
8417 }
8418
8419 /* Fetch the registers included in the target's 'g' packet. */
8420
8421 int
8422 remote_target::send_g_packet ()
8423 {
8424 struct remote_state *rs = get_remote_state ();
8425 int buf_len;
8426
8427 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8428 putpkt (rs->buf);
8429 getpkt (&rs->buf, 0);
8430 if (packet_check_result (rs->buf) == PACKET_ERROR)
8431 error (_("Could not read registers; remote failure reply '%s'"),
8432 rs->buf.data ());
8433
8434 /* We can get out of synch in various cases. If the first character
8435 in the buffer is not a hex character, assume that has happened
8436 and try to fetch another packet to read. */
8437 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8438 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8439 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8440 && rs->buf[0] != 'x') /* New: unavailable register value. */
8441 {
8442 remote_debug_printf ("Bad register packet; fetching a new packet");
8443 getpkt (&rs->buf, 0);
8444 }
8445
8446 buf_len = strlen (rs->buf.data ());
8447
8448 /* Sanity check the received packet. */
8449 if (buf_len % 2 != 0)
8450 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8451
8452 return buf_len / 2;
8453 }
8454
8455 void
8456 remote_target::process_g_packet (struct regcache *regcache)
8457 {
8458 struct gdbarch *gdbarch = regcache->arch ();
8459 struct remote_state *rs = get_remote_state ();
8460 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8461 int i, buf_len;
8462 char *p;
8463 char *regs;
8464
8465 buf_len = strlen (rs->buf.data ());
8466
8467 /* Further sanity checks, with knowledge of the architecture. */
8468 if (buf_len > 2 * rsa->sizeof_g_packet)
8469 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8470 "bytes): %s"),
8471 rsa->sizeof_g_packet, buf_len / 2,
8472 rs->buf.data ());
8473
8474 /* Save the size of the packet sent to us by the target. It is used
8475 as a heuristic when determining the max size of packets that the
8476 target can safely receive. */
8477 if (rsa->actual_register_packet_size == 0)
8478 rsa->actual_register_packet_size = buf_len;
8479
8480 /* If this is smaller than we guessed the 'g' packet would be,
8481 update our records. A 'g' reply that doesn't include a register's
8482 value implies either that the register is not available, or that
8483 the 'p' packet must be used. */
8484 if (buf_len < 2 * rsa->sizeof_g_packet)
8485 {
8486 long sizeof_g_packet = buf_len / 2;
8487
8488 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8489 {
8490 long offset = rsa->regs[i].offset;
8491 long reg_size = register_size (gdbarch, i);
8492
8493 if (rsa->regs[i].pnum == -1)
8494 continue;
8495
8496 if (offset >= sizeof_g_packet)
8497 rsa->regs[i].in_g_packet = 0;
8498 else if (offset + reg_size > sizeof_g_packet)
8499 error (_("Truncated register %d in remote 'g' packet"), i);
8500 else
8501 rsa->regs[i].in_g_packet = 1;
8502 }
8503
8504 /* Looks valid enough, we can assume this is the correct length
8505 for a 'g' packet. It's important not to adjust
8506 rsa->sizeof_g_packet if we have truncated registers otherwise
8507 this "if" won't be run the next time the method is called
8508 with a packet of the same size and one of the internal errors
8509 below will trigger instead. */
8510 rsa->sizeof_g_packet = sizeof_g_packet;
8511 }
8512
8513 regs = (char *) alloca (rsa->sizeof_g_packet);
8514
8515 /* Unimplemented registers read as all bits zero. */
8516 memset (regs, 0, rsa->sizeof_g_packet);
8517
8518 /* Reply describes registers byte by byte, each byte encoded as two
8519 hex characters. Suck them all up, then supply them to the
8520 register cacheing/storage mechanism. */
8521
8522 p = rs->buf.data ();
8523 for (i = 0; i < rsa->sizeof_g_packet; i++)
8524 {
8525 if (p[0] == 0 || p[1] == 0)
8526 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8527 internal_error (__FILE__, __LINE__,
8528 _("unexpected end of 'g' packet reply"));
8529
8530 if (p[0] == 'x' && p[1] == 'x')
8531 regs[i] = 0; /* 'x' */
8532 else
8533 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8534 p += 2;
8535 }
8536
8537 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8538 {
8539 struct packet_reg *r = &rsa->regs[i];
8540 long reg_size = register_size (gdbarch, i);
8541
8542 if (r->in_g_packet)
8543 {
8544 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8545 /* This shouldn't happen - we adjusted in_g_packet above. */
8546 internal_error (__FILE__, __LINE__,
8547 _("unexpected end of 'g' packet reply"));
8548 else if (rs->buf[r->offset * 2] == 'x')
8549 {
8550 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8551 /* The register isn't available, mark it as such (at
8552 the same time setting the value to zero). */
8553 regcache->raw_supply (r->regnum, NULL);
8554 }
8555 else
8556 regcache->raw_supply (r->regnum, regs + r->offset);
8557 }
8558 }
8559 }
8560
8561 void
8562 remote_target::fetch_registers_using_g (struct regcache *regcache)
8563 {
8564 send_g_packet ();
8565 process_g_packet (regcache);
8566 }
8567
8568 /* Make the remote selected traceframe match GDB's selected
8569 traceframe. */
8570
8571 void
8572 remote_target::set_remote_traceframe ()
8573 {
8574 int newnum;
8575 struct remote_state *rs = get_remote_state ();
8576
8577 if (rs->remote_traceframe_number == get_traceframe_number ())
8578 return;
8579
8580 /* Avoid recursion, remote_trace_find calls us again. */
8581 rs->remote_traceframe_number = get_traceframe_number ();
8582
8583 newnum = target_trace_find (tfind_number,
8584 get_traceframe_number (), 0, 0, NULL);
8585
8586 /* Should not happen. If it does, all bets are off. */
8587 if (newnum != get_traceframe_number ())
8588 warning (_("could not set remote traceframe"));
8589 }
8590
8591 void
8592 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8593 {
8594 struct gdbarch *gdbarch = regcache->arch ();
8595 struct remote_state *rs = get_remote_state ();
8596 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8597 int i;
8598
8599 set_remote_traceframe ();
8600 set_general_thread (regcache->ptid ());
8601
8602 if (regnum >= 0)
8603 {
8604 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8605
8606 gdb_assert (reg != NULL);
8607
8608 /* If this register might be in the 'g' packet, try that first -
8609 we are likely to read more than one register. If this is the
8610 first 'g' packet, we might be overly optimistic about its
8611 contents, so fall back to 'p'. */
8612 if (reg->in_g_packet)
8613 {
8614 fetch_registers_using_g (regcache);
8615 if (reg->in_g_packet)
8616 return;
8617 }
8618
8619 if (fetch_register_using_p (regcache, reg))
8620 return;
8621
8622 /* This register is not available. */
8623 regcache->raw_supply (reg->regnum, NULL);
8624
8625 return;
8626 }
8627
8628 fetch_registers_using_g (regcache);
8629
8630 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8631 if (!rsa->regs[i].in_g_packet)
8632 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8633 {
8634 /* This register is not available. */
8635 regcache->raw_supply (i, NULL);
8636 }
8637 }
8638
8639 /* Prepare to store registers. Since we may send them all (using a
8640 'G' request), we have to read out the ones we don't want to change
8641 first. */
8642
8643 void
8644 remote_target::prepare_to_store (struct regcache *regcache)
8645 {
8646 struct remote_state *rs = get_remote_state ();
8647 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8648 int i;
8649
8650 /* Make sure the entire registers array is valid. */
8651 switch (packet_support (PACKET_P))
8652 {
8653 case PACKET_DISABLE:
8654 case PACKET_SUPPORT_UNKNOWN:
8655 /* Make sure all the necessary registers are cached. */
8656 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8657 if (rsa->regs[i].in_g_packet)
8658 regcache->raw_update (rsa->regs[i].regnum);
8659 break;
8660 case PACKET_ENABLE:
8661 break;
8662 }
8663 }
8664
8665 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8666 packet was not recognized. */
8667
8668 int
8669 remote_target::store_register_using_P (const struct regcache *regcache,
8670 packet_reg *reg)
8671 {
8672 struct gdbarch *gdbarch = regcache->arch ();
8673 struct remote_state *rs = get_remote_state ();
8674 /* Try storing a single register. */
8675 char *buf = rs->buf.data ();
8676 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8677 char *p;
8678
8679 if (packet_support (PACKET_P) == PACKET_DISABLE)
8680 return 0;
8681
8682 if (reg->pnum == -1)
8683 return 0;
8684
8685 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8686 p = buf + strlen (buf);
8687 regcache->raw_collect (reg->regnum, regp);
8688 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8689 putpkt (rs->buf);
8690 getpkt (&rs->buf, 0);
8691
8692 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8693 {
8694 case PACKET_OK:
8695 return 1;
8696 case PACKET_ERROR:
8697 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8698 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
8699 case PACKET_UNKNOWN:
8700 return 0;
8701 default:
8702 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8703 }
8704 }
8705
8706 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8707 contents of the register cache buffer. FIXME: ignores errors. */
8708
8709 void
8710 remote_target::store_registers_using_G (const struct regcache *regcache)
8711 {
8712 struct remote_state *rs = get_remote_state ();
8713 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8714 gdb_byte *regs;
8715 char *p;
8716
8717 /* Extract all the registers in the regcache copying them into a
8718 local buffer. */
8719 {
8720 int i;
8721
8722 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8723 memset (regs, 0, rsa->sizeof_g_packet);
8724 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8725 {
8726 struct packet_reg *r = &rsa->regs[i];
8727
8728 if (r->in_g_packet)
8729 regcache->raw_collect (r->regnum, regs + r->offset);
8730 }
8731 }
8732
8733 /* Command describes registers byte by byte,
8734 each byte encoded as two hex characters. */
8735 p = rs->buf.data ();
8736 *p++ = 'G';
8737 bin2hex (regs, p, rsa->sizeof_g_packet);
8738 putpkt (rs->buf);
8739 getpkt (&rs->buf, 0);
8740 if (packet_check_result (rs->buf) == PACKET_ERROR)
8741 error (_("Could not write registers; remote failure reply '%s'"),
8742 rs->buf.data ());
8743 }
8744
8745 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8746 of the register cache buffer. FIXME: ignores errors. */
8747
8748 void
8749 remote_target::store_registers (struct regcache *regcache, int regnum)
8750 {
8751 struct gdbarch *gdbarch = regcache->arch ();
8752 struct remote_state *rs = get_remote_state ();
8753 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8754 int i;
8755
8756 set_remote_traceframe ();
8757 set_general_thread (regcache->ptid ());
8758
8759 if (regnum >= 0)
8760 {
8761 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8762
8763 gdb_assert (reg != NULL);
8764
8765 /* Always prefer to store registers using the 'P' packet if
8766 possible; we often change only a small number of registers.
8767 Sometimes we change a larger number; we'd need help from a
8768 higher layer to know to use 'G'. */
8769 if (store_register_using_P (regcache, reg))
8770 return;
8771
8772 /* For now, don't complain if we have no way to write the
8773 register. GDB loses track of unavailable registers too
8774 easily. Some day, this may be an error. We don't have
8775 any way to read the register, either... */
8776 if (!reg->in_g_packet)
8777 return;
8778
8779 store_registers_using_G (regcache);
8780 return;
8781 }
8782
8783 store_registers_using_G (regcache);
8784
8785 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8786 if (!rsa->regs[i].in_g_packet)
8787 if (!store_register_using_P (regcache, &rsa->regs[i]))
8788 /* See above for why we do not issue an error here. */
8789 continue;
8790 }
8791 \f
8792
8793 /* Return the number of hex digits in num. */
8794
8795 static int
8796 hexnumlen (ULONGEST num)
8797 {
8798 int i;
8799
8800 for (i = 0; num != 0; i++)
8801 num >>= 4;
8802
8803 return std::max (i, 1);
8804 }
8805
8806 /* Set BUF to the minimum number of hex digits representing NUM. */
8807
8808 static int
8809 hexnumstr (char *buf, ULONGEST num)
8810 {
8811 int len = hexnumlen (num);
8812
8813 return hexnumnstr (buf, num, len);
8814 }
8815
8816
8817 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
8818
8819 static int
8820 hexnumnstr (char *buf, ULONGEST num, int width)
8821 {
8822 int i;
8823
8824 buf[width] = '\0';
8825
8826 for (i = width - 1; i >= 0; i--)
8827 {
8828 buf[i] = "0123456789abcdef"[(num & 0xf)];
8829 num >>= 4;
8830 }
8831
8832 return width;
8833 }
8834
8835 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8836
8837 static CORE_ADDR
8838 remote_address_masked (CORE_ADDR addr)
8839 {
8840 unsigned int address_size = remote_address_size;
8841
8842 /* If "remoteaddresssize" was not set, default to target address size. */
8843 if (!address_size)
8844 address_size = gdbarch_addr_bit (target_gdbarch ());
8845
8846 if (address_size > 0
8847 && address_size < (sizeof (ULONGEST) * 8))
8848 {
8849 /* Only create a mask when that mask can safely be constructed
8850 in a ULONGEST variable. */
8851 ULONGEST mask = 1;
8852
8853 mask = (mask << address_size) - 1;
8854 addr &= mask;
8855 }
8856 return addr;
8857 }
8858
8859 /* Determine whether the remote target supports binary downloading.
8860 This is accomplished by sending a no-op memory write of zero length
8861 to the target at the specified address. It does not suffice to send
8862 the whole packet, since many stubs strip the eighth bit and
8863 subsequently compute a wrong checksum, which causes real havoc with
8864 remote_write_bytes.
8865
8866 NOTE: This can still lose if the serial line is not eight-bit
8867 clean. In cases like this, the user should clear "remote
8868 X-packet". */
8869
8870 void
8871 remote_target::check_binary_download (CORE_ADDR addr)
8872 {
8873 struct remote_state *rs = get_remote_state ();
8874
8875 switch (packet_support (PACKET_X))
8876 {
8877 case PACKET_DISABLE:
8878 break;
8879 case PACKET_ENABLE:
8880 break;
8881 case PACKET_SUPPORT_UNKNOWN:
8882 {
8883 char *p;
8884
8885 p = rs->buf.data ();
8886 *p++ = 'X';
8887 p += hexnumstr (p, (ULONGEST) addr);
8888 *p++ = ',';
8889 p += hexnumstr (p, (ULONGEST) 0);
8890 *p++ = ':';
8891 *p = '\0';
8892
8893 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
8894 getpkt (&rs->buf, 0);
8895
8896 if (rs->buf[0] == '\0')
8897 {
8898 remote_debug_printf ("binary downloading NOT supported by target");
8899 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8900 }
8901 else
8902 {
8903 remote_debug_printf ("binary downloading supported by target");
8904 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8905 }
8906 break;
8907 }
8908 }
8909 }
8910
8911 /* Helper function to resize the payload in order to try to get a good
8912 alignment. We try to write an amount of data such that the next write will
8913 start on an address aligned on REMOTE_ALIGN_WRITES. */
8914
8915 static int
8916 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8917 {
8918 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8919 }
8920
8921 /* Write memory data directly to the remote machine.
8922 This does not inform the data cache; the data cache uses this.
8923 HEADER is the starting part of the packet.
8924 MEMADDR is the address in the remote memory space.
8925 MYADDR is the address of the buffer in our space.
8926 LEN_UNITS is the number of addressable units to write.
8927 UNIT_SIZE is the length in bytes of an addressable unit.
8928 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8929 should send data as binary ('X'), or hex-encoded ('M').
8930
8931 The function creates packet of the form
8932 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8933
8934 where encoding of <DATA> is terminated by PACKET_FORMAT.
8935
8936 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8937 are omitted.
8938
8939 Return the transferred status, error or OK (an
8940 'enum target_xfer_status' value). Save the number of addressable units
8941 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8942
8943 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8944 exchange between gdb and the stub could look like (?? in place of the
8945 checksum):
8946
8947 -> $m1000,4#??
8948 <- aaaabbbbccccdddd
8949
8950 -> $M1000,3:eeeeffffeeee#??
8951 <- OK
8952
8953 -> $m1000,4#??
8954 <- eeeeffffeeeedddd */
8955
8956 target_xfer_status
8957 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8958 const gdb_byte *myaddr,
8959 ULONGEST len_units,
8960 int unit_size,
8961 ULONGEST *xfered_len_units,
8962 char packet_format, int use_length)
8963 {
8964 struct remote_state *rs = get_remote_state ();
8965 char *p;
8966 char *plen = NULL;
8967 int plenlen = 0;
8968 int todo_units;
8969 int units_written;
8970 int payload_capacity_bytes;
8971 int payload_length_bytes;
8972
8973 if (packet_format != 'X' && packet_format != 'M')
8974 internal_error (__FILE__, __LINE__,
8975 _("remote_write_bytes_aux: bad packet format"));
8976
8977 if (len_units == 0)
8978 return TARGET_XFER_EOF;
8979
8980 payload_capacity_bytes = get_memory_write_packet_size ();
8981
8982 /* The packet buffer will be large enough for the payload;
8983 get_memory_packet_size ensures this. */
8984 rs->buf[0] = '\0';
8985
8986 /* Compute the size of the actual payload by subtracting out the
8987 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8988
8989 payload_capacity_bytes -= strlen ("$,:#NN");
8990 if (!use_length)
8991 /* The comma won't be used. */
8992 payload_capacity_bytes += 1;
8993 payload_capacity_bytes -= strlen (header);
8994 payload_capacity_bytes -= hexnumlen (memaddr);
8995
8996 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
8997
8998 strcat (rs->buf.data (), header);
8999 p = rs->buf.data () + strlen (header);
9000
9001 /* Compute a best guess of the number of bytes actually transfered. */
9002 if (packet_format == 'X')
9003 {
9004 /* Best guess at number of bytes that will fit. */
9005 todo_units = std::min (len_units,
9006 (ULONGEST) payload_capacity_bytes / unit_size);
9007 if (use_length)
9008 payload_capacity_bytes -= hexnumlen (todo_units);
9009 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9010 }
9011 else
9012 {
9013 /* Number of bytes that will fit. */
9014 todo_units
9015 = std::min (len_units,
9016 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9017 if (use_length)
9018 payload_capacity_bytes -= hexnumlen (todo_units);
9019 todo_units = std::min (todo_units,
9020 (payload_capacity_bytes / unit_size) / 2);
9021 }
9022
9023 if (todo_units <= 0)
9024 internal_error (__FILE__, __LINE__,
9025 _("minimum packet size too small to write data"));
9026
9027 /* If we already need another packet, then try to align the end
9028 of this packet to a useful boundary. */
9029 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9030 todo_units = align_for_efficient_write (todo_units, memaddr);
9031
9032 /* Append "<memaddr>". */
9033 memaddr = remote_address_masked (memaddr);
9034 p += hexnumstr (p, (ULONGEST) memaddr);
9035
9036 if (use_length)
9037 {
9038 /* Append ",". */
9039 *p++ = ',';
9040
9041 /* Append the length and retain its location and size. It may need to be
9042 adjusted once the packet body has been created. */
9043 plen = p;
9044 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9045 p += plenlen;
9046 }
9047
9048 /* Append ":". */
9049 *p++ = ':';
9050 *p = '\0';
9051
9052 /* Append the packet body. */
9053 if (packet_format == 'X')
9054 {
9055 /* Binary mode. Send target system values byte by byte, in
9056 increasing byte addresses. Only escape certain critical
9057 characters. */
9058 payload_length_bytes =
9059 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9060 &units_written, payload_capacity_bytes);
9061
9062 /* If not all TODO units fit, then we'll need another packet. Make
9063 a second try to keep the end of the packet aligned. Don't do
9064 this if the packet is tiny. */
9065 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9066 {
9067 int new_todo_units;
9068
9069 new_todo_units = align_for_efficient_write (units_written, memaddr);
9070
9071 if (new_todo_units != units_written)
9072 payload_length_bytes =
9073 remote_escape_output (myaddr, new_todo_units, unit_size,
9074 (gdb_byte *) p, &units_written,
9075 payload_capacity_bytes);
9076 }
9077
9078 p += payload_length_bytes;
9079 if (use_length && units_written < todo_units)
9080 {
9081 /* Escape chars have filled up the buffer prematurely,
9082 and we have actually sent fewer units than planned.
9083 Fix-up the length field of the packet. Use the same
9084 number of characters as before. */
9085 plen += hexnumnstr (plen, (ULONGEST) units_written,
9086 plenlen);
9087 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9088 }
9089 }
9090 else
9091 {
9092 /* Normal mode: Send target system values byte by byte, in
9093 increasing byte addresses. Each byte is encoded as a two hex
9094 value. */
9095 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9096 units_written = todo_units;
9097 }
9098
9099 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9100 getpkt (&rs->buf, 0);
9101
9102 if (rs->buf[0] == 'E')
9103 return TARGET_XFER_E_IO;
9104
9105 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9106 send fewer units than we'd planned. */
9107 *xfered_len_units = (ULONGEST) units_written;
9108 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9109 }
9110
9111 /* Write memory data directly to the remote machine.
9112 This does not inform the data cache; the data cache uses this.
9113 MEMADDR is the address in the remote memory space.
9114 MYADDR is the address of the buffer in our space.
9115 LEN is the number of bytes.
9116
9117 Return the transferred status, error or OK (an
9118 'enum target_xfer_status' value). Save the number of bytes
9119 transferred in *XFERED_LEN. Only transfer a single packet. */
9120
9121 target_xfer_status
9122 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9123 ULONGEST len, int unit_size,
9124 ULONGEST *xfered_len)
9125 {
9126 const char *packet_format = NULL;
9127
9128 /* Check whether the target supports binary download. */
9129 check_binary_download (memaddr);
9130
9131 switch (packet_support (PACKET_X))
9132 {
9133 case PACKET_ENABLE:
9134 packet_format = "X";
9135 break;
9136 case PACKET_DISABLE:
9137 packet_format = "M";
9138 break;
9139 case PACKET_SUPPORT_UNKNOWN:
9140 internal_error (__FILE__, __LINE__,
9141 _("remote_write_bytes: bad internal state"));
9142 default:
9143 internal_error (__FILE__, __LINE__, _("bad switch"));
9144 }
9145
9146 return remote_write_bytes_aux (packet_format,
9147 memaddr, myaddr, len, unit_size, xfered_len,
9148 packet_format[0], 1);
9149 }
9150
9151 /* Read memory data directly from the remote machine.
9152 This does not use the data cache; the data cache uses this.
9153 MEMADDR is the address in the remote memory space.
9154 MYADDR is the address of the buffer in our space.
9155 LEN_UNITS is the number of addressable memory units to read..
9156 UNIT_SIZE is the length in bytes of an addressable unit.
9157
9158 Return the transferred status, error or OK (an
9159 'enum target_xfer_status' value). Save the number of bytes
9160 transferred in *XFERED_LEN_UNITS.
9161
9162 See the comment of remote_write_bytes_aux for an example of
9163 memory read/write exchange between gdb and the stub. */
9164
9165 target_xfer_status
9166 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9167 ULONGEST len_units,
9168 int unit_size, ULONGEST *xfered_len_units)
9169 {
9170 struct remote_state *rs = get_remote_state ();
9171 int buf_size_bytes; /* Max size of packet output buffer. */
9172 char *p;
9173 int todo_units;
9174 int decoded_bytes;
9175
9176 buf_size_bytes = get_memory_read_packet_size ();
9177 /* The packet buffer will be large enough for the payload;
9178 get_memory_packet_size ensures this. */
9179
9180 /* Number of units that will fit. */
9181 todo_units = std::min (len_units,
9182 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9183
9184 /* Construct "m"<memaddr>","<len>". */
9185 memaddr = remote_address_masked (memaddr);
9186 p = rs->buf.data ();
9187 *p++ = 'm';
9188 p += hexnumstr (p, (ULONGEST) memaddr);
9189 *p++ = ',';
9190 p += hexnumstr (p, (ULONGEST) todo_units);
9191 *p = '\0';
9192 putpkt (rs->buf);
9193 getpkt (&rs->buf, 0);
9194 if (rs->buf[0] == 'E'
9195 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9196 && rs->buf[3] == '\0')
9197 return TARGET_XFER_E_IO;
9198 /* Reply describes memory byte by byte, each byte encoded as two hex
9199 characters. */
9200 p = rs->buf.data ();
9201 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9202 /* Return what we have. Let higher layers handle partial reads. */
9203 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9204 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9205 }
9206
9207 /* Using the set of read-only target sections of remote, read live
9208 read-only memory.
9209
9210 For interface/parameters/return description see target.h,
9211 to_xfer_partial. */
9212
9213 target_xfer_status
9214 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9215 ULONGEST memaddr,
9216 ULONGEST len,
9217 int unit_size,
9218 ULONGEST *xfered_len)
9219 {
9220 const struct target_section *secp;
9221
9222 secp = target_section_by_addr (this, memaddr);
9223 if (secp != NULL
9224 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9225 {
9226 ULONGEST memend = memaddr + len;
9227
9228 const target_section_table *table = target_get_section_table (this);
9229 for (const target_section &p : *table)
9230 {
9231 if (memaddr >= p.addr)
9232 {
9233 if (memend <= p.endaddr)
9234 {
9235 /* Entire transfer is within this section. */
9236 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9237 xfered_len);
9238 }
9239 else if (memaddr >= p.endaddr)
9240 {
9241 /* This section ends before the transfer starts. */
9242 continue;
9243 }
9244 else
9245 {
9246 /* This section overlaps the transfer. Just do half. */
9247 len = p.endaddr - memaddr;
9248 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9249 xfered_len);
9250 }
9251 }
9252 }
9253 }
9254
9255 return TARGET_XFER_EOF;
9256 }
9257
9258 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9259 first if the requested memory is unavailable in traceframe.
9260 Otherwise, fall back to remote_read_bytes_1. */
9261
9262 target_xfer_status
9263 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9264 gdb_byte *myaddr, ULONGEST len, int unit_size,
9265 ULONGEST *xfered_len)
9266 {
9267 if (len == 0)
9268 return TARGET_XFER_EOF;
9269
9270 if (get_traceframe_number () != -1)
9271 {
9272 std::vector<mem_range> available;
9273
9274 /* If we fail to get the set of available memory, then the
9275 target does not support querying traceframe info, and so we
9276 attempt reading from the traceframe anyway (assuming the
9277 target implements the old QTro packet then). */
9278 if (traceframe_available_memory (&available, memaddr, len))
9279 {
9280 if (available.empty () || available[0].start != memaddr)
9281 {
9282 enum target_xfer_status res;
9283
9284 /* Don't read into the traceframe's available
9285 memory. */
9286 if (!available.empty ())
9287 {
9288 LONGEST oldlen = len;
9289
9290 len = available[0].start - memaddr;
9291 gdb_assert (len <= oldlen);
9292 }
9293
9294 /* This goes through the topmost target again. */
9295 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9296 len, unit_size, xfered_len);
9297 if (res == TARGET_XFER_OK)
9298 return TARGET_XFER_OK;
9299 else
9300 {
9301 /* No use trying further, we know some memory starting
9302 at MEMADDR isn't available. */
9303 *xfered_len = len;
9304 return (*xfered_len != 0) ?
9305 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9306 }
9307 }
9308
9309 /* Don't try to read more than how much is available, in
9310 case the target implements the deprecated QTro packet to
9311 cater for older GDBs (the target's knowledge of read-only
9312 sections may be outdated by now). */
9313 len = available[0].length;
9314 }
9315 }
9316
9317 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9318 }
9319
9320 \f
9321
9322 /* Sends a packet with content determined by the printf format string
9323 FORMAT and the remaining arguments, then gets the reply. Returns
9324 whether the packet was a success, a failure, or unknown. */
9325
9326 packet_result
9327 remote_target::remote_send_printf (const char *format, ...)
9328 {
9329 struct remote_state *rs = get_remote_state ();
9330 int max_size = get_remote_packet_size ();
9331 va_list ap;
9332
9333 va_start (ap, format);
9334
9335 rs->buf[0] = '\0';
9336 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9337
9338 va_end (ap);
9339
9340 if (size >= max_size)
9341 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
9342
9343 if (putpkt (rs->buf) < 0)
9344 error (_("Communication problem with target."));
9345
9346 rs->buf[0] = '\0';
9347 getpkt (&rs->buf, 0);
9348
9349 return packet_check_result (rs->buf);
9350 }
9351
9352 /* Flash writing can take quite some time. We'll set
9353 effectively infinite timeout for flash operations.
9354 In future, we'll need to decide on a better approach. */
9355 static const int remote_flash_timeout = 1000;
9356
9357 void
9358 remote_target::flash_erase (ULONGEST address, LONGEST length)
9359 {
9360 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9361 enum packet_result ret;
9362 scoped_restore restore_timeout
9363 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9364
9365 ret = remote_send_printf ("vFlashErase:%s,%s",
9366 phex (address, addr_size),
9367 phex (length, 4));
9368 switch (ret)
9369 {
9370 case PACKET_UNKNOWN:
9371 error (_("Remote target does not support flash erase"));
9372 case PACKET_ERROR:
9373 error (_("Error erasing flash with vFlashErase packet"));
9374 default:
9375 break;
9376 }
9377 }
9378
9379 target_xfer_status
9380 remote_target::remote_flash_write (ULONGEST address,
9381 ULONGEST length, ULONGEST *xfered_len,
9382 const gdb_byte *data)
9383 {
9384 scoped_restore restore_timeout
9385 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9386 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9387 xfered_len,'X', 0);
9388 }
9389
9390 void
9391 remote_target::flash_done ()
9392 {
9393 int ret;
9394
9395 scoped_restore restore_timeout
9396 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9397
9398 ret = remote_send_printf ("vFlashDone");
9399
9400 switch (ret)
9401 {
9402 case PACKET_UNKNOWN:
9403 error (_("Remote target does not support vFlashDone"));
9404 case PACKET_ERROR:
9405 error (_("Error finishing flash operation"));
9406 default:
9407 break;
9408 }
9409 }
9410
9411 \f
9412 /* Stuff for dealing with the packets which are part of this protocol.
9413 See comment at top of file for details. */
9414
9415 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9416 error to higher layers. Called when a serial error is detected.
9417 The exception message is STRING, followed by a colon and a blank,
9418 the system error message for errno at function entry and final dot
9419 for output compatibility with throw_perror_with_name. */
9420
9421 static void
9422 unpush_and_perror (remote_target *target, const char *string)
9423 {
9424 int saved_errno = errno;
9425
9426 remote_unpush_target (target);
9427 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9428 safe_strerror (saved_errno));
9429 }
9430
9431 /* Read a single character from the remote end. The current quit
9432 handler is overridden to avoid quitting in the middle of packet
9433 sequence, as that would break communication with the remote server.
9434 See remote_serial_quit_handler for more detail. */
9435
9436 int
9437 remote_target::readchar (int timeout)
9438 {
9439 int ch;
9440 struct remote_state *rs = get_remote_state ();
9441
9442 {
9443 scoped_restore restore_quit_target
9444 = make_scoped_restore (&curr_quit_handler_target, this);
9445 scoped_restore restore_quit
9446 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9447
9448 rs->got_ctrlc_during_io = 0;
9449
9450 ch = serial_readchar (rs->remote_desc, timeout);
9451
9452 if (rs->got_ctrlc_during_io)
9453 set_quit_flag ();
9454 }
9455
9456 if (ch >= 0)
9457 return ch;
9458
9459 switch ((enum serial_rc) ch)
9460 {
9461 case SERIAL_EOF:
9462 remote_unpush_target (this);
9463 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9464 /* no return */
9465 case SERIAL_ERROR:
9466 unpush_and_perror (this, _("Remote communication error. "
9467 "Target disconnected."));
9468 /* no return */
9469 case SERIAL_TIMEOUT:
9470 break;
9471 }
9472 return ch;
9473 }
9474
9475 /* Wrapper for serial_write that closes the target and throws if
9476 writing fails. The current quit handler is overridden to avoid
9477 quitting in the middle of packet sequence, as that would break
9478 communication with the remote server. See
9479 remote_serial_quit_handler for more detail. */
9480
9481 void
9482 remote_target::remote_serial_write (const char *str, int len)
9483 {
9484 struct remote_state *rs = get_remote_state ();
9485
9486 scoped_restore restore_quit_target
9487 = make_scoped_restore (&curr_quit_handler_target, this);
9488 scoped_restore restore_quit
9489 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9490
9491 rs->got_ctrlc_during_io = 0;
9492
9493 if (serial_write (rs->remote_desc, str, len))
9494 {
9495 unpush_and_perror (this, _("Remote communication error. "
9496 "Target disconnected."));
9497 }
9498
9499 if (rs->got_ctrlc_during_io)
9500 set_quit_flag ();
9501 }
9502
9503 /* Return a string representing an escaped version of BUF, of len N.
9504 E.g. \n is converted to \\n, \t to \\t, etc. */
9505
9506 static std::string
9507 escape_buffer (const char *buf, int n)
9508 {
9509 string_file stb;
9510
9511 stb.putstrn (buf, n, '\\');
9512 return stb.release ();
9513 }
9514
9515 int
9516 remote_target::putpkt (const char *buf)
9517 {
9518 return putpkt_binary (buf, strlen (buf));
9519 }
9520
9521 /* Wrapper around remote_target::putpkt to avoid exporting
9522 remote_target. */
9523
9524 int
9525 putpkt (remote_target *remote, const char *buf)
9526 {
9527 return remote->putpkt (buf);
9528 }
9529
9530 /* Send a packet to the remote machine, with error checking. The data
9531 of the packet is in BUF. The string in BUF can be at most
9532 get_remote_packet_size () - 5 to account for the $, # and checksum,
9533 and for a possible /0 if we are debugging (remote_debug) and want
9534 to print the sent packet as a string. */
9535
9536 int
9537 remote_target::putpkt_binary (const char *buf, int cnt)
9538 {
9539 struct remote_state *rs = get_remote_state ();
9540 int i;
9541 unsigned char csum = 0;
9542 gdb::def_vector<char> data (cnt + 6);
9543 char *buf2 = data.data ();
9544
9545 int ch;
9546 int tcount = 0;
9547 char *p;
9548
9549 /* Catch cases like trying to read memory or listing threads while
9550 we're waiting for a stop reply. The remote server wouldn't be
9551 ready to handle this request, so we'd hang and timeout. We don't
9552 have to worry about this in synchronous mode, because in that
9553 case it's not possible to issue a command while the target is
9554 running. This is not a problem in non-stop mode, because in that
9555 case, the stub is always ready to process serial input. */
9556 if (!target_is_non_stop_p ()
9557 && target_is_async_p ()
9558 && rs->waiting_for_stop_reply)
9559 {
9560 error (_("Cannot execute this command while the target is running.\n"
9561 "Use the \"interrupt\" command to stop the target\n"
9562 "and then try again."));
9563 }
9564
9565 /* Copy the packet into buffer BUF2, encapsulating it
9566 and giving it a checksum. */
9567
9568 p = buf2;
9569 *p++ = '$';
9570
9571 for (i = 0; i < cnt; i++)
9572 {
9573 csum += buf[i];
9574 *p++ = buf[i];
9575 }
9576 *p++ = '#';
9577 *p++ = tohex ((csum >> 4) & 0xf);
9578 *p++ = tohex (csum & 0xf);
9579
9580 /* Send it over and over until we get a positive ack. */
9581
9582 while (1)
9583 {
9584 if (remote_debug)
9585 {
9586 *p = '\0';
9587
9588 int len = (int) (p - buf2);
9589 int max_chars;
9590
9591 if (remote_packet_max_chars < 0)
9592 max_chars = len;
9593 else
9594 max_chars = remote_packet_max_chars;
9595
9596 std::string str
9597 = escape_buffer (buf2, std::min (len, max_chars));
9598
9599 if (len > max_chars)
9600 remote_debug_printf_nofunc
9601 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9602 len - max_chars);
9603 else
9604 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9605 }
9606 remote_serial_write (buf2, p - buf2);
9607
9608 /* If this is a no acks version of the remote protocol, send the
9609 packet and move on. */
9610 if (rs->noack_mode)
9611 break;
9612
9613 /* Read until either a timeout occurs (-2) or '+' is read.
9614 Handle any notification that arrives in the mean time. */
9615 while (1)
9616 {
9617 ch = readchar (remote_timeout);
9618
9619 switch (ch)
9620 {
9621 case '+':
9622 remote_debug_printf_nofunc ("Received Ack");
9623 return 1;
9624 case '-':
9625 remote_debug_printf_nofunc ("Received Nak");
9626 /* FALLTHROUGH */
9627 case SERIAL_TIMEOUT:
9628 tcount++;
9629 if (tcount > 3)
9630 return 0;
9631 break; /* Retransmit buffer. */
9632 case '$':
9633 {
9634 remote_debug_printf ("Packet instead of Ack, ignoring it");
9635 /* It's probably an old response sent because an ACK
9636 was lost. Gobble up the packet and ack it so it
9637 doesn't get retransmitted when we resend this
9638 packet. */
9639 skip_frame ();
9640 remote_serial_write ("+", 1);
9641 continue; /* Now, go look for +. */
9642 }
9643
9644 case '%':
9645 {
9646 int val;
9647
9648 /* If we got a notification, handle it, and go back to looking
9649 for an ack. */
9650 /* We've found the start of a notification. Now
9651 collect the data. */
9652 val = read_frame (&rs->buf);
9653 if (val >= 0)
9654 {
9655 remote_debug_printf_nofunc
9656 (" Notification received: %s",
9657 escape_buffer (rs->buf.data (), val).c_str ());
9658
9659 handle_notification (rs->notif_state, rs->buf.data ());
9660 /* We're in sync now, rewait for the ack. */
9661 tcount = 0;
9662 }
9663 else
9664 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9665 rs->buf.data ());
9666 continue;
9667 }
9668 /* fall-through */
9669 default:
9670 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9671 rs->buf.data ());
9672 continue;
9673 }
9674 break; /* Here to retransmit. */
9675 }
9676
9677 #if 0
9678 /* This is wrong. If doing a long backtrace, the user should be
9679 able to get out next time we call QUIT, without anything as
9680 violent as interrupt_query. If we want to provide a way out of
9681 here without getting to the next QUIT, it should be based on
9682 hitting ^C twice as in remote_wait. */
9683 if (quit_flag)
9684 {
9685 quit_flag = 0;
9686 interrupt_query ();
9687 }
9688 #endif
9689 }
9690
9691 return 0;
9692 }
9693
9694 /* Come here after finding the start of a frame when we expected an
9695 ack. Do our best to discard the rest of this packet. */
9696
9697 void
9698 remote_target::skip_frame ()
9699 {
9700 int c;
9701
9702 while (1)
9703 {
9704 c = readchar (remote_timeout);
9705 switch (c)
9706 {
9707 case SERIAL_TIMEOUT:
9708 /* Nothing we can do. */
9709 return;
9710 case '#':
9711 /* Discard the two bytes of checksum and stop. */
9712 c = readchar (remote_timeout);
9713 if (c >= 0)
9714 c = readchar (remote_timeout);
9715
9716 return;
9717 case '*': /* Run length encoding. */
9718 /* Discard the repeat count. */
9719 c = readchar (remote_timeout);
9720 if (c < 0)
9721 return;
9722 break;
9723 default:
9724 /* A regular character. */
9725 break;
9726 }
9727 }
9728 }
9729
9730 /* Come here after finding the start of the frame. Collect the rest
9731 into *BUF, verifying the checksum, length, and handling run-length
9732 compression. NUL terminate the buffer. If there is not enough room,
9733 expand *BUF.
9734
9735 Returns -1 on error, number of characters in buffer (ignoring the
9736 trailing NULL) on success. (could be extended to return one of the
9737 SERIAL status indications). */
9738
9739 long
9740 remote_target::read_frame (gdb::char_vector *buf_p)
9741 {
9742 unsigned char csum;
9743 long bc;
9744 int c;
9745 char *buf = buf_p->data ();
9746 struct remote_state *rs = get_remote_state ();
9747
9748 csum = 0;
9749 bc = 0;
9750
9751 while (1)
9752 {
9753 c = readchar (remote_timeout);
9754 switch (c)
9755 {
9756 case SERIAL_TIMEOUT:
9757 remote_debug_printf ("Timeout in mid-packet, retrying");
9758 return -1;
9759
9760 case '$':
9761 remote_debug_printf ("Saw new packet start in middle of old one");
9762 return -1; /* Start a new packet, count retries. */
9763
9764 case '#':
9765 {
9766 unsigned char pktcsum;
9767 int check_0 = 0;
9768 int check_1 = 0;
9769
9770 buf[bc] = '\0';
9771
9772 check_0 = readchar (remote_timeout);
9773 if (check_0 >= 0)
9774 check_1 = readchar (remote_timeout);
9775
9776 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9777 {
9778 remote_debug_printf ("Timeout in checksum, retrying");
9779 return -1;
9780 }
9781 else if (check_0 < 0 || check_1 < 0)
9782 {
9783 remote_debug_printf ("Communication error in checksum");
9784 return -1;
9785 }
9786
9787 /* Don't recompute the checksum; with no ack packets we
9788 don't have any way to indicate a packet retransmission
9789 is necessary. */
9790 if (rs->noack_mode)
9791 return bc;
9792
9793 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9794 if (csum == pktcsum)
9795 return bc;
9796
9797 remote_debug_printf
9798 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
9799 pktcsum, csum, escape_buffer (buf, bc).c_str ());
9800
9801 /* Number of characters in buffer ignoring trailing
9802 NULL. */
9803 return -1;
9804 }
9805 case '*': /* Run length encoding. */
9806 {
9807 int repeat;
9808
9809 csum += c;
9810 c = readchar (remote_timeout);
9811 csum += c;
9812 repeat = c - ' ' + 3; /* Compute repeat count. */
9813
9814 /* The character before ``*'' is repeated. */
9815
9816 if (repeat > 0 && repeat <= 255 && bc > 0)
9817 {
9818 if (bc + repeat - 1 >= buf_p->size () - 1)
9819 {
9820 /* Make some more room in the buffer. */
9821 buf_p->resize (buf_p->size () + repeat);
9822 buf = buf_p->data ();
9823 }
9824
9825 memset (&buf[bc], buf[bc - 1], repeat);
9826 bc += repeat;
9827 continue;
9828 }
9829
9830 buf[bc] = '\0';
9831 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
9832 return -1;
9833 }
9834 default:
9835 if (bc >= buf_p->size () - 1)
9836 {
9837 /* Make some more room in the buffer. */
9838 buf_p->resize (buf_p->size () * 2);
9839 buf = buf_p->data ();
9840 }
9841
9842 buf[bc++] = c;
9843 csum += c;
9844 continue;
9845 }
9846 }
9847 }
9848
9849 /* Set this to the maximum number of seconds to wait instead of waiting forever
9850 in target_wait(). If this timer times out, then it generates an error and
9851 the command is aborted. This replaces most of the need for timeouts in the
9852 GDB test suite, and makes it possible to distinguish between a hung target
9853 and one with slow communications. */
9854
9855 static int watchdog = 0;
9856 static void
9857 show_watchdog (struct ui_file *file, int from_tty,
9858 struct cmd_list_element *c, const char *value)
9859 {
9860 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
9861 }
9862
9863 /* Read a packet from the remote machine, with error checking, and
9864 store it in *BUF. Resize *BUF if necessary to hold the result. If
9865 FOREVER, wait forever rather than timing out; this is used (in
9866 synchronous mode) to wait for a target that is is executing user
9867 code to stop. */
9868 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9869 don't have to change all the calls to getpkt to deal with the
9870 return value, because at the moment I don't know what the right
9871 thing to do it for those. */
9872
9873 void
9874 remote_target::getpkt (gdb::char_vector *buf, int forever)
9875 {
9876 getpkt_sane (buf, forever);
9877 }
9878
9879
9880 /* Read a packet from the remote machine, with error checking, and
9881 store it in *BUF. Resize *BUF if necessary to hold the result. If
9882 FOREVER, wait forever rather than timing out; this is used (in
9883 synchronous mode) to wait for a target that is is executing user
9884 code to stop. If FOREVER == 0, this function is allowed to time
9885 out gracefully and return an indication of this to the caller.
9886 Otherwise return the number of bytes read. If EXPECTING_NOTIF,
9887 consider receiving a notification enough reason to return to the
9888 caller. *IS_NOTIF is an output boolean that indicates whether *BUF
9889 holds a notification or not (a regular packet). */
9890
9891 int
9892 remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
9893 int forever, int expecting_notif,
9894 int *is_notif)
9895 {
9896 struct remote_state *rs = get_remote_state ();
9897 int c;
9898 int tries;
9899 int timeout;
9900 int val = -1;
9901
9902 strcpy (buf->data (), "timeout");
9903
9904 if (forever)
9905 timeout = watchdog > 0 ? watchdog : -1;
9906 else if (expecting_notif)
9907 timeout = 0; /* There should already be a char in the buffer. If
9908 not, bail out. */
9909 else
9910 timeout = remote_timeout;
9911
9912 #define MAX_TRIES 3
9913
9914 /* Process any number of notifications, and then return when
9915 we get a packet. */
9916 for (;;)
9917 {
9918 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9919 times. */
9920 for (tries = 1; tries <= MAX_TRIES; tries++)
9921 {
9922 /* This can loop forever if the remote side sends us
9923 characters continuously, but if it pauses, we'll get
9924 SERIAL_TIMEOUT from readchar because of timeout. Then
9925 we'll count that as a retry.
9926
9927 Note that even when forever is set, we will only wait
9928 forever prior to the start of a packet. After that, we
9929 expect characters to arrive at a brisk pace. They should
9930 show up within remote_timeout intervals. */
9931 do
9932 c = readchar (timeout);
9933 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9934
9935 if (c == SERIAL_TIMEOUT)
9936 {
9937 if (expecting_notif)
9938 return -1; /* Don't complain, it's normal to not get
9939 anything in this case. */
9940
9941 if (forever) /* Watchdog went off? Kill the target. */
9942 {
9943 remote_unpush_target (this);
9944 throw_error (TARGET_CLOSE_ERROR,
9945 _("Watchdog timeout has expired. "
9946 "Target detached."));
9947 }
9948
9949 remote_debug_printf ("Timed out.");
9950 }
9951 else
9952 {
9953 /* We've found the start of a packet or notification.
9954 Now collect the data. */
9955 val = read_frame (buf);
9956 if (val >= 0)
9957 break;
9958 }
9959
9960 remote_serial_write ("-", 1);
9961 }
9962
9963 if (tries > MAX_TRIES)
9964 {
9965 /* We have tried hard enough, and just can't receive the
9966 packet/notification. Give up. */
9967 gdb_printf (_("Ignoring packet error, continuing...\n"));
9968
9969 /* Skip the ack char if we're in no-ack mode. */
9970 if (!rs->noack_mode)
9971 remote_serial_write ("+", 1);
9972 return -1;
9973 }
9974
9975 /* If we got an ordinary packet, return that to our caller. */
9976 if (c == '$')
9977 {
9978 if (remote_debug)
9979 {
9980 int max_chars;
9981
9982 if (remote_packet_max_chars < 0)
9983 max_chars = val;
9984 else
9985 max_chars = remote_packet_max_chars;
9986
9987 std::string str
9988 = escape_buffer (buf->data (),
9989 std::min (val, max_chars));
9990
9991 if (val > max_chars)
9992 remote_debug_printf_nofunc
9993 ("Packet received: %s [%d bytes omitted]", str.c_str (),
9994 val - max_chars);
9995 else
9996 remote_debug_printf_nofunc ("Packet received: %s",
9997 str.c_str ());
9998 }
9999
10000 /* Skip the ack char if we're in no-ack mode. */
10001 if (!rs->noack_mode)
10002 remote_serial_write ("+", 1);
10003 if (is_notif != NULL)
10004 *is_notif = 0;
10005 return val;
10006 }
10007
10008 /* If we got a notification, handle it, and go back to looking
10009 for a packet. */
10010 else
10011 {
10012 gdb_assert (c == '%');
10013
10014 remote_debug_printf_nofunc
10015 (" Notification received: %s",
10016 escape_buffer (buf->data (), val).c_str ());
10017
10018 if (is_notif != NULL)
10019 *is_notif = 1;
10020
10021 handle_notification (rs->notif_state, buf->data ());
10022
10023 /* Notifications require no acknowledgement. */
10024
10025 if (expecting_notif)
10026 return val;
10027 }
10028 }
10029 }
10030
10031 int
10032 remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
10033 {
10034 return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
10035 }
10036
10037 int
10038 remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
10039 int *is_notif)
10040 {
10041 return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
10042 }
10043
10044 /* Kill any new fork children of inferior INF that haven't been
10045 processed by follow_fork. */
10046
10047 void
10048 remote_target::kill_new_fork_children (inferior *inf)
10049 {
10050 remote_state *rs = get_remote_state ();
10051 struct notif_client *notif = &notif_client_stop;
10052
10053 /* Kill the fork child threads of any threads in inferior INF that are stopped
10054 at a fork event. */
10055 for (thread_info *thread : inf->non_exited_threads ())
10056 {
10057 const target_waitstatus *ws = thread_pending_fork_status (thread);
10058
10059 if (ws == nullptr)
10060 continue;
10061
10062 int child_pid = ws->child_ptid ().pid ();
10063 int res = remote_vkill (child_pid);
10064
10065 if (res != 0)
10066 error (_("Can't kill fork child process %d"), child_pid);
10067 }
10068
10069 /* Check for any pending fork events (not reported or processed yet)
10070 in inferior INF and kill those fork child threads as well. */
10071 remote_notif_get_pending_events (notif);
10072 for (auto &event : rs->stop_reply_queue)
10073 {
10074 if (event->ptid.pid () != inf->pid)
10075 continue;
10076
10077 if (!is_fork_status (event->ws.kind ()))
10078 continue;
10079
10080 int child_pid = event->ws.child_ptid ().pid ();
10081 int res = remote_vkill (child_pid);
10082
10083 if (res != 0)
10084 error (_("Can't kill fork child process %d"), child_pid);
10085 }
10086 }
10087
10088 \f
10089 /* Target hook to kill the current inferior. */
10090
10091 void
10092 remote_target::kill ()
10093 {
10094 int res = -1;
10095 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10096 struct remote_state *rs = get_remote_state ();
10097
10098 gdb_assert (inf != nullptr);
10099
10100 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
10101 {
10102 /* If we're stopped while forking and we haven't followed yet,
10103 kill the child task. We need to do this before killing the
10104 parent task because if this is a vfork then the parent will
10105 be sleeping. */
10106 kill_new_fork_children (inf);
10107
10108 res = remote_vkill (inf->pid);
10109 if (res == 0)
10110 {
10111 target_mourn_inferior (inferior_ptid);
10112 return;
10113 }
10114 }
10115
10116 /* If we are in 'target remote' mode and we are killing the only
10117 inferior, then we will tell gdbserver to exit and unpush the
10118 target. */
10119 if (res == -1 && !remote_multi_process_p (rs)
10120 && number_of_live_inferiors (this) == 1)
10121 {
10122 remote_kill_k ();
10123
10124 /* We've killed the remote end, we get to mourn it. If we are
10125 not in extended mode, mourning the inferior also unpushes
10126 remote_ops from the target stack, which closes the remote
10127 connection. */
10128 target_mourn_inferior (inferior_ptid);
10129
10130 return;
10131 }
10132
10133 error (_("Can't kill process"));
10134 }
10135
10136 /* Send a kill request to the target using the 'vKill' packet. */
10137
10138 int
10139 remote_target::remote_vkill (int pid)
10140 {
10141 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
10142 return -1;
10143
10144 remote_state *rs = get_remote_state ();
10145
10146 /* Tell the remote target to detach. */
10147 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10148 putpkt (rs->buf);
10149 getpkt (&rs->buf, 0);
10150
10151 switch (packet_ok (rs->buf,
10152 &remote_protocol_packets[PACKET_vKill]))
10153 {
10154 case PACKET_OK:
10155 return 0;
10156 case PACKET_ERROR:
10157 return 1;
10158 case PACKET_UNKNOWN:
10159 return -1;
10160 default:
10161 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
10162 }
10163 }
10164
10165 /* Send a kill request to the target using the 'k' packet. */
10166
10167 void
10168 remote_target::remote_kill_k ()
10169 {
10170 /* Catch errors so the user can quit from gdb even when we
10171 aren't on speaking terms with the remote system. */
10172 try
10173 {
10174 putpkt ("k");
10175 }
10176 catch (const gdb_exception_error &ex)
10177 {
10178 if (ex.error == TARGET_CLOSE_ERROR)
10179 {
10180 /* If we got an (EOF) error that caused the target
10181 to go away, then we're done, that's what we wanted.
10182 "k" is susceptible to cause a premature EOF, given
10183 that the remote server isn't actually required to
10184 reply to "k", and it can happen that it doesn't
10185 even get to reply ACK to the "k". */
10186 return;
10187 }
10188
10189 /* Otherwise, something went wrong. We didn't actually kill
10190 the target. Just propagate the exception, and let the
10191 user or higher layers decide what to do. */
10192 throw;
10193 }
10194 }
10195
10196 void
10197 remote_target::mourn_inferior ()
10198 {
10199 struct remote_state *rs = get_remote_state ();
10200
10201 /* We're no longer interested in notification events of an inferior
10202 that exited or was killed/detached. */
10203 discard_pending_stop_replies (current_inferior ());
10204
10205 /* In 'target remote' mode with one inferior, we close the connection. */
10206 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10207 {
10208 remote_unpush_target (this);
10209 return;
10210 }
10211
10212 /* In case we got here due to an error, but we're going to stay
10213 connected. */
10214 rs->waiting_for_stop_reply = 0;
10215
10216 /* If the current general thread belonged to the process we just
10217 detached from or has exited, the remote side current general
10218 thread becomes undefined. Considering a case like this:
10219
10220 - We just got here due to a detach.
10221 - The process that we're detaching from happens to immediately
10222 report a global breakpoint being hit in non-stop mode, in the
10223 same thread we had selected before.
10224 - GDB attaches to this process again.
10225 - This event happens to be the next event we handle.
10226
10227 GDB would consider that the current general thread didn't need to
10228 be set on the stub side (with Hg), since for all it knew,
10229 GENERAL_THREAD hadn't changed.
10230
10231 Notice that although in all-stop mode, the remote server always
10232 sets the current thread to the thread reporting the stop event,
10233 that doesn't happen in non-stop mode; in non-stop, the stub *must
10234 not* change the current thread when reporting a breakpoint hit,
10235 due to the decoupling of event reporting and event handling.
10236
10237 To keep things simple, we always invalidate our notion of the
10238 current thread. */
10239 record_currthread (rs, minus_one_ptid);
10240
10241 /* Call common code to mark the inferior as not running. */
10242 generic_mourn_inferior ();
10243 }
10244
10245 bool
10246 extended_remote_target::supports_disable_randomization ()
10247 {
10248 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
10249 }
10250
10251 void
10252 remote_target::extended_remote_disable_randomization (int val)
10253 {
10254 struct remote_state *rs = get_remote_state ();
10255 char *reply;
10256
10257 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10258 "QDisableRandomization:%x", val);
10259 putpkt (rs->buf);
10260 reply = remote_get_noisy_reply ();
10261 if (*reply == '\0')
10262 error (_("Target does not support QDisableRandomization."));
10263 if (strcmp (reply, "OK") != 0)
10264 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10265 }
10266
10267 int
10268 remote_target::extended_remote_run (const std::string &args)
10269 {
10270 struct remote_state *rs = get_remote_state ();
10271 int len;
10272 const char *remote_exec_file = get_remote_exec_file ();
10273
10274 /* If the user has disabled vRun support, or we have detected that
10275 support is not available, do not try it. */
10276 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
10277 return -1;
10278
10279 strcpy (rs->buf.data (), "vRun;");
10280 len = strlen (rs->buf.data ());
10281
10282 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10283 error (_("Remote file name too long for run packet"));
10284 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10285 strlen (remote_exec_file));
10286
10287 if (!args.empty ())
10288 {
10289 int i;
10290
10291 gdb_argv argv (args.c_str ());
10292 for (i = 0; argv[i] != NULL; i++)
10293 {
10294 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10295 error (_("Argument list too long for run packet"));
10296 rs->buf[len++] = ';';
10297 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10298 strlen (argv[i]));
10299 }
10300 }
10301
10302 rs->buf[len++] = '\0';
10303
10304 putpkt (rs->buf);
10305 getpkt (&rs->buf, 0);
10306
10307 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
10308 {
10309 case PACKET_OK:
10310 /* We have a wait response. All is well. */
10311 return 0;
10312 case PACKET_UNKNOWN:
10313 return -1;
10314 case PACKET_ERROR:
10315 if (remote_exec_file[0] == '\0')
10316 error (_("Running the default executable on the remote target failed; "
10317 "try \"set remote exec-file\"?"));
10318 else
10319 error (_("Running \"%s\" on the remote target failed"),
10320 remote_exec_file);
10321 default:
10322 gdb_assert_not_reached ("bad switch");
10323 }
10324 }
10325
10326 /* Helper function to send set/unset environment packets. ACTION is
10327 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10328 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10329 sent. */
10330
10331 void
10332 remote_target::send_environment_packet (const char *action,
10333 const char *packet,
10334 const char *value)
10335 {
10336 remote_state *rs = get_remote_state ();
10337
10338 /* Convert the environment variable to an hex string, which
10339 is the best format to be transmitted over the wire. */
10340 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10341 strlen (value));
10342
10343 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10344 "%s:%s", packet, encoded_value.c_str ());
10345
10346 putpkt (rs->buf);
10347 getpkt (&rs->buf, 0);
10348 if (strcmp (rs->buf.data (), "OK") != 0)
10349 warning (_("Unable to %s environment variable '%s' on remote."),
10350 action, value);
10351 }
10352
10353 /* Helper function to handle the QEnvironment* packets. */
10354
10355 void
10356 remote_target::extended_remote_environment_support ()
10357 {
10358 remote_state *rs = get_remote_state ();
10359
10360 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10361 {
10362 putpkt ("QEnvironmentReset");
10363 getpkt (&rs->buf, 0);
10364 if (strcmp (rs->buf.data (), "OK") != 0)
10365 warning (_("Unable to reset environment on remote."));
10366 }
10367
10368 gdb_environ *e = &current_inferior ()->environment;
10369
10370 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10371 for (const std::string &el : e->user_set_env ())
10372 send_environment_packet ("set", "QEnvironmentHexEncoded",
10373 el.c_str ());
10374
10375 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10376 for (const std::string &el : e->user_unset_env ())
10377 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10378 }
10379
10380 /* Helper function to set the current working directory for the
10381 inferior in the remote target. */
10382
10383 void
10384 remote_target::extended_remote_set_inferior_cwd ()
10385 {
10386 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10387 {
10388 const std::string &inferior_cwd = current_inferior ()->cwd ();
10389 remote_state *rs = get_remote_state ();
10390
10391 if (!inferior_cwd.empty ())
10392 {
10393 std::string hexpath
10394 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10395 inferior_cwd.size ());
10396
10397 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10398 "QSetWorkingDir:%s", hexpath.c_str ());
10399 }
10400 else
10401 {
10402 /* An empty inferior_cwd means that the user wants us to
10403 reset the remote server's inferior's cwd. */
10404 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10405 "QSetWorkingDir:");
10406 }
10407
10408 putpkt (rs->buf);
10409 getpkt (&rs->buf, 0);
10410 if (packet_ok (rs->buf,
10411 &remote_protocol_packets[PACKET_QSetWorkingDir])
10412 != PACKET_OK)
10413 error (_("\
10414 Remote replied unexpectedly while setting the inferior's working\n\
10415 directory: %s"),
10416 rs->buf.data ());
10417
10418 }
10419 }
10420
10421 /* In the extended protocol we want to be able to do things like
10422 "run" and have them basically work as expected. So we need
10423 a special create_inferior function. We support changing the
10424 executable file and the command line arguments, but not the
10425 environment. */
10426
10427 void
10428 extended_remote_target::create_inferior (const char *exec_file,
10429 const std::string &args,
10430 char **env, int from_tty)
10431 {
10432 int run_worked;
10433 char *stop_reply;
10434 struct remote_state *rs = get_remote_state ();
10435 const char *remote_exec_file = get_remote_exec_file ();
10436
10437 /* If running asynchronously, register the target file descriptor
10438 with the event loop. */
10439 if (target_can_async_p ())
10440 target_async (1);
10441
10442 /* Disable address space randomization if requested (and supported). */
10443 if (supports_disable_randomization ())
10444 extended_remote_disable_randomization (disable_randomization);
10445
10446 /* If startup-with-shell is on, we inform gdbserver to start the
10447 remote inferior using a shell. */
10448 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10449 {
10450 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10451 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10452 putpkt (rs->buf);
10453 getpkt (&rs->buf, 0);
10454 if (strcmp (rs->buf.data (), "OK") != 0)
10455 error (_("\
10456 Remote replied unexpectedly while setting startup-with-shell: %s"),
10457 rs->buf.data ());
10458 }
10459
10460 extended_remote_environment_support ();
10461
10462 extended_remote_set_inferior_cwd ();
10463
10464 /* Now restart the remote server. */
10465 run_worked = extended_remote_run (args) != -1;
10466 if (!run_worked)
10467 {
10468 /* vRun was not supported. Fail if we need it to do what the
10469 user requested. */
10470 if (remote_exec_file[0])
10471 error (_("Remote target does not support \"set remote exec-file\""));
10472 if (!args.empty ())
10473 error (_("Remote target does not support \"set args\" or run ARGS"));
10474
10475 /* Fall back to "R". */
10476 extended_remote_restart ();
10477 }
10478
10479 /* vRun's success return is a stop reply. */
10480 stop_reply = run_worked ? rs->buf.data () : NULL;
10481 add_current_inferior_and_thread (stop_reply);
10482
10483 /* Get updated offsets, if the stub uses qOffsets. */
10484 get_offsets ();
10485 }
10486 \f
10487
10488 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10489 the list of conditions (in agent expression bytecode format), if any, the
10490 target needs to evaluate. The output is placed into the packet buffer
10491 started from BUF and ended at BUF_END. */
10492
10493 static int
10494 remote_add_target_side_condition (struct gdbarch *gdbarch,
10495 struct bp_target_info *bp_tgt, char *buf,
10496 char *buf_end)
10497 {
10498 if (bp_tgt->conditions.empty ())
10499 return 0;
10500
10501 buf += strlen (buf);
10502 xsnprintf (buf, buf_end - buf, "%s", ";");
10503 buf++;
10504
10505 /* Send conditions to the target. */
10506 for (agent_expr *aexpr : bp_tgt->conditions)
10507 {
10508 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10509 buf += strlen (buf);
10510 for (int i = 0; i < aexpr->len; ++i)
10511 buf = pack_hex_byte (buf, aexpr->buf[i]);
10512 *buf = '\0';
10513 }
10514 return 0;
10515 }
10516
10517 static void
10518 remote_add_target_side_commands (struct gdbarch *gdbarch,
10519 struct bp_target_info *bp_tgt, char *buf)
10520 {
10521 if (bp_tgt->tcommands.empty ())
10522 return;
10523
10524 buf += strlen (buf);
10525
10526 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10527 buf += strlen (buf);
10528
10529 /* Concatenate all the agent expressions that are commands into the
10530 cmds parameter. */
10531 for (agent_expr *aexpr : bp_tgt->tcommands)
10532 {
10533 sprintf (buf, "X%x,", aexpr->len);
10534 buf += strlen (buf);
10535 for (int i = 0; i < aexpr->len; ++i)
10536 buf = pack_hex_byte (buf, aexpr->buf[i]);
10537 *buf = '\0';
10538 }
10539 }
10540
10541 /* Insert a breakpoint. On targets that have software breakpoint
10542 support, we ask the remote target to do the work; on targets
10543 which don't, we insert a traditional memory breakpoint. */
10544
10545 int
10546 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10547 struct bp_target_info *bp_tgt)
10548 {
10549 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10550 If it succeeds, then set the support to PACKET_ENABLE. If it
10551 fails, and the user has explicitly requested the Z support then
10552 report an error, otherwise, mark it disabled and go on. */
10553
10554 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10555 {
10556 CORE_ADDR addr = bp_tgt->reqstd_address;
10557 struct remote_state *rs;
10558 char *p, *endbuf;
10559
10560 /* Make sure the remote is pointing at the right process, if
10561 necessary. */
10562 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10563 set_general_process ();
10564
10565 rs = get_remote_state ();
10566 p = rs->buf.data ();
10567 endbuf = p + get_remote_packet_size ();
10568
10569 *(p++) = 'Z';
10570 *(p++) = '0';
10571 *(p++) = ',';
10572 addr = (ULONGEST) remote_address_masked (addr);
10573 p += hexnumstr (p, addr);
10574 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10575
10576 if (supports_evaluation_of_breakpoint_conditions ())
10577 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10578
10579 if (can_run_breakpoint_commands ())
10580 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10581
10582 putpkt (rs->buf);
10583 getpkt (&rs->buf, 0);
10584
10585 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10586 {
10587 case PACKET_ERROR:
10588 return -1;
10589 case PACKET_OK:
10590 return 0;
10591 case PACKET_UNKNOWN:
10592 break;
10593 }
10594 }
10595
10596 /* If this breakpoint has target-side commands but this stub doesn't
10597 support Z0 packets, throw error. */
10598 if (!bp_tgt->tcommands.empty ())
10599 throw_error (NOT_SUPPORTED_ERROR, _("\
10600 Target doesn't support breakpoints that have target side commands."));
10601
10602 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10603 }
10604
10605 int
10606 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10607 struct bp_target_info *bp_tgt,
10608 enum remove_bp_reason reason)
10609 {
10610 CORE_ADDR addr = bp_tgt->placed_address;
10611 struct remote_state *rs = get_remote_state ();
10612
10613 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10614 {
10615 char *p = rs->buf.data ();
10616 char *endbuf = p + get_remote_packet_size ();
10617
10618 /* Make sure the remote is pointing at the right process, if
10619 necessary. */
10620 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10621 set_general_process ();
10622
10623 *(p++) = 'z';
10624 *(p++) = '0';
10625 *(p++) = ',';
10626
10627 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10628 p += hexnumstr (p, addr);
10629 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10630
10631 putpkt (rs->buf);
10632 getpkt (&rs->buf, 0);
10633
10634 return (rs->buf[0] == 'E');
10635 }
10636
10637 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10638 }
10639
10640 static enum Z_packet_type
10641 watchpoint_to_Z_packet (int type)
10642 {
10643 switch (type)
10644 {
10645 case hw_write:
10646 return Z_PACKET_WRITE_WP;
10647 break;
10648 case hw_read:
10649 return Z_PACKET_READ_WP;
10650 break;
10651 case hw_access:
10652 return Z_PACKET_ACCESS_WP;
10653 break;
10654 default:
10655 internal_error (__FILE__, __LINE__,
10656 _("hw_bp_to_z: bad watchpoint type %d"), type);
10657 }
10658 }
10659
10660 int
10661 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10662 enum target_hw_bp_type type, struct expression *cond)
10663 {
10664 struct remote_state *rs = get_remote_state ();
10665 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10666 char *p;
10667 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10668
10669 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10670 return 1;
10671
10672 /* Make sure the remote is pointing at the right process, if
10673 necessary. */
10674 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10675 set_general_process ();
10676
10677 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10678 p = strchr (rs->buf.data (), '\0');
10679 addr = remote_address_masked (addr);
10680 p += hexnumstr (p, (ULONGEST) addr);
10681 xsnprintf (p, endbuf - p, ",%x", len);
10682
10683 putpkt (rs->buf);
10684 getpkt (&rs->buf, 0);
10685
10686 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10687 {
10688 case PACKET_ERROR:
10689 return -1;
10690 case PACKET_UNKNOWN:
10691 return 1;
10692 case PACKET_OK:
10693 return 0;
10694 }
10695 internal_error (__FILE__, __LINE__,
10696 _("remote_insert_watchpoint: reached end of function"));
10697 }
10698
10699 bool
10700 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10701 CORE_ADDR start, int length)
10702 {
10703 CORE_ADDR diff = remote_address_masked (addr - start);
10704
10705 return diff < length;
10706 }
10707
10708
10709 int
10710 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10711 enum target_hw_bp_type type, struct expression *cond)
10712 {
10713 struct remote_state *rs = get_remote_state ();
10714 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10715 char *p;
10716 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10717
10718 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10719 return -1;
10720
10721 /* Make sure the remote is pointing at the right process, if
10722 necessary. */
10723 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10724 set_general_process ();
10725
10726 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10727 p = strchr (rs->buf.data (), '\0');
10728 addr = remote_address_masked (addr);
10729 p += hexnumstr (p, (ULONGEST) addr);
10730 xsnprintf (p, endbuf - p, ",%x", len);
10731 putpkt (rs->buf);
10732 getpkt (&rs->buf, 0);
10733
10734 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10735 {
10736 case PACKET_ERROR:
10737 case PACKET_UNKNOWN:
10738 return -1;
10739 case PACKET_OK:
10740 return 0;
10741 }
10742 internal_error (__FILE__, __LINE__,
10743 _("remote_remove_watchpoint: reached end of function"));
10744 }
10745
10746
10747 static int remote_hw_watchpoint_limit = -1;
10748 static int remote_hw_watchpoint_length_limit = -1;
10749 static int remote_hw_breakpoint_limit = -1;
10750
10751 int
10752 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10753 {
10754 if (remote_hw_watchpoint_length_limit == 0)
10755 return 0;
10756 else if (remote_hw_watchpoint_length_limit < 0)
10757 return 1;
10758 else if (len <= remote_hw_watchpoint_length_limit)
10759 return 1;
10760 else
10761 return 0;
10762 }
10763
10764 int
10765 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10766 {
10767 if (type == bp_hardware_breakpoint)
10768 {
10769 if (remote_hw_breakpoint_limit == 0)
10770 return 0;
10771 else if (remote_hw_breakpoint_limit < 0)
10772 return 1;
10773 else if (cnt <= remote_hw_breakpoint_limit)
10774 return 1;
10775 }
10776 else
10777 {
10778 if (remote_hw_watchpoint_limit == 0)
10779 return 0;
10780 else if (remote_hw_watchpoint_limit < 0)
10781 return 1;
10782 else if (ot)
10783 return -1;
10784 else if (cnt <= remote_hw_watchpoint_limit)
10785 return 1;
10786 }
10787 return -1;
10788 }
10789
10790 /* The to_stopped_by_sw_breakpoint method of target remote. */
10791
10792 bool
10793 remote_target::stopped_by_sw_breakpoint ()
10794 {
10795 struct thread_info *thread = inferior_thread ();
10796
10797 return (thread->priv != NULL
10798 && (get_remote_thread_info (thread)->stop_reason
10799 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10800 }
10801
10802 /* The to_supports_stopped_by_sw_breakpoint method of target
10803 remote. */
10804
10805 bool
10806 remote_target::supports_stopped_by_sw_breakpoint ()
10807 {
10808 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10809 }
10810
10811 /* The to_stopped_by_hw_breakpoint method of target remote. */
10812
10813 bool
10814 remote_target::stopped_by_hw_breakpoint ()
10815 {
10816 struct thread_info *thread = inferior_thread ();
10817
10818 return (thread->priv != NULL
10819 && (get_remote_thread_info (thread)->stop_reason
10820 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10821 }
10822
10823 /* The to_supports_stopped_by_hw_breakpoint method of target
10824 remote. */
10825
10826 bool
10827 remote_target::supports_stopped_by_hw_breakpoint ()
10828 {
10829 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10830 }
10831
10832 bool
10833 remote_target::stopped_by_watchpoint ()
10834 {
10835 struct thread_info *thread = inferior_thread ();
10836
10837 return (thread->priv != NULL
10838 && (get_remote_thread_info (thread)->stop_reason
10839 == TARGET_STOPPED_BY_WATCHPOINT));
10840 }
10841
10842 bool
10843 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10844 {
10845 struct thread_info *thread = inferior_thread ();
10846
10847 if (thread->priv != NULL
10848 && (get_remote_thread_info (thread)->stop_reason
10849 == TARGET_STOPPED_BY_WATCHPOINT))
10850 {
10851 *addr_p = get_remote_thread_info (thread)->watch_data_address;
10852 return true;
10853 }
10854
10855 return false;
10856 }
10857
10858
10859 int
10860 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10861 struct bp_target_info *bp_tgt)
10862 {
10863 CORE_ADDR addr = bp_tgt->reqstd_address;
10864 struct remote_state *rs;
10865 char *p, *endbuf;
10866 char *message;
10867
10868 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10869 return -1;
10870
10871 /* Make sure the remote is pointing at the right process, if
10872 necessary. */
10873 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10874 set_general_process ();
10875
10876 rs = get_remote_state ();
10877 p = rs->buf.data ();
10878 endbuf = p + get_remote_packet_size ();
10879
10880 *(p++) = 'Z';
10881 *(p++) = '1';
10882 *(p++) = ',';
10883
10884 addr = remote_address_masked (addr);
10885 p += hexnumstr (p, (ULONGEST) addr);
10886 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10887
10888 if (supports_evaluation_of_breakpoint_conditions ())
10889 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10890
10891 if (can_run_breakpoint_commands ())
10892 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10893
10894 putpkt (rs->buf);
10895 getpkt (&rs->buf, 0);
10896
10897 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10898 {
10899 case PACKET_ERROR:
10900 if (rs->buf[1] == '.')
10901 {
10902 message = strchr (&rs->buf[2], '.');
10903 if (message)
10904 error (_("Remote failure reply: %s"), message + 1);
10905 }
10906 return -1;
10907 case PACKET_UNKNOWN:
10908 return -1;
10909 case PACKET_OK:
10910 return 0;
10911 }
10912 internal_error (__FILE__, __LINE__,
10913 _("remote_insert_hw_breakpoint: reached end of function"));
10914 }
10915
10916
10917 int
10918 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10919 struct bp_target_info *bp_tgt)
10920 {
10921 CORE_ADDR addr;
10922 struct remote_state *rs = get_remote_state ();
10923 char *p = rs->buf.data ();
10924 char *endbuf = p + get_remote_packet_size ();
10925
10926 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10927 return -1;
10928
10929 /* Make sure the remote is pointing at the right process, if
10930 necessary. */
10931 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10932 set_general_process ();
10933
10934 *(p++) = 'z';
10935 *(p++) = '1';
10936 *(p++) = ',';
10937
10938 addr = remote_address_masked (bp_tgt->placed_address);
10939 p += hexnumstr (p, (ULONGEST) addr);
10940 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10941
10942 putpkt (rs->buf);
10943 getpkt (&rs->buf, 0);
10944
10945 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10946 {
10947 case PACKET_ERROR:
10948 case PACKET_UNKNOWN:
10949 return -1;
10950 case PACKET_OK:
10951 return 0;
10952 }
10953 internal_error (__FILE__, __LINE__,
10954 _("remote_remove_hw_breakpoint: reached end of function"));
10955 }
10956
10957 /* Verify memory using the "qCRC:" request. */
10958
10959 int
10960 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10961 {
10962 struct remote_state *rs = get_remote_state ();
10963 unsigned long host_crc, target_crc;
10964 char *tmp;
10965
10966 /* It doesn't make sense to use qCRC if the remote target is
10967 connected but not running. */
10968 if (target_has_execution ()
10969 && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10970 {
10971 enum packet_result result;
10972
10973 /* Make sure the remote is pointing at the right process. */
10974 set_general_process ();
10975
10976 /* FIXME: assumes lma can fit into long. */
10977 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
10978 (long) lma, (long) size);
10979 putpkt (rs->buf);
10980
10981 /* Be clever; compute the host_crc before waiting for target
10982 reply. */
10983 host_crc = xcrc32 (data, size, 0xffffffff);
10984
10985 getpkt (&rs->buf, 0);
10986
10987 result = packet_ok (rs->buf,
10988 &remote_protocol_packets[PACKET_qCRC]);
10989 if (result == PACKET_ERROR)
10990 return -1;
10991 else if (result == PACKET_OK)
10992 {
10993 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10994 target_crc = target_crc * 16 + fromhex (*tmp);
10995
10996 return (host_crc == target_crc);
10997 }
10998 }
10999
11000 return simple_verify_memory (this, data, lma, size);
11001 }
11002
11003 /* compare-sections command
11004
11005 With no arguments, compares each loadable section in the exec bfd
11006 with the same memory range on the target, and reports mismatches.
11007 Useful for verifying the image on the target against the exec file. */
11008
11009 static void
11010 compare_sections_command (const char *args, int from_tty)
11011 {
11012 asection *s;
11013 const char *sectname;
11014 bfd_size_type size;
11015 bfd_vma lma;
11016 int matched = 0;
11017 int mismatched = 0;
11018 int res;
11019 int read_only = 0;
11020
11021 if (!current_program_space->exec_bfd ())
11022 error (_("command cannot be used without an exec file"));
11023
11024 if (args != NULL && strcmp (args, "-r") == 0)
11025 {
11026 read_only = 1;
11027 args = NULL;
11028 }
11029
11030 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11031 {
11032 if (!(s->flags & SEC_LOAD))
11033 continue; /* Skip non-loadable section. */
11034
11035 if (read_only && (s->flags & SEC_READONLY) == 0)
11036 continue; /* Skip writeable sections */
11037
11038 size = bfd_section_size (s);
11039 if (size == 0)
11040 continue; /* Skip zero-length section. */
11041
11042 sectname = bfd_section_name (s);
11043 if (args && strcmp (args, sectname) != 0)
11044 continue; /* Not the section selected by user. */
11045
11046 matched = 1; /* Do this section. */
11047 lma = s->lma;
11048
11049 gdb::byte_vector sectdata (size);
11050 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11051 sectdata.data (), 0, size);
11052
11053 res = target_verify_memory (sectdata.data (), lma, size);
11054
11055 if (res == -1)
11056 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11057 paddress (target_gdbarch (), lma),
11058 paddress (target_gdbarch (), lma + size));
11059
11060 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11061 paddress (target_gdbarch (), lma),
11062 paddress (target_gdbarch (), lma + size));
11063 if (res)
11064 gdb_printf ("matched.\n");
11065 else
11066 {
11067 gdb_printf ("MIS-MATCHED!\n");
11068 mismatched++;
11069 }
11070 }
11071 if (mismatched > 0)
11072 warning (_("One or more sections of the target image does not match\n\
11073 the loaded file\n"));
11074 if (args && !matched)
11075 gdb_printf (_("No loaded section named '%s'.\n"), args);
11076 }
11077
11078 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11079 into remote target. The number of bytes written to the remote
11080 target is returned, or -1 for error. */
11081
11082 target_xfer_status
11083 remote_target::remote_write_qxfer (const char *object_name,
11084 const char *annex, const gdb_byte *writebuf,
11085 ULONGEST offset, LONGEST len,
11086 ULONGEST *xfered_len,
11087 struct packet_config *packet)
11088 {
11089 int i, buf_len;
11090 ULONGEST n;
11091 struct remote_state *rs = get_remote_state ();
11092 int max_size = get_memory_write_packet_size ();
11093
11094 if (packet_config_support (packet) == PACKET_DISABLE)
11095 return TARGET_XFER_E_IO;
11096
11097 /* Insert header. */
11098 i = snprintf (rs->buf.data (), max_size,
11099 "qXfer:%s:write:%s:%s:",
11100 object_name, annex ? annex : "",
11101 phex_nz (offset, sizeof offset));
11102 max_size -= (i + 1);
11103
11104 /* Escape as much data as fits into rs->buf. */
11105 buf_len = remote_escape_output
11106 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11107
11108 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11109 || getpkt_sane (&rs->buf, 0) < 0
11110 || packet_ok (rs->buf, packet) != PACKET_OK)
11111 return TARGET_XFER_E_IO;
11112
11113 unpack_varlen_hex (rs->buf.data (), &n);
11114
11115 *xfered_len = n;
11116 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11117 }
11118
11119 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11120 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11121 number of bytes read is returned, or 0 for EOF, or -1 for error.
11122 The number of bytes read may be less than LEN without indicating an
11123 EOF. PACKET is checked and updated to indicate whether the remote
11124 target supports this object. */
11125
11126 target_xfer_status
11127 remote_target::remote_read_qxfer (const char *object_name,
11128 const char *annex,
11129 gdb_byte *readbuf, ULONGEST offset,
11130 LONGEST len,
11131 ULONGEST *xfered_len,
11132 struct packet_config *packet)
11133 {
11134 struct remote_state *rs = get_remote_state ();
11135 LONGEST i, n, packet_len;
11136
11137 if (packet_config_support (packet) == PACKET_DISABLE)
11138 return TARGET_XFER_E_IO;
11139
11140 /* Check whether we've cached an end-of-object packet that matches
11141 this request. */
11142 if (rs->finished_object)
11143 {
11144 if (strcmp (object_name, rs->finished_object) == 0
11145 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11146 && offset == rs->finished_offset)
11147 return TARGET_XFER_EOF;
11148
11149
11150 /* Otherwise, we're now reading something different. Discard
11151 the cache. */
11152 xfree (rs->finished_object);
11153 xfree (rs->finished_annex);
11154 rs->finished_object = NULL;
11155 rs->finished_annex = NULL;
11156 }
11157
11158 /* Request only enough to fit in a single packet. The actual data
11159 may not, since we don't know how much of it will need to be escaped;
11160 the target is free to respond with slightly less data. We subtract
11161 five to account for the response type and the protocol frame. */
11162 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11163 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11164 "qXfer:%s:read:%s:%s,%s",
11165 object_name, annex ? annex : "",
11166 phex_nz (offset, sizeof offset),
11167 phex_nz (n, sizeof n));
11168 i = putpkt (rs->buf);
11169 if (i < 0)
11170 return TARGET_XFER_E_IO;
11171
11172 rs->buf[0] = '\0';
11173 packet_len = getpkt_sane (&rs->buf, 0);
11174 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
11175 return TARGET_XFER_E_IO;
11176
11177 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11178 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11179
11180 /* 'm' means there is (or at least might be) more data after this
11181 batch. That does not make sense unless there's at least one byte
11182 of data in this reply. */
11183 if (rs->buf[0] == 'm' && packet_len == 1)
11184 error (_("Remote qXfer reply contained no data."));
11185
11186 /* Got some data. */
11187 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11188 packet_len - 1, readbuf, n);
11189
11190 /* 'l' is an EOF marker, possibly including a final block of data,
11191 or possibly empty. If we have the final block of a non-empty
11192 object, record this fact to bypass a subsequent partial read. */
11193 if (rs->buf[0] == 'l' && offset + i > 0)
11194 {
11195 rs->finished_object = xstrdup (object_name);
11196 rs->finished_annex = xstrdup (annex ? annex : "");
11197 rs->finished_offset = offset + i;
11198 }
11199
11200 if (i == 0)
11201 return TARGET_XFER_EOF;
11202 else
11203 {
11204 *xfered_len = i;
11205 return TARGET_XFER_OK;
11206 }
11207 }
11208
11209 enum target_xfer_status
11210 remote_target::xfer_partial (enum target_object object,
11211 const char *annex, gdb_byte *readbuf,
11212 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11213 ULONGEST *xfered_len)
11214 {
11215 struct remote_state *rs;
11216 int i;
11217 char *p2;
11218 char query_type;
11219 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
11220
11221 set_remote_traceframe ();
11222 set_general_thread (inferior_ptid);
11223
11224 rs = get_remote_state ();
11225
11226 /* Handle memory using the standard memory routines. */
11227 if (object == TARGET_OBJECT_MEMORY)
11228 {
11229 /* If the remote target is connected but not running, we should
11230 pass this request down to a lower stratum (e.g. the executable
11231 file). */
11232 if (!target_has_execution ())
11233 return TARGET_XFER_EOF;
11234
11235 if (writebuf != NULL)
11236 return remote_write_bytes (offset, writebuf, len, unit_size,
11237 xfered_len);
11238 else
11239 return remote_read_bytes (offset, readbuf, len, unit_size,
11240 xfered_len);
11241 }
11242
11243 /* Handle extra signal info using qxfer packets. */
11244 if (object == TARGET_OBJECT_SIGNAL_INFO)
11245 {
11246 if (readbuf)
11247 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11248 xfered_len, &remote_protocol_packets
11249 [PACKET_qXfer_siginfo_read]);
11250 else
11251 return remote_write_qxfer ("siginfo", annex,
11252 writebuf, offset, len, xfered_len,
11253 &remote_protocol_packets
11254 [PACKET_qXfer_siginfo_write]);
11255 }
11256
11257 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11258 {
11259 if (readbuf)
11260 return remote_read_qxfer ("statictrace", annex,
11261 readbuf, offset, len, xfered_len,
11262 &remote_protocol_packets
11263 [PACKET_qXfer_statictrace_read]);
11264 else
11265 return TARGET_XFER_E_IO;
11266 }
11267
11268 /* Only handle flash writes. */
11269 if (writebuf != NULL)
11270 {
11271 switch (object)
11272 {
11273 case TARGET_OBJECT_FLASH:
11274 return remote_flash_write (offset, len, xfered_len,
11275 writebuf);
11276
11277 default:
11278 return TARGET_XFER_E_IO;
11279 }
11280 }
11281
11282 /* Map pre-existing objects onto letters. DO NOT do this for new
11283 objects!!! Instead specify new query packets. */
11284 switch (object)
11285 {
11286 case TARGET_OBJECT_AVR:
11287 query_type = 'R';
11288 break;
11289
11290 case TARGET_OBJECT_AUXV:
11291 gdb_assert (annex == NULL);
11292 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
11293 xfered_len,
11294 &remote_protocol_packets[PACKET_qXfer_auxv]);
11295
11296 case TARGET_OBJECT_AVAILABLE_FEATURES:
11297 return remote_read_qxfer
11298 ("features", annex, readbuf, offset, len, xfered_len,
11299 &remote_protocol_packets[PACKET_qXfer_features]);
11300
11301 case TARGET_OBJECT_LIBRARIES:
11302 return remote_read_qxfer
11303 ("libraries", annex, readbuf, offset, len, xfered_len,
11304 &remote_protocol_packets[PACKET_qXfer_libraries]);
11305
11306 case TARGET_OBJECT_LIBRARIES_SVR4:
11307 return remote_read_qxfer
11308 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11309 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
11310
11311 case TARGET_OBJECT_MEMORY_MAP:
11312 gdb_assert (annex == NULL);
11313 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
11314 xfered_len,
11315 &remote_protocol_packets[PACKET_qXfer_memory_map]);
11316
11317 case TARGET_OBJECT_OSDATA:
11318 /* Should only get here if we're connected. */
11319 gdb_assert (rs->remote_desc);
11320 return remote_read_qxfer
11321 ("osdata", annex, readbuf, offset, len, xfered_len,
11322 &remote_protocol_packets[PACKET_qXfer_osdata]);
11323
11324 case TARGET_OBJECT_THREADS:
11325 gdb_assert (annex == NULL);
11326 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
11327 xfered_len,
11328 &remote_protocol_packets[PACKET_qXfer_threads]);
11329
11330 case TARGET_OBJECT_TRACEFRAME_INFO:
11331 gdb_assert (annex == NULL);
11332 return remote_read_qxfer
11333 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11334 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
11335
11336 case TARGET_OBJECT_FDPIC:
11337 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
11338 xfered_len,
11339 &remote_protocol_packets[PACKET_qXfer_fdpic]);
11340
11341 case TARGET_OBJECT_OPENVMS_UIB:
11342 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
11343 xfered_len,
11344 &remote_protocol_packets[PACKET_qXfer_uib]);
11345
11346 case TARGET_OBJECT_BTRACE:
11347 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
11348 xfered_len,
11349 &remote_protocol_packets[PACKET_qXfer_btrace]);
11350
11351 case TARGET_OBJECT_BTRACE_CONF:
11352 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
11353 len, xfered_len,
11354 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11355
11356 case TARGET_OBJECT_EXEC_FILE:
11357 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
11358 len, xfered_len,
11359 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11360
11361 default:
11362 return TARGET_XFER_E_IO;
11363 }
11364
11365 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11366 large enough let the caller deal with it. */
11367 if (len < get_remote_packet_size ())
11368 return TARGET_XFER_E_IO;
11369 len = get_remote_packet_size ();
11370
11371 /* Except for querying the minimum buffer size, target must be open. */
11372 if (!rs->remote_desc)
11373 error (_("remote query is only available after target open"));
11374
11375 gdb_assert (annex != NULL);
11376 gdb_assert (readbuf != NULL);
11377
11378 p2 = rs->buf.data ();
11379 *p2++ = 'q';
11380 *p2++ = query_type;
11381
11382 /* We used one buffer char for the remote protocol q command and
11383 another for the query type. As the remote protocol encapsulation
11384 uses 4 chars plus one extra in case we are debugging
11385 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11386 string. */
11387 i = 0;
11388 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11389 {
11390 /* Bad caller may have sent forbidden characters. */
11391 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11392 *p2++ = annex[i];
11393 i++;
11394 }
11395 *p2 = '\0';
11396 gdb_assert (annex[i] == '\0');
11397
11398 i = putpkt (rs->buf);
11399 if (i < 0)
11400 return TARGET_XFER_E_IO;
11401
11402 getpkt (&rs->buf, 0);
11403 strcpy ((char *) readbuf, rs->buf.data ());
11404
11405 *xfered_len = strlen ((char *) readbuf);
11406 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11407 }
11408
11409 /* Implementation of to_get_memory_xfer_limit. */
11410
11411 ULONGEST
11412 remote_target::get_memory_xfer_limit ()
11413 {
11414 return get_memory_write_packet_size ();
11415 }
11416
11417 int
11418 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11419 const gdb_byte *pattern, ULONGEST pattern_len,
11420 CORE_ADDR *found_addrp)
11421 {
11422 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11423 struct remote_state *rs = get_remote_state ();
11424 int max_size = get_memory_write_packet_size ();
11425 struct packet_config *packet =
11426 &remote_protocol_packets[PACKET_qSearch_memory];
11427 /* Number of packet bytes used to encode the pattern;
11428 this could be more than PATTERN_LEN due to escape characters. */
11429 int escaped_pattern_len;
11430 /* Amount of pattern that was encodable in the packet. */
11431 int used_pattern_len;
11432 int i;
11433 int found;
11434 ULONGEST found_addr;
11435
11436 auto read_memory = [=] (CORE_ADDR addr, gdb_byte *result, size_t len)
11437 {
11438 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11439 == len);
11440 };
11441
11442 /* Don't go to the target if we don't have to. This is done before
11443 checking packet_config_support to avoid the possibility that a
11444 success for this edge case means the facility works in
11445 general. */
11446 if (pattern_len > search_space_len)
11447 return 0;
11448 if (pattern_len == 0)
11449 {
11450 *found_addrp = start_addr;
11451 return 1;
11452 }
11453
11454 /* If we already know the packet isn't supported, fall back to the simple
11455 way of searching memory. */
11456
11457 if (packet_config_support (packet) == PACKET_DISABLE)
11458 {
11459 /* Target doesn't provided special support, fall back and use the
11460 standard support (copy memory and do the search here). */
11461 return simple_search_memory (read_memory, start_addr, search_space_len,
11462 pattern, pattern_len, found_addrp);
11463 }
11464
11465 /* Make sure the remote is pointing at the right process. */
11466 set_general_process ();
11467
11468 /* Insert header. */
11469 i = snprintf (rs->buf.data (), max_size,
11470 "qSearch:memory:%s;%s;",
11471 phex_nz (start_addr, addr_size),
11472 phex_nz (search_space_len, sizeof (search_space_len)));
11473 max_size -= (i + 1);
11474
11475 /* Escape as much data as fits into rs->buf. */
11476 escaped_pattern_len =
11477 remote_escape_output (pattern, pattern_len, 1,
11478 (gdb_byte *) rs->buf.data () + i,
11479 &used_pattern_len, max_size);
11480
11481 /* Bail if the pattern is too large. */
11482 if (used_pattern_len != pattern_len)
11483 error (_("Pattern is too large to transmit to remote target."));
11484
11485 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11486 || getpkt_sane (&rs->buf, 0) < 0
11487 || packet_ok (rs->buf, packet) != PACKET_OK)
11488 {
11489 /* The request may not have worked because the command is not
11490 supported. If so, fall back to the simple way. */
11491 if (packet_config_support (packet) == PACKET_DISABLE)
11492 {
11493 return simple_search_memory (read_memory, start_addr, search_space_len,
11494 pattern, pattern_len, found_addrp);
11495 }
11496 return -1;
11497 }
11498
11499 if (rs->buf[0] == '0')
11500 found = 0;
11501 else if (rs->buf[0] == '1')
11502 {
11503 found = 1;
11504 if (rs->buf[1] != ',')
11505 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11506 unpack_varlen_hex (&rs->buf[2], &found_addr);
11507 *found_addrp = found_addr;
11508 }
11509 else
11510 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11511
11512 return found;
11513 }
11514
11515 void
11516 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11517 {
11518 struct remote_state *rs = get_remote_state ();
11519 char *p = rs->buf.data ();
11520
11521 if (!rs->remote_desc)
11522 error (_("remote rcmd is only available after target open"));
11523
11524 /* Send a NULL command across as an empty command. */
11525 if (command == NULL)
11526 command = "";
11527
11528 /* The query prefix. */
11529 strcpy (rs->buf.data (), "qRcmd,");
11530 p = strchr (rs->buf.data (), '\0');
11531
11532 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11533 > get_remote_packet_size ())
11534 error (_("\"monitor\" command ``%s'' is too long."), command);
11535
11536 /* Encode the actual command. */
11537 bin2hex ((const gdb_byte *) command, p, strlen (command));
11538
11539 if (putpkt (rs->buf) < 0)
11540 error (_("Communication problem with target."));
11541
11542 /* get/display the response */
11543 while (1)
11544 {
11545 char *buf;
11546
11547 /* XXX - see also remote_get_noisy_reply(). */
11548 QUIT; /* Allow user to bail out with ^C. */
11549 rs->buf[0] = '\0';
11550 if (getpkt_sane (&rs->buf, 0) == -1)
11551 {
11552 /* Timeout. Continue to (try to) read responses.
11553 This is better than stopping with an error, assuming the stub
11554 is still executing the (long) monitor command.
11555 If needed, the user can interrupt gdb using C-c, obtaining
11556 an effect similar to stop on timeout. */
11557 continue;
11558 }
11559 buf = rs->buf.data ();
11560 if (buf[0] == '\0')
11561 error (_("Target does not support this command."));
11562 if (buf[0] == 'O' && buf[1] != 'K')
11563 {
11564 remote_console_output (buf + 1); /* 'O' message from stub. */
11565 continue;
11566 }
11567 if (strcmp (buf, "OK") == 0)
11568 break;
11569 if (strlen (buf) == 3 && buf[0] == 'E'
11570 && isxdigit (buf[1]) && isxdigit (buf[2]))
11571 {
11572 error (_("Protocol error with Rcmd"));
11573 }
11574 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11575 {
11576 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11577
11578 gdb_putc (c, outbuf);
11579 }
11580 break;
11581 }
11582 }
11583
11584 std::vector<mem_region>
11585 remote_target::memory_map ()
11586 {
11587 std::vector<mem_region> result;
11588 gdb::optional<gdb::char_vector> text
11589 = target_read_stralloc (current_inferior ()->top_target (),
11590 TARGET_OBJECT_MEMORY_MAP, NULL);
11591
11592 if (text)
11593 result = parse_memory_map (text->data ());
11594
11595 return result;
11596 }
11597
11598 /* Set of callbacks used to implement the 'maint packet' command. */
11599
11600 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
11601 {
11602 /* Called before the packet is sent. BUF is the packet content before
11603 the protocol specific prefix, suffix, and escaping is added. */
11604
11605 void sending (gdb::array_view<const char> &buf) override
11606 {
11607 gdb_puts ("sending: ");
11608 print_packet (buf);
11609 gdb_puts ("\n");
11610 }
11611
11612 /* Called with BUF, the reply from the remote target. */
11613
11614 void received (gdb::array_view<const char> &buf) override
11615 {
11616 gdb_puts ("received: \"");
11617 print_packet (buf);
11618 gdb_puts ("\"\n");
11619 }
11620
11621 private:
11622
11623 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11624 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11625
11626 static void
11627 print_packet (gdb::array_view<const char> &buf)
11628 {
11629 string_file stb;
11630
11631 for (int i = 0; i < buf.size (); ++i)
11632 {
11633 gdb_byte c = buf[i];
11634 if (isprint (c))
11635 gdb_putc (c, &stb);
11636 else
11637 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
11638 }
11639
11640 gdb_puts (stb.string ().c_str ());
11641 }
11642 };
11643
11644 /* See remote.h. */
11645
11646 void
11647 send_remote_packet (gdb::array_view<const char> &buf,
11648 send_remote_packet_callbacks *callbacks)
11649 {
11650 if (buf.size () == 0 || buf.data ()[0] == '\0')
11651 error (_("a remote packet must not be empty"));
11652
11653 remote_target *remote = get_current_remote_target ();
11654 if (remote == nullptr)
11655 error (_("packets can only be sent to a remote target"));
11656
11657 callbacks->sending (buf);
11658
11659 remote->putpkt_binary (buf.data (), buf.size ());
11660 remote_state *rs = remote->get_remote_state ();
11661 int bytes = remote->getpkt_sane (&rs->buf, 0);
11662
11663 if (bytes < 0)
11664 error (_("error while fetching packet from remote target"));
11665
11666 gdb::array_view<const char> view (&rs->buf[0], bytes);
11667 callbacks->received (view);
11668 }
11669
11670 /* Entry point for the 'maint packet' command. */
11671
11672 static void
11673 cli_packet_command (const char *args, int from_tty)
11674 {
11675 cli_packet_command_callbacks cb;
11676 gdb::array_view<const char> view
11677 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11678 send_remote_packet (view, &cb);
11679 }
11680
11681 #if 0
11682 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11683
11684 static void display_thread_info (struct gdb_ext_thread_info *info);
11685
11686 static void threadset_test_cmd (char *cmd, int tty);
11687
11688 static void threadalive_test (char *cmd, int tty);
11689
11690 static void threadlist_test_cmd (char *cmd, int tty);
11691
11692 int get_and_display_threadinfo (threadref *ref);
11693
11694 static void threadinfo_test_cmd (char *cmd, int tty);
11695
11696 static int thread_display_step (threadref *ref, void *context);
11697
11698 static void threadlist_update_test_cmd (char *cmd, int tty);
11699
11700 static void init_remote_threadtests (void);
11701
11702 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11703
11704 static void
11705 threadset_test_cmd (const char *cmd, int tty)
11706 {
11707 int sample_thread = SAMPLE_THREAD;
11708
11709 gdb_printf (_("Remote threadset test\n"));
11710 set_general_thread (sample_thread);
11711 }
11712
11713
11714 static void
11715 threadalive_test (const char *cmd, int tty)
11716 {
11717 int sample_thread = SAMPLE_THREAD;
11718 int pid = inferior_ptid.pid ();
11719 ptid_t ptid = ptid_t (pid, sample_thread, 0);
11720
11721 if (remote_thread_alive (ptid))
11722 gdb_printf ("PASS: Thread alive test\n");
11723 else
11724 gdb_printf ("FAIL: Thread alive test\n");
11725 }
11726
11727 void output_threadid (char *title, threadref *ref);
11728
11729 void
11730 output_threadid (char *title, threadref *ref)
11731 {
11732 char hexid[20];
11733
11734 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
11735 hexid[16] = 0;
11736 gdb_printf ("%s %s\n", title, (&hexid[0]));
11737 }
11738
11739 static void
11740 threadlist_test_cmd (const char *cmd, int tty)
11741 {
11742 int startflag = 1;
11743 threadref nextthread;
11744 int done, result_count;
11745 threadref threadlist[3];
11746
11747 gdb_printf ("Remote Threadlist test\n");
11748 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11749 &result_count, &threadlist[0]))
11750 gdb_printf ("FAIL: threadlist test\n");
11751 else
11752 {
11753 threadref *scan = threadlist;
11754 threadref *limit = scan + result_count;
11755
11756 while (scan < limit)
11757 output_threadid (" thread ", scan++);
11758 }
11759 }
11760
11761 void
11762 display_thread_info (struct gdb_ext_thread_info *info)
11763 {
11764 output_threadid ("Threadid: ", &info->threadid);
11765 gdb_printf ("Name: %s\n ", info->shortname);
11766 gdb_printf ("State: %s\n", info->display);
11767 gdb_printf ("other: %s\n\n", info->more_display);
11768 }
11769
11770 int
11771 get_and_display_threadinfo (threadref *ref)
11772 {
11773 int result;
11774 int set;
11775 struct gdb_ext_thread_info threadinfo;
11776
11777 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11778 | TAG_MOREDISPLAY | TAG_DISPLAY;
11779 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11780 display_thread_info (&threadinfo);
11781 return result;
11782 }
11783
11784 static void
11785 threadinfo_test_cmd (const char *cmd, int tty)
11786 {
11787 int athread = SAMPLE_THREAD;
11788 threadref thread;
11789 int set;
11790
11791 int_to_threadref (&thread, athread);
11792 gdb_printf ("Remote Threadinfo test\n");
11793 if (!get_and_display_threadinfo (&thread))
11794 gdb_printf ("FAIL cannot get thread info\n");
11795 }
11796
11797 static int
11798 thread_display_step (threadref *ref, void *context)
11799 {
11800 /* output_threadid(" threadstep ",ref); *//* simple test */
11801 return get_and_display_threadinfo (ref);
11802 }
11803
11804 static void
11805 threadlist_update_test_cmd (const char *cmd, int tty)
11806 {
11807 gdb_printf ("Remote Threadlist update test\n");
11808 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11809 }
11810
11811 static void
11812 init_remote_threadtests (void)
11813 {
11814 add_com ("tlist", class_obscure, threadlist_test_cmd,
11815 _("Fetch and print the remote list of "
11816 "thread identifiers, one pkt only."));
11817 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11818 _("Fetch and display info about one thread."));
11819 add_com ("tset", class_obscure, threadset_test_cmd,
11820 _("Test setting to a different thread."));
11821 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11822 _("Iterate through updating all remote thread info."));
11823 add_com ("talive", class_obscure, threadalive_test,
11824 _("Remote thread alive test."));
11825 }
11826
11827 #endif /* 0 */
11828
11829 /* Convert a thread ID to a string. */
11830
11831 std::string
11832 remote_target::pid_to_str (ptid_t ptid)
11833 {
11834 struct remote_state *rs = get_remote_state ();
11835
11836 if (ptid == null_ptid)
11837 return normal_pid_to_str (ptid);
11838 else if (ptid.is_pid ())
11839 {
11840 /* Printing an inferior target id. */
11841
11842 /* When multi-process extensions are off, there's no way in the
11843 remote protocol to know the remote process id, if there's any
11844 at all. There's one exception --- when we're connected with
11845 target extended-remote, and we manually attached to a process
11846 with "attach PID". We don't record anywhere a flag that
11847 allows us to distinguish that case from the case of
11848 connecting with extended-remote and the stub already being
11849 attached to a process, and reporting yes to qAttached, hence
11850 no smart special casing here. */
11851 if (!remote_multi_process_p (rs))
11852 return "Remote target";
11853
11854 return normal_pid_to_str (ptid);
11855 }
11856 else
11857 {
11858 if (magic_null_ptid == ptid)
11859 return "Thread <main>";
11860 else if (remote_multi_process_p (rs))
11861 if (ptid.lwp () == 0)
11862 return normal_pid_to_str (ptid);
11863 else
11864 return string_printf ("Thread %d.%ld",
11865 ptid.pid (), ptid.lwp ());
11866 else
11867 return string_printf ("Thread %ld", ptid.lwp ());
11868 }
11869 }
11870
11871 /* Get the address of the thread local variable in OBJFILE which is
11872 stored at OFFSET within the thread local storage for thread PTID. */
11873
11874 CORE_ADDR
11875 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11876 CORE_ADDR offset)
11877 {
11878 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11879 {
11880 struct remote_state *rs = get_remote_state ();
11881 char *p = rs->buf.data ();
11882 char *endp = p + get_remote_packet_size ();
11883 enum packet_result result;
11884
11885 strcpy (p, "qGetTLSAddr:");
11886 p += strlen (p);
11887 p = write_ptid (p, endp, ptid);
11888 *p++ = ',';
11889 p += hexnumstr (p, offset);
11890 *p++ = ',';
11891 p += hexnumstr (p, lm);
11892 *p++ = '\0';
11893
11894 putpkt (rs->buf);
11895 getpkt (&rs->buf, 0);
11896 result = packet_ok (rs->buf,
11897 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11898 if (result == PACKET_OK)
11899 {
11900 ULONGEST addr;
11901
11902 unpack_varlen_hex (rs->buf.data (), &addr);
11903 return addr;
11904 }
11905 else if (result == PACKET_UNKNOWN)
11906 throw_error (TLS_GENERIC_ERROR,
11907 _("Remote target doesn't support qGetTLSAddr packet"));
11908 else
11909 throw_error (TLS_GENERIC_ERROR,
11910 _("Remote target failed to process qGetTLSAddr request"));
11911 }
11912 else
11913 throw_error (TLS_GENERIC_ERROR,
11914 _("TLS not supported or disabled on this target"));
11915 /* Not reached. */
11916 return 0;
11917 }
11918
11919 /* Provide thread local base, i.e. Thread Information Block address.
11920 Returns 1 if ptid is found and thread_local_base is non zero. */
11921
11922 bool
11923 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11924 {
11925 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11926 {
11927 struct remote_state *rs = get_remote_state ();
11928 char *p = rs->buf.data ();
11929 char *endp = p + get_remote_packet_size ();
11930 enum packet_result result;
11931
11932 strcpy (p, "qGetTIBAddr:");
11933 p += strlen (p);
11934 p = write_ptid (p, endp, ptid);
11935 *p++ = '\0';
11936
11937 putpkt (rs->buf);
11938 getpkt (&rs->buf, 0);
11939 result = packet_ok (rs->buf,
11940 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11941 if (result == PACKET_OK)
11942 {
11943 ULONGEST val;
11944 unpack_varlen_hex (rs->buf.data (), &val);
11945 if (addr)
11946 *addr = (CORE_ADDR) val;
11947 return true;
11948 }
11949 else if (result == PACKET_UNKNOWN)
11950 error (_("Remote target doesn't support qGetTIBAddr packet"));
11951 else
11952 error (_("Remote target failed to process qGetTIBAddr request"));
11953 }
11954 else
11955 error (_("qGetTIBAddr not supported or disabled on this target"));
11956 /* Not reached. */
11957 return false;
11958 }
11959
11960 /* Support for inferring a target description based on the current
11961 architecture and the size of a 'g' packet. While the 'g' packet
11962 can have any size (since optional registers can be left off the
11963 end), some sizes are easily recognizable given knowledge of the
11964 approximate architecture. */
11965
11966 struct remote_g_packet_guess
11967 {
11968 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
11969 : bytes (bytes_),
11970 tdesc (tdesc_)
11971 {
11972 }
11973
11974 int bytes;
11975 const struct target_desc *tdesc;
11976 };
11977
11978 struct remote_g_packet_data : public allocate_on_obstack
11979 {
11980 std::vector<remote_g_packet_guess> guesses;
11981 };
11982
11983 static struct gdbarch_data *remote_g_packet_data_handle;
11984
11985 static void *
11986 remote_g_packet_data_init (struct obstack *obstack)
11987 {
11988 return new (obstack) remote_g_packet_data;
11989 }
11990
11991 void
11992 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11993 const struct target_desc *tdesc)
11994 {
11995 struct remote_g_packet_data *data
11996 = ((struct remote_g_packet_data *)
11997 gdbarch_data (gdbarch, remote_g_packet_data_handle));
11998
11999 gdb_assert (tdesc != NULL);
12000
12001 for (const remote_g_packet_guess &guess : data->guesses)
12002 if (guess.bytes == bytes)
12003 internal_error (__FILE__, __LINE__,
12004 _("Duplicate g packet description added for size %d"),
12005 bytes);
12006
12007 data->guesses.emplace_back (bytes, tdesc);
12008 }
12009
12010 /* Return true if remote_read_description would do anything on this target
12011 and architecture, false otherwise. */
12012
12013 static bool
12014 remote_read_description_p (struct target_ops *target)
12015 {
12016 struct remote_g_packet_data *data
12017 = ((struct remote_g_packet_data *)
12018 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
12019
12020 return !data->guesses.empty ();
12021 }
12022
12023 const struct target_desc *
12024 remote_target::read_description ()
12025 {
12026 struct remote_g_packet_data *data
12027 = ((struct remote_g_packet_data *)
12028 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
12029
12030 /* Do not try this during initial connection, when we do not know
12031 whether there is a running but stopped thread. */
12032 if (!target_has_execution () || inferior_ptid == null_ptid)
12033 return beneath ()->read_description ();
12034
12035 if (!data->guesses.empty ())
12036 {
12037 int bytes = send_g_packet ();
12038
12039 for (const remote_g_packet_guess &guess : data->guesses)
12040 if (guess.bytes == bytes)
12041 return guess.tdesc;
12042
12043 /* We discard the g packet. A minor optimization would be to
12044 hold on to it, and fill the register cache once we have selected
12045 an architecture, but it's too tricky to do safely. */
12046 }
12047
12048 return beneath ()->read_description ();
12049 }
12050
12051 /* Remote file transfer support. This is host-initiated I/O, not
12052 target-initiated; for target-initiated, see remote-fileio.c. */
12053
12054 /* If *LEFT is at least the length of STRING, copy STRING to
12055 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12056 decrease *LEFT. Otherwise raise an error. */
12057
12058 static void
12059 remote_buffer_add_string (char **buffer, int *left, const char *string)
12060 {
12061 int len = strlen (string);
12062
12063 if (len > *left)
12064 error (_("Packet too long for target."));
12065
12066 memcpy (*buffer, string, len);
12067 *buffer += len;
12068 *left -= len;
12069
12070 /* NUL-terminate the buffer as a convenience, if there is
12071 room. */
12072 if (*left)
12073 **buffer = '\0';
12074 }
12075
12076 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12077 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12078 decrease *LEFT. Otherwise raise an error. */
12079
12080 static void
12081 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12082 int len)
12083 {
12084 if (2 * len > *left)
12085 error (_("Packet too long for target."));
12086
12087 bin2hex (bytes, *buffer, len);
12088 *buffer += 2 * len;
12089 *left -= 2 * len;
12090
12091 /* NUL-terminate the buffer as a convenience, if there is
12092 room. */
12093 if (*left)
12094 **buffer = '\0';
12095 }
12096
12097 /* If *LEFT is large enough, convert VALUE to hex and add it to
12098 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12099 decrease *LEFT. Otherwise raise an error. */
12100
12101 static void
12102 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12103 {
12104 int len = hexnumlen (value);
12105
12106 if (len > *left)
12107 error (_("Packet too long for target."));
12108
12109 hexnumstr (*buffer, value);
12110 *buffer += len;
12111 *left -= len;
12112
12113 /* NUL-terminate the buffer as a convenience, if there is
12114 room. */
12115 if (*left)
12116 **buffer = '\0';
12117 }
12118
12119 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12120 value, *REMOTE_ERRNO to the remote error number or zero if none
12121 was included, and *ATTACHMENT to point to the start of the annex
12122 if any. The length of the packet isn't needed here; there may
12123 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12124
12125 Return 0 if the packet could be parsed, -1 if it could not. If
12126 -1 is returned, the other variables may not be initialized. */
12127
12128 static int
12129 remote_hostio_parse_result (const char *buffer, int *retcode,
12130 int *remote_errno, const char **attachment)
12131 {
12132 char *p, *p2;
12133
12134 *remote_errno = 0;
12135 *attachment = NULL;
12136
12137 if (buffer[0] != 'F')
12138 return -1;
12139
12140 errno = 0;
12141 *retcode = strtol (&buffer[1], &p, 16);
12142 if (errno != 0 || p == &buffer[1])
12143 return -1;
12144
12145 /* Check for ",errno". */
12146 if (*p == ',')
12147 {
12148 errno = 0;
12149 *remote_errno = strtol (p + 1, &p2, 16);
12150 if (errno != 0 || p + 1 == p2)
12151 return -1;
12152 p = p2;
12153 }
12154
12155 /* Check for ";attachment". If there is no attachment, the
12156 packet should end here. */
12157 if (*p == ';')
12158 {
12159 *attachment = p + 1;
12160 return 0;
12161 }
12162 else if (*p == '\0')
12163 return 0;
12164 else
12165 return -1;
12166 }
12167
12168 /* Send a prepared I/O packet to the target and read its response.
12169 The prepared packet is in the global RS->BUF before this function
12170 is called, and the answer is there when we return.
12171
12172 COMMAND_BYTES is the length of the request to send, which may include
12173 binary data. WHICH_PACKET is the packet configuration to check
12174 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12175 is set to the error number and -1 is returned. Otherwise the value
12176 returned by the function is returned.
12177
12178 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12179 attachment is expected; an error will be reported if there's a
12180 mismatch. If one is found, *ATTACHMENT will be set to point into
12181 the packet buffer and *ATTACHMENT_LEN will be set to the
12182 attachment's length. */
12183
12184 int
12185 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12186 int *remote_errno, const char **attachment,
12187 int *attachment_len)
12188 {
12189 struct remote_state *rs = get_remote_state ();
12190 int ret, bytes_read;
12191 const char *attachment_tmp;
12192
12193 if (packet_support (which_packet) == PACKET_DISABLE)
12194 {
12195 *remote_errno = FILEIO_ENOSYS;
12196 return -1;
12197 }
12198
12199 putpkt_binary (rs->buf.data (), command_bytes);
12200 bytes_read = getpkt_sane (&rs->buf, 0);
12201
12202 /* If it timed out, something is wrong. Don't try to parse the
12203 buffer. */
12204 if (bytes_read < 0)
12205 {
12206 *remote_errno = FILEIO_EINVAL;
12207 return -1;
12208 }
12209
12210 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
12211 {
12212 case PACKET_ERROR:
12213 *remote_errno = FILEIO_EINVAL;
12214 return -1;
12215 case PACKET_UNKNOWN:
12216 *remote_errno = FILEIO_ENOSYS;
12217 return -1;
12218 case PACKET_OK:
12219 break;
12220 }
12221
12222 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12223 &attachment_tmp))
12224 {
12225 *remote_errno = FILEIO_EINVAL;
12226 return -1;
12227 }
12228
12229 /* Make sure we saw an attachment if and only if we expected one. */
12230 if ((attachment_tmp == NULL && attachment != NULL)
12231 || (attachment_tmp != NULL && attachment == NULL))
12232 {
12233 *remote_errno = FILEIO_EINVAL;
12234 return -1;
12235 }
12236
12237 /* If an attachment was found, it must point into the packet buffer;
12238 work out how many bytes there were. */
12239 if (attachment_tmp != NULL)
12240 {
12241 *attachment = attachment_tmp;
12242 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12243 }
12244
12245 return ret;
12246 }
12247
12248 /* See declaration.h. */
12249
12250 void
12251 readahead_cache::invalidate ()
12252 {
12253 this->fd = -1;
12254 }
12255
12256 /* See declaration.h. */
12257
12258 void
12259 readahead_cache::invalidate_fd (int fd)
12260 {
12261 if (this->fd == fd)
12262 this->fd = -1;
12263 }
12264
12265 /* Set the filesystem remote_hostio functions that take FILENAME
12266 arguments will use. Return 0 on success, or -1 if an error
12267 occurs (and set *REMOTE_ERRNO). */
12268
12269 int
12270 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12271 int *remote_errno)
12272 {
12273 struct remote_state *rs = get_remote_state ();
12274 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12275 char *p = rs->buf.data ();
12276 int left = get_remote_packet_size () - 1;
12277 char arg[9];
12278 int ret;
12279
12280 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12281 return 0;
12282
12283 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12284 return 0;
12285
12286 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12287
12288 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12289 remote_buffer_add_string (&p, &left, arg);
12290
12291 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12292 remote_errno, NULL, NULL);
12293
12294 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12295 return 0;
12296
12297 if (ret == 0)
12298 rs->fs_pid = required_pid;
12299
12300 return ret;
12301 }
12302
12303 /* Implementation of to_fileio_open. */
12304
12305 int
12306 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12307 int flags, int mode, int warn_if_slow,
12308 int *remote_errno)
12309 {
12310 struct remote_state *rs = get_remote_state ();
12311 char *p = rs->buf.data ();
12312 int left = get_remote_packet_size () - 1;
12313
12314 if (warn_if_slow)
12315 {
12316 static int warning_issued = 0;
12317
12318 gdb_printf (_("Reading %s from remote target...\n"),
12319 filename);
12320
12321 if (!warning_issued)
12322 {
12323 warning (_("File transfers from remote targets can be slow."
12324 " Use \"set sysroot\" to access files locally"
12325 " instead."));
12326 warning_issued = 1;
12327 }
12328 }
12329
12330 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12331 return -1;
12332
12333 remote_buffer_add_string (&p, &left, "vFile:open:");
12334
12335 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12336 strlen (filename));
12337 remote_buffer_add_string (&p, &left, ",");
12338
12339 remote_buffer_add_int (&p, &left, flags);
12340 remote_buffer_add_string (&p, &left, ",");
12341
12342 remote_buffer_add_int (&p, &left, mode);
12343
12344 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12345 remote_errno, NULL, NULL);
12346 }
12347
12348 int
12349 remote_target::fileio_open (struct inferior *inf, const char *filename,
12350 int flags, int mode, int warn_if_slow,
12351 int *remote_errno)
12352 {
12353 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12354 remote_errno);
12355 }
12356
12357 /* Implementation of to_fileio_pwrite. */
12358
12359 int
12360 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12361 ULONGEST offset, int *remote_errno)
12362 {
12363 struct remote_state *rs = get_remote_state ();
12364 char *p = rs->buf.data ();
12365 int left = get_remote_packet_size ();
12366 int out_len;
12367
12368 rs->readahead_cache.invalidate_fd (fd);
12369
12370 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12371
12372 remote_buffer_add_int (&p, &left, fd);
12373 remote_buffer_add_string (&p, &left, ",");
12374
12375 remote_buffer_add_int (&p, &left, offset);
12376 remote_buffer_add_string (&p, &left, ",");
12377
12378 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12379 (get_remote_packet_size ()
12380 - (p - rs->buf.data ())));
12381
12382 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12383 remote_errno, NULL, NULL);
12384 }
12385
12386 int
12387 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12388 ULONGEST offset, int *remote_errno)
12389 {
12390 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12391 }
12392
12393 /* Helper for the implementation of to_fileio_pread. Read the file
12394 from the remote side with vFile:pread. */
12395
12396 int
12397 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12398 ULONGEST offset, int *remote_errno)
12399 {
12400 struct remote_state *rs = get_remote_state ();
12401 char *p = rs->buf.data ();
12402 const char *attachment;
12403 int left = get_remote_packet_size ();
12404 int ret, attachment_len;
12405 int read_len;
12406
12407 remote_buffer_add_string (&p, &left, "vFile:pread:");
12408
12409 remote_buffer_add_int (&p, &left, fd);
12410 remote_buffer_add_string (&p, &left, ",");
12411
12412 remote_buffer_add_int (&p, &left, len);
12413 remote_buffer_add_string (&p, &left, ",");
12414
12415 remote_buffer_add_int (&p, &left, offset);
12416
12417 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12418 remote_errno, &attachment,
12419 &attachment_len);
12420
12421 if (ret < 0)
12422 return ret;
12423
12424 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12425 read_buf, len);
12426 if (read_len != ret)
12427 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12428
12429 return ret;
12430 }
12431
12432 /* See declaration.h. */
12433
12434 int
12435 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12436 ULONGEST offset)
12437 {
12438 if (this->fd == fd
12439 && this->offset <= offset
12440 && offset < this->offset + this->bufsize)
12441 {
12442 ULONGEST max = this->offset + this->bufsize;
12443
12444 if (offset + len > max)
12445 len = max - offset;
12446
12447 memcpy (read_buf, this->buf + offset - this->offset, len);
12448 return len;
12449 }
12450
12451 return 0;
12452 }
12453
12454 /* Implementation of to_fileio_pread. */
12455
12456 int
12457 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12458 ULONGEST offset, int *remote_errno)
12459 {
12460 int ret;
12461 struct remote_state *rs = get_remote_state ();
12462 readahead_cache *cache = &rs->readahead_cache;
12463
12464 ret = cache->pread (fd, read_buf, len, offset);
12465 if (ret > 0)
12466 {
12467 cache->hit_count++;
12468
12469 remote_debug_printf ("readahead cache hit %s",
12470 pulongest (cache->hit_count));
12471 return ret;
12472 }
12473
12474 cache->miss_count++;
12475
12476 remote_debug_printf ("readahead cache miss %s",
12477 pulongest (cache->miss_count));
12478
12479 cache->fd = fd;
12480 cache->offset = offset;
12481 cache->bufsize = get_remote_packet_size ();
12482 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12483
12484 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12485 cache->offset, remote_errno);
12486 if (ret <= 0)
12487 {
12488 cache->invalidate_fd (fd);
12489 return ret;
12490 }
12491
12492 cache->bufsize = ret;
12493 return cache->pread (fd, read_buf, len, offset);
12494 }
12495
12496 int
12497 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12498 ULONGEST offset, int *remote_errno)
12499 {
12500 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12501 }
12502
12503 /* Implementation of to_fileio_close. */
12504
12505 int
12506 remote_target::remote_hostio_close (int fd, int *remote_errno)
12507 {
12508 struct remote_state *rs = get_remote_state ();
12509 char *p = rs->buf.data ();
12510 int left = get_remote_packet_size () - 1;
12511
12512 rs->readahead_cache.invalidate_fd (fd);
12513
12514 remote_buffer_add_string (&p, &left, "vFile:close:");
12515
12516 remote_buffer_add_int (&p, &left, fd);
12517
12518 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12519 remote_errno, NULL, NULL);
12520 }
12521
12522 int
12523 remote_target::fileio_close (int fd, int *remote_errno)
12524 {
12525 return remote_hostio_close (fd, remote_errno);
12526 }
12527
12528 /* Implementation of to_fileio_unlink. */
12529
12530 int
12531 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12532 int *remote_errno)
12533 {
12534 struct remote_state *rs = get_remote_state ();
12535 char *p = rs->buf.data ();
12536 int left = get_remote_packet_size () - 1;
12537
12538 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12539 return -1;
12540
12541 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12542
12543 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12544 strlen (filename));
12545
12546 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12547 remote_errno, NULL, NULL);
12548 }
12549
12550 int
12551 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12552 int *remote_errno)
12553 {
12554 return remote_hostio_unlink (inf, filename, remote_errno);
12555 }
12556
12557 /* Implementation of to_fileio_readlink. */
12558
12559 gdb::optional<std::string>
12560 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12561 int *remote_errno)
12562 {
12563 struct remote_state *rs = get_remote_state ();
12564 char *p = rs->buf.data ();
12565 const char *attachment;
12566 int left = get_remote_packet_size ();
12567 int len, attachment_len;
12568 int read_len;
12569
12570 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12571 return {};
12572
12573 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12574
12575 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12576 strlen (filename));
12577
12578 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12579 remote_errno, &attachment,
12580 &attachment_len);
12581
12582 if (len < 0)
12583 return {};
12584
12585 std::string ret (len, '\0');
12586
12587 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12588 (gdb_byte *) &ret[0], len);
12589 if (read_len != len)
12590 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12591
12592 return ret;
12593 }
12594
12595 /* Implementation of to_fileio_fstat. */
12596
12597 int
12598 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12599 {
12600 struct remote_state *rs = get_remote_state ();
12601 char *p = rs->buf.data ();
12602 int left = get_remote_packet_size ();
12603 int attachment_len, ret;
12604 const char *attachment;
12605 struct fio_stat fst;
12606 int read_len;
12607
12608 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12609
12610 remote_buffer_add_int (&p, &left, fd);
12611
12612 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12613 remote_errno, &attachment,
12614 &attachment_len);
12615 if (ret < 0)
12616 {
12617 if (*remote_errno != FILEIO_ENOSYS)
12618 return ret;
12619
12620 /* Strictly we should return -1, ENOSYS here, but when
12621 "set sysroot remote:" was implemented in August 2008
12622 BFD's need for a stat function was sidestepped with
12623 this hack. This was not remedied until March 2015
12624 so we retain the previous behavior to avoid breaking
12625 compatibility.
12626
12627 Note that the memset is a March 2015 addition; older
12628 GDBs set st_size *and nothing else* so the structure
12629 would have garbage in all other fields. This might
12630 break something but retaining the previous behavior
12631 here would be just too wrong. */
12632
12633 memset (st, 0, sizeof (struct stat));
12634 st->st_size = INT_MAX;
12635 return 0;
12636 }
12637
12638 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12639 (gdb_byte *) &fst, sizeof (fst));
12640
12641 if (read_len != ret)
12642 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12643
12644 if (read_len != sizeof (fst))
12645 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12646 read_len, (int) sizeof (fst));
12647
12648 remote_fileio_to_host_stat (&fst, st);
12649
12650 return 0;
12651 }
12652
12653 /* Implementation of to_filesystem_is_local. */
12654
12655 bool
12656 remote_target::filesystem_is_local ()
12657 {
12658 /* Valgrind GDB presents itself as a remote target but works
12659 on the local filesystem: it does not implement remote get
12660 and users are not expected to set a sysroot. To handle
12661 this case we treat the remote filesystem as local if the
12662 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12663 does not support vFile:open. */
12664 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
12665 {
12666 enum packet_support ps = packet_support (PACKET_vFile_open);
12667
12668 if (ps == PACKET_SUPPORT_UNKNOWN)
12669 {
12670 int fd, remote_errno;
12671
12672 /* Try opening a file to probe support. The supplied
12673 filename is irrelevant, we only care about whether
12674 the stub recognizes the packet or not. */
12675 fd = remote_hostio_open (NULL, "just probing",
12676 FILEIO_O_RDONLY, 0700, 0,
12677 &remote_errno);
12678
12679 if (fd >= 0)
12680 remote_hostio_close (fd, &remote_errno);
12681
12682 ps = packet_support (PACKET_vFile_open);
12683 }
12684
12685 if (ps == PACKET_DISABLE)
12686 {
12687 static int warning_issued = 0;
12688
12689 if (!warning_issued)
12690 {
12691 warning (_("remote target does not support file"
12692 " transfer, attempting to access files"
12693 " from local filesystem."));
12694 warning_issued = 1;
12695 }
12696
12697 return true;
12698 }
12699 }
12700
12701 return false;
12702 }
12703
12704 static int
12705 remote_fileio_errno_to_host (int errnum)
12706 {
12707 switch (errnum)
12708 {
12709 case FILEIO_EPERM:
12710 return EPERM;
12711 case FILEIO_ENOENT:
12712 return ENOENT;
12713 case FILEIO_EINTR:
12714 return EINTR;
12715 case FILEIO_EIO:
12716 return EIO;
12717 case FILEIO_EBADF:
12718 return EBADF;
12719 case FILEIO_EACCES:
12720 return EACCES;
12721 case FILEIO_EFAULT:
12722 return EFAULT;
12723 case FILEIO_EBUSY:
12724 return EBUSY;
12725 case FILEIO_EEXIST:
12726 return EEXIST;
12727 case FILEIO_ENODEV:
12728 return ENODEV;
12729 case FILEIO_ENOTDIR:
12730 return ENOTDIR;
12731 case FILEIO_EISDIR:
12732 return EISDIR;
12733 case FILEIO_EINVAL:
12734 return EINVAL;
12735 case FILEIO_ENFILE:
12736 return ENFILE;
12737 case FILEIO_EMFILE:
12738 return EMFILE;
12739 case FILEIO_EFBIG:
12740 return EFBIG;
12741 case FILEIO_ENOSPC:
12742 return ENOSPC;
12743 case FILEIO_ESPIPE:
12744 return ESPIPE;
12745 case FILEIO_EROFS:
12746 return EROFS;
12747 case FILEIO_ENOSYS:
12748 return ENOSYS;
12749 case FILEIO_ENAMETOOLONG:
12750 return ENAMETOOLONG;
12751 }
12752 return -1;
12753 }
12754
12755 static char *
12756 remote_hostio_error (int errnum)
12757 {
12758 int host_error = remote_fileio_errno_to_host (errnum);
12759
12760 if (host_error == -1)
12761 error (_("Unknown remote I/O error %d"), errnum);
12762 else
12763 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12764 }
12765
12766 /* A RAII wrapper around a remote file descriptor. */
12767
12768 class scoped_remote_fd
12769 {
12770 public:
12771 scoped_remote_fd (remote_target *remote, int fd)
12772 : m_remote (remote), m_fd (fd)
12773 {
12774 }
12775
12776 ~scoped_remote_fd ()
12777 {
12778 if (m_fd != -1)
12779 {
12780 try
12781 {
12782 int remote_errno;
12783 m_remote->remote_hostio_close (m_fd, &remote_errno);
12784 }
12785 catch (...)
12786 {
12787 /* Swallow exception before it escapes the dtor. If
12788 something goes wrong, likely the connection is gone,
12789 and there's nothing else that can be done. */
12790 }
12791 }
12792 }
12793
12794 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12795
12796 /* Release ownership of the file descriptor, and return it. */
12797 ATTRIBUTE_UNUSED_RESULT int release () noexcept
12798 {
12799 int fd = m_fd;
12800 m_fd = -1;
12801 return fd;
12802 }
12803
12804 /* Return the owned file descriptor. */
12805 int get () const noexcept
12806 {
12807 return m_fd;
12808 }
12809
12810 private:
12811 /* The remote target. */
12812 remote_target *m_remote;
12813
12814 /* The owned remote I/O file descriptor. */
12815 int m_fd;
12816 };
12817
12818 void
12819 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12820 {
12821 remote_target *remote = get_current_remote_target ();
12822
12823 if (remote == nullptr)
12824 error (_("command can only be used with remote target"));
12825
12826 remote->remote_file_put (local_file, remote_file, from_tty);
12827 }
12828
12829 void
12830 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12831 int from_tty)
12832 {
12833 int retcode, remote_errno, bytes, io_size;
12834 int bytes_in_buffer;
12835 int saw_eof;
12836 ULONGEST offset;
12837
12838 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12839 if (file == NULL)
12840 perror_with_name (local_file);
12841
12842 scoped_remote_fd fd
12843 (this, remote_hostio_open (NULL,
12844 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12845 | FILEIO_O_TRUNC),
12846 0700, 0, &remote_errno));
12847 if (fd.get () == -1)
12848 remote_hostio_error (remote_errno);
12849
12850 /* Send up to this many bytes at once. They won't all fit in the
12851 remote packet limit, so we'll transfer slightly fewer. */
12852 io_size = get_remote_packet_size ();
12853 gdb::byte_vector buffer (io_size);
12854
12855 bytes_in_buffer = 0;
12856 saw_eof = 0;
12857 offset = 0;
12858 while (bytes_in_buffer || !saw_eof)
12859 {
12860 if (!saw_eof)
12861 {
12862 bytes = fread (buffer.data () + bytes_in_buffer, 1,
12863 io_size - bytes_in_buffer,
12864 file.get ());
12865 if (bytes == 0)
12866 {
12867 if (ferror (file.get ()))
12868 error (_("Error reading %s."), local_file);
12869 else
12870 {
12871 /* EOF. Unless there is something still in the
12872 buffer from the last iteration, we are done. */
12873 saw_eof = 1;
12874 if (bytes_in_buffer == 0)
12875 break;
12876 }
12877 }
12878 }
12879 else
12880 bytes = 0;
12881
12882 bytes += bytes_in_buffer;
12883 bytes_in_buffer = 0;
12884
12885 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12886 offset, &remote_errno);
12887
12888 if (retcode < 0)
12889 remote_hostio_error (remote_errno);
12890 else if (retcode == 0)
12891 error (_("Remote write of %d bytes returned 0!"), bytes);
12892 else if (retcode < bytes)
12893 {
12894 /* Short write. Save the rest of the read data for the next
12895 write. */
12896 bytes_in_buffer = bytes - retcode;
12897 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
12898 }
12899
12900 offset += retcode;
12901 }
12902
12903 if (remote_hostio_close (fd.release (), &remote_errno))
12904 remote_hostio_error (remote_errno);
12905
12906 if (from_tty)
12907 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
12908 }
12909
12910 void
12911 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12912 {
12913 remote_target *remote = get_current_remote_target ();
12914
12915 if (remote == nullptr)
12916 error (_("command can only be used with remote target"));
12917
12918 remote->remote_file_get (remote_file, local_file, from_tty);
12919 }
12920
12921 void
12922 remote_target::remote_file_get (const char *remote_file, const char *local_file,
12923 int from_tty)
12924 {
12925 int remote_errno, bytes, io_size;
12926 ULONGEST offset;
12927
12928 scoped_remote_fd fd
12929 (this, remote_hostio_open (NULL,
12930 remote_file, FILEIO_O_RDONLY, 0, 0,
12931 &remote_errno));
12932 if (fd.get () == -1)
12933 remote_hostio_error (remote_errno);
12934
12935 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12936 if (file == NULL)
12937 perror_with_name (local_file);
12938
12939 /* Send up to this many bytes at once. They won't all fit in the
12940 remote packet limit, so we'll transfer slightly fewer. */
12941 io_size = get_remote_packet_size ();
12942 gdb::byte_vector buffer (io_size);
12943
12944 offset = 0;
12945 while (1)
12946 {
12947 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
12948 &remote_errno);
12949 if (bytes == 0)
12950 /* Success, but no bytes, means end-of-file. */
12951 break;
12952 if (bytes == -1)
12953 remote_hostio_error (remote_errno);
12954
12955 offset += bytes;
12956
12957 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
12958 if (bytes == 0)
12959 perror_with_name (local_file);
12960 }
12961
12962 if (remote_hostio_close (fd.release (), &remote_errno))
12963 remote_hostio_error (remote_errno);
12964
12965 if (from_tty)
12966 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
12967 }
12968
12969 void
12970 remote_file_delete (const char *remote_file, int from_tty)
12971 {
12972 remote_target *remote = get_current_remote_target ();
12973
12974 if (remote == nullptr)
12975 error (_("command can only be used with remote target"));
12976
12977 remote->remote_file_delete (remote_file, from_tty);
12978 }
12979
12980 void
12981 remote_target::remote_file_delete (const char *remote_file, int from_tty)
12982 {
12983 int retcode, remote_errno;
12984
12985 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
12986 if (retcode == -1)
12987 remote_hostio_error (remote_errno);
12988
12989 if (from_tty)
12990 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
12991 }
12992
12993 static void
12994 remote_put_command (const char *args, int from_tty)
12995 {
12996 if (args == NULL)
12997 error_no_arg (_("file to put"));
12998
12999 gdb_argv argv (args);
13000 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13001 error (_("Invalid parameters to remote put"));
13002
13003 remote_file_put (argv[0], argv[1], from_tty);
13004 }
13005
13006 static void
13007 remote_get_command (const char *args, int from_tty)
13008 {
13009 if (args == NULL)
13010 error_no_arg (_("file to get"));
13011
13012 gdb_argv argv (args);
13013 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13014 error (_("Invalid parameters to remote get"));
13015
13016 remote_file_get (argv[0], argv[1], from_tty);
13017 }
13018
13019 static void
13020 remote_delete_command (const char *args, int from_tty)
13021 {
13022 if (args == NULL)
13023 error_no_arg (_("file to delete"));
13024
13025 gdb_argv argv (args);
13026 if (argv[0] == NULL || argv[1] != NULL)
13027 error (_("Invalid parameters to remote delete"));
13028
13029 remote_file_delete (argv[0], from_tty);
13030 }
13031
13032 bool
13033 remote_target::can_execute_reverse ()
13034 {
13035 if (packet_support (PACKET_bs) == PACKET_ENABLE
13036 || packet_support (PACKET_bc) == PACKET_ENABLE)
13037 return true;
13038 else
13039 return false;
13040 }
13041
13042 bool
13043 remote_target::supports_non_stop ()
13044 {
13045 return true;
13046 }
13047
13048 bool
13049 remote_target::supports_disable_randomization ()
13050 {
13051 /* Only supported in extended mode. */
13052 return false;
13053 }
13054
13055 bool
13056 remote_target::supports_multi_process ()
13057 {
13058 struct remote_state *rs = get_remote_state ();
13059
13060 return remote_multi_process_p (rs);
13061 }
13062
13063 static int
13064 remote_supports_cond_tracepoints ()
13065 {
13066 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
13067 }
13068
13069 bool
13070 remote_target::supports_evaluation_of_breakpoint_conditions ()
13071 {
13072 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
13073 }
13074
13075 static int
13076 remote_supports_fast_tracepoints ()
13077 {
13078 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13079 }
13080
13081 static int
13082 remote_supports_static_tracepoints ()
13083 {
13084 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13085 }
13086
13087 static int
13088 remote_supports_install_in_trace ()
13089 {
13090 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13091 }
13092
13093 bool
13094 remote_target::supports_enable_disable_tracepoint ()
13095 {
13096 return (packet_support (PACKET_EnableDisableTracepoints_feature)
13097 == PACKET_ENABLE);
13098 }
13099
13100 bool
13101 remote_target::supports_string_tracing ()
13102 {
13103 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13104 }
13105
13106 bool
13107 remote_target::can_run_breakpoint_commands ()
13108 {
13109 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13110 }
13111
13112 void
13113 remote_target::trace_init ()
13114 {
13115 struct remote_state *rs = get_remote_state ();
13116
13117 putpkt ("QTinit");
13118 remote_get_noisy_reply ();
13119 if (strcmp (rs->buf.data (), "OK") != 0)
13120 error (_("Target does not support this command."));
13121 }
13122
13123 /* Recursive routine to walk through command list including loops, and
13124 download packets for each command. */
13125
13126 void
13127 remote_target::remote_download_command_source (int num, ULONGEST addr,
13128 struct command_line *cmds)
13129 {
13130 struct remote_state *rs = get_remote_state ();
13131 struct command_line *cmd;
13132
13133 for (cmd = cmds; cmd; cmd = cmd->next)
13134 {
13135 QUIT; /* Allow user to bail out with ^C. */
13136 strcpy (rs->buf.data (), "QTDPsrc:");
13137 encode_source_string (num, addr, "cmd", cmd->line,
13138 rs->buf.data () + strlen (rs->buf.data ()),
13139 rs->buf.size () - strlen (rs->buf.data ()));
13140 putpkt (rs->buf);
13141 remote_get_noisy_reply ();
13142 if (strcmp (rs->buf.data (), "OK"))
13143 warning (_("Target does not support source download."));
13144
13145 if (cmd->control_type == while_control
13146 || cmd->control_type == while_stepping_control)
13147 {
13148 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13149
13150 QUIT; /* Allow user to bail out with ^C. */
13151 strcpy (rs->buf.data (), "QTDPsrc:");
13152 encode_source_string (num, addr, "cmd", "end",
13153 rs->buf.data () + strlen (rs->buf.data ()),
13154 rs->buf.size () - strlen (rs->buf.data ()));
13155 putpkt (rs->buf);
13156 remote_get_noisy_reply ();
13157 if (strcmp (rs->buf.data (), "OK"))
13158 warning (_("Target does not support source download."));
13159 }
13160 }
13161 }
13162
13163 void
13164 remote_target::download_tracepoint (struct bp_location *loc)
13165 {
13166 CORE_ADDR tpaddr;
13167 char addrbuf[40];
13168 std::vector<std::string> tdp_actions;
13169 std::vector<std::string> stepping_actions;
13170 char *pkt;
13171 struct breakpoint *b = loc->owner;
13172 struct tracepoint *t = (struct tracepoint *) b;
13173 struct remote_state *rs = get_remote_state ();
13174 int ret;
13175 const char *err_msg = _("Tracepoint packet too large for target.");
13176 size_t size_left;
13177
13178 /* We use a buffer other than rs->buf because we'll build strings
13179 across multiple statements, and other statements in between could
13180 modify rs->buf. */
13181 gdb::char_vector buf (get_remote_packet_size ());
13182
13183 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13184
13185 tpaddr = loc->address;
13186 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13187 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13188 b->number, addrbuf, /* address */
13189 (b->enable_state == bp_enabled ? 'E' : 'D'),
13190 t->step_count, t->pass_count);
13191
13192 if (ret < 0 || ret >= buf.size ())
13193 error ("%s", err_msg);
13194
13195 /* Fast tracepoints are mostly handled by the target, but we can
13196 tell the target how big of an instruction block should be moved
13197 around. */
13198 if (b->type == bp_fast_tracepoint)
13199 {
13200 /* Only test for support at download time; we may not know
13201 target capabilities at definition time. */
13202 if (remote_supports_fast_tracepoints ())
13203 {
13204 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13205 NULL))
13206 {
13207 size_left = buf.size () - strlen (buf.data ());
13208 ret = snprintf (buf.data () + strlen (buf.data ()),
13209 size_left, ":F%x",
13210 gdb_insn_length (loc->gdbarch, tpaddr));
13211
13212 if (ret < 0 || ret >= size_left)
13213 error ("%s", err_msg);
13214 }
13215 else
13216 /* If it passed validation at definition but fails now,
13217 something is very wrong. */
13218 internal_error (__FILE__, __LINE__,
13219 _("Fast tracepoint not "
13220 "valid during download"));
13221 }
13222 else
13223 /* Fast tracepoints are functionally identical to regular
13224 tracepoints, so don't take lack of support as a reason to
13225 give up on the trace run. */
13226 warning (_("Target does not support fast tracepoints, "
13227 "downloading %d as regular tracepoint"), b->number);
13228 }
13229 else if (b->type == bp_static_tracepoint)
13230 {
13231 /* Only test for support at download time; we may not know
13232 target capabilities at definition time. */
13233 if (remote_supports_static_tracepoints ())
13234 {
13235 struct static_tracepoint_marker marker;
13236
13237 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13238 {
13239 size_left = buf.size () - strlen (buf.data ());
13240 ret = snprintf (buf.data () + strlen (buf.data ()),
13241 size_left, ":S");
13242
13243 if (ret < 0 || ret >= size_left)
13244 error ("%s", err_msg);
13245 }
13246 else
13247 error (_("Static tracepoint not valid during download"));
13248 }
13249 else
13250 /* Fast tracepoints are functionally identical to regular
13251 tracepoints, so don't take lack of support as a reason
13252 to give up on the trace run. */
13253 error (_("Target does not support static tracepoints"));
13254 }
13255 /* If the tracepoint has a conditional, make it into an agent
13256 expression and append to the definition. */
13257 if (loc->cond)
13258 {
13259 /* Only test support at download time, we may not know target
13260 capabilities at definition time. */
13261 if (remote_supports_cond_tracepoints ())
13262 {
13263 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13264 loc->cond.get ());
13265
13266 size_left = buf.size () - strlen (buf.data ());
13267
13268 ret = snprintf (buf.data () + strlen (buf.data ()),
13269 size_left, ":X%x,", aexpr->len);
13270
13271 if (ret < 0 || ret >= size_left)
13272 error ("%s", err_msg);
13273
13274 size_left = buf.size () - strlen (buf.data ());
13275
13276 /* Two bytes to encode each aexpr byte, plus the terminating
13277 null byte. */
13278 if (aexpr->len * 2 + 1 > size_left)
13279 error ("%s", err_msg);
13280
13281 pkt = buf.data () + strlen (buf.data ());
13282
13283 for (int ndx = 0; ndx < aexpr->len; ++ndx)
13284 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13285 *pkt = '\0';
13286 }
13287 else
13288 warning (_("Target does not support conditional tracepoints, "
13289 "ignoring tp %d cond"), b->number);
13290 }
13291
13292 if (b->commands || !default_collect.empty ())
13293 {
13294 size_left = buf.size () - strlen (buf.data ());
13295
13296 ret = snprintf (buf.data () + strlen (buf.data ()),
13297 size_left, "-");
13298
13299 if (ret < 0 || ret >= size_left)
13300 error ("%s", err_msg);
13301 }
13302
13303 putpkt (buf.data ());
13304 remote_get_noisy_reply ();
13305 if (strcmp (rs->buf.data (), "OK"))
13306 error (_("Target does not support tracepoints."));
13307
13308 /* do_single_steps (t); */
13309 for (auto action_it = tdp_actions.begin ();
13310 action_it != tdp_actions.end (); action_it++)
13311 {
13312 QUIT; /* Allow user to bail out with ^C. */
13313
13314 bool has_more = ((action_it + 1) != tdp_actions.end ()
13315 || !stepping_actions.empty ());
13316
13317 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13318 b->number, addrbuf, /* address */
13319 action_it->c_str (),
13320 has_more ? '-' : 0);
13321
13322 if (ret < 0 || ret >= buf.size ())
13323 error ("%s", err_msg);
13324
13325 putpkt (buf.data ());
13326 remote_get_noisy_reply ();
13327 if (strcmp (rs->buf.data (), "OK"))
13328 error (_("Error on target while setting tracepoints."));
13329 }
13330
13331 for (auto action_it = stepping_actions.begin ();
13332 action_it != stepping_actions.end (); action_it++)
13333 {
13334 QUIT; /* Allow user to bail out with ^C. */
13335
13336 bool is_first = action_it == stepping_actions.begin ();
13337 bool has_more = (action_it + 1) != stepping_actions.end ();
13338
13339 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13340 b->number, addrbuf, /* address */
13341 is_first ? "S" : "",
13342 action_it->c_str (),
13343 has_more ? "-" : "");
13344
13345 if (ret < 0 || ret >= buf.size ())
13346 error ("%s", err_msg);
13347
13348 putpkt (buf.data ());
13349 remote_get_noisy_reply ();
13350 if (strcmp (rs->buf.data (), "OK"))
13351 error (_("Error on target while setting tracepoints."));
13352 }
13353
13354 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13355 {
13356 if (b->location != NULL)
13357 {
13358 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13359
13360 if (ret < 0 || ret >= buf.size ())
13361 error ("%s", err_msg);
13362
13363 encode_source_string (b->number, loc->address, "at",
13364 event_location_to_string (b->location.get ()),
13365 buf.data () + strlen (buf.data ()),
13366 buf.size () - strlen (buf.data ()));
13367 putpkt (buf.data ());
13368 remote_get_noisy_reply ();
13369 if (strcmp (rs->buf.data (), "OK"))
13370 warning (_("Target does not support source download."));
13371 }
13372 if (b->cond_string)
13373 {
13374 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13375
13376 if (ret < 0 || ret >= buf.size ())
13377 error ("%s", err_msg);
13378
13379 encode_source_string (b->number, loc->address,
13380 "cond", b->cond_string.get (),
13381 buf.data () + strlen (buf.data ()),
13382 buf.size () - strlen (buf.data ()));
13383 putpkt (buf.data ());
13384 remote_get_noisy_reply ();
13385 if (strcmp (rs->buf.data (), "OK"))
13386 warning (_("Target does not support source download."));
13387 }
13388 remote_download_command_source (b->number, loc->address,
13389 breakpoint_commands (b));
13390 }
13391 }
13392
13393 bool
13394 remote_target::can_download_tracepoint ()
13395 {
13396 struct remote_state *rs = get_remote_state ();
13397 struct trace_status *ts;
13398 int status;
13399
13400 /* Don't try to install tracepoints until we've relocated our
13401 symbols, and fetched and merged the target's tracepoint list with
13402 ours. */
13403 if (rs->starting_up)
13404 return false;
13405
13406 ts = current_trace_status ();
13407 status = get_trace_status (ts);
13408
13409 if (status == -1 || !ts->running_known || !ts->running)
13410 return false;
13411
13412 /* If we are in a tracing experiment, but remote stub doesn't support
13413 installing tracepoint in trace, we have to return. */
13414 if (!remote_supports_install_in_trace ())
13415 return false;
13416
13417 return true;
13418 }
13419
13420
13421 void
13422 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13423 {
13424 struct remote_state *rs = get_remote_state ();
13425 char *p;
13426
13427 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13428 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13429 tsv.builtin);
13430 p = rs->buf.data () + strlen (rs->buf.data ());
13431 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13432 >= get_remote_packet_size ())
13433 error (_("Trace state variable name too long for tsv definition packet"));
13434 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13435 *p++ = '\0';
13436 putpkt (rs->buf);
13437 remote_get_noisy_reply ();
13438 if (rs->buf[0] == '\0')
13439 error (_("Target does not support this command."));
13440 if (strcmp (rs->buf.data (), "OK") != 0)
13441 error (_("Error on target while downloading trace state variable."));
13442 }
13443
13444 void
13445 remote_target::enable_tracepoint (struct bp_location *location)
13446 {
13447 struct remote_state *rs = get_remote_state ();
13448
13449 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13450 location->owner->number,
13451 phex (location->address, sizeof (CORE_ADDR)));
13452 putpkt (rs->buf);
13453 remote_get_noisy_reply ();
13454 if (rs->buf[0] == '\0')
13455 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13456 if (strcmp (rs->buf.data (), "OK") != 0)
13457 error (_("Error on target while enabling tracepoint."));
13458 }
13459
13460 void
13461 remote_target::disable_tracepoint (struct bp_location *location)
13462 {
13463 struct remote_state *rs = get_remote_state ();
13464
13465 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13466 location->owner->number,
13467 phex (location->address, sizeof (CORE_ADDR)));
13468 putpkt (rs->buf);
13469 remote_get_noisy_reply ();
13470 if (rs->buf[0] == '\0')
13471 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13472 if (strcmp (rs->buf.data (), "OK") != 0)
13473 error (_("Error on target while disabling tracepoint."));
13474 }
13475
13476 void
13477 remote_target::trace_set_readonly_regions ()
13478 {
13479 asection *s;
13480 bfd_size_type size;
13481 bfd_vma vma;
13482 int anysecs = 0;
13483 int offset = 0;
13484
13485 if (!current_program_space->exec_bfd ())
13486 return; /* No information to give. */
13487
13488 struct remote_state *rs = get_remote_state ();
13489
13490 strcpy (rs->buf.data (), "QTro");
13491 offset = strlen (rs->buf.data ());
13492 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
13493 {
13494 char tmp1[40], tmp2[40];
13495 int sec_length;
13496
13497 if ((s->flags & SEC_LOAD) == 0 ||
13498 /* (s->flags & SEC_CODE) == 0 || */
13499 (s->flags & SEC_READONLY) == 0)
13500 continue;
13501
13502 anysecs = 1;
13503 vma = bfd_section_vma (s);
13504 size = bfd_section_size (s);
13505 sprintf_vma (tmp1, vma);
13506 sprintf_vma (tmp2, vma + size);
13507 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13508 if (offset + sec_length + 1 > rs->buf.size ())
13509 {
13510 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
13511 warning (_("\
13512 Too many sections for read-only sections definition packet."));
13513 break;
13514 }
13515 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13516 tmp1, tmp2);
13517 offset += sec_length;
13518 }
13519 if (anysecs)
13520 {
13521 putpkt (rs->buf);
13522 getpkt (&rs->buf, 0);
13523 }
13524 }
13525
13526 void
13527 remote_target::trace_start ()
13528 {
13529 struct remote_state *rs = get_remote_state ();
13530
13531 putpkt ("QTStart");
13532 remote_get_noisy_reply ();
13533 if (rs->buf[0] == '\0')
13534 error (_("Target does not support this command."));
13535 if (strcmp (rs->buf.data (), "OK") != 0)
13536 error (_("Bogus reply from target: %s"), rs->buf.data ());
13537 }
13538
13539 int
13540 remote_target::get_trace_status (struct trace_status *ts)
13541 {
13542 /* Initialize it just to avoid a GCC false warning. */
13543 char *p = NULL;
13544 enum packet_result result;
13545 struct remote_state *rs = get_remote_state ();
13546
13547 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13548 return -1;
13549
13550 /* FIXME we need to get register block size some other way. */
13551 trace_regblock_size
13552 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13553
13554 putpkt ("qTStatus");
13555
13556 try
13557 {
13558 p = remote_get_noisy_reply ();
13559 }
13560 catch (const gdb_exception_error &ex)
13561 {
13562 if (ex.error != TARGET_CLOSE_ERROR)
13563 {
13564 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13565 return -1;
13566 }
13567 throw;
13568 }
13569
13570 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13571
13572 /* If the remote target doesn't do tracing, flag it. */
13573 if (result == PACKET_UNKNOWN)
13574 return -1;
13575
13576 /* We're working with a live target. */
13577 ts->filename = NULL;
13578
13579 if (*p++ != 'T')
13580 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13581
13582 /* Function 'parse_trace_status' sets default value of each field of
13583 'ts' at first, so we don't have to do it here. */
13584 parse_trace_status (p, ts);
13585
13586 return ts->running;
13587 }
13588
13589 void
13590 remote_target::get_tracepoint_status (struct breakpoint *bp,
13591 struct uploaded_tp *utp)
13592 {
13593 struct remote_state *rs = get_remote_state ();
13594 char *reply;
13595 struct tracepoint *tp = (struct tracepoint *) bp;
13596 size_t size = get_remote_packet_size ();
13597
13598 if (tp)
13599 {
13600 tp->hit_count = 0;
13601 tp->traceframe_usage = 0;
13602 for (bp_location *loc : tp->locations ())
13603 {
13604 /* If the tracepoint was never downloaded, don't go asking for
13605 any status. */
13606 if (tp->number_on_target == 0)
13607 continue;
13608 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13609 phex_nz (loc->address, 0));
13610 putpkt (rs->buf);
13611 reply = remote_get_noisy_reply ();
13612 if (reply && *reply)
13613 {
13614 if (*reply == 'V')
13615 parse_tracepoint_status (reply + 1, bp, utp);
13616 }
13617 }
13618 }
13619 else if (utp)
13620 {
13621 utp->hit_count = 0;
13622 utp->traceframe_usage = 0;
13623 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13624 phex_nz (utp->addr, 0));
13625 putpkt (rs->buf);
13626 reply = remote_get_noisy_reply ();
13627 if (reply && *reply)
13628 {
13629 if (*reply == 'V')
13630 parse_tracepoint_status (reply + 1, bp, utp);
13631 }
13632 }
13633 }
13634
13635 void
13636 remote_target::trace_stop ()
13637 {
13638 struct remote_state *rs = get_remote_state ();
13639
13640 putpkt ("QTStop");
13641 remote_get_noisy_reply ();
13642 if (rs->buf[0] == '\0')
13643 error (_("Target does not support this command."));
13644 if (strcmp (rs->buf.data (), "OK") != 0)
13645 error (_("Bogus reply from target: %s"), rs->buf.data ());
13646 }
13647
13648 int
13649 remote_target::trace_find (enum trace_find_type type, int num,
13650 CORE_ADDR addr1, CORE_ADDR addr2,
13651 int *tpp)
13652 {
13653 struct remote_state *rs = get_remote_state ();
13654 char *endbuf = rs->buf.data () + get_remote_packet_size ();
13655 char *p, *reply;
13656 int target_frameno = -1, target_tracept = -1;
13657
13658 /* Lookups other than by absolute frame number depend on the current
13659 trace selected, so make sure it is correct on the remote end
13660 first. */
13661 if (type != tfind_number)
13662 set_remote_traceframe ();
13663
13664 p = rs->buf.data ();
13665 strcpy (p, "QTFrame:");
13666 p = strchr (p, '\0');
13667 switch (type)
13668 {
13669 case tfind_number:
13670 xsnprintf (p, endbuf - p, "%x", num);
13671 break;
13672 case tfind_pc:
13673 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13674 break;
13675 case tfind_tp:
13676 xsnprintf (p, endbuf - p, "tdp:%x", num);
13677 break;
13678 case tfind_range:
13679 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13680 phex_nz (addr2, 0));
13681 break;
13682 case tfind_outside:
13683 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13684 phex_nz (addr2, 0));
13685 break;
13686 default:
13687 error (_("Unknown trace find type %d"), type);
13688 }
13689
13690 putpkt (rs->buf);
13691 reply = remote_get_noisy_reply ();
13692 if (*reply == '\0')
13693 error (_("Target does not support this command."));
13694
13695 while (reply && *reply)
13696 switch (*reply)
13697 {
13698 case 'F':
13699 p = ++reply;
13700 target_frameno = (int) strtol (p, &reply, 16);
13701 if (reply == p)
13702 error (_("Unable to parse trace frame number"));
13703 /* Don't update our remote traceframe number cache on failure
13704 to select a remote traceframe. */
13705 if (target_frameno == -1)
13706 return -1;
13707 break;
13708 case 'T':
13709 p = ++reply;
13710 target_tracept = (int) strtol (p, &reply, 16);
13711 if (reply == p)
13712 error (_("Unable to parse tracepoint number"));
13713 break;
13714 case 'O': /* "OK"? */
13715 if (reply[1] == 'K' && reply[2] == '\0')
13716 reply += 2;
13717 else
13718 error (_("Bogus reply from target: %s"), reply);
13719 break;
13720 default:
13721 error (_("Bogus reply from target: %s"), reply);
13722 }
13723 if (tpp)
13724 *tpp = target_tracept;
13725
13726 rs->remote_traceframe_number = target_frameno;
13727 return target_frameno;
13728 }
13729
13730 bool
13731 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13732 {
13733 struct remote_state *rs = get_remote_state ();
13734 char *reply;
13735 ULONGEST uval;
13736
13737 set_remote_traceframe ();
13738
13739 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
13740 putpkt (rs->buf);
13741 reply = remote_get_noisy_reply ();
13742 if (reply && *reply)
13743 {
13744 if (*reply == 'V')
13745 {
13746 unpack_varlen_hex (reply + 1, &uval);
13747 *val = (LONGEST) uval;
13748 return true;
13749 }
13750 }
13751 return false;
13752 }
13753
13754 int
13755 remote_target::save_trace_data (const char *filename)
13756 {
13757 struct remote_state *rs = get_remote_state ();
13758 char *p, *reply;
13759
13760 p = rs->buf.data ();
13761 strcpy (p, "QTSave:");
13762 p += strlen (p);
13763 if ((p - rs->buf.data ()) + strlen (filename) * 2
13764 >= get_remote_packet_size ())
13765 error (_("Remote file name too long for trace save packet"));
13766 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13767 *p++ = '\0';
13768 putpkt (rs->buf);
13769 reply = remote_get_noisy_reply ();
13770 if (*reply == '\0')
13771 error (_("Target does not support this command."));
13772 if (strcmp (reply, "OK") != 0)
13773 error (_("Bogus reply from target: %s"), reply);
13774 return 0;
13775 }
13776
13777 /* This is basically a memory transfer, but needs to be its own packet
13778 because we don't know how the target actually organizes its trace
13779 memory, plus we want to be able to ask for as much as possible, but
13780 not be unhappy if we don't get as much as we ask for. */
13781
13782 LONGEST
13783 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13784 {
13785 struct remote_state *rs = get_remote_state ();
13786 char *reply;
13787 char *p;
13788 int rslt;
13789
13790 p = rs->buf.data ();
13791 strcpy (p, "qTBuffer:");
13792 p += strlen (p);
13793 p += hexnumstr (p, offset);
13794 *p++ = ',';
13795 p += hexnumstr (p, len);
13796 *p++ = '\0';
13797
13798 putpkt (rs->buf);
13799 reply = remote_get_noisy_reply ();
13800 if (reply && *reply)
13801 {
13802 /* 'l' by itself means we're at the end of the buffer and
13803 there is nothing more to get. */
13804 if (*reply == 'l')
13805 return 0;
13806
13807 /* Convert the reply into binary. Limit the number of bytes to
13808 convert according to our passed-in buffer size, rather than
13809 what was returned in the packet; if the target is
13810 unexpectedly generous and gives us a bigger reply than we
13811 asked for, we don't want to crash. */
13812 rslt = hex2bin (reply, buf, len);
13813 return rslt;
13814 }
13815
13816 /* Something went wrong, flag as an error. */
13817 return -1;
13818 }
13819
13820 void
13821 remote_target::set_disconnected_tracing (int val)
13822 {
13823 struct remote_state *rs = get_remote_state ();
13824
13825 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13826 {
13827 char *reply;
13828
13829 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13830 "QTDisconnected:%x", val);
13831 putpkt (rs->buf);
13832 reply = remote_get_noisy_reply ();
13833 if (*reply == '\0')
13834 error (_("Target does not support this command."));
13835 if (strcmp (reply, "OK") != 0)
13836 error (_("Bogus reply from target: %s"), reply);
13837 }
13838 else if (val)
13839 warning (_("Target does not support disconnected tracing."));
13840 }
13841
13842 int
13843 remote_target::core_of_thread (ptid_t ptid)
13844 {
13845 thread_info *info = find_thread_ptid (this, ptid);
13846
13847 if (info != NULL && info->priv != NULL)
13848 return get_remote_thread_info (info)->core;
13849
13850 return -1;
13851 }
13852
13853 void
13854 remote_target::set_circular_trace_buffer (int val)
13855 {
13856 struct remote_state *rs = get_remote_state ();
13857 char *reply;
13858
13859 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13860 "QTBuffer:circular:%x", val);
13861 putpkt (rs->buf);
13862 reply = remote_get_noisy_reply ();
13863 if (*reply == '\0')
13864 error (_("Target does not support this command."));
13865 if (strcmp (reply, "OK") != 0)
13866 error (_("Bogus reply from target: %s"), reply);
13867 }
13868
13869 traceframe_info_up
13870 remote_target::traceframe_info ()
13871 {
13872 gdb::optional<gdb::char_vector> text
13873 = target_read_stralloc (current_inferior ()->top_target (),
13874 TARGET_OBJECT_TRACEFRAME_INFO,
13875 NULL);
13876 if (text)
13877 return parse_traceframe_info (text->data ());
13878
13879 return NULL;
13880 }
13881
13882 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13883 instruction on which a fast tracepoint may be placed. Returns -1
13884 if the packet is not supported, and 0 if the minimum instruction
13885 length is unknown. */
13886
13887 int
13888 remote_target::get_min_fast_tracepoint_insn_len ()
13889 {
13890 struct remote_state *rs = get_remote_state ();
13891 char *reply;
13892
13893 /* If we're not debugging a process yet, the IPA can't be
13894 loaded. */
13895 if (!target_has_execution ())
13896 return 0;
13897
13898 /* Make sure the remote is pointing at the right process. */
13899 set_general_process ();
13900
13901 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
13902 putpkt (rs->buf);
13903 reply = remote_get_noisy_reply ();
13904 if (*reply == '\0')
13905 return -1;
13906 else
13907 {
13908 ULONGEST min_insn_len;
13909
13910 unpack_varlen_hex (reply, &min_insn_len);
13911
13912 return (int) min_insn_len;
13913 }
13914 }
13915
13916 void
13917 remote_target::set_trace_buffer_size (LONGEST val)
13918 {
13919 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13920 {
13921 struct remote_state *rs = get_remote_state ();
13922 char *buf = rs->buf.data ();
13923 char *endbuf = buf + get_remote_packet_size ();
13924 enum packet_result result;
13925
13926 gdb_assert (val >= 0 || val == -1);
13927 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13928 /* Send -1 as literal "-1" to avoid host size dependency. */
13929 if (val < 0)
13930 {
13931 *buf++ = '-';
13932 buf += hexnumstr (buf, (ULONGEST) -val);
13933 }
13934 else
13935 buf += hexnumstr (buf, (ULONGEST) val);
13936
13937 putpkt (rs->buf);
13938 remote_get_noisy_reply ();
13939 result = packet_ok (rs->buf,
13940 &remote_protocol_packets[PACKET_QTBuffer_size]);
13941
13942 if (result != PACKET_OK)
13943 warning (_("Bogus reply from target: %s"), rs->buf.data ());
13944 }
13945 }
13946
13947 bool
13948 remote_target::set_trace_notes (const char *user, const char *notes,
13949 const char *stop_notes)
13950 {
13951 struct remote_state *rs = get_remote_state ();
13952 char *reply;
13953 char *buf = rs->buf.data ();
13954 char *endbuf = buf + get_remote_packet_size ();
13955 int nbytes;
13956
13957 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13958 if (user)
13959 {
13960 buf += xsnprintf (buf, endbuf - buf, "user:");
13961 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13962 buf += 2 * nbytes;
13963 *buf++ = ';';
13964 }
13965 if (notes)
13966 {
13967 buf += xsnprintf (buf, endbuf - buf, "notes:");
13968 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13969 buf += 2 * nbytes;
13970 *buf++ = ';';
13971 }
13972 if (stop_notes)
13973 {
13974 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13975 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13976 buf += 2 * nbytes;
13977 *buf++ = ';';
13978 }
13979 /* Ensure the buffer is terminated. */
13980 *buf = '\0';
13981
13982 putpkt (rs->buf);
13983 reply = remote_get_noisy_reply ();
13984 if (*reply == '\0')
13985 return false;
13986
13987 if (strcmp (reply, "OK") != 0)
13988 error (_("Bogus reply from target: %s"), reply);
13989
13990 return true;
13991 }
13992
13993 bool
13994 remote_target::use_agent (bool use)
13995 {
13996 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13997 {
13998 struct remote_state *rs = get_remote_state ();
13999
14000 /* If the stub supports QAgent. */
14001 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
14002 putpkt (rs->buf);
14003 getpkt (&rs->buf, 0);
14004
14005 if (strcmp (rs->buf.data (), "OK") == 0)
14006 {
14007 ::use_agent = use;
14008 return true;
14009 }
14010 }
14011
14012 return false;
14013 }
14014
14015 bool
14016 remote_target::can_use_agent ()
14017 {
14018 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
14019 }
14020
14021 struct btrace_target_info
14022 {
14023 /* The ptid of the traced thread. */
14024 ptid_t ptid;
14025
14026 /* The obtained branch trace configuration. */
14027 struct btrace_config conf;
14028 };
14029
14030 /* Reset our idea of our target's btrace configuration. */
14031
14032 static void
14033 remote_btrace_reset (remote_state *rs)
14034 {
14035 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14036 }
14037
14038 /* Synchronize the configuration with the target. */
14039
14040 void
14041 remote_target::btrace_sync_conf (const btrace_config *conf)
14042 {
14043 struct packet_config *packet;
14044 struct remote_state *rs;
14045 char *buf, *pos, *endbuf;
14046
14047 rs = get_remote_state ();
14048 buf = rs->buf.data ();
14049 endbuf = buf + get_remote_packet_size ();
14050
14051 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
14052 if (packet_config_support (packet) == PACKET_ENABLE
14053 && conf->bts.size != rs->btrace_config.bts.size)
14054 {
14055 pos = buf;
14056 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
14057 conf->bts.size);
14058
14059 putpkt (buf);
14060 getpkt (&rs->buf, 0);
14061
14062 if (packet_ok (buf, packet) == PACKET_ERROR)
14063 {
14064 if (buf[0] == 'E' && buf[1] == '.')
14065 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14066 else
14067 error (_("Failed to configure the BTS buffer size."));
14068 }
14069
14070 rs->btrace_config.bts.size = conf->bts.size;
14071 }
14072
14073 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
14074 if (packet_config_support (packet) == PACKET_ENABLE
14075 && conf->pt.size != rs->btrace_config.pt.size)
14076 {
14077 pos = buf;
14078 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
14079 conf->pt.size);
14080
14081 putpkt (buf);
14082 getpkt (&rs->buf, 0);
14083
14084 if (packet_ok (buf, packet) == PACKET_ERROR)
14085 {
14086 if (buf[0] == 'E' && buf[1] == '.')
14087 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14088 else
14089 error (_("Failed to configure the trace buffer size."));
14090 }
14091
14092 rs->btrace_config.pt.size = conf->pt.size;
14093 }
14094 }
14095
14096 /* Read TP's btrace configuration from the target and store it into CONF. */
14097
14098 static void
14099 btrace_read_config (thread_info *tp, struct btrace_config *conf)
14100 {
14101 /* target_read_stralloc relies on INFERIOR_PTID. */
14102 scoped_restore_current_thread restore_thread;
14103 switch_to_thread (tp);
14104
14105 gdb::optional<gdb::char_vector> xml
14106 = target_read_stralloc (current_inferior ()->top_target (),
14107 TARGET_OBJECT_BTRACE_CONF, "");
14108 if (xml)
14109 parse_xml_btrace_conf (conf, xml->data ());
14110 }
14111
14112 /* Maybe reopen target btrace. */
14113
14114 void
14115 remote_target::remote_btrace_maybe_reopen ()
14116 {
14117 struct remote_state *rs = get_remote_state ();
14118 int btrace_target_pushed = 0;
14119 #if !defined (HAVE_LIBIPT)
14120 int warned = 0;
14121 #endif
14122
14123 /* Don't bother walking the entirety of the remote thread list when
14124 we know the feature isn't supported by the remote. */
14125 if (packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14126 return;
14127
14128 for (thread_info *tp : all_non_exited_threads (this))
14129 {
14130 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14131 btrace_read_config (tp, &rs->btrace_config);
14132
14133 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14134 continue;
14135
14136 #if !defined (HAVE_LIBIPT)
14137 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14138 {
14139 if (!warned)
14140 {
14141 warned = 1;
14142 warning (_("Target is recording using Intel Processor Trace "
14143 "but support was disabled at compile time."));
14144 }
14145
14146 continue;
14147 }
14148 #endif /* !defined (HAVE_LIBIPT) */
14149
14150 /* Push target, once, but before anything else happens. This way our
14151 changes to the threads will be cleaned up by unpushing the target
14152 in case btrace_read_config () throws. */
14153 if (!btrace_target_pushed)
14154 {
14155 btrace_target_pushed = 1;
14156 record_btrace_push_target ();
14157 gdb_printf (_("Target is recording using %s.\n"),
14158 btrace_format_string (rs->btrace_config.format));
14159 }
14160
14161 tp->btrace.target = XCNEW (struct btrace_target_info);
14162 tp->btrace.target->ptid = tp->ptid;
14163 tp->btrace.target->conf = rs->btrace_config;
14164 }
14165 }
14166
14167 /* Enable branch tracing. */
14168
14169 struct btrace_target_info *
14170 remote_target::enable_btrace (thread_info *tp,
14171 const struct btrace_config *conf)
14172 {
14173 struct btrace_target_info *tinfo = NULL;
14174 struct packet_config *packet = NULL;
14175 struct remote_state *rs = get_remote_state ();
14176 char *buf = rs->buf.data ();
14177 char *endbuf = buf + get_remote_packet_size ();
14178
14179 switch (conf->format)
14180 {
14181 case BTRACE_FORMAT_BTS:
14182 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
14183 break;
14184
14185 case BTRACE_FORMAT_PT:
14186 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
14187 break;
14188 }
14189
14190 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14191 error (_("Target does not support branch tracing."));
14192
14193 btrace_sync_conf (conf);
14194
14195 ptid_t ptid = tp->ptid;
14196 set_general_thread (ptid);
14197
14198 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14199 putpkt (rs->buf);
14200 getpkt (&rs->buf, 0);
14201
14202 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14203 {
14204 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14205 error (_("Could not enable branch tracing for %s: %s"),
14206 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14207 else
14208 error (_("Could not enable branch tracing for %s."),
14209 target_pid_to_str (ptid).c_str ());
14210 }
14211
14212 tinfo = XCNEW (struct btrace_target_info);
14213 tinfo->ptid = ptid;
14214
14215 /* If we fail to read the configuration, we lose some information, but the
14216 tracing itself is not impacted. */
14217 try
14218 {
14219 btrace_read_config (tp, &tinfo->conf);
14220 }
14221 catch (const gdb_exception_error &err)
14222 {
14223 if (err.message != NULL)
14224 warning ("%s", err.what ());
14225 }
14226
14227 return tinfo;
14228 }
14229
14230 /* Disable branch tracing. */
14231
14232 void
14233 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14234 {
14235 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
14236 struct remote_state *rs = get_remote_state ();
14237 char *buf = rs->buf.data ();
14238 char *endbuf = buf + get_remote_packet_size ();
14239
14240 if (packet_config_support (packet) != PACKET_ENABLE)
14241 error (_("Target does not support branch tracing."));
14242
14243 set_general_thread (tinfo->ptid);
14244
14245 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14246 putpkt (rs->buf);
14247 getpkt (&rs->buf, 0);
14248
14249 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14250 {
14251 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14252 error (_("Could not disable branch tracing for %s: %s"),
14253 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14254 else
14255 error (_("Could not disable branch tracing for %s."),
14256 target_pid_to_str (tinfo->ptid).c_str ());
14257 }
14258
14259 xfree (tinfo);
14260 }
14261
14262 /* Teardown branch tracing. */
14263
14264 void
14265 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14266 {
14267 /* We must not talk to the target during teardown. */
14268 xfree (tinfo);
14269 }
14270
14271 /* Read the branch trace. */
14272
14273 enum btrace_error
14274 remote_target::read_btrace (struct btrace_data *btrace,
14275 struct btrace_target_info *tinfo,
14276 enum btrace_read_type type)
14277 {
14278 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
14279 const char *annex;
14280
14281 if (packet_config_support (packet) != PACKET_ENABLE)
14282 error (_("Target does not support branch tracing."));
14283
14284 #if !defined(HAVE_LIBEXPAT)
14285 error (_("Cannot process branch tracing result. XML parsing not supported."));
14286 #endif
14287
14288 switch (type)
14289 {
14290 case BTRACE_READ_ALL:
14291 annex = "all";
14292 break;
14293 case BTRACE_READ_NEW:
14294 annex = "new";
14295 break;
14296 case BTRACE_READ_DELTA:
14297 annex = "delta";
14298 break;
14299 default:
14300 internal_error (__FILE__, __LINE__,
14301 _("Bad branch tracing read type: %u."),
14302 (unsigned int) type);
14303 }
14304
14305 gdb::optional<gdb::char_vector> xml
14306 = target_read_stralloc (current_inferior ()->top_target (),
14307 TARGET_OBJECT_BTRACE, annex);
14308 if (!xml)
14309 return BTRACE_ERR_UNKNOWN;
14310
14311 parse_xml_btrace (btrace, xml->data ());
14312
14313 return BTRACE_ERR_NONE;
14314 }
14315
14316 const struct btrace_config *
14317 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14318 {
14319 return &tinfo->conf;
14320 }
14321
14322 bool
14323 remote_target::augmented_libraries_svr4_read ()
14324 {
14325 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
14326 == PACKET_ENABLE);
14327 }
14328
14329 /* Implementation of to_load. */
14330
14331 void
14332 remote_target::load (const char *name, int from_tty)
14333 {
14334 generic_load (name, from_tty);
14335 }
14336
14337 /* Accepts an integer PID; returns a string representing a file that
14338 can be opened on the remote side to get the symbols for the child
14339 process. Returns NULL if the operation is not supported. */
14340
14341 char *
14342 remote_target::pid_to_exec_file (int pid)
14343 {
14344 static gdb::optional<gdb::char_vector> filename;
14345 char *annex = NULL;
14346
14347 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14348 return NULL;
14349
14350 inferior *inf = find_inferior_pid (this, pid);
14351 if (inf == NULL)
14352 internal_error (__FILE__, __LINE__,
14353 _("not currently attached to process %d"), pid);
14354
14355 if (!inf->fake_pid_p)
14356 {
14357 const int annex_size = 9;
14358
14359 annex = (char *) alloca (annex_size);
14360 xsnprintf (annex, annex_size, "%x", pid);
14361 }
14362
14363 filename = target_read_stralloc (current_inferior ()->top_target (),
14364 TARGET_OBJECT_EXEC_FILE, annex);
14365
14366 return filename ? filename->data () : nullptr;
14367 }
14368
14369 /* Implement the to_can_do_single_step target_ops method. */
14370
14371 int
14372 remote_target::can_do_single_step ()
14373 {
14374 /* We can only tell whether target supports single step or not by
14375 supported s and S vCont actions if the stub supports vContSupported
14376 feature. If the stub doesn't support vContSupported feature,
14377 we have conservatively to think target doesn't supports single
14378 step. */
14379 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14380 {
14381 struct remote_state *rs = get_remote_state ();
14382
14383 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14384 remote_vcont_probe ();
14385
14386 return rs->supports_vCont.s && rs->supports_vCont.S;
14387 }
14388 else
14389 return 0;
14390 }
14391
14392 /* Implementation of the to_execution_direction method for the remote
14393 target. */
14394
14395 enum exec_direction_kind
14396 remote_target::execution_direction ()
14397 {
14398 struct remote_state *rs = get_remote_state ();
14399
14400 return rs->last_resume_exec_dir;
14401 }
14402
14403 /* Return pointer to the thread_info struct which corresponds to
14404 THREAD_HANDLE (having length HANDLE_LEN). */
14405
14406 thread_info *
14407 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14408 int handle_len,
14409 inferior *inf)
14410 {
14411 for (thread_info *tp : all_non_exited_threads (this))
14412 {
14413 remote_thread_info *priv = get_remote_thread_info (tp);
14414
14415 if (tp->inf == inf && priv != NULL)
14416 {
14417 if (handle_len != priv->thread_handle.size ())
14418 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14419 handle_len, priv->thread_handle.size ());
14420 if (memcmp (thread_handle, priv->thread_handle.data (),
14421 handle_len) == 0)
14422 return tp;
14423 }
14424 }
14425
14426 return NULL;
14427 }
14428
14429 gdb::byte_vector
14430 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14431 {
14432 remote_thread_info *priv = get_remote_thread_info (tp);
14433 return priv->thread_handle;
14434 }
14435
14436 bool
14437 remote_target::can_async_p ()
14438 {
14439 /* This flag should be checked in the common target.c code. */
14440 gdb_assert (target_async_permitted);
14441
14442 /* We're async whenever the serial device can. */
14443 struct remote_state *rs = get_remote_state ();
14444 return serial_can_async_p (rs->remote_desc);
14445 }
14446
14447 bool
14448 remote_target::is_async_p ()
14449 {
14450 /* We're async whenever the serial device is. */
14451 struct remote_state *rs = get_remote_state ();
14452 return serial_is_async_p (rs->remote_desc);
14453 }
14454
14455 /* Pass the SERIAL event on and up to the client. One day this code
14456 will be able to delay notifying the client of an event until the
14457 point where an entire packet has been received. */
14458
14459 static serial_event_ftype remote_async_serial_handler;
14460
14461 static void
14462 remote_async_serial_handler (struct serial *scb, void *context)
14463 {
14464 /* Don't propogate error information up to the client. Instead let
14465 the client find out about the error by querying the target. */
14466 inferior_event_handler (INF_REG_EVENT);
14467 }
14468
14469 static void
14470 remote_async_inferior_event_handler (gdb_client_data data)
14471 {
14472 inferior_event_handler (INF_REG_EVENT);
14473 }
14474
14475 int
14476 remote_target::async_wait_fd ()
14477 {
14478 struct remote_state *rs = get_remote_state ();
14479 return rs->remote_desc->fd;
14480 }
14481
14482 void
14483 remote_target::async (int enable)
14484 {
14485 struct remote_state *rs = get_remote_state ();
14486
14487 if (enable)
14488 {
14489 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14490
14491 /* If there are pending events in the stop reply queue tell the
14492 event loop to process them. */
14493 if (!rs->stop_reply_queue.empty ())
14494 mark_async_event_handler (rs->remote_async_inferior_event_token);
14495 /* For simplicity, below we clear the pending events token
14496 without remembering whether it is marked, so here we always
14497 mark it. If there's actually no pending notification to
14498 process, this ends up being a no-op (other than a spurious
14499 event-loop wakeup). */
14500 if (target_is_non_stop_p ())
14501 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14502 }
14503 else
14504 {
14505 serial_async (rs->remote_desc, NULL, NULL);
14506 /* If the core is disabling async, it doesn't want to be
14507 disturbed with target events. Clear all async event sources
14508 too. */
14509 clear_async_event_handler (rs->remote_async_inferior_event_token);
14510 if (target_is_non_stop_p ())
14511 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14512 }
14513 }
14514
14515 /* Implementation of the to_thread_events method. */
14516
14517 void
14518 remote_target::thread_events (int enable)
14519 {
14520 struct remote_state *rs = get_remote_state ();
14521 size_t size = get_remote_packet_size ();
14522
14523 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14524 return;
14525
14526 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
14527 putpkt (rs->buf);
14528 getpkt (&rs->buf, 0);
14529
14530 switch (packet_ok (rs->buf,
14531 &remote_protocol_packets[PACKET_QThreadEvents]))
14532 {
14533 case PACKET_OK:
14534 if (strcmp (rs->buf.data (), "OK") != 0)
14535 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
14536 break;
14537 case PACKET_ERROR:
14538 warning (_("Remote failure reply: %s"), rs->buf.data ());
14539 break;
14540 case PACKET_UNKNOWN:
14541 break;
14542 }
14543 }
14544
14545 static void
14546 show_remote_cmd (const char *args, int from_tty)
14547 {
14548 /* We can't just use cmd_show_list here, because we want to skip
14549 the redundant "show remote Z-packet" and the legacy aliases. */
14550 struct cmd_list_element *list = remote_show_cmdlist;
14551 struct ui_out *uiout = current_uiout;
14552
14553 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14554 for (; list != NULL; list = list->next)
14555 if (strcmp (list->name, "Z-packet") == 0)
14556 continue;
14557 else if (list->type == not_set_cmd)
14558 /* Alias commands are exactly like the original, except they
14559 don't have the normal type. */
14560 continue;
14561 else
14562 {
14563 ui_out_emit_tuple option_emitter (uiout, "option");
14564
14565 uiout->field_string ("name", list->name);
14566 uiout->text (": ");
14567 if (list->type == show_cmd)
14568 do_show_command (NULL, from_tty, list);
14569 else
14570 cmd_func (list, NULL, from_tty);
14571 }
14572 }
14573
14574
14575 /* Function to be called whenever a new objfile (shlib) is detected. */
14576 static void
14577 remote_new_objfile (struct objfile *objfile)
14578 {
14579 remote_target *remote = get_current_remote_target ();
14580
14581 /* First, check whether the current inferior's process target is a remote
14582 target. */
14583 if (remote == nullptr)
14584 return;
14585
14586 /* When we are attaching or handling a fork child and the shared library
14587 subsystem reads the list of loaded libraries, we receive new objfile
14588 events in between each found library. The libraries are read in an
14589 undefined order, so if we gave the remote side a chance to look up
14590 symbols between each objfile, we might give it an inconsistent picture
14591 of the inferior. It could appear that a library A appears loaded but
14592 a library B does not, even though library A requires library B. That
14593 would present a state that couldn't normally exist in the inferior.
14594
14595 So, skip these events, we'll give the remote a chance to look up symbols
14596 once all the loaded libraries and their symbols are known to GDB. */
14597 if (current_inferior ()->in_initial_library_scan)
14598 return;
14599
14600 remote->remote_check_symbols ();
14601 }
14602
14603 /* Pull all the tracepoints defined on the target and create local
14604 data structures representing them. We don't want to create real
14605 tracepoints yet, we don't want to mess up the user's existing
14606 collection. */
14607
14608 int
14609 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14610 {
14611 struct remote_state *rs = get_remote_state ();
14612 char *p;
14613
14614 /* Ask for a first packet of tracepoint definition. */
14615 putpkt ("qTfP");
14616 getpkt (&rs->buf, 0);
14617 p = rs->buf.data ();
14618 while (*p && *p != 'l')
14619 {
14620 parse_tracepoint_definition (p, utpp);
14621 /* Ask for another packet of tracepoint definition. */
14622 putpkt ("qTsP");
14623 getpkt (&rs->buf, 0);
14624 p = rs->buf.data ();
14625 }
14626 return 0;
14627 }
14628
14629 int
14630 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14631 {
14632 struct remote_state *rs = get_remote_state ();
14633 char *p;
14634
14635 /* Ask for a first packet of variable definition. */
14636 putpkt ("qTfV");
14637 getpkt (&rs->buf, 0);
14638 p = rs->buf.data ();
14639 while (*p && *p != 'l')
14640 {
14641 parse_tsv_definition (p, utsvp);
14642 /* Ask for another packet of variable definition. */
14643 putpkt ("qTsV");
14644 getpkt (&rs->buf, 0);
14645 p = rs->buf.data ();
14646 }
14647 return 0;
14648 }
14649
14650 /* The "set/show range-stepping" show hook. */
14651
14652 static void
14653 show_range_stepping (struct ui_file *file, int from_tty,
14654 struct cmd_list_element *c,
14655 const char *value)
14656 {
14657 gdb_printf (file,
14658 _("Debugger's willingness to use range stepping "
14659 "is %s.\n"), value);
14660 }
14661
14662 /* Return true if the vCont;r action is supported by the remote
14663 stub. */
14664
14665 bool
14666 remote_target::vcont_r_supported ()
14667 {
14668 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14669 remote_vcont_probe ();
14670
14671 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14672 && get_remote_state ()->supports_vCont.r);
14673 }
14674
14675 /* The "set/show range-stepping" set hook. */
14676
14677 static void
14678 set_range_stepping (const char *ignore_args, int from_tty,
14679 struct cmd_list_element *c)
14680 {
14681 /* When enabling, check whether range stepping is actually supported
14682 by the target, and warn if not. */
14683 if (use_range_stepping)
14684 {
14685 remote_target *remote = get_current_remote_target ();
14686 if (remote == NULL
14687 || !remote->vcont_r_supported ())
14688 warning (_("Range stepping is not supported by the current target"));
14689 }
14690 }
14691
14692 static void
14693 show_remote_debug (struct ui_file *file, int from_tty,
14694 struct cmd_list_element *c, const char *value)
14695 {
14696 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
14697 value);
14698 }
14699
14700 static void
14701 show_remote_timeout (struct ui_file *file, int from_tty,
14702 struct cmd_list_element *c, const char *value)
14703 {
14704 gdb_printf (file,
14705 _("Timeout limit to wait for target to respond is %s.\n"),
14706 value);
14707 }
14708
14709 /* Implement the "supports_memory_tagging" target_ops method. */
14710
14711 bool
14712 remote_target::supports_memory_tagging ()
14713 {
14714 return remote_memory_tagging_p ();
14715 }
14716
14717 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
14718
14719 static void
14720 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14721 size_t len, int type)
14722 {
14723 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14724
14725 std::string request = string_printf ("qMemTags:%s,%s:%s",
14726 phex_nz (address, addr_size),
14727 phex_nz (len, sizeof (len)),
14728 phex_nz (type, sizeof (type)));
14729
14730 strcpy (packet.data (), request.c_str ());
14731 }
14732
14733 /* Parse the qMemTags packet reply into TAGS.
14734
14735 Return true if successful, false otherwise. */
14736
14737 static bool
14738 parse_fetch_memtags_reply (const gdb::char_vector &reply,
14739 gdb::byte_vector &tags)
14740 {
14741 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
14742 return false;
14743
14744 /* Copy the tag data. */
14745 tags = hex2bin (reply.data () + 1);
14746
14747 return true;
14748 }
14749
14750 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
14751
14752 static void
14753 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14754 size_t len, int type,
14755 const gdb::byte_vector &tags)
14756 {
14757 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14758
14759 /* Put together the main packet, address and length. */
14760 std::string request = string_printf ("QMemTags:%s,%s:%s:",
14761 phex_nz (address, addr_size),
14762 phex_nz (len, sizeof (len)),
14763 phex_nz (type, sizeof (type)));
14764 request += bin2hex (tags.data (), tags.size ());
14765
14766 /* Check if we have exceeded the maximum packet size. */
14767 if (packet.size () < request.length ())
14768 error (_("Contents too big for packet QMemTags."));
14769
14770 strcpy (packet.data (), request.c_str ());
14771 }
14772
14773 /* Implement the "fetch_memtags" target_ops method. */
14774
14775 bool
14776 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
14777 gdb::byte_vector &tags, int type)
14778 {
14779 /* Make sure the qMemTags packet is supported. */
14780 if (!remote_memory_tagging_p ())
14781 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
14782
14783 struct remote_state *rs = get_remote_state ();
14784
14785 create_fetch_memtags_request (rs->buf, address, len, type);
14786
14787 putpkt (rs->buf);
14788 getpkt (&rs->buf, 0);
14789
14790 return parse_fetch_memtags_reply (rs->buf, tags);
14791 }
14792
14793 /* Implement the "store_memtags" target_ops method. */
14794
14795 bool
14796 remote_target::store_memtags (CORE_ADDR address, size_t len,
14797 const gdb::byte_vector &tags, int type)
14798 {
14799 /* Make sure the QMemTags packet is supported. */
14800 if (!remote_memory_tagging_p ())
14801 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
14802
14803 struct remote_state *rs = get_remote_state ();
14804
14805 create_store_memtags_request (rs->buf, address, len, type, tags);
14806
14807 putpkt (rs->buf);
14808 getpkt (&rs->buf, 0);
14809
14810 /* Verify if the request was successful. */
14811 return packet_check_result (rs->buf.data ()) == PACKET_OK;
14812 }
14813
14814 /* Return true if remote target T is non-stop. */
14815
14816 bool
14817 remote_target_is_non_stop_p (remote_target *t)
14818 {
14819 scoped_restore_current_thread restore_thread;
14820 switch_to_target_no_thread (t);
14821
14822 return target_is_non_stop_p ();
14823 }
14824
14825 #if GDB_SELF_TEST
14826
14827 namespace selftests {
14828
14829 static void
14830 test_memory_tagging_functions ()
14831 {
14832 remote_target remote;
14833
14834 struct packet_config *config
14835 = &remote_protocol_packets[PACKET_memory_tagging_feature];
14836
14837 scoped_restore restore_memtag_support_
14838 = make_scoped_restore (&config->support);
14839
14840 /* Test memory tagging packet support. */
14841 config->support = PACKET_SUPPORT_UNKNOWN;
14842 SELF_CHECK (remote.supports_memory_tagging () == false);
14843 config->support = PACKET_DISABLE;
14844 SELF_CHECK (remote.supports_memory_tagging () == false);
14845 config->support = PACKET_ENABLE;
14846 SELF_CHECK (remote.supports_memory_tagging () == true);
14847
14848 /* Setup testing. */
14849 gdb::char_vector packet;
14850 gdb::byte_vector tags, bv;
14851 std::string expected, reply;
14852 packet.resize (32000);
14853
14854 /* Test creating a qMemTags request. */
14855
14856 expected = "qMemTags:0,0:0";
14857 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
14858 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14859
14860 expected = "qMemTags:deadbeef,10:1";
14861 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
14862 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14863
14864 /* Test parsing a qMemTags reply. */
14865
14866 /* Error reply, tags vector unmodified. */
14867 reply = "E00";
14868 strcpy (packet.data (), reply.c_str ());
14869 tags.resize (0);
14870 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
14871 SELF_CHECK (tags.size () == 0);
14872
14873 /* Valid reply, tags vector updated. */
14874 tags.resize (0);
14875 bv.resize (0);
14876
14877 for (int i = 0; i < 5; i++)
14878 bv.push_back (i);
14879
14880 reply = "m" + bin2hex (bv.data (), bv.size ());
14881 strcpy (packet.data (), reply.c_str ());
14882
14883 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
14884 SELF_CHECK (tags.size () == 5);
14885
14886 for (int i = 0; i < 5; i++)
14887 SELF_CHECK (tags[i] == i);
14888
14889 /* Test creating a QMemTags request. */
14890
14891 /* Empty tag data. */
14892 tags.resize (0);
14893 expected = "QMemTags:0,0:0:";
14894 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
14895 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14896 expected.length ()) == 0);
14897
14898 /* Non-empty tag data. */
14899 tags.resize (0);
14900 for (int i = 0; i < 5; i++)
14901 tags.push_back (i);
14902 expected = "QMemTags:deadbeef,ff:1:0001020304";
14903 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
14904 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14905 expected.length ()) == 0);
14906 }
14907
14908 } // namespace selftests
14909 #endif /* GDB_SELF_TEST */
14910
14911 void _initialize_remote ();
14912 void
14913 _initialize_remote ()
14914 {
14915 /* architecture specific data */
14916 remote_g_packet_data_handle =
14917 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14918
14919 add_target (remote_target_info, remote_target::open);
14920 add_target (extended_remote_target_info, extended_remote_target::open);
14921
14922 /* Hook into new objfile notification. */
14923 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
14924
14925 #if 0
14926 init_remote_threadtests ();
14927 #endif
14928
14929 /* set/show remote ... */
14930
14931 add_basic_prefix_cmd ("remote", class_maintenance, _("\
14932 Remote protocol specific variables.\n\
14933 Configure various remote-protocol specific variables such as\n\
14934 the packets being used."),
14935 &remote_set_cmdlist,
14936 0 /* allow-unknown */, &setlist);
14937 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14938 Remote protocol specific variables.\n\
14939 Configure various remote-protocol specific variables such as\n\
14940 the packets being used."),
14941 &remote_show_cmdlist,
14942 0 /* allow-unknown */, &showlist);
14943
14944 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14945 Compare section data on target to the exec file.\n\
14946 Argument is a single section name (default: all loaded sections).\n\
14947 To compare only read-only loaded sections, specify the -r option."),
14948 &cmdlist);
14949
14950 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
14951 Send an arbitrary packet to a remote target.\n\
14952 maintenance packet TEXT\n\
14953 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14954 this command sends the string TEXT to the inferior, and displays the\n\
14955 response packet. GDB supplies the initial `$' character, and the\n\
14956 terminating `#' character and checksum."),
14957 &maintenancelist);
14958
14959 set_show_commands remotebreak_cmds
14960 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14961 Set whether to send break if interrupted."), _("\
14962 Show whether to send break if interrupted."), _("\
14963 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14964 set_remotebreak, show_remotebreak,
14965 &setlist, &showlist);
14966 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
14967 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
14968
14969 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14970 interrupt_sequence_modes, &interrupt_sequence_mode,
14971 _("\
14972 Set interrupt sequence to remote target."), _("\
14973 Show interrupt sequence to remote target."), _("\
14974 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14975 NULL, show_interrupt_sequence,
14976 &remote_set_cmdlist,
14977 &remote_show_cmdlist);
14978
14979 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14980 &interrupt_on_connect, _("\
14981 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
14982 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
14983 If set, interrupt sequence is sent to remote target."),
14984 NULL, NULL,
14985 &remote_set_cmdlist, &remote_show_cmdlist);
14986
14987 /* Install commands for configuring memory read/write packets. */
14988
14989 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14990 Set the maximum number of bytes per memory write packet (deprecated)."),
14991 &setlist);
14992 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14993 Show the maximum number of bytes per memory write packet (deprecated)."),
14994 &showlist);
14995 add_cmd ("memory-write-packet-size", no_class,
14996 set_memory_write_packet_size, _("\
14997 Set the maximum number of bytes per memory-write packet.\n\
14998 Specify the number of bytes in a packet or 0 (zero) for the\n\
14999 default packet size. The actual limit is further reduced\n\
15000 dependent on the target. Specify ``fixed'' to disable the\n\
15001 further restriction and ``limit'' to enable that restriction."),
15002 &remote_set_cmdlist);
15003 add_cmd ("memory-read-packet-size", no_class,
15004 set_memory_read_packet_size, _("\
15005 Set the maximum number of bytes per memory-read packet.\n\
15006 Specify the number of bytes in a packet or 0 (zero) for the\n\
15007 default packet size. The actual limit is further reduced\n\
15008 dependent on the target. Specify ``fixed'' to disable the\n\
15009 further restriction and ``limit'' to enable that restriction."),
15010 &remote_set_cmdlist);
15011 add_cmd ("memory-write-packet-size", no_class,
15012 show_memory_write_packet_size,
15013 _("Show the maximum number of bytes per memory-write packet."),
15014 &remote_show_cmdlist);
15015 add_cmd ("memory-read-packet-size", no_class,
15016 show_memory_read_packet_size,
15017 _("Show the maximum number of bytes per memory-read packet."),
15018 &remote_show_cmdlist);
15019
15020 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
15021 &remote_hw_watchpoint_limit, _("\
15022 Set the maximum number of target hardware watchpoints."), _("\
15023 Show the maximum number of target hardware watchpoints."), _("\
15024 Specify \"unlimited\" for unlimited hardware watchpoints."),
15025 NULL, show_hardware_watchpoint_limit,
15026 &remote_set_cmdlist,
15027 &remote_show_cmdlist);
15028 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15029 no_class,
15030 &remote_hw_watchpoint_length_limit, _("\
15031 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15032 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15033 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15034 NULL, show_hardware_watchpoint_length_limit,
15035 &remote_set_cmdlist, &remote_show_cmdlist);
15036 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
15037 &remote_hw_breakpoint_limit, _("\
15038 Set the maximum number of target hardware breakpoints."), _("\
15039 Show the maximum number of target hardware breakpoints."), _("\
15040 Specify \"unlimited\" for unlimited hardware breakpoints."),
15041 NULL, show_hardware_breakpoint_limit,
15042 &remote_set_cmdlist, &remote_show_cmdlist);
15043
15044 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15045 &remote_address_size, _("\
15046 Set the maximum size of the address (in bits) in a memory packet."), _("\
15047 Show the maximum size of the address (in bits) in a memory packet."), NULL,
15048 NULL,
15049 NULL, /* FIXME: i18n: */
15050 &setlist, &showlist);
15051
15052 init_all_packet_configs ();
15053
15054 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
15055 "X", "binary-download", 1);
15056
15057 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
15058 "vCont", "verbose-resume", 0);
15059
15060 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
15061 "QPassSignals", "pass-signals", 0);
15062
15063 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
15064 "QCatchSyscalls", "catch-syscalls", 0);
15065
15066 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
15067 "QProgramSignals", "program-signals", 0);
15068
15069 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
15070 "QSetWorkingDir", "set-working-dir", 0);
15071
15072 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
15073 "QStartupWithShell", "startup-with-shell", 0);
15074
15075 add_packet_config_cmd (&remote_protocol_packets
15076 [PACKET_QEnvironmentHexEncoded],
15077 "QEnvironmentHexEncoded", "environment-hex-encoded",
15078 0);
15079
15080 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
15081 "QEnvironmentReset", "environment-reset",
15082 0);
15083
15084 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
15085 "QEnvironmentUnset", "environment-unset",
15086 0);
15087
15088 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
15089 "qSymbol", "symbol-lookup", 0);
15090
15091 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
15092 "P", "set-register", 1);
15093
15094 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
15095 "p", "fetch-register", 1);
15096
15097 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
15098 "Z0", "software-breakpoint", 0);
15099
15100 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
15101 "Z1", "hardware-breakpoint", 0);
15102
15103 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
15104 "Z2", "write-watchpoint", 0);
15105
15106 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
15107 "Z3", "read-watchpoint", 0);
15108
15109 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
15110 "Z4", "access-watchpoint", 0);
15111
15112 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
15113 "qXfer:auxv:read", "read-aux-vector", 0);
15114
15115 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
15116 "qXfer:exec-file:read", "pid-to-exec-file", 0);
15117
15118 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
15119 "qXfer:features:read", "target-features", 0);
15120
15121 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
15122 "qXfer:libraries:read", "library-info", 0);
15123
15124 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
15125 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15126
15127 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
15128 "qXfer:memory-map:read", "memory-map", 0);
15129
15130 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
15131 "qXfer:osdata:read", "osdata", 0);
15132
15133 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
15134 "qXfer:threads:read", "threads", 0);
15135
15136 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
15137 "qXfer:siginfo:read", "read-siginfo-object", 0);
15138
15139 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
15140 "qXfer:siginfo:write", "write-siginfo-object", 0);
15141
15142 add_packet_config_cmd
15143 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
15144 "qXfer:traceframe-info:read", "traceframe-info", 0);
15145
15146 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
15147 "qXfer:uib:read", "unwind-info-block", 0);
15148
15149 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
15150 "qGetTLSAddr", "get-thread-local-storage-address",
15151 0);
15152
15153 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
15154 "qGetTIBAddr", "get-thread-information-block-address",
15155 0);
15156
15157 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
15158 "bc", "reverse-continue", 0);
15159
15160 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
15161 "bs", "reverse-step", 0);
15162
15163 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
15164 "qSupported", "supported-packets", 0);
15165
15166 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
15167 "qSearch:memory", "search-memory", 0);
15168
15169 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
15170 "qTStatus", "trace-status", 0);
15171
15172 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
15173 "vFile:setfs", "hostio-setfs", 0);
15174
15175 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
15176 "vFile:open", "hostio-open", 0);
15177
15178 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
15179 "vFile:pread", "hostio-pread", 0);
15180
15181 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
15182 "vFile:pwrite", "hostio-pwrite", 0);
15183
15184 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
15185 "vFile:close", "hostio-close", 0);
15186
15187 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
15188 "vFile:unlink", "hostio-unlink", 0);
15189
15190 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
15191 "vFile:readlink", "hostio-readlink", 0);
15192
15193 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
15194 "vFile:fstat", "hostio-fstat", 0);
15195
15196 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
15197 "vAttach", "attach", 0);
15198
15199 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
15200 "vRun", "run", 0);
15201
15202 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
15203 "QStartNoAckMode", "noack", 0);
15204
15205 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
15206 "vKill", "kill", 0);
15207
15208 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
15209 "qAttached", "query-attached", 0);
15210
15211 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
15212 "ConditionalTracepoints",
15213 "conditional-tracepoints", 0);
15214
15215 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
15216 "ConditionalBreakpoints",
15217 "conditional-breakpoints", 0);
15218
15219 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
15220 "BreakpointCommands",
15221 "breakpoint-commands", 0);
15222
15223 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
15224 "FastTracepoints", "fast-tracepoints", 0);
15225
15226 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
15227 "TracepointSource", "TracepointSource", 0);
15228
15229 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
15230 "QAllow", "allow", 0);
15231
15232 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
15233 "StaticTracepoints", "static-tracepoints", 0);
15234
15235 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
15236 "InstallInTrace", "install-in-trace", 0);
15237
15238 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
15239 "qXfer:statictrace:read", "read-sdata-object", 0);
15240
15241 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
15242 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
15243
15244 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
15245 "QDisableRandomization", "disable-randomization", 0);
15246
15247 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
15248 "QAgent", "agent", 0);
15249
15250 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
15251 "QTBuffer:size", "trace-buffer-size", 0);
15252
15253 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
15254 "Qbtrace:off", "disable-btrace", 0);
15255
15256 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
15257 "Qbtrace:bts", "enable-btrace-bts", 0);
15258
15259 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
15260 "Qbtrace:pt", "enable-btrace-pt", 0);
15261
15262 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
15263 "qXfer:btrace", "read-btrace", 0);
15264
15265 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
15266 "qXfer:btrace-conf", "read-btrace-conf", 0);
15267
15268 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
15269 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
15270
15271 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
15272 "multiprocess-feature", "multiprocess-feature", 0);
15273
15274 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
15275 "swbreak-feature", "swbreak-feature", 0);
15276
15277 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
15278 "hwbreak-feature", "hwbreak-feature", 0);
15279
15280 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
15281 "fork-event-feature", "fork-event-feature", 0);
15282
15283 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
15284 "vfork-event-feature", "vfork-event-feature", 0);
15285
15286 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
15287 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
15288
15289 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
15290 "vContSupported", "verbose-resume-supported", 0);
15291
15292 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
15293 "exec-event-feature", "exec-event-feature", 0);
15294
15295 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
15296 "vCtrlC", "ctrl-c", 0);
15297
15298 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
15299 "QThreadEvents", "thread-events", 0);
15300
15301 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
15302 "N stop reply", "no-resumed-stop-reply", 0);
15303
15304 add_packet_config_cmd (&remote_protocol_packets[PACKET_memory_tagging_feature],
15305 "memory-tagging-feature", "memory-tagging-feature", 0);
15306
15307 /* Assert that we've registered "set remote foo-packet" commands
15308 for all packet configs. */
15309 {
15310 int i;
15311
15312 for (i = 0; i < PACKET_MAX; i++)
15313 {
15314 /* Ideally all configs would have a command associated. Some
15315 still don't though. */
15316 int excepted;
15317
15318 switch (i)
15319 {
15320 case PACKET_QNonStop:
15321 case PACKET_EnableDisableTracepoints_feature:
15322 case PACKET_tracenz_feature:
15323 case PACKET_DisconnectedTracing_feature:
15324 case PACKET_augmented_libraries_svr4_read_feature:
15325 case PACKET_qCRC:
15326 /* Additions to this list need to be well justified:
15327 pre-existing packets are OK; new packets are not. */
15328 excepted = 1;
15329 break;
15330 default:
15331 excepted = 0;
15332 break;
15333 }
15334
15335 /* This catches both forgetting to add a config command, and
15336 forgetting to remove a packet from the exception list. */
15337 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
15338 }
15339 }
15340
15341 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15342 Z sub-packet has its own set and show commands, but users may
15343 have sets to this variable in their .gdbinit files (or in their
15344 documentation). */
15345 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
15346 &remote_Z_packet_detect, _("\
15347 Set use of remote protocol `Z' packets."), _("\
15348 Show use of remote protocol `Z' packets."), _("\
15349 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
15350 packets."),
15351 set_remote_protocol_Z_packet_cmd,
15352 show_remote_protocol_Z_packet_cmd,
15353 /* FIXME: i18n: Use of remote protocol
15354 `Z' packets is %s. */
15355 &remote_set_cmdlist, &remote_show_cmdlist);
15356
15357 add_basic_prefix_cmd ("remote", class_files, _("\
15358 Manipulate files on the remote system.\n\
15359 Transfer files to and from the remote target system."),
15360 &remote_cmdlist,
15361 0 /* allow-unknown */, &cmdlist);
15362
15363 add_cmd ("put", class_files, remote_put_command,
15364 _("Copy a local file to the remote system."),
15365 &remote_cmdlist);
15366
15367 add_cmd ("get", class_files, remote_get_command,
15368 _("Copy a remote file to the local system."),
15369 &remote_cmdlist);
15370
15371 add_cmd ("delete", class_files, remote_delete_command,
15372 _("Delete a remote file."),
15373 &remote_cmdlist);
15374
15375 add_setshow_string_noescape_cmd ("exec-file", class_files,
15376 &remote_exec_file_var, _("\
15377 Set the remote pathname for \"run\"."), _("\
15378 Show the remote pathname for \"run\"."), NULL,
15379 set_remote_exec_file,
15380 show_remote_exec_file,
15381 &remote_set_cmdlist,
15382 &remote_show_cmdlist);
15383
15384 add_setshow_boolean_cmd ("range-stepping", class_run,
15385 &use_range_stepping, _("\
15386 Enable or disable range stepping."), _("\
15387 Show whether target-assisted range stepping is enabled."), _("\
15388 If on, and the target supports it, when stepping a source line, GDB\n\
15389 tells the target to step the corresponding range of addresses itself instead\n\
15390 of issuing multiple single-steps. This speeds up source level\n\
15391 stepping. If off, GDB always issues single-steps, even if range\n\
15392 stepping is supported by the target. The default is on."),
15393 set_range_stepping,
15394 show_range_stepping,
15395 &setlist,
15396 &showlist);
15397
15398 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15399 Set watchdog timer."), _("\
15400 Show watchdog timer."), _("\
15401 When non-zero, this timeout is used instead of waiting forever for a target\n\
15402 to finish a low-level step or continue operation. If the specified amount\n\
15403 of time passes without a response from the target, an error occurs."),
15404 NULL,
15405 show_watchdog,
15406 &setlist, &showlist);
15407
15408 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15409 &remote_packet_max_chars, _("\
15410 Set the maximum number of characters to display for each remote packet."), _("\
15411 Show the maximum number of characters to display for each remote packet."), _("\
15412 Specify \"unlimited\" to display all the characters."),
15413 NULL, show_remote_packet_max_chars,
15414 &setdebuglist, &showdebuglist);
15415
15416 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15417 _("Set debugging of remote protocol."),
15418 _("Show debugging of remote protocol."),
15419 _("\
15420 When enabled, each packet sent or received with the remote target\n\
15421 is displayed."),
15422 NULL,
15423 show_remote_debug,
15424 &setdebuglist, &showdebuglist);
15425
15426 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15427 &remote_timeout, _("\
15428 Set timeout limit to wait for target to respond."), _("\
15429 Show timeout limit to wait for target to respond."), _("\
15430 This value is used to set the time limit for gdb to wait for a response\n\
15431 from the target."),
15432 NULL,
15433 show_remote_timeout,
15434 &setlist, &showlist);
15435
15436 /* Eventually initialize fileio. See fileio.c */
15437 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
15438
15439 #if GDB_SELF_TEST
15440 selftests::register_test ("remote_memory_tagging",
15441 selftests::test_memory_tagging_functions);
15442 #endif
15443 }