]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/remote.c
5118ecd0a31254cf551f01292651284bfe42e1d9
[thirdparty/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 "gdbsupport/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 const 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 (bool) 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 fileio_error *target_errno) override;
564
565 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
566 ULONGEST offset, fileio_error *target_errno) override;
567
568 int fileio_pread (int fd, gdb_byte *read_buf, int len,
569 ULONGEST offset, fileio_error *target_errno) override;
570
571 int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
572
573 int fileio_close (int fd, fileio_error *target_errno) override;
574
575 int fileio_unlink (struct inferior *inf,
576 const char *filename,
577 fileio_error *target_errno) override;
578
579 gdb::optional<std::string>
580 fileio_readlink (struct inferior *inf,
581 const char *filename,
582 fileio_error *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, fileio_error *remote_errno);
705 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
706 ULONGEST offset, fileio_error *remote_errno);
707 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
708 ULONGEST offset, fileio_error *remote_errno);
709
710 int remote_hostio_send_command (int command_bytes, int which_packet,
711 fileio_error *remote_errno, const char **attachment,
712 int *attachment_len);
713 int remote_hostio_set_filesystem (struct inferior *inf,
714 fileio_error *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 fileio_error *remote_errno);
719 int remote_hostio_close (int fd, fileio_error *remote_errno);
720
721 int remote_hostio_unlink (inferior *inf, const char *filename,
722 fileio_error *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 scope_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 /* Return TARGET as a remote_target if it is one, else nullptr. */
1020
1021 static remote_target *
1022 as_remote_target (process_stratum_target *target)
1023 {
1024 return dynamic_cast<remote_target *> (target);
1025 }
1026
1027 /* See remote.h. */
1028
1029 bool
1030 is_remote_target (process_stratum_target *target)
1031 {
1032 return as_remote_target (target) != nullptr;
1033 }
1034
1035 /* Per-program-space data key. */
1036 static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
1037 remote_pspace_data;
1038
1039 /* The variable registered as the control variable used by the
1040 remote exec-file commands. While the remote exec-file setting is
1041 per-program-space, the set/show machinery uses this as the
1042 location of the remote exec-file value. */
1043 static std::string remote_exec_file_var;
1044
1045 /* The size to align memory write packets, when practical. The protocol
1046 does not guarantee any alignment, and gdb will generate short
1047 writes and unaligned writes, but even as a best-effort attempt this
1048 can improve bulk transfers. For instance, if a write is misaligned
1049 relative to the target's data bus, the stub may need to make an extra
1050 round trip fetching data from the target. This doesn't make a
1051 huge difference, but it's easy to do, so we try to be helpful.
1052
1053 The alignment chosen is arbitrary; usually data bus width is
1054 important here, not the possibly larger cache line size. */
1055 enum { REMOTE_ALIGN_WRITES = 16 };
1056
1057 /* Prototypes for local functions. */
1058
1059 static int hexnumlen (ULONGEST num);
1060
1061 static int stubhex (int ch);
1062
1063 static int hexnumstr (char *, ULONGEST);
1064
1065 static int hexnumnstr (char *, ULONGEST, int);
1066
1067 static CORE_ADDR remote_address_masked (CORE_ADDR);
1068
1069 static int stub_unpack_int (const char *buff, int fieldlength);
1070
1071 struct packet_config;
1072
1073 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1074 int from_tty,
1075 struct cmd_list_element *c,
1076 const char *value);
1077
1078 static ptid_t read_ptid (const char *buf, const char **obuf);
1079
1080 static void remote_async_inferior_event_handler (gdb_client_data);
1081
1082 static bool remote_read_description_p (struct target_ops *target);
1083
1084 static void remote_console_output (const char *msg);
1085
1086 static void remote_btrace_reset (remote_state *rs);
1087
1088 static void remote_unpush_and_throw (remote_target *target);
1089
1090 /* For "remote". */
1091
1092 static struct cmd_list_element *remote_cmdlist;
1093
1094 /* For "set remote" and "show remote". */
1095
1096 static struct cmd_list_element *remote_set_cmdlist;
1097 static struct cmd_list_element *remote_show_cmdlist;
1098
1099 /* Controls whether GDB is willing to use range stepping. */
1100
1101 static bool use_range_stepping = true;
1102
1103 /* From the remote target's point of view, each thread is in one of these three
1104 states. */
1105 enum class resume_state
1106 {
1107 /* Not resumed - we haven't been asked to resume this thread. */
1108 NOT_RESUMED,
1109
1110 /* We have been asked to resume this thread, but haven't sent a vCont action
1111 for it yet. We'll need to consider it next time commit_resume is
1112 called. */
1113 RESUMED_PENDING_VCONT,
1114
1115 /* We have been asked to resume this thread, and we have sent a vCont action
1116 for it. */
1117 RESUMED,
1118 };
1119
1120 /* Information about a thread's pending vCont-resume. Used when a thread is in
1121 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1122 stores this information which is then picked up by
1123 remote_target::commit_resume to know which is the proper action for this
1124 thread to include in the vCont packet. */
1125 struct resumed_pending_vcont_info
1126 {
1127 /* True if the last resume call for this thread was a step request, false
1128 if a continue request. */
1129 bool step;
1130
1131 /* The signal specified in the last resume call for this thread. */
1132 gdb_signal sig;
1133 };
1134
1135 /* Private data that we'll store in (struct thread_info)->priv. */
1136 struct remote_thread_info : public private_thread_info
1137 {
1138 std::string extra;
1139 std::string name;
1140 int core = -1;
1141
1142 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1143 sequence of bytes. */
1144 gdb::byte_vector thread_handle;
1145
1146 /* Whether the target stopped for a breakpoint/watchpoint. */
1147 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1148
1149 /* This is set to the data address of the access causing the target
1150 to stop for a watchpoint. */
1151 CORE_ADDR watch_data_address = 0;
1152
1153 /* Get the thread's resume state. */
1154 enum resume_state get_resume_state () const
1155 {
1156 return m_resume_state;
1157 }
1158
1159 /* Put the thread in the NOT_RESUMED state. */
1160 void set_not_resumed ()
1161 {
1162 m_resume_state = resume_state::NOT_RESUMED;
1163 }
1164
1165 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1166 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1167 {
1168 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1169 m_resumed_pending_vcont_info.step = step;
1170 m_resumed_pending_vcont_info.sig = sig;
1171 }
1172
1173 /* Get the information this thread's pending vCont-resumption.
1174
1175 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1176 state. */
1177 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1178 {
1179 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1180
1181 return m_resumed_pending_vcont_info;
1182 }
1183
1184 /* Put the thread in the VCONT_RESUMED state. */
1185 void set_resumed ()
1186 {
1187 m_resume_state = resume_state::RESUMED;
1188 }
1189
1190 private:
1191 /* Resume state for this thread. This is used to implement vCont action
1192 coalescing (only when the target operates in non-stop mode).
1193
1194 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1195 which notes that this thread must be considered in the next commit_resume
1196 call.
1197
1198 remote_target::commit_resume sends a vCont packet with actions for the
1199 threads in the RESUMED_PENDING_VCONT state and moves them to the
1200 VCONT_RESUMED state.
1201
1202 When reporting a stop to the core for a thread, that thread is moved back
1203 to the NOT_RESUMED state. */
1204 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1205
1206 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1207 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1208 };
1209
1210 remote_state::remote_state ()
1211 : buf (400)
1212 {
1213 }
1214
1215 remote_state::~remote_state ()
1216 {
1217 xfree (this->last_pass_packet);
1218 xfree (this->last_program_signals_packet);
1219 xfree (this->finished_object);
1220 xfree (this->finished_annex);
1221 }
1222
1223 /* Utility: generate error from an incoming stub packet. */
1224 static void
1225 trace_error (char *buf)
1226 {
1227 if (*buf++ != 'E')
1228 return; /* not an error msg */
1229 switch (*buf)
1230 {
1231 case '1': /* malformed packet error */
1232 if (*++buf == '0') /* general case: */
1233 error (_("remote.c: error in outgoing packet."));
1234 else
1235 error (_("remote.c: error in outgoing packet at field #%ld."),
1236 strtol (buf, NULL, 16));
1237 default:
1238 error (_("Target returns error code '%s'."), buf);
1239 }
1240 }
1241
1242 /* Utility: wait for reply from stub, while accepting "O" packets. */
1243
1244 char *
1245 remote_target::remote_get_noisy_reply ()
1246 {
1247 struct remote_state *rs = get_remote_state ();
1248
1249 do /* Loop on reply from remote stub. */
1250 {
1251 char *buf;
1252
1253 QUIT; /* Allow user to bail out with ^C. */
1254 getpkt (&rs->buf, 0);
1255 buf = rs->buf.data ();
1256 if (buf[0] == 'E')
1257 trace_error (buf);
1258 else if (startswith (buf, "qRelocInsn:"))
1259 {
1260 ULONGEST ul;
1261 CORE_ADDR from, to, org_to;
1262 const char *p, *pp;
1263 int adjusted_size = 0;
1264 int relocated = 0;
1265
1266 p = buf + strlen ("qRelocInsn:");
1267 pp = unpack_varlen_hex (p, &ul);
1268 if (*pp != ';')
1269 error (_("invalid qRelocInsn packet: %s"), buf);
1270 from = ul;
1271
1272 p = pp + 1;
1273 unpack_varlen_hex (p, &ul);
1274 to = ul;
1275
1276 org_to = to;
1277
1278 try
1279 {
1280 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
1281 relocated = 1;
1282 }
1283 catch (const gdb_exception &ex)
1284 {
1285 if (ex.error == MEMORY_ERROR)
1286 {
1287 /* Propagate memory errors silently back to the
1288 target. The stub may have limited the range of
1289 addresses we can write to, for example. */
1290 }
1291 else
1292 {
1293 /* Something unexpectedly bad happened. Be verbose
1294 so we can tell what, and propagate the error back
1295 to the stub, so it doesn't get stuck waiting for
1296 a response. */
1297 exception_fprintf (gdb_stderr, ex,
1298 _("warning: relocating instruction: "));
1299 }
1300 putpkt ("E01");
1301 }
1302
1303 if (relocated)
1304 {
1305 adjusted_size = to - org_to;
1306
1307 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1308 putpkt (buf);
1309 }
1310 }
1311 else if (buf[0] == 'O' && buf[1] != 'K')
1312 remote_console_output (buf + 1); /* 'O' message from stub */
1313 else
1314 return buf; /* Here's the actual reply. */
1315 }
1316 while (1);
1317 }
1318
1319 struct remote_arch_state *
1320 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1321 {
1322 remote_arch_state *rsa;
1323
1324 auto it = this->m_arch_states.find (gdbarch);
1325 if (it == this->m_arch_states.end ())
1326 {
1327 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1328 std::forward_as_tuple (gdbarch),
1329 std::forward_as_tuple (gdbarch));
1330 rsa = &p.first->second;
1331
1332 /* Make sure that the packet buffer is plenty big enough for
1333 this architecture. */
1334 if (this->buf.size () < rsa->remote_packet_size)
1335 this->buf.resize (2 * rsa->remote_packet_size);
1336 }
1337 else
1338 rsa = &it->second;
1339
1340 return rsa;
1341 }
1342
1343 /* Fetch the global remote target state. */
1344
1345 remote_state *
1346 remote_target::get_remote_state ()
1347 {
1348 /* Make sure that the remote architecture state has been
1349 initialized, because doing so might reallocate rs->buf. Any
1350 function which calls getpkt also needs to be mindful of changes
1351 to rs->buf, but this call limits the number of places which run
1352 into trouble. */
1353 m_remote_state.get_remote_arch_state (target_gdbarch ());
1354
1355 return &m_remote_state;
1356 }
1357
1358 /* Fetch the remote exec-file from the current program space. */
1359
1360 static const char *
1361 get_remote_exec_file (void)
1362 {
1363 char *remote_exec_file;
1364
1365 remote_exec_file = remote_pspace_data.get (current_program_space);
1366 if (remote_exec_file == NULL)
1367 return "";
1368
1369 return remote_exec_file;
1370 }
1371
1372 /* Set the remote exec file for PSPACE. */
1373
1374 static void
1375 set_pspace_remote_exec_file (struct program_space *pspace,
1376 const char *remote_exec_file)
1377 {
1378 char *old_file = remote_pspace_data.get (pspace);
1379
1380 xfree (old_file);
1381 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1382 }
1383
1384 /* The "set/show remote exec-file" set command hook. */
1385
1386 static void
1387 set_remote_exec_file (const char *ignored, int from_tty,
1388 struct cmd_list_element *c)
1389 {
1390 set_pspace_remote_exec_file (current_program_space,
1391 remote_exec_file_var.c_str ());
1392 }
1393
1394 /* The "set/show remote exec-file" show command hook. */
1395
1396 static void
1397 show_remote_exec_file (struct ui_file *file, int from_tty,
1398 struct cmd_list_element *cmd, const char *value)
1399 {
1400 gdb_printf (file, "%s\n", get_remote_exec_file ());
1401 }
1402
1403 static int
1404 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1405 {
1406 int regnum, num_remote_regs, offset;
1407 struct packet_reg **remote_regs;
1408
1409 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1410 {
1411 struct packet_reg *r = &regs[regnum];
1412
1413 if (register_size (gdbarch, regnum) == 0)
1414 /* Do not try to fetch zero-sized (placeholder) registers. */
1415 r->pnum = -1;
1416 else
1417 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1418
1419 r->regnum = regnum;
1420 }
1421
1422 /* Define the g/G packet format as the contents of each register
1423 with a remote protocol number, in order of ascending protocol
1424 number. */
1425
1426 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1427 for (num_remote_regs = 0, regnum = 0;
1428 regnum < gdbarch_num_regs (gdbarch);
1429 regnum++)
1430 if (regs[regnum].pnum != -1)
1431 remote_regs[num_remote_regs++] = &regs[regnum];
1432
1433 std::sort (remote_regs, remote_regs + num_remote_regs,
1434 [] (const packet_reg *a, const packet_reg *b)
1435 { return a->pnum < b->pnum; });
1436
1437 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1438 {
1439 remote_regs[regnum]->in_g_packet = 1;
1440 remote_regs[regnum]->offset = offset;
1441 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1442 }
1443
1444 return offset;
1445 }
1446
1447 /* Given the architecture described by GDBARCH, return the remote
1448 protocol register's number and the register's offset in the g/G
1449 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1450 If the target does not have a mapping for REGNUM, return false,
1451 otherwise, return true. */
1452
1453 int
1454 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1455 int *pnum, int *poffset)
1456 {
1457 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1458
1459 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1460
1461 map_regcache_remote_table (gdbarch, regs.data ());
1462
1463 *pnum = regs[regnum].pnum;
1464 *poffset = regs[regnum].offset;
1465
1466 return *pnum != -1;
1467 }
1468
1469 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1470 {
1471 /* Use the architecture to build a regnum<->pnum table, which will be
1472 1:1 unless a feature set specifies otherwise. */
1473 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1474
1475 /* Record the maximum possible size of the g packet - it may turn out
1476 to be smaller. */
1477 this->sizeof_g_packet
1478 = map_regcache_remote_table (gdbarch, this->regs.get ());
1479
1480 /* Default maximum number of characters in a packet body. Many
1481 remote stubs have a hardwired buffer size of 400 bytes
1482 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1483 as the maximum packet-size to ensure that the packet and an extra
1484 NUL character can always fit in the buffer. This stops GDB
1485 trashing stubs that try to squeeze an extra NUL into what is
1486 already a full buffer (As of 1999-12-04 that was most stubs). */
1487 this->remote_packet_size = 400 - 1;
1488
1489 /* This one is filled in when a ``g'' packet is received. */
1490 this->actual_register_packet_size = 0;
1491
1492 /* Should rsa->sizeof_g_packet needs more space than the
1493 default, adjust the size accordingly. Remember that each byte is
1494 encoded as two characters. 32 is the overhead for the packet
1495 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1496 (``$NN:G...#NN'') is a better guess, the below has been padded a
1497 little. */
1498 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1499 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1500 }
1501
1502 /* Get a pointer to the current remote target. If not connected to a
1503 remote target, return NULL. */
1504
1505 static remote_target *
1506 get_current_remote_target ()
1507 {
1508 target_ops *proc_target = current_inferior ()->process_target ();
1509 return dynamic_cast<remote_target *> (proc_target);
1510 }
1511
1512 /* Return the current allowed size of a remote packet. This is
1513 inferred from the current architecture, and should be used to
1514 limit the length of outgoing packets. */
1515 long
1516 remote_target::get_remote_packet_size ()
1517 {
1518 struct remote_state *rs = get_remote_state ();
1519 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1520
1521 if (rs->explicit_packet_size)
1522 return rs->explicit_packet_size;
1523
1524 return rsa->remote_packet_size;
1525 }
1526
1527 static struct packet_reg *
1528 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1529 long regnum)
1530 {
1531 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1532 return NULL;
1533 else
1534 {
1535 struct packet_reg *r = &rsa->regs[regnum];
1536
1537 gdb_assert (r->regnum == regnum);
1538 return r;
1539 }
1540 }
1541
1542 static struct packet_reg *
1543 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1544 LONGEST pnum)
1545 {
1546 int i;
1547
1548 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1549 {
1550 struct packet_reg *r = &rsa->regs[i];
1551
1552 if (r->pnum == pnum)
1553 return r;
1554 }
1555 return NULL;
1556 }
1557
1558 /* Allow the user to specify what sequence to send to the remote
1559 when he requests a program interruption: Although ^C is usually
1560 what remote systems expect (this is the default, here), it is
1561 sometimes preferable to send a break. On other systems such
1562 as the Linux kernel, a break followed by g, which is Magic SysRq g
1563 is required in order to interrupt the execution. */
1564 const char interrupt_sequence_control_c[] = "Ctrl-C";
1565 const char interrupt_sequence_break[] = "BREAK";
1566 const char interrupt_sequence_break_g[] = "BREAK-g";
1567 static const char *const interrupt_sequence_modes[] =
1568 {
1569 interrupt_sequence_control_c,
1570 interrupt_sequence_break,
1571 interrupt_sequence_break_g,
1572 NULL
1573 };
1574 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1575
1576 static void
1577 show_interrupt_sequence (struct ui_file *file, int from_tty,
1578 struct cmd_list_element *c,
1579 const char *value)
1580 {
1581 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1582 gdb_printf (file,
1583 _("Send the ASCII ETX character (Ctrl-c) "
1584 "to the remote target to interrupt the "
1585 "execution of the program.\n"));
1586 else if (interrupt_sequence_mode == interrupt_sequence_break)
1587 gdb_printf (file,
1588 _("send a break signal to the remote target "
1589 "to interrupt the execution of the program.\n"));
1590 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1591 gdb_printf (file,
1592 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1593 "the remote target to interrupt the execution "
1594 "of Linux kernel.\n"));
1595 else
1596 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
1597 interrupt_sequence_mode);
1598 }
1599
1600 /* This boolean variable specifies whether interrupt_sequence is sent
1601 to the remote target when gdb connects to it.
1602 This is mostly needed when you debug the Linux kernel: The Linux kernel
1603 expects BREAK g which is Magic SysRq g for connecting gdb. */
1604 static bool interrupt_on_connect = false;
1605
1606 /* This variable is used to implement the "set/show remotebreak" commands.
1607 Since these commands are now deprecated in favor of "set/show remote
1608 interrupt-sequence", it no longer has any effect on the code. */
1609 static bool remote_break;
1610
1611 static void
1612 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1613 {
1614 if (remote_break)
1615 interrupt_sequence_mode = interrupt_sequence_break;
1616 else
1617 interrupt_sequence_mode = interrupt_sequence_control_c;
1618 }
1619
1620 static void
1621 show_remotebreak (struct ui_file *file, int from_tty,
1622 struct cmd_list_element *c,
1623 const char *value)
1624 {
1625 }
1626
1627 /* This variable sets the number of bits in an address that are to be
1628 sent in a memory ("M" or "m") packet. Normally, after stripping
1629 leading zeros, the entire address would be sent. This variable
1630 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1631 initial implementation of remote.c restricted the address sent in
1632 memory packets to ``host::sizeof long'' bytes - (typically 32
1633 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1634 address was never sent. Since fixing this bug may cause a break in
1635 some remote targets this variable is principally provided to
1636 facilitate backward compatibility. */
1637
1638 static unsigned int remote_address_size;
1639
1640 \f
1641 /* User configurable variables for the number of characters in a
1642 memory read/write packet. MIN (rsa->remote_packet_size,
1643 rsa->sizeof_g_packet) is the default. Some targets need smaller
1644 values (fifo overruns, et.al.) and some users need larger values
1645 (speed up transfers). The variables ``preferred_*'' (the user
1646 request), ``current_*'' (what was actually set) and ``forced_*''
1647 (Positive - a soft limit, negative - a hard limit). */
1648
1649 struct memory_packet_config
1650 {
1651 const char *name;
1652 long size;
1653 int fixed_p;
1654 };
1655
1656 /* The default max memory-write-packet-size, when the setting is
1657 "fixed". The 16k is historical. (It came from older GDB's using
1658 alloca for buffers and the knowledge (folklore?) that some hosts
1659 don't cope very well with large alloca calls.) */
1660 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1661
1662 /* The minimum remote packet size for memory transfers. Ensures we
1663 can write at least one byte. */
1664 #define MIN_MEMORY_PACKET_SIZE 20
1665
1666 /* Get the memory packet size, assuming it is fixed. */
1667
1668 static long
1669 get_fixed_memory_packet_size (struct memory_packet_config *config)
1670 {
1671 gdb_assert (config->fixed_p);
1672
1673 if (config->size <= 0)
1674 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1675 else
1676 return config->size;
1677 }
1678
1679 /* Compute the current size of a read/write packet. Since this makes
1680 use of ``actual_register_packet_size'' the computation is dynamic. */
1681
1682 long
1683 remote_target::get_memory_packet_size (struct memory_packet_config *config)
1684 {
1685 struct remote_state *rs = get_remote_state ();
1686 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1687
1688 long what_they_get;
1689 if (config->fixed_p)
1690 what_they_get = get_fixed_memory_packet_size (config);
1691 else
1692 {
1693 what_they_get = get_remote_packet_size ();
1694 /* Limit the packet to the size specified by the user. */
1695 if (config->size > 0
1696 && what_they_get > config->size)
1697 what_they_get = config->size;
1698
1699 /* Limit it to the size of the targets ``g'' response unless we have
1700 permission from the stub to use a larger packet size. */
1701 if (rs->explicit_packet_size == 0
1702 && rsa->actual_register_packet_size > 0
1703 && what_they_get > rsa->actual_register_packet_size)
1704 what_they_get = rsa->actual_register_packet_size;
1705 }
1706 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1707 what_they_get = MIN_MEMORY_PACKET_SIZE;
1708
1709 /* Make sure there is room in the global buffer for this packet
1710 (including its trailing NUL byte). */
1711 if (rs->buf.size () < what_they_get + 1)
1712 rs->buf.resize (2 * what_they_get);
1713
1714 return what_they_get;
1715 }
1716
1717 /* Update the size of a read/write packet. If they user wants
1718 something really big then do a sanity check. */
1719
1720 static void
1721 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1722 {
1723 int fixed_p = config->fixed_p;
1724 long size = config->size;
1725
1726 if (args == NULL)
1727 error (_("Argument required (integer, `fixed' or `limited')."));
1728 else if (strcmp (args, "hard") == 0
1729 || strcmp (args, "fixed") == 0)
1730 fixed_p = 1;
1731 else if (strcmp (args, "soft") == 0
1732 || strcmp (args, "limit") == 0)
1733 fixed_p = 0;
1734 else
1735 {
1736 char *end;
1737
1738 size = strtoul (args, &end, 0);
1739 if (args == end)
1740 error (_("Invalid %s (bad syntax)."), config->name);
1741
1742 /* Instead of explicitly capping the size of a packet to or
1743 disallowing it, the user is allowed to set the size to
1744 something arbitrarily large. */
1745 }
1746
1747 /* Extra checks? */
1748 if (fixed_p && !config->fixed_p)
1749 {
1750 /* So that the query shows the correct value. */
1751 long query_size = (size <= 0
1752 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1753 : size);
1754
1755 if (! query (_("The target may not be able to correctly handle a %s\n"
1756 "of %ld bytes. Change the packet size? "),
1757 config->name, query_size))
1758 error (_("Packet size not changed."));
1759 }
1760 /* Update the config. */
1761 config->fixed_p = fixed_p;
1762 config->size = size;
1763 }
1764
1765 static void
1766 show_memory_packet_size (struct memory_packet_config *config)
1767 {
1768 if (config->size == 0)
1769 gdb_printf (_("The %s is 0 (default). "), config->name);
1770 else
1771 gdb_printf (_("The %s is %ld. "), config->name, config->size);
1772 if (config->fixed_p)
1773 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
1774 get_fixed_memory_packet_size (config));
1775 else
1776 {
1777 remote_target *remote = get_current_remote_target ();
1778
1779 if (remote != NULL)
1780 gdb_printf (_("Packets are limited to %ld bytes.\n"),
1781 remote->get_memory_packet_size (config));
1782 else
1783 gdb_puts ("The actual limit will be further reduced "
1784 "dependent on the target.\n");
1785 }
1786 }
1787
1788 /* FIXME: needs to be per-remote-target. */
1789 static struct memory_packet_config memory_write_packet_config =
1790 {
1791 "memory-write-packet-size",
1792 };
1793
1794 static void
1795 set_memory_write_packet_size (const char *args, int from_tty)
1796 {
1797 set_memory_packet_size (args, &memory_write_packet_config);
1798 }
1799
1800 static void
1801 show_memory_write_packet_size (const char *args, int from_tty)
1802 {
1803 show_memory_packet_size (&memory_write_packet_config);
1804 }
1805
1806 /* Show the number of hardware watchpoints that can be used. */
1807
1808 static void
1809 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
1810 struct cmd_list_element *c,
1811 const char *value)
1812 {
1813 gdb_printf (file, _("The maximum number of target hardware "
1814 "watchpoints is %s.\n"), value);
1815 }
1816
1817 /* Show the length limit (in bytes) for hardware watchpoints. */
1818
1819 static void
1820 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
1821 struct cmd_list_element *c,
1822 const char *value)
1823 {
1824 gdb_printf (file, _("The maximum length (in bytes) of a target "
1825 "hardware watchpoint is %s.\n"), value);
1826 }
1827
1828 /* Show the number of hardware breakpoints that can be used. */
1829
1830 static void
1831 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
1832 struct cmd_list_element *c,
1833 const char *value)
1834 {
1835 gdb_printf (file, _("The maximum number of target hardware "
1836 "breakpoints is %s.\n"), value);
1837 }
1838
1839 /* Controls the maximum number of characters to display in the debug output
1840 for each remote packet. The remaining characters are omitted. */
1841
1842 static int remote_packet_max_chars = 512;
1843
1844 /* Show the maximum number of characters to display for each remote packet
1845 when remote debugging is enabled. */
1846
1847 static void
1848 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
1849 struct cmd_list_element *c,
1850 const char *value)
1851 {
1852 gdb_printf (file, _("Number of remote packet characters to "
1853 "display is %s.\n"), value);
1854 }
1855
1856 long
1857 remote_target::get_memory_write_packet_size ()
1858 {
1859 return get_memory_packet_size (&memory_write_packet_config);
1860 }
1861
1862 /* FIXME: needs to be per-remote-target. */
1863 static struct memory_packet_config memory_read_packet_config =
1864 {
1865 "memory-read-packet-size",
1866 };
1867
1868 static void
1869 set_memory_read_packet_size (const char *args, int from_tty)
1870 {
1871 set_memory_packet_size (args, &memory_read_packet_config);
1872 }
1873
1874 static void
1875 show_memory_read_packet_size (const char *args, int from_tty)
1876 {
1877 show_memory_packet_size (&memory_read_packet_config);
1878 }
1879
1880 long
1881 remote_target::get_memory_read_packet_size ()
1882 {
1883 long size = get_memory_packet_size (&memory_read_packet_config);
1884
1885 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1886 extra buffer size argument before the memory read size can be
1887 increased beyond this. */
1888 if (size > get_remote_packet_size ())
1889 size = get_remote_packet_size ();
1890 return size;
1891 }
1892
1893 \f
1894
1895 struct packet_config
1896 {
1897 const char *name;
1898 const char *title;
1899
1900 /* If auto, GDB auto-detects support for this packet or feature,
1901 either through qSupported, or by trying the packet and looking
1902 at the response. If true, GDB assumes the target supports this
1903 packet. If false, the packet is disabled. Configs that don't
1904 have an associated command always have this set to auto. */
1905 enum auto_boolean detect;
1906
1907 /* The "show remote foo-packet" command created for this packet. */
1908 cmd_list_element *show_cmd;
1909
1910 /* Does the target support this packet? */
1911 enum packet_support support;
1912 };
1913
1914 static enum packet_support packet_config_support (struct packet_config *config);
1915 static enum packet_support packet_support (int packet);
1916
1917 static void
1918 show_packet_config_cmd (ui_file *file, struct packet_config *config)
1919 {
1920 const char *support = "internal-error";
1921
1922 switch (packet_config_support (config))
1923 {
1924 case PACKET_ENABLE:
1925 support = "enabled";
1926 break;
1927 case PACKET_DISABLE:
1928 support = "disabled";
1929 break;
1930 case PACKET_SUPPORT_UNKNOWN:
1931 support = "unknown";
1932 break;
1933 }
1934 switch (config->detect)
1935 {
1936 case AUTO_BOOLEAN_AUTO:
1937 gdb_printf (file,
1938 _("Support for the `%s' packet "
1939 "is auto-detected, currently %s.\n"),
1940 config->name, support);
1941 break;
1942 case AUTO_BOOLEAN_TRUE:
1943 case AUTO_BOOLEAN_FALSE:
1944 gdb_printf (file,
1945 _("Support for the `%s' packet is currently %s.\n"),
1946 config->name, support);
1947 break;
1948 }
1949 }
1950
1951 static void
1952 add_packet_config_cmd (struct packet_config *config, const char *name,
1953 const char *title, int legacy)
1954 {
1955 config->name = name;
1956 config->title = title;
1957 gdb::unique_xmalloc_ptr<char> set_doc
1958 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
1959 name, title);
1960 gdb::unique_xmalloc_ptr<char> show_doc
1961 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
1962 name, title);
1963 /* set/show TITLE-packet {auto,on,off} */
1964 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
1965 set_show_commands cmds
1966 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
1967 &config->detect, set_doc.get (),
1968 show_doc.get (), NULL, /* help_doc */
1969 NULL,
1970 show_remote_protocol_packet_cmd,
1971 &remote_set_cmdlist, &remote_show_cmdlist);
1972 config->show_cmd = cmds.show;
1973
1974 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1975 if (legacy)
1976 {
1977 /* It's not clear who should take ownership of the LEGACY_NAME string
1978 created below, so, for now, place the string into a static vector
1979 which ensures the strings is released when GDB exits. */
1980 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
1981 gdb::unique_xmalloc_ptr<char> legacy_name
1982 = xstrprintf ("%s-packet", name);
1983 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
1984 &remote_set_cmdlist);
1985 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
1986 &remote_show_cmdlist);
1987 legacy_names.emplace_back (std::move (legacy_name));
1988 }
1989 }
1990
1991 static enum packet_result
1992 packet_check_result (const char *buf)
1993 {
1994 if (buf[0] != '\0')
1995 {
1996 /* The stub recognized the packet request. Check that the
1997 operation succeeded. */
1998 if (buf[0] == 'E'
1999 && isxdigit (buf[1]) && isxdigit (buf[2])
2000 && buf[3] == '\0')
2001 /* "Enn" - definitely an error. */
2002 return PACKET_ERROR;
2003
2004 /* Always treat "E." as an error. This will be used for
2005 more verbose error messages, such as E.memtypes. */
2006 if (buf[0] == 'E' && buf[1] == '.')
2007 return PACKET_ERROR;
2008
2009 /* The packet may or may not be OK. Just assume it is. */
2010 return PACKET_OK;
2011 }
2012 else
2013 /* The stub does not support the packet. */
2014 return PACKET_UNKNOWN;
2015 }
2016
2017 static enum packet_result
2018 packet_check_result (const gdb::char_vector &buf)
2019 {
2020 return packet_check_result (buf.data ());
2021 }
2022
2023 static enum packet_result
2024 packet_ok (const char *buf, struct packet_config *config)
2025 {
2026 enum packet_result result;
2027
2028 if (config->detect != AUTO_BOOLEAN_TRUE
2029 && config->support == PACKET_DISABLE)
2030 internal_error (_("packet_ok: attempt to use a disabled packet"));
2031
2032 result = packet_check_result (buf);
2033 switch (result)
2034 {
2035 case PACKET_OK:
2036 case PACKET_ERROR:
2037 /* The stub recognized the packet request. */
2038 if (config->support == PACKET_SUPPORT_UNKNOWN)
2039 {
2040 remote_debug_printf ("Packet %s (%s) is supported",
2041 config->name, config->title);
2042 config->support = PACKET_ENABLE;
2043 }
2044 break;
2045 case PACKET_UNKNOWN:
2046 /* The stub does not support the packet. */
2047 if (config->detect == AUTO_BOOLEAN_AUTO
2048 && config->support == PACKET_ENABLE)
2049 {
2050 /* If the stub previously indicated that the packet was
2051 supported then there is a protocol error. */
2052 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2053 config->name, config->title);
2054 }
2055 else if (config->detect == AUTO_BOOLEAN_TRUE)
2056 {
2057 /* The user set it wrong. */
2058 error (_("Enabled packet %s (%s) not recognized by stub"),
2059 config->name, config->title);
2060 }
2061
2062 remote_debug_printf ("Packet %s (%s) is NOT supported",
2063 config->name, config->title);
2064 config->support = PACKET_DISABLE;
2065 break;
2066 }
2067
2068 return result;
2069 }
2070
2071 static enum packet_result
2072 packet_ok (const gdb::char_vector &buf, struct packet_config *config)
2073 {
2074 return packet_ok (buf.data (), config);
2075 }
2076
2077 enum {
2078 PACKET_vCont = 0,
2079 PACKET_X,
2080 PACKET_qSymbol,
2081 PACKET_P,
2082 PACKET_p,
2083 PACKET_Z0,
2084 PACKET_Z1,
2085 PACKET_Z2,
2086 PACKET_Z3,
2087 PACKET_Z4,
2088 PACKET_vFile_setfs,
2089 PACKET_vFile_open,
2090 PACKET_vFile_pread,
2091 PACKET_vFile_pwrite,
2092 PACKET_vFile_close,
2093 PACKET_vFile_unlink,
2094 PACKET_vFile_readlink,
2095 PACKET_vFile_fstat,
2096 PACKET_qXfer_auxv,
2097 PACKET_qXfer_features,
2098 PACKET_qXfer_exec_file,
2099 PACKET_qXfer_libraries,
2100 PACKET_qXfer_libraries_svr4,
2101 PACKET_qXfer_memory_map,
2102 PACKET_qXfer_osdata,
2103 PACKET_qXfer_threads,
2104 PACKET_qXfer_statictrace_read,
2105 PACKET_qXfer_traceframe_info,
2106 PACKET_qXfer_uib,
2107 PACKET_qGetTIBAddr,
2108 PACKET_qGetTLSAddr,
2109 PACKET_qSupported,
2110 PACKET_qTStatus,
2111 PACKET_QPassSignals,
2112 PACKET_QCatchSyscalls,
2113 PACKET_QProgramSignals,
2114 PACKET_QSetWorkingDir,
2115 PACKET_QStartupWithShell,
2116 PACKET_QEnvironmentHexEncoded,
2117 PACKET_QEnvironmentReset,
2118 PACKET_QEnvironmentUnset,
2119 PACKET_qCRC,
2120 PACKET_qSearch_memory,
2121 PACKET_vAttach,
2122 PACKET_vRun,
2123 PACKET_QStartNoAckMode,
2124 PACKET_vKill,
2125 PACKET_qXfer_siginfo_read,
2126 PACKET_qXfer_siginfo_write,
2127 PACKET_qAttached,
2128
2129 /* Support for conditional tracepoints. */
2130 PACKET_ConditionalTracepoints,
2131
2132 /* Support for target-side breakpoint conditions. */
2133 PACKET_ConditionalBreakpoints,
2134
2135 /* Support for target-side breakpoint commands. */
2136 PACKET_BreakpointCommands,
2137
2138 /* Support for fast tracepoints. */
2139 PACKET_FastTracepoints,
2140
2141 /* Support for static tracepoints. */
2142 PACKET_StaticTracepoints,
2143
2144 /* Support for installing tracepoints while a trace experiment is
2145 running. */
2146 PACKET_InstallInTrace,
2147
2148 PACKET_bc,
2149 PACKET_bs,
2150 PACKET_TracepointSource,
2151 PACKET_QAllow,
2152 PACKET_qXfer_fdpic,
2153 PACKET_QDisableRandomization,
2154 PACKET_QAgent,
2155 PACKET_QTBuffer_size,
2156 PACKET_Qbtrace_off,
2157 PACKET_Qbtrace_bts,
2158 PACKET_Qbtrace_pt,
2159 PACKET_qXfer_btrace,
2160
2161 /* Support for the QNonStop packet. */
2162 PACKET_QNonStop,
2163
2164 /* Support for the QThreadEvents packet. */
2165 PACKET_QThreadEvents,
2166
2167 /* Support for multi-process extensions. */
2168 PACKET_multiprocess_feature,
2169
2170 /* Support for enabling and disabling tracepoints while a trace
2171 experiment is running. */
2172 PACKET_EnableDisableTracepoints_feature,
2173
2174 /* Support for collecting strings using the tracenz bytecode. */
2175 PACKET_tracenz_feature,
2176
2177 /* Support for continuing to run a trace experiment while GDB is
2178 disconnected. */
2179 PACKET_DisconnectedTracing_feature,
2180
2181 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2182 PACKET_augmented_libraries_svr4_read_feature,
2183
2184 /* Support for the qXfer:btrace-conf:read packet. */
2185 PACKET_qXfer_btrace_conf,
2186
2187 /* Support for the Qbtrace-conf:bts:size packet. */
2188 PACKET_Qbtrace_conf_bts_size,
2189
2190 /* Support for swbreak+ feature. */
2191 PACKET_swbreak_feature,
2192
2193 /* Support for hwbreak+ feature. */
2194 PACKET_hwbreak_feature,
2195
2196 /* Support for fork events. */
2197 PACKET_fork_event_feature,
2198
2199 /* Support for vfork events. */
2200 PACKET_vfork_event_feature,
2201
2202 /* Support for the Qbtrace-conf:pt:size packet. */
2203 PACKET_Qbtrace_conf_pt_size,
2204
2205 /* Support for exec events. */
2206 PACKET_exec_event_feature,
2207
2208 /* Support for query supported vCont actions. */
2209 PACKET_vContSupported,
2210
2211 /* Support remote CTRL-C. */
2212 PACKET_vCtrlC,
2213
2214 /* Support TARGET_WAITKIND_NO_RESUMED. */
2215 PACKET_no_resumed,
2216
2217 /* Support for memory tagging, allocation tag fetch/store
2218 packets and the tag violation stop replies. */
2219 PACKET_memory_tagging_feature,
2220
2221 PACKET_MAX
2222 };
2223
2224 /* FIXME: needs to be per-remote-target. Ignoring this for now,
2225 assuming all remote targets are the same server (thus all support
2226 the same packets). */
2227 static struct packet_config remote_protocol_packets[PACKET_MAX];
2228
2229 /* Returns the packet's corresponding "set remote foo-packet" command
2230 state. See struct packet_config for more details. */
2231
2232 static enum auto_boolean
2233 packet_set_cmd_state (int packet)
2234 {
2235 return remote_protocol_packets[packet].detect;
2236 }
2237
2238 /* Returns whether a given packet or feature is supported. This takes
2239 into account the state of the corresponding "set remote foo-packet"
2240 command, which may be used to bypass auto-detection. */
2241
2242 static enum packet_support
2243 packet_config_support (struct packet_config *config)
2244 {
2245 switch (config->detect)
2246 {
2247 case AUTO_BOOLEAN_TRUE:
2248 return PACKET_ENABLE;
2249 case AUTO_BOOLEAN_FALSE:
2250 return PACKET_DISABLE;
2251 case AUTO_BOOLEAN_AUTO:
2252 return config->support;
2253 default:
2254 gdb_assert_not_reached ("bad switch");
2255 }
2256 }
2257
2258 /* Same as packet_config_support, but takes the packet's enum value as
2259 argument. */
2260
2261 static enum packet_support
2262 packet_support (int packet)
2263 {
2264 struct packet_config *config = &remote_protocol_packets[packet];
2265
2266 return packet_config_support (config);
2267 }
2268
2269 static void
2270 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2271 struct cmd_list_element *c,
2272 const char *value)
2273 {
2274 struct packet_config *packet;
2275 gdb_assert (c->var.has_value ());
2276
2277 for (packet = remote_protocol_packets;
2278 packet < &remote_protocol_packets[PACKET_MAX];
2279 packet++)
2280 {
2281 if (c == packet->show_cmd)
2282 {
2283 show_packet_config_cmd (file, packet);
2284 return;
2285 }
2286 }
2287 internal_error (_("Could not find config for %s"),
2288 c->name);
2289 }
2290
2291 /* Should we try one of the 'Z' requests? */
2292
2293 enum Z_packet_type
2294 {
2295 Z_PACKET_SOFTWARE_BP,
2296 Z_PACKET_HARDWARE_BP,
2297 Z_PACKET_WRITE_WP,
2298 Z_PACKET_READ_WP,
2299 Z_PACKET_ACCESS_WP,
2300 NR_Z_PACKET_TYPES
2301 };
2302
2303 /* For compatibility with older distributions. Provide a ``set remote
2304 Z-packet ...'' command that updates all the Z packet types. */
2305
2306 static enum auto_boolean remote_Z_packet_detect;
2307
2308 static void
2309 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2310 struct cmd_list_element *c)
2311 {
2312 int i;
2313
2314 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2315 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2316 }
2317
2318 static void
2319 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2320 struct cmd_list_element *c,
2321 const char *value)
2322 {
2323 int i;
2324
2325 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2326 {
2327 show_packet_config_cmd (file, &remote_protocol_packets[PACKET_Z0 + i]);
2328 }
2329 }
2330
2331 /* Returns true if the multi-process extensions are in effect. */
2332
2333 static int
2334 remote_multi_process_p (struct remote_state *rs)
2335 {
2336 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2337 }
2338
2339 /* Returns true if fork events are supported. */
2340
2341 static int
2342 remote_fork_event_p (struct remote_state *rs)
2343 {
2344 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2345 }
2346
2347 /* Returns true if vfork events are supported. */
2348
2349 static int
2350 remote_vfork_event_p (struct remote_state *rs)
2351 {
2352 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2353 }
2354
2355 /* Returns true if exec events are supported. */
2356
2357 static int
2358 remote_exec_event_p (struct remote_state *rs)
2359 {
2360 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2361 }
2362
2363 /* Returns true if memory tagging is supported, false otherwise. */
2364
2365 static bool
2366 remote_memory_tagging_p ()
2367 {
2368 return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE;
2369 }
2370
2371 /* Insert fork catchpoint target routine. If fork events are enabled
2372 then return success, nothing more to do. */
2373
2374 int
2375 remote_target::insert_fork_catchpoint (int pid)
2376 {
2377 struct remote_state *rs = get_remote_state ();
2378
2379 return !remote_fork_event_p (rs);
2380 }
2381
2382 /* Remove fork catchpoint target routine. Nothing to do, just
2383 return success. */
2384
2385 int
2386 remote_target::remove_fork_catchpoint (int pid)
2387 {
2388 return 0;
2389 }
2390
2391 /* Insert vfork catchpoint target routine. If vfork events are enabled
2392 then return success, nothing more to do. */
2393
2394 int
2395 remote_target::insert_vfork_catchpoint (int pid)
2396 {
2397 struct remote_state *rs = get_remote_state ();
2398
2399 return !remote_vfork_event_p (rs);
2400 }
2401
2402 /* Remove vfork catchpoint target routine. Nothing to do, just
2403 return success. */
2404
2405 int
2406 remote_target::remove_vfork_catchpoint (int pid)
2407 {
2408 return 0;
2409 }
2410
2411 /* Insert exec catchpoint target routine. If exec events are
2412 enabled, just return success. */
2413
2414 int
2415 remote_target::insert_exec_catchpoint (int pid)
2416 {
2417 struct remote_state *rs = get_remote_state ();
2418
2419 return !remote_exec_event_p (rs);
2420 }
2421
2422 /* Remove exec catchpoint target routine. Nothing to do, just
2423 return success. */
2424
2425 int
2426 remote_target::remove_exec_catchpoint (int pid)
2427 {
2428 return 0;
2429 }
2430
2431 \f
2432
2433 /* Take advantage of the fact that the TID field is not used, to tag
2434 special ptids with it set to != 0. */
2435 static const ptid_t magic_null_ptid (42000, -1, 1);
2436 static const ptid_t not_sent_ptid (42000, -2, 1);
2437 static const ptid_t any_thread_ptid (42000, 0, 1);
2438
2439 /* Find out if the stub attached to PID (and hence GDB should offer to
2440 detach instead of killing it when bailing out). */
2441
2442 int
2443 remote_target::remote_query_attached (int pid)
2444 {
2445 struct remote_state *rs = get_remote_state ();
2446 size_t size = get_remote_packet_size ();
2447
2448 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2449 return 0;
2450
2451 if (remote_multi_process_p (rs))
2452 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2453 else
2454 xsnprintf (rs->buf.data (), size, "qAttached");
2455
2456 putpkt (rs->buf);
2457 getpkt (&rs->buf, 0);
2458
2459 switch (packet_ok (rs->buf,
2460 &remote_protocol_packets[PACKET_qAttached]))
2461 {
2462 case PACKET_OK:
2463 if (strcmp (rs->buf.data (), "1") == 0)
2464 return 1;
2465 break;
2466 case PACKET_ERROR:
2467 warning (_("Remote failure reply: %s"), rs->buf.data ());
2468 break;
2469 case PACKET_UNKNOWN:
2470 break;
2471 }
2472
2473 return 0;
2474 }
2475
2476 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2477 has been invented by GDB, instead of reported by the target. Since
2478 we can be connected to a remote system before before knowing about
2479 any inferior, mark the target with execution when we find the first
2480 inferior. If ATTACHED is 1, then we had just attached to this
2481 inferior. If it is 0, then we just created this inferior. If it
2482 is -1, then try querying the remote stub to find out if it had
2483 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2484 attempt to open this inferior's executable as the main executable
2485 if no main executable is open already. */
2486
2487 inferior *
2488 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2489 int try_open_exec)
2490 {
2491 struct inferior *inf;
2492
2493 /* Check whether this process we're learning about is to be
2494 considered attached, or if is to be considered to have been
2495 spawned by the stub. */
2496 if (attached == -1)
2497 attached = remote_query_attached (pid);
2498
2499 if (gdbarch_has_global_solist (target_gdbarch ()))
2500 {
2501 /* If the target shares code across all inferiors, then every
2502 attach adds a new inferior. */
2503 inf = add_inferior (pid);
2504
2505 /* ... and every inferior is bound to the same program space.
2506 However, each inferior may still have its own address
2507 space. */
2508 inf->aspace = maybe_new_address_space ();
2509 inf->pspace = current_program_space;
2510 }
2511 else
2512 {
2513 /* In the traditional debugging scenario, there's a 1-1 match
2514 between program/address spaces. We simply bind the inferior
2515 to the program space's address space. */
2516 inf = current_inferior ();
2517
2518 /* However, if the current inferior is already bound to a
2519 process, find some other empty inferior. */
2520 if (inf->pid != 0)
2521 {
2522 inf = nullptr;
2523 for (inferior *it : all_inferiors ())
2524 if (it->pid == 0)
2525 {
2526 inf = it;
2527 break;
2528 }
2529 }
2530 if (inf == nullptr)
2531 {
2532 /* Since all inferiors were already bound to a process, add
2533 a new inferior. */
2534 inf = add_inferior_with_spaces ();
2535 }
2536 switch_to_inferior_no_thread (inf);
2537 inf->push_target (this);
2538 inferior_appeared (inf, pid);
2539 }
2540
2541 inf->attach_flag = attached;
2542 inf->fake_pid_p = fake_pid_p;
2543
2544 /* If no main executable is currently open then attempt to
2545 open the file that was executed to create this inferior. */
2546 if (try_open_exec && get_exec_file (0) == NULL)
2547 exec_file_locate_attach (pid, 0, 1);
2548
2549 /* Check for exec file mismatch, and let the user solve it. */
2550 validate_exec_file (1);
2551
2552 return inf;
2553 }
2554
2555 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2556 static remote_thread_info *get_remote_thread_info (remote_target *target,
2557 ptid_t ptid);
2558
2559 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2560 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2561 remote_state::starting_up flag) is true then the new thread is added
2562 silently, otherwise the new thread will be announced to the user. */
2563
2564 thread_info *
2565 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2566 bool silent_p)
2567 {
2568 struct remote_state *rs = get_remote_state ();
2569 struct thread_info *thread;
2570
2571 /* GDB historically didn't pull threads in the initial connection
2572 setup. If the remote target doesn't even have a concept of
2573 threads (e.g., a bare-metal target), even if internally we
2574 consider that a single-threaded target, mentioning a new thread
2575 might be confusing to the user. Be silent then, preserving the
2576 age old behavior. */
2577 if (rs->starting_up || silent_p)
2578 thread = add_thread_silent (this, ptid);
2579 else
2580 thread = add_thread (this, ptid);
2581
2582 /* We start by assuming threads are resumed. That state then gets updated
2583 when we process a matching stop reply. */
2584 get_remote_thread_info (thread)->set_resumed ();
2585
2586 set_executing (this, ptid, executing);
2587 set_running (this, ptid, running);
2588
2589 return thread;
2590 }
2591
2592 /* Come here when we learn about a thread id from the remote target.
2593 It may be the first time we hear about such thread, so take the
2594 opportunity to add it to GDB's thread list. In case this is the
2595 first time we're noticing its corresponding inferior, add it to
2596 GDB's inferior list as well. EXECUTING indicates whether the
2597 thread is (internally) executing or stopped. */
2598
2599 void
2600 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2601 {
2602 /* In non-stop mode, we assume new found threads are (externally)
2603 running until proven otherwise with a stop reply. In all-stop,
2604 we can only get here if all threads are stopped. */
2605 bool running = target_is_non_stop_p ();
2606
2607 /* If this is a new thread, add it to GDB's thread list.
2608 If we leave it up to WFI to do this, bad things will happen. */
2609
2610 thread_info *tp = find_thread_ptid (this, currthread);
2611 if (tp != NULL && tp->state == THREAD_EXITED)
2612 {
2613 /* We're seeing an event on a thread id we knew had exited.
2614 This has to be a new thread reusing the old id. Add it. */
2615 remote_add_thread (currthread, running, executing, false);
2616 return;
2617 }
2618
2619 if (!in_thread_list (this, currthread))
2620 {
2621 struct inferior *inf = NULL;
2622 int pid = currthread.pid ();
2623
2624 if (inferior_ptid.is_pid ()
2625 && pid == inferior_ptid.pid ())
2626 {
2627 /* inferior_ptid has no thread member yet. This can happen
2628 with the vAttach -> remote_wait,"TAAthread:" path if the
2629 stub doesn't support qC. This is the first stop reported
2630 after an attach, so this is the main thread. Update the
2631 ptid in the thread list. */
2632 if (in_thread_list (this, ptid_t (pid)))
2633 thread_change_ptid (this, inferior_ptid, currthread);
2634 else
2635 {
2636 thread_info *thr
2637 = remote_add_thread (currthread, running, executing, false);
2638 switch_to_thread (thr);
2639 }
2640 return;
2641 }
2642
2643 if (magic_null_ptid == inferior_ptid)
2644 {
2645 /* inferior_ptid is not set yet. This can happen with the
2646 vRun -> remote_wait,"TAAthread:" path if the stub
2647 doesn't support qC. This is the first stop reported
2648 after an attach, so this is the main thread. Update the
2649 ptid in the thread list. */
2650 thread_change_ptid (this, inferior_ptid, currthread);
2651 return;
2652 }
2653
2654 /* When connecting to a target remote, or to a target
2655 extended-remote which already was debugging an inferior, we
2656 may not know about it yet. Add it before adding its child
2657 thread, so notifications are emitted in a sensible order. */
2658 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2659 {
2660 struct remote_state *rs = get_remote_state ();
2661 bool fake_pid_p = !remote_multi_process_p (rs);
2662
2663 inf = remote_add_inferior (fake_pid_p,
2664 currthread.pid (), -1, 1);
2665 }
2666
2667 /* This is really a new thread. Add it. */
2668 thread_info *new_thr
2669 = remote_add_thread (currthread, running, executing, false);
2670
2671 /* If we found a new inferior, let the common code do whatever
2672 it needs to with it (e.g., read shared libraries, insert
2673 breakpoints), unless we're just setting up an all-stop
2674 connection. */
2675 if (inf != NULL)
2676 {
2677 struct remote_state *rs = get_remote_state ();
2678
2679 if (!rs->starting_up)
2680 notice_new_inferior (new_thr, executing, 0);
2681 }
2682 }
2683 }
2684
2685 /* Return THREAD's private thread data, creating it if necessary. */
2686
2687 static remote_thread_info *
2688 get_remote_thread_info (thread_info *thread)
2689 {
2690 gdb_assert (thread != NULL);
2691
2692 if (thread->priv == NULL)
2693 thread->priv.reset (new remote_thread_info);
2694
2695 return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
2696 }
2697
2698 /* Return PTID's private thread data, creating it if necessary. */
2699
2700 static remote_thread_info *
2701 get_remote_thread_info (remote_target *target, ptid_t ptid)
2702 {
2703 thread_info *thr = find_thread_ptid (target, ptid);
2704 return get_remote_thread_info (thr);
2705 }
2706
2707 /* Call this function as a result of
2708 1) A halt indication (T packet) containing a thread id
2709 2) A direct query of currthread
2710 3) Successful execution of set thread */
2711
2712 static void
2713 record_currthread (struct remote_state *rs, ptid_t currthread)
2714 {
2715 rs->general_thread = currthread;
2716 }
2717
2718 /* If 'QPassSignals' is supported, tell the remote stub what signals
2719 it can simply pass through to the inferior without reporting. */
2720
2721 void
2722 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2723 {
2724 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2725 {
2726 char *pass_packet, *p;
2727 int count = 0;
2728 struct remote_state *rs = get_remote_state ();
2729
2730 gdb_assert (pass_signals.size () < 256);
2731 for (size_t i = 0; i < pass_signals.size (); i++)
2732 {
2733 if (pass_signals[i])
2734 count++;
2735 }
2736 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2737 strcpy (pass_packet, "QPassSignals:");
2738 p = pass_packet + strlen (pass_packet);
2739 for (size_t i = 0; i < pass_signals.size (); i++)
2740 {
2741 if (pass_signals[i])
2742 {
2743 if (i >= 16)
2744 *p++ = tohex (i >> 4);
2745 *p++ = tohex (i & 15);
2746 if (count)
2747 *p++ = ';';
2748 else
2749 break;
2750 count--;
2751 }
2752 }
2753 *p = 0;
2754 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2755 {
2756 putpkt (pass_packet);
2757 getpkt (&rs->buf, 0);
2758 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2759 xfree (rs->last_pass_packet);
2760 rs->last_pass_packet = pass_packet;
2761 }
2762 else
2763 xfree (pass_packet);
2764 }
2765 }
2766
2767 /* If 'QCatchSyscalls' is supported, tell the remote stub
2768 to report syscalls to GDB. */
2769
2770 int
2771 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2772 gdb::array_view<const int> syscall_counts)
2773 {
2774 const char *catch_packet;
2775 enum packet_result result;
2776 int n_sysno = 0;
2777
2778 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2779 {
2780 /* Not supported. */
2781 return 1;
2782 }
2783
2784 if (needed && any_count == 0)
2785 {
2786 /* Count how many syscalls are to be caught. */
2787 for (size_t i = 0; i < syscall_counts.size (); i++)
2788 {
2789 if (syscall_counts[i] != 0)
2790 n_sysno++;
2791 }
2792 }
2793
2794 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
2795 pid, needed, any_count, n_sysno);
2796
2797 std::string built_packet;
2798 if (needed)
2799 {
2800 /* Prepare a packet with the sysno list, assuming max 8+1
2801 characters for a sysno. If the resulting packet size is too
2802 big, fallback on the non-selective packet. */
2803 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2804 built_packet.reserve (maxpktsz);
2805 built_packet = "QCatchSyscalls:1";
2806 if (any_count == 0)
2807 {
2808 /* Add in each syscall to be caught. */
2809 for (size_t i = 0; i < syscall_counts.size (); i++)
2810 {
2811 if (syscall_counts[i] != 0)
2812 string_appendf (built_packet, ";%zx", i);
2813 }
2814 }
2815 if (built_packet.size () > get_remote_packet_size ())
2816 {
2817 /* catch_packet too big. Fallback to less efficient
2818 non selective mode, with GDB doing the filtering. */
2819 catch_packet = "QCatchSyscalls:1";
2820 }
2821 else
2822 catch_packet = built_packet.c_str ();
2823 }
2824 else
2825 catch_packet = "QCatchSyscalls:0";
2826
2827 struct remote_state *rs = get_remote_state ();
2828
2829 putpkt (catch_packet);
2830 getpkt (&rs->buf, 0);
2831 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2832 if (result == PACKET_OK)
2833 return 0;
2834 else
2835 return -1;
2836 }
2837
2838 /* If 'QProgramSignals' is supported, tell the remote stub what
2839 signals it should pass through to the inferior when detaching. */
2840
2841 void
2842 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
2843 {
2844 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2845 {
2846 char *packet, *p;
2847 int count = 0;
2848 struct remote_state *rs = get_remote_state ();
2849
2850 gdb_assert (signals.size () < 256);
2851 for (size_t i = 0; i < signals.size (); i++)
2852 {
2853 if (signals[i])
2854 count++;
2855 }
2856 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2857 strcpy (packet, "QProgramSignals:");
2858 p = packet + strlen (packet);
2859 for (size_t i = 0; i < signals.size (); i++)
2860 {
2861 if (signal_pass_state (i))
2862 {
2863 if (i >= 16)
2864 *p++ = tohex (i >> 4);
2865 *p++ = tohex (i & 15);
2866 if (count)
2867 *p++ = ';';
2868 else
2869 break;
2870 count--;
2871 }
2872 }
2873 *p = 0;
2874 if (!rs->last_program_signals_packet
2875 || strcmp (rs->last_program_signals_packet, packet) != 0)
2876 {
2877 putpkt (packet);
2878 getpkt (&rs->buf, 0);
2879 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2880 xfree (rs->last_program_signals_packet);
2881 rs->last_program_signals_packet = packet;
2882 }
2883 else
2884 xfree (packet);
2885 }
2886 }
2887
2888 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2889 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2890 thread. If GEN is set, set the general thread, if not, then set
2891 the step/continue thread. */
2892 void
2893 remote_target::set_thread (ptid_t ptid, int gen)
2894 {
2895 struct remote_state *rs = get_remote_state ();
2896 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2897 char *buf = rs->buf.data ();
2898 char *endbuf = buf + get_remote_packet_size ();
2899
2900 if (state == ptid)
2901 return;
2902
2903 *buf++ = 'H';
2904 *buf++ = gen ? 'g' : 'c';
2905 if (ptid == magic_null_ptid)
2906 xsnprintf (buf, endbuf - buf, "0");
2907 else if (ptid == any_thread_ptid)
2908 xsnprintf (buf, endbuf - buf, "0");
2909 else if (ptid == minus_one_ptid)
2910 xsnprintf (buf, endbuf - buf, "-1");
2911 else
2912 write_ptid (buf, endbuf, ptid);
2913 putpkt (rs->buf);
2914 getpkt (&rs->buf, 0);
2915 if (gen)
2916 rs->general_thread = ptid;
2917 else
2918 rs->continue_thread = ptid;
2919 }
2920
2921 void
2922 remote_target::set_general_thread (ptid_t ptid)
2923 {
2924 set_thread (ptid, 1);
2925 }
2926
2927 void
2928 remote_target::set_continue_thread (ptid_t ptid)
2929 {
2930 set_thread (ptid, 0);
2931 }
2932
2933 /* Change the remote current process. Which thread within the process
2934 ends up selected isn't important, as long as it is the same process
2935 as what INFERIOR_PTID points to.
2936
2937 This comes from that fact that there is no explicit notion of
2938 "selected process" in the protocol. The selected process for
2939 general operations is the process the selected general thread
2940 belongs to. */
2941
2942 void
2943 remote_target::set_general_process ()
2944 {
2945 struct remote_state *rs = get_remote_state ();
2946
2947 /* If the remote can't handle multiple processes, don't bother. */
2948 if (!remote_multi_process_p (rs))
2949 return;
2950
2951 /* We only need to change the remote current thread if it's pointing
2952 at some other process. */
2953 if (rs->general_thread.pid () != inferior_ptid.pid ())
2954 set_general_thread (inferior_ptid);
2955 }
2956
2957 \f
2958 /* Return nonzero if this is the main thread that we made up ourselves
2959 to model non-threaded targets as single-threaded. */
2960
2961 static int
2962 remote_thread_always_alive (ptid_t ptid)
2963 {
2964 if (ptid == magic_null_ptid)
2965 /* The main thread is always alive. */
2966 return 1;
2967
2968 if (ptid.pid () != 0 && ptid.lwp () == 0)
2969 /* The main thread is always alive. This can happen after a
2970 vAttach, if the remote side doesn't support
2971 multi-threading. */
2972 return 1;
2973
2974 return 0;
2975 }
2976
2977 /* Return nonzero if the thread PTID is still alive on the remote
2978 system. */
2979
2980 bool
2981 remote_target::thread_alive (ptid_t ptid)
2982 {
2983 struct remote_state *rs = get_remote_state ();
2984 char *p, *endp;
2985
2986 /* Check if this is a thread that we made up ourselves to model
2987 non-threaded targets as single-threaded. */
2988 if (remote_thread_always_alive (ptid))
2989 return 1;
2990
2991 p = rs->buf.data ();
2992 endp = p + get_remote_packet_size ();
2993
2994 *p++ = 'T';
2995 write_ptid (p, endp, ptid);
2996
2997 putpkt (rs->buf);
2998 getpkt (&rs->buf, 0);
2999 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
3000 }
3001
3002 /* Return a pointer to a thread name if we know it and NULL otherwise.
3003 The thread_info object owns the memory for the name. */
3004
3005 const char *
3006 remote_target::thread_name (struct thread_info *info)
3007 {
3008 if (info->priv != NULL)
3009 {
3010 const std::string &name = get_remote_thread_info (info)->name;
3011 return !name.empty () ? name.c_str () : NULL;
3012 }
3013
3014 return NULL;
3015 }
3016
3017 /* About these extended threadlist and threadinfo packets. They are
3018 variable length packets but, the fields within them are often fixed
3019 length. They are redundant enough to send over UDP as is the
3020 remote protocol in general. There is a matching unit test module
3021 in libstub. */
3022
3023 /* WARNING: This threadref data structure comes from the remote O.S.,
3024 libstub protocol encoding, and remote.c. It is not particularly
3025 changable. */
3026
3027 /* Right now, the internal structure is int. We want it to be bigger.
3028 Plan to fix this. */
3029
3030 typedef int gdb_threadref; /* Internal GDB thread reference. */
3031
3032 /* gdb_ext_thread_info is an internal GDB data structure which is
3033 equivalent to the reply of the remote threadinfo packet. */
3034
3035 struct gdb_ext_thread_info
3036 {
3037 threadref threadid; /* External form of thread reference. */
3038 int active; /* Has state interesting to GDB?
3039 regs, stack. */
3040 char display[256]; /* Brief state display, name,
3041 blocked/suspended. */
3042 char shortname[32]; /* To be used to name threads. */
3043 char more_display[256]; /* Long info, statistics, queue depth,
3044 whatever. */
3045 };
3046
3047 /* The volume of remote transfers can be limited by submitting
3048 a mask containing bits specifying the desired information.
3049 Use a union of these values as the 'selection' parameter to
3050 get_thread_info. FIXME: Make these TAG names more thread specific. */
3051
3052 #define TAG_THREADID 1
3053 #define TAG_EXISTS 2
3054 #define TAG_DISPLAY 4
3055 #define TAG_THREADNAME 8
3056 #define TAG_MOREDISPLAY 16
3057
3058 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3059
3060 static const char *unpack_nibble (const char *buf, int *val);
3061
3062 static const char *unpack_byte (const char *buf, int *value);
3063
3064 static char *pack_int (char *buf, int value);
3065
3066 static const char *unpack_int (const char *buf, int *value);
3067
3068 static const char *unpack_string (const char *src, char *dest, int length);
3069
3070 static char *pack_threadid (char *pkt, threadref *id);
3071
3072 static const char *unpack_threadid (const char *inbuf, threadref *id);
3073
3074 void int_to_threadref (threadref *id, int value);
3075
3076 static int threadref_to_int (threadref *ref);
3077
3078 static void copy_threadref (threadref *dest, threadref *src);
3079
3080 static int threadmatch (threadref *dest, threadref *src);
3081
3082 static char *pack_threadinfo_request (char *pkt, int mode,
3083 threadref *id);
3084
3085 static char *pack_threadlist_request (char *pkt, int startflag,
3086 int threadcount,
3087 threadref *nextthread);
3088
3089 static int remote_newthread_step (threadref *ref, void *context);
3090
3091
3092 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3093 buffer we're allowed to write to. Returns
3094 BUF+CHARACTERS_WRITTEN. */
3095
3096 char *
3097 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3098 {
3099 int pid, tid;
3100 struct remote_state *rs = get_remote_state ();
3101
3102 if (remote_multi_process_p (rs))
3103 {
3104 pid = ptid.pid ();
3105 if (pid < 0)
3106 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3107 else
3108 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3109 }
3110 tid = ptid.lwp ();
3111 if (tid < 0)
3112 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3113 else
3114 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3115
3116 return buf;
3117 }
3118
3119 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3120 last parsed char. Returns null_ptid if no thread id is found, and
3121 throws an error if the thread id has an invalid format. */
3122
3123 static ptid_t
3124 read_ptid (const char *buf, const char **obuf)
3125 {
3126 const char *p = buf;
3127 const char *pp;
3128 ULONGEST pid = 0, tid = 0;
3129
3130 if (*p == 'p')
3131 {
3132 /* Multi-process ptid. */
3133 pp = unpack_varlen_hex (p + 1, &pid);
3134 if (*pp != '.')
3135 error (_("invalid remote ptid: %s"), p);
3136
3137 p = pp;
3138 pp = unpack_varlen_hex (p + 1, &tid);
3139 if (obuf)
3140 *obuf = pp;
3141 return ptid_t (pid, tid);
3142 }
3143
3144 /* No multi-process. Just a tid. */
3145 pp = unpack_varlen_hex (p, &tid);
3146
3147 /* Return null_ptid when no thread id is found. */
3148 if (p == pp)
3149 {
3150 if (obuf)
3151 *obuf = pp;
3152 return null_ptid;
3153 }
3154
3155 /* Since the stub is not sending a process id, default to what's
3156 current_inferior, unless it doesn't have a PID yet. If so,
3157 then since there's no way to know the pid of the reported
3158 threads, use the magic number. */
3159 inferior *inf = current_inferior ();
3160 if (inf->pid == 0)
3161 pid = magic_null_ptid.pid ();
3162 else
3163 pid = inf->pid;
3164
3165 if (obuf)
3166 *obuf = pp;
3167 return ptid_t (pid, tid);
3168 }
3169
3170 static int
3171 stubhex (int ch)
3172 {
3173 if (ch >= 'a' && ch <= 'f')
3174 return ch - 'a' + 10;
3175 if (ch >= '0' && ch <= '9')
3176 return ch - '0';
3177 if (ch >= 'A' && ch <= 'F')
3178 return ch - 'A' + 10;
3179 return -1;
3180 }
3181
3182 static int
3183 stub_unpack_int (const char *buff, int fieldlength)
3184 {
3185 int nibble;
3186 int retval = 0;
3187
3188 while (fieldlength)
3189 {
3190 nibble = stubhex (*buff++);
3191 retval |= nibble;
3192 fieldlength--;
3193 if (fieldlength)
3194 retval = retval << 4;
3195 }
3196 return retval;
3197 }
3198
3199 static const char *
3200 unpack_nibble (const char *buf, int *val)
3201 {
3202 *val = fromhex (*buf++);
3203 return buf;
3204 }
3205
3206 static const char *
3207 unpack_byte (const char *buf, int *value)
3208 {
3209 *value = stub_unpack_int (buf, 2);
3210 return buf + 2;
3211 }
3212
3213 static char *
3214 pack_int (char *buf, int value)
3215 {
3216 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3217 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3218 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3219 buf = pack_hex_byte (buf, (value & 0xff));
3220 return buf;
3221 }
3222
3223 static const char *
3224 unpack_int (const char *buf, int *value)
3225 {
3226 *value = stub_unpack_int (buf, 8);
3227 return buf + 8;
3228 }
3229
3230 #if 0 /* Currently unused, uncomment when needed. */
3231 static char *pack_string (char *pkt, char *string);
3232
3233 static char *
3234 pack_string (char *pkt, char *string)
3235 {
3236 char ch;
3237 int len;
3238
3239 len = strlen (string);
3240 if (len > 200)
3241 len = 200; /* Bigger than most GDB packets, junk??? */
3242 pkt = pack_hex_byte (pkt, len);
3243 while (len-- > 0)
3244 {
3245 ch = *string++;
3246 if ((ch == '\0') || (ch == '#'))
3247 ch = '*'; /* Protect encapsulation. */
3248 *pkt++ = ch;
3249 }
3250 return pkt;
3251 }
3252 #endif /* 0 (unused) */
3253
3254 static const char *
3255 unpack_string (const char *src, char *dest, int length)
3256 {
3257 while (length--)
3258 *dest++ = *src++;
3259 *dest = '\0';
3260 return src;
3261 }
3262
3263 static char *
3264 pack_threadid (char *pkt, threadref *id)
3265 {
3266 char *limit;
3267 unsigned char *altid;
3268
3269 altid = (unsigned char *) id;
3270 limit = pkt + BUF_THREAD_ID_SIZE;
3271 while (pkt < limit)
3272 pkt = pack_hex_byte (pkt, *altid++);
3273 return pkt;
3274 }
3275
3276
3277 static const char *
3278 unpack_threadid (const char *inbuf, threadref *id)
3279 {
3280 char *altref;
3281 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3282 int x, y;
3283
3284 altref = (char *) id;
3285
3286 while (inbuf < limit)
3287 {
3288 x = stubhex (*inbuf++);
3289 y = stubhex (*inbuf++);
3290 *altref++ = (x << 4) | y;
3291 }
3292 return inbuf;
3293 }
3294
3295 /* Externally, threadrefs are 64 bits but internally, they are still
3296 ints. This is due to a mismatch of specifications. We would like
3297 to use 64bit thread references internally. This is an adapter
3298 function. */
3299
3300 void
3301 int_to_threadref (threadref *id, int value)
3302 {
3303 unsigned char *scan;
3304
3305 scan = (unsigned char *) id;
3306 {
3307 int i = 4;
3308 while (i--)
3309 *scan++ = 0;
3310 }
3311 *scan++ = (value >> 24) & 0xff;
3312 *scan++ = (value >> 16) & 0xff;
3313 *scan++ = (value >> 8) & 0xff;
3314 *scan++ = (value & 0xff);
3315 }
3316
3317 static int
3318 threadref_to_int (threadref *ref)
3319 {
3320 int i, value = 0;
3321 unsigned char *scan;
3322
3323 scan = *ref;
3324 scan += 4;
3325 i = 4;
3326 while (i-- > 0)
3327 value = (value << 8) | ((*scan++) & 0xff);
3328 return value;
3329 }
3330
3331 static void
3332 copy_threadref (threadref *dest, threadref *src)
3333 {
3334 int i;
3335 unsigned char *csrc, *cdest;
3336
3337 csrc = (unsigned char *) src;
3338 cdest = (unsigned char *) dest;
3339 i = 8;
3340 while (i--)
3341 *cdest++ = *csrc++;
3342 }
3343
3344 static int
3345 threadmatch (threadref *dest, threadref *src)
3346 {
3347 /* Things are broken right now, so just assume we got a match. */
3348 #if 0
3349 unsigned char *srcp, *destp;
3350 int i, result;
3351 srcp = (char *) src;
3352 destp = (char *) dest;
3353
3354 result = 1;
3355 while (i-- > 0)
3356 result &= (*srcp++ == *destp++) ? 1 : 0;
3357 return result;
3358 #endif
3359 return 1;
3360 }
3361
3362 /*
3363 threadid:1, # always request threadid
3364 context_exists:2,
3365 display:4,
3366 unique_name:8,
3367 more_display:16
3368 */
3369
3370 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3371
3372 static char *
3373 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3374 {
3375 *pkt++ = 'q'; /* Info Query */
3376 *pkt++ = 'P'; /* process or thread info */
3377 pkt = pack_int (pkt, mode); /* mode */
3378 pkt = pack_threadid (pkt, id); /* threadid */
3379 *pkt = '\0'; /* terminate */
3380 return pkt;
3381 }
3382
3383 /* These values tag the fields in a thread info response packet. */
3384 /* Tagging the fields allows us to request specific fields and to
3385 add more fields as time goes by. */
3386
3387 #define TAG_THREADID 1 /* Echo the thread identifier. */
3388 #define TAG_EXISTS 2 /* Is this process defined enough to
3389 fetch registers and its stack? */
3390 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3391 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3392 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3393 the process. */
3394
3395 int
3396 remote_target::remote_unpack_thread_info_response (const char *pkt,
3397 threadref *expectedref,
3398 gdb_ext_thread_info *info)
3399 {
3400 struct remote_state *rs = get_remote_state ();
3401 int mask, length;
3402 int tag;
3403 threadref ref;
3404 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3405 int retval = 1;
3406
3407 /* info->threadid = 0; FIXME: implement zero_threadref. */
3408 info->active = 0;
3409 info->display[0] = '\0';
3410 info->shortname[0] = '\0';
3411 info->more_display[0] = '\0';
3412
3413 /* Assume the characters indicating the packet type have been
3414 stripped. */
3415 pkt = unpack_int (pkt, &mask); /* arg mask */
3416 pkt = unpack_threadid (pkt, &ref);
3417
3418 if (mask == 0)
3419 warning (_("Incomplete response to threadinfo request."));
3420 if (!threadmatch (&ref, expectedref))
3421 { /* This is an answer to a different request. */
3422 warning (_("ERROR RMT Thread info mismatch."));
3423 return 0;
3424 }
3425 copy_threadref (&info->threadid, &ref);
3426
3427 /* Loop on tagged fields , try to bail if something goes wrong. */
3428
3429 /* Packets are terminated with nulls. */
3430 while ((pkt < limit) && mask && *pkt)
3431 {
3432 pkt = unpack_int (pkt, &tag); /* tag */
3433 pkt = unpack_byte (pkt, &length); /* length */
3434 if (!(tag & mask)) /* Tags out of synch with mask. */
3435 {
3436 warning (_("ERROR RMT: threadinfo tag mismatch."));
3437 retval = 0;
3438 break;
3439 }
3440 if (tag == TAG_THREADID)
3441 {
3442 if (length != 16)
3443 {
3444 warning (_("ERROR RMT: length of threadid is not 16."));
3445 retval = 0;
3446 break;
3447 }
3448 pkt = unpack_threadid (pkt, &ref);
3449 mask = mask & ~TAG_THREADID;
3450 continue;
3451 }
3452 if (tag == TAG_EXISTS)
3453 {
3454 info->active = stub_unpack_int (pkt, length);
3455 pkt += length;
3456 mask = mask & ~(TAG_EXISTS);
3457 if (length > 8)
3458 {
3459 warning (_("ERROR RMT: 'exists' length too long."));
3460 retval = 0;
3461 break;
3462 }
3463 continue;
3464 }
3465 if (tag == TAG_THREADNAME)
3466 {
3467 pkt = unpack_string (pkt, &info->shortname[0], length);
3468 mask = mask & ~TAG_THREADNAME;
3469 continue;
3470 }
3471 if (tag == TAG_DISPLAY)
3472 {
3473 pkt = unpack_string (pkt, &info->display[0], length);
3474 mask = mask & ~TAG_DISPLAY;
3475 continue;
3476 }
3477 if (tag == TAG_MOREDISPLAY)
3478 {
3479 pkt = unpack_string (pkt, &info->more_display[0], length);
3480 mask = mask & ~TAG_MOREDISPLAY;
3481 continue;
3482 }
3483 warning (_("ERROR RMT: unknown thread info tag."));
3484 break; /* Not a tag we know about. */
3485 }
3486 return retval;
3487 }
3488
3489 int
3490 remote_target::remote_get_threadinfo (threadref *threadid,
3491 int fieldset,
3492 gdb_ext_thread_info *info)
3493 {
3494 struct remote_state *rs = get_remote_state ();
3495 int result;
3496
3497 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3498 putpkt (rs->buf);
3499 getpkt (&rs->buf, 0);
3500
3501 if (rs->buf[0] == '\0')
3502 return 0;
3503
3504 result = remote_unpack_thread_info_response (&rs->buf[2],
3505 threadid, info);
3506 return result;
3507 }
3508
3509 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3510
3511 static char *
3512 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3513 threadref *nextthread)
3514 {
3515 *pkt++ = 'q'; /* info query packet */
3516 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3517 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3518 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3519 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3520 *pkt = '\0';
3521 return pkt;
3522 }
3523
3524 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3525
3526 int
3527 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3528 threadref *original_echo,
3529 threadref *resultlist,
3530 int *doneflag)
3531 {
3532 struct remote_state *rs = get_remote_state ();
3533 int count, resultcount, done;
3534
3535 resultcount = 0;
3536 /* Assume the 'q' and 'M chars have been stripped. */
3537 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3538 /* done parse past here */
3539 pkt = unpack_byte (pkt, &count); /* count field */
3540 pkt = unpack_nibble (pkt, &done);
3541 /* The first threadid is the argument threadid. */
3542 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3543 while ((count-- > 0) && (pkt < limit))
3544 {
3545 pkt = unpack_threadid (pkt, resultlist++);
3546 if (resultcount++ >= result_limit)
3547 break;
3548 }
3549 if (doneflag)
3550 *doneflag = done;
3551 return resultcount;
3552 }
3553
3554 /* Fetch the next batch of threads from the remote. Returns -1 if the
3555 qL packet is not supported, 0 on error and 1 on success. */
3556
3557 int
3558 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3559 int result_limit, int *done, int *result_count,
3560 threadref *threadlist)
3561 {
3562 struct remote_state *rs = get_remote_state ();
3563 int result = 1;
3564
3565 /* Truncate result limit to be smaller than the packet size. */
3566 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3567 >= get_remote_packet_size ())
3568 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3569
3570 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3571 nextthread);
3572 putpkt (rs->buf);
3573 getpkt (&rs->buf, 0);
3574 if (rs->buf[0] == '\0')
3575 {
3576 /* Packet not supported. */
3577 return -1;
3578 }
3579
3580 *result_count =
3581 parse_threadlist_response (&rs->buf[2], result_limit,
3582 &rs->echo_nextthread, threadlist, done);
3583
3584 if (!threadmatch (&rs->echo_nextthread, nextthread))
3585 {
3586 /* FIXME: This is a good reason to drop the packet. */
3587 /* Possibly, there is a duplicate response. */
3588 /* Possibilities :
3589 retransmit immediatly - race conditions
3590 retransmit after timeout - yes
3591 exit
3592 wait for packet, then exit
3593 */
3594 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3595 return 0; /* I choose simply exiting. */
3596 }
3597 if (*result_count <= 0)
3598 {
3599 if (*done != 1)
3600 {
3601 warning (_("RMT ERROR : failed to get remote thread list."));
3602 result = 0;
3603 }
3604 return result; /* break; */
3605 }
3606 if (*result_count > result_limit)
3607 {
3608 *result_count = 0;
3609 warning (_("RMT ERROR: threadlist response longer than requested."));
3610 return 0;
3611 }
3612 return result;
3613 }
3614
3615 /* Fetch the list of remote threads, with the qL packet, and call
3616 STEPFUNCTION for each thread found. Stops iterating and returns 1
3617 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3618 STEPFUNCTION returns false. If the packet is not supported,
3619 returns -1. */
3620
3621 int
3622 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3623 void *context, int looplimit)
3624 {
3625 struct remote_state *rs = get_remote_state ();
3626 int done, i, result_count;
3627 int startflag = 1;
3628 int result = 1;
3629 int loopcount = 0;
3630
3631 done = 0;
3632 while (!done)
3633 {
3634 if (loopcount++ > looplimit)
3635 {
3636 result = 0;
3637 warning (_("Remote fetch threadlist -infinite loop-."));
3638 break;
3639 }
3640 result = remote_get_threadlist (startflag, &rs->nextthread,
3641 MAXTHREADLISTRESULTS,
3642 &done, &result_count,
3643 rs->resultthreadlist);
3644 if (result <= 0)
3645 break;
3646 /* Clear for later iterations. */
3647 startflag = 0;
3648 /* Setup to resume next batch of thread references, set nextthread. */
3649 if (result_count >= 1)
3650 copy_threadref (&rs->nextthread,
3651 &rs->resultthreadlist[result_count - 1]);
3652 i = 0;
3653 while (result_count--)
3654 {
3655 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3656 {
3657 result = 0;
3658 break;
3659 }
3660 }
3661 }
3662 return result;
3663 }
3664
3665 /* A thread found on the remote target. */
3666
3667 struct thread_item
3668 {
3669 explicit thread_item (ptid_t ptid_)
3670 : ptid (ptid_)
3671 {}
3672
3673 thread_item (thread_item &&other) = default;
3674 thread_item &operator= (thread_item &&other) = default;
3675
3676 DISABLE_COPY_AND_ASSIGN (thread_item);
3677
3678 /* The thread's PTID. */
3679 ptid_t ptid;
3680
3681 /* The thread's extra info. */
3682 std::string extra;
3683
3684 /* The thread's name. */
3685 std::string name;
3686
3687 /* The core the thread was running on. -1 if not known. */
3688 int core = -1;
3689
3690 /* The thread handle associated with the thread. */
3691 gdb::byte_vector thread_handle;
3692 };
3693
3694 /* Context passed around to the various methods listing remote
3695 threads. As new threads are found, they're added to the ITEMS
3696 vector. */
3697
3698 struct threads_listing_context
3699 {
3700 /* Return true if this object contains an entry for a thread with ptid
3701 PTID. */
3702
3703 bool contains_thread (ptid_t ptid) const
3704 {
3705 auto match_ptid = [&] (const thread_item &item)
3706 {
3707 return item.ptid == ptid;
3708 };
3709
3710 auto it = std::find_if (this->items.begin (),
3711 this->items.end (),
3712 match_ptid);
3713
3714 return it != this->items.end ();
3715 }
3716
3717 /* Remove the thread with ptid PTID. */
3718
3719 void remove_thread (ptid_t ptid)
3720 {
3721 auto match_ptid = [&] (const thread_item &item)
3722 {
3723 return item.ptid == ptid;
3724 };
3725
3726 auto it = std::remove_if (this->items.begin (),
3727 this->items.end (),
3728 match_ptid);
3729
3730 if (it != this->items.end ())
3731 this->items.erase (it);
3732 }
3733
3734 /* The threads found on the remote target. */
3735 std::vector<thread_item> items;
3736 };
3737
3738 static int
3739 remote_newthread_step (threadref *ref, void *data)
3740 {
3741 struct threads_listing_context *context
3742 = (struct threads_listing_context *) data;
3743 int pid = inferior_ptid.pid ();
3744 int lwp = threadref_to_int (ref);
3745 ptid_t ptid (pid, lwp);
3746
3747 context->items.emplace_back (ptid);
3748
3749 return 1; /* continue iterator */
3750 }
3751
3752 #define CRAZY_MAX_THREADS 1000
3753
3754 ptid_t
3755 remote_target::remote_current_thread (ptid_t oldpid)
3756 {
3757 struct remote_state *rs = get_remote_state ();
3758
3759 putpkt ("qC");
3760 getpkt (&rs->buf, 0);
3761 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3762 {
3763 const char *obuf;
3764 ptid_t result;
3765
3766 result = read_ptid (&rs->buf[2], &obuf);
3767 if (*obuf != '\0')
3768 remote_debug_printf ("warning: garbage in qC reply");
3769
3770 return result;
3771 }
3772 else
3773 return oldpid;
3774 }
3775
3776 /* List remote threads using the deprecated qL packet. */
3777
3778 int
3779 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3780 {
3781 if (remote_threadlist_iterator (remote_newthread_step, context,
3782 CRAZY_MAX_THREADS) >= 0)
3783 return 1;
3784
3785 return 0;
3786 }
3787
3788 #if defined(HAVE_LIBEXPAT)
3789
3790 static void
3791 start_thread (struct gdb_xml_parser *parser,
3792 const struct gdb_xml_element *element,
3793 void *user_data,
3794 std::vector<gdb_xml_value> &attributes)
3795 {
3796 struct threads_listing_context *data
3797 = (struct threads_listing_context *) user_data;
3798 struct gdb_xml_value *attr;
3799
3800 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3801 ptid_t ptid = read_ptid (id, NULL);
3802
3803 data->items.emplace_back (ptid);
3804 thread_item &item = data->items.back ();
3805
3806 attr = xml_find_attribute (attributes, "core");
3807 if (attr != NULL)
3808 item.core = *(ULONGEST *) attr->value.get ();
3809
3810 attr = xml_find_attribute (attributes, "name");
3811 if (attr != NULL)
3812 item.name = (const char *) attr->value.get ();
3813
3814 attr = xml_find_attribute (attributes, "handle");
3815 if (attr != NULL)
3816 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3817 }
3818
3819 static void
3820 end_thread (struct gdb_xml_parser *parser,
3821 const struct gdb_xml_element *element,
3822 void *user_data, const char *body_text)
3823 {
3824 struct threads_listing_context *data
3825 = (struct threads_listing_context *) user_data;
3826
3827 if (body_text != NULL && *body_text != '\0')
3828 data->items.back ().extra = body_text;
3829 }
3830
3831 const struct gdb_xml_attribute thread_attributes[] = {
3832 { "id", GDB_XML_AF_NONE, NULL, NULL },
3833 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3834 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3835 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3836 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3837 };
3838
3839 const struct gdb_xml_element thread_children[] = {
3840 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3841 };
3842
3843 const struct gdb_xml_element threads_children[] = {
3844 { "thread", thread_attributes, thread_children,
3845 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3846 start_thread, end_thread },
3847 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3848 };
3849
3850 const struct gdb_xml_element threads_elements[] = {
3851 { "threads", NULL, threads_children,
3852 GDB_XML_EF_NONE, NULL, NULL },
3853 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3854 };
3855
3856 #endif
3857
3858 /* List remote threads using qXfer:threads:read. */
3859
3860 int
3861 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
3862 {
3863 #if defined(HAVE_LIBEXPAT)
3864 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3865 {
3866 gdb::optional<gdb::char_vector> xml
3867 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
3868
3869 if (xml && (*xml)[0] != '\0')
3870 {
3871 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3872 threads_elements, xml->data (), context);
3873 }
3874
3875 return 1;
3876 }
3877 #endif
3878
3879 return 0;
3880 }
3881
3882 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3883
3884 int
3885 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
3886 {
3887 struct remote_state *rs = get_remote_state ();
3888
3889 if (rs->use_threadinfo_query)
3890 {
3891 const char *bufp;
3892
3893 putpkt ("qfThreadInfo");
3894 getpkt (&rs->buf, 0);
3895 bufp = rs->buf.data ();
3896 if (bufp[0] != '\0') /* q packet recognized */
3897 {
3898 while (*bufp++ == 'm') /* reply contains one or more TID */
3899 {
3900 do
3901 {
3902 ptid_t ptid = read_ptid (bufp, &bufp);
3903 context->items.emplace_back (ptid);
3904 }
3905 while (*bufp++ == ','); /* comma-separated list */
3906 putpkt ("qsThreadInfo");
3907 getpkt (&rs->buf, 0);
3908 bufp = rs->buf.data ();
3909 }
3910 return 1;
3911 }
3912 else
3913 {
3914 /* Packet not recognized. */
3915 rs->use_threadinfo_query = 0;
3916 }
3917 }
3918
3919 return 0;
3920 }
3921
3922 /* Return true if INF only has one non-exited thread. */
3923
3924 static bool
3925 has_single_non_exited_thread (inferior *inf)
3926 {
3927 int count = 0;
3928 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
3929 if (++count > 1)
3930 break;
3931 return count == 1;
3932 }
3933
3934 /* Implement the to_update_thread_list function for the remote
3935 targets. */
3936
3937 void
3938 remote_target::update_thread_list ()
3939 {
3940 struct threads_listing_context context;
3941 int got_list = 0;
3942
3943 /* We have a few different mechanisms to fetch the thread list. Try
3944 them all, starting with the most preferred one first, falling
3945 back to older methods. */
3946 if (remote_get_threads_with_qxfer (&context)
3947 || remote_get_threads_with_qthreadinfo (&context)
3948 || remote_get_threads_with_ql (&context))
3949 {
3950 got_list = 1;
3951
3952 if (context.items.empty ()
3953 && remote_thread_always_alive (inferior_ptid))
3954 {
3955 /* Some targets don't really support threads, but still
3956 reply an (empty) thread list in response to the thread
3957 listing packets, instead of replying "packet not
3958 supported". Exit early so we don't delete the main
3959 thread. */
3960 return;
3961 }
3962
3963 /* CONTEXT now holds the current thread list on the remote
3964 target end. Delete GDB-side threads no longer found on the
3965 target. */
3966 for (thread_info *tp : all_threads_safe ())
3967 {
3968 if (tp->inf->process_target () != this)
3969 continue;
3970
3971 if (!context.contains_thread (tp->ptid))
3972 {
3973 /* Do not remove the thread if it is the last thread in
3974 the inferior. This situation happens when we have a
3975 pending exit process status to process. Otherwise we
3976 may end up with a seemingly live inferior (i.e. pid
3977 != 0) that has no threads. */
3978 if (has_single_non_exited_thread (tp->inf))
3979 continue;
3980
3981 /* Not found. */
3982 delete_thread (tp);
3983 }
3984 }
3985
3986 /* Remove any unreported fork child threads from CONTEXT so
3987 that we don't interfere with follow fork, which is where
3988 creation of such threads is handled. */
3989 remove_new_fork_children (&context);
3990
3991 /* And now add threads we don't know about yet to our list. */
3992 for (thread_item &item : context.items)
3993 {
3994 if (item.ptid != null_ptid)
3995 {
3996 /* In non-stop mode, we assume new found threads are
3997 executing until proven otherwise with a stop reply.
3998 In all-stop, we can only get here if all threads are
3999 stopped. */
4000 bool executing = target_is_non_stop_p ();
4001
4002 remote_notice_new_inferior (item.ptid, executing);
4003
4004 thread_info *tp = find_thread_ptid (this, item.ptid);
4005 remote_thread_info *info = get_remote_thread_info (tp);
4006 info->core = item.core;
4007 info->extra = std::move (item.extra);
4008 info->name = std::move (item.name);
4009 info->thread_handle = std::move (item.thread_handle);
4010 }
4011 }
4012 }
4013
4014 if (!got_list)
4015 {
4016 /* If no thread listing method is supported, then query whether
4017 each known thread is alive, one by one, with the T packet.
4018 If the target doesn't support threads at all, then this is a
4019 no-op. See remote_thread_alive. */
4020 prune_threads ();
4021 }
4022 }
4023
4024 /*
4025 * Collect a descriptive string about the given thread.
4026 * The target may say anything it wants to about the thread
4027 * (typically info about its blocked / runnable state, name, etc.).
4028 * This string will appear in the info threads display.
4029 *
4030 * Optional: targets are not required to implement this function.
4031 */
4032
4033 const char *
4034 remote_target::extra_thread_info (thread_info *tp)
4035 {
4036 struct remote_state *rs = get_remote_state ();
4037 int set;
4038 threadref id;
4039 struct gdb_ext_thread_info threadinfo;
4040
4041 if (rs->remote_desc == 0) /* paranoia */
4042 internal_error (_("remote_threads_extra_info"));
4043
4044 if (tp->ptid == magic_null_ptid
4045 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4046 /* This is the main thread which was added by GDB. The remote
4047 server doesn't know about it. */
4048 return NULL;
4049
4050 std::string &extra = get_remote_thread_info (tp)->extra;
4051
4052 /* If already have cached info, use it. */
4053 if (!extra.empty ())
4054 return extra.c_str ();
4055
4056 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4057 {
4058 /* If we're using qXfer:threads:read, then the extra info is
4059 included in the XML. So if we didn't have anything cached,
4060 it's because there's really no extra info. */
4061 return NULL;
4062 }
4063
4064 if (rs->use_threadextra_query)
4065 {
4066 char *b = rs->buf.data ();
4067 char *endb = b + get_remote_packet_size ();
4068
4069 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4070 b += strlen (b);
4071 write_ptid (b, endb, tp->ptid);
4072
4073 putpkt (rs->buf);
4074 getpkt (&rs->buf, 0);
4075 if (rs->buf[0] != 0)
4076 {
4077 extra.resize (strlen (rs->buf.data ()) / 2);
4078 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4079 return extra.c_str ();
4080 }
4081 }
4082
4083 /* If the above query fails, fall back to the old method. */
4084 rs->use_threadextra_query = 0;
4085 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4086 | TAG_MOREDISPLAY | TAG_DISPLAY;
4087 int_to_threadref (&id, tp->ptid.lwp ());
4088 if (remote_get_threadinfo (&id, set, &threadinfo))
4089 if (threadinfo.active)
4090 {
4091 if (*threadinfo.shortname)
4092 string_appendf (extra, " Name: %s", threadinfo.shortname);
4093 if (*threadinfo.display)
4094 {
4095 if (!extra.empty ())
4096 extra += ',';
4097 string_appendf (extra, " State: %s", threadinfo.display);
4098 }
4099 if (*threadinfo.more_display)
4100 {
4101 if (!extra.empty ())
4102 extra += ',';
4103 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4104 }
4105 return extra.c_str ();
4106 }
4107 return NULL;
4108 }
4109 \f
4110
4111 bool
4112 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4113 struct static_tracepoint_marker *marker)
4114 {
4115 struct remote_state *rs = get_remote_state ();
4116 char *p = rs->buf.data ();
4117
4118 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4119 p += strlen (p);
4120 p += hexnumstr (p, addr);
4121 putpkt (rs->buf);
4122 getpkt (&rs->buf, 0);
4123 p = rs->buf.data ();
4124
4125 if (*p == 'E')
4126 error (_("Remote failure reply: %s"), p);
4127
4128 if (*p++ == 'm')
4129 {
4130 parse_static_tracepoint_marker_definition (p, NULL, marker);
4131 return true;
4132 }
4133
4134 return false;
4135 }
4136
4137 std::vector<static_tracepoint_marker>
4138 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4139 {
4140 struct remote_state *rs = get_remote_state ();
4141 std::vector<static_tracepoint_marker> markers;
4142 const char *p;
4143 static_tracepoint_marker marker;
4144
4145 /* Ask for a first packet of static tracepoint marker
4146 definition. */
4147 putpkt ("qTfSTM");
4148 getpkt (&rs->buf, 0);
4149 p = rs->buf.data ();
4150 if (*p == 'E')
4151 error (_("Remote failure reply: %s"), p);
4152
4153 while (*p++ == 'm')
4154 {
4155 do
4156 {
4157 parse_static_tracepoint_marker_definition (p, &p, &marker);
4158
4159 if (strid == NULL || marker.str_id == strid)
4160 markers.push_back (std::move (marker));
4161 }
4162 while (*p++ == ','); /* comma-separated list */
4163 /* Ask for another packet of static tracepoint definition. */
4164 putpkt ("qTsSTM");
4165 getpkt (&rs->buf, 0);
4166 p = rs->buf.data ();
4167 }
4168
4169 return markers;
4170 }
4171
4172 \f
4173 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4174
4175 ptid_t
4176 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4177 {
4178 return ptid_t (inferior_ptid.pid (), lwp);
4179 }
4180 \f
4181
4182 /* Restart the remote side; this is an extended protocol operation. */
4183
4184 void
4185 remote_target::extended_remote_restart ()
4186 {
4187 struct remote_state *rs = get_remote_state ();
4188
4189 /* Send the restart command; for reasons I don't understand the
4190 remote side really expects a number after the "R". */
4191 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4192 putpkt (rs->buf);
4193
4194 remote_fileio_reset ();
4195 }
4196 \f
4197 /* Clean up connection to a remote debugger. */
4198
4199 void
4200 remote_target::close ()
4201 {
4202 /* Make sure we leave stdin registered in the event loop. */
4203 terminal_ours ();
4204
4205 trace_reset_local_state ();
4206
4207 delete this;
4208 }
4209
4210 remote_target::~remote_target ()
4211 {
4212 struct remote_state *rs = get_remote_state ();
4213
4214 /* Check for NULL because we may get here with a partially
4215 constructed target/connection. */
4216 if (rs->remote_desc == nullptr)
4217 return;
4218
4219 serial_close (rs->remote_desc);
4220
4221 /* We are destroying the remote target, so we should discard
4222 everything of this target. */
4223 discard_pending_stop_replies_in_queue ();
4224
4225 if (rs->remote_async_inferior_event_token)
4226 delete_async_event_handler (&rs->remote_async_inferior_event_token);
4227
4228 delete rs->notif_state;
4229 }
4230
4231 /* Query the remote side for the text, data and bss offsets. */
4232
4233 void
4234 remote_target::get_offsets ()
4235 {
4236 struct remote_state *rs = get_remote_state ();
4237 char *buf;
4238 char *ptr;
4239 int lose, num_segments = 0, do_sections, do_segments;
4240 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4241
4242 if (current_program_space->symfile_object_file == NULL)
4243 return;
4244
4245 putpkt ("qOffsets");
4246 getpkt (&rs->buf, 0);
4247 buf = rs->buf.data ();
4248
4249 if (buf[0] == '\000')
4250 return; /* Return silently. Stub doesn't support
4251 this command. */
4252 if (buf[0] == 'E')
4253 {
4254 warning (_("Remote failure reply: %s"), buf);
4255 return;
4256 }
4257
4258 /* Pick up each field in turn. This used to be done with scanf, but
4259 scanf will make trouble if CORE_ADDR size doesn't match
4260 conversion directives correctly. The following code will work
4261 with any size of CORE_ADDR. */
4262 text_addr = data_addr = bss_addr = 0;
4263 ptr = buf;
4264 lose = 0;
4265
4266 if (startswith (ptr, "Text="))
4267 {
4268 ptr += 5;
4269 /* Don't use strtol, could lose on big values. */
4270 while (*ptr && *ptr != ';')
4271 text_addr = (text_addr << 4) + fromhex (*ptr++);
4272
4273 if (startswith (ptr, ";Data="))
4274 {
4275 ptr += 6;
4276 while (*ptr && *ptr != ';')
4277 data_addr = (data_addr << 4) + fromhex (*ptr++);
4278 }
4279 else
4280 lose = 1;
4281
4282 if (!lose && startswith (ptr, ";Bss="))
4283 {
4284 ptr += 5;
4285 while (*ptr && *ptr != ';')
4286 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4287
4288 if (bss_addr != data_addr)
4289 warning (_("Target reported unsupported offsets: %s"), buf);
4290 }
4291 else
4292 lose = 1;
4293 }
4294 else if (startswith (ptr, "TextSeg="))
4295 {
4296 ptr += 8;
4297 /* Don't use strtol, could lose on big values. */
4298 while (*ptr && *ptr != ';')
4299 text_addr = (text_addr << 4) + fromhex (*ptr++);
4300 num_segments = 1;
4301
4302 if (startswith (ptr, ";DataSeg="))
4303 {
4304 ptr += 9;
4305 while (*ptr && *ptr != ';')
4306 data_addr = (data_addr << 4) + fromhex (*ptr++);
4307 num_segments++;
4308 }
4309 }
4310 else
4311 lose = 1;
4312
4313 if (lose)
4314 error (_("Malformed response to offset query, %s"), buf);
4315 else if (*ptr != '\0')
4316 warning (_("Target reported unsupported offsets: %s"), buf);
4317
4318 objfile *objf = current_program_space->symfile_object_file;
4319 section_offsets offs = objf->section_offsets;
4320
4321 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
4322 do_segments = (data != NULL);
4323 do_sections = num_segments == 0;
4324
4325 if (num_segments > 0)
4326 {
4327 segments[0] = text_addr;
4328 segments[1] = data_addr;
4329 }
4330 /* If we have two segments, we can still try to relocate everything
4331 by assuming that the .text and .data offsets apply to the whole
4332 text and data segments. Convert the offsets given in the packet
4333 to base addresses for symfile_map_offsets_to_segments. */
4334 else if (data != nullptr && data->segments.size () == 2)
4335 {
4336 segments[0] = data->segments[0].base + text_addr;
4337 segments[1] = data->segments[1].base + data_addr;
4338 num_segments = 2;
4339 }
4340 /* If the object file has only one segment, assume that it is text
4341 rather than data; main programs with no writable data are rare,
4342 but programs with no code are useless. Of course the code might
4343 have ended up in the data segment... to detect that we would need
4344 the permissions here. */
4345 else if (data && data->segments.size () == 1)
4346 {
4347 segments[0] = data->segments[0].base + text_addr;
4348 num_segments = 1;
4349 }
4350 /* There's no way to relocate by segment. */
4351 else
4352 do_segments = 0;
4353
4354 if (do_segments)
4355 {
4356 int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
4357 data.get (), offs,
4358 num_segments, segments);
4359
4360 if (ret == 0 && !do_sections)
4361 error (_("Can not handle qOffsets TextSeg "
4362 "response with this symbol file"));
4363
4364 if (ret > 0)
4365 do_sections = 0;
4366 }
4367
4368 if (do_sections)
4369 {
4370 offs[SECT_OFF_TEXT (objf)] = text_addr;
4371
4372 /* This is a temporary kludge to force data and bss to use the
4373 same offsets because that's what nlmconv does now. The real
4374 solution requires changes to the stub and remote.c that I
4375 don't have time to do right now. */
4376
4377 offs[SECT_OFF_DATA (objf)] = data_addr;
4378 offs[SECT_OFF_BSS (objf)] = data_addr;
4379 }
4380
4381 objfile_relocate (objf, offs);
4382 }
4383
4384 /* Send interrupt_sequence to remote target. */
4385
4386 void
4387 remote_target::send_interrupt_sequence ()
4388 {
4389 struct remote_state *rs = get_remote_state ();
4390
4391 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4392 remote_serial_write ("\x03", 1);
4393 else if (interrupt_sequence_mode == interrupt_sequence_break)
4394 serial_send_break (rs->remote_desc);
4395 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4396 {
4397 serial_send_break (rs->remote_desc);
4398 remote_serial_write ("g", 1);
4399 }
4400 else
4401 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
4402 interrupt_sequence_mode);
4403 }
4404
4405
4406 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4407 and extract the PTID. Returns NULL_PTID if not found. */
4408
4409 static ptid_t
4410 stop_reply_extract_thread (const char *stop_reply)
4411 {
4412 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4413 {
4414 const char *p;
4415
4416 /* Txx r:val ; r:val (...) */
4417 p = &stop_reply[3];
4418
4419 /* Look for "register" named "thread". */
4420 while (*p != '\0')
4421 {
4422 const char *p1;
4423
4424 p1 = strchr (p, ':');
4425 if (p1 == NULL)
4426 return null_ptid;
4427
4428 if (strncmp (p, "thread", p1 - p) == 0)
4429 return read_ptid (++p1, &p);
4430
4431 p1 = strchr (p, ';');
4432 if (p1 == NULL)
4433 return null_ptid;
4434 p1++;
4435
4436 p = p1;
4437 }
4438 }
4439
4440 return null_ptid;
4441 }
4442
4443 /* Determine the remote side's current thread. If we have a stop
4444 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4445 "thread" register we can extract the current thread from. If not,
4446 ask the remote which is the current thread with qC. The former
4447 method avoids a roundtrip. */
4448
4449 ptid_t
4450 remote_target::get_current_thread (const char *wait_status)
4451 {
4452 ptid_t ptid = null_ptid;
4453
4454 /* Note we don't use remote_parse_stop_reply as that makes use of
4455 the target architecture, which we haven't yet fully determined at
4456 this point. */
4457 if (wait_status != NULL)
4458 ptid = stop_reply_extract_thread (wait_status);
4459 if (ptid == null_ptid)
4460 ptid = remote_current_thread (inferior_ptid);
4461
4462 return ptid;
4463 }
4464
4465 /* Query the remote target for which is the current thread/process,
4466 add it to our tables, and update INFERIOR_PTID. The caller is
4467 responsible for setting the state such that the remote end is ready
4468 to return the current thread.
4469
4470 This function is called after handling the '?' or 'vRun' packets,
4471 whose response is a stop reply from which we can also try
4472 extracting the thread. If the target doesn't support the explicit
4473 qC query, we infer the current thread from that stop reply, passed
4474 in in WAIT_STATUS, which may be NULL.
4475
4476 The function returns pointer to the main thread of the inferior. */
4477
4478 thread_info *
4479 remote_target::add_current_inferior_and_thread (const char *wait_status)
4480 {
4481 struct remote_state *rs = get_remote_state ();
4482 bool fake_pid_p = false;
4483
4484 switch_to_no_thread ();
4485
4486 /* Now, if we have thread information, update the current thread's
4487 ptid. */
4488 ptid_t curr_ptid = get_current_thread (wait_status);
4489
4490 if (curr_ptid != null_ptid)
4491 {
4492 if (!remote_multi_process_p (rs))
4493 fake_pid_p = true;
4494 }
4495 else
4496 {
4497 /* Without this, some commands which require an active target
4498 (such as kill) won't work. This variable serves (at least)
4499 double duty as both the pid of the target process (if it has
4500 such), and as a flag indicating that a target is active. */
4501 curr_ptid = magic_null_ptid;
4502 fake_pid_p = true;
4503 }
4504
4505 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4506
4507 /* Add the main thread and switch to it. Don't try reading
4508 registers yet, since we haven't fetched the target description
4509 yet. */
4510 thread_info *tp = add_thread_silent (this, curr_ptid);
4511 switch_to_thread_no_regs (tp);
4512
4513 return tp;
4514 }
4515
4516 /* Print info about a thread that was found already stopped on
4517 connection. */
4518
4519 void
4520 remote_target::print_one_stopped_thread (thread_info *thread)
4521 {
4522 target_waitstatus ws;
4523
4524 /* If there is a pending waitstatus, use it. If there isn't it's because
4525 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4526 and process_initial_stop_replies decided it wasn't interesting to save
4527 and report to the core. */
4528 if (thread->has_pending_waitstatus ())
4529 {
4530 ws = thread->pending_waitstatus ();
4531 thread->clear_pending_waitstatus ();
4532 }
4533 else
4534 {
4535 ws.set_stopped (GDB_SIGNAL_0);
4536 }
4537
4538 switch_to_thread (thread);
4539 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4540 set_current_sal_from_frame (get_current_frame ());
4541
4542 /* For "info program". */
4543 set_last_target_status (this, thread->ptid, ws);
4544
4545 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4546 {
4547 enum gdb_signal sig = ws.sig ();
4548
4549 if (signal_print_state (sig))
4550 gdb::observers::signal_received.notify (sig);
4551 }
4552 gdb::observers::normal_stop.notify (NULL, 1);
4553 }
4554
4555 /* Process all initial stop replies the remote side sent in response
4556 to the ? packet. These indicate threads that were already stopped
4557 on initial connection. We mark these threads as stopped and print
4558 their current frame before giving the user the prompt. */
4559
4560 void
4561 remote_target::process_initial_stop_replies (int from_tty)
4562 {
4563 int pending_stop_replies = stop_reply_queue_length ();
4564 struct thread_info *selected = NULL;
4565 struct thread_info *lowest_stopped = NULL;
4566 struct thread_info *first = NULL;
4567
4568 /* This is only used when the target is non-stop. */
4569 gdb_assert (target_is_non_stop_p ());
4570
4571 /* Consume the initial pending events. */
4572 while (pending_stop_replies-- > 0)
4573 {
4574 ptid_t waiton_ptid = minus_one_ptid;
4575 ptid_t event_ptid;
4576 struct target_waitstatus ws;
4577 int ignore_event = 0;
4578
4579 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4580 if (remote_debug)
4581 print_target_wait_results (waiton_ptid, event_ptid, ws);
4582
4583 switch (ws.kind ())
4584 {
4585 case TARGET_WAITKIND_IGNORE:
4586 case TARGET_WAITKIND_NO_RESUMED:
4587 case TARGET_WAITKIND_SIGNALLED:
4588 case TARGET_WAITKIND_EXITED:
4589 /* We shouldn't see these, but if we do, just ignore. */
4590 remote_debug_printf ("event ignored");
4591 ignore_event = 1;
4592 break;
4593
4594 default:
4595 break;
4596 }
4597
4598 if (ignore_event)
4599 continue;
4600
4601 thread_info *evthread = find_thread_ptid (this, event_ptid);
4602
4603 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4604 {
4605 enum gdb_signal sig = ws.sig ();
4606
4607 /* Stubs traditionally report SIGTRAP as initial signal,
4608 instead of signal 0. Suppress it. */
4609 if (sig == GDB_SIGNAL_TRAP)
4610 sig = GDB_SIGNAL_0;
4611 evthread->set_stop_signal (sig);
4612 ws.set_stopped (sig);
4613 }
4614
4615 if (ws.kind () != TARGET_WAITKIND_STOPPED
4616 || ws.sig () != GDB_SIGNAL_0)
4617 evthread->set_pending_waitstatus (ws);
4618
4619 set_executing (this, event_ptid, false);
4620 set_running (this, event_ptid, false);
4621 get_remote_thread_info (evthread)->set_not_resumed ();
4622 }
4623
4624 /* "Notice" the new inferiors before anything related to
4625 registers/memory. */
4626 for (inferior *inf : all_non_exited_inferiors (this))
4627 {
4628 inf->needs_setup = 1;
4629
4630 if (non_stop)
4631 {
4632 thread_info *thread = any_live_thread_of_inferior (inf);
4633 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4634 from_tty);
4635 }
4636 }
4637
4638 /* If all-stop on top of non-stop, pause all threads. Note this
4639 records the threads' stop pc, so must be done after "noticing"
4640 the inferiors. */
4641 if (!non_stop)
4642 {
4643 {
4644 /* At this point, the remote target is not async. It needs to be for
4645 the poll in stop_all_threads to consider events from it, so enable
4646 it temporarily. */
4647 gdb_assert (!this->is_async_p ());
4648 SCOPE_EXIT { target_async (false); };
4649 target_async (true);
4650 stop_all_threads ("remote connect in all-stop");
4651 }
4652
4653 /* If all threads of an inferior were already stopped, we
4654 haven't setup the inferior yet. */
4655 for (inferior *inf : all_non_exited_inferiors (this))
4656 {
4657 if (inf->needs_setup)
4658 {
4659 thread_info *thread = any_live_thread_of_inferior (inf);
4660 switch_to_thread_no_regs (thread);
4661 setup_inferior (0);
4662 }
4663 }
4664 }
4665
4666 /* Now go over all threads that are stopped, and print their current
4667 frame. If all-stop, then if there's a signalled thread, pick
4668 that as current. */
4669 for (thread_info *thread : all_non_exited_threads (this))
4670 {
4671 if (first == NULL)
4672 first = thread;
4673
4674 if (!non_stop)
4675 thread->set_running (false);
4676 else if (thread->state != THREAD_STOPPED)
4677 continue;
4678
4679 if (selected == nullptr && thread->has_pending_waitstatus ())
4680 selected = thread;
4681
4682 if (lowest_stopped == NULL
4683 || thread->inf->num < lowest_stopped->inf->num
4684 || thread->per_inf_num < lowest_stopped->per_inf_num)
4685 lowest_stopped = thread;
4686
4687 if (non_stop)
4688 print_one_stopped_thread (thread);
4689 }
4690
4691 /* In all-stop, we only print the status of one thread, and leave
4692 others with their status pending. */
4693 if (!non_stop)
4694 {
4695 thread_info *thread = selected;
4696 if (thread == NULL)
4697 thread = lowest_stopped;
4698 if (thread == NULL)
4699 thread = first;
4700
4701 print_one_stopped_thread (thread);
4702 }
4703 }
4704
4705 /* Mark a remote_target as marking (by setting the starting_up flag within
4706 its remote_state) for the lifetime of this object. The reference count
4707 on the remote target is temporarily incremented, to prevent the target
4708 being deleted under our feet. */
4709
4710 struct scoped_mark_target_starting
4711 {
4712 /* Constructor, TARGET is the target to be marked as starting, its
4713 reference count will be incremented. */
4714 scoped_mark_target_starting (remote_target *target)
4715 : m_remote_target (target)
4716 {
4717 m_remote_target->incref ();
4718 remote_state *rs = m_remote_target->get_remote_state ();
4719 rs->starting_up = true;
4720 }
4721
4722 /* Destructor, mark the target being worked on as no longer starting, and
4723 decrement the reference count. */
4724 ~scoped_mark_target_starting ()
4725 {
4726 remote_state *rs = m_remote_target->get_remote_state ();
4727 rs->starting_up = false;
4728 decref_target (m_remote_target);
4729 }
4730
4731 private:
4732
4733 /* The target on which we are operating. */
4734 remote_target *m_remote_target;
4735 };
4736
4737 /* Helper for remote_target::start_remote, start the remote connection and
4738 sync state. Return true if everything goes OK, otherwise, return false.
4739 This function exists so that the scoped_restore created within it will
4740 expire before we return to remote_target::start_remote. */
4741
4742 bool
4743 remote_target::start_remote_1 (int from_tty, int extended_p)
4744 {
4745 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4746
4747 struct remote_state *rs = get_remote_state ();
4748 struct packet_config *noack_config;
4749
4750 /* Signal other parts that we're going through the initial setup,
4751 and so things may not be stable yet. E.g., we don't try to
4752 install tracepoints until we've relocated symbols. Also, a
4753 Ctrl-C before we're connected and synced up can't interrupt the
4754 target. Instead, it offers to drop the (potentially wedged)
4755 connection. */
4756 scoped_mark_target_starting target_is_starting (this);
4757
4758 QUIT;
4759
4760 if (interrupt_on_connect)
4761 send_interrupt_sequence ();
4762
4763 /* Ack any packet which the remote side has already sent. */
4764 remote_serial_write ("+", 1);
4765
4766 /* The first packet we send to the target is the optional "supported
4767 packets" request. If the target can answer this, it will tell us
4768 which later probes to skip. */
4769 remote_query_supported ();
4770
4771 /* If the stub wants to get a QAllow, compose one and send it. */
4772 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4773 set_permissions ();
4774
4775 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4776 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4777 as a reply to known packet. For packet "vFile:setfs:" it is an
4778 invalid reply and GDB would return error in
4779 remote_hostio_set_filesystem, making remote files access impossible.
4780 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4781 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4782 {
4783 const char v_mustreplyempty[] = "vMustReplyEmpty";
4784
4785 putpkt (v_mustreplyempty);
4786 getpkt (&rs->buf, 0);
4787 if (strcmp (rs->buf.data (), "OK") == 0)
4788 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4789 else if (strcmp (rs->buf.data (), "") != 0)
4790 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4791 rs->buf.data ());
4792 }
4793
4794 /* Next, we possibly activate noack mode.
4795
4796 If the QStartNoAckMode packet configuration is set to AUTO,
4797 enable noack mode if the stub reported a wish for it with
4798 qSupported.
4799
4800 If set to TRUE, then enable noack mode even if the stub didn't
4801 report it in qSupported. If the stub doesn't reply OK, the
4802 session ends with an error.
4803
4804 If FALSE, then don't activate noack mode, regardless of what the
4805 stub claimed should be the default with qSupported. */
4806
4807 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4808 if (packet_config_support (noack_config) != PACKET_DISABLE)
4809 {
4810 putpkt ("QStartNoAckMode");
4811 getpkt (&rs->buf, 0);
4812 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4813 rs->noack_mode = 1;
4814 }
4815
4816 if (extended_p)
4817 {
4818 /* Tell the remote that we are using the extended protocol. */
4819 putpkt ("!");
4820 getpkt (&rs->buf, 0);
4821 }
4822
4823 /* Let the target know which signals it is allowed to pass down to
4824 the program. */
4825 update_signals_program_target ();
4826
4827 /* Next, if the target can specify a description, read it. We do
4828 this before anything involving memory or registers. */
4829 target_find_description ();
4830
4831 /* Next, now that we know something about the target, update the
4832 address spaces in the program spaces. */
4833 update_address_spaces ();
4834
4835 /* On OSs where the list of libraries is global to all
4836 processes, we fetch them early. */
4837 if (gdbarch_has_global_solist (target_gdbarch ()))
4838 solib_add (NULL, from_tty, auto_solib_add);
4839
4840 if (target_is_non_stop_p ())
4841 {
4842 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4843 error (_("Non-stop mode requested, but remote "
4844 "does not support non-stop"));
4845
4846 putpkt ("QNonStop:1");
4847 getpkt (&rs->buf, 0);
4848
4849 if (strcmp (rs->buf.data (), "OK") != 0)
4850 error (_("Remote refused setting non-stop mode with: %s"),
4851 rs->buf.data ());
4852
4853 /* Find about threads and processes the stub is already
4854 controlling. We default to adding them in the running state.
4855 The '?' query below will then tell us about which threads are
4856 stopped. */
4857 this->update_thread_list ();
4858 }
4859 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4860 {
4861 /* Don't assume that the stub can operate in all-stop mode.
4862 Request it explicitly. */
4863 putpkt ("QNonStop:0");
4864 getpkt (&rs->buf, 0);
4865
4866 if (strcmp (rs->buf.data (), "OK") != 0)
4867 error (_("Remote refused setting all-stop mode with: %s"),
4868 rs->buf.data ());
4869 }
4870
4871 /* Upload TSVs regardless of whether the target is running or not. The
4872 remote stub, such as GDBserver, may have some predefined or builtin
4873 TSVs, even if the target is not running. */
4874 if (get_trace_status (current_trace_status ()) != -1)
4875 {
4876 struct uploaded_tsv *uploaded_tsvs = NULL;
4877
4878 upload_trace_state_variables (&uploaded_tsvs);
4879 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4880 }
4881
4882 /* Check whether the target is running now. */
4883 putpkt ("?");
4884 getpkt (&rs->buf, 0);
4885
4886 if (!target_is_non_stop_p ())
4887 {
4888 char *wait_status = NULL;
4889
4890 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4891 {
4892 if (!extended_p)
4893 error (_("The target is not running (try extended-remote?)"));
4894 return false;
4895 }
4896 else
4897 {
4898 /* Save the reply for later. */
4899 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
4900 strcpy (wait_status, rs->buf.data ());
4901 }
4902
4903 /* Fetch thread list. */
4904 target_update_thread_list ();
4905
4906 /* Let the stub know that we want it to return the thread. */
4907 set_continue_thread (minus_one_ptid);
4908
4909 if (thread_count (this) == 0)
4910 {
4911 /* Target has no concept of threads at all. GDB treats
4912 non-threaded target as single-threaded; add a main
4913 thread. */
4914 thread_info *tp = add_current_inferior_and_thread (wait_status);
4915 get_remote_thread_info (tp)->set_resumed ();
4916 }
4917 else
4918 {
4919 /* We have thread information; select the thread the target
4920 says should be current. If we're reconnecting to a
4921 multi-threaded program, this will ideally be the thread
4922 that last reported an event before GDB disconnected. */
4923 ptid_t curr_thread = get_current_thread (wait_status);
4924 if (curr_thread == null_ptid)
4925 {
4926 /* Odd... The target was able to list threads, but not
4927 tell us which thread was current (no "thread"
4928 register in T stop reply?). Just pick the first
4929 thread in the thread list then. */
4930
4931 remote_debug_printf ("warning: couldn't determine remote "
4932 "current thread; picking first in list.");
4933
4934 for (thread_info *tp : all_non_exited_threads (this,
4935 minus_one_ptid))
4936 {
4937 switch_to_thread (tp);
4938 break;
4939 }
4940 }
4941 else
4942 switch_to_thread (find_thread_ptid (this, curr_thread));
4943 }
4944
4945 /* init_wait_for_inferior should be called before get_offsets in order
4946 to manage `inserted' flag in bp loc in a correct state.
4947 breakpoint_init_inferior, called from init_wait_for_inferior, set
4948 `inserted' flag to 0, while before breakpoint_re_set, called from
4949 start_remote, set `inserted' flag to 1. In the initialization of
4950 inferior, breakpoint_init_inferior should be called first, and then
4951 breakpoint_re_set can be called. If this order is broken, state of
4952 `inserted' flag is wrong, and cause some problems on breakpoint
4953 manipulation. */
4954 init_wait_for_inferior ();
4955
4956 get_offsets (); /* Get text, data & bss offsets. */
4957
4958 /* If we could not find a description using qXfer, and we know
4959 how to do it some other way, try again. This is not
4960 supported for non-stop; it could be, but it is tricky if
4961 there are no stopped threads when we connect. */
4962 if (remote_read_description_p (this)
4963 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4964 {
4965 target_clear_description ();
4966 target_find_description ();
4967 }
4968
4969 /* Use the previously fetched status. */
4970 gdb_assert (wait_status != NULL);
4971 struct notif_event *reply
4972 = remote_notif_parse (this, &notif_client_stop, wait_status);
4973 push_stop_reply ((struct stop_reply *) reply);
4974
4975 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
4976 }
4977 else
4978 {
4979 /* Clear WFI global state. Do this before finding about new
4980 threads and inferiors, and setting the current inferior.
4981 Otherwise we would clear the proceed status of the current
4982 inferior when we want its stop_soon state to be preserved
4983 (see notice_new_inferior). */
4984 init_wait_for_inferior ();
4985
4986 /* In non-stop, we will either get an "OK", meaning that there
4987 are no stopped threads at this time; or, a regular stop
4988 reply. In the latter case, there may be more than one thread
4989 stopped --- we pull them all out using the vStopped
4990 mechanism. */
4991 if (strcmp (rs->buf.data (), "OK") != 0)
4992 {
4993 struct notif_client *notif = &notif_client_stop;
4994
4995 /* remote_notif_get_pending_replies acks this one, and gets
4996 the rest out. */
4997 rs->notif_state->pending_event[notif_client_stop.id]
4998 = remote_notif_parse (this, notif, rs->buf.data ());
4999 remote_notif_get_pending_events (notif);
5000 }
5001
5002 if (thread_count (this) == 0)
5003 {
5004 if (!extended_p)
5005 error (_("The target is not running (try extended-remote?)"));
5006 return false;
5007 }
5008
5009 /* Report all signals during attach/startup. */
5010 pass_signals ({});
5011
5012 /* If there are already stopped threads, mark them stopped and
5013 report their stops before giving the prompt to the user. */
5014 process_initial_stop_replies (from_tty);
5015
5016 if (target_can_async_p ())
5017 target_async (true);
5018 }
5019
5020 /* Give the target a chance to look up symbols. */
5021 for (inferior *inf : all_inferiors (this))
5022 {
5023 /* The inferiors that exist at this point were created from what
5024 was found already running on the remote side, so we know they
5025 have execution. */
5026 gdb_assert (this->has_execution (inf));
5027
5028 /* No use without a symbol-file. */
5029 if (inf->pspace->symfile_object_file == nullptr)
5030 continue;
5031
5032 /* Need to switch to a specific thread, because remote_check_symbols
5033 uses INFERIOR_PTID to set the general thread. */
5034 scoped_restore_current_thread restore_thread;
5035 thread_info *thread = any_thread_of_inferior (inf);
5036 switch_to_thread (thread);
5037 this->remote_check_symbols ();
5038 }
5039
5040 /* Possibly the target has been engaged in a trace run started
5041 previously; find out where things are at. */
5042 if (get_trace_status (current_trace_status ()) != -1)
5043 {
5044 struct uploaded_tp *uploaded_tps = NULL;
5045
5046 if (current_trace_status ()->running)
5047 gdb_printf (_("Trace is already running on the target.\n"));
5048
5049 upload_tracepoints (&uploaded_tps);
5050
5051 merge_uploaded_tracepoints (&uploaded_tps);
5052 }
5053
5054 /* Possibly the target has been engaged in a btrace record started
5055 previously; find out where things are at. */
5056 remote_btrace_maybe_reopen ();
5057
5058 return true;
5059 }
5060
5061 /* Start the remote connection and sync state. */
5062
5063 void
5064 remote_target::start_remote (int from_tty, int extended_p)
5065 {
5066 if (start_remote_1 (from_tty, extended_p)
5067 && breakpoints_should_be_inserted_now ())
5068 insert_breakpoints ();
5069 }
5070
5071 const char *
5072 remote_target::connection_string ()
5073 {
5074 remote_state *rs = get_remote_state ();
5075
5076 if (rs->remote_desc->name != NULL)
5077 return rs->remote_desc->name;
5078 else
5079 return NULL;
5080 }
5081
5082 /* Open a connection to a remote debugger.
5083 NAME is the filename used for communication. */
5084
5085 void
5086 remote_target::open (const char *name, int from_tty)
5087 {
5088 open_1 (name, from_tty, 0);
5089 }
5090
5091 /* Open a connection to a remote debugger using the extended
5092 remote gdb protocol. NAME is the filename used for communication. */
5093
5094 void
5095 extended_remote_target::open (const char *name, int from_tty)
5096 {
5097 open_1 (name, from_tty, 1 /*extended_p */);
5098 }
5099
5100 /* Reset all packets back to "unknown support". Called when opening a
5101 new connection to a remote target. */
5102
5103 static void
5104 reset_all_packet_configs_support (void)
5105 {
5106 int i;
5107
5108 for (i = 0; i < PACKET_MAX; i++)
5109 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5110 }
5111
5112 /* Initialize all packet configs. */
5113
5114 static void
5115 init_all_packet_configs (void)
5116 {
5117 int i;
5118
5119 for (i = 0; i < PACKET_MAX; i++)
5120 {
5121 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5122 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5123 }
5124 }
5125
5126 /* Symbol look-up. */
5127
5128 void
5129 remote_target::remote_check_symbols ()
5130 {
5131 char *tmp;
5132 int end;
5133
5134 /* It doesn't make sense to send a qSymbol packet for an inferior that
5135 doesn't have execution, because the remote side doesn't know about
5136 inferiors without execution. */
5137 gdb_assert (target_has_execution ());
5138
5139 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5140 return;
5141
5142 /* Make sure the remote is pointing at the right process. Note
5143 there's no way to select "no process". */
5144 set_general_process ();
5145
5146 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5147 because we need both at the same time. */
5148 gdb::char_vector msg (get_remote_packet_size ());
5149 gdb::char_vector reply (get_remote_packet_size ());
5150
5151 /* Invite target to request symbol lookups. */
5152
5153 putpkt ("qSymbol::");
5154 getpkt (&reply, 0);
5155 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
5156
5157 while (startswith (reply.data (), "qSymbol:"))
5158 {
5159 struct bound_minimal_symbol sym;
5160
5161 tmp = &reply[8];
5162 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5163 strlen (tmp) / 2);
5164 msg[end] = '\0';
5165 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5166 if (sym.minsym == NULL)
5167 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5168 &reply[8]);
5169 else
5170 {
5171 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5172 CORE_ADDR sym_addr = sym.value_address ();
5173
5174 /* If this is a function address, return the start of code
5175 instead of any data function descriptor. */
5176 sym_addr = gdbarch_convert_from_func_ptr_addr
5177 (target_gdbarch (), sym_addr, current_inferior ()->top_target ());
5178
5179 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5180 phex_nz (sym_addr, addr_size), &reply[8]);
5181 }
5182
5183 putpkt (msg.data ());
5184 getpkt (&reply, 0);
5185 }
5186 }
5187
5188 static struct serial *
5189 remote_serial_open (const char *name)
5190 {
5191 static int udp_warning = 0;
5192
5193 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5194 of in ser-tcp.c, because it is the remote protocol assuming that the
5195 serial connection is reliable and not the serial connection promising
5196 to be. */
5197 if (!udp_warning && startswith (name, "udp:"))
5198 {
5199 warning (_("The remote protocol may be unreliable over UDP.\n"
5200 "Some events may be lost, rendering further debugging "
5201 "impossible."));
5202 udp_warning = 1;
5203 }
5204
5205 return serial_open (name);
5206 }
5207
5208 /* Inform the target of our permission settings. The permission flags
5209 work without this, but if the target knows the settings, it can do
5210 a couple things. First, it can add its own check, to catch cases
5211 that somehow manage to get by the permissions checks in target
5212 methods. Second, if the target is wired to disallow particular
5213 settings (for instance, a system in the field that is not set up to
5214 be able to stop at a breakpoint), it can object to any unavailable
5215 permissions. */
5216
5217 void
5218 remote_target::set_permissions ()
5219 {
5220 struct remote_state *rs = get_remote_state ();
5221
5222 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5223 "WriteReg:%x;WriteMem:%x;"
5224 "InsertBreak:%x;InsertTrace:%x;"
5225 "InsertFastTrace:%x;Stop:%x",
5226 may_write_registers, may_write_memory,
5227 may_insert_breakpoints, may_insert_tracepoints,
5228 may_insert_fast_tracepoints, may_stop);
5229 putpkt (rs->buf);
5230 getpkt (&rs->buf, 0);
5231
5232 /* If the target didn't like the packet, warn the user. Do not try
5233 to undo the user's settings, that would just be maddening. */
5234 if (strcmp (rs->buf.data (), "OK") != 0)
5235 warning (_("Remote refused setting permissions with: %s"),
5236 rs->buf.data ());
5237 }
5238
5239 /* This type describes each known response to the qSupported
5240 packet. */
5241 struct protocol_feature
5242 {
5243 /* The name of this protocol feature. */
5244 const char *name;
5245
5246 /* The default for this protocol feature. */
5247 enum packet_support default_support;
5248
5249 /* The function to call when this feature is reported, or after
5250 qSupported processing if the feature is not supported.
5251 The first argument points to this structure. The second
5252 argument indicates whether the packet requested support be
5253 enabled, disabled, or probed (or the default, if this function
5254 is being called at the end of processing and this feature was
5255 not reported). The third argument may be NULL; if not NULL, it
5256 is a NUL-terminated string taken from the packet following
5257 this feature's name and an equals sign. */
5258 void (*func) (remote_target *remote, const struct protocol_feature *,
5259 enum packet_support, const char *);
5260
5261 /* The corresponding packet for this feature. Only used if
5262 FUNC is remote_supported_packet. */
5263 int packet;
5264 };
5265
5266 static void
5267 remote_supported_packet (remote_target *remote,
5268 const struct protocol_feature *feature,
5269 enum packet_support support,
5270 const char *argument)
5271 {
5272 if (argument)
5273 {
5274 warning (_("Remote qSupported response supplied an unexpected value for"
5275 " \"%s\"."), feature->name);
5276 return;
5277 }
5278
5279 remote_protocol_packets[feature->packet].support = support;
5280 }
5281
5282 void
5283 remote_target::remote_packet_size (const protocol_feature *feature,
5284 enum packet_support support, const char *value)
5285 {
5286 struct remote_state *rs = get_remote_state ();
5287
5288 int packet_size;
5289 char *value_end;
5290
5291 if (support != PACKET_ENABLE)
5292 return;
5293
5294 if (value == NULL || *value == '\0')
5295 {
5296 warning (_("Remote target reported \"%s\" without a size."),
5297 feature->name);
5298 return;
5299 }
5300
5301 errno = 0;
5302 packet_size = strtol (value, &value_end, 16);
5303 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5304 {
5305 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5306 feature->name, value);
5307 return;
5308 }
5309
5310 /* Record the new maximum packet size. */
5311 rs->explicit_packet_size = packet_size;
5312 }
5313
5314 static void
5315 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5316 enum packet_support support, const char *value)
5317 {
5318 remote->remote_packet_size (feature, support, value);
5319 }
5320
5321 static const struct protocol_feature remote_protocol_features[] = {
5322 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5323 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5324 PACKET_qXfer_auxv },
5325 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5326 PACKET_qXfer_exec_file },
5327 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5328 PACKET_qXfer_features },
5329 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5330 PACKET_qXfer_libraries },
5331 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5332 PACKET_qXfer_libraries_svr4 },
5333 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5334 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5335 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5336 PACKET_qXfer_memory_map },
5337 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5338 PACKET_qXfer_osdata },
5339 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5340 PACKET_qXfer_threads },
5341 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5342 PACKET_qXfer_traceframe_info },
5343 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5344 PACKET_QPassSignals },
5345 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5346 PACKET_QCatchSyscalls },
5347 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5348 PACKET_QProgramSignals },
5349 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5350 PACKET_QSetWorkingDir },
5351 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5352 PACKET_QStartupWithShell },
5353 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5354 PACKET_QEnvironmentHexEncoded },
5355 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5356 PACKET_QEnvironmentReset },
5357 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5358 PACKET_QEnvironmentUnset },
5359 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5360 PACKET_QStartNoAckMode },
5361 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5362 PACKET_multiprocess_feature },
5363 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5364 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5365 PACKET_qXfer_siginfo_read },
5366 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5367 PACKET_qXfer_siginfo_write },
5368 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5369 PACKET_ConditionalTracepoints },
5370 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5371 PACKET_ConditionalBreakpoints },
5372 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5373 PACKET_BreakpointCommands },
5374 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5375 PACKET_FastTracepoints },
5376 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5377 PACKET_StaticTracepoints },
5378 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5379 PACKET_InstallInTrace},
5380 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5381 PACKET_DisconnectedTracing_feature },
5382 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5383 PACKET_bc },
5384 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5385 PACKET_bs },
5386 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5387 PACKET_TracepointSource },
5388 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5389 PACKET_QAllow },
5390 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5391 PACKET_EnableDisableTracepoints_feature },
5392 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5393 PACKET_qXfer_fdpic },
5394 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5395 PACKET_qXfer_uib },
5396 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5397 PACKET_QDisableRandomization },
5398 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5399 { "QTBuffer:size", PACKET_DISABLE,
5400 remote_supported_packet, PACKET_QTBuffer_size},
5401 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5402 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5403 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5404 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5405 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5406 PACKET_qXfer_btrace },
5407 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5408 PACKET_qXfer_btrace_conf },
5409 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5410 PACKET_Qbtrace_conf_bts_size },
5411 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5412 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5413 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5414 PACKET_fork_event_feature },
5415 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5416 PACKET_vfork_event_feature },
5417 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5418 PACKET_exec_event_feature },
5419 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5420 PACKET_Qbtrace_conf_pt_size },
5421 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5422 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5423 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5424 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5425 PACKET_memory_tagging_feature },
5426 };
5427
5428 static char *remote_support_xml;
5429
5430 /* Register string appended to "xmlRegisters=" in qSupported query. */
5431
5432 void
5433 register_remote_support_xml (const char *xml)
5434 {
5435 #if defined(HAVE_LIBEXPAT)
5436 if (remote_support_xml == NULL)
5437 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5438 else
5439 {
5440 char *copy = xstrdup (remote_support_xml + 13);
5441 char *saveptr;
5442 char *p = strtok_r (copy, ",", &saveptr);
5443
5444 do
5445 {
5446 if (strcmp (p, xml) == 0)
5447 {
5448 /* already there */
5449 xfree (copy);
5450 return;
5451 }
5452 }
5453 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5454 xfree (copy);
5455
5456 remote_support_xml = reconcat (remote_support_xml,
5457 remote_support_xml, ",", xml,
5458 (char *) NULL);
5459 }
5460 #endif
5461 }
5462
5463 static void
5464 remote_query_supported_append (std::string *msg, const char *append)
5465 {
5466 if (!msg->empty ())
5467 msg->append (";");
5468 msg->append (append);
5469 }
5470
5471 void
5472 remote_target::remote_query_supported ()
5473 {
5474 struct remote_state *rs = get_remote_state ();
5475 char *next;
5476 int i;
5477 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5478
5479 /* The packet support flags are handled differently for this packet
5480 than for most others. We treat an error, a disabled packet, and
5481 an empty response identically: any features which must be reported
5482 to be used will be automatically disabled. An empty buffer
5483 accomplishes this, since that is also the representation for a list
5484 containing no features. */
5485
5486 rs->buf[0] = 0;
5487 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5488 {
5489 std::string q;
5490
5491 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5492 remote_query_supported_append (&q, "multiprocess+");
5493
5494 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5495 remote_query_supported_append (&q, "swbreak+");
5496 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5497 remote_query_supported_append (&q, "hwbreak+");
5498
5499 remote_query_supported_append (&q, "qRelocInsn+");
5500
5501 if (packet_set_cmd_state (PACKET_fork_event_feature)
5502 != AUTO_BOOLEAN_FALSE)
5503 remote_query_supported_append (&q, "fork-events+");
5504 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5505 != AUTO_BOOLEAN_FALSE)
5506 remote_query_supported_append (&q, "vfork-events+");
5507 if (packet_set_cmd_state (PACKET_exec_event_feature)
5508 != AUTO_BOOLEAN_FALSE)
5509 remote_query_supported_append (&q, "exec-events+");
5510
5511 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5512 remote_query_supported_append (&q, "vContSupported+");
5513
5514 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5515 remote_query_supported_append (&q, "QThreadEvents+");
5516
5517 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5518 remote_query_supported_append (&q, "no-resumed+");
5519
5520 if (packet_set_cmd_state (PACKET_memory_tagging_feature)
5521 != AUTO_BOOLEAN_FALSE)
5522 remote_query_supported_append (&q, "memory-tagging+");
5523
5524 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5525 the qSupported:xmlRegisters=i386 handling. */
5526 if (remote_support_xml != NULL
5527 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5528 remote_query_supported_append (&q, remote_support_xml);
5529
5530 q = "qSupported:" + q;
5531 putpkt (q.c_str ());
5532
5533 getpkt (&rs->buf, 0);
5534
5535 /* If an error occured, warn, but do not return - just reset the
5536 buffer to empty and go on to disable features. */
5537 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5538 == PACKET_ERROR)
5539 {
5540 warning (_("Remote failure reply: %s"), rs->buf.data ());
5541 rs->buf[0] = 0;
5542 }
5543 }
5544
5545 memset (seen, 0, sizeof (seen));
5546
5547 next = rs->buf.data ();
5548 while (*next)
5549 {
5550 enum packet_support is_supported;
5551 char *p, *end, *name_end, *value;
5552
5553 /* First separate out this item from the rest of the packet. If
5554 there's another item after this, we overwrite the separator
5555 (terminated strings are much easier to work with). */
5556 p = next;
5557 end = strchr (p, ';');
5558 if (end == NULL)
5559 {
5560 end = p + strlen (p);
5561 next = end;
5562 }
5563 else
5564 {
5565 *end = '\0';
5566 next = end + 1;
5567
5568 if (end == p)
5569 {
5570 warning (_("empty item in \"qSupported\" response"));
5571 continue;
5572 }
5573 }
5574
5575 name_end = strchr (p, '=');
5576 if (name_end)
5577 {
5578 /* This is a name=value entry. */
5579 is_supported = PACKET_ENABLE;
5580 value = name_end + 1;
5581 *name_end = '\0';
5582 }
5583 else
5584 {
5585 value = NULL;
5586 switch (end[-1])
5587 {
5588 case '+':
5589 is_supported = PACKET_ENABLE;
5590 break;
5591
5592 case '-':
5593 is_supported = PACKET_DISABLE;
5594 break;
5595
5596 case '?':
5597 is_supported = PACKET_SUPPORT_UNKNOWN;
5598 break;
5599
5600 default:
5601 warning (_("unrecognized item \"%s\" "
5602 "in \"qSupported\" response"), p);
5603 continue;
5604 }
5605 end[-1] = '\0';
5606 }
5607
5608 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5609 if (strcmp (remote_protocol_features[i].name, p) == 0)
5610 {
5611 const struct protocol_feature *feature;
5612
5613 seen[i] = 1;
5614 feature = &remote_protocol_features[i];
5615 feature->func (this, feature, is_supported, value);
5616 break;
5617 }
5618 }
5619
5620 /* If we increased the packet size, make sure to increase the global
5621 buffer size also. We delay this until after parsing the entire
5622 qSupported packet, because this is the same buffer we were
5623 parsing. */
5624 if (rs->buf.size () < rs->explicit_packet_size)
5625 rs->buf.resize (rs->explicit_packet_size);
5626
5627 /* Handle the defaults for unmentioned features. */
5628 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5629 if (!seen[i])
5630 {
5631 const struct protocol_feature *feature;
5632
5633 feature = &remote_protocol_features[i];
5634 feature->func (this, feature, feature->default_support, NULL);
5635 }
5636 }
5637
5638 /* Serial QUIT handler for the remote serial descriptor.
5639
5640 Defers handling a Ctrl-C until we're done with the current
5641 command/response packet sequence, unless:
5642
5643 - We're setting up the connection. Don't send a remote interrupt
5644 request, as we're not fully synced yet. Quit immediately
5645 instead.
5646
5647 - The target has been resumed in the foreground
5648 (target_terminal::is_ours is false) with a synchronous resume
5649 packet, and we're blocked waiting for the stop reply, thus a
5650 Ctrl-C should be immediately sent to the target.
5651
5652 - We get a second Ctrl-C while still within the same serial read or
5653 write. In that case the serial is seemingly wedged --- offer to
5654 quit/disconnect.
5655
5656 - We see a second Ctrl-C without target response, after having
5657 previously interrupted the target. In that case the target/stub
5658 is probably wedged --- offer to quit/disconnect.
5659 */
5660
5661 void
5662 remote_target::remote_serial_quit_handler ()
5663 {
5664 struct remote_state *rs = get_remote_state ();
5665
5666 if (check_quit_flag ())
5667 {
5668 /* If we're starting up, we're not fully synced yet. Quit
5669 immediately. */
5670 if (rs->starting_up)
5671 quit ();
5672 else if (rs->got_ctrlc_during_io)
5673 {
5674 if (query (_("The target is not responding to GDB commands.\n"
5675 "Stop debugging it? ")))
5676 remote_unpush_and_throw (this);
5677 }
5678 /* If ^C has already been sent once, offer to disconnect. */
5679 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5680 interrupt_query ();
5681 /* All-stop protocol, and blocked waiting for stop reply. Send
5682 an interrupt request. */
5683 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5684 target_interrupt ();
5685 else
5686 rs->got_ctrlc_during_io = 1;
5687 }
5688 }
5689
5690 /* The remote_target that is current while the quit handler is
5691 overridden with remote_serial_quit_handler. */
5692 static remote_target *curr_quit_handler_target;
5693
5694 static void
5695 remote_serial_quit_handler ()
5696 {
5697 curr_quit_handler_target->remote_serial_quit_handler ();
5698 }
5699
5700 /* Remove the remote target from the target stack of each inferior
5701 that is using it. Upper targets depend on it so remove them
5702 first. */
5703
5704 static void
5705 remote_unpush_target (remote_target *target)
5706 {
5707 /* We have to unpush the target from all inferiors, even those that
5708 aren't running. */
5709 scoped_restore_current_inferior restore_current_inferior;
5710
5711 for (inferior *inf : all_inferiors (target))
5712 {
5713 switch_to_inferior_no_thread (inf);
5714 pop_all_targets_at_and_above (process_stratum);
5715 generic_mourn_inferior ();
5716 }
5717
5718 /* Don't rely on target_close doing this when the target is popped
5719 from the last remote inferior above, because something may be
5720 holding a reference to the target higher up on the stack, meaning
5721 target_close won't be called yet. We lost the connection to the
5722 target, so clear these now, otherwise we may later throw
5723 TARGET_CLOSE_ERROR while trying to tell the remote target to
5724 close the file. */
5725 fileio_handles_invalidate_target (target);
5726 }
5727
5728 static void
5729 remote_unpush_and_throw (remote_target *target)
5730 {
5731 remote_unpush_target (target);
5732 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5733 }
5734
5735 void
5736 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5737 {
5738 remote_target *curr_remote = get_current_remote_target ();
5739
5740 if (name == 0)
5741 error (_("To open a remote debug connection, you need to specify what\n"
5742 "serial device is attached to the remote system\n"
5743 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5744
5745 /* If we're connected to a running target, target_preopen will kill it.
5746 Ask this question first, before target_preopen has a chance to kill
5747 anything. */
5748 if (curr_remote != NULL && !target_has_execution ())
5749 {
5750 if (from_tty
5751 && !query (_("Already connected to a remote target. Disconnect? ")))
5752 error (_("Still connected."));
5753 }
5754
5755 /* Here the possibly existing remote target gets unpushed. */
5756 target_preopen (from_tty);
5757
5758 remote_fileio_reset ();
5759 reopen_exec_file ();
5760 reread_symbols (from_tty);
5761
5762 remote_target *remote
5763 = (extended_p ? new extended_remote_target () : new remote_target ());
5764 target_ops_up target_holder (remote);
5765
5766 remote_state *rs = remote->get_remote_state ();
5767
5768 /* See FIXME above. */
5769 if (!target_async_permitted)
5770 rs->wait_forever_enabled_p = 1;
5771
5772 rs->remote_desc = remote_serial_open (name);
5773 if (!rs->remote_desc)
5774 perror_with_name (name);
5775
5776 if (baud_rate != -1)
5777 {
5778 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5779 {
5780 /* The requested speed could not be set. Error out to
5781 top level after closing remote_desc. Take care to
5782 set remote_desc to NULL to avoid closing remote_desc
5783 more than once. */
5784 serial_close (rs->remote_desc);
5785 rs->remote_desc = NULL;
5786 perror_with_name (name);
5787 }
5788 }
5789
5790 serial_setparity (rs->remote_desc, serial_parity);
5791 serial_raw (rs->remote_desc);
5792
5793 /* If there is something sitting in the buffer we might take it as a
5794 response to a command, which would be bad. */
5795 serial_flush_input (rs->remote_desc);
5796
5797 if (from_tty)
5798 {
5799 gdb_puts ("Remote debugging using ");
5800 gdb_puts (name);
5801 gdb_puts ("\n");
5802 }
5803
5804 /* Switch to using the remote target now. */
5805 current_inferior ()->push_target (std::move (target_holder));
5806
5807 /* Register extra event sources in the event loop. */
5808 rs->remote_async_inferior_event_token
5809 = create_async_event_handler (remote_async_inferior_event_handler, nullptr,
5810 "remote");
5811 rs->notif_state = remote_notif_state_allocate (remote);
5812
5813 /* Reset the target state; these things will be queried either by
5814 remote_query_supported or as they are needed. */
5815 reset_all_packet_configs_support ();
5816 rs->explicit_packet_size = 0;
5817 rs->noack_mode = 0;
5818 rs->extended = extended_p;
5819 rs->waiting_for_stop_reply = 0;
5820 rs->ctrlc_pending_p = 0;
5821 rs->got_ctrlc_during_io = 0;
5822
5823 rs->general_thread = not_sent_ptid;
5824 rs->continue_thread = not_sent_ptid;
5825 rs->remote_traceframe_number = -1;
5826
5827 rs->last_resume_exec_dir = EXEC_FORWARD;
5828
5829 /* Probe for ability to use "ThreadInfo" query, as required. */
5830 rs->use_threadinfo_query = 1;
5831 rs->use_threadextra_query = 1;
5832
5833 rs->readahead_cache.invalidate ();
5834
5835 if (target_async_permitted)
5836 {
5837 /* FIXME: cagney/1999-09-23: During the initial connection it is
5838 assumed that the target is already ready and able to respond to
5839 requests. Unfortunately remote_start_remote() eventually calls
5840 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5841 around this. Eventually a mechanism that allows
5842 wait_for_inferior() to expect/get timeouts will be
5843 implemented. */
5844 rs->wait_forever_enabled_p = 0;
5845 }
5846
5847 /* First delete any symbols previously loaded from shared libraries. */
5848 no_shared_libraries (NULL, 0);
5849
5850 /* Start the remote connection. If error() or QUIT, discard this
5851 target (we'd otherwise be in an inconsistent state) and then
5852 propogate the error on up the exception chain. This ensures that
5853 the caller doesn't stumble along blindly assuming that the
5854 function succeeded. The CLI doesn't have this problem but other
5855 UI's, such as MI do.
5856
5857 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5858 this function should return an error indication letting the
5859 caller restore the previous state. Unfortunately the command
5860 ``target remote'' is directly wired to this function making that
5861 impossible. On a positive note, the CLI side of this problem has
5862 been fixed - the function set_cmd_context() makes it possible for
5863 all the ``target ....'' commands to share a common callback
5864 function. See cli-dump.c. */
5865 {
5866
5867 try
5868 {
5869 remote->start_remote (from_tty, extended_p);
5870 }
5871 catch (const gdb_exception &ex)
5872 {
5873 /* Pop the partially set up target - unless something else did
5874 already before throwing the exception. */
5875 if (ex.error != TARGET_CLOSE_ERROR)
5876 remote_unpush_target (remote);
5877 throw;
5878 }
5879 }
5880
5881 remote_btrace_reset (rs);
5882
5883 if (target_async_permitted)
5884 rs->wait_forever_enabled_p = 1;
5885 }
5886
5887 /* Determine if WS represents a fork status. */
5888
5889 static bool
5890 is_fork_status (target_waitkind kind)
5891 {
5892 return (kind == TARGET_WAITKIND_FORKED
5893 || kind == TARGET_WAITKIND_VFORKED);
5894 }
5895
5896 /* Return THREAD's pending status if it is a pending fork parent, else
5897 return nullptr. */
5898
5899 static const target_waitstatus *
5900 thread_pending_fork_status (struct thread_info *thread)
5901 {
5902 const target_waitstatus &ws
5903 = (thread->has_pending_waitstatus ()
5904 ? thread->pending_waitstatus ()
5905 : thread->pending_follow);
5906
5907 if (!is_fork_status (ws.kind ()))
5908 return nullptr;
5909
5910 return &ws;
5911 }
5912
5913 /* Detach the specified process. */
5914
5915 void
5916 remote_target::remote_detach_pid (int pid)
5917 {
5918 struct remote_state *rs = get_remote_state ();
5919
5920 /* This should not be necessary, but the handling for D;PID in
5921 GDBserver versions prior to 8.2 incorrectly assumes that the
5922 selected process points to the same process we're detaching,
5923 leading to misbehavior (and possibly GDBserver crashing) when it
5924 does not. Since it's easy and cheap, work around it by forcing
5925 GDBserver to select GDB's current process. */
5926 set_general_process ();
5927
5928 if (remote_multi_process_p (rs))
5929 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
5930 else
5931 strcpy (rs->buf.data (), "D");
5932
5933 putpkt (rs->buf);
5934 getpkt (&rs->buf, 0);
5935
5936 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5937 ;
5938 else if (rs->buf[0] == '\0')
5939 error (_("Remote doesn't know how to detach"));
5940 else
5941 error (_("Can't detach process."));
5942 }
5943
5944 /* This detaches a program to which we previously attached, using
5945 inferior_ptid to identify the process. After this is done, GDB
5946 can be used to debug some other program. We better not have left
5947 any breakpoints in the target program or it'll die when it hits
5948 one. */
5949
5950 void
5951 remote_target::remote_detach_1 (inferior *inf, int from_tty)
5952 {
5953 int pid = inferior_ptid.pid ();
5954 struct remote_state *rs = get_remote_state ();
5955 int is_fork_parent;
5956
5957 if (!target_has_execution ())
5958 error (_("No process to detach from."));
5959
5960 target_announce_detach (from_tty);
5961
5962 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
5963 {
5964 /* If we're in breakpoints-always-inserted mode, or the inferior
5965 is running, we have to remove breakpoints before detaching.
5966 We don't do this in common code instead because not all
5967 targets support removing breakpoints while the target is
5968 running. The remote target / gdbserver does, though. */
5969 remove_breakpoints_inf (current_inferior ());
5970 }
5971
5972 /* Tell the remote target to detach. */
5973 remote_detach_pid (pid);
5974
5975 /* Exit only if this is the only active inferior. */
5976 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
5977 gdb_puts (_("Ending remote debugging.\n"));
5978
5979 /* See if any thread of the inferior we are detaching has a pending fork
5980 status. In that case, we must detach from the child resulting from
5981 that fork. */
5982 for (thread_info *thread : inf->non_exited_threads ())
5983 {
5984 const target_waitstatus *ws = thread_pending_fork_status (thread);
5985
5986 if (ws == nullptr)
5987 continue;
5988
5989 remote_detach_pid (ws->child_ptid ().pid ());
5990 }
5991
5992 /* Check also for any pending fork events in the stop reply queue. */
5993 remote_notif_get_pending_events (&notif_client_stop);
5994 for (stop_reply_up &reply : rs->stop_reply_queue)
5995 {
5996 if (reply->ptid.pid () != pid)
5997 continue;
5998
5999 if (!is_fork_status (reply->ws.kind ()))
6000 continue;
6001
6002 remote_detach_pid (reply->ws.child_ptid ().pid ());
6003 }
6004
6005 thread_info *tp = find_thread_ptid (this, inferior_ptid);
6006
6007 /* Check to see if we are detaching a fork parent. Note that if we
6008 are detaching a fork child, tp == NULL. */
6009 is_fork_parent = (tp != NULL
6010 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
6011
6012 /* If doing detach-on-fork, we don't mourn, because that will delete
6013 breakpoints that should be available for the followed inferior. */
6014 if (!is_fork_parent)
6015 {
6016 /* Save the pid as a string before mourning, since that will
6017 unpush the remote target, and we need the string after. */
6018 std::string infpid = target_pid_to_str (ptid_t (pid));
6019
6020 target_mourn_inferior (inferior_ptid);
6021 if (print_inferior_events)
6022 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6023 inf->num, infpid.c_str ());
6024 }
6025 else
6026 {
6027 switch_to_no_thread ();
6028 detach_inferior (current_inferior ());
6029 }
6030 }
6031
6032 void
6033 remote_target::detach (inferior *inf, int from_tty)
6034 {
6035 remote_detach_1 (inf, from_tty);
6036 }
6037
6038 void
6039 extended_remote_target::detach (inferior *inf, int from_tty)
6040 {
6041 remote_detach_1 (inf, from_tty);
6042 }
6043
6044 /* Target follow-fork function for remote targets. On entry, and
6045 at return, the current inferior is the fork parent.
6046
6047 Note that although this is currently only used for extended-remote,
6048 it is named remote_follow_fork in anticipation of using it for the
6049 remote target as well. */
6050
6051 void
6052 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6053 target_waitkind fork_kind, bool follow_child,
6054 bool detach_fork)
6055 {
6056 process_stratum_target::follow_fork (child_inf, child_ptid,
6057 fork_kind, follow_child, detach_fork);
6058
6059 struct remote_state *rs = get_remote_state ();
6060
6061 if ((fork_kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
6062 || (fork_kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
6063 {
6064 /* When following the parent and detaching the child, we detach
6065 the child here. For the case of following the child and
6066 detaching the parent, the detach is done in the target-
6067 independent follow fork code in infrun.c. We can't use
6068 target_detach when detaching an unfollowed child because
6069 the client side doesn't know anything about the child. */
6070 if (detach_fork && !follow_child)
6071 {
6072 /* Detach the fork child. */
6073 remote_detach_pid (child_ptid.pid ());
6074 }
6075 }
6076 }
6077
6078 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6079 in the program space of the new inferior. */
6080
6081 void
6082 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6083 const char *execd_pathname)
6084 {
6085 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6086
6087 /* We know that this is a target file name, so if it has the "target:"
6088 prefix we strip it off before saving it in the program space. */
6089 if (is_target_filename (execd_pathname))
6090 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6091
6092 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6093 }
6094
6095 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6096
6097 void
6098 remote_target::disconnect (const char *args, int from_tty)
6099 {
6100 if (args)
6101 error (_("Argument given to \"disconnect\" when remotely debugging."));
6102
6103 /* Make sure we unpush even the extended remote targets. Calling
6104 target_mourn_inferior won't unpush, and
6105 remote_target::mourn_inferior won't unpush if there is more than
6106 one inferior left. */
6107 remote_unpush_target (this);
6108
6109 if (from_tty)
6110 gdb_puts ("Ending remote debugging.\n");
6111 }
6112
6113 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6114 be chatty about it. */
6115
6116 void
6117 extended_remote_target::attach (const char *args, int from_tty)
6118 {
6119 struct remote_state *rs = get_remote_state ();
6120 int pid;
6121 char *wait_status = NULL;
6122
6123 pid = parse_pid_to_attach (args);
6124
6125 /* Remote PID can be freely equal to getpid, do not check it here the same
6126 way as in other targets. */
6127
6128 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
6129 error (_("This target does not support attaching to a process"));
6130
6131 target_announce_attach (from_tty, pid);
6132
6133 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6134 putpkt (rs->buf);
6135 getpkt (&rs->buf, 0);
6136
6137 switch (packet_ok (rs->buf,
6138 &remote_protocol_packets[PACKET_vAttach]))
6139 {
6140 case PACKET_OK:
6141 if (!target_is_non_stop_p ())
6142 {
6143 /* Save the reply for later. */
6144 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6145 strcpy (wait_status, rs->buf.data ());
6146 }
6147 else if (strcmp (rs->buf.data (), "OK") != 0)
6148 error (_("Attaching to %s failed with: %s"),
6149 target_pid_to_str (ptid_t (pid)).c_str (),
6150 rs->buf.data ());
6151 break;
6152 case PACKET_UNKNOWN:
6153 error (_("This target does not support attaching to a process"));
6154 default:
6155 error (_("Attaching to %s failed"),
6156 target_pid_to_str (ptid_t (pid)).c_str ());
6157 }
6158
6159 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6160
6161 inferior_ptid = ptid_t (pid);
6162
6163 if (target_is_non_stop_p ())
6164 {
6165 /* Get list of threads. */
6166 update_thread_list ();
6167
6168 thread_info *thread = first_thread_of_inferior (current_inferior ());
6169 if (thread != nullptr)
6170 switch_to_thread (thread);
6171
6172 /* Invalidate our notion of the remote current thread. */
6173 record_currthread (rs, minus_one_ptid);
6174 }
6175 else
6176 {
6177 /* Now, if we have thread information, update the main thread's
6178 ptid. */
6179 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6180
6181 /* Add the main thread to the thread list. We add the thread
6182 silently in this case (the final true parameter). */
6183 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
6184
6185 switch_to_thread (thr);
6186 }
6187
6188 /* Next, if the target can specify a description, read it. We do
6189 this before anything involving memory or registers. */
6190 target_find_description ();
6191
6192 if (!target_is_non_stop_p ())
6193 {
6194 /* Use the previously fetched status. */
6195 gdb_assert (wait_status != NULL);
6196
6197 struct notif_event *reply
6198 = remote_notif_parse (this, &notif_client_stop, wait_status);
6199
6200 push_stop_reply ((struct stop_reply *) reply);
6201 }
6202 else
6203 {
6204 gdb_assert (wait_status == NULL);
6205
6206 gdb_assert (target_can_async_p ());
6207 }
6208 }
6209
6210 /* Implementation of the to_post_attach method. */
6211
6212 void
6213 extended_remote_target::post_attach (int pid)
6214 {
6215 /* Get text, data & bss offsets. */
6216 get_offsets ();
6217
6218 /* In certain cases GDB might not have had the chance to start
6219 symbol lookup up until now. This could happen if the debugged
6220 binary is not using shared libraries, the vsyscall page is not
6221 present (on Linux) and the binary itself hadn't changed since the
6222 debugging process was started. */
6223 if (current_program_space->symfile_object_file != NULL)
6224 remote_check_symbols();
6225 }
6226
6227 \f
6228 /* Check for the availability of vCont. This function should also check
6229 the response. */
6230
6231 void
6232 remote_target::remote_vcont_probe ()
6233 {
6234 remote_state *rs = get_remote_state ();
6235 char *buf;
6236
6237 strcpy (rs->buf.data (), "vCont?");
6238 putpkt (rs->buf);
6239 getpkt (&rs->buf, 0);
6240 buf = rs->buf.data ();
6241
6242 /* Make sure that the features we assume are supported. */
6243 if (startswith (buf, "vCont"))
6244 {
6245 char *p = &buf[5];
6246 int support_c, support_C;
6247
6248 rs->supports_vCont.s = 0;
6249 rs->supports_vCont.S = 0;
6250 support_c = 0;
6251 support_C = 0;
6252 rs->supports_vCont.t = 0;
6253 rs->supports_vCont.r = 0;
6254 while (p && *p == ';')
6255 {
6256 p++;
6257 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6258 rs->supports_vCont.s = 1;
6259 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6260 rs->supports_vCont.S = 1;
6261 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6262 support_c = 1;
6263 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6264 support_C = 1;
6265 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6266 rs->supports_vCont.t = 1;
6267 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6268 rs->supports_vCont.r = 1;
6269
6270 p = strchr (p, ';');
6271 }
6272
6273 /* If c, and C are not all supported, we can't use vCont. Clearing
6274 BUF will make packet_ok disable the packet. */
6275 if (!support_c || !support_C)
6276 buf[0] = 0;
6277 }
6278
6279 packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCont]);
6280 rs->supports_vCont_probed = true;
6281 }
6282
6283 /* Helper function for building "vCont" resumptions. Write a
6284 resumption to P. ENDP points to one-passed-the-end of the buffer
6285 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6286 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6287 resumed thread should be single-stepped and/or signalled. If PTID
6288 equals minus_one_ptid, then all threads are resumed; if PTID
6289 represents a process, then all threads of the process are
6290 resumed. */
6291
6292 char *
6293 remote_target::append_resumption (char *p, char *endp,
6294 ptid_t ptid, int step, gdb_signal siggnal)
6295 {
6296 struct remote_state *rs = get_remote_state ();
6297
6298 if (step && siggnal != GDB_SIGNAL_0)
6299 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6300 else if (step
6301 /* GDB is willing to range step. */
6302 && use_range_stepping
6303 /* Target supports range stepping. */
6304 && rs->supports_vCont.r
6305 /* We don't currently support range stepping multiple
6306 threads with a wildcard (though the protocol allows it,
6307 so stubs shouldn't make an active effort to forbid
6308 it). */
6309 && !(remote_multi_process_p (rs) && ptid.is_pid ()))
6310 {
6311 struct thread_info *tp;
6312
6313 if (ptid == minus_one_ptid)
6314 {
6315 /* If we don't know about the target thread's tid, then
6316 we're resuming magic_null_ptid (see caller). */
6317 tp = find_thread_ptid (this, magic_null_ptid);
6318 }
6319 else
6320 tp = find_thread_ptid (this, ptid);
6321 gdb_assert (tp != NULL);
6322
6323 if (tp->control.may_range_step)
6324 {
6325 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6326
6327 p += xsnprintf (p, endp - p, ";r%s,%s",
6328 phex_nz (tp->control.step_range_start,
6329 addr_size),
6330 phex_nz (tp->control.step_range_end,
6331 addr_size));
6332 }
6333 else
6334 p += xsnprintf (p, endp - p, ";s");
6335 }
6336 else if (step)
6337 p += xsnprintf (p, endp - p, ";s");
6338 else if (siggnal != GDB_SIGNAL_0)
6339 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6340 else
6341 p += xsnprintf (p, endp - p, ";c");
6342
6343 if (remote_multi_process_p (rs) && ptid.is_pid ())
6344 {
6345 ptid_t nptid;
6346
6347 /* All (-1) threads of process. */
6348 nptid = ptid_t (ptid.pid (), -1);
6349
6350 p += xsnprintf (p, endp - p, ":");
6351 p = write_ptid (p, endp, nptid);
6352 }
6353 else if (ptid != minus_one_ptid)
6354 {
6355 p += xsnprintf (p, endp - p, ":");
6356 p = write_ptid (p, endp, ptid);
6357 }
6358
6359 return p;
6360 }
6361
6362 /* Clear the thread's private info on resume. */
6363
6364 static void
6365 resume_clear_thread_private_info (struct thread_info *thread)
6366 {
6367 if (thread->priv != NULL)
6368 {
6369 remote_thread_info *priv = get_remote_thread_info (thread);
6370
6371 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6372 priv->watch_data_address = 0;
6373 }
6374 }
6375
6376 /* Append a vCont continue-with-signal action for threads that have a
6377 non-zero stop signal. */
6378
6379 char *
6380 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6381 ptid_t ptid)
6382 {
6383 for (thread_info *thread : all_non_exited_threads (this, ptid))
6384 if (inferior_ptid != thread->ptid
6385 && thread->stop_signal () != GDB_SIGNAL_0)
6386 {
6387 p = append_resumption (p, endp, thread->ptid,
6388 0, thread->stop_signal ());
6389 thread->set_stop_signal (GDB_SIGNAL_0);
6390 resume_clear_thread_private_info (thread);
6391 }
6392
6393 return p;
6394 }
6395
6396 /* Set the target running, using the packets that use Hc
6397 (c/s/C/S). */
6398
6399 void
6400 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6401 gdb_signal siggnal)
6402 {
6403 struct remote_state *rs = get_remote_state ();
6404 char *buf;
6405
6406 rs->last_sent_signal = siggnal;
6407 rs->last_sent_step = step;
6408
6409 /* The c/s/C/S resume packets use Hc, so set the continue
6410 thread. */
6411 if (ptid == minus_one_ptid)
6412 set_continue_thread (any_thread_ptid);
6413 else
6414 set_continue_thread (ptid);
6415
6416 for (thread_info *thread : all_non_exited_threads (this))
6417 resume_clear_thread_private_info (thread);
6418
6419 buf = rs->buf.data ();
6420 if (::execution_direction == EXEC_REVERSE)
6421 {
6422 /* We don't pass signals to the target in reverse exec mode. */
6423 if (info_verbose && siggnal != GDB_SIGNAL_0)
6424 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6425 siggnal);
6426
6427 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6428 error (_("Remote reverse-step not supported."));
6429 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6430 error (_("Remote reverse-continue not supported."));
6431
6432 strcpy (buf, step ? "bs" : "bc");
6433 }
6434 else if (siggnal != GDB_SIGNAL_0)
6435 {
6436 buf[0] = step ? 'S' : 'C';
6437 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6438 buf[2] = tohex (((int) siggnal) & 0xf);
6439 buf[3] = '\0';
6440 }
6441 else
6442 strcpy (buf, step ? "s" : "c");
6443
6444 putpkt (buf);
6445 }
6446
6447 /* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6448 STEP, and SIGGNAL have the same meaning as in target_resume. This
6449 function returns non-zero iff it resumes the inferior.
6450
6451 This function issues a strict subset of all possible vCont commands
6452 at the moment. */
6453
6454 int
6455 remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6456 enum gdb_signal siggnal)
6457 {
6458 struct remote_state *rs = get_remote_state ();
6459 char *p;
6460 char *endp;
6461
6462 /* No reverse execution actions defined for vCont. */
6463 if (::execution_direction == EXEC_REVERSE)
6464 return 0;
6465
6466 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6467 remote_vcont_probe ();
6468
6469 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6470 return 0;
6471
6472 p = rs->buf.data ();
6473 endp = p + get_remote_packet_size ();
6474
6475 /* If we could generate a wider range of packets, we'd have to worry
6476 about overflowing BUF. Should there be a generic
6477 "multi-part-packet" packet? */
6478
6479 p += xsnprintf (p, endp - p, "vCont");
6480
6481 if (scope_ptid == magic_null_ptid)
6482 {
6483 /* MAGIC_NULL_PTID means that we don't have any active threads,
6484 so we don't have any TID numbers the inferior will
6485 understand. Make sure to only send forms that do not specify
6486 a TID. */
6487 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6488 }
6489 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
6490 {
6491 /* Resume all threads (of all processes, or of a single
6492 process), with preference for INFERIOR_PTID. This assumes
6493 inferior_ptid belongs to the set of all threads we are about
6494 to resume. */
6495 if (step || siggnal != GDB_SIGNAL_0)
6496 {
6497 /* Step inferior_ptid, with or without signal. */
6498 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6499 }
6500
6501 /* Also pass down any pending signaled resumption for other
6502 threads not the current. */
6503 p = append_pending_thread_resumptions (p, endp, scope_ptid);
6504
6505 /* And continue others without a signal. */
6506 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
6507 }
6508 else
6509 {
6510 /* Scheduler locking; resume only SCOPE_PTID. */
6511 append_resumption (p, endp, scope_ptid, step, siggnal);
6512 }
6513
6514 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6515 putpkt (rs->buf);
6516
6517 if (target_is_non_stop_p ())
6518 {
6519 /* In non-stop, the stub replies to vCont with "OK". The stop
6520 reply will be reported asynchronously by means of a `%Stop'
6521 notification. */
6522 getpkt (&rs->buf, 0);
6523 if (strcmp (rs->buf.data (), "OK") != 0)
6524 error (_("Unexpected vCont reply in non-stop mode: %s"),
6525 rs->buf.data ());
6526 }
6527
6528 return 1;
6529 }
6530
6531 /* Tell the remote machine to resume. */
6532
6533 void
6534 remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
6535 {
6536 struct remote_state *rs = get_remote_state ();
6537
6538 /* When connected in non-stop mode, the core resumes threads
6539 individually. Resuming remote threads directly in target_resume
6540 would thus result in sending one packet per thread. Instead, to
6541 minimize roundtrip latency, here we just store the resume
6542 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6543 resumption will be done in remote_target::commit_resume, where we'll be
6544 able to do vCont action coalescing. */
6545 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6546 {
6547 remote_thread_info *remote_thr
6548 = get_remote_thread_info (inferior_thread ());
6549
6550 /* We don't expect the core to ask to resume an already resumed (from
6551 its point of view) thread. */
6552 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6553
6554 remote_thr->set_resumed_pending_vcont (step, siggnal);
6555
6556 /* There's actually nothing that says that the core can't
6557 request a wildcard resume in non-stop mode, though. It's
6558 just that we know it doesn't currently, so we don't bother
6559 with it. */
6560 gdb_assert (scope_ptid == inferior_ptid);
6561 return;
6562 }
6563
6564 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6565 (explained in remote-notif.c:handle_notification) so
6566 remote_notif_process is not called. We need find a place where
6567 it is safe to start a 'vNotif' sequence. It is good to do it
6568 before resuming inferior, because inferior was stopped and no RSP
6569 traffic at that moment. */
6570 if (!target_is_non_stop_p ())
6571 remote_notif_process (rs->notif_state, &notif_client_stop);
6572
6573 rs->last_resume_exec_dir = ::execution_direction;
6574
6575 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6576 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
6577 remote_resume_with_hc (scope_ptid, step, siggnal);
6578
6579 /* Update resumed state tracked by the remote target. */
6580 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
6581 get_remote_thread_info (tp)->set_resumed ();
6582
6583 /* We've just told the target to resume. The remote server will
6584 wait for the inferior to stop, and then send a stop reply. In
6585 the mean time, we can't start another command/query ourselves
6586 because the stub wouldn't be ready to process it. This applies
6587 only to the base all-stop protocol, however. In non-stop (which
6588 only supports vCont), the stub replies with an "OK", and is
6589 immediate able to process further serial input. */
6590 if (!target_is_non_stop_p ())
6591 rs->waiting_for_stop_reply = 1;
6592 }
6593
6594 /* Private per-inferior info for target remote processes. */
6595
6596 struct remote_inferior : public private_inferior
6597 {
6598 /* Whether we can send a wildcard vCont for this process. */
6599 bool may_wildcard_vcont = true;
6600 };
6601
6602 /* Get the remote private inferior data associated to INF. */
6603
6604 static remote_inferior *
6605 get_remote_inferior (inferior *inf)
6606 {
6607 if (inf->priv == NULL)
6608 inf->priv.reset (new remote_inferior);
6609
6610 return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
6611 }
6612
6613 /* Class used to track the construction of a vCont packet in the
6614 outgoing packet buffer. This is used to send multiple vCont
6615 packets if we have more actions than would fit a single packet. */
6616
6617 class vcont_builder
6618 {
6619 public:
6620 explicit vcont_builder (remote_target *remote)
6621 : m_remote (remote)
6622 {
6623 restart ();
6624 }
6625
6626 void flush ();
6627 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6628
6629 private:
6630 void restart ();
6631
6632 /* The remote target. */
6633 remote_target *m_remote;
6634
6635 /* Pointer to the first action. P points here if no action has been
6636 appended yet. */
6637 char *m_first_action;
6638
6639 /* Where the next action will be appended. */
6640 char *m_p;
6641
6642 /* The end of the buffer. Must never write past this. */
6643 char *m_endp;
6644 };
6645
6646 /* Prepare the outgoing buffer for a new vCont packet. */
6647
6648 void
6649 vcont_builder::restart ()
6650 {
6651 struct remote_state *rs = m_remote->get_remote_state ();
6652
6653 m_p = rs->buf.data ();
6654 m_endp = m_p + m_remote->get_remote_packet_size ();
6655 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6656 m_first_action = m_p;
6657 }
6658
6659 /* If the vCont packet being built has any action, send it to the
6660 remote end. */
6661
6662 void
6663 vcont_builder::flush ()
6664 {
6665 struct remote_state *rs;
6666
6667 if (m_p == m_first_action)
6668 return;
6669
6670 rs = m_remote->get_remote_state ();
6671 m_remote->putpkt (rs->buf);
6672 m_remote->getpkt (&rs->buf, 0);
6673 if (strcmp (rs->buf.data (), "OK") != 0)
6674 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
6675 }
6676
6677 /* The largest action is range-stepping, with its two addresses. This
6678 is more than sufficient. If a new, bigger action is created, it'll
6679 quickly trigger a failed assertion in append_resumption (and we'll
6680 just bump this). */
6681 #define MAX_ACTION_SIZE 200
6682
6683 /* Append a new vCont action in the outgoing packet being built. If
6684 the action doesn't fit the packet along with previous actions, push
6685 what we've got so far to the remote end and start over a new vCont
6686 packet (with the new action). */
6687
6688 void
6689 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6690 {
6691 char buf[MAX_ACTION_SIZE + 1];
6692
6693 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6694 ptid, step, siggnal);
6695
6696 /* Check whether this new action would fit in the vCont packet along
6697 with previous actions. If not, send what we've got so far and
6698 start a new vCont packet. */
6699 size_t rsize = endp - buf;
6700 if (rsize > m_endp - m_p)
6701 {
6702 flush ();
6703 restart ();
6704
6705 /* Should now fit. */
6706 gdb_assert (rsize <= m_endp - m_p);
6707 }
6708
6709 memcpy (m_p, buf, rsize);
6710 m_p += rsize;
6711 *m_p = '\0';
6712 }
6713
6714 /* to_commit_resume implementation. */
6715
6716 void
6717 remote_target::commit_resumed ()
6718 {
6719 /* If connected in all-stop mode, we'd send the remote resume
6720 request directly from remote_resume. Likewise if
6721 reverse-debugging, as there are no defined vCont actions for
6722 reverse execution. */
6723 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6724 return;
6725
6726 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6727 instead of resuming all threads of each process individually.
6728 However, if any thread of a process must remain halted, we can't
6729 send wildcard resumes and must send one action per thread.
6730
6731 Care must be taken to not resume threads/processes the server
6732 side already told us are stopped, but the core doesn't know about
6733 yet, because the events are still in the vStopped notification
6734 queue. For example:
6735
6736 #1 => vCont s:p1.1;c
6737 #2 <= OK
6738 #3 <= %Stopped T05 p1.1
6739 #4 => vStopped
6740 #5 <= T05 p1.2
6741 #6 => vStopped
6742 #7 <= OK
6743 #8 (infrun handles the stop for p1.1 and continues stepping)
6744 #9 => vCont s:p1.1;c
6745
6746 The last vCont above would resume thread p1.2 by mistake, because
6747 the server has no idea that the event for p1.2 had not been
6748 handled yet.
6749
6750 The server side must similarly ignore resume actions for the
6751 thread that has a pending %Stopped notification (and any other
6752 threads with events pending), until GDB acks the notification
6753 with vStopped. Otherwise, e.g., the following case is
6754 mishandled:
6755
6756 #1 => g (or any other packet)
6757 #2 <= [registers]
6758 #3 <= %Stopped T05 p1.2
6759 #4 => vCont s:p1.1;c
6760 #5 <= OK
6761
6762 Above, the server must not resume thread p1.2. GDB can't know
6763 that p1.2 stopped until it acks the %Stopped notification, and
6764 since from GDB's perspective all threads should be running, it
6765 sends a "c" action.
6766
6767 Finally, special care must also be given to handling fork/vfork
6768 events. A (v)fork event actually tells us that two processes
6769 stopped -- the parent and the child. Until we follow the fork,
6770 we must not resume the child. Therefore, if we have a pending
6771 fork follow, we must not send a global wildcard resume action
6772 (vCont;c). We can still send process-wide wildcards though. */
6773
6774 /* Start by assuming a global wildcard (vCont;c) is possible. */
6775 bool may_global_wildcard_vcont = true;
6776
6777 /* And assume every process is individually wildcard-able too. */
6778 for (inferior *inf : all_non_exited_inferiors (this))
6779 {
6780 remote_inferior *priv = get_remote_inferior (inf);
6781
6782 priv->may_wildcard_vcont = true;
6783 }
6784
6785 /* Check for any pending events (not reported or processed yet) and
6786 disable process and global wildcard resumes appropriately. */
6787 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6788
6789 bool any_pending_vcont_resume = false;
6790
6791 for (thread_info *tp : all_non_exited_threads (this))
6792 {
6793 remote_thread_info *priv = get_remote_thread_info (tp);
6794
6795 /* If a thread of a process is not meant to be resumed, then we
6796 can't wildcard that process. */
6797 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
6798 {
6799 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6800
6801 /* And if we can't wildcard a process, we can't wildcard
6802 everything either. */
6803 may_global_wildcard_vcont = false;
6804 continue;
6805 }
6806
6807 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
6808 any_pending_vcont_resume = true;
6809
6810 /* If a thread is the parent of an unfollowed fork, then we
6811 can't do a global wildcard, as that would resume the fork
6812 child. */
6813 if (thread_pending_fork_status (tp) != nullptr)
6814 may_global_wildcard_vcont = false;
6815 }
6816
6817 /* We didn't have any resumed thread pending a vCont resume, so nothing to
6818 do. */
6819 if (!any_pending_vcont_resume)
6820 return;
6821
6822 /* Now let's build the vCont packet(s). Actions must be appended
6823 from narrower to wider scopes (thread -> process -> global). If
6824 we end up with too many actions for a single packet vcont_builder
6825 flushes the current vCont packet to the remote side and starts a
6826 new one. */
6827 struct vcont_builder vcont_builder (this);
6828
6829 /* Threads first. */
6830 for (thread_info *tp : all_non_exited_threads (this))
6831 {
6832 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6833
6834 /* If the thread was previously vCont-resumed, no need to send a specific
6835 action for it. If we didn't receive a resume request for it, don't
6836 send an action for it either. */
6837 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
6838 continue;
6839
6840 gdb_assert (!thread_is_in_step_over_chain (tp));
6841
6842 /* We should never be commit-resuming a thread that has a stop reply.
6843 Otherwise, we would end up reporting a stop event for a thread while
6844 it is running on the remote target. */
6845 remote_state *rs = get_remote_state ();
6846 for (const auto &stop_reply : rs->stop_reply_queue)
6847 gdb_assert (stop_reply->ptid != tp->ptid);
6848
6849 const resumed_pending_vcont_info &info
6850 = remote_thr->resumed_pending_vcont_info ();
6851
6852 /* Check if we need to send a specific action for this thread. If not,
6853 it will be included in a wildcard resume instead. */
6854 if (info.step || info.sig != GDB_SIGNAL_0
6855 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
6856 vcont_builder.push_action (tp->ptid, info.step, info.sig);
6857
6858 remote_thr->set_resumed ();
6859 }
6860
6861 /* Now check whether we can send any process-wide wildcard. This is
6862 to avoid sending a global wildcard in the case nothing is
6863 supposed to be resumed. */
6864 bool any_process_wildcard = false;
6865
6866 for (inferior *inf : all_non_exited_inferiors (this))
6867 {
6868 if (get_remote_inferior (inf)->may_wildcard_vcont)
6869 {
6870 any_process_wildcard = true;
6871 break;
6872 }
6873 }
6874
6875 if (any_process_wildcard)
6876 {
6877 /* If all processes are wildcard-able, then send a single "c"
6878 action, otherwise, send an "all (-1) threads of process"
6879 continue action for each running process, if any. */
6880 if (may_global_wildcard_vcont)
6881 {
6882 vcont_builder.push_action (minus_one_ptid,
6883 false, GDB_SIGNAL_0);
6884 }
6885 else
6886 {
6887 for (inferior *inf : all_non_exited_inferiors (this))
6888 {
6889 if (get_remote_inferior (inf)->may_wildcard_vcont)
6890 {
6891 vcont_builder.push_action (ptid_t (inf->pid),
6892 false, GDB_SIGNAL_0);
6893 }
6894 }
6895 }
6896 }
6897
6898 vcont_builder.flush ();
6899 }
6900
6901 /* Implementation of target_has_pending_events. */
6902
6903 bool
6904 remote_target::has_pending_events ()
6905 {
6906 if (target_can_async_p ())
6907 {
6908 remote_state *rs = get_remote_state ();
6909
6910 if (async_event_handler_marked (rs->remote_async_inferior_event_token))
6911 return true;
6912
6913 /* Note that BUFCNT can be negative, indicating sticky
6914 error. */
6915 if (rs->remote_desc->bufcnt != 0)
6916 return true;
6917 }
6918 return false;
6919 }
6920
6921 \f
6922
6923 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6924 thread, all threads of a remote process, or all threads of all
6925 processes. */
6926
6927 void
6928 remote_target::remote_stop_ns (ptid_t ptid)
6929 {
6930 struct remote_state *rs = get_remote_state ();
6931 char *p = rs->buf.data ();
6932 char *endp = p + get_remote_packet_size ();
6933
6934 /* If any thread that needs to stop was resumed but pending a vCont
6935 resume, generate a phony stop_reply. However, first check
6936 whether the thread wasn't resumed with a signal. Generating a
6937 phony stop in that case would result in losing the signal. */
6938 bool needs_commit = false;
6939 for (thread_info *tp : all_non_exited_threads (this, ptid))
6940 {
6941 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6942
6943 if (remote_thr->get_resume_state ()
6944 == resume_state::RESUMED_PENDING_VCONT)
6945 {
6946 const resumed_pending_vcont_info &info
6947 = remote_thr->resumed_pending_vcont_info ();
6948 if (info.sig != GDB_SIGNAL_0)
6949 {
6950 /* This signal must be forwarded to the inferior. We
6951 could commit-resume just this thread, but its simpler
6952 to just commit-resume everything. */
6953 needs_commit = true;
6954 break;
6955 }
6956 }
6957 }
6958
6959 if (needs_commit)
6960 commit_resumed ();
6961 else
6962 for (thread_info *tp : all_non_exited_threads (this, ptid))
6963 {
6964 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6965
6966 if (remote_thr->get_resume_state ()
6967 == resume_state::RESUMED_PENDING_VCONT)
6968 {
6969 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
6970 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
6971 tp->ptid.lwp (),
6972 pulongest (tp->ptid.tid ()));
6973
6974 /* Check that the thread wasn't resumed with a signal.
6975 Generating a phony stop would result in losing the
6976 signal. */
6977 const resumed_pending_vcont_info &info
6978 = remote_thr->resumed_pending_vcont_info ();
6979 gdb_assert (info.sig == GDB_SIGNAL_0);
6980
6981 stop_reply *sr = new stop_reply ();
6982 sr->ptid = tp->ptid;
6983 sr->rs = rs;
6984 sr->ws.set_stopped (GDB_SIGNAL_0);
6985 sr->arch = tp->inf->gdbarch;
6986 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6987 sr->watch_data_address = 0;
6988 sr->core = 0;
6989 this->push_stop_reply (sr);
6990
6991 /* Pretend that this thread was actually resumed on the
6992 remote target, then stopped. If we leave it in the
6993 RESUMED_PENDING_VCONT state and the commit_resumed
6994 method is called while the stop reply is still in the
6995 queue, we'll end up reporting a stop event to the core
6996 for that thread while it is running on the remote
6997 target... that would be bad. */
6998 remote_thr->set_resumed ();
6999 }
7000 }
7001
7002 /* FIXME: This supports_vCont_probed check is a workaround until
7003 packet_support is per-connection. */
7004 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN
7005 || !rs->supports_vCont_probed)
7006 remote_vcont_probe ();
7007
7008 if (!rs->supports_vCont.t)
7009 error (_("Remote server does not support stopping threads"));
7010
7011 if (ptid == minus_one_ptid
7012 || (!remote_multi_process_p (rs) && ptid.is_pid ()))
7013 p += xsnprintf (p, endp - p, "vCont;t");
7014 else
7015 {
7016 ptid_t nptid;
7017
7018 p += xsnprintf (p, endp - p, "vCont;t:");
7019
7020 if (ptid.is_pid ())
7021 /* All (-1) threads of process. */
7022 nptid = ptid_t (ptid.pid (), -1);
7023 else
7024 {
7025 /* Small optimization: if we already have a stop reply for
7026 this thread, no use in telling the stub we want this
7027 stopped. */
7028 if (peek_stop_reply (ptid))
7029 return;
7030
7031 nptid = ptid;
7032 }
7033
7034 write_ptid (p, endp, nptid);
7035 }
7036
7037 /* In non-stop, we get an immediate OK reply. The stop reply will
7038 come in asynchronously by notification. */
7039 putpkt (rs->buf);
7040 getpkt (&rs->buf, 0);
7041 if (strcmp (rs->buf.data (), "OK") != 0)
7042 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7043 rs->buf.data ());
7044 }
7045
7046 /* All-stop version of target_interrupt. Sends a break or a ^C to
7047 interrupt the remote target. It is undefined which thread of which
7048 process reports the interrupt. */
7049
7050 void
7051 remote_target::remote_interrupt_as ()
7052 {
7053 struct remote_state *rs = get_remote_state ();
7054
7055 rs->ctrlc_pending_p = 1;
7056
7057 /* If the inferior is stopped already, but the core didn't know
7058 about it yet, just ignore the request. The pending stop events
7059 will be collected in remote_wait. */
7060 if (stop_reply_queue_length () > 0)
7061 return;
7062
7063 /* Send interrupt_sequence to remote target. */
7064 send_interrupt_sequence ();
7065 }
7066
7067 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7068 the remote target. It is undefined which thread of which process
7069 reports the interrupt. Throws an error if the packet is not
7070 supported by the server. */
7071
7072 void
7073 remote_target::remote_interrupt_ns ()
7074 {
7075 struct remote_state *rs = get_remote_state ();
7076 char *p = rs->buf.data ();
7077 char *endp = p + get_remote_packet_size ();
7078
7079 xsnprintf (p, endp - p, "vCtrlC");
7080
7081 /* In non-stop, we get an immediate OK reply. The stop reply will
7082 come in asynchronously by notification. */
7083 putpkt (rs->buf);
7084 getpkt (&rs->buf, 0);
7085
7086 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
7087 {
7088 case PACKET_OK:
7089 break;
7090 case PACKET_UNKNOWN:
7091 error (_("No support for interrupting the remote target."));
7092 case PACKET_ERROR:
7093 error (_("Interrupting target failed: %s"), rs->buf.data ());
7094 }
7095 }
7096
7097 /* Implement the to_stop function for the remote targets. */
7098
7099 void
7100 remote_target::stop (ptid_t ptid)
7101 {
7102 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7103
7104 if (target_is_non_stop_p ())
7105 remote_stop_ns (ptid);
7106 else
7107 {
7108 /* We don't currently have a way to transparently pause the
7109 remote target in all-stop mode. Interrupt it instead. */
7110 remote_interrupt_as ();
7111 }
7112 }
7113
7114 /* Implement the to_interrupt function for the remote targets. */
7115
7116 void
7117 remote_target::interrupt ()
7118 {
7119 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7120
7121 if (target_is_non_stop_p ())
7122 remote_interrupt_ns ();
7123 else
7124 remote_interrupt_as ();
7125 }
7126
7127 /* Implement the to_pass_ctrlc function for the remote targets. */
7128
7129 void
7130 remote_target::pass_ctrlc ()
7131 {
7132 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7133
7134 struct remote_state *rs = get_remote_state ();
7135
7136 /* If we're starting up, we're not fully synced yet. Quit
7137 immediately. */
7138 if (rs->starting_up)
7139 quit ();
7140 /* If ^C has already been sent once, offer to disconnect. */
7141 else if (rs->ctrlc_pending_p)
7142 interrupt_query ();
7143 else
7144 target_interrupt ();
7145 }
7146
7147 /* Ask the user what to do when an interrupt is received. */
7148
7149 void
7150 remote_target::interrupt_query ()
7151 {
7152 struct remote_state *rs = get_remote_state ();
7153
7154 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7155 {
7156 if (query (_("The target is not responding to interrupt requests.\n"
7157 "Stop debugging it? ")))
7158 {
7159 remote_unpush_target (this);
7160 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7161 }
7162 }
7163 else
7164 {
7165 if (query (_("Interrupted while waiting for the program.\n"
7166 "Give up waiting? ")))
7167 quit ();
7168 }
7169 }
7170
7171 /* Enable/disable target terminal ownership. Most targets can use
7172 terminal groups to control terminal ownership. Remote targets are
7173 different in that explicit transfer of ownership to/from GDB/target
7174 is required. */
7175
7176 void
7177 remote_target::terminal_inferior ()
7178 {
7179 /* NOTE: At this point we could also register our selves as the
7180 recipient of all input. Any characters typed could then be
7181 passed on down to the target. */
7182 }
7183
7184 void
7185 remote_target::terminal_ours ()
7186 {
7187 }
7188
7189 static void
7190 remote_console_output (const char *msg)
7191 {
7192 const char *p;
7193
7194 for (p = msg; p[0] && p[1]; p += 2)
7195 {
7196 char tb[2];
7197 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7198
7199 tb[0] = c;
7200 tb[1] = 0;
7201 gdb_stdtarg->puts (tb);
7202 }
7203 gdb_stdtarg->flush ();
7204 }
7205
7206 /* Return the length of the stop reply queue. */
7207
7208 int
7209 remote_target::stop_reply_queue_length ()
7210 {
7211 remote_state *rs = get_remote_state ();
7212 return rs->stop_reply_queue.size ();
7213 }
7214
7215 static void
7216 remote_notif_stop_parse (remote_target *remote,
7217 struct notif_client *self, const char *buf,
7218 struct notif_event *event)
7219 {
7220 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7221 }
7222
7223 static void
7224 remote_notif_stop_ack (remote_target *remote,
7225 struct notif_client *self, const char *buf,
7226 struct notif_event *event)
7227 {
7228 struct stop_reply *stop_reply = (struct stop_reply *) event;
7229
7230 /* acknowledge */
7231 putpkt (remote, self->ack_command);
7232
7233 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7234 the notification. It was left in the queue because we need to
7235 acknowledge it and pull the rest of the notifications out. */
7236 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7237 remote->push_stop_reply (stop_reply);
7238 }
7239
7240 static int
7241 remote_notif_stop_can_get_pending_events (remote_target *remote,
7242 struct notif_client *self)
7243 {
7244 /* We can't get pending events in remote_notif_process for
7245 notification stop, and we have to do this in remote_wait_ns
7246 instead. If we fetch all queued events from stub, remote stub
7247 may exit and we have no chance to process them back in
7248 remote_wait_ns. */
7249 remote_state *rs = remote->get_remote_state ();
7250 mark_async_event_handler (rs->remote_async_inferior_event_token);
7251 return 0;
7252 }
7253
7254 stop_reply::~stop_reply ()
7255 {
7256 for (cached_reg_t &reg : regcache)
7257 xfree (reg.data);
7258 }
7259
7260 static notif_event_up
7261 remote_notif_stop_alloc_reply ()
7262 {
7263 return notif_event_up (new struct stop_reply ());
7264 }
7265
7266 /* A client of notification Stop. */
7267
7268 struct notif_client notif_client_stop =
7269 {
7270 "Stop",
7271 "vStopped",
7272 remote_notif_stop_parse,
7273 remote_notif_stop_ack,
7274 remote_notif_stop_can_get_pending_events,
7275 remote_notif_stop_alloc_reply,
7276 REMOTE_NOTIF_STOP,
7277 };
7278
7279 /* If CONTEXT contains any fork child threads that have not been
7280 reported yet, remove them from the CONTEXT list. If such a
7281 thread exists it is because we are stopped at a fork catchpoint
7282 and have not yet called follow_fork, which will set up the
7283 host-side data structures for the new process. */
7284
7285 void
7286 remote_target::remove_new_fork_children (threads_listing_context *context)
7287 {
7288 struct notif_client *notif = &notif_client_stop;
7289
7290 /* For any threads stopped at a fork event, remove the corresponding
7291 fork child threads from the CONTEXT list. */
7292 for (thread_info *thread : all_non_exited_threads (this))
7293 {
7294 const target_waitstatus *ws = thread_pending_fork_status (thread);
7295
7296 if (ws == nullptr)
7297 continue;
7298
7299 context->remove_thread (ws->child_ptid ());
7300 }
7301
7302 /* Check for any pending fork events (not reported or processed yet)
7303 in process PID and remove those fork child threads from the
7304 CONTEXT list as well. */
7305 remote_notif_get_pending_events (notif);
7306 for (auto &event : get_remote_state ()->stop_reply_queue)
7307 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7308 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7309 context->remove_thread (event->ws.child_ptid ());
7310 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7311 context->remove_thread (event->ptid);
7312 }
7313
7314 /* Check whether any event pending in the vStopped queue would prevent a
7315 global or process wildcard vCont action. Set *may_global_wildcard to
7316 false if we can't do a global wildcard (vCont;c), and clear the event
7317 inferior's may_wildcard_vcont flag if we can't do a process-wide
7318 wildcard resume (vCont;c:pPID.-1). */
7319
7320 void
7321 remote_target::check_pending_events_prevent_wildcard_vcont
7322 (bool *may_global_wildcard)
7323 {
7324 struct notif_client *notif = &notif_client_stop;
7325
7326 remote_notif_get_pending_events (notif);
7327 for (auto &event : get_remote_state ()->stop_reply_queue)
7328 {
7329 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7330 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7331 continue;
7332
7333 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7334 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7335 *may_global_wildcard = false;
7336
7337 /* This may be the first time we heard about this process.
7338 Regardless, we must not do a global wildcard resume, otherwise
7339 we'd resume this process too. */
7340 *may_global_wildcard = false;
7341 if (event->ptid != null_ptid)
7342 {
7343 inferior *inf = find_inferior_ptid (this, event->ptid);
7344 if (inf != NULL)
7345 get_remote_inferior (inf)->may_wildcard_vcont = false;
7346 }
7347 }
7348 }
7349
7350 /* Discard all pending stop replies of inferior INF. */
7351
7352 void
7353 remote_target::discard_pending_stop_replies (struct inferior *inf)
7354 {
7355 struct stop_reply *reply;
7356 struct remote_state *rs = get_remote_state ();
7357 struct remote_notif_state *rns = rs->notif_state;
7358
7359 /* This function can be notified when an inferior exists. When the
7360 target is not remote, the notification state is NULL. */
7361 if (rs->remote_desc == NULL)
7362 return;
7363
7364 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7365
7366 /* Discard the in-flight notification. */
7367 if (reply != NULL && reply->ptid.pid () == inf->pid)
7368 {
7369 /* Leave the notification pending, since the server expects that
7370 we acknowledge it with vStopped. But clear its contents, so
7371 that later on when we acknowledge it, we also discard it. */
7372 remote_debug_printf
7373 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7374 reply->ptid.to_string().c_str(),
7375 reply->ws.to_string ().c_str ());
7376 reply->ws.set_ignore ();
7377 }
7378
7379 /* Discard the stop replies we have already pulled with
7380 vStopped. */
7381 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7382 rs->stop_reply_queue.end (),
7383 [=] (const stop_reply_up &event)
7384 {
7385 return event->ptid.pid () == inf->pid;
7386 });
7387 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7388 remote_debug_printf
7389 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7390 reply->ptid.to_string().c_str(),
7391 reply->ws.to_string ().c_str ());
7392 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7393 }
7394
7395 /* Discard the stop replies for RS in stop_reply_queue. */
7396
7397 void
7398 remote_target::discard_pending_stop_replies_in_queue ()
7399 {
7400 remote_state *rs = get_remote_state ();
7401
7402 /* Discard the stop replies we have already pulled with
7403 vStopped. */
7404 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7405 rs->stop_reply_queue.end (),
7406 [=] (const stop_reply_up &event)
7407 {
7408 return event->rs == rs;
7409 });
7410 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7411 }
7412
7413 /* Remove the first reply in 'stop_reply_queue' which matches
7414 PTID. */
7415
7416 struct stop_reply *
7417 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7418 {
7419 remote_state *rs = get_remote_state ();
7420
7421 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7422 rs->stop_reply_queue.end (),
7423 [=] (const stop_reply_up &event)
7424 {
7425 return event->ptid.matches (ptid);
7426 });
7427 struct stop_reply *result;
7428 if (iter == rs->stop_reply_queue.end ())
7429 result = nullptr;
7430 else
7431 {
7432 result = iter->release ();
7433 rs->stop_reply_queue.erase (iter);
7434 }
7435
7436 if (notif_debug)
7437 gdb_printf (gdb_stdlog,
7438 "notif: discard queued event: 'Stop' in %s\n",
7439 ptid.to_string ().c_str ());
7440
7441 return result;
7442 }
7443
7444 /* Look for a queued stop reply belonging to PTID. If one is found,
7445 remove it from the queue, and return it. Returns NULL if none is
7446 found. If there are still queued events left to process, tell the
7447 event loop to get back to target_wait soon. */
7448
7449 struct stop_reply *
7450 remote_target::queued_stop_reply (ptid_t ptid)
7451 {
7452 remote_state *rs = get_remote_state ();
7453 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7454
7455 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7456 {
7457 /* There's still at least an event left. */
7458 mark_async_event_handler (rs->remote_async_inferior_event_token);
7459 }
7460
7461 return r;
7462 }
7463
7464 /* Push a fully parsed stop reply in the stop reply queue. Since we
7465 know that we now have at least one queued event left to pass to the
7466 core side, tell the event loop to get back to target_wait soon. */
7467
7468 void
7469 remote_target::push_stop_reply (struct stop_reply *new_event)
7470 {
7471 remote_state *rs = get_remote_state ();
7472 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7473
7474 if (notif_debug)
7475 gdb_printf (gdb_stdlog,
7476 "notif: push 'Stop' %s to queue %d\n",
7477 new_event->ptid.to_string ().c_str (),
7478 int (rs->stop_reply_queue.size ()));
7479
7480 /* Mark the pending event queue only if async mode is currently enabled.
7481 If async mode is not currently enabled, then, if it later becomes
7482 enabled, and there are events in this queue, we will mark the event
7483 token at that point, see remote_target::async. */
7484 if (target_is_async_p ())
7485 mark_async_event_handler (rs->remote_async_inferior_event_token);
7486 }
7487
7488 /* Returns true if we have a stop reply for PTID. */
7489
7490 int
7491 remote_target::peek_stop_reply (ptid_t ptid)
7492 {
7493 remote_state *rs = get_remote_state ();
7494 for (auto &event : rs->stop_reply_queue)
7495 if (ptid == event->ptid
7496 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7497 return 1;
7498 return 0;
7499 }
7500
7501 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7502 starting with P and ending with PEND matches PREFIX. */
7503
7504 static int
7505 strprefix (const char *p, const char *pend, const char *prefix)
7506 {
7507 for ( ; p < pend; p++, prefix++)
7508 if (*p != *prefix)
7509 return 0;
7510 return *prefix == '\0';
7511 }
7512
7513 /* Parse the stop reply in BUF. Either the function succeeds, and the
7514 result is stored in EVENT, or throws an error. */
7515
7516 void
7517 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7518 {
7519 remote_arch_state *rsa = NULL;
7520 ULONGEST addr;
7521 const char *p;
7522 int skipregs = 0;
7523
7524 event->ptid = null_ptid;
7525 event->rs = get_remote_state ();
7526 event->ws.set_ignore ();
7527 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7528 event->regcache.clear ();
7529 event->core = -1;
7530
7531 switch (buf[0])
7532 {
7533 case 'T': /* Status with PC, SP, FP, ... */
7534 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7535 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7536 ss = signal number
7537 n... = register number
7538 r... = register contents
7539 */
7540
7541 p = &buf[3]; /* after Txx */
7542 while (*p)
7543 {
7544 const char *p1;
7545 int fieldsize;
7546
7547 p1 = strchr (p, ':');
7548 if (p1 == NULL)
7549 error (_("Malformed packet(a) (missing colon): %s\n\
7550 Packet: '%s'\n"),
7551 p, buf);
7552 if (p == p1)
7553 error (_("Malformed packet(a) (missing register number): %s\n\
7554 Packet: '%s'\n"),
7555 p, buf);
7556
7557 /* Some "registers" are actually extended stop information.
7558 Note if you're adding a new entry here: GDB 7.9 and
7559 earlier assume that all register "numbers" that start
7560 with an hex digit are real register numbers. Make sure
7561 the server only sends such a packet if it knows the
7562 client understands it. */
7563
7564 if (strprefix (p, p1, "thread"))
7565 event->ptid = read_ptid (++p1, &p);
7566 else if (strprefix (p, p1, "syscall_entry"))
7567 {
7568 ULONGEST sysno;
7569
7570 p = unpack_varlen_hex (++p1, &sysno);
7571 event->ws.set_syscall_entry ((int) sysno);
7572 }
7573 else if (strprefix (p, p1, "syscall_return"))
7574 {
7575 ULONGEST sysno;
7576
7577 p = unpack_varlen_hex (++p1, &sysno);
7578 event->ws.set_syscall_return ((int) sysno);
7579 }
7580 else if (strprefix (p, p1, "watch")
7581 || strprefix (p, p1, "rwatch")
7582 || strprefix (p, p1, "awatch"))
7583 {
7584 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7585 p = unpack_varlen_hex (++p1, &addr);
7586 event->watch_data_address = (CORE_ADDR) addr;
7587 }
7588 else if (strprefix (p, p1, "swbreak"))
7589 {
7590 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7591
7592 /* Make sure the stub doesn't forget to indicate support
7593 with qSupported. */
7594 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7595 error (_("Unexpected swbreak stop reason"));
7596
7597 /* The value part is documented as "must be empty",
7598 though we ignore it, in case we ever decide to make
7599 use of it in a backward compatible way. */
7600 p = strchrnul (p1 + 1, ';');
7601 }
7602 else if (strprefix (p, p1, "hwbreak"))
7603 {
7604 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7605
7606 /* Make sure the stub doesn't forget to indicate support
7607 with qSupported. */
7608 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7609 error (_("Unexpected hwbreak stop reason"));
7610
7611 /* See above. */
7612 p = strchrnul (p1 + 1, ';');
7613 }
7614 else if (strprefix (p, p1, "library"))
7615 {
7616 event->ws.set_loaded ();
7617 p = strchrnul (p1 + 1, ';');
7618 }
7619 else if (strprefix (p, p1, "replaylog"))
7620 {
7621 event->ws.set_no_history ();
7622 /* p1 will indicate "begin" or "end", but it makes
7623 no difference for now, so ignore it. */
7624 p = strchrnul (p1 + 1, ';');
7625 }
7626 else if (strprefix (p, p1, "core"))
7627 {
7628 ULONGEST c;
7629
7630 p = unpack_varlen_hex (++p1, &c);
7631 event->core = c;
7632 }
7633 else if (strprefix (p, p1, "fork"))
7634 event->ws.set_forked (read_ptid (++p1, &p));
7635 else if (strprefix (p, p1, "vfork"))
7636 event->ws.set_vforked (read_ptid (++p1, &p));
7637 else if (strprefix (p, p1, "vforkdone"))
7638 {
7639 event->ws.set_vfork_done ();
7640 p = strchrnul (p1 + 1, ';');
7641 }
7642 else if (strprefix (p, p1, "exec"))
7643 {
7644 ULONGEST ignored;
7645 int pathlen;
7646
7647 /* Determine the length of the execd pathname. */
7648 p = unpack_varlen_hex (++p1, &ignored);
7649 pathlen = (p - p1) / 2;
7650
7651 /* Save the pathname for event reporting and for
7652 the next run command. */
7653 gdb::unique_xmalloc_ptr<char> pathname
7654 ((char *) xmalloc (pathlen + 1));
7655 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
7656 pathname.get ()[pathlen] = '\0';
7657
7658 /* This is freed during event handling. */
7659 event->ws.set_execd (std::move (pathname));
7660
7661 /* Skip the registers included in this packet, since
7662 they may be for an architecture different from the
7663 one used by the original program. */
7664 skipregs = 1;
7665 }
7666 else if (strprefix (p, p1, "create"))
7667 {
7668 event->ws.set_thread_created ();
7669 p = strchrnul (p1 + 1, ';');
7670 }
7671 else
7672 {
7673 ULONGEST pnum;
7674 const char *p_temp;
7675
7676 if (skipregs)
7677 {
7678 p = strchrnul (p1 + 1, ';');
7679 p++;
7680 continue;
7681 }
7682
7683 /* Maybe a real ``P'' register number. */
7684 p_temp = unpack_varlen_hex (p, &pnum);
7685 /* If the first invalid character is the colon, we got a
7686 register number. Otherwise, it's an unknown stop
7687 reason. */
7688 if (p_temp == p1)
7689 {
7690 /* If we haven't parsed the event's thread yet, find
7691 it now, in order to find the architecture of the
7692 reported expedited registers. */
7693 if (event->ptid == null_ptid)
7694 {
7695 /* If there is no thread-id information then leave
7696 the event->ptid as null_ptid. Later in
7697 process_stop_reply we will pick a suitable
7698 thread. */
7699 const char *thr = strstr (p1 + 1, ";thread:");
7700 if (thr != NULL)
7701 event->ptid = read_ptid (thr + strlen (";thread:"),
7702 NULL);
7703 }
7704
7705 if (rsa == NULL)
7706 {
7707 inferior *inf
7708 = (event->ptid == null_ptid
7709 ? NULL
7710 : find_inferior_ptid (this, event->ptid));
7711 /* If this is the first time we learn anything
7712 about this process, skip the registers
7713 included in this packet, since we don't yet
7714 know which architecture to use to parse them.
7715 We'll determine the architecture later when
7716 we process the stop reply and retrieve the
7717 target description, via
7718 remote_notice_new_inferior ->
7719 post_create_inferior. */
7720 if (inf == NULL)
7721 {
7722 p = strchrnul (p1 + 1, ';');
7723 p++;
7724 continue;
7725 }
7726
7727 event->arch = inf->gdbarch;
7728 rsa = event->rs->get_remote_arch_state (event->arch);
7729 }
7730
7731 packet_reg *reg
7732 = packet_reg_from_pnum (event->arch, rsa, pnum);
7733 cached_reg_t cached_reg;
7734
7735 if (reg == NULL)
7736 error (_("Remote sent bad register number %s: %s\n\
7737 Packet: '%s'\n"),
7738 hex_string (pnum), p, buf);
7739
7740 cached_reg.num = reg->regnum;
7741 cached_reg.data = (gdb_byte *)
7742 xmalloc (register_size (event->arch, reg->regnum));
7743
7744 p = p1 + 1;
7745 fieldsize = hex2bin (p, cached_reg.data,
7746 register_size (event->arch, reg->regnum));
7747 p += 2 * fieldsize;
7748 if (fieldsize < register_size (event->arch, reg->regnum))
7749 warning (_("Remote reply is too short: %s"), buf);
7750
7751 event->regcache.push_back (cached_reg);
7752 }
7753 else
7754 {
7755 /* Not a number. Silently skip unknown optional
7756 info. */
7757 p = strchrnul (p1 + 1, ';');
7758 }
7759 }
7760
7761 if (*p != ';')
7762 error (_("Remote register badly formatted: %s\nhere: %s"),
7763 buf, p);
7764 ++p;
7765 }
7766
7767 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
7768 break;
7769
7770 /* fall through */
7771 case 'S': /* Old style status, just signal only. */
7772 {
7773 int sig;
7774
7775 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7776 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7777 event->ws.set_stopped ((enum gdb_signal) sig);
7778 else
7779 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
7780 }
7781 break;
7782 case 'w': /* Thread exited. */
7783 {
7784 ULONGEST value;
7785
7786 p = unpack_varlen_hex (&buf[1], &value);
7787 event->ws.set_thread_exited (value);
7788 if (*p != ';')
7789 error (_("stop reply packet badly formatted: %s"), buf);
7790 event->ptid = read_ptid (++p, NULL);
7791 break;
7792 }
7793 case 'W': /* Target exited. */
7794 case 'X':
7795 {
7796 ULONGEST value;
7797
7798 /* GDB used to accept only 2 hex chars here. Stubs should
7799 only send more if they detect GDB supports multi-process
7800 support. */
7801 p = unpack_varlen_hex (&buf[1], &value);
7802
7803 if (buf[0] == 'W')
7804 {
7805 /* The remote process exited. */
7806 event->ws.set_exited (value);
7807 }
7808 else
7809 {
7810 /* The remote process exited with a signal. */
7811 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7812 event->ws.set_signalled ((enum gdb_signal) value);
7813 else
7814 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
7815 }
7816
7817 /* If no process is specified, return null_ptid, and let the
7818 caller figure out the right process to use. */
7819 int pid = 0;
7820 if (*p == '\0')
7821 ;
7822 else if (*p == ';')
7823 {
7824 p++;
7825
7826 if (*p == '\0')
7827 ;
7828 else if (startswith (p, "process:"))
7829 {
7830 ULONGEST upid;
7831
7832 p += sizeof ("process:") - 1;
7833 unpack_varlen_hex (p, &upid);
7834 pid = upid;
7835 }
7836 else
7837 error (_("unknown stop reply packet: %s"), buf);
7838 }
7839 else
7840 error (_("unknown stop reply packet: %s"), buf);
7841 event->ptid = ptid_t (pid);
7842 }
7843 break;
7844 case 'N':
7845 event->ws.set_no_resumed ();
7846 event->ptid = minus_one_ptid;
7847 break;
7848 }
7849 }
7850
7851 /* When the stub wants to tell GDB about a new notification reply, it
7852 sends a notification (%Stop, for example). Those can come it at
7853 any time, hence, we have to make sure that any pending
7854 putpkt/getpkt sequence we're making is finished, before querying
7855 the stub for more events with the corresponding ack command
7856 (vStopped, for example). E.g., if we started a vStopped sequence
7857 immediately upon receiving the notification, something like this
7858 could happen:
7859
7860 1.1) --> Hg 1
7861 1.2) <-- OK
7862 1.3) --> g
7863 1.4) <-- %Stop
7864 1.5) --> vStopped
7865 1.6) <-- (registers reply to step #1.3)
7866
7867 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7868 query.
7869
7870 To solve this, whenever we parse a %Stop notification successfully,
7871 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7872 doing whatever we were doing:
7873
7874 2.1) --> Hg 1
7875 2.2) <-- OK
7876 2.3) --> g
7877 2.4) <-- %Stop
7878 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7879 2.5) <-- (registers reply to step #2.3)
7880
7881 Eventually after step #2.5, we return to the event loop, which
7882 notices there's an event on the
7883 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7884 associated callback --- the function below. At this point, we're
7885 always safe to start a vStopped sequence. :
7886
7887 2.6) --> vStopped
7888 2.7) <-- T05 thread:2
7889 2.8) --> vStopped
7890 2.9) --> OK
7891 */
7892
7893 void
7894 remote_target::remote_notif_get_pending_events (notif_client *nc)
7895 {
7896 struct remote_state *rs = get_remote_state ();
7897
7898 if (rs->notif_state->pending_event[nc->id] != NULL)
7899 {
7900 if (notif_debug)
7901 gdb_printf (gdb_stdlog,
7902 "notif: process: '%s' ack pending event\n",
7903 nc->name);
7904
7905 /* acknowledge */
7906 nc->ack (this, nc, rs->buf.data (),
7907 rs->notif_state->pending_event[nc->id]);
7908 rs->notif_state->pending_event[nc->id] = NULL;
7909
7910 while (1)
7911 {
7912 getpkt (&rs->buf, 0);
7913 if (strcmp (rs->buf.data (), "OK") == 0)
7914 break;
7915 else
7916 remote_notif_ack (this, nc, rs->buf.data ());
7917 }
7918 }
7919 else
7920 {
7921 if (notif_debug)
7922 gdb_printf (gdb_stdlog,
7923 "notif: process: '%s' no pending reply\n",
7924 nc->name);
7925 }
7926 }
7927
7928 /* Wrapper around remote_target::remote_notif_get_pending_events to
7929 avoid having to export the whole remote_target class. */
7930
7931 void
7932 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7933 {
7934 remote->remote_notif_get_pending_events (nc);
7935 }
7936
7937 /* Called from process_stop_reply when the stop packet we are responding
7938 to didn't include a process-id or thread-id. STATUS is the stop event
7939 we are responding to.
7940
7941 It is the task of this function to select a suitable thread (or process)
7942 and return its ptid, this is the thread (or process) we will assume the
7943 stop event came from.
7944
7945 In some cases there isn't really any choice about which thread (or
7946 process) is selected, a basic remote with a single process containing a
7947 single thread might choose not to send any process-id or thread-id in
7948 its stop packets, this function will select and return the one and only
7949 thread.
7950
7951 However, if a target supports multiple threads (or processes) and still
7952 doesn't include a thread-id (or process-id) in its stop packet then
7953 first, this is a badly behaving target, and second, we're going to have
7954 to select a thread (or process) at random and use that. This function
7955 will print a warning to the user if it detects that there is the
7956 possibility that GDB is guessing which thread (or process) to
7957 report.
7958
7959 Note that this is called before GDB fetches the updated thread list from the
7960 target. So it's possible for the stop reply to be ambiguous and for GDB to
7961 not realize it. For example, if there's initially one thread, the target
7962 spawns a second thread, and then sends a stop reply without an id that
7963 concerns the first thread. GDB will assume the stop reply is about the
7964 first thread - the only thread it knows about - without printing a warning.
7965 Anyway, if the remote meant for the stop reply to be about the second thread,
7966 then it would be really broken, because GDB doesn't know about that thread
7967 yet. */
7968
7969 ptid_t
7970 remote_target::select_thread_for_ambiguous_stop_reply
7971 (const target_waitstatus &status)
7972 {
7973 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7974
7975 /* Some stop events apply to all threads in an inferior, while others
7976 only apply to a single thread. */
7977 bool process_wide_stop
7978 = (status.kind () == TARGET_WAITKIND_EXITED
7979 || status.kind () == TARGET_WAITKIND_SIGNALLED);
7980
7981 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
7982
7983 thread_info *first_resumed_thread = nullptr;
7984 bool ambiguous = false;
7985
7986 /* Consider all non-exited threads of the target, find the first resumed
7987 one. */
7988 for (thread_info *thr : all_non_exited_threads (this))
7989 {
7990 remote_thread_info *remote_thr = get_remote_thread_info (thr);
7991
7992 if (remote_thr->get_resume_state () != resume_state::RESUMED)
7993 continue;
7994
7995 if (first_resumed_thread == nullptr)
7996 first_resumed_thread = thr;
7997 else if (!process_wide_stop
7998 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
7999 ambiguous = true;
8000 }
8001
8002 gdb_assert (first_resumed_thread != nullptr);
8003
8004 remote_debug_printf ("first resumed thread is %s",
8005 pid_to_str (first_resumed_thread->ptid).c_str ());
8006 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8007
8008 /* Warn if the remote target is sending ambiguous stop replies. */
8009 if (ambiguous)
8010 {
8011 static bool warned = false;
8012
8013 if (!warned)
8014 {
8015 /* If you are seeing this warning then the remote target has
8016 stopped without specifying a thread-id, but the target
8017 does have multiple threads (or inferiors), and so GDB is
8018 having to guess which thread stopped.
8019
8020 Examples of what might cause this are the target sending
8021 and 'S' stop packet, or a 'T' stop packet and not
8022 including a thread-id.
8023
8024 Additionally, the target might send a 'W' or 'X packet
8025 without including a process-id, when the target has
8026 multiple running inferiors. */
8027 if (process_wide_stop)
8028 warning (_("multi-inferior target stopped without "
8029 "sending a process-id, using first "
8030 "non-exited inferior"));
8031 else
8032 warning (_("multi-threaded target stopped without "
8033 "sending a thread-id, using first "
8034 "non-exited thread"));
8035 warned = true;
8036 }
8037 }
8038
8039 /* If this is a stop for all threads then don't use a particular threads
8040 ptid, instead create a new ptid where only the pid field is set. */
8041 if (process_wide_stop)
8042 return ptid_t (first_resumed_thread->ptid.pid ());
8043 else
8044 return first_resumed_thread->ptid;
8045 }
8046
8047 /* Called when it is decided that STOP_REPLY holds the info of the
8048 event that is to be returned to the core. This function always
8049 destroys STOP_REPLY. */
8050
8051 ptid_t
8052 remote_target::process_stop_reply (struct stop_reply *stop_reply,
8053 struct target_waitstatus *status)
8054 {
8055 *status = stop_reply->ws;
8056 ptid_t ptid = stop_reply->ptid;
8057
8058 /* If no thread/process was reported by the stub then select a suitable
8059 thread/process. */
8060 if (ptid == null_ptid)
8061 ptid = select_thread_for_ambiguous_stop_reply (*status);
8062 gdb_assert (ptid != null_ptid);
8063
8064 if (status->kind () != TARGET_WAITKIND_EXITED
8065 && status->kind () != TARGET_WAITKIND_SIGNALLED
8066 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8067 {
8068 /* Expedited registers. */
8069 if (!stop_reply->regcache.empty ())
8070 {
8071 struct regcache *regcache
8072 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
8073
8074 for (cached_reg_t &reg : stop_reply->regcache)
8075 {
8076 regcache->raw_supply (reg.num, reg.data);
8077 xfree (reg.data);
8078 }
8079
8080 stop_reply->regcache.clear ();
8081 }
8082
8083 remote_notice_new_inferior (ptid, false);
8084 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8085 remote_thr->core = stop_reply->core;
8086 remote_thr->stop_reason = stop_reply->stop_reason;
8087 remote_thr->watch_data_address = stop_reply->watch_data_address;
8088
8089 if (target_is_non_stop_p ())
8090 {
8091 /* If the target works in non-stop mode, a stop-reply indicates that
8092 only this thread stopped. */
8093 remote_thr->set_not_resumed ();
8094 }
8095 else
8096 {
8097 /* If the target works in all-stop mode, a stop-reply indicates that
8098 all the target's threads stopped. */
8099 for (thread_info *tp : all_non_exited_threads (this))
8100 get_remote_thread_info (tp)->set_not_resumed ();
8101 }
8102 }
8103
8104 delete stop_reply;
8105 return ptid;
8106 }
8107
8108 /* The non-stop mode version of target_wait. */
8109
8110 ptid_t
8111 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8112 target_wait_flags options)
8113 {
8114 struct remote_state *rs = get_remote_state ();
8115 struct stop_reply *stop_reply;
8116 int ret;
8117 int is_notif = 0;
8118
8119 /* If in non-stop mode, get out of getpkt even if a
8120 notification is received. */
8121
8122 ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
8123 while (1)
8124 {
8125 if (ret != -1 && !is_notif)
8126 switch (rs->buf[0])
8127 {
8128 case 'E': /* Error of some sort. */
8129 /* We're out of sync with the target now. Did it continue
8130 or not? We can't tell which thread it was in non-stop,
8131 so just ignore this. */
8132 warning (_("Remote failure reply: %s"), rs->buf.data ());
8133 break;
8134 case 'O': /* Console output. */
8135 remote_console_output (&rs->buf[1]);
8136 break;
8137 default:
8138 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8139 break;
8140 }
8141
8142 /* Acknowledge a pending stop reply that may have arrived in the
8143 mean time. */
8144 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8145 remote_notif_get_pending_events (&notif_client_stop);
8146
8147 /* If indeed we noticed a stop reply, we're done. */
8148 stop_reply = queued_stop_reply (ptid);
8149 if (stop_reply != NULL)
8150 return process_stop_reply (stop_reply, status);
8151
8152 /* Still no event. If we're just polling for an event, then
8153 return to the event loop. */
8154 if (options & TARGET_WNOHANG)
8155 {
8156 status->set_ignore ();
8157 return minus_one_ptid;
8158 }
8159
8160 /* Otherwise do a blocking wait. */
8161 ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
8162 }
8163 }
8164
8165 /* Return the first resumed thread. */
8166
8167 static ptid_t
8168 first_remote_resumed_thread (remote_target *target)
8169 {
8170 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8171 if (tp->resumed ())
8172 return tp->ptid;
8173 return null_ptid;
8174 }
8175
8176 /* Wait until the remote machine stops, then return, storing status in
8177 STATUS just as `wait' would. */
8178
8179 ptid_t
8180 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8181 target_wait_flags options)
8182 {
8183 struct remote_state *rs = get_remote_state ();
8184 ptid_t event_ptid = null_ptid;
8185 char *buf;
8186 struct stop_reply *stop_reply;
8187
8188 again:
8189
8190 status->set_ignore ();
8191
8192 stop_reply = queued_stop_reply (ptid);
8193 if (stop_reply != NULL)
8194 {
8195 /* None of the paths that push a stop reply onto the queue should
8196 have set the waiting_for_stop_reply flag. */
8197 gdb_assert (!rs->waiting_for_stop_reply);
8198 event_ptid = process_stop_reply (stop_reply, status);
8199 }
8200 else
8201 {
8202 int forever = ((options & TARGET_WNOHANG) == 0
8203 && rs->wait_forever_enabled_p);
8204
8205 if (!rs->waiting_for_stop_reply)
8206 {
8207 status->set_no_resumed ();
8208 return minus_one_ptid;
8209 }
8210
8211 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8212 _never_ wait for ever -> test on target_is_async_p().
8213 However, before we do that we need to ensure that the caller
8214 knows how to take the target into/out of async mode. */
8215 int is_notif;
8216 int ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
8217
8218 /* GDB gets a notification. Return to core as this event is
8219 not interesting. */
8220 if (ret != -1 && is_notif)
8221 return minus_one_ptid;
8222
8223 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8224 return minus_one_ptid;
8225
8226 buf = rs->buf.data ();
8227
8228 /* Assume that the target has acknowledged Ctrl-C unless we receive
8229 an 'F' or 'O' packet. */
8230 if (buf[0] != 'F' && buf[0] != 'O')
8231 rs->ctrlc_pending_p = 0;
8232
8233 switch (buf[0])
8234 {
8235 case 'E': /* Error of some sort. */
8236 /* We're out of sync with the target now. Did it continue or
8237 not? Not is more likely, so report a stop. */
8238 rs->waiting_for_stop_reply = 0;
8239
8240 warning (_("Remote failure reply: %s"), buf);
8241 status->set_stopped (GDB_SIGNAL_0);
8242 break;
8243 case 'F': /* File-I/O request. */
8244 /* GDB may access the inferior memory while handling the File-I/O
8245 request, but we don't want GDB accessing memory while waiting
8246 for a stop reply. See the comments in putpkt_binary. Set
8247 waiting_for_stop_reply to 0 temporarily. */
8248 rs->waiting_for_stop_reply = 0;
8249 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8250 rs->ctrlc_pending_p = 0;
8251 /* GDB handled the File-I/O request, and the target is running
8252 again. Keep waiting for events. */
8253 rs->waiting_for_stop_reply = 1;
8254 break;
8255 case 'N': case 'T': case 'S': case 'X': case 'W':
8256 {
8257 /* There is a stop reply to handle. */
8258 rs->waiting_for_stop_reply = 0;
8259
8260 stop_reply
8261 = (struct stop_reply *) remote_notif_parse (this,
8262 &notif_client_stop,
8263 rs->buf.data ());
8264
8265 event_ptid = process_stop_reply (stop_reply, status);
8266 break;
8267 }
8268 case 'O': /* Console output. */
8269 remote_console_output (buf + 1);
8270 break;
8271 case '\0':
8272 if (rs->last_sent_signal != GDB_SIGNAL_0)
8273 {
8274 /* Zero length reply means that we tried 'S' or 'C' and the
8275 remote system doesn't support it. */
8276 target_terminal::ours_for_output ();
8277 gdb_printf
8278 ("Can't send signals to this remote system. %s not sent.\n",
8279 gdb_signal_to_name (rs->last_sent_signal));
8280 rs->last_sent_signal = GDB_SIGNAL_0;
8281 target_terminal::inferior ();
8282
8283 strcpy (buf, rs->last_sent_step ? "s" : "c");
8284 putpkt (buf);
8285 break;
8286 }
8287 /* fallthrough */
8288 default:
8289 warning (_("Invalid remote reply: %s"), buf);
8290 break;
8291 }
8292 }
8293
8294 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8295 return minus_one_ptid;
8296 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8297 {
8298 /* Nothing interesting happened. If we're doing a non-blocking
8299 poll, we're done. Otherwise, go back to waiting. */
8300 if (options & TARGET_WNOHANG)
8301 return minus_one_ptid;
8302 else
8303 goto again;
8304 }
8305 else if (status->kind () != TARGET_WAITKIND_EXITED
8306 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8307 {
8308 if (event_ptid != null_ptid)
8309 record_currthread (rs, event_ptid);
8310 else
8311 event_ptid = first_remote_resumed_thread (this);
8312 }
8313 else
8314 {
8315 /* A process exit. Invalidate our notion of current thread. */
8316 record_currthread (rs, minus_one_ptid);
8317 /* It's possible that the packet did not include a pid. */
8318 if (event_ptid == null_ptid)
8319 event_ptid = first_remote_resumed_thread (this);
8320 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8321 if (event_ptid == null_ptid)
8322 event_ptid = magic_null_ptid;
8323 }
8324
8325 return event_ptid;
8326 }
8327
8328 /* Wait until the remote machine stops, then return, storing status in
8329 STATUS just as `wait' would. */
8330
8331 ptid_t
8332 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8333 target_wait_flags options)
8334 {
8335 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8336
8337 remote_state *rs = get_remote_state ();
8338
8339 /* Start by clearing the flag that asks for our wait method to be called,
8340 we'll mark it again at the end if needed. If the target is not in
8341 async mode then the async token should not be marked. */
8342 if (target_is_async_p ())
8343 clear_async_event_handler (rs->remote_async_inferior_event_token);
8344 else
8345 gdb_assert (!async_event_handler_marked
8346 (rs->remote_async_inferior_event_token));
8347
8348 ptid_t event_ptid;
8349
8350 if (target_is_non_stop_p ())
8351 event_ptid = wait_ns (ptid, status, options);
8352 else
8353 event_ptid = wait_as (ptid, status, options);
8354
8355 if (target_is_async_p ())
8356 {
8357 /* If there are events left in the queue, or unacknowledged
8358 notifications, then tell the event loop to call us again. */
8359 if (!rs->stop_reply_queue.empty ()
8360 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8361 mark_async_event_handler (rs->remote_async_inferior_event_token);
8362 }
8363
8364 return event_ptid;
8365 }
8366
8367 /* Fetch a single register using a 'p' packet. */
8368
8369 int
8370 remote_target::fetch_register_using_p (struct regcache *regcache,
8371 packet_reg *reg)
8372 {
8373 struct gdbarch *gdbarch = regcache->arch ();
8374 struct remote_state *rs = get_remote_state ();
8375 char *buf, *p;
8376 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8377 int i;
8378
8379 if (packet_support (PACKET_p) == PACKET_DISABLE)
8380 return 0;
8381
8382 if (reg->pnum == -1)
8383 return 0;
8384
8385 p = rs->buf.data ();
8386 *p++ = 'p';
8387 p += hexnumstr (p, reg->pnum);
8388 *p++ = '\0';
8389 putpkt (rs->buf);
8390 getpkt (&rs->buf, 0);
8391
8392 buf = rs->buf.data ();
8393
8394 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_p]))
8395 {
8396 case PACKET_OK:
8397 break;
8398 case PACKET_UNKNOWN:
8399 return 0;
8400 case PACKET_ERROR:
8401 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8402 gdbarch_register_name (regcache->arch (),
8403 reg->regnum),
8404 buf);
8405 }
8406
8407 /* If this register is unfetchable, tell the regcache. */
8408 if (buf[0] == 'x')
8409 {
8410 regcache->raw_supply (reg->regnum, NULL);
8411 return 1;
8412 }
8413
8414 /* Otherwise, parse and supply the value. */
8415 p = buf;
8416 i = 0;
8417 while (p[0] != 0)
8418 {
8419 if (p[1] == 0)
8420 error (_("fetch_register_using_p: early buf termination"));
8421
8422 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8423 p += 2;
8424 }
8425 regcache->raw_supply (reg->regnum, regp);
8426 return 1;
8427 }
8428
8429 /* Fetch the registers included in the target's 'g' packet. */
8430
8431 int
8432 remote_target::send_g_packet ()
8433 {
8434 struct remote_state *rs = get_remote_state ();
8435 int buf_len;
8436
8437 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8438 putpkt (rs->buf);
8439 getpkt (&rs->buf, 0);
8440 if (packet_check_result (rs->buf) == PACKET_ERROR)
8441 error (_("Could not read registers; remote failure reply '%s'"),
8442 rs->buf.data ());
8443
8444 /* We can get out of synch in various cases. If the first character
8445 in the buffer is not a hex character, assume that has happened
8446 and try to fetch another packet to read. */
8447 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8448 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8449 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8450 && rs->buf[0] != 'x') /* New: unavailable register value. */
8451 {
8452 remote_debug_printf ("Bad register packet; fetching a new packet");
8453 getpkt (&rs->buf, 0);
8454 }
8455
8456 buf_len = strlen (rs->buf.data ());
8457
8458 /* Sanity check the received packet. */
8459 if (buf_len % 2 != 0)
8460 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8461
8462 return buf_len / 2;
8463 }
8464
8465 void
8466 remote_target::process_g_packet (struct regcache *regcache)
8467 {
8468 struct gdbarch *gdbarch = regcache->arch ();
8469 struct remote_state *rs = get_remote_state ();
8470 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8471 int i, buf_len;
8472 char *p;
8473 char *regs;
8474
8475 buf_len = strlen (rs->buf.data ());
8476
8477 /* Further sanity checks, with knowledge of the architecture. */
8478 if (buf_len > 2 * rsa->sizeof_g_packet)
8479 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8480 "bytes): %s"),
8481 rsa->sizeof_g_packet, buf_len / 2,
8482 rs->buf.data ());
8483
8484 /* Save the size of the packet sent to us by the target. It is used
8485 as a heuristic when determining the max size of packets that the
8486 target can safely receive. */
8487 if (rsa->actual_register_packet_size == 0)
8488 rsa->actual_register_packet_size = buf_len;
8489
8490 /* If this is smaller than we guessed the 'g' packet would be,
8491 update our records. A 'g' reply that doesn't include a register's
8492 value implies either that the register is not available, or that
8493 the 'p' packet must be used. */
8494 if (buf_len < 2 * rsa->sizeof_g_packet)
8495 {
8496 long sizeof_g_packet = buf_len / 2;
8497
8498 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8499 {
8500 long offset = rsa->regs[i].offset;
8501 long reg_size = register_size (gdbarch, i);
8502
8503 if (rsa->regs[i].pnum == -1)
8504 continue;
8505
8506 if (offset >= sizeof_g_packet)
8507 rsa->regs[i].in_g_packet = 0;
8508 else if (offset + reg_size > sizeof_g_packet)
8509 error (_("Truncated register %d in remote 'g' packet"), i);
8510 else
8511 rsa->regs[i].in_g_packet = 1;
8512 }
8513
8514 /* Looks valid enough, we can assume this is the correct length
8515 for a 'g' packet. It's important not to adjust
8516 rsa->sizeof_g_packet if we have truncated registers otherwise
8517 this "if" won't be run the next time the method is called
8518 with a packet of the same size and one of the internal errors
8519 below will trigger instead. */
8520 rsa->sizeof_g_packet = sizeof_g_packet;
8521 }
8522
8523 regs = (char *) alloca (rsa->sizeof_g_packet);
8524
8525 /* Unimplemented registers read as all bits zero. */
8526 memset (regs, 0, rsa->sizeof_g_packet);
8527
8528 /* Reply describes registers byte by byte, each byte encoded as two
8529 hex characters. Suck them all up, then supply them to the
8530 register cacheing/storage mechanism. */
8531
8532 p = rs->buf.data ();
8533 for (i = 0; i < rsa->sizeof_g_packet; i++)
8534 {
8535 if (p[0] == 0 || p[1] == 0)
8536 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8537 internal_error (_("unexpected end of 'g' packet reply"));
8538
8539 if (p[0] == 'x' && p[1] == 'x')
8540 regs[i] = 0; /* 'x' */
8541 else
8542 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8543 p += 2;
8544 }
8545
8546 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8547 {
8548 struct packet_reg *r = &rsa->regs[i];
8549 long reg_size = register_size (gdbarch, i);
8550
8551 if (r->in_g_packet)
8552 {
8553 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8554 /* This shouldn't happen - we adjusted in_g_packet above. */
8555 internal_error (_("unexpected end of 'g' packet reply"));
8556 else if (rs->buf[r->offset * 2] == 'x')
8557 {
8558 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8559 /* The register isn't available, mark it as such (at
8560 the same time setting the value to zero). */
8561 regcache->raw_supply (r->regnum, NULL);
8562 }
8563 else
8564 regcache->raw_supply (r->regnum, regs + r->offset);
8565 }
8566 }
8567 }
8568
8569 void
8570 remote_target::fetch_registers_using_g (struct regcache *regcache)
8571 {
8572 send_g_packet ();
8573 process_g_packet (regcache);
8574 }
8575
8576 /* Make the remote selected traceframe match GDB's selected
8577 traceframe. */
8578
8579 void
8580 remote_target::set_remote_traceframe ()
8581 {
8582 int newnum;
8583 struct remote_state *rs = get_remote_state ();
8584
8585 if (rs->remote_traceframe_number == get_traceframe_number ())
8586 return;
8587
8588 /* Avoid recursion, remote_trace_find calls us again. */
8589 rs->remote_traceframe_number = get_traceframe_number ();
8590
8591 newnum = target_trace_find (tfind_number,
8592 get_traceframe_number (), 0, 0, NULL);
8593
8594 /* Should not happen. If it does, all bets are off. */
8595 if (newnum != get_traceframe_number ())
8596 warning (_("could not set remote traceframe"));
8597 }
8598
8599 void
8600 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8601 {
8602 struct gdbarch *gdbarch = regcache->arch ();
8603 struct remote_state *rs = get_remote_state ();
8604 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8605 int i;
8606
8607 set_remote_traceframe ();
8608 set_general_thread (regcache->ptid ());
8609
8610 if (regnum >= 0)
8611 {
8612 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8613
8614 gdb_assert (reg != NULL);
8615
8616 /* If this register might be in the 'g' packet, try that first -
8617 we are likely to read more than one register. If this is the
8618 first 'g' packet, we might be overly optimistic about its
8619 contents, so fall back to 'p'. */
8620 if (reg->in_g_packet)
8621 {
8622 fetch_registers_using_g (regcache);
8623 if (reg->in_g_packet)
8624 return;
8625 }
8626
8627 if (fetch_register_using_p (regcache, reg))
8628 return;
8629
8630 /* This register is not available. */
8631 regcache->raw_supply (reg->regnum, NULL);
8632
8633 return;
8634 }
8635
8636 fetch_registers_using_g (regcache);
8637
8638 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8639 if (!rsa->regs[i].in_g_packet)
8640 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8641 {
8642 /* This register is not available. */
8643 regcache->raw_supply (i, NULL);
8644 }
8645 }
8646
8647 /* Prepare to store registers. Since we may send them all (using a
8648 'G' request), we have to read out the ones we don't want to change
8649 first. */
8650
8651 void
8652 remote_target::prepare_to_store (struct regcache *regcache)
8653 {
8654 struct remote_state *rs = get_remote_state ();
8655 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8656 int i;
8657
8658 /* Make sure the entire registers array is valid. */
8659 switch (packet_support (PACKET_P))
8660 {
8661 case PACKET_DISABLE:
8662 case PACKET_SUPPORT_UNKNOWN:
8663 /* Make sure all the necessary registers are cached. */
8664 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8665 if (rsa->regs[i].in_g_packet)
8666 regcache->raw_update (rsa->regs[i].regnum);
8667 break;
8668 case PACKET_ENABLE:
8669 break;
8670 }
8671 }
8672
8673 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8674 packet was not recognized. */
8675
8676 int
8677 remote_target::store_register_using_P (const struct regcache *regcache,
8678 packet_reg *reg)
8679 {
8680 struct gdbarch *gdbarch = regcache->arch ();
8681 struct remote_state *rs = get_remote_state ();
8682 /* Try storing a single register. */
8683 char *buf = rs->buf.data ();
8684 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8685 char *p;
8686
8687 if (packet_support (PACKET_P) == PACKET_DISABLE)
8688 return 0;
8689
8690 if (reg->pnum == -1)
8691 return 0;
8692
8693 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8694 p = buf + strlen (buf);
8695 regcache->raw_collect (reg->regnum, regp);
8696 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8697 putpkt (rs->buf);
8698 getpkt (&rs->buf, 0);
8699
8700 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8701 {
8702 case PACKET_OK:
8703 return 1;
8704 case PACKET_ERROR:
8705 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8706 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
8707 case PACKET_UNKNOWN:
8708 return 0;
8709 default:
8710 internal_error (_("Bad result from packet_ok"));
8711 }
8712 }
8713
8714 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8715 contents of the register cache buffer. FIXME: ignores errors. */
8716
8717 void
8718 remote_target::store_registers_using_G (const struct regcache *regcache)
8719 {
8720 struct remote_state *rs = get_remote_state ();
8721 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8722 gdb_byte *regs;
8723 char *p;
8724
8725 /* Extract all the registers in the regcache copying them into a
8726 local buffer. */
8727 {
8728 int i;
8729
8730 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8731 memset (regs, 0, rsa->sizeof_g_packet);
8732 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8733 {
8734 struct packet_reg *r = &rsa->regs[i];
8735
8736 if (r->in_g_packet)
8737 regcache->raw_collect (r->regnum, regs + r->offset);
8738 }
8739 }
8740
8741 /* Command describes registers byte by byte,
8742 each byte encoded as two hex characters. */
8743 p = rs->buf.data ();
8744 *p++ = 'G';
8745 bin2hex (regs, p, rsa->sizeof_g_packet);
8746 putpkt (rs->buf);
8747 getpkt (&rs->buf, 0);
8748 if (packet_check_result (rs->buf) == PACKET_ERROR)
8749 error (_("Could not write registers; remote failure reply '%s'"),
8750 rs->buf.data ());
8751 }
8752
8753 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8754 of the register cache buffer. FIXME: ignores errors. */
8755
8756 void
8757 remote_target::store_registers (struct regcache *regcache, int regnum)
8758 {
8759 struct gdbarch *gdbarch = regcache->arch ();
8760 struct remote_state *rs = get_remote_state ();
8761 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8762 int i;
8763
8764 set_remote_traceframe ();
8765 set_general_thread (regcache->ptid ());
8766
8767 if (regnum >= 0)
8768 {
8769 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8770
8771 gdb_assert (reg != NULL);
8772
8773 /* Always prefer to store registers using the 'P' packet if
8774 possible; we often change only a small number of registers.
8775 Sometimes we change a larger number; we'd need help from a
8776 higher layer to know to use 'G'. */
8777 if (store_register_using_P (regcache, reg))
8778 return;
8779
8780 /* For now, don't complain if we have no way to write the
8781 register. GDB loses track of unavailable registers too
8782 easily. Some day, this may be an error. We don't have
8783 any way to read the register, either... */
8784 if (!reg->in_g_packet)
8785 return;
8786
8787 store_registers_using_G (regcache);
8788 return;
8789 }
8790
8791 store_registers_using_G (regcache);
8792
8793 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8794 if (!rsa->regs[i].in_g_packet)
8795 if (!store_register_using_P (regcache, &rsa->regs[i]))
8796 /* See above for why we do not issue an error here. */
8797 continue;
8798 }
8799 \f
8800
8801 /* Return the number of hex digits in num. */
8802
8803 static int
8804 hexnumlen (ULONGEST num)
8805 {
8806 int i;
8807
8808 for (i = 0; num != 0; i++)
8809 num >>= 4;
8810
8811 return std::max (i, 1);
8812 }
8813
8814 /* Set BUF to the minimum number of hex digits representing NUM. */
8815
8816 static int
8817 hexnumstr (char *buf, ULONGEST num)
8818 {
8819 int len = hexnumlen (num);
8820
8821 return hexnumnstr (buf, num, len);
8822 }
8823
8824
8825 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
8826
8827 static int
8828 hexnumnstr (char *buf, ULONGEST num, int width)
8829 {
8830 int i;
8831
8832 buf[width] = '\0';
8833
8834 for (i = width - 1; i >= 0; i--)
8835 {
8836 buf[i] = "0123456789abcdef"[(num & 0xf)];
8837 num >>= 4;
8838 }
8839
8840 return width;
8841 }
8842
8843 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8844
8845 static CORE_ADDR
8846 remote_address_masked (CORE_ADDR addr)
8847 {
8848 unsigned int address_size = remote_address_size;
8849
8850 /* If "remoteaddresssize" was not set, default to target address size. */
8851 if (!address_size)
8852 address_size = gdbarch_addr_bit (target_gdbarch ());
8853
8854 if (address_size > 0
8855 && address_size < (sizeof (ULONGEST) * 8))
8856 {
8857 /* Only create a mask when that mask can safely be constructed
8858 in a ULONGEST variable. */
8859 ULONGEST mask = 1;
8860
8861 mask = (mask << address_size) - 1;
8862 addr &= mask;
8863 }
8864 return addr;
8865 }
8866
8867 /* Determine whether the remote target supports binary downloading.
8868 This is accomplished by sending a no-op memory write of zero length
8869 to the target at the specified address. It does not suffice to send
8870 the whole packet, since many stubs strip the eighth bit and
8871 subsequently compute a wrong checksum, which causes real havoc with
8872 remote_write_bytes.
8873
8874 NOTE: This can still lose if the serial line is not eight-bit
8875 clean. In cases like this, the user should clear "remote
8876 X-packet". */
8877
8878 void
8879 remote_target::check_binary_download (CORE_ADDR addr)
8880 {
8881 struct remote_state *rs = get_remote_state ();
8882
8883 switch (packet_support (PACKET_X))
8884 {
8885 case PACKET_DISABLE:
8886 break;
8887 case PACKET_ENABLE:
8888 break;
8889 case PACKET_SUPPORT_UNKNOWN:
8890 {
8891 char *p;
8892
8893 p = rs->buf.data ();
8894 *p++ = 'X';
8895 p += hexnumstr (p, (ULONGEST) addr);
8896 *p++ = ',';
8897 p += hexnumstr (p, (ULONGEST) 0);
8898 *p++ = ':';
8899 *p = '\0';
8900
8901 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
8902 getpkt (&rs->buf, 0);
8903
8904 if (rs->buf[0] == '\0')
8905 {
8906 remote_debug_printf ("binary downloading NOT supported by target");
8907 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8908 }
8909 else
8910 {
8911 remote_debug_printf ("binary downloading supported by target");
8912 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8913 }
8914 break;
8915 }
8916 }
8917 }
8918
8919 /* Helper function to resize the payload in order to try to get a good
8920 alignment. We try to write an amount of data such that the next write will
8921 start on an address aligned on REMOTE_ALIGN_WRITES. */
8922
8923 static int
8924 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8925 {
8926 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8927 }
8928
8929 /* Write memory data directly to the remote machine.
8930 This does not inform the data cache; the data cache uses this.
8931 HEADER is the starting part of the packet.
8932 MEMADDR is the address in the remote memory space.
8933 MYADDR is the address of the buffer in our space.
8934 LEN_UNITS is the number of addressable units to write.
8935 UNIT_SIZE is the length in bytes of an addressable unit.
8936 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8937 should send data as binary ('X'), or hex-encoded ('M').
8938
8939 The function creates packet of the form
8940 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8941
8942 where encoding of <DATA> is terminated by PACKET_FORMAT.
8943
8944 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8945 are omitted.
8946
8947 Return the transferred status, error or OK (an
8948 'enum target_xfer_status' value). Save the number of addressable units
8949 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8950
8951 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8952 exchange between gdb and the stub could look like (?? in place of the
8953 checksum):
8954
8955 -> $m1000,4#??
8956 <- aaaabbbbccccdddd
8957
8958 -> $M1000,3:eeeeffffeeee#??
8959 <- OK
8960
8961 -> $m1000,4#??
8962 <- eeeeffffeeeedddd */
8963
8964 target_xfer_status
8965 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8966 const gdb_byte *myaddr,
8967 ULONGEST len_units,
8968 int unit_size,
8969 ULONGEST *xfered_len_units,
8970 char packet_format, int use_length)
8971 {
8972 struct remote_state *rs = get_remote_state ();
8973 char *p;
8974 char *plen = NULL;
8975 int plenlen = 0;
8976 int todo_units;
8977 int units_written;
8978 int payload_capacity_bytes;
8979 int payload_length_bytes;
8980
8981 if (packet_format != 'X' && packet_format != 'M')
8982 internal_error (_("remote_write_bytes_aux: bad packet format"));
8983
8984 if (len_units == 0)
8985 return TARGET_XFER_EOF;
8986
8987 payload_capacity_bytes = get_memory_write_packet_size ();
8988
8989 /* The packet buffer will be large enough for the payload;
8990 get_memory_packet_size ensures this. */
8991 rs->buf[0] = '\0';
8992
8993 /* Compute the size of the actual payload by subtracting out the
8994 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8995
8996 payload_capacity_bytes -= strlen ("$,:#NN");
8997 if (!use_length)
8998 /* The comma won't be used. */
8999 payload_capacity_bytes += 1;
9000 payload_capacity_bytes -= strlen (header);
9001 payload_capacity_bytes -= hexnumlen (memaddr);
9002
9003 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9004
9005 strcat (rs->buf.data (), header);
9006 p = rs->buf.data () + strlen (header);
9007
9008 /* Compute a best guess of the number of bytes actually transfered. */
9009 if (packet_format == 'X')
9010 {
9011 /* Best guess at number of bytes that will fit. */
9012 todo_units = std::min (len_units,
9013 (ULONGEST) payload_capacity_bytes / unit_size);
9014 if (use_length)
9015 payload_capacity_bytes -= hexnumlen (todo_units);
9016 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9017 }
9018 else
9019 {
9020 /* Number of bytes that will fit. */
9021 todo_units
9022 = std::min (len_units,
9023 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9024 if (use_length)
9025 payload_capacity_bytes -= hexnumlen (todo_units);
9026 todo_units = std::min (todo_units,
9027 (payload_capacity_bytes / unit_size) / 2);
9028 }
9029
9030 if (todo_units <= 0)
9031 internal_error (_("minimum packet size too small to write data"));
9032
9033 /* If we already need another packet, then try to align the end
9034 of this packet to a useful boundary. */
9035 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9036 todo_units = align_for_efficient_write (todo_units, memaddr);
9037
9038 /* Append "<memaddr>". */
9039 memaddr = remote_address_masked (memaddr);
9040 p += hexnumstr (p, (ULONGEST) memaddr);
9041
9042 if (use_length)
9043 {
9044 /* Append ",". */
9045 *p++ = ',';
9046
9047 /* Append the length and retain its location and size. It may need to be
9048 adjusted once the packet body has been created. */
9049 plen = p;
9050 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9051 p += plenlen;
9052 }
9053
9054 /* Append ":". */
9055 *p++ = ':';
9056 *p = '\0';
9057
9058 /* Append the packet body. */
9059 if (packet_format == 'X')
9060 {
9061 /* Binary mode. Send target system values byte by byte, in
9062 increasing byte addresses. Only escape certain critical
9063 characters. */
9064 payload_length_bytes =
9065 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9066 &units_written, payload_capacity_bytes);
9067
9068 /* If not all TODO units fit, then we'll need another packet. Make
9069 a second try to keep the end of the packet aligned. Don't do
9070 this if the packet is tiny. */
9071 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9072 {
9073 int new_todo_units;
9074
9075 new_todo_units = align_for_efficient_write (units_written, memaddr);
9076
9077 if (new_todo_units != units_written)
9078 payload_length_bytes =
9079 remote_escape_output (myaddr, new_todo_units, unit_size,
9080 (gdb_byte *) p, &units_written,
9081 payload_capacity_bytes);
9082 }
9083
9084 p += payload_length_bytes;
9085 if (use_length && units_written < todo_units)
9086 {
9087 /* Escape chars have filled up the buffer prematurely,
9088 and we have actually sent fewer units than planned.
9089 Fix-up the length field of the packet. Use the same
9090 number of characters as before. */
9091 plen += hexnumnstr (plen, (ULONGEST) units_written,
9092 plenlen);
9093 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9094 }
9095 }
9096 else
9097 {
9098 /* Normal mode: Send target system values byte by byte, in
9099 increasing byte addresses. Each byte is encoded as a two hex
9100 value. */
9101 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9102 units_written = todo_units;
9103 }
9104
9105 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9106 getpkt (&rs->buf, 0);
9107
9108 if (rs->buf[0] == 'E')
9109 return TARGET_XFER_E_IO;
9110
9111 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9112 send fewer units than we'd planned. */
9113 *xfered_len_units = (ULONGEST) units_written;
9114 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9115 }
9116
9117 /* Write memory data directly to the remote machine.
9118 This does not inform the data cache; the data cache uses this.
9119 MEMADDR is the address in the remote memory space.
9120 MYADDR is the address of the buffer in our space.
9121 LEN is the number of bytes.
9122
9123 Return the transferred status, error or OK (an
9124 'enum target_xfer_status' value). Save the number of bytes
9125 transferred in *XFERED_LEN. Only transfer a single packet. */
9126
9127 target_xfer_status
9128 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9129 ULONGEST len, int unit_size,
9130 ULONGEST *xfered_len)
9131 {
9132 const char *packet_format = NULL;
9133
9134 /* Check whether the target supports binary download. */
9135 check_binary_download (memaddr);
9136
9137 switch (packet_support (PACKET_X))
9138 {
9139 case PACKET_ENABLE:
9140 packet_format = "X";
9141 break;
9142 case PACKET_DISABLE:
9143 packet_format = "M";
9144 break;
9145 case PACKET_SUPPORT_UNKNOWN:
9146 internal_error (_("remote_write_bytes: bad internal state"));
9147 default:
9148 internal_error (_("bad switch"));
9149 }
9150
9151 return remote_write_bytes_aux (packet_format,
9152 memaddr, myaddr, len, unit_size, xfered_len,
9153 packet_format[0], 1);
9154 }
9155
9156 /* Read memory data directly from the remote machine.
9157 This does not use the data cache; the data cache uses this.
9158 MEMADDR is the address in the remote memory space.
9159 MYADDR is the address of the buffer in our space.
9160 LEN_UNITS is the number of addressable memory units to read..
9161 UNIT_SIZE is the length in bytes of an addressable unit.
9162
9163 Return the transferred status, error or OK (an
9164 'enum target_xfer_status' value). Save the number of bytes
9165 transferred in *XFERED_LEN_UNITS.
9166
9167 See the comment of remote_write_bytes_aux for an example of
9168 memory read/write exchange between gdb and the stub. */
9169
9170 target_xfer_status
9171 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9172 ULONGEST len_units,
9173 int unit_size, ULONGEST *xfered_len_units)
9174 {
9175 struct remote_state *rs = get_remote_state ();
9176 int buf_size_bytes; /* Max size of packet output buffer. */
9177 char *p;
9178 int todo_units;
9179 int decoded_bytes;
9180
9181 buf_size_bytes = get_memory_read_packet_size ();
9182 /* The packet buffer will be large enough for the payload;
9183 get_memory_packet_size ensures this. */
9184
9185 /* Number of units that will fit. */
9186 todo_units = std::min (len_units,
9187 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9188
9189 /* Construct "m"<memaddr>","<len>". */
9190 memaddr = remote_address_masked (memaddr);
9191 p = rs->buf.data ();
9192 *p++ = 'm';
9193 p += hexnumstr (p, (ULONGEST) memaddr);
9194 *p++ = ',';
9195 p += hexnumstr (p, (ULONGEST) todo_units);
9196 *p = '\0';
9197 putpkt (rs->buf);
9198 getpkt (&rs->buf, 0);
9199 if (rs->buf[0] == 'E'
9200 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9201 && rs->buf[3] == '\0')
9202 return TARGET_XFER_E_IO;
9203 /* Reply describes memory byte by byte, each byte encoded as two hex
9204 characters. */
9205 p = rs->buf.data ();
9206 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9207 /* Return what we have. Let higher layers handle partial reads. */
9208 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9209 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9210 }
9211
9212 /* Using the set of read-only target sections of remote, read live
9213 read-only memory.
9214
9215 For interface/parameters/return description see target.h,
9216 to_xfer_partial. */
9217
9218 target_xfer_status
9219 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9220 ULONGEST memaddr,
9221 ULONGEST len,
9222 int unit_size,
9223 ULONGEST *xfered_len)
9224 {
9225 const struct target_section *secp;
9226
9227 secp = target_section_by_addr (this, memaddr);
9228 if (secp != NULL
9229 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9230 {
9231 ULONGEST memend = memaddr + len;
9232
9233 const target_section_table *table = target_get_section_table (this);
9234 for (const target_section &p : *table)
9235 {
9236 if (memaddr >= p.addr)
9237 {
9238 if (memend <= p.endaddr)
9239 {
9240 /* Entire transfer is within this section. */
9241 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9242 xfered_len);
9243 }
9244 else if (memaddr >= p.endaddr)
9245 {
9246 /* This section ends before the transfer starts. */
9247 continue;
9248 }
9249 else
9250 {
9251 /* This section overlaps the transfer. Just do half. */
9252 len = p.endaddr - memaddr;
9253 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9254 xfered_len);
9255 }
9256 }
9257 }
9258 }
9259
9260 return TARGET_XFER_EOF;
9261 }
9262
9263 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9264 first if the requested memory is unavailable in traceframe.
9265 Otherwise, fall back to remote_read_bytes_1. */
9266
9267 target_xfer_status
9268 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9269 gdb_byte *myaddr, ULONGEST len, int unit_size,
9270 ULONGEST *xfered_len)
9271 {
9272 if (len == 0)
9273 return TARGET_XFER_EOF;
9274
9275 if (get_traceframe_number () != -1)
9276 {
9277 std::vector<mem_range> available;
9278
9279 /* If we fail to get the set of available memory, then the
9280 target does not support querying traceframe info, and so we
9281 attempt reading from the traceframe anyway (assuming the
9282 target implements the old QTro packet then). */
9283 if (traceframe_available_memory (&available, memaddr, len))
9284 {
9285 if (available.empty () || available[0].start != memaddr)
9286 {
9287 enum target_xfer_status res;
9288
9289 /* Don't read into the traceframe's available
9290 memory. */
9291 if (!available.empty ())
9292 {
9293 LONGEST oldlen = len;
9294
9295 len = available[0].start - memaddr;
9296 gdb_assert (len <= oldlen);
9297 }
9298
9299 /* This goes through the topmost target again. */
9300 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9301 len, unit_size, xfered_len);
9302 if (res == TARGET_XFER_OK)
9303 return TARGET_XFER_OK;
9304 else
9305 {
9306 /* No use trying further, we know some memory starting
9307 at MEMADDR isn't available. */
9308 *xfered_len = len;
9309 return (*xfered_len != 0) ?
9310 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9311 }
9312 }
9313
9314 /* Don't try to read more than how much is available, in
9315 case the target implements the deprecated QTro packet to
9316 cater for older GDBs (the target's knowledge of read-only
9317 sections may be outdated by now). */
9318 len = available[0].length;
9319 }
9320 }
9321
9322 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9323 }
9324
9325 \f
9326
9327 /* Sends a packet with content determined by the printf format string
9328 FORMAT and the remaining arguments, then gets the reply. Returns
9329 whether the packet was a success, a failure, or unknown. */
9330
9331 packet_result
9332 remote_target::remote_send_printf (const char *format, ...)
9333 {
9334 struct remote_state *rs = get_remote_state ();
9335 int max_size = get_remote_packet_size ();
9336 va_list ap;
9337
9338 va_start (ap, format);
9339
9340 rs->buf[0] = '\0';
9341 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9342
9343 va_end (ap);
9344
9345 if (size >= max_size)
9346 internal_error (_("Too long remote packet."));
9347
9348 if (putpkt (rs->buf) < 0)
9349 error (_("Communication problem with target."));
9350
9351 rs->buf[0] = '\0';
9352 getpkt (&rs->buf, 0);
9353
9354 return packet_check_result (rs->buf);
9355 }
9356
9357 /* Flash writing can take quite some time. We'll set
9358 effectively infinite timeout for flash operations.
9359 In future, we'll need to decide on a better approach. */
9360 static const int remote_flash_timeout = 1000;
9361
9362 void
9363 remote_target::flash_erase (ULONGEST address, LONGEST length)
9364 {
9365 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9366 enum packet_result ret;
9367 scoped_restore restore_timeout
9368 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9369
9370 ret = remote_send_printf ("vFlashErase:%s,%s",
9371 phex (address, addr_size),
9372 phex (length, 4));
9373 switch (ret)
9374 {
9375 case PACKET_UNKNOWN:
9376 error (_("Remote target does not support flash erase"));
9377 case PACKET_ERROR:
9378 error (_("Error erasing flash with vFlashErase packet"));
9379 default:
9380 break;
9381 }
9382 }
9383
9384 target_xfer_status
9385 remote_target::remote_flash_write (ULONGEST address,
9386 ULONGEST length, ULONGEST *xfered_len,
9387 const gdb_byte *data)
9388 {
9389 scoped_restore restore_timeout
9390 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9391 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9392 xfered_len,'X', 0);
9393 }
9394
9395 void
9396 remote_target::flash_done ()
9397 {
9398 int ret;
9399
9400 scoped_restore restore_timeout
9401 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9402
9403 ret = remote_send_printf ("vFlashDone");
9404
9405 switch (ret)
9406 {
9407 case PACKET_UNKNOWN:
9408 error (_("Remote target does not support vFlashDone"));
9409 case PACKET_ERROR:
9410 error (_("Error finishing flash operation"));
9411 default:
9412 break;
9413 }
9414 }
9415
9416 \f
9417 /* Stuff for dealing with the packets which are part of this protocol.
9418 See comment at top of file for details. */
9419
9420 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9421 error to higher layers. Called when a serial error is detected.
9422 The exception message is STRING, followed by a colon and a blank,
9423 the system error message for errno at function entry and final dot
9424 for output compatibility with throw_perror_with_name. */
9425
9426 static void
9427 unpush_and_perror (remote_target *target, const char *string)
9428 {
9429 int saved_errno = errno;
9430
9431 remote_unpush_target (target);
9432 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9433 safe_strerror (saved_errno));
9434 }
9435
9436 /* Read a single character from the remote end. The current quit
9437 handler is overridden to avoid quitting in the middle of packet
9438 sequence, as that would break communication with the remote server.
9439 See remote_serial_quit_handler for more detail. */
9440
9441 int
9442 remote_target::readchar (int timeout)
9443 {
9444 int ch;
9445 struct remote_state *rs = get_remote_state ();
9446
9447 {
9448 scoped_restore restore_quit_target
9449 = make_scoped_restore (&curr_quit_handler_target, this);
9450 scoped_restore restore_quit
9451 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9452
9453 rs->got_ctrlc_during_io = 0;
9454
9455 ch = serial_readchar (rs->remote_desc, timeout);
9456
9457 if (rs->got_ctrlc_during_io)
9458 set_quit_flag ();
9459 }
9460
9461 if (ch >= 0)
9462 return ch;
9463
9464 switch ((enum serial_rc) ch)
9465 {
9466 case SERIAL_EOF:
9467 remote_unpush_target (this);
9468 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9469 /* no return */
9470 case SERIAL_ERROR:
9471 unpush_and_perror (this, _("Remote communication error. "
9472 "Target disconnected."));
9473 /* no return */
9474 case SERIAL_TIMEOUT:
9475 break;
9476 }
9477 return ch;
9478 }
9479
9480 /* Wrapper for serial_write that closes the target and throws if
9481 writing fails. The current quit handler is overridden to avoid
9482 quitting in the middle of packet sequence, as that would break
9483 communication with the remote server. See
9484 remote_serial_quit_handler for more detail. */
9485
9486 void
9487 remote_target::remote_serial_write (const char *str, int len)
9488 {
9489 struct remote_state *rs = get_remote_state ();
9490
9491 scoped_restore restore_quit_target
9492 = make_scoped_restore (&curr_quit_handler_target, this);
9493 scoped_restore restore_quit
9494 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9495
9496 rs->got_ctrlc_during_io = 0;
9497
9498 if (serial_write (rs->remote_desc, str, len))
9499 {
9500 unpush_and_perror (this, _("Remote communication error. "
9501 "Target disconnected."));
9502 }
9503
9504 if (rs->got_ctrlc_during_io)
9505 set_quit_flag ();
9506 }
9507
9508 /* Return a string representing an escaped version of BUF, of len N.
9509 E.g. \n is converted to \\n, \t to \\t, etc. */
9510
9511 static std::string
9512 escape_buffer (const char *buf, int n)
9513 {
9514 string_file stb;
9515
9516 stb.putstrn (buf, n, '\\');
9517 return stb.release ();
9518 }
9519
9520 int
9521 remote_target::putpkt (const char *buf)
9522 {
9523 return putpkt_binary (buf, strlen (buf));
9524 }
9525
9526 /* Wrapper around remote_target::putpkt to avoid exporting
9527 remote_target. */
9528
9529 int
9530 putpkt (remote_target *remote, const char *buf)
9531 {
9532 return remote->putpkt (buf);
9533 }
9534
9535 /* Send a packet to the remote machine, with error checking. The data
9536 of the packet is in BUF. The string in BUF can be at most
9537 get_remote_packet_size () - 5 to account for the $, # and checksum,
9538 and for a possible /0 if we are debugging (remote_debug) and want
9539 to print the sent packet as a string. */
9540
9541 int
9542 remote_target::putpkt_binary (const char *buf, int cnt)
9543 {
9544 struct remote_state *rs = get_remote_state ();
9545 int i;
9546 unsigned char csum = 0;
9547 gdb::def_vector<char> data (cnt + 6);
9548 char *buf2 = data.data ();
9549
9550 int ch;
9551 int tcount = 0;
9552 char *p;
9553
9554 /* Catch cases like trying to read memory or listing threads while
9555 we're waiting for a stop reply. The remote server wouldn't be
9556 ready to handle this request, so we'd hang and timeout. We don't
9557 have to worry about this in synchronous mode, because in that
9558 case it's not possible to issue a command while the target is
9559 running. This is not a problem in non-stop mode, because in that
9560 case, the stub is always ready to process serial input. */
9561 if (!target_is_non_stop_p ()
9562 && target_is_async_p ()
9563 && rs->waiting_for_stop_reply)
9564 {
9565 error (_("Cannot execute this command while the target is running.\n"
9566 "Use the \"interrupt\" command to stop the target\n"
9567 "and then try again."));
9568 }
9569
9570 /* Copy the packet into buffer BUF2, encapsulating it
9571 and giving it a checksum. */
9572
9573 p = buf2;
9574 *p++ = '$';
9575
9576 for (i = 0; i < cnt; i++)
9577 {
9578 csum += buf[i];
9579 *p++ = buf[i];
9580 }
9581 *p++ = '#';
9582 *p++ = tohex ((csum >> 4) & 0xf);
9583 *p++ = tohex (csum & 0xf);
9584
9585 /* Send it over and over until we get a positive ack. */
9586
9587 while (1)
9588 {
9589 if (remote_debug)
9590 {
9591 *p = '\0';
9592
9593 int len = (int) (p - buf2);
9594 int max_chars;
9595
9596 if (remote_packet_max_chars < 0)
9597 max_chars = len;
9598 else
9599 max_chars = remote_packet_max_chars;
9600
9601 std::string str
9602 = escape_buffer (buf2, std::min (len, max_chars));
9603
9604 if (len > max_chars)
9605 remote_debug_printf_nofunc
9606 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9607 len - max_chars);
9608 else
9609 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9610 }
9611 remote_serial_write (buf2, p - buf2);
9612
9613 /* If this is a no acks version of the remote protocol, send the
9614 packet and move on. */
9615 if (rs->noack_mode)
9616 break;
9617
9618 /* Read until either a timeout occurs (-2) or '+' is read.
9619 Handle any notification that arrives in the mean time. */
9620 while (1)
9621 {
9622 ch = readchar (remote_timeout);
9623
9624 switch (ch)
9625 {
9626 case '+':
9627 remote_debug_printf_nofunc ("Received Ack");
9628 return 1;
9629 case '-':
9630 remote_debug_printf_nofunc ("Received Nak");
9631 /* FALLTHROUGH */
9632 case SERIAL_TIMEOUT:
9633 tcount++;
9634 if (tcount > 3)
9635 return 0;
9636 break; /* Retransmit buffer. */
9637 case '$':
9638 {
9639 remote_debug_printf ("Packet instead of Ack, ignoring it");
9640 /* It's probably an old response sent because an ACK
9641 was lost. Gobble up the packet and ack it so it
9642 doesn't get retransmitted when we resend this
9643 packet. */
9644 skip_frame ();
9645 remote_serial_write ("+", 1);
9646 continue; /* Now, go look for +. */
9647 }
9648
9649 case '%':
9650 {
9651 int val;
9652
9653 /* If we got a notification, handle it, and go back to looking
9654 for an ack. */
9655 /* We've found the start of a notification. Now
9656 collect the data. */
9657 val = read_frame (&rs->buf);
9658 if (val >= 0)
9659 {
9660 remote_debug_printf_nofunc
9661 (" Notification received: %s",
9662 escape_buffer (rs->buf.data (), val).c_str ());
9663
9664 handle_notification (rs->notif_state, rs->buf.data ());
9665 /* We're in sync now, rewait for the ack. */
9666 tcount = 0;
9667 }
9668 else
9669 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9670 rs->buf.data ());
9671 continue;
9672 }
9673 /* fall-through */
9674 default:
9675 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9676 rs->buf.data ());
9677 continue;
9678 }
9679 break; /* Here to retransmit. */
9680 }
9681
9682 #if 0
9683 /* This is wrong. If doing a long backtrace, the user should be
9684 able to get out next time we call QUIT, without anything as
9685 violent as interrupt_query. If we want to provide a way out of
9686 here without getting to the next QUIT, it should be based on
9687 hitting ^C twice as in remote_wait. */
9688 if (quit_flag)
9689 {
9690 quit_flag = 0;
9691 interrupt_query ();
9692 }
9693 #endif
9694 }
9695
9696 return 0;
9697 }
9698
9699 /* Come here after finding the start of a frame when we expected an
9700 ack. Do our best to discard the rest of this packet. */
9701
9702 void
9703 remote_target::skip_frame ()
9704 {
9705 int c;
9706
9707 while (1)
9708 {
9709 c = readchar (remote_timeout);
9710 switch (c)
9711 {
9712 case SERIAL_TIMEOUT:
9713 /* Nothing we can do. */
9714 return;
9715 case '#':
9716 /* Discard the two bytes of checksum and stop. */
9717 c = readchar (remote_timeout);
9718 if (c >= 0)
9719 c = readchar (remote_timeout);
9720
9721 return;
9722 case '*': /* Run length encoding. */
9723 /* Discard the repeat count. */
9724 c = readchar (remote_timeout);
9725 if (c < 0)
9726 return;
9727 break;
9728 default:
9729 /* A regular character. */
9730 break;
9731 }
9732 }
9733 }
9734
9735 /* Come here after finding the start of the frame. Collect the rest
9736 into *BUF, verifying the checksum, length, and handling run-length
9737 compression. NUL terminate the buffer. If there is not enough room,
9738 expand *BUF.
9739
9740 Returns -1 on error, number of characters in buffer (ignoring the
9741 trailing NULL) on success. (could be extended to return one of the
9742 SERIAL status indications). */
9743
9744 long
9745 remote_target::read_frame (gdb::char_vector *buf_p)
9746 {
9747 unsigned char csum;
9748 long bc;
9749 int c;
9750 char *buf = buf_p->data ();
9751 struct remote_state *rs = get_remote_state ();
9752
9753 csum = 0;
9754 bc = 0;
9755
9756 while (1)
9757 {
9758 c = readchar (remote_timeout);
9759 switch (c)
9760 {
9761 case SERIAL_TIMEOUT:
9762 remote_debug_printf ("Timeout in mid-packet, retrying");
9763 return -1;
9764
9765 case '$':
9766 remote_debug_printf ("Saw new packet start in middle of old one");
9767 return -1; /* Start a new packet, count retries. */
9768
9769 case '#':
9770 {
9771 unsigned char pktcsum;
9772 int check_0 = 0;
9773 int check_1 = 0;
9774
9775 buf[bc] = '\0';
9776
9777 check_0 = readchar (remote_timeout);
9778 if (check_0 >= 0)
9779 check_1 = readchar (remote_timeout);
9780
9781 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9782 {
9783 remote_debug_printf ("Timeout in checksum, retrying");
9784 return -1;
9785 }
9786 else if (check_0 < 0 || check_1 < 0)
9787 {
9788 remote_debug_printf ("Communication error in checksum");
9789 return -1;
9790 }
9791
9792 /* Don't recompute the checksum; with no ack packets we
9793 don't have any way to indicate a packet retransmission
9794 is necessary. */
9795 if (rs->noack_mode)
9796 return bc;
9797
9798 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9799 if (csum == pktcsum)
9800 return bc;
9801
9802 remote_debug_printf
9803 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
9804 pktcsum, csum, escape_buffer (buf, bc).c_str ());
9805
9806 /* Number of characters in buffer ignoring trailing
9807 NULL. */
9808 return -1;
9809 }
9810 case '*': /* Run length encoding. */
9811 {
9812 int repeat;
9813
9814 csum += c;
9815 c = readchar (remote_timeout);
9816 csum += c;
9817 repeat = c - ' ' + 3; /* Compute repeat count. */
9818
9819 /* The character before ``*'' is repeated. */
9820
9821 if (repeat > 0 && repeat <= 255 && bc > 0)
9822 {
9823 if (bc + repeat - 1 >= buf_p->size () - 1)
9824 {
9825 /* Make some more room in the buffer. */
9826 buf_p->resize (buf_p->size () + repeat);
9827 buf = buf_p->data ();
9828 }
9829
9830 memset (&buf[bc], buf[bc - 1], repeat);
9831 bc += repeat;
9832 continue;
9833 }
9834
9835 buf[bc] = '\0';
9836 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
9837 return -1;
9838 }
9839 default:
9840 if (bc >= buf_p->size () - 1)
9841 {
9842 /* Make some more room in the buffer. */
9843 buf_p->resize (buf_p->size () * 2);
9844 buf = buf_p->data ();
9845 }
9846
9847 buf[bc++] = c;
9848 csum += c;
9849 continue;
9850 }
9851 }
9852 }
9853
9854 /* Set this to the maximum number of seconds to wait instead of waiting forever
9855 in target_wait(). If this timer times out, then it generates an error and
9856 the command is aborted. This replaces most of the need for timeouts in the
9857 GDB test suite, and makes it possible to distinguish between a hung target
9858 and one with slow communications. */
9859
9860 static int watchdog = 0;
9861 static void
9862 show_watchdog (struct ui_file *file, int from_tty,
9863 struct cmd_list_element *c, const char *value)
9864 {
9865 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
9866 }
9867
9868 /* Read a packet from the remote machine, with error checking, and
9869 store it in *BUF. Resize *BUF if necessary to hold the result. If
9870 FOREVER, wait forever rather than timing out; this is used (in
9871 synchronous mode) to wait for a target that is is executing user
9872 code to stop. */
9873 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9874 don't have to change all the calls to getpkt to deal with the
9875 return value, because at the moment I don't know what the right
9876 thing to do it for those. */
9877
9878 void
9879 remote_target::getpkt (gdb::char_vector *buf, int forever)
9880 {
9881 getpkt_sane (buf, forever);
9882 }
9883
9884
9885 /* Read a packet from the remote machine, with error checking, and
9886 store it in *BUF. Resize *BUF if necessary to hold the result. If
9887 FOREVER, wait forever rather than timing out; this is used (in
9888 synchronous mode) to wait for a target that is is executing user
9889 code to stop. If FOREVER == 0, this function is allowed to time
9890 out gracefully and return an indication of this to the caller.
9891 Otherwise return the number of bytes read. If EXPECTING_NOTIF,
9892 consider receiving a notification enough reason to return to the
9893 caller. *IS_NOTIF is an output boolean that indicates whether *BUF
9894 holds a notification or not (a regular packet). */
9895
9896 int
9897 remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
9898 int forever, int expecting_notif,
9899 int *is_notif)
9900 {
9901 struct remote_state *rs = get_remote_state ();
9902 int c;
9903 int tries;
9904 int timeout;
9905 int val = -1;
9906
9907 strcpy (buf->data (), "timeout");
9908
9909 if (forever)
9910 timeout = watchdog > 0 ? watchdog : -1;
9911 else if (expecting_notif)
9912 timeout = 0; /* There should already be a char in the buffer. If
9913 not, bail out. */
9914 else
9915 timeout = remote_timeout;
9916
9917 #define MAX_TRIES 3
9918
9919 /* Process any number of notifications, and then return when
9920 we get a packet. */
9921 for (;;)
9922 {
9923 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9924 times. */
9925 for (tries = 1; tries <= MAX_TRIES; tries++)
9926 {
9927 /* This can loop forever if the remote side sends us
9928 characters continuously, but if it pauses, we'll get
9929 SERIAL_TIMEOUT from readchar because of timeout. Then
9930 we'll count that as a retry.
9931
9932 Note that even when forever is set, we will only wait
9933 forever prior to the start of a packet. After that, we
9934 expect characters to arrive at a brisk pace. They should
9935 show up within remote_timeout intervals. */
9936 do
9937 c = readchar (timeout);
9938 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9939
9940 if (c == SERIAL_TIMEOUT)
9941 {
9942 if (expecting_notif)
9943 return -1; /* Don't complain, it's normal to not get
9944 anything in this case. */
9945
9946 if (forever) /* Watchdog went off? Kill the target. */
9947 {
9948 remote_unpush_target (this);
9949 throw_error (TARGET_CLOSE_ERROR,
9950 _("Watchdog timeout has expired. "
9951 "Target detached."));
9952 }
9953
9954 remote_debug_printf ("Timed out.");
9955 }
9956 else
9957 {
9958 /* We've found the start of a packet or notification.
9959 Now collect the data. */
9960 val = read_frame (buf);
9961 if (val >= 0)
9962 break;
9963 }
9964
9965 remote_serial_write ("-", 1);
9966 }
9967
9968 if (tries > MAX_TRIES)
9969 {
9970 /* We have tried hard enough, and just can't receive the
9971 packet/notification. Give up. */
9972 gdb_printf (_("Ignoring packet error, continuing...\n"));
9973
9974 /* Skip the ack char if we're in no-ack mode. */
9975 if (!rs->noack_mode)
9976 remote_serial_write ("+", 1);
9977 return -1;
9978 }
9979
9980 /* If we got an ordinary packet, return that to our caller. */
9981 if (c == '$')
9982 {
9983 if (remote_debug)
9984 {
9985 int max_chars;
9986
9987 if (remote_packet_max_chars < 0)
9988 max_chars = val;
9989 else
9990 max_chars = remote_packet_max_chars;
9991
9992 std::string str
9993 = escape_buffer (buf->data (),
9994 std::min (val, max_chars));
9995
9996 if (val > max_chars)
9997 remote_debug_printf_nofunc
9998 ("Packet received: %s [%d bytes omitted]", str.c_str (),
9999 val - max_chars);
10000 else
10001 remote_debug_printf_nofunc ("Packet received: %s",
10002 str.c_str ());
10003 }
10004
10005 /* Skip the ack char if we're in no-ack mode. */
10006 if (!rs->noack_mode)
10007 remote_serial_write ("+", 1);
10008 if (is_notif != NULL)
10009 *is_notif = 0;
10010 return val;
10011 }
10012
10013 /* If we got a notification, handle it, and go back to looking
10014 for a packet. */
10015 else
10016 {
10017 gdb_assert (c == '%');
10018
10019 remote_debug_printf_nofunc
10020 (" Notification received: %s",
10021 escape_buffer (buf->data (), val).c_str ());
10022
10023 if (is_notif != NULL)
10024 *is_notif = 1;
10025
10026 handle_notification (rs->notif_state, buf->data ());
10027
10028 /* Notifications require no acknowledgement. */
10029
10030 if (expecting_notif)
10031 return val;
10032 }
10033 }
10034 }
10035
10036 int
10037 remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
10038 {
10039 return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
10040 }
10041
10042 int
10043 remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
10044 int *is_notif)
10045 {
10046 return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
10047 }
10048
10049 /* Kill any new fork children of inferior INF that haven't been
10050 processed by follow_fork. */
10051
10052 void
10053 remote_target::kill_new_fork_children (inferior *inf)
10054 {
10055 remote_state *rs = get_remote_state ();
10056 struct notif_client *notif = &notif_client_stop;
10057
10058 /* Kill the fork child threads of any threads in inferior INF that are stopped
10059 at a fork event. */
10060 for (thread_info *thread : inf->non_exited_threads ())
10061 {
10062 const target_waitstatus *ws = thread_pending_fork_status (thread);
10063
10064 if (ws == nullptr)
10065 continue;
10066
10067 int child_pid = ws->child_ptid ().pid ();
10068 int res = remote_vkill (child_pid);
10069
10070 if (res != 0)
10071 error (_("Can't kill fork child process %d"), child_pid);
10072 }
10073
10074 /* Check for any pending fork events (not reported or processed yet)
10075 in inferior INF and kill those fork child threads as well. */
10076 remote_notif_get_pending_events (notif);
10077 for (auto &event : rs->stop_reply_queue)
10078 {
10079 if (event->ptid.pid () != inf->pid)
10080 continue;
10081
10082 if (!is_fork_status (event->ws.kind ()))
10083 continue;
10084
10085 int child_pid = event->ws.child_ptid ().pid ();
10086 int res = remote_vkill (child_pid);
10087
10088 if (res != 0)
10089 error (_("Can't kill fork child process %d"), child_pid);
10090 }
10091 }
10092
10093 \f
10094 /* Target hook to kill the current inferior. */
10095
10096 void
10097 remote_target::kill ()
10098 {
10099 int res = -1;
10100 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10101 struct remote_state *rs = get_remote_state ();
10102
10103 gdb_assert (inf != nullptr);
10104
10105 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
10106 {
10107 /* If we're stopped while forking and we haven't followed yet,
10108 kill the child task. We need to do this before killing the
10109 parent task because if this is a vfork then the parent will
10110 be sleeping. */
10111 kill_new_fork_children (inf);
10112
10113 res = remote_vkill (inf->pid);
10114 if (res == 0)
10115 {
10116 target_mourn_inferior (inferior_ptid);
10117 return;
10118 }
10119 }
10120
10121 /* If we are in 'target remote' mode and we are killing the only
10122 inferior, then we will tell gdbserver to exit and unpush the
10123 target. */
10124 if (res == -1 && !remote_multi_process_p (rs)
10125 && number_of_live_inferiors (this) == 1)
10126 {
10127 remote_kill_k ();
10128
10129 /* We've killed the remote end, we get to mourn it. If we are
10130 not in extended mode, mourning the inferior also unpushes
10131 remote_ops from the target stack, which closes the remote
10132 connection. */
10133 target_mourn_inferior (inferior_ptid);
10134
10135 return;
10136 }
10137
10138 error (_("Can't kill process"));
10139 }
10140
10141 /* Send a kill request to the target using the 'vKill' packet. */
10142
10143 int
10144 remote_target::remote_vkill (int pid)
10145 {
10146 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
10147 return -1;
10148
10149 remote_state *rs = get_remote_state ();
10150
10151 /* Tell the remote target to detach. */
10152 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10153 putpkt (rs->buf);
10154 getpkt (&rs->buf, 0);
10155
10156 switch (packet_ok (rs->buf,
10157 &remote_protocol_packets[PACKET_vKill]))
10158 {
10159 case PACKET_OK:
10160 return 0;
10161 case PACKET_ERROR:
10162 return 1;
10163 case PACKET_UNKNOWN:
10164 return -1;
10165 default:
10166 internal_error (_("Bad result from packet_ok"));
10167 }
10168 }
10169
10170 /* Send a kill request to the target using the 'k' packet. */
10171
10172 void
10173 remote_target::remote_kill_k ()
10174 {
10175 /* Catch errors so the user can quit from gdb even when we
10176 aren't on speaking terms with the remote system. */
10177 try
10178 {
10179 putpkt ("k");
10180 }
10181 catch (const gdb_exception_error &ex)
10182 {
10183 if (ex.error == TARGET_CLOSE_ERROR)
10184 {
10185 /* If we got an (EOF) error that caused the target
10186 to go away, then we're done, that's what we wanted.
10187 "k" is susceptible to cause a premature EOF, given
10188 that the remote server isn't actually required to
10189 reply to "k", and it can happen that it doesn't
10190 even get to reply ACK to the "k". */
10191 return;
10192 }
10193
10194 /* Otherwise, something went wrong. We didn't actually kill
10195 the target. Just propagate the exception, and let the
10196 user or higher layers decide what to do. */
10197 throw;
10198 }
10199 }
10200
10201 void
10202 remote_target::mourn_inferior ()
10203 {
10204 struct remote_state *rs = get_remote_state ();
10205
10206 /* We're no longer interested in notification events of an inferior
10207 that exited or was killed/detached. */
10208 discard_pending_stop_replies (current_inferior ());
10209
10210 /* In 'target remote' mode with one inferior, we close the connection. */
10211 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10212 {
10213 remote_unpush_target (this);
10214 return;
10215 }
10216
10217 /* In case we got here due to an error, but we're going to stay
10218 connected. */
10219 rs->waiting_for_stop_reply = 0;
10220
10221 /* If the current general thread belonged to the process we just
10222 detached from or has exited, the remote side current general
10223 thread becomes undefined. Considering a case like this:
10224
10225 - We just got here due to a detach.
10226 - The process that we're detaching from happens to immediately
10227 report a global breakpoint being hit in non-stop mode, in the
10228 same thread we had selected before.
10229 - GDB attaches to this process again.
10230 - This event happens to be the next event we handle.
10231
10232 GDB would consider that the current general thread didn't need to
10233 be set on the stub side (with Hg), since for all it knew,
10234 GENERAL_THREAD hadn't changed.
10235
10236 Notice that although in all-stop mode, the remote server always
10237 sets the current thread to the thread reporting the stop event,
10238 that doesn't happen in non-stop mode; in non-stop, the stub *must
10239 not* change the current thread when reporting a breakpoint hit,
10240 due to the decoupling of event reporting and event handling.
10241
10242 To keep things simple, we always invalidate our notion of the
10243 current thread. */
10244 record_currthread (rs, minus_one_ptid);
10245
10246 /* Call common code to mark the inferior as not running. */
10247 generic_mourn_inferior ();
10248 }
10249
10250 bool
10251 extended_remote_target::supports_disable_randomization ()
10252 {
10253 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
10254 }
10255
10256 void
10257 remote_target::extended_remote_disable_randomization (int val)
10258 {
10259 struct remote_state *rs = get_remote_state ();
10260 char *reply;
10261
10262 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10263 "QDisableRandomization:%x", val);
10264 putpkt (rs->buf);
10265 reply = remote_get_noisy_reply ();
10266 if (*reply == '\0')
10267 error (_("Target does not support QDisableRandomization."));
10268 if (strcmp (reply, "OK") != 0)
10269 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10270 }
10271
10272 int
10273 remote_target::extended_remote_run (const std::string &args)
10274 {
10275 struct remote_state *rs = get_remote_state ();
10276 int len;
10277 const char *remote_exec_file = get_remote_exec_file ();
10278
10279 /* If the user has disabled vRun support, or we have detected that
10280 support is not available, do not try it. */
10281 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
10282 return -1;
10283
10284 strcpy (rs->buf.data (), "vRun;");
10285 len = strlen (rs->buf.data ());
10286
10287 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10288 error (_("Remote file name too long for run packet"));
10289 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10290 strlen (remote_exec_file));
10291
10292 if (!args.empty ())
10293 {
10294 int i;
10295
10296 gdb_argv argv (args.c_str ());
10297 for (i = 0; argv[i] != NULL; i++)
10298 {
10299 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10300 error (_("Argument list too long for run packet"));
10301 rs->buf[len++] = ';';
10302 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10303 strlen (argv[i]));
10304 }
10305 }
10306
10307 rs->buf[len++] = '\0';
10308
10309 putpkt (rs->buf);
10310 getpkt (&rs->buf, 0);
10311
10312 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
10313 {
10314 case PACKET_OK:
10315 /* We have a wait response. All is well. */
10316 return 0;
10317 case PACKET_UNKNOWN:
10318 return -1;
10319 case PACKET_ERROR:
10320 if (remote_exec_file[0] == '\0')
10321 error (_("Running the default executable on the remote target failed; "
10322 "try \"set remote exec-file\"?"));
10323 else
10324 error (_("Running \"%s\" on the remote target failed"),
10325 remote_exec_file);
10326 default:
10327 gdb_assert_not_reached ("bad switch");
10328 }
10329 }
10330
10331 /* Helper function to send set/unset environment packets. ACTION is
10332 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10333 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10334 sent. */
10335
10336 void
10337 remote_target::send_environment_packet (const char *action,
10338 const char *packet,
10339 const char *value)
10340 {
10341 remote_state *rs = get_remote_state ();
10342
10343 /* Convert the environment variable to an hex string, which
10344 is the best format to be transmitted over the wire. */
10345 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10346 strlen (value));
10347
10348 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10349 "%s:%s", packet, encoded_value.c_str ());
10350
10351 putpkt (rs->buf);
10352 getpkt (&rs->buf, 0);
10353 if (strcmp (rs->buf.data (), "OK") != 0)
10354 warning (_("Unable to %s environment variable '%s' on remote."),
10355 action, value);
10356 }
10357
10358 /* Helper function to handle the QEnvironment* packets. */
10359
10360 void
10361 remote_target::extended_remote_environment_support ()
10362 {
10363 remote_state *rs = get_remote_state ();
10364
10365 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10366 {
10367 putpkt ("QEnvironmentReset");
10368 getpkt (&rs->buf, 0);
10369 if (strcmp (rs->buf.data (), "OK") != 0)
10370 warning (_("Unable to reset environment on remote."));
10371 }
10372
10373 gdb_environ *e = &current_inferior ()->environment;
10374
10375 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10376 for (const std::string &el : e->user_set_env ())
10377 send_environment_packet ("set", "QEnvironmentHexEncoded",
10378 el.c_str ());
10379
10380 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10381 for (const std::string &el : e->user_unset_env ())
10382 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10383 }
10384
10385 /* Helper function to set the current working directory for the
10386 inferior in the remote target. */
10387
10388 void
10389 remote_target::extended_remote_set_inferior_cwd ()
10390 {
10391 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10392 {
10393 const std::string &inferior_cwd = current_inferior ()->cwd ();
10394 remote_state *rs = get_remote_state ();
10395
10396 if (!inferior_cwd.empty ())
10397 {
10398 std::string hexpath
10399 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10400 inferior_cwd.size ());
10401
10402 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10403 "QSetWorkingDir:%s", hexpath.c_str ());
10404 }
10405 else
10406 {
10407 /* An empty inferior_cwd means that the user wants us to
10408 reset the remote server's inferior's cwd. */
10409 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10410 "QSetWorkingDir:");
10411 }
10412
10413 putpkt (rs->buf);
10414 getpkt (&rs->buf, 0);
10415 if (packet_ok (rs->buf,
10416 &remote_protocol_packets[PACKET_QSetWorkingDir])
10417 != PACKET_OK)
10418 error (_("\
10419 Remote replied unexpectedly while setting the inferior's working\n\
10420 directory: %s"),
10421 rs->buf.data ());
10422
10423 }
10424 }
10425
10426 /* In the extended protocol we want to be able to do things like
10427 "run" and have them basically work as expected. So we need
10428 a special create_inferior function. We support changing the
10429 executable file and the command line arguments, but not the
10430 environment. */
10431
10432 void
10433 extended_remote_target::create_inferior (const char *exec_file,
10434 const std::string &args,
10435 char **env, int from_tty)
10436 {
10437 int run_worked;
10438 char *stop_reply;
10439 struct remote_state *rs = get_remote_state ();
10440 const char *remote_exec_file = get_remote_exec_file ();
10441
10442 /* If running asynchronously, register the target file descriptor
10443 with the event loop. */
10444 if (target_can_async_p ())
10445 target_async (true);
10446
10447 /* Disable address space randomization if requested (and supported). */
10448 if (supports_disable_randomization ())
10449 extended_remote_disable_randomization (disable_randomization);
10450
10451 /* If startup-with-shell is on, we inform gdbserver to start the
10452 remote inferior using a shell. */
10453 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10454 {
10455 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10456 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10457 putpkt (rs->buf);
10458 getpkt (&rs->buf, 0);
10459 if (strcmp (rs->buf.data (), "OK") != 0)
10460 error (_("\
10461 Remote replied unexpectedly while setting startup-with-shell: %s"),
10462 rs->buf.data ());
10463 }
10464
10465 extended_remote_environment_support ();
10466
10467 extended_remote_set_inferior_cwd ();
10468
10469 /* Now restart the remote server. */
10470 run_worked = extended_remote_run (args) != -1;
10471 if (!run_worked)
10472 {
10473 /* vRun was not supported. Fail if we need it to do what the
10474 user requested. */
10475 if (remote_exec_file[0])
10476 error (_("Remote target does not support \"set remote exec-file\""));
10477 if (!args.empty ())
10478 error (_("Remote target does not support \"set args\" or run ARGS"));
10479
10480 /* Fall back to "R". */
10481 extended_remote_restart ();
10482 }
10483
10484 /* vRun's success return is a stop reply. */
10485 stop_reply = run_worked ? rs->buf.data () : NULL;
10486 add_current_inferior_and_thread (stop_reply);
10487
10488 /* Get updated offsets, if the stub uses qOffsets. */
10489 get_offsets ();
10490 }
10491 \f
10492
10493 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10494 the list of conditions (in agent expression bytecode format), if any, the
10495 target needs to evaluate. The output is placed into the packet buffer
10496 started from BUF and ended at BUF_END. */
10497
10498 static int
10499 remote_add_target_side_condition (struct gdbarch *gdbarch,
10500 struct bp_target_info *bp_tgt, char *buf,
10501 char *buf_end)
10502 {
10503 if (bp_tgt->conditions.empty ())
10504 return 0;
10505
10506 buf += strlen (buf);
10507 xsnprintf (buf, buf_end - buf, "%s", ";");
10508 buf++;
10509
10510 /* Send conditions to the target. */
10511 for (agent_expr *aexpr : bp_tgt->conditions)
10512 {
10513 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10514 buf += strlen (buf);
10515 for (int i = 0; i < aexpr->len; ++i)
10516 buf = pack_hex_byte (buf, aexpr->buf[i]);
10517 *buf = '\0';
10518 }
10519 return 0;
10520 }
10521
10522 static void
10523 remote_add_target_side_commands (struct gdbarch *gdbarch,
10524 struct bp_target_info *bp_tgt, char *buf)
10525 {
10526 if (bp_tgt->tcommands.empty ())
10527 return;
10528
10529 buf += strlen (buf);
10530
10531 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10532 buf += strlen (buf);
10533
10534 /* Concatenate all the agent expressions that are commands into the
10535 cmds parameter. */
10536 for (agent_expr *aexpr : bp_tgt->tcommands)
10537 {
10538 sprintf (buf, "X%x,", aexpr->len);
10539 buf += strlen (buf);
10540 for (int i = 0; i < aexpr->len; ++i)
10541 buf = pack_hex_byte (buf, aexpr->buf[i]);
10542 *buf = '\0';
10543 }
10544 }
10545
10546 /* Insert a breakpoint. On targets that have software breakpoint
10547 support, we ask the remote target to do the work; on targets
10548 which don't, we insert a traditional memory breakpoint. */
10549
10550 int
10551 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10552 struct bp_target_info *bp_tgt)
10553 {
10554 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10555 If it succeeds, then set the support to PACKET_ENABLE. If it
10556 fails, and the user has explicitly requested the Z support then
10557 report an error, otherwise, mark it disabled and go on. */
10558
10559 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10560 {
10561 CORE_ADDR addr = bp_tgt->reqstd_address;
10562 struct remote_state *rs;
10563 char *p, *endbuf;
10564
10565 /* Make sure the remote is pointing at the right process, if
10566 necessary. */
10567 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10568 set_general_process ();
10569
10570 rs = get_remote_state ();
10571 p = rs->buf.data ();
10572 endbuf = p + get_remote_packet_size ();
10573
10574 *(p++) = 'Z';
10575 *(p++) = '0';
10576 *(p++) = ',';
10577 addr = (ULONGEST) remote_address_masked (addr);
10578 p += hexnumstr (p, addr);
10579 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10580
10581 if (supports_evaluation_of_breakpoint_conditions ())
10582 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10583
10584 if (can_run_breakpoint_commands ())
10585 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10586
10587 putpkt (rs->buf);
10588 getpkt (&rs->buf, 0);
10589
10590 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10591 {
10592 case PACKET_ERROR:
10593 return -1;
10594 case PACKET_OK:
10595 return 0;
10596 case PACKET_UNKNOWN:
10597 break;
10598 }
10599 }
10600
10601 /* If this breakpoint has target-side commands but this stub doesn't
10602 support Z0 packets, throw error. */
10603 if (!bp_tgt->tcommands.empty ())
10604 throw_error (NOT_SUPPORTED_ERROR, _("\
10605 Target doesn't support breakpoints that have target side commands."));
10606
10607 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10608 }
10609
10610 int
10611 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10612 struct bp_target_info *bp_tgt,
10613 enum remove_bp_reason reason)
10614 {
10615 CORE_ADDR addr = bp_tgt->placed_address;
10616 struct remote_state *rs = get_remote_state ();
10617
10618 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10619 {
10620 char *p = rs->buf.data ();
10621 char *endbuf = p + get_remote_packet_size ();
10622
10623 /* Make sure the remote is pointing at the right process, if
10624 necessary. */
10625 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10626 set_general_process ();
10627
10628 *(p++) = 'z';
10629 *(p++) = '0';
10630 *(p++) = ',';
10631
10632 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10633 p += hexnumstr (p, addr);
10634 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10635
10636 putpkt (rs->buf);
10637 getpkt (&rs->buf, 0);
10638
10639 return (rs->buf[0] == 'E');
10640 }
10641
10642 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10643 }
10644
10645 static enum Z_packet_type
10646 watchpoint_to_Z_packet (int type)
10647 {
10648 switch (type)
10649 {
10650 case hw_write:
10651 return Z_PACKET_WRITE_WP;
10652 break;
10653 case hw_read:
10654 return Z_PACKET_READ_WP;
10655 break;
10656 case hw_access:
10657 return Z_PACKET_ACCESS_WP;
10658 break;
10659 default:
10660 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
10661 }
10662 }
10663
10664 int
10665 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10666 enum target_hw_bp_type type, struct expression *cond)
10667 {
10668 struct remote_state *rs = get_remote_state ();
10669 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10670 char *p;
10671 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10672
10673 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10674 return 1;
10675
10676 /* Make sure the remote is pointing at the right process, if
10677 necessary. */
10678 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10679 set_general_process ();
10680
10681 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10682 p = strchr (rs->buf.data (), '\0');
10683 addr = remote_address_masked (addr);
10684 p += hexnumstr (p, (ULONGEST) addr);
10685 xsnprintf (p, endbuf - p, ",%x", len);
10686
10687 putpkt (rs->buf);
10688 getpkt (&rs->buf, 0);
10689
10690 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10691 {
10692 case PACKET_ERROR:
10693 return -1;
10694 case PACKET_UNKNOWN:
10695 return 1;
10696 case PACKET_OK:
10697 return 0;
10698 }
10699 internal_error (_("remote_insert_watchpoint: reached end of function"));
10700 }
10701
10702 bool
10703 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10704 CORE_ADDR start, int length)
10705 {
10706 CORE_ADDR diff = remote_address_masked (addr - start);
10707
10708 return diff < length;
10709 }
10710
10711
10712 int
10713 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10714 enum target_hw_bp_type type, struct expression *cond)
10715 {
10716 struct remote_state *rs = get_remote_state ();
10717 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10718 char *p;
10719 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10720
10721 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10722 return -1;
10723
10724 /* Make sure the remote is pointing at the right process, if
10725 necessary. */
10726 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10727 set_general_process ();
10728
10729 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10730 p = strchr (rs->buf.data (), '\0');
10731 addr = remote_address_masked (addr);
10732 p += hexnumstr (p, (ULONGEST) addr);
10733 xsnprintf (p, endbuf - p, ",%x", len);
10734 putpkt (rs->buf);
10735 getpkt (&rs->buf, 0);
10736
10737 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10738 {
10739 case PACKET_ERROR:
10740 case PACKET_UNKNOWN:
10741 return -1;
10742 case PACKET_OK:
10743 return 0;
10744 }
10745 internal_error (_("remote_remove_watchpoint: reached end of function"));
10746 }
10747
10748
10749 static int remote_hw_watchpoint_limit = -1;
10750 static int remote_hw_watchpoint_length_limit = -1;
10751 static int remote_hw_breakpoint_limit = -1;
10752
10753 int
10754 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10755 {
10756 if (remote_hw_watchpoint_length_limit == 0)
10757 return 0;
10758 else if (remote_hw_watchpoint_length_limit < 0)
10759 return 1;
10760 else if (len <= remote_hw_watchpoint_length_limit)
10761 return 1;
10762 else
10763 return 0;
10764 }
10765
10766 int
10767 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10768 {
10769 if (type == bp_hardware_breakpoint)
10770 {
10771 if (remote_hw_breakpoint_limit == 0)
10772 return 0;
10773 else if (remote_hw_breakpoint_limit < 0)
10774 return 1;
10775 else if (cnt <= remote_hw_breakpoint_limit)
10776 return 1;
10777 }
10778 else
10779 {
10780 if (remote_hw_watchpoint_limit == 0)
10781 return 0;
10782 else if (remote_hw_watchpoint_limit < 0)
10783 return 1;
10784 else if (ot)
10785 return -1;
10786 else if (cnt <= remote_hw_watchpoint_limit)
10787 return 1;
10788 }
10789 return -1;
10790 }
10791
10792 /* The to_stopped_by_sw_breakpoint method of target remote. */
10793
10794 bool
10795 remote_target::stopped_by_sw_breakpoint ()
10796 {
10797 struct thread_info *thread = inferior_thread ();
10798
10799 return (thread->priv != NULL
10800 && (get_remote_thread_info (thread)->stop_reason
10801 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10802 }
10803
10804 /* The to_supports_stopped_by_sw_breakpoint method of target
10805 remote. */
10806
10807 bool
10808 remote_target::supports_stopped_by_sw_breakpoint ()
10809 {
10810 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10811 }
10812
10813 /* The to_stopped_by_hw_breakpoint method of target remote. */
10814
10815 bool
10816 remote_target::stopped_by_hw_breakpoint ()
10817 {
10818 struct thread_info *thread = inferior_thread ();
10819
10820 return (thread->priv != NULL
10821 && (get_remote_thread_info (thread)->stop_reason
10822 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10823 }
10824
10825 /* The to_supports_stopped_by_hw_breakpoint method of target
10826 remote. */
10827
10828 bool
10829 remote_target::supports_stopped_by_hw_breakpoint ()
10830 {
10831 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10832 }
10833
10834 bool
10835 remote_target::stopped_by_watchpoint ()
10836 {
10837 struct thread_info *thread = inferior_thread ();
10838
10839 return (thread->priv != NULL
10840 && (get_remote_thread_info (thread)->stop_reason
10841 == TARGET_STOPPED_BY_WATCHPOINT));
10842 }
10843
10844 bool
10845 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10846 {
10847 struct thread_info *thread = inferior_thread ();
10848
10849 if (thread->priv != NULL
10850 && (get_remote_thread_info (thread)->stop_reason
10851 == TARGET_STOPPED_BY_WATCHPOINT))
10852 {
10853 *addr_p = get_remote_thread_info (thread)->watch_data_address;
10854 return true;
10855 }
10856
10857 return false;
10858 }
10859
10860
10861 int
10862 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10863 struct bp_target_info *bp_tgt)
10864 {
10865 CORE_ADDR addr = bp_tgt->reqstd_address;
10866 struct remote_state *rs;
10867 char *p, *endbuf;
10868 char *message;
10869
10870 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10871 return -1;
10872
10873 /* Make sure the remote is pointing at the right process, if
10874 necessary. */
10875 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10876 set_general_process ();
10877
10878 rs = get_remote_state ();
10879 p = rs->buf.data ();
10880 endbuf = p + get_remote_packet_size ();
10881
10882 *(p++) = 'Z';
10883 *(p++) = '1';
10884 *(p++) = ',';
10885
10886 addr = remote_address_masked (addr);
10887 p += hexnumstr (p, (ULONGEST) addr);
10888 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10889
10890 if (supports_evaluation_of_breakpoint_conditions ())
10891 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10892
10893 if (can_run_breakpoint_commands ())
10894 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10895
10896 putpkt (rs->buf);
10897 getpkt (&rs->buf, 0);
10898
10899 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10900 {
10901 case PACKET_ERROR:
10902 if (rs->buf[1] == '.')
10903 {
10904 message = strchr (&rs->buf[2], '.');
10905 if (message)
10906 error (_("Remote failure reply: %s"), message + 1);
10907 }
10908 return -1;
10909 case PACKET_UNKNOWN:
10910 return -1;
10911 case PACKET_OK:
10912 return 0;
10913 }
10914 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
10915 }
10916
10917
10918 int
10919 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10920 struct bp_target_info *bp_tgt)
10921 {
10922 CORE_ADDR addr;
10923 struct remote_state *rs = get_remote_state ();
10924 char *p = rs->buf.data ();
10925 char *endbuf = p + get_remote_packet_size ();
10926
10927 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10928 return -1;
10929
10930 /* Make sure the remote is pointing at the right process, if
10931 necessary. */
10932 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10933 set_general_process ();
10934
10935 *(p++) = 'z';
10936 *(p++) = '1';
10937 *(p++) = ',';
10938
10939 addr = remote_address_masked (bp_tgt->placed_address);
10940 p += hexnumstr (p, (ULONGEST) addr);
10941 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10942
10943 putpkt (rs->buf);
10944 getpkt (&rs->buf, 0);
10945
10946 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10947 {
10948 case PACKET_ERROR:
10949 case PACKET_UNKNOWN:
10950 return -1;
10951 case PACKET_OK:
10952 return 0;
10953 }
10954 internal_error (_("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
11979 {
11980 std::vector<remote_g_packet_guess> guesses;
11981 };
11982
11983 static const registry<gdbarch>::key<struct remote_g_packet_data>
11984 remote_g_packet_data_handle;
11985
11986 static struct remote_g_packet_data *
11987 get_g_packet_data (struct gdbarch *gdbarch)
11988 {
11989 struct remote_g_packet_data *data
11990 = remote_g_packet_data_handle.get (gdbarch);
11991 if (data == nullptr)
11992 data = remote_g_packet_data_handle.emplace (gdbarch);
11993 return data;
11994 }
11995
11996 void
11997 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11998 const struct target_desc *tdesc)
11999 {
12000 struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
12001
12002 gdb_assert (tdesc != NULL);
12003
12004 for (const remote_g_packet_guess &guess : data->guesses)
12005 if (guess.bytes == bytes)
12006 internal_error (_("Duplicate g packet description added for size %d"),
12007 bytes);
12008
12009 data->guesses.emplace_back (bytes, tdesc);
12010 }
12011
12012 /* Return true if remote_read_description would do anything on this target
12013 and architecture, false otherwise. */
12014
12015 static bool
12016 remote_read_description_p (struct target_ops *target)
12017 {
12018 struct remote_g_packet_data *data = get_g_packet_data (target_gdbarch ());
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 = get_g_packet_data (target_gdbarch ());
12027
12028 /* Do not try this during initial connection, when we do not know
12029 whether there is a running but stopped thread. */
12030 if (!target_has_execution () || inferior_ptid == null_ptid)
12031 return beneath ()->read_description ();
12032
12033 if (!data->guesses.empty ())
12034 {
12035 int bytes = send_g_packet ();
12036
12037 for (const remote_g_packet_guess &guess : data->guesses)
12038 if (guess.bytes == bytes)
12039 return guess.tdesc;
12040
12041 /* We discard the g packet. A minor optimization would be to
12042 hold on to it, and fill the register cache once we have selected
12043 an architecture, but it's too tricky to do safely. */
12044 }
12045
12046 return beneath ()->read_description ();
12047 }
12048
12049 /* Remote file transfer support. This is host-initiated I/O, not
12050 target-initiated; for target-initiated, see remote-fileio.c. */
12051
12052 /* If *LEFT is at least the length of STRING, copy STRING to
12053 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12054 decrease *LEFT. Otherwise raise an error. */
12055
12056 static void
12057 remote_buffer_add_string (char **buffer, int *left, const char *string)
12058 {
12059 int len = strlen (string);
12060
12061 if (len > *left)
12062 error (_("Packet too long for target."));
12063
12064 memcpy (*buffer, string, len);
12065 *buffer += len;
12066 *left -= len;
12067
12068 /* NUL-terminate the buffer as a convenience, if there is
12069 room. */
12070 if (*left)
12071 **buffer = '\0';
12072 }
12073
12074 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12075 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12076 decrease *LEFT. Otherwise raise an error. */
12077
12078 static void
12079 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12080 int len)
12081 {
12082 if (2 * len > *left)
12083 error (_("Packet too long for target."));
12084
12085 bin2hex (bytes, *buffer, len);
12086 *buffer += 2 * len;
12087 *left -= 2 * len;
12088
12089 /* NUL-terminate the buffer as a convenience, if there is
12090 room. */
12091 if (*left)
12092 **buffer = '\0';
12093 }
12094
12095 /* If *LEFT is large enough, convert VALUE to hex and add it to
12096 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12097 decrease *LEFT. Otherwise raise an error. */
12098
12099 static void
12100 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12101 {
12102 int len = hexnumlen (value);
12103
12104 if (len > *left)
12105 error (_("Packet too long for target."));
12106
12107 hexnumstr (*buffer, value);
12108 *buffer += len;
12109 *left -= len;
12110
12111 /* NUL-terminate the buffer as a convenience, if there is
12112 room. */
12113 if (*left)
12114 **buffer = '\0';
12115 }
12116
12117 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12118 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
12119 was included, and *ATTACHMENT to point to the start of the annex
12120 if any. The length of the packet isn't needed here; there may
12121 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12122
12123 Return 0 if the packet could be parsed, -1 if it could not. If
12124 -1 is returned, the other variables may not be initialized. */
12125
12126 static int
12127 remote_hostio_parse_result (const char *buffer, int *retcode,
12128 fileio_error *remote_errno, const char **attachment)
12129 {
12130 char *p, *p2;
12131
12132 *remote_errno = FILEIO_SUCCESS;
12133 *attachment = NULL;
12134
12135 if (buffer[0] != 'F')
12136 return -1;
12137
12138 errno = 0;
12139 *retcode = strtol (&buffer[1], &p, 16);
12140 if (errno != 0 || p == &buffer[1])
12141 return -1;
12142
12143 /* Check for ",errno". */
12144 if (*p == ',')
12145 {
12146 errno = 0;
12147 *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
12148 if (errno != 0 || p + 1 == p2)
12149 return -1;
12150 p = p2;
12151 }
12152
12153 /* Check for ";attachment". If there is no attachment, the
12154 packet should end here. */
12155 if (*p == ';')
12156 {
12157 *attachment = p + 1;
12158 return 0;
12159 }
12160 else if (*p == '\0')
12161 return 0;
12162 else
12163 return -1;
12164 }
12165
12166 /* Send a prepared I/O packet to the target and read its response.
12167 The prepared packet is in the global RS->BUF before this function
12168 is called, and the answer is there when we return.
12169
12170 COMMAND_BYTES is the length of the request to send, which may include
12171 binary data. WHICH_PACKET is the packet configuration to check
12172 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12173 is set to the error number and -1 is returned. Otherwise the value
12174 returned by the function is returned.
12175
12176 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12177 attachment is expected; an error will be reported if there's a
12178 mismatch. If one is found, *ATTACHMENT will be set to point into
12179 the packet buffer and *ATTACHMENT_LEN will be set to the
12180 attachment's length. */
12181
12182 int
12183 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12184 fileio_error *remote_errno, const char **attachment,
12185 int *attachment_len)
12186 {
12187 struct remote_state *rs = get_remote_state ();
12188 int ret, bytes_read;
12189 const char *attachment_tmp;
12190
12191 if (packet_support (which_packet) == PACKET_DISABLE)
12192 {
12193 *remote_errno = FILEIO_ENOSYS;
12194 return -1;
12195 }
12196
12197 putpkt_binary (rs->buf.data (), command_bytes);
12198 bytes_read = getpkt_sane (&rs->buf, 0);
12199
12200 /* If it timed out, something is wrong. Don't try to parse the
12201 buffer. */
12202 if (bytes_read < 0)
12203 {
12204 *remote_errno = FILEIO_EINVAL;
12205 return -1;
12206 }
12207
12208 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
12209 {
12210 case PACKET_ERROR:
12211 *remote_errno = FILEIO_EINVAL;
12212 return -1;
12213 case PACKET_UNKNOWN:
12214 *remote_errno = FILEIO_ENOSYS;
12215 return -1;
12216 case PACKET_OK:
12217 break;
12218 }
12219
12220 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12221 &attachment_tmp))
12222 {
12223 *remote_errno = FILEIO_EINVAL;
12224 return -1;
12225 }
12226
12227 /* Make sure we saw an attachment if and only if we expected one. */
12228 if ((attachment_tmp == NULL && attachment != NULL)
12229 || (attachment_tmp != NULL && attachment == NULL))
12230 {
12231 *remote_errno = FILEIO_EINVAL;
12232 return -1;
12233 }
12234
12235 /* If an attachment was found, it must point into the packet buffer;
12236 work out how many bytes there were. */
12237 if (attachment_tmp != NULL)
12238 {
12239 *attachment = attachment_tmp;
12240 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12241 }
12242
12243 return ret;
12244 }
12245
12246 /* See declaration.h. */
12247
12248 void
12249 readahead_cache::invalidate ()
12250 {
12251 this->fd = -1;
12252 }
12253
12254 /* See declaration.h. */
12255
12256 void
12257 readahead_cache::invalidate_fd (int fd)
12258 {
12259 if (this->fd == fd)
12260 this->fd = -1;
12261 }
12262
12263 /* Set the filesystem remote_hostio functions that take FILENAME
12264 arguments will use. Return 0 on success, or -1 if an error
12265 occurs (and set *REMOTE_ERRNO). */
12266
12267 int
12268 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12269 fileio_error *remote_errno)
12270 {
12271 struct remote_state *rs = get_remote_state ();
12272 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12273 char *p = rs->buf.data ();
12274 int left = get_remote_packet_size () - 1;
12275 char arg[9];
12276 int ret;
12277
12278 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12279 return 0;
12280
12281 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12282 return 0;
12283
12284 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12285
12286 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12287 remote_buffer_add_string (&p, &left, arg);
12288
12289 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12290 remote_errno, NULL, NULL);
12291
12292 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12293 return 0;
12294
12295 if (ret == 0)
12296 rs->fs_pid = required_pid;
12297
12298 return ret;
12299 }
12300
12301 /* Implementation of to_fileio_open. */
12302
12303 int
12304 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12305 int flags, int mode, int warn_if_slow,
12306 fileio_error *remote_errno)
12307 {
12308 struct remote_state *rs = get_remote_state ();
12309 char *p = rs->buf.data ();
12310 int left = get_remote_packet_size () - 1;
12311
12312 if (warn_if_slow)
12313 {
12314 static int warning_issued = 0;
12315
12316 gdb_printf (_("Reading %s from remote target...\n"),
12317 filename);
12318
12319 if (!warning_issued)
12320 {
12321 warning (_("File transfers from remote targets can be slow."
12322 " Use \"set sysroot\" to access files locally"
12323 " instead."));
12324 warning_issued = 1;
12325 }
12326 }
12327
12328 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12329 return -1;
12330
12331 remote_buffer_add_string (&p, &left, "vFile:open:");
12332
12333 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12334 strlen (filename));
12335 remote_buffer_add_string (&p, &left, ",");
12336
12337 remote_buffer_add_int (&p, &left, flags);
12338 remote_buffer_add_string (&p, &left, ",");
12339
12340 remote_buffer_add_int (&p, &left, mode);
12341
12342 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12343 remote_errno, NULL, NULL);
12344 }
12345
12346 int
12347 remote_target::fileio_open (struct inferior *inf, const char *filename,
12348 int flags, int mode, int warn_if_slow,
12349 fileio_error *remote_errno)
12350 {
12351 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12352 remote_errno);
12353 }
12354
12355 /* Implementation of to_fileio_pwrite. */
12356
12357 int
12358 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12359 ULONGEST offset, fileio_error *remote_errno)
12360 {
12361 struct remote_state *rs = get_remote_state ();
12362 char *p = rs->buf.data ();
12363 int left = get_remote_packet_size ();
12364 int out_len;
12365
12366 rs->readahead_cache.invalidate_fd (fd);
12367
12368 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12369
12370 remote_buffer_add_int (&p, &left, fd);
12371 remote_buffer_add_string (&p, &left, ",");
12372
12373 remote_buffer_add_int (&p, &left, offset);
12374 remote_buffer_add_string (&p, &left, ",");
12375
12376 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12377 (get_remote_packet_size ()
12378 - (p - rs->buf.data ())));
12379
12380 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12381 remote_errno, NULL, NULL);
12382 }
12383
12384 int
12385 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12386 ULONGEST offset, fileio_error *remote_errno)
12387 {
12388 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12389 }
12390
12391 /* Helper for the implementation of to_fileio_pread. Read the file
12392 from the remote side with vFile:pread. */
12393
12394 int
12395 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12396 ULONGEST offset, fileio_error *remote_errno)
12397 {
12398 struct remote_state *rs = get_remote_state ();
12399 char *p = rs->buf.data ();
12400 const char *attachment;
12401 int left = get_remote_packet_size ();
12402 int ret, attachment_len;
12403 int read_len;
12404
12405 remote_buffer_add_string (&p, &left, "vFile:pread:");
12406
12407 remote_buffer_add_int (&p, &left, fd);
12408 remote_buffer_add_string (&p, &left, ",");
12409
12410 remote_buffer_add_int (&p, &left, len);
12411 remote_buffer_add_string (&p, &left, ",");
12412
12413 remote_buffer_add_int (&p, &left, offset);
12414
12415 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12416 remote_errno, &attachment,
12417 &attachment_len);
12418
12419 if (ret < 0)
12420 return ret;
12421
12422 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12423 read_buf, len);
12424 if (read_len != ret)
12425 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12426
12427 return ret;
12428 }
12429
12430 /* See declaration.h. */
12431
12432 int
12433 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12434 ULONGEST offset)
12435 {
12436 if (this->fd == fd
12437 && this->offset <= offset
12438 && offset < this->offset + this->bufsize)
12439 {
12440 ULONGEST max = this->offset + this->bufsize;
12441
12442 if (offset + len > max)
12443 len = max - offset;
12444
12445 memcpy (read_buf, this->buf + offset - this->offset, len);
12446 return len;
12447 }
12448
12449 return 0;
12450 }
12451
12452 /* Implementation of to_fileio_pread. */
12453
12454 int
12455 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12456 ULONGEST offset, fileio_error *remote_errno)
12457 {
12458 int ret;
12459 struct remote_state *rs = get_remote_state ();
12460 readahead_cache *cache = &rs->readahead_cache;
12461
12462 ret = cache->pread (fd, read_buf, len, offset);
12463 if (ret > 0)
12464 {
12465 cache->hit_count++;
12466
12467 remote_debug_printf ("readahead cache hit %s",
12468 pulongest (cache->hit_count));
12469 return ret;
12470 }
12471
12472 cache->miss_count++;
12473
12474 remote_debug_printf ("readahead cache miss %s",
12475 pulongest (cache->miss_count));
12476
12477 cache->fd = fd;
12478 cache->offset = offset;
12479 cache->bufsize = get_remote_packet_size ();
12480 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12481
12482 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12483 cache->offset, remote_errno);
12484 if (ret <= 0)
12485 {
12486 cache->invalidate_fd (fd);
12487 return ret;
12488 }
12489
12490 cache->bufsize = ret;
12491 return cache->pread (fd, read_buf, len, offset);
12492 }
12493
12494 int
12495 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12496 ULONGEST offset, fileio_error *remote_errno)
12497 {
12498 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12499 }
12500
12501 /* Implementation of to_fileio_close. */
12502
12503 int
12504 remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
12505 {
12506 struct remote_state *rs = get_remote_state ();
12507 char *p = rs->buf.data ();
12508 int left = get_remote_packet_size () - 1;
12509
12510 rs->readahead_cache.invalidate_fd (fd);
12511
12512 remote_buffer_add_string (&p, &left, "vFile:close:");
12513
12514 remote_buffer_add_int (&p, &left, fd);
12515
12516 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12517 remote_errno, NULL, NULL);
12518 }
12519
12520 int
12521 remote_target::fileio_close (int fd, fileio_error *remote_errno)
12522 {
12523 return remote_hostio_close (fd, remote_errno);
12524 }
12525
12526 /* Implementation of to_fileio_unlink. */
12527
12528 int
12529 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12530 fileio_error *remote_errno)
12531 {
12532 struct remote_state *rs = get_remote_state ();
12533 char *p = rs->buf.data ();
12534 int left = get_remote_packet_size () - 1;
12535
12536 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12537 return -1;
12538
12539 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12540
12541 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12542 strlen (filename));
12543
12544 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12545 remote_errno, NULL, NULL);
12546 }
12547
12548 int
12549 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12550 fileio_error *remote_errno)
12551 {
12552 return remote_hostio_unlink (inf, filename, remote_errno);
12553 }
12554
12555 /* Implementation of to_fileio_readlink. */
12556
12557 gdb::optional<std::string>
12558 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12559 fileio_error *remote_errno)
12560 {
12561 struct remote_state *rs = get_remote_state ();
12562 char *p = rs->buf.data ();
12563 const char *attachment;
12564 int left = get_remote_packet_size ();
12565 int len, attachment_len;
12566 int read_len;
12567
12568 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12569 return {};
12570
12571 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12572
12573 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12574 strlen (filename));
12575
12576 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12577 remote_errno, &attachment,
12578 &attachment_len);
12579
12580 if (len < 0)
12581 return {};
12582
12583 std::string ret (len, '\0');
12584
12585 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12586 (gdb_byte *) &ret[0], len);
12587 if (read_len != len)
12588 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12589
12590 return ret;
12591 }
12592
12593 /* Implementation of to_fileio_fstat. */
12594
12595 int
12596 remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
12597 {
12598 struct remote_state *rs = get_remote_state ();
12599 char *p = rs->buf.data ();
12600 int left = get_remote_packet_size ();
12601 int attachment_len, ret;
12602 const char *attachment;
12603 struct fio_stat fst;
12604 int read_len;
12605
12606 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12607
12608 remote_buffer_add_int (&p, &left, fd);
12609
12610 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12611 remote_errno, &attachment,
12612 &attachment_len);
12613 if (ret < 0)
12614 {
12615 if (*remote_errno != FILEIO_ENOSYS)
12616 return ret;
12617
12618 /* Strictly we should return -1, ENOSYS here, but when
12619 "set sysroot remote:" was implemented in August 2008
12620 BFD's need for a stat function was sidestepped with
12621 this hack. This was not remedied until March 2015
12622 so we retain the previous behavior to avoid breaking
12623 compatibility.
12624
12625 Note that the memset is a March 2015 addition; older
12626 GDBs set st_size *and nothing else* so the structure
12627 would have garbage in all other fields. This might
12628 break something but retaining the previous behavior
12629 here would be just too wrong. */
12630
12631 memset (st, 0, sizeof (struct stat));
12632 st->st_size = INT_MAX;
12633 return 0;
12634 }
12635
12636 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12637 (gdb_byte *) &fst, sizeof (fst));
12638
12639 if (read_len != ret)
12640 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12641
12642 if (read_len != sizeof (fst))
12643 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12644 read_len, (int) sizeof (fst));
12645
12646 remote_fileio_to_host_stat (&fst, st);
12647
12648 return 0;
12649 }
12650
12651 /* Implementation of to_filesystem_is_local. */
12652
12653 bool
12654 remote_target::filesystem_is_local ()
12655 {
12656 /* Valgrind GDB presents itself as a remote target but works
12657 on the local filesystem: it does not implement remote get
12658 and users are not expected to set a sysroot. To handle
12659 this case we treat the remote filesystem as local if the
12660 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12661 does not support vFile:open. */
12662 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
12663 {
12664 enum packet_support ps = packet_support (PACKET_vFile_open);
12665
12666 if (ps == PACKET_SUPPORT_UNKNOWN)
12667 {
12668 int fd;
12669 fileio_error remote_errno;
12670
12671 /* Try opening a file to probe support. The supplied
12672 filename is irrelevant, we only care about whether
12673 the stub recognizes the packet or not. */
12674 fd = remote_hostio_open (NULL, "just probing",
12675 FILEIO_O_RDONLY, 0700, 0,
12676 &remote_errno);
12677
12678 if (fd >= 0)
12679 remote_hostio_close (fd, &remote_errno);
12680
12681 ps = packet_support (PACKET_vFile_open);
12682 }
12683
12684 if (ps == PACKET_DISABLE)
12685 {
12686 static int warning_issued = 0;
12687
12688 if (!warning_issued)
12689 {
12690 warning (_("remote target does not support file"
12691 " transfer, attempting to access files"
12692 " from local filesystem."));
12693 warning_issued = 1;
12694 }
12695
12696 return true;
12697 }
12698 }
12699
12700 return false;
12701 }
12702
12703 static char *
12704 remote_hostio_error (fileio_error errnum)
12705 {
12706 int host_error = fileio_error_to_host (errnum);
12707
12708 if (host_error == -1)
12709 error (_("Unknown remote I/O error %d"), errnum);
12710 else
12711 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12712 }
12713
12714 /* A RAII wrapper around a remote file descriptor. */
12715
12716 class scoped_remote_fd
12717 {
12718 public:
12719 scoped_remote_fd (remote_target *remote, int fd)
12720 : m_remote (remote), m_fd (fd)
12721 {
12722 }
12723
12724 ~scoped_remote_fd ()
12725 {
12726 if (m_fd != -1)
12727 {
12728 try
12729 {
12730 fileio_error remote_errno;
12731 m_remote->remote_hostio_close (m_fd, &remote_errno);
12732 }
12733 catch (...)
12734 {
12735 /* Swallow exception before it escapes the dtor. If
12736 something goes wrong, likely the connection is gone,
12737 and there's nothing else that can be done. */
12738 }
12739 }
12740 }
12741
12742 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12743
12744 /* Release ownership of the file descriptor, and return it. */
12745 ATTRIBUTE_UNUSED_RESULT int release () noexcept
12746 {
12747 int fd = m_fd;
12748 m_fd = -1;
12749 return fd;
12750 }
12751
12752 /* Return the owned file descriptor. */
12753 int get () const noexcept
12754 {
12755 return m_fd;
12756 }
12757
12758 private:
12759 /* The remote target. */
12760 remote_target *m_remote;
12761
12762 /* The owned remote I/O file descriptor. */
12763 int m_fd;
12764 };
12765
12766 void
12767 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12768 {
12769 remote_target *remote = get_current_remote_target ();
12770
12771 if (remote == nullptr)
12772 error (_("command can only be used with remote target"));
12773
12774 remote->remote_file_put (local_file, remote_file, from_tty);
12775 }
12776
12777 void
12778 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12779 int from_tty)
12780 {
12781 int retcode, bytes, io_size;
12782 fileio_error remote_errno;
12783 int bytes_in_buffer;
12784 int saw_eof;
12785 ULONGEST offset;
12786
12787 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12788 if (file == NULL)
12789 perror_with_name (local_file);
12790
12791 scoped_remote_fd fd
12792 (this, remote_hostio_open (NULL,
12793 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12794 | FILEIO_O_TRUNC),
12795 0700, 0, &remote_errno));
12796 if (fd.get () == -1)
12797 remote_hostio_error (remote_errno);
12798
12799 /* Send up to this many bytes at once. They won't all fit in the
12800 remote packet limit, so we'll transfer slightly fewer. */
12801 io_size = get_remote_packet_size ();
12802 gdb::byte_vector buffer (io_size);
12803
12804 bytes_in_buffer = 0;
12805 saw_eof = 0;
12806 offset = 0;
12807 while (bytes_in_buffer || !saw_eof)
12808 {
12809 if (!saw_eof)
12810 {
12811 bytes = fread (buffer.data () + bytes_in_buffer, 1,
12812 io_size - bytes_in_buffer,
12813 file.get ());
12814 if (bytes == 0)
12815 {
12816 if (ferror (file.get ()))
12817 error (_("Error reading %s."), local_file);
12818 else
12819 {
12820 /* EOF. Unless there is something still in the
12821 buffer from the last iteration, we are done. */
12822 saw_eof = 1;
12823 if (bytes_in_buffer == 0)
12824 break;
12825 }
12826 }
12827 }
12828 else
12829 bytes = 0;
12830
12831 bytes += bytes_in_buffer;
12832 bytes_in_buffer = 0;
12833
12834 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12835 offset, &remote_errno);
12836
12837 if (retcode < 0)
12838 remote_hostio_error (remote_errno);
12839 else if (retcode == 0)
12840 error (_("Remote write of %d bytes returned 0!"), bytes);
12841 else if (retcode < bytes)
12842 {
12843 /* Short write. Save the rest of the read data for the next
12844 write. */
12845 bytes_in_buffer = bytes - retcode;
12846 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
12847 }
12848
12849 offset += retcode;
12850 }
12851
12852 if (remote_hostio_close (fd.release (), &remote_errno))
12853 remote_hostio_error (remote_errno);
12854
12855 if (from_tty)
12856 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
12857 }
12858
12859 void
12860 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12861 {
12862 remote_target *remote = get_current_remote_target ();
12863
12864 if (remote == nullptr)
12865 error (_("command can only be used with remote target"));
12866
12867 remote->remote_file_get (remote_file, local_file, from_tty);
12868 }
12869
12870 void
12871 remote_target::remote_file_get (const char *remote_file, const char *local_file,
12872 int from_tty)
12873 {
12874 fileio_error remote_errno;
12875 int bytes, io_size;
12876 ULONGEST offset;
12877
12878 scoped_remote_fd fd
12879 (this, remote_hostio_open (NULL,
12880 remote_file, FILEIO_O_RDONLY, 0, 0,
12881 &remote_errno));
12882 if (fd.get () == -1)
12883 remote_hostio_error (remote_errno);
12884
12885 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12886 if (file == NULL)
12887 perror_with_name (local_file);
12888
12889 /* Send up to this many bytes at once. They won't all fit in the
12890 remote packet limit, so we'll transfer slightly fewer. */
12891 io_size = get_remote_packet_size ();
12892 gdb::byte_vector buffer (io_size);
12893
12894 offset = 0;
12895 while (1)
12896 {
12897 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
12898 &remote_errno);
12899 if (bytes == 0)
12900 /* Success, but no bytes, means end-of-file. */
12901 break;
12902 if (bytes == -1)
12903 remote_hostio_error (remote_errno);
12904
12905 offset += bytes;
12906
12907 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
12908 if (bytes == 0)
12909 perror_with_name (local_file);
12910 }
12911
12912 if (remote_hostio_close (fd.release (), &remote_errno))
12913 remote_hostio_error (remote_errno);
12914
12915 if (from_tty)
12916 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
12917 }
12918
12919 void
12920 remote_file_delete (const char *remote_file, int from_tty)
12921 {
12922 remote_target *remote = get_current_remote_target ();
12923
12924 if (remote == nullptr)
12925 error (_("command can only be used with remote target"));
12926
12927 remote->remote_file_delete (remote_file, from_tty);
12928 }
12929
12930 void
12931 remote_target::remote_file_delete (const char *remote_file, int from_tty)
12932 {
12933 int retcode;
12934 fileio_error remote_errno;
12935
12936 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
12937 if (retcode == -1)
12938 remote_hostio_error (remote_errno);
12939
12940 if (from_tty)
12941 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
12942 }
12943
12944 static void
12945 remote_put_command (const char *args, int from_tty)
12946 {
12947 if (args == NULL)
12948 error_no_arg (_("file to put"));
12949
12950 gdb_argv argv (args);
12951 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12952 error (_("Invalid parameters to remote put"));
12953
12954 remote_file_put (argv[0], argv[1], from_tty);
12955 }
12956
12957 static void
12958 remote_get_command (const char *args, int from_tty)
12959 {
12960 if (args == NULL)
12961 error_no_arg (_("file to get"));
12962
12963 gdb_argv argv (args);
12964 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12965 error (_("Invalid parameters to remote get"));
12966
12967 remote_file_get (argv[0], argv[1], from_tty);
12968 }
12969
12970 static void
12971 remote_delete_command (const char *args, int from_tty)
12972 {
12973 if (args == NULL)
12974 error_no_arg (_("file to delete"));
12975
12976 gdb_argv argv (args);
12977 if (argv[0] == NULL || argv[1] != NULL)
12978 error (_("Invalid parameters to remote delete"));
12979
12980 remote_file_delete (argv[0], from_tty);
12981 }
12982
12983 bool
12984 remote_target::can_execute_reverse ()
12985 {
12986 if (packet_support (PACKET_bs) == PACKET_ENABLE
12987 || packet_support (PACKET_bc) == PACKET_ENABLE)
12988 return true;
12989 else
12990 return false;
12991 }
12992
12993 bool
12994 remote_target::supports_non_stop ()
12995 {
12996 return true;
12997 }
12998
12999 bool
13000 remote_target::supports_disable_randomization ()
13001 {
13002 /* Only supported in extended mode. */
13003 return false;
13004 }
13005
13006 bool
13007 remote_target::supports_multi_process ()
13008 {
13009 struct remote_state *rs = get_remote_state ();
13010
13011 return remote_multi_process_p (rs);
13012 }
13013
13014 static int
13015 remote_supports_cond_tracepoints ()
13016 {
13017 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
13018 }
13019
13020 bool
13021 remote_target::supports_evaluation_of_breakpoint_conditions ()
13022 {
13023 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
13024 }
13025
13026 static int
13027 remote_supports_fast_tracepoints ()
13028 {
13029 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13030 }
13031
13032 static int
13033 remote_supports_static_tracepoints ()
13034 {
13035 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13036 }
13037
13038 static int
13039 remote_supports_install_in_trace ()
13040 {
13041 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13042 }
13043
13044 bool
13045 remote_target::supports_enable_disable_tracepoint ()
13046 {
13047 return (packet_support (PACKET_EnableDisableTracepoints_feature)
13048 == PACKET_ENABLE);
13049 }
13050
13051 bool
13052 remote_target::supports_string_tracing ()
13053 {
13054 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13055 }
13056
13057 bool
13058 remote_target::can_run_breakpoint_commands ()
13059 {
13060 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13061 }
13062
13063 void
13064 remote_target::trace_init ()
13065 {
13066 struct remote_state *rs = get_remote_state ();
13067
13068 putpkt ("QTinit");
13069 remote_get_noisy_reply ();
13070 if (strcmp (rs->buf.data (), "OK") != 0)
13071 error (_("Target does not support this command."));
13072 }
13073
13074 /* Recursive routine to walk through command list including loops, and
13075 download packets for each command. */
13076
13077 void
13078 remote_target::remote_download_command_source (int num, ULONGEST addr,
13079 struct command_line *cmds)
13080 {
13081 struct remote_state *rs = get_remote_state ();
13082 struct command_line *cmd;
13083
13084 for (cmd = cmds; cmd; cmd = cmd->next)
13085 {
13086 QUIT; /* Allow user to bail out with ^C. */
13087 strcpy (rs->buf.data (), "QTDPsrc:");
13088 encode_source_string (num, addr, "cmd", cmd->line,
13089 rs->buf.data () + strlen (rs->buf.data ()),
13090 rs->buf.size () - strlen (rs->buf.data ()));
13091 putpkt (rs->buf);
13092 remote_get_noisy_reply ();
13093 if (strcmp (rs->buf.data (), "OK"))
13094 warning (_("Target does not support source download."));
13095
13096 if (cmd->control_type == while_control
13097 || cmd->control_type == while_stepping_control)
13098 {
13099 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13100
13101 QUIT; /* Allow user to bail out with ^C. */
13102 strcpy (rs->buf.data (), "QTDPsrc:");
13103 encode_source_string (num, addr, "cmd", "end",
13104 rs->buf.data () + strlen (rs->buf.data ()),
13105 rs->buf.size () - strlen (rs->buf.data ()));
13106 putpkt (rs->buf);
13107 remote_get_noisy_reply ();
13108 if (strcmp (rs->buf.data (), "OK"))
13109 warning (_("Target does not support source download."));
13110 }
13111 }
13112 }
13113
13114 void
13115 remote_target::download_tracepoint (struct bp_location *loc)
13116 {
13117 CORE_ADDR tpaddr;
13118 char addrbuf[40];
13119 std::vector<std::string> tdp_actions;
13120 std::vector<std::string> stepping_actions;
13121 char *pkt;
13122 struct breakpoint *b = loc->owner;
13123 struct tracepoint *t = (struct tracepoint *) b;
13124 struct remote_state *rs = get_remote_state ();
13125 int ret;
13126 const char *err_msg = _("Tracepoint packet too large for target.");
13127 size_t size_left;
13128
13129 /* We use a buffer other than rs->buf because we'll build strings
13130 across multiple statements, and other statements in between could
13131 modify rs->buf. */
13132 gdb::char_vector buf (get_remote_packet_size ());
13133
13134 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13135
13136 tpaddr = loc->address;
13137 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13138 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13139 b->number, addrbuf, /* address */
13140 (b->enable_state == bp_enabled ? 'E' : 'D'),
13141 t->step_count, t->pass_count);
13142
13143 if (ret < 0 || ret >= buf.size ())
13144 error ("%s", err_msg);
13145
13146 /* Fast tracepoints are mostly handled by the target, but we can
13147 tell the target how big of an instruction block should be moved
13148 around. */
13149 if (b->type == bp_fast_tracepoint)
13150 {
13151 /* Only test for support at download time; we may not know
13152 target capabilities at definition time. */
13153 if (remote_supports_fast_tracepoints ())
13154 {
13155 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13156 NULL))
13157 {
13158 size_left = buf.size () - strlen (buf.data ());
13159 ret = snprintf (buf.data () + strlen (buf.data ()),
13160 size_left, ":F%x",
13161 gdb_insn_length (loc->gdbarch, tpaddr));
13162
13163 if (ret < 0 || ret >= size_left)
13164 error ("%s", err_msg);
13165 }
13166 else
13167 /* If it passed validation at definition but fails now,
13168 something is very wrong. */
13169 internal_error (_("Fast tracepoint not valid during download"));
13170 }
13171 else
13172 /* Fast tracepoints are functionally identical to regular
13173 tracepoints, so don't take lack of support as a reason to
13174 give up on the trace run. */
13175 warning (_("Target does not support fast tracepoints, "
13176 "downloading %d as regular tracepoint"), b->number);
13177 }
13178 else if (b->type == bp_static_tracepoint
13179 || b->type == bp_static_marker_tracepoint)
13180 {
13181 /* Only test for support at download time; we may not know
13182 target capabilities at definition time. */
13183 if (remote_supports_static_tracepoints ())
13184 {
13185 struct static_tracepoint_marker marker;
13186
13187 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13188 {
13189 size_left = buf.size () - strlen (buf.data ());
13190 ret = snprintf (buf.data () + strlen (buf.data ()),
13191 size_left, ":S");
13192
13193 if (ret < 0 || ret >= size_left)
13194 error ("%s", err_msg);
13195 }
13196 else
13197 error (_("Static tracepoint not valid during download"));
13198 }
13199 else
13200 /* Fast tracepoints are functionally identical to regular
13201 tracepoints, so don't take lack of support as a reason
13202 to give up on the trace run. */
13203 error (_("Target does not support static tracepoints"));
13204 }
13205 /* If the tracepoint has a conditional, make it into an agent
13206 expression and append to the definition. */
13207 if (loc->cond)
13208 {
13209 /* Only test support at download time, we may not know target
13210 capabilities at definition time. */
13211 if (remote_supports_cond_tracepoints ())
13212 {
13213 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13214 loc->cond.get ());
13215
13216 size_left = buf.size () - strlen (buf.data ());
13217
13218 ret = snprintf (buf.data () + strlen (buf.data ()),
13219 size_left, ":X%x,", aexpr->len);
13220
13221 if (ret < 0 || ret >= size_left)
13222 error ("%s", err_msg);
13223
13224 size_left = buf.size () - strlen (buf.data ());
13225
13226 /* Two bytes to encode each aexpr byte, plus the terminating
13227 null byte. */
13228 if (aexpr->len * 2 + 1 > size_left)
13229 error ("%s", err_msg);
13230
13231 pkt = buf.data () + strlen (buf.data ());
13232
13233 for (int ndx = 0; ndx < aexpr->len; ++ndx)
13234 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13235 *pkt = '\0';
13236 }
13237 else
13238 warning (_("Target does not support conditional tracepoints, "
13239 "ignoring tp %d cond"), b->number);
13240 }
13241
13242 if (b->commands || !default_collect.empty ())
13243 {
13244 size_left = buf.size () - strlen (buf.data ());
13245
13246 ret = snprintf (buf.data () + strlen (buf.data ()),
13247 size_left, "-");
13248
13249 if (ret < 0 || ret >= size_left)
13250 error ("%s", err_msg);
13251 }
13252
13253 putpkt (buf.data ());
13254 remote_get_noisy_reply ();
13255 if (strcmp (rs->buf.data (), "OK"))
13256 error (_("Target does not support tracepoints."));
13257
13258 /* do_single_steps (t); */
13259 for (auto action_it = tdp_actions.begin ();
13260 action_it != tdp_actions.end (); action_it++)
13261 {
13262 QUIT; /* Allow user to bail out with ^C. */
13263
13264 bool has_more = ((action_it + 1) != tdp_actions.end ()
13265 || !stepping_actions.empty ());
13266
13267 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13268 b->number, addrbuf, /* address */
13269 action_it->c_str (),
13270 has_more ? '-' : 0);
13271
13272 if (ret < 0 || ret >= buf.size ())
13273 error ("%s", err_msg);
13274
13275 putpkt (buf.data ());
13276 remote_get_noisy_reply ();
13277 if (strcmp (rs->buf.data (), "OK"))
13278 error (_("Error on target while setting tracepoints."));
13279 }
13280
13281 for (auto action_it = stepping_actions.begin ();
13282 action_it != stepping_actions.end (); action_it++)
13283 {
13284 QUIT; /* Allow user to bail out with ^C. */
13285
13286 bool is_first = action_it == stepping_actions.begin ();
13287 bool has_more = (action_it + 1) != stepping_actions.end ();
13288
13289 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13290 b->number, addrbuf, /* address */
13291 is_first ? "S" : "",
13292 action_it->c_str (),
13293 has_more ? "-" : "");
13294
13295 if (ret < 0 || ret >= buf.size ())
13296 error ("%s", err_msg);
13297
13298 putpkt (buf.data ());
13299 remote_get_noisy_reply ();
13300 if (strcmp (rs->buf.data (), "OK"))
13301 error (_("Error on target while setting tracepoints."));
13302 }
13303
13304 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13305 {
13306 if (b->locspec != nullptr)
13307 {
13308 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13309
13310 if (ret < 0 || ret >= buf.size ())
13311 error ("%s", err_msg);
13312
13313 const char *str = b->locspec->to_string ();
13314 encode_source_string (b->number, loc->address, "at", str,
13315 buf.data () + strlen (buf.data ()),
13316 buf.size () - strlen (buf.data ()));
13317 putpkt (buf.data ());
13318 remote_get_noisy_reply ();
13319 if (strcmp (rs->buf.data (), "OK"))
13320 warning (_("Target does not support source download."));
13321 }
13322 if (b->cond_string)
13323 {
13324 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13325
13326 if (ret < 0 || ret >= buf.size ())
13327 error ("%s", err_msg);
13328
13329 encode_source_string (b->number, loc->address,
13330 "cond", b->cond_string.get (),
13331 buf.data () + strlen (buf.data ()),
13332 buf.size () - strlen (buf.data ()));
13333 putpkt (buf.data ());
13334 remote_get_noisy_reply ();
13335 if (strcmp (rs->buf.data (), "OK"))
13336 warning (_("Target does not support source download."));
13337 }
13338 remote_download_command_source (b->number, loc->address,
13339 breakpoint_commands (b));
13340 }
13341 }
13342
13343 bool
13344 remote_target::can_download_tracepoint ()
13345 {
13346 struct remote_state *rs = get_remote_state ();
13347 struct trace_status *ts;
13348 int status;
13349
13350 /* Don't try to install tracepoints until we've relocated our
13351 symbols, and fetched and merged the target's tracepoint list with
13352 ours. */
13353 if (rs->starting_up)
13354 return false;
13355
13356 ts = current_trace_status ();
13357 status = get_trace_status (ts);
13358
13359 if (status == -1 || !ts->running_known || !ts->running)
13360 return false;
13361
13362 /* If we are in a tracing experiment, but remote stub doesn't support
13363 installing tracepoint in trace, we have to return. */
13364 if (!remote_supports_install_in_trace ())
13365 return false;
13366
13367 return true;
13368 }
13369
13370
13371 void
13372 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13373 {
13374 struct remote_state *rs = get_remote_state ();
13375 char *p;
13376
13377 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13378 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13379 tsv.builtin);
13380 p = rs->buf.data () + strlen (rs->buf.data ());
13381 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13382 >= get_remote_packet_size ())
13383 error (_("Trace state variable name too long for tsv definition packet"));
13384 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13385 *p++ = '\0';
13386 putpkt (rs->buf);
13387 remote_get_noisy_reply ();
13388 if (rs->buf[0] == '\0')
13389 error (_("Target does not support this command."));
13390 if (strcmp (rs->buf.data (), "OK") != 0)
13391 error (_("Error on target while downloading trace state variable."));
13392 }
13393
13394 void
13395 remote_target::enable_tracepoint (struct bp_location *location)
13396 {
13397 struct remote_state *rs = get_remote_state ();
13398
13399 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13400 location->owner->number,
13401 phex (location->address, sizeof (CORE_ADDR)));
13402 putpkt (rs->buf);
13403 remote_get_noisy_reply ();
13404 if (rs->buf[0] == '\0')
13405 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13406 if (strcmp (rs->buf.data (), "OK") != 0)
13407 error (_("Error on target while enabling tracepoint."));
13408 }
13409
13410 void
13411 remote_target::disable_tracepoint (struct bp_location *location)
13412 {
13413 struct remote_state *rs = get_remote_state ();
13414
13415 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13416 location->owner->number,
13417 phex (location->address, sizeof (CORE_ADDR)));
13418 putpkt (rs->buf);
13419 remote_get_noisy_reply ();
13420 if (rs->buf[0] == '\0')
13421 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13422 if (strcmp (rs->buf.data (), "OK") != 0)
13423 error (_("Error on target while disabling tracepoint."));
13424 }
13425
13426 void
13427 remote_target::trace_set_readonly_regions ()
13428 {
13429 asection *s;
13430 bfd_size_type size;
13431 bfd_vma vma;
13432 int anysecs = 0;
13433 int offset = 0;
13434 bfd *abfd = current_program_space->exec_bfd ();
13435
13436 if (!abfd)
13437 return; /* No information to give. */
13438
13439 struct remote_state *rs = get_remote_state ();
13440
13441 strcpy (rs->buf.data (), "QTro");
13442 offset = strlen (rs->buf.data ());
13443 for (s = abfd->sections; s; s = s->next)
13444 {
13445 char tmp1[40], tmp2[40];
13446 int sec_length;
13447
13448 if ((s->flags & SEC_LOAD) == 0
13449 /* || (s->flags & SEC_CODE) == 0 */
13450 || (s->flags & SEC_READONLY) == 0)
13451 continue;
13452
13453 anysecs = 1;
13454 vma = bfd_section_vma (s);
13455 size = bfd_section_size (s);
13456 bfd_sprintf_vma (abfd, tmp1, vma);
13457 bfd_sprintf_vma (abfd, tmp2, vma + size);
13458 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13459 if (offset + sec_length + 1 > rs->buf.size ())
13460 {
13461 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
13462 warning (_("\
13463 Too many sections for read-only sections definition packet."));
13464 break;
13465 }
13466 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13467 tmp1, tmp2);
13468 offset += sec_length;
13469 }
13470 if (anysecs)
13471 {
13472 putpkt (rs->buf);
13473 getpkt (&rs->buf, 0);
13474 }
13475 }
13476
13477 void
13478 remote_target::trace_start ()
13479 {
13480 struct remote_state *rs = get_remote_state ();
13481
13482 putpkt ("QTStart");
13483 remote_get_noisy_reply ();
13484 if (rs->buf[0] == '\0')
13485 error (_("Target does not support this command."));
13486 if (strcmp (rs->buf.data (), "OK") != 0)
13487 error (_("Bogus reply from target: %s"), rs->buf.data ());
13488 }
13489
13490 int
13491 remote_target::get_trace_status (struct trace_status *ts)
13492 {
13493 /* Initialize it just to avoid a GCC false warning. */
13494 char *p = NULL;
13495 enum packet_result result;
13496 struct remote_state *rs = get_remote_state ();
13497
13498 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13499 return -1;
13500
13501 /* FIXME we need to get register block size some other way. */
13502 trace_regblock_size
13503 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13504
13505 putpkt ("qTStatus");
13506
13507 try
13508 {
13509 p = remote_get_noisy_reply ();
13510 }
13511 catch (const gdb_exception_error &ex)
13512 {
13513 if (ex.error != TARGET_CLOSE_ERROR)
13514 {
13515 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13516 return -1;
13517 }
13518 throw;
13519 }
13520
13521 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13522
13523 /* If the remote target doesn't do tracing, flag it. */
13524 if (result == PACKET_UNKNOWN)
13525 return -1;
13526
13527 /* We're working with a live target. */
13528 ts->filename = NULL;
13529
13530 if (*p++ != 'T')
13531 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13532
13533 /* Function 'parse_trace_status' sets default value of each field of
13534 'ts' at first, so we don't have to do it here. */
13535 parse_trace_status (p, ts);
13536
13537 return ts->running;
13538 }
13539
13540 void
13541 remote_target::get_tracepoint_status (struct breakpoint *bp,
13542 struct uploaded_tp *utp)
13543 {
13544 struct remote_state *rs = get_remote_state ();
13545 char *reply;
13546 struct tracepoint *tp = (struct tracepoint *) bp;
13547 size_t size = get_remote_packet_size ();
13548
13549 if (tp)
13550 {
13551 tp->hit_count = 0;
13552 tp->traceframe_usage = 0;
13553 for (bp_location *loc : tp->locations ())
13554 {
13555 /* If the tracepoint was never downloaded, don't go asking for
13556 any status. */
13557 if (tp->number_on_target == 0)
13558 continue;
13559 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13560 phex_nz (loc->address, 0));
13561 putpkt (rs->buf);
13562 reply = remote_get_noisy_reply ();
13563 if (reply && *reply)
13564 {
13565 if (*reply == 'V')
13566 parse_tracepoint_status (reply + 1, bp, utp);
13567 }
13568 }
13569 }
13570 else if (utp)
13571 {
13572 utp->hit_count = 0;
13573 utp->traceframe_usage = 0;
13574 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13575 phex_nz (utp->addr, 0));
13576 putpkt (rs->buf);
13577 reply = remote_get_noisy_reply ();
13578 if (reply && *reply)
13579 {
13580 if (*reply == 'V')
13581 parse_tracepoint_status (reply + 1, bp, utp);
13582 }
13583 }
13584 }
13585
13586 void
13587 remote_target::trace_stop ()
13588 {
13589 struct remote_state *rs = get_remote_state ();
13590
13591 putpkt ("QTStop");
13592 remote_get_noisy_reply ();
13593 if (rs->buf[0] == '\0')
13594 error (_("Target does not support this command."));
13595 if (strcmp (rs->buf.data (), "OK") != 0)
13596 error (_("Bogus reply from target: %s"), rs->buf.data ());
13597 }
13598
13599 int
13600 remote_target::trace_find (enum trace_find_type type, int num,
13601 CORE_ADDR addr1, CORE_ADDR addr2,
13602 int *tpp)
13603 {
13604 struct remote_state *rs = get_remote_state ();
13605 char *endbuf = rs->buf.data () + get_remote_packet_size ();
13606 char *p, *reply;
13607 int target_frameno = -1, target_tracept = -1;
13608
13609 /* Lookups other than by absolute frame number depend on the current
13610 trace selected, so make sure it is correct on the remote end
13611 first. */
13612 if (type != tfind_number)
13613 set_remote_traceframe ();
13614
13615 p = rs->buf.data ();
13616 strcpy (p, "QTFrame:");
13617 p = strchr (p, '\0');
13618 switch (type)
13619 {
13620 case tfind_number:
13621 xsnprintf (p, endbuf - p, "%x", num);
13622 break;
13623 case tfind_pc:
13624 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13625 break;
13626 case tfind_tp:
13627 xsnprintf (p, endbuf - p, "tdp:%x", num);
13628 break;
13629 case tfind_range:
13630 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13631 phex_nz (addr2, 0));
13632 break;
13633 case tfind_outside:
13634 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13635 phex_nz (addr2, 0));
13636 break;
13637 default:
13638 error (_("Unknown trace find type %d"), type);
13639 }
13640
13641 putpkt (rs->buf);
13642 reply = remote_get_noisy_reply ();
13643 if (*reply == '\0')
13644 error (_("Target does not support this command."));
13645
13646 while (reply && *reply)
13647 switch (*reply)
13648 {
13649 case 'F':
13650 p = ++reply;
13651 target_frameno = (int) strtol (p, &reply, 16);
13652 if (reply == p)
13653 error (_("Unable to parse trace frame number"));
13654 /* Don't update our remote traceframe number cache on failure
13655 to select a remote traceframe. */
13656 if (target_frameno == -1)
13657 return -1;
13658 break;
13659 case 'T':
13660 p = ++reply;
13661 target_tracept = (int) strtol (p, &reply, 16);
13662 if (reply == p)
13663 error (_("Unable to parse tracepoint number"));
13664 break;
13665 case 'O': /* "OK"? */
13666 if (reply[1] == 'K' && reply[2] == '\0')
13667 reply += 2;
13668 else
13669 error (_("Bogus reply from target: %s"), reply);
13670 break;
13671 default:
13672 error (_("Bogus reply from target: %s"), reply);
13673 }
13674 if (tpp)
13675 *tpp = target_tracept;
13676
13677 rs->remote_traceframe_number = target_frameno;
13678 return target_frameno;
13679 }
13680
13681 bool
13682 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13683 {
13684 struct remote_state *rs = get_remote_state ();
13685 char *reply;
13686 ULONGEST uval;
13687
13688 set_remote_traceframe ();
13689
13690 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
13691 putpkt (rs->buf);
13692 reply = remote_get_noisy_reply ();
13693 if (reply && *reply)
13694 {
13695 if (*reply == 'V')
13696 {
13697 unpack_varlen_hex (reply + 1, &uval);
13698 *val = (LONGEST) uval;
13699 return true;
13700 }
13701 }
13702 return false;
13703 }
13704
13705 int
13706 remote_target::save_trace_data (const char *filename)
13707 {
13708 struct remote_state *rs = get_remote_state ();
13709 char *p, *reply;
13710
13711 p = rs->buf.data ();
13712 strcpy (p, "QTSave:");
13713 p += strlen (p);
13714 if ((p - rs->buf.data ()) + strlen (filename) * 2
13715 >= get_remote_packet_size ())
13716 error (_("Remote file name too long for trace save packet"));
13717 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13718 *p++ = '\0';
13719 putpkt (rs->buf);
13720 reply = remote_get_noisy_reply ();
13721 if (*reply == '\0')
13722 error (_("Target does not support this command."));
13723 if (strcmp (reply, "OK") != 0)
13724 error (_("Bogus reply from target: %s"), reply);
13725 return 0;
13726 }
13727
13728 /* This is basically a memory transfer, but needs to be its own packet
13729 because we don't know how the target actually organizes its trace
13730 memory, plus we want to be able to ask for as much as possible, but
13731 not be unhappy if we don't get as much as we ask for. */
13732
13733 LONGEST
13734 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13735 {
13736 struct remote_state *rs = get_remote_state ();
13737 char *reply;
13738 char *p;
13739 int rslt;
13740
13741 p = rs->buf.data ();
13742 strcpy (p, "qTBuffer:");
13743 p += strlen (p);
13744 p += hexnumstr (p, offset);
13745 *p++ = ',';
13746 p += hexnumstr (p, len);
13747 *p++ = '\0';
13748
13749 putpkt (rs->buf);
13750 reply = remote_get_noisy_reply ();
13751 if (reply && *reply)
13752 {
13753 /* 'l' by itself means we're at the end of the buffer and
13754 there is nothing more to get. */
13755 if (*reply == 'l')
13756 return 0;
13757
13758 /* Convert the reply into binary. Limit the number of bytes to
13759 convert according to our passed-in buffer size, rather than
13760 what was returned in the packet; if the target is
13761 unexpectedly generous and gives us a bigger reply than we
13762 asked for, we don't want to crash. */
13763 rslt = hex2bin (reply, buf, len);
13764 return rslt;
13765 }
13766
13767 /* Something went wrong, flag as an error. */
13768 return -1;
13769 }
13770
13771 void
13772 remote_target::set_disconnected_tracing (int val)
13773 {
13774 struct remote_state *rs = get_remote_state ();
13775
13776 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13777 {
13778 char *reply;
13779
13780 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13781 "QTDisconnected:%x", val);
13782 putpkt (rs->buf);
13783 reply = remote_get_noisy_reply ();
13784 if (*reply == '\0')
13785 error (_("Target does not support this command."));
13786 if (strcmp (reply, "OK") != 0)
13787 error (_("Bogus reply from target: %s"), reply);
13788 }
13789 else if (val)
13790 warning (_("Target does not support disconnected tracing."));
13791 }
13792
13793 int
13794 remote_target::core_of_thread (ptid_t ptid)
13795 {
13796 thread_info *info = find_thread_ptid (this, ptid);
13797
13798 if (info != NULL && info->priv != NULL)
13799 return get_remote_thread_info (info)->core;
13800
13801 return -1;
13802 }
13803
13804 void
13805 remote_target::set_circular_trace_buffer (int val)
13806 {
13807 struct remote_state *rs = get_remote_state ();
13808 char *reply;
13809
13810 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13811 "QTBuffer:circular:%x", val);
13812 putpkt (rs->buf);
13813 reply = remote_get_noisy_reply ();
13814 if (*reply == '\0')
13815 error (_("Target does not support this command."));
13816 if (strcmp (reply, "OK") != 0)
13817 error (_("Bogus reply from target: %s"), reply);
13818 }
13819
13820 traceframe_info_up
13821 remote_target::traceframe_info ()
13822 {
13823 gdb::optional<gdb::char_vector> text
13824 = target_read_stralloc (current_inferior ()->top_target (),
13825 TARGET_OBJECT_TRACEFRAME_INFO,
13826 NULL);
13827 if (text)
13828 return parse_traceframe_info (text->data ());
13829
13830 return NULL;
13831 }
13832
13833 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13834 instruction on which a fast tracepoint may be placed. Returns -1
13835 if the packet is not supported, and 0 if the minimum instruction
13836 length is unknown. */
13837
13838 int
13839 remote_target::get_min_fast_tracepoint_insn_len ()
13840 {
13841 struct remote_state *rs = get_remote_state ();
13842 char *reply;
13843
13844 /* If we're not debugging a process yet, the IPA can't be
13845 loaded. */
13846 if (!target_has_execution ())
13847 return 0;
13848
13849 /* Make sure the remote is pointing at the right process. */
13850 set_general_process ();
13851
13852 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
13853 putpkt (rs->buf);
13854 reply = remote_get_noisy_reply ();
13855 if (*reply == '\0')
13856 return -1;
13857 else
13858 {
13859 ULONGEST min_insn_len;
13860
13861 unpack_varlen_hex (reply, &min_insn_len);
13862
13863 return (int) min_insn_len;
13864 }
13865 }
13866
13867 void
13868 remote_target::set_trace_buffer_size (LONGEST val)
13869 {
13870 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13871 {
13872 struct remote_state *rs = get_remote_state ();
13873 char *buf = rs->buf.data ();
13874 char *endbuf = buf + get_remote_packet_size ();
13875 enum packet_result result;
13876
13877 gdb_assert (val >= 0 || val == -1);
13878 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13879 /* Send -1 as literal "-1" to avoid host size dependency. */
13880 if (val < 0)
13881 {
13882 *buf++ = '-';
13883 buf += hexnumstr (buf, (ULONGEST) -val);
13884 }
13885 else
13886 buf += hexnumstr (buf, (ULONGEST) val);
13887
13888 putpkt (rs->buf);
13889 remote_get_noisy_reply ();
13890 result = packet_ok (rs->buf,
13891 &remote_protocol_packets[PACKET_QTBuffer_size]);
13892
13893 if (result != PACKET_OK)
13894 warning (_("Bogus reply from target: %s"), rs->buf.data ());
13895 }
13896 }
13897
13898 bool
13899 remote_target::set_trace_notes (const char *user, const char *notes,
13900 const char *stop_notes)
13901 {
13902 struct remote_state *rs = get_remote_state ();
13903 char *reply;
13904 char *buf = rs->buf.data ();
13905 char *endbuf = buf + get_remote_packet_size ();
13906 int nbytes;
13907
13908 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13909 if (user)
13910 {
13911 buf += xsnprintf (buf, endbuf - buf, "user:");
13912 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13913 buf += 2 * nbytes;
13914 *buf++ = ';';
13915 }
13916 if (notes)
13917 {
13918 buf += xsnprintf (buf, endbuf - buf, "notes:");
13919 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13920 buf += 2 * nbytes;
13921 *buf++ = ';';
13922 }
13923 if (stop_notes)
13924 {
13925 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13926 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13927 buf += 2 * nbytes;
13928 *buf++ = ';';
13929 }
13930 /* Ensure the buffer is terminated. */
13931 *buf = '\0';
13932
13933 putpkt (rs->buf);
13934 reply = remote_get_noisy_reply ();
13935 if (*reply == '\0')
13936 return false;
13937
13938 if (strcmp (reply, "OK") != 0)
13939 error (_("Bogus reply from target: %s"), reply);
13940
13941 return true;
13942 }
13943
13944 bool
13945 remote_target::use_agent (bool use)
13946 {
13947 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13948 {
13949 struct remote_state *rs = get_remote_state ();
13950
13951 /* If the stub supports QAgent. */
13952 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
13953 putpkt (rs->buf);
13954 getpkt (&rs->buf, 0);
13955
13956 if (strcmp (rs->buf.data (), "OK") == 0)
13957 {
13958 ::use_agent = use;
13959 return true;
13960 }
13961 }
13962
13963 return false;
13964 }
13965
13966 bool
13967 remote_target::can_use_agent ()
13968 {
13969 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13970 }
13971
13972 struct btrace_target_info
13973 {
13974 /* The ptid of the traced thread. */
13975 ptid_t ptid;
13976
13977 /* The obtained branch trace configuration. */
13978 struct btrace_config conf;
13979 };
13980
13981 /* Reset our idea of our target's btrace configuration. */
13982
13983 static void
13984 remote_btrace_reset (remote_state *rs)
13985 {
13986 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13987 }
13988
13989 /* Synchronize the configuration with the target. */
13990
13991 void
13992 remote_target::btrace_sync_conf (const btrace_config *conf)
13993 {
13994 struct packet_config *packet;
13995 struct remote_state *rs;
13996 char *buf, *pos, *endbuf;
13997
13998 rs = get_remote_state ();
13999 buf = rs->buf.data ();
14000 endbuf = buf + get_remote_packet_size ();
14001
14002 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
14003 if (packet_config_support (packet) == PACKET_ENABLE
14004 && conf->bts.size != rs->btrace_config.bts.size)
14005 {
14006 pos = buf;
14007 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
14008 conf->bts.size);
14009
14010 putpkt (buf);
14011 getpkt (&rs->buf, 0);
14012
14013 if (packet_ok (buf, packet) == PACKET_ERROR)
14014 {
14015 if (buf[0] == 'E' && buf[1] == '.')
14016 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14017 else
14018 error (_("Failed to configure the BTS buffer size."));
14019 }
14020
14021 rs->btrace_config.bts.size = conf->bts.size;
14022 }
14023
14024 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
14025 if (packet_config_support (packet) == PACKET_ENABLE
14026 && conf->pt.size != rs->btrace_config.pt.size)
14027 {
14028 pos = buf;
14029 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
14030 conf->pt.size);
14031
14032 putpkt (buf);
14033 getpkt (&rs->buf, 0);
14034
14035 if (packet_ok (buf, packet) == PACKET_ERROR)
14036 {
14037 if (buf[0] == 'E' && buf[1] == '.')
14038 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14039 else
14040 error (_("Failed to configure the trace buffer size."));
14041 }
14042
14043 rs->btrace_config.pt.size = conf->pt.size;
14044 }
14045 }
14046
14047 /* Read TP's btrace configuration from the target and store it into CONF. */
14048
14049 static void
14050 btrace_read_config (thread_info *tp, struct btrace_config *conf)
14051 {
14052 /* target_read_stralloc relies on INFERIOR_PTID. */
14053 scoped_restore_current_thread restore_thread;
14054 switch_to_thread (tp);
14055
14056 gdb::optional<gdb::char_vector> xml
14057 = target_read_stralloc (current_inferior ()->top_target (),
14058 TARGET_OBJECT_BTRACE_CONF, "");
14059 if (xml)
14060 parse_xml_btrace_conf (conf, xml->data ());
14061 }
14062
14063 /* Maybe reopen target btrace. */
14064
14065 void
14066 remote_target::remote_btrace_maybe_reopen ()
14067 {
14068 struct remote_state *rs = get_remote_state ();
14069 int btrace_target_pushed = 0;
14070 #if !defined (HAVE_LIBIPT)
14071 int warned = 0;
14072 #endif
14073
14074 /* Don't bother walking the entirety of the remote thread list when
14075 we know the feature isn't supported by the remote. */
14076 if (packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14077 return;
14078
14079 for (thread_info *tp : all_non_exited_threads (this))
14080 {
14081 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14082 btrace_read_config (tp, &rs->btrace_config);
14083
14084 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14085 continue;
14086
14087 #if !defined (HAVE_LIBIPT)
14088 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14089 {
14090 if (!warned)
14091 {
14092 warned = 1;
14093 warning (_("Target is recording using Intel Processor Trace "
14094 "but support was disabled at compile time."));
14095 }
14096
14097 continue;
14098 }
14099 #endif /* !defined (HAVE_LIBIPT) */
14100
14101 /* Push target, once, but before anything else happens. This way our
14102 changes to the threads will be cleaned up by unpushing the target
14103 in case btrace_read_config () throws. */
14104 if (!btrace_target_pushed)
14105 {
14106 btrace_target_pushed = 1;
14107 record_btrace_push_target ();
14108 gdb_printf (_("Target is recording using %s.\n"),
14109 btrace_format_string (rs->btrace_config.format));
14110 }
14111
14112 tp->btrace.target = XCNEW (struct btrace_target_info);
14113 tp->btrace.target->ptid = tp->ptid;
14114 tp->btrace.target->conf = rs->btrace_config;
14115 }
14116 }
14117
14118 /* Enable branch tracing. */
14119
14120 struct btrace_target_info *
14121 remote_target::enable_btrace (thread_info *tp,
14122 const struct btrace_config *conf)
14123 {
14124 struct btrace_target_info *tinfo = NULL;
14125 struct packet_config *packet = NULL;
14126 struct remote_state *rs = get_remote_state ();
14127 char *buf = rs->buf.data ();
14128 char *endbuf = buf + get_remote_packet_size ();
14129
14130 switch (conf->format)
14131 {
14132 case BTRACE_FORMAT_BTS:
14133 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
14134 break;
14135
14136 case BTRACE_FORMAT_PT:
14137 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
14138 break;
14139 }
14140
14141 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14142 error (_("Target does not support branch tracing."));
14143
14144 btrace_sync_conf (conf);
14145
14146 ptid_t ptid = tp->ptid;
14147 set_general_thread (ptid);
14148
14149 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14150 putpkt (rs->buf);
14151 getpkt (&rs->buf, 0);
14152
14153 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14154 {
14155 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14156 error (_("Could not enable branch tracing for %s: %s"),
14157 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14158 else
14159 error (_("Could not enable branch tracing for %s."),
14160 target_pid_to_str (ptid).c_str ());
14161 }
14162
14163 tinfo = XCNEW (struct btrace_target_info);
14164 tinfo->ptid = ptid;
14165
14166 /* If we fail to read the configuration, we lose some information, but the
14167 tracing itself is not impacted. */
14168 try
14169 {
14170 btrace_read_config (tp, &tinfo->conf);
14171 }
14172 catch (const gdb_exception_error &err)
14173 {
14174 if (err.message != NULL)
14175 warning ("%s", err.what ());
14176 }
14177
14178 return tinfo;
14179 }
14180
14181 /* Disable branch tracing. */
14182
14183 void
14184 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14185 {
14186 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
14187 struct remote_state *rs = get_remote_state ();
14188 char *buf = rs->buf.data ();
14189 char *endbuf = buf + get_remote_packet_size ();
14190
14191 if (packet_config_support (packet) != PACKET_ENABLE)
14192 error (_("Target does not support branch tracing."));
14193
14194 set_general_thread (tinfo->ptid);
14195
14196 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14197 putpkt (rs->buf);
14198 getpkt (&rs->buf, 0);
14199
14200 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14201 {
14202 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14203 error (_("Could not disable branch tracing for %s: %s"),
14204 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14205 else
14206 error (_("Could not disable branch tracing for %s."),
14207 target_pid_to_str (tinfo->ptid).c_str ());
14208 }
14209
14210 xfree (tinfo);
14211 }
14212
14213 /* Teardown branch tracing. */
14214
14215 void
14216 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14217 {
14218 /* We must not talk to the target during teardown. */
14219 xfree (tinfo);
14220 }
14221
14222 /* Read the branch trace. */
14223
14224 enum btrace_error
14225 remote_target::read_btrace (struct btrace_data *btrace,
14226 struct btrace_target_info *tinfo,
14227 enum btrace_read_type type)
14228 {
14229 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
14230 const char *annex;
14231
14232 if (packet_config_support (packet) != PACKET_ENABLE)
14233 error (_("Target does not support branch tracing."));
14234
14235 #if !defined(HAVE_LIBEXPAT)
14236 error (_("Cannot process branch tracing result. XML parsing not supported."));
14237 #endif
14238
14239 switch (type)
14240 {
14241 case BTRACE_READ_ALL:
14242 annex = "all";
14243 break;
14244 case BTRACE_READ_NEW:
14245 annex = "new";
14246 break;
14247 case BTRACE_READ_DELTA:
14248 annex = "delta";
14249 break;
14250 default:
14251 internal_error (_("Bad branch tracing read type: %u."),
14252 (unsigned int) type);
14253 }
14254
14255 gdb::optional<gdb::char_vector> xml
14256 = target_read_stralloc (current_inferior ()->top_target (),
14257 TARGET_OBJECT_BTRACE, annex);
14258 if (!xml)
14259 return BTRACE_ERR_UNKNOWN;
14260
14261 parse_xml_btrace (btrace, xml->data ());
14262
14263 return BTRACE_ERR_NONE;
14264 }
14265
14266 const struct btrace_config *
14267 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14268 {
14269 return &tinfo->conf;
14270 }
14271
14272 bool
14273 remote_target::augmented_libraries_svr4_read ()
14274 {
14275 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
14276 == PACKET_ENABLE);
14277 }
14278
14279 /* Implementation of to_load. */
14280
14281 void
14282 remote_target::load (const char *name, int from_tty)
14283 {
14284 generic_load (name, from_tty);
14285 }
14286
14287 /* Accepts an integer PID; returns a string representing a file that
14288 can be opened on the remote side to get the symbols for the child
14289 process. Returns NULL if the operation is not supported. */
14290
14291 const char *
14292 remote_target::pid_to_exec_file (int pid)
14293 {
14294 static gdb::optional<gdb::char_vector> filename;
14295 char *annex = NULL;
14296
14297 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14298 return NULL;
14299
14300 inferior *inf = find_inferior_pid (this, pid);
14301 if (inf == NULL)
14302 internal_error (_("not currently attached to process %d"), pid);
14303
14304 if (!inf->fake_pid_p)
14305 {
14306 const int annex_size = 9;
14307
14308 annex = (char *) alloca (annex_size);
14309 xsnprintf (annex, annex_size, "%x", pid);
14310 }
14311
14312 filename = target_read_stralloc (current_inferior ()->top_target (),
14313 TARGET_OBJECT_EXEC_FILE, annex);
14314
14315 return filename ? filename->data () : nullptr;
14316 }
14317
14318 /* Implement the to_can_do_single_step target_ops method. */
14319
14320 int
14321 remote_target::can_do_single_step ()
14322 {
14323 /* We can only tell whether target supports single step or not by
14324 supported s and S vCont actions if the stub supports vContSupported
14325 feature. If the stub doesn't support vContSupported feature,
14326 we have conservatively to think target doesn't supports single
14327 step. */
14328 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14329 {
14330 struct remote_state *rs = get_remote_state ();
14331
14332 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14333 remote_vcont_probe ();
14334
14335 return rs->supports_vCont.s && rs->supports_vCont.S;
14336 }
14337 else
14338 return 0;
14339 }
14340
14341 /* Implementation of the to_execution_direction method for the remote
14342 target. */
14343
14344 enum exec_direction_kind
14345 remote_target::execution_direction ()
14346 {
14347 struct remote_state *rs = get_remote_state ();
14348
14349 return rs->last_resume_exec_dir;
14350 }
14351
14352 /* Return pointer to the thread_info struct which corresponds to
14353 THREAD_HANDLE (having length HANDLE_LEN). */
14354
14355 thread_info *
14356 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14357 int handle_len,
14358 inferior *inf)
14359 {
14360 for (thread_info *tp : all_non_exited_threads (this))
14361 {
14362 remote_thread_info *priv = get_remote_thread_info (tp);
14363
14364 if (tp->inf == inf && priv != NULL)
14365 {
14366 if (handle_len != priv->thread_handle.size ())
14367 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14368 handle_len, priv->thread_handle.size ());
14369 if (memcmp (thread_handle, priv->thread_handle.data (),
14370 handle_len) == 0)
14371 return tp;
14372 }
14373 }
14374
14375 return NULL;
14376 }
14377
14378 gdb::byte_vector
14379 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14380 {
14381 remote_thread_info *priv = get_remote_thread_info (tp);
14382 return priv->thread_handle;
14383 }
14384
14385 bool
14386 remote_target::can_async_p ()
14387 {
14388 /* This flag should be checked in the common target.c code. */
14389 gdb_assert (target_async_permitted);
14390
14391 /* We're async whenever the serial device can. */
14392 struct remote_state *rs = get_remote_state ();
14393 return serial_can_async_p (rs->remote_desc);
14394 }
14395
14396 bool
14397 remote_target::is_async_p ()
14398 {
14399 /* We're async whenever the serial device is. */
14400 struct remote_state *rs = get_remote_state ();
14401 return serial_is_async_p (rs->remote_desc);
14402 }
14403
14404 /* Pass the SERIAL event on and up to the client. One day this code
14405 will be able to delay notifying the client of an event until the
14406 point where an entire packet has been received. */
14407
14408 static serial_event_ftype remote_async_serial_handler;
14409
14410 static void
14411 remote_async_serial_handler (struct serial *scb, void *context)
14412 {
14413 /* Don't propogate error information up to the client. Instead let
14414 the client find out about the error by querying the target. */
14415 inferior_event_handler (INF_REG_EVENT);
14416 }
14417
14418 static void
14419 remote_async_inferior_event_handler (gdb_client_data data)
14420 {
14421 inferior_event_handler (INF_REG_EVENT);
14422 }
14423
14424 int
14425 remote_target::async_wait_fd ()
14426 {
14427 struct remote_state *rs = get_remote_state ();
14428 return rs->remote_desc->fd;
14429 }
14430
14431 void
14432 remote_target::async (bool enable)
14433 {
14434 struct remote_state *rs = get_remote_state ();
14435
14436 if (enable)
14437 {
14438 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14439
14440 /* If there are pending events in the stop reply queue tell the
14441 event loop to process them. */
14442 if (!rs->stop_reply_queue.empty ())
14443 mark_async_event_handler (rs->remote_async_inferior_event_token);
14444 /* For simplicity, below we clear the pending events token
14445 without remembering whether it is marked, so here we always
14446 mark it. If there's actually no pending notification to
14447 process, this ends up being a no-op (other than a spurious
14448 event-loop wakeup). */
14449 if (target_is_non_stop_p ())
14450 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14451 }
14452 else
14453 {
14454 serial_async (rs->remote_desc, NULL, NULL);
14455 /* If the core is disabling async, it doesn't want to be
14456 disturbed with target events. Clear all async event sources
14457 too. */
14458 clear_async_event_handler (rs->remote_async_inferior_event_token);
14459 if (target_is_non_stop_p ())
14460 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14461 }
14462 }
14463
14464 /* Implementation of the to_thread_events method. */
14465
14466 void
14467 remote_target::thread_events (int enable)
14468 {
14469 struct remote_state *rs = get_remote_state ();
14470 size_t size = get_remote_packet_size ();
14471
14472 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14473 return;
14474
14475 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
14476 putpkt (rs->buf);
14477 getpkt (&rs->buf, 0);
14478
14479 switch (packet_ok (rs->buf,
14480 &remote_protocol_packets[PACKET_QThreadEvents]))
14481 {
14482 case PACKET_OK:
14483 if (strcmp (rs->buf.data (), "OK") != 0)
14484 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
14485 break;
14486 case PACKET_ERROR:
14487 warning (_("Remote failure reply: %s"), rs->buf.data ());
14488 break;
14489 case PACKET_UNKNOWN:
14490 break;
14491 }
14492 }
14493
14494 static void
14495 show_remote_cmd (const char *args, int from_tty)
14496 {
14497 /* We can't just use cmd_show_list here, because we want to skip
14498 the redundant "show remote Z-packet" and the legacy aliases. */
14499 struct cmd_list_element *list = remote_show_cmdlist;
14500 struct ui_out *uiout = current_uiout;
14501
14502 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14503 for (; list != NULL; list = list->next)
14504 if (strcmp (list->name, "Z-packet") == 0)
14505 continue;
14506 else if (list->type == not_set_cmd)
14507 /* Alias commands are exactly like the original, except they
14508 don't have the normal type. */
14509 continue;
14510 else
14511 {
14512 ui_out_emit_tuple option_emitter (uiout, "option");
14513
14514 uiout->field_string ("name", list->name);
14515 uiout->text (": ");
14516 if (list->type == show_cmd)
14517 do_show_command (NULL, from_tty, list);
14518 else
14519 cmd_func (list, NULL, from_tty);
14520 }
14521 }
14522
14523
14524 /* Function to be called whenever a new objfile (shlib) is detected. */
14525 static void
14526 remote_new_objfile (struct objfile *objfile)
14527 {
14528 /* The objfile change happened in that program space. */
14529 program_space *pspace = current_program_space;
14530
14531 /* The affected program space is possibly shared by multiple inferiors.
14532 Consider sending a qSymbol packet for each of the inferiors using that
14533 program space. */
14534 for (inferior *inf : all_inferiors ())
14535 {
14536 if (inf->pspace != pspace)
14537 continue;
14538
14539 /* Check whether the inferior's process target is a remote target. */
14540 remote_target *remote = as_remote_target (inf->process_target ());
14541 if (remote == nullptr)
14542 continue;
14543
14544 /* When we are attaching or handling a fork child and the shared library
14545 subsystem reads the list of loaded libraries, we receive new objfile
14546 events in between each found library. The libraries are read in an
14547 undefined order, so if we gave the remote side a chance to look up
14548 symbols between each objfile, we might give it an inconsistent picture
14549 of the inferior. It could appear that a library A appears loaded but
14550 a library B does not, even though library A requires library B. That
14551 would present a state that couldn't normally exist in the inferior.
14552
14553 So, skip these events, we'll give the remote a chance to look up
14554 symbols once all the loaded libraries and their symbols are known to
14555 GDB. */
14556 if (inf->in_initial_library_scan)
14557 continue;
14558
14559 if (!remote->has_execution (inf))
14560 continue;
14561
14562 /* Need to switch to a specific thread, because remote_check_symbols will
14563 set the general thread using INFERIOR_PTID.
14564
14565 It's possible to have inferiors with no thread here, because we are
14566 called very early in the connection process, while the inferior is
14567 being set up, before threads are added. Just skip it, start_remote_1
14568 also calls remote_check_symbols when it's done setting things up. */
14569 thread_info *thread = any_thread_of_inferior (inf);
14570 if (thread != nullptr)
14571 {
14572 scoped_restore_current_thread restore_thread;
14573 switch_to_thread (thread);
14574 remote->remote_check_symbols ();
14575 }
14576 }
14577 }
14578
14579 /* Pull all the tracepoints defined on the target and create local
14580 data structures representing them. We don't want to create real
14581 tracepoints yet, we don't want to mess up the user's existing
14582 collection. */
14583
14584 int
14585 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14586 {
14587 struct remote_state *rs = get_remote_state ();
14588 char *p;
14589
14590 /* Ask for a first packet of tracepoint definition. */
14591 putpkt ("qTfP");
14592 getpkt (&rs->buf, 0);
14593 p = rs->buf.data ();
14594 while (*p && *p != 'l')
14595 {
14596 parse_tracepoint_definition (p, utpp);
14597 /* Ask for another packet of tracepoint definition. */
14598 putpkt ("qTsP");
14599 getpkt (&rs->buf, 0);
14600 p = rs->buf.data ();
14601 }
14602 return 0;
14603 }
14604
14605 int
14606 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14607 {
14608 struct remote_state *rs = get_remote_state ();
14609 char *p;
14610
14611 /* Ask for a first packet of variable definition. */
14612 putpkt ("qTfV");
14613 getpkt (&rs->buf, 0);
14614 p = rs->buf.data ();
14615 while (*p && *p != 'l')
14616 {
14617 parse_tsv_definition (p, utsvp);
14618 /* Ask for another packet of variable definition. */
14619 putpkt ("qTsV");
14620 getpkt (&rs->buf, 0);
14621 p = rs->buf.data ();
14622 }
14623 return 0;
14624 }
14625
14626 /* The "set/show range-stepping" show hook. */
14627
14628 static void
14629 show_range_stepping (struct ui_file *file, int from_tty,
14630 struct cmd_list_element *c,
14631 const char *value)
14632 {
14633 gdb_printf (file,
14634 _("Debugger's willingness to use range stepping "
14635 "is %s.\n"), value);
14636 }
14637
14638 /* Return true if the vCont;r action is supported by the remote
14639 stub. */
14640
14641 bool
14642 remote_target::vcont_r_supported ()
14643 {
14644 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14645 remote_vcont_probe ();
14646
14647 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14648 && get_remote_state ()->supports_vCont.r);
14649 }
14650
14651 /* The "set/show range-stepping" set hook. */
14652
14653 static void
14654 set_range_stepping (const char *ignore_args, int from_tty,
14655 struct cmd_list_element *c)
14656 {
14657 /* When enabling, check whether range stepping is actually supported
14658 by the target, and warn if not. */
14659 if (use_range_stepping)
14660 {
14661 remote_target *remote = get_current_remote_target ();
14662 if (remote == NULL
14663 || !remote->vcont_r_supported ())
14664 warning (_("Range stepping is not supported by the current target"));
14665 }
14666 }
14667
14668 static void
14669 show_remote_debug (struct ui_file *file, int from_tty,
14670 struct cmd_list_element *c, const char *value)
14671 {
14672 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
14673 value);
14674 }
14675
14676 static void
14677 show_remote_timeout (struct ui_file *file, int from_tty,
14678 struct cmd_list_element *c, const char *value)
14679 {
14680 gdb_printf (file,
14681 _("Timeout limit to wait for target to respond is %s.\n"),
14682 value);
14683 }
14684
14685 /* Implement the "supports_memory_tagging" target_ops method. */
14686
14687 bool
14688 remote_target::supports_memory_tagging ()
14689 {
14690 return remote_memory_tagging_p ();
14691 }
14692
14693 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
14694
14695 static void
14696 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14697 size_t len, int type)
14698 {
14699 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14700
14701 std::string request = string_printf ("qMemTags:%s,%s:%s",
14702 phex_nz (address, addr_size),
14703 phex_nz (len, sizeof (len)),
14704 phex_nz (type, sizeof (type)));
14705
14706 strcpy (packet.data (), request.c_str ());
14707 }
14708
14709 /* Parse the qMemTags packet reply into TAGS.
14710
14711 Return true if successful, false otherwise. */
14712
14713 static bool
14714 parse_fetch_memtags_reply (const gdb::char_vector &reply,
14715 gdb::byte_vector &tags)
14716 {
14717 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
14718 return false;
14719
14720 /* Copy the tag data. */
14721 tags = hex2bin (reply.data () + 1);
14722
14723 return true;
14724 }
14725
14726 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
14727
14728 static void
14729 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14730 size_t len, int type,
14731 const gdb::byte_vector &tags)
14732 {
14733 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14734
14735 /* Put together the main packet, address and length. */
14736 std::string request = string_printf ("QMemTags:%s,%s:%s:",
14737 phex_nz (address, addr_size),
14738 phex_nz (len, sizeof (len)),
14739 phex_nz (type, sizeof (type)));
14740 request += bin2hex (tags.data (), tags.size ());
14741
14742 /* Check if we have exceeded the maximum packet size. */
14743 if (packet.size () < request.length ())
14744 error (_("Contents too big for packet QMemTags."));
14745
14746 strcpy (packet.data (), request.c_str ());
14747 }
14748
14749 /* Implement the "fetch_memtags" target_ops method. */
14750
14751 bool
14752 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
14753 gdb::byte_vector &tags, int type)
14754 {
14755 /* Make sure the qMemTags packet is supported. */
14756 if (!remote_memory_tagging_p ())
14757 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
14758
14759 struct remote_state *rs = get_remote_state ();
14760
14761 create_fetch_memtags_request (rs->buf, address, len, type);
14762
14763 putpkt (rs->buf);
14764 getpkt (&rs->buf, 0);
14765
14766 return parse_fetch_memtags_reply (rs->buf, tags);
14767 }
14768
14769 /* Implement the "store_memtags" target_ops method. */
14770
14771 bool
14772 remote_target::store_memtags (CORE_ADDR address, size_t len,
14773 const gdb::byte_vector &tags, int type)
14774 {
14775 /* Make sure the QMemTags packet is supported. */
14776 if (!remote_memory_tagging_p ())
14777 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
14778
14779 struct remote_state *rs = get_remote_state ();
14780
14781 create_store_memtags_request (rs->buf, address, len, type, tags);
14782
14783 putpkt (rs->buf);
14784 getpkt (&rs->buf, 0);
14785
14786 /* Verify if the request was successful. */
14787 return packet_check_result (rs->buf.data ()) == PACKET_OK;
14788 }
14789
14790 /* Return true if remote target T is non-stop. */
14791
14792 bool
14793 remote_target_is_non_stop_p (remote_target *t)
14794 {
14795 scoped_restore_current_thread restore_thread;
14796 switch_to_target_no_thread (t);
14797
14798 return target_is_non_stop_p ();
14799 }
14800
14801 #if GDB_SELF_TEST
14802
14803 namespace selftests {
14804
14805 static void
14806 test_memory_tagging_functions ()
14807 {
14808 remote_target remote;
14809
14810 struct packet_config *config
14811 = &remote_protocol_packets[PACKET_memory_tagging_feature];
14812
14813 scoped_restore restore_memtag_support_
14814 = make_scoped_restore (&config->support);
14815
14816 /* Test memory tagging packet support. */
14817 config->support = PACKET_SUPPORT_UNKNOWN;
14818 SELF_CHECK (remote.supports_memory_tagging () == false);
14819 config->support = PACKET_DISABLE;
14820 SELF_CHECK (remote.supports_memory_tagging () == false);
14821 config->support = PACKET_ENABLE;
14822 SELF_CHECK (remote.supports_memory_tagging () == true);
14823
14824 /* Setup testing. */
14825 gdb::char_vector packet;
14826 gdb::byte_vector tags, bv;
14827 std::string expected, reply;
14828 packet.resize (32000);
14829
14830 /* Test creating a qMemTags request. */
14831
14832 expected = "qMemTags:0,0:0";
14833 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
14834 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14835
14836 expected = "qMemTags:deadbeef,10:1";
14837 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
14838 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14839
14840 /* Test parsing a qMemTags reply. */
14841
14842 /* Error reply, tags vector unmodified. */
14843 reply = "E00";
14844 strcpy (packet.data (), reply.c_str ());
14845 tags.resize (0);
14846 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
14847 SELF_CHECK (tags.size () == 0);
14848
14849 /* Valid reply, tags vector updated. */
14850 tags.resize (0);
14851 bv.resize (0);
14852
14853 for (int i = 0; i < 5; i++)
14854 bv.push_back (i);
14855
14856 reply = "m" + bin2hex (bv.data (), bv.size ());
14857 strcpy (packet.data (), reply.c_str ());
14858
14859 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
14860 SELF_CHECK (tags.size () == 5);
14861
14862 for (int i = 0; i < 5; i++)
14863 SELF_CHECK (tags[i] == i);
14864
14865 /* Test creating a QMemTags request. */
14866
14867 /* Empty tag data. */
14868 tags.resize (0);
14869 expected = "QMemTags:0,0:0:";
14870 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
14871 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14872 expected.length ()) == 0);
14873
14874 /* Non-empty tag data. */
14875 tags.resize (0);
14876 for (int i = 0; i < 5; i++)
14877 tags.push_back (i);
14878 expected = "QMemTags:deadbeef,ff:1:0001020304";
14879 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
14880 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14881 expected.length ()) == 0);
14882 }
14883
14884 } // namespace selftests
14885 #endif /* GDB_SELF_TEST */
14886
14887 void _initialize_remote ();
14888 void
14889 _initialize_remote ()
14890 {
14891 add_target (remote_target_info, remote_target::open);
14892 add_target (extended_remote_target_info, extended_remote_target::open);
14893
14894 /* Hook into new objfile notification. */
14895 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
14896
14897 #if 0
14898 init_remote_threadtests ();
14899 #endif
14900
14901 /* set/show remote ... */
14902
14903 add_basic_prefix_cmd ("remote", class_maintenance, _("\
14904 Remote protocol specific variables.\n\
14905 Configure various remote-protocol specific variables such as\n\
14906 the packets being used."),
14907 &remote_set_cmdlist,
14908 0 /* allow-unknown */, &setlist);
14909 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14910 Remote protocol specific variables.\n\
14911 Configure various remote-protocol specific variables such as\n\
14912 the packets being used."),
14913 &remote_show_cmdlist,
14914 0 /* allow-unknown */, &showlist);
14915
14916 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14917 Compare section data on target to the exec file.\n\
14918 Argument is a single section name (default: all loaded sections).\n\
14919 To compare only read-only loaded sections, specify the -r option."),
14920 &cmdlist);
14921
14922 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
14923 Send an arbitrary packet to a remote target.\n\
14924 maintenance packet TEXT\n\
14925 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14926 this command sends the string TEXT to the inferior, and displays the\n\
14927 response packet. GDB supplies the initial `$' character, and the\n\
14928 terminating `#' character and checksum."),
14929 &maintenancelist);
14930
14931 set_show_commands remotebreak_cmds
14932 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14933 Set whether to send break if interrupted."), _("\
14934 Show whether to send break if interrupted."), _("\
14935 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14936 set_remotebreak, show_remotebreak,
14937 &setlist, &showlist);
14938 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
14939 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
14940
14941 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14942 interrupt_sequence_modes, &interrupt_sequence_mode,
14943 _("\
14944 Set interrupt sequence to remote target."), _("\
14945 Show interrupt sequence to remote target."), _("\
14946 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14947 NULL, show_interrupt_sequence,
14948 &remote_set_cmdlist,
14949 &remote_show_cmdlist);
14950
14951 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14952 &interrupt_on_connect, _("\
14953 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
14954 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
14955 If set, interrupt sequence is sent to remote target."),
14956 NULL, NULL,
14957 &remote_set_cmdlist, &remote_show_cmdlist);
14958
14959 /* Install commands for configuring memory read/write packets. */
14960
14961 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14962 Set the maximum number of bytes per memory write packet (deprecated)."),
14963 &setlist);
14964 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14965 Show the maximum number of bytes per memory write packet (deprecated)."),
14966 &showlist);
14967 add_cmd ("memory-write-packet-size", no_class,
14968 set_memory_write_packet_size, _("\
14969 Set the maximum number of bytes per memory-write packet.\n\
14970 Specify the number of bytes in a packet or 0 (zero) for the\n\
14971 default packet size. The actual limit is further reduced\n\
14972 dependent on the target. Specify ``fixed'' to disable the\n\
14973 further restriction and ``limit'' to enable that restriction."),
14974 &remote_set_cmdlist);
14975 add_cmd ("memory-read-packet-size", no_class,
14976 set_memory_read_packet_size, _("\
14977 Set the maximum number of bytes per memory-read packet.\n\
14978 Specify the number of bytes in a packet or 0 (zero) for the\n\
14979 default packet size. The actual limit is further reduced\n\
14980 dependent on the target. Specify ``fixed'' to disable the\n\
14981 further restriction and ``limit'' to enable that restriction."),
14982 &remote_set_cmdlist);
14983 add_cmd ("memory-write-packet-size", no_class,
14984 show_memory_write_packet_size,
14985 _("Show the maximum number of bytes per memory-write packet."),
14986 &remote_show_cmdlist);
14987 add_cmd ("memory-read-packet-size", no_class,
14988 show_memory_read_packet_size,
14989 _("Show the maximum number of bytes per memory-read packet."),
14990 &remote_show_cmdlist);
14991
14992 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
14993 &remote_hw_watchpoint_limit, _("\
14994 Set the maximum number of target hardware watchpoints."), _("\
14995 Show the maximum number of target hardware watchpoints."), _("\
14996 Specify \"unlimited\" for unlimited hardware watchpoints."),
14997 NULL, show_hardware_watchpoint_limit,
14998 &remote_set_cmdlist,
14999 &remote_show_cmdlist);
15000 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15001 no_class,
15002 &remote_hw_watchpoint_length_limit, _("\
15003 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15004 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15005 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15006 NULL, show_hardware_watchpoint_length_limit,
15007 &remote_set_cmdlist, &remote_show_cmdlist);
15008 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
15009 &remote_hw_breakpoint_limit, _("\
15010 Set the maximum number of target hardware breakpoints."), _("\
15011 Show the maximum number of target hardware breakpoints."), _("\
15012 Specify \"unlimited\" for unlimited hardware breakpoints."),
15013 NULL, show_hardware_breakpoint_limit,
15014 &remote_set_cmdlist, &remote_show_cmdlist);
15015
15016 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15017 &remote_address_size, _("\
15018 Set the maximum size of the address (in bits) in a memory packet."), _("\
15019 Show the maximum size of the address (in bits) in a memory packet."), NULL,
15020 NULL,
15021 NULL, /* FIXME: i18n: */
15022 &setlist, &showlist);
15023
15024 init_all_packet_configs ();
15025
15026 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
15027 "X", "binary-download", 1);
15028
15029 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
15030 "vCont", "verbose-resume", 0);
15031
15032 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
15033 "QPassSignals", "pass-signals", 0);
15034
15035 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
15036 "QCatchSyscalls", "catch-syscalls", 0);
15037
15038 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
15039 "QProgramSignals", "program-signals", 0);
15040
15041 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
15042 "QSetWorkingDir", "set-working-dir", 0);
15043
15044 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
15045 "QStartupWithShell", "startup-with-shell", 0);
15046
15047 add_packet_config_cmd (&remote_protocol_packets
15048 [PACKET_QEnvironmentHexEncoded],
15049 "QEnvironmentHexEncoded", "environment-hex-encoded",
15050 0);
15051
15052 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
15053 "QEnvironmentReset", "environment-reset",
15054 0);
15055
15056 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
15057 "QEnvironmentUnset", "environment-unset",
15058 0);
15059
15060 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
15061 "qSymbol", "symbol-lookup", 0);
15062
15063 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
15064 "P", "set-register", 1);
15065
15066 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
15067 "p", "fetch-register", 1);
15068
15069 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
15070 "Z0", "software-breakpoint", 0);
15071
15072 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
15073 "Z1", "hardware-breakpoint", 0);
15074
15075 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
15076 "Z2", "write-watchpoint", 0);
15077
15078 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
15079 "Z3", "read-watchpoint", 0);
15080
15081 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
15082 "Z4", "access-watchpoint", 0);
15083
15084 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
15085 "qXfer:auxv:read", "read-aux-vector", 0);
15086
15087 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
15088 "qXfer:exec-file:read", "pid-to-exec-file", 0);
15089
15090 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
15091 "qXfer:features:read", "target-features", 0);
15092
15093 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
15094 "qXfer:libraries:read", "library-info", 0);
15095
15096 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
15097 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15098
15099 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
15100 "qXfer:memory-map:read", "memory-map", 0);
15101
15102 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
15103 "qXfer:osdata:read", "osdata", 0);
15104
15105 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
15106 "qXfer:threads:read", "threads", 0);
15107
15108 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
15109 "qXfer:siginfo:read", "read-siginfo-object", 0);
15110
15111 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
15112 "qXfer:siginfo:write", "write-siginfo-object", 0);
15113
15114 add_packet_config_cmd
15115 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
15116 "qXfer:traceframe-info:read", "traceframe-info", 0);
15117
15118 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
15119 "qXfer:uib:read", "unwind-info-block", 0);
15120
15121 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
15122 "qGetTLSAddr", "get-thread-local-storage-address",
15123 0);
15124
15125 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
15126 "qGetTIBAddr", "get-thread-information-block-address",
15127 0);
15128
15129 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
15130 "bc", "reverse-continue", 0);
15131
15132 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
15133 "bs", "reverse-step", 0);
15134
15135 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
15136 "qSupported", "supported-packets", 0);
15137
15138 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
15139 "qSearch:memory", "search-memory", 0);
15140
15141 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
15142 "qTStatus", "trace-status", 0);
15143
15144 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
15145 "vFile:setfs", "hostio-setfs", 0);
15146
15147 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
15148 "vFile:open", "hostio-open", 0);
15149
15150 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
15151 "vFile:pread", "hostio-pread", 0);
15152
15153 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
15154 "vFile:pwrite", "hostio-pwrite", 0);
15155
15156 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
15157 "vFile:close", "hostio-close", 0);
15158
15159 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
15160 "vFile:unlink", "hostio-unlink", 0);
15161
15162 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
15163 "vFile:readlink", "hostio-readlink", 0);
15164
15165 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
15166 "vFile:fstat", "hostio-fstat", 0);
15167
15168 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
15169 "vAttach", "attach", 0);
15170
15171 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
15172 "vRun", "run", 0);
15173
15174 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
15175 "QStartNoAckMode", "noack", 0);
15176
15177 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
15178 "vKill", "kill", 0);
15179
15180 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
15181 "qAttached", "query-attached", 0);
15182
15183 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
15184 "ConditionalTracepoints",
15185 "conditional-tracepoints", 0);
15186
15187 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
15188 "ConditionalBreakpoints",
15189 "conditional-breakpoints", 0);
15190
15191 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
15192 "BreakpointCommands",
15193 "breakpoint-commands", 0);
15194
15195 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
15196 "FastTracepoints", "fast-tracepoints", 0);
15197
15198 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
15199 "TracepointSource", "TracepointSource", 0);
15200
15201 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
15202 "QAllow", "allow", 0);
15203
15204 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
15205 "StaticTracepoints", "static-tracepoints", 0);
15206
15207 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
15208 "InstallInTrace", "install-in-trace", 0);
15209
15210 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
15211 "qXfer:statictrace:read", "read-sdata-object", 0);
15212
15213 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
15214 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
15215
15216 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
15217 "QDisableRandomization", "disable-randomization", 0);
15218
15219 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
15220 "QAgent", "agent", 0);
15221
15222 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
15223 "QTBuffer:size", "trace-buffer-size", 0);
15224
15225 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
15226 "Qbtrace:off", "disable-btrace", 0);
15227
15228 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
15229 "Qbtrace:bts", "enable-btrace-bts", 0);
15230
15231 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
15232 "Qbtrace:pt", "enable-btrace-pt", 0);
15233
15234 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
15235 "qXfer:btrace", "read-btrace", 0);
15236
15237 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
15238 "qXfer:btrace-conf", "read-btrace-conf", 0);
15239
15240 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
15241 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
15242
15243 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
15244 "multiprocess-feature", "multiprocess-feature", 0);
15245
15246 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
15247 "swbreak-feature", "swbreak-feature", 0);
15248
15249 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
15250 "hwbreak-feature", "hwbreak-feature", 0);
15251
15252 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
15253 "fork-event-feature", "fork-event-feature", 0);
15254
15255 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
15256 "vfork-event-feature", "vfork-event-feature", 0);
15257
15258 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
15259 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
15260
15261 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
15262 "vContSupported", "verbose-resume-supported", 0);
15263
15264 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
15265 "exec-event-feature", "exec-event-feature", 0);
15266
15267 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
15268 "vCtrlC", "ctrl-c", 0);
15269
15270 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
15271 "QThreadEvents", "thread-events", 0);
15272
15273 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
15274 "N stop reply", "no-resumed-stop-reply", 0);
15275
15276 add_packet_config_cmd (&remote_protocol_packets[PACKET_memory_tagging_feature],
15277 "memory-tagging-feature", "memory-tagging-feature", 0);
15278
15279 /* Assert that we've registered "set remote foo-packet" commands
15280 for all packet configs. */
15281 {
15282 int i;
15283
15284 for (i = 0; i < PACKET_MAX; i++)
15285 {
15286 /* Ideally all configs would have a command associated. Some
15287 still don't though. */
15288 int excepted;
15289
15290 switch (i)
15291 {
15292 case PACKET_QNonStop:
15293 case PACKET_EnableDisableTracepoints_feature:
15294 case PACKET_tracenz_feature:
15295 case PACKET_DisconnectedTracing_feature:
15296 case PACKET_augmented_libraries_svr4_read_feature:
15297 case PACKET_qCRC:
15298 /* Additions to this list need to be well justified:
15299 pre-existing packets are OK; new packets are not. */
15300 excepted = 1;
15301 break;
15302 default:
15303 excepted = 0;
15304 break;
15305 }
15306
15307 /* This catches both forgetting to add a config command, and
15308 forgetting to remove a packet from the exception list. */
15309 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
15310 }
15311 }
15312
15313 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15314 Z sub-packet has its own set and show commands, but users may
15315 have sets to this variable in their .gdbinit files (or in their
15316 documentation). */
15317 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
15318 &remote_Z_packet_detect, _("\
15319 Set use of remote protocol `Z' packets."), _("\
15320 Show use of remote protocol `Z' packets."), _("\
15321 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
15322 packets."),
15323 set_remote_protocol_Z_packet_cmd,
15324 show_remote_protocol_Z_packet_cmd,
15325 /* FIXME: i18n: Use of remote protocol
15326 `Z' packets is %s. */
15327 &remote_set_cmdlist, &remote_show_cmdlist);
15328
15329 add_basic_prefix_cmd ("remote", class_files, _("\
15330 Manipulate files on the remote system.\n\
15331 Transfer files to and from the remote target system."),
15332 &remote_cmdlist,
15333 0 /* allow-unknown */, &cmdlist);
15334
15335 add_cmd ("put", class_files, remote_put_command,
15336 _("Copy a local file to the remote system."),
15337 &remote_cmdlist);
15338
15339 add_cmd ("get", class_files, remote_get_command,
15340 _("Copy a remote file to the local system."),
15341 &remote_cmdlist);
15342
15343 add_cmd ("delete", class_files, remote_delete_command,
15344 _("Delete a remote file."),
15345 &remote_cmdlist);
15346
15347 add_setshow_string_noescape_cmd ("exec-file", class_files,
15348 &remote_exec_file_var, _("\
15349 Set the remote pathname for \"run\"."), _("\
15350 Show the remote pathname for \"run\"."), NULL,
15351 set_remote_exec_file,
15352 show_remote_exec_file,
15353 &remote_set_cmdlist,
15354 &remote_show_cmdlist);
15355
15356 add_setshow_boolean_cmd ("range-stepping", class_run,
15357 &use_range_stepping, _("\
15358 Enable or disable range stepping."), _("\
15359 Show whether target-assisted range stepping is enabled."), _("\
15360 If on, and the target supports it, when stepping a source line, GDB\n\
15361 tells the target to step the corresponding range of addresses itself instead\n\
15362 of issuing multiple single-steps. This speeds up source level\n\
15363 stepping. If off, GDB always issues single-steps, even if range\n\
15364 stepping is supported by the target. The default is on."),
15365 set_range_stepping,
15366 show_range_stepping,
15367 &setlist,
15368 &showlist);
15369
15370 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15371 Set watchdog timer."), _("\
15372 Show watchdog timer."), _("\
15373 When non-zero, this timeout is used instead of waiting forever for a target\n\
15374 to finish a low-level step or continue operation. If the specified amount\n\
15375 of time passes without a response from the target, an error occurs."),
15376 NULL,
15377 show_watchdog,
15378 &setlist, &showlist);
15379
15380 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15381 &remote_packet_max_chars, _("\
15382 Set the maximum number of characters to display for each remote packet."), _("\
15383 Show the maximum number of characters to display for each remote packet."), _("\
15384 Specify \"unlimited\" to display all the characters."),
15385 NULL, show_remote_packet_max_chars,
15386 &setdebuglist, &showdebuglist);
15387
15388 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15389 _("Set debugging of remote protocol."),
15390 _("Show debugging of remote protocol."),
15391 _("\
15392 When enabled, each packet sent or received with the remote target\n\
15393 is displayed."),
15394 NULL,
15395 show_remote_debug,
15396 &setdebuglist, &showdebuglist);
15397
15398 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15399 &remote_timeout, _("\
15400 Set timeout limit to wait for target to respond."), _("\
15401 Show timeout limit to wait for target to respond."), _("\
15402 This value is used to set the time limit for gdb to wait for a response\n\
15403 from the target."),
15404 NULL,
15405 show_remote_timeout,
15406 &setlist, &showlist);
15407
15408 /* Eventually initialize fileio. See fileio.c */
15409 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
15410
15411 #if GDB_SELF_TEST
15412 selftests::register_test ("remote_memory_tagging",
15413 selftests::test_memory_tagging_functions);
15414 #endif
15415 }