]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/remote.c
gdb/remote: iterate on pspace inferiors in remote_new_objfile
[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 "gdb/fileio.h"
63 #include <sys/stat.h>
64 #include "xml-support.h"
65
66 #include "memory-map.h"
67
68 #include "tracepoint.h"
69 #include "ax.h"
70 #include "ax-gdb.h"
71 #include "gdbsupport/agent.h"
72 #include "btrace.h"
73 #include "record-btrace.h"
74 #include <algorithm>
75 #include "gdbsupport/scoped_restore.h"
76 #include "gdbsupport/environ.h"
77 #include "gdbsupport/byte-vector.h"
78 #include "gdbsupport/search.h"
79 #include <algorithm>
80 #include <unordered_map>
81 #include "async-event.h"
82 #include "gdbsupport/selftest.h"
83
84 /* The remote target. */
85
86 static const char remote_doc[] = N_("\
87 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
88 Specify the serial device it is connected to\n\
89 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
90
91 /* See remote.h */
92
93 bool remote_debug = false;
94
95 #define OPAQUETHREADBYTES 8
96
97 /* a 64 bit opaque identifier */
98 typedef unsigned char threadref[OPAQUETHREADBYTES];
99
100 struct gdb_ext_thread_info;
101 struct threads_listing_context;
102 typedef int (*rmt_thread_action) (threadref *ref, void *context);
103 struct protocol_feature;
104 struct packet_reg;
105
106 struct stop_reply;
107 typedef std::unique_ptr<stop_reply> stop_reply_up;
108
109 /* Generic configuration support for packets the stub optionally
110 supports. Allows the user to specify the use of the packet as well
111 as allowing GDB to auto-detect support in the remote stub. */
112
113 enum packet_support
114 {
115 PACKET_SUPPORT_UNKNOWN = 0,
116 PACKET_ENABLE,
117 PACKET_DISABLE
118 };
119
120 /* Analyze a packet's return value and update the packet config
121 accordingly. */
122
123 enum packet_result
124 {
125 PACKET_ERROR,
126 PACKET_OK,
127 PACKET_UNKNOWN
128 };
129
130 struct threads_listing_context;
131
132 /* Stub vCont actions support.
133
134 Each field is a boolean flag indicating whether the stub reports
135 support for the corresponding action. */
136
137 struct vCont_action_support
138 {
139 /* vCont;t */
140 bool t = false;
141
142 /* vCont;r */
143 bool r = false;
144
145 /* vCont;s */
146 bool s = false;
147
148 /* vCont;S */
149 bool S = false;
150 };
151
152 /* About this many threadids fit in a packet. */
153
154 #define MAXTHREADLISTRESULTS 32
155
156 /* Data for the vFile:pread readahead cache. */
157
158 struct readahead_cache
159 {
160 /* Invalidate the readahead cache. */
161 void invalidate ();
162
163 /* Invalidate the readahead cache if it is holding data for FD. */
164 void invalidate_fd (int fd);
165
166 /* Serve pread from the readahead cache. Returns number of bytes
167 read, or 0 if the request can't be served from the cache. */
168 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
169
170 /* The file descriptor for the file that is being cached. -1 if the
171 cache is invalid. */
172 int fd = -1;
173
174 /* The offset into the file that the cache buffer corresponds
175 to. */
176 ULONGEST offset = 0;
177
178 /* The buffer holding the cache contents. */
179 gdb_byte *buf = nullptr;
180 /* The buffer's size. We try to read as much as fits into a packet
181 at a time. */
182 size_t bufsize = 0;
183
184 /* Cache hit and miss counters. */
185 ULONGEST hit_count = 0;
186 ULONGEST miss_count = 0;
187 };
188
189 /* Description of the remote protocol for a given architecture. */
190
191 struct packet_reg
192 {
193 long offset; /* Offset into G packet. */
194 long regnum; /* GDB's internal register number. */
195 LONGEST pnum; /* Remote protocol register number. */
196 int in_g_packet; /* Always part of G packet. */
197 /* long size in bytes; == register_size (target_gdbarch (), regnum);
198 at present. */
199 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
200 at present. */
201 };
202
203 struct remote_arch_state
204 {
205 explicit remote_arch_state (struct gdbarch *gdbarch);
206
207 /* Description of the remote protocol registers. */
208 long sizeof_g_packet;
209
210 /* Description of the remote protocol registers indexed by REGNUM
211 (making an array gdbarch_num_regs in size). */
212 std::unique_ptr<packet_reg[]> regs;
213
214 /* This is the size (in chars) of the first response to the ``g''
215 packet. It is used as a heuristic when determining the maximum
216 size of memory-read and memory-write packets. A target will
217 typically only reserve a buffer large enough to hold the ``g''
218 packet. The size does not include packet overhead (headers and
219 trailers). */
220 long actual_register_packet_size;
221
222 /* This is the maximum size (in chars) of a non read/write packet.
223 It is also used as a cap on the size of read/write packets. */
224 long remote_packet_size;
225 };
226
227 /* Description of the remote protocol state for the currently
228 connected target. This is per-target state, and independent of the
229 selected architecture. */
230
231 class remote_state
232 {
233 public:
234
235 remote_state ();
236 ~remote_state ();
237
238 /* Get the remote arch state for GDBARCH. */
239 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
240
241 public: /* data */
242
243 /* A buffer to use for incoming packets, and its current size. The
244 buffer is grown dynamically for larger incoming packets.
245 Outgoing packets may also be constructed in this buffer.
246 The size of the buffer is always at least REMOTE_PACKET_SIZE;
247 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
248 packets. */
249 gdb::char_vector buf;
250
251 /* True if we're going through initial connection setup (finding out
252 about the remote side's threads, relocating symbols, etc.). */
253 bool starting_up = false;
254
255 /* If we negotiated packet size explicitly (and thus can bypass
256 heuristics for the largest packet size that will not overflow
257 a buffer in the stub), this will be set to that packet size.
258 Otherwise zero, meaning to use the guessed size. */
259 long explicit_packet_size = 0;
260
261 /* True, if in no ack mode. That is, neither GDB nor the stub will
262 expect acks from each other. The connection is assumed to be
263 reliable. */
264 bool noack_mode = false;
265
266 /* True if we're connected in extended remote mode. */
267 bool extended = false;
268
269 /* True if we resumed the target and we're waiting for the target to
270 stop. In the mean time, we can't start another command/query.
271 The remote server wouldn't be ready to process it, so we'd
272 timeout waiting for a reply that would never come and eventually
273 we'd close the connection. This can happen in asynchronous mode
274 because we allow GDB commands while the target is running. */
275 bool waiting_for_stop_reply = false;
276
277 /* The status of the stub support for the various vCont actions. */
278 vCont_action_support supports_vCont;
279 /* Whether vCont support was probed already. This is a workaround
280 until packet_support is per-connection. */
281 bool supports_vCont_probed;
282
283 /* True if the user has pressed Ctrl-C, but the target hasn't
284 responded to that. */
285 bool ctrlc_pending_p = false;
286
287 /* True if we saw a Ctrl-C while reading or writing from/to the
288 remote descriptor. At that point it is not safe to send a remote
289 interrupt packet, so we instead remember we saw the Ctrl-C and
290 process it once we're done with sending/receiving the current
291 packet, which should be shortly. If however that takes too long,
292 and the user presses Ctrl-C again, we offer to disconnect. */
293 bool got_ctrlc_during_io = false;
294
295 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
296 remote_open knows that we don't have a file open when the program
297 starts. */
298 struct serial *remote_desc = nullptr;
299
300 /* These are the threads which we last sent to the remote system. The
301 TID member will be -1 for all or -2 for not sent yet. */
302 ptid_t general_thread = null_ptid;
303 ptid_t continue_thread = null_ptid;
304
305 /* This is the traceframe which we last selected on the remote system.
306 It will be -1 if no traceframe is selected. */
307 int remote_traceframe_number = -1;
308
309 char *last_pass_packet = nullptr;
310
311 /* The last QProgramSignals packet sent to the target. We bypass
312 sending a new program signals list down to the target if the new
313 packet is exactly the same as the last we sent. IOW, we only let
314 the target know about program signals list changes. */
315 char *last_program_signals_packet = nullptr;
316
317 gdb_signal last_sent_signal = GDB_SIGNAL_0;
318
319 bool last_sent_step = false;
320
321 /* The execution direction of the last resume we got. */
322 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
323
324 char *finished_object = nullptr;
325 char *finished_annex = nullptr;
326 ULONGEST finished_offset = 0;
327
328 /* Should we try the 'ThreadInfo' query packet?
329
330 This variable (NOT available to the user: auto-detect only!)
331 determines whether GDB will use the new, simpler "ThreadInfo"
332 query or the older, more complex syntax for thread queries.
333 This is an auto-detect variable (set to true at each connect,
334 and set to false when the target fails to recognize it). */
335 bool use_threadinfo_query = false;
336 bool use_threadextra_query = false;
337
338 threadref echo_nextthread {};
339 threadref nextthread {};
340 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
341
342 /* The state of remote notification. */
343 struct remote_notif_state *notif_state = nullptr;
344
345 /* The branch trace configuration. */
346 struct btrace_config btrace_config {};
347
348 /* The argument to the last "vFile:setfs:" packet we sent, used
349 to avoid sending repeated unnecessary "vFile:setfs:" packets.
350 Initialized to -1 to indicate that no "vFile:setfs:" packet
351 has yet been sent. */
352 int fs_pid = -1;
353
354 /* A readahead cache for vFile:pread. Often, reading a binary
355 involves a sequence of small reads. E.g., when parsing an ELF
356 file. A readahead cache helps mostly the case of remote
357 debugging on a connection with higher latency, due to the
358 request/reply nature of the RSP. We only cache data for a single
359 file descriptor at a time. */
360 struct readahead_cache readahead_cache;
361
362 /* The list of already fetched and acknowledged stop events. This
363 queue is used for notification Stop, and other notifications
364 don't need queue for their events, because the notification
365 events of Stop can't be consumed immediately, so that events
366 should be queued first, and be consumed by remote_wait_{ns,as}
367 one per time. Other notifications can consume their events
368 immediately, so queue is not needed for them. */
369 std::vector<stop_reply_up> stop_reply_queue;
370
371 /* Asynchronous signal handle registered as event loop source for
372 when we have pending events ready to be passed to the core. */
373 struct async_event_handler *remote_async_inferior_event_token = nullptr;
374
375 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
376 ``forever'' still use the normal timeout mechanism. This is
377 currently used by the ASYNC code to guarentee that target reads
378 during the initial connect always time-out. Once getpkt has been
379 modified to return a timeout indication and, in turn
380 remote_wait()/wait_for_inferior() have gained a timeout parameter
381 this can go away. */
382 int wait_forever_enabled_p = 1;
383
384 private:
385 /* Mapping of remote protocol data for each gdbarch. Usually there
386 is only one entry here, though we may see more with stubs that
387 support multi-process. */
388 std::unordered_map<struct gdbarch *, remote_arch_state>
389 m_arch_states;
390 };
391
392 static const target_info remote_target_info = {
393 "remote",
394 N_("Remote target using gdb-specific protocol"),
395 remote_doc
396 };
397
398 class remote_target : public process_stratum_target
399 {
400 public:
401 remote_target () = default;
402 ~remote_target () override;
403
404 const target_info &info () const override
405 { return remote_target_info; }
406
407 const char *connection_string () override;
408
409 thread_control_capabilities get_thread_control_capabilities () override
410 { return tc_schedlock; }
411
412 /* Open a remote connection. */
413 static void open (const char *, int);
414
415 void close () override;
416
417 void detach (inferior *, int) override;
418 void disconnect (const char *, int) override;
419
420 void commit_resumed () override;
421 void resume (ptid_t, int, enum gdb_signal) override;
422 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
423 bool has_pending_events () override;
424
425 void fetch_registers (struct regcache *, int) override;
426 void store_registers (struct regcache *, int) override;
427 void prepare_to_store (struct regcache *) override;
428
429 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
430
431 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
432 enum remove_bp_reason) override;
433
434
435 bool stopped_by_sw_breakpoint () override;
436 bool supports_stopped_by_sw_breakpoint () override;
437
438 bool stopped_by_hw_breakpoint () override;
439
440 bool supports_stopped_by_hw_breakpoint () override;
441
442 bool stopped_by_watchpoint () override;
443
444 bool stopped_data_address (CORE_ADDR *) override;
445
446 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
447
448 int can_use_hw_breakpoint (enum bptype, int, int) override;
449
450 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
451
452 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
453
454 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
455
456 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
457 struct expression *) override;
458
459 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
460 struct expression *) override;
461
462 void kill () override;
463
464 void load (const char *, int) override;
465
466 void mourn_inferior () override;
467
468 void pass_signals (gdb::array_view<const unsigned char>) override;
469
470 int set_syscall_catchpoint (int, bool, int,
471 gdb::array_view<const int>) override;
472
473 void program_signals (gdb::array_view<const unsigned char>) override;
474
475 bool thread_alive (ptid_t ptid) override;
476
477 const char *thread_name (struct thread_info *) override;
478
479 void update_thread_list () override;
480
481 std::string pid_to_str (ptid_t) override;
482
483 const char *extra_thread_info (struct thread_info *) override;
484
485 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
486
487 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
488 int handle_len,
489 inferior *inf) override;
490
491 gdb::byte_vector thread_info_to_thread_handle (struct thread_info *tp)
492 override;
493
494 void stop (ptid_t) override;
495
496 void interrupt () override;
497
498 void pass_ctrlc () override;
499
500 enum target_xfer_status xfer_partial (enum target_object object,
501 const char *annex,
502 gdb_byte *readbuf,
503 const gdb_byte *writebuf,
504 ULONGEST offset, ULONGEST len,
505 ULONGEST *xfered_len) override;
506
507 ULONGEST get_memory_xfer_limit () override;
508
509 void rcmd (const char *command, struct ui_file *output) override;
510
511 char *pid_to_exec_file (int pid) override;
512
513 void log_command (const char *cmd) override
514 {
515 serial_log_command (this, cmd);
516 }
517
518 CORE_ADDR get_thread_local_address (ptid_t ptid,
519 CORE_ADDR load_module_addr,
520 CORE_ADDR offset) override;
521
522 bool can_execute_reverse () override;
523
524 std::vector<mem_region> memory_map () override;
525
526 void flash_erase (ULONGEST address, LONGEST length) override;
527
528 void flash_done () override;
529
530 const struct target_desc *read_description () override;
531
532 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
533 const gdb_byte *pattern, ULONGEST pattern_len,
534 CORE_ADDR *found_addrp) override;
535
536 bool can_async_p () override;
537
538 bool is_async_p () override;
539
540 void async (int) override;
541
542 int async_wait_fd () override;
543
544 void thread_events (int) override;
545
546 int can_do_single_step () override;
547
548 void terminal_inferior () override;
549
550 void terminal_ours () override;
551
552 bool supports_non_stop () override;
553
554 bool supports_multi_process () override;
555
556 bool supports_disable_randomization () override;
557
558 bool filesystem_is_local () override;
559
560
561 int fileio_open (struct inferior *inf, const char *filename,
562 int flags, int mode, int warn_if_slow,
563 int *target_errno) override;
564
565 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
566 ULONGEST offset, int *target_errno) override;
567
568 int fileio_pread (int fd, gdb_byte *read_buf, int len,
569 ULONGEST offset, int *target_errno) override;
570
571 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
572
573 int fileio_close (int fd, int *target_errno) override;
574
575 int fileio_unlink (struct inferior *inf,
576 const char *filename,
577 int *target_errno) override;
578
579 gdb::optional<std::string>
580 fileio_readlink (struct inferior *inf,
581 const char *filename,
582 int *target_errno) override;
583
584 bool supports_enable_disable_tracepoint () override;
585
586 bool supports_string_tracing () override;
587
588 bool supports_evaluation_of_breakpoint_conditions () override;
589
590 bool can_run_breakpoint_commands () override;
591
592 void trace_init () override;
593
594 void download_tracepoint (struct bp_location *location) override;
595
596 bool can_download_tracepoint () override;
597
598 void download_trace_state_variable (const trace_state_variable &tsv) override;
599
600 void enable_tracepoint (struct bp_location *location) override;
601
602 void disable_tracepoint (struct bp_location *location) override;
603
604 void trace_set_readonly_regions () override;
605
606 void trace_start () override;
607
608 int get_trace_status (struct trace_status *ts) override;
609
610 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
611 override;
612
613 void trace_stop () override;
614
615 int trace_find (enum trace_find_type type, int num,
616 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
617
618 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
619
620 int save_trace_data (const char *filename) override;
621
622 int upload_tracepoints (struct uploaded_tp **utpp) override;
623
624 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
625
626 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
627
628 int get_min_fast_tracepoint_insn_len () override;
629
630 void set_disconnected_tracing (int val) override;
631
632 void set_circular_trace_buffer (int val) override;
633
634 void set_trace_buffer_size (LONGEST val) override;
635
636 bool set_trace_notes (const char *user, const char *notes,
637 const char *stopnotes) override;
638
639 int core_of_thread (ptid_t ptid) override;
640
641 int verify_memory (const gdb_byte *data,
642 CORE_ADDR memaddr, ULONGEST size) override;
643
644
645 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
646
647 void set_permissions () override;
648
649 bool static_tracepoint_marker_at (CORE_ADDR,
650 struct static_tracepoint_marker *marker)
651 override;
652
653 std::vector<static_tracepoint_marker>
654 static_tracepoint_markers_by_strid (const char *id) override;
655
656 traceframe_info_up traceframe_info () override;
657
658 bool use_agent (bool use) override;
659 bool can_use_agent () override;
660
661 struct btrace_target_info *
662 enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
663
664 void disable_btrace (struct btrace_target_info *tinfo) override;
665
666 void teardown_btrace (struct btrace_target_info *tinfo) override;
667
668 enum btrace_error read_btrace (struct btrace_data *data,
669 struct btrace_target_info *btinfo,
670 enum btrace_read_type type) override;
671
672 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
673 bool augmented_libraries_svr4_read () override;
674 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
675 void follow_exec (inferior *, ptid_t, const char *) override;
676 int insert_fork_catchpoint (int) override;
677 int remove_fork_catchpoint (int) override;
678 int insert_vfork_catchpoint (int) override;
679 int remove_vfork_catchpoint (int) override;
680 int insert_exec_catchpoint (int) override;
681 int remove_exec_catchpoint (int) override;
682 enum exec_direction_kind execution_direction () override;
683
684 bool supports_memory_tagging () override;
685
686 bool fetch_memtags (CORE_ADDR address, size_t len,
687 gdb::byte_vector &tags, int type) override;
688
689 bool store_memtags (CORE_ADDR address, size_t len,
690 const gdb::byte_vector &tags, int type) override;
691
692 public: /* Remote specific methods. */
693
694 void remote_download_command_source (int num, ULONGEST addr,
695 struct command_line *cmds);
696
697 void remote_file_put (const char *local_file, const char *remote_file,
698 int from_tty);
699 void remote_file_get (const char *remote_file, const char *local_file,
700 int from_tty);
701 void remote_file_delete (const char *remote_file, int from_tty);
702
703 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
704 ULONGEST offset, int *remote_errno);
705 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
706 ULONGEST offset, int *remote_errno);
707 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
708 ULONGEST offset, int *remote_errno);
709
710 int remote_hostio_send_command (int command_bytes, int which_packet,
711 int *remote_errno, const char **attachment,
712 int *attachment_len);
713 int remote_hostio_set_filesystem (struct inferior *inf,
714 int *remote_errno);
715 /* We should get rid of this and use fileio_open directly. */
716 int remote_hostio_open (struct inferior *inf, const char *filename,
717 int flags, int mode, int warn_if_slow,
718 int *remote_errno);
719 int remote_hostio_close (int fd, int *remote_errno);
720
721 int remote_hostio_unlink (inferior *inf, const char *filename,
722 int *remote_errno);
723
724 struct remote_state *get_remote_state ();
725
726 long get_remote_packet_size (void);
727 long get_memory_packet_size (struct memory_packet_config *config);
728
729 long get_memory_write_packet_size ();
730 long get_memory_read_packet_size ();
731
732 char *append_pending_thread_resumptions (char *p, char *endp,
733 ptid_t ptid);
734 static void open_1 (const char *name, int from_tty, int extended_p);
735 void start_remote (int from_tty, int extended_p);
736 void remote_detach_1 (struct inferior *inf, int from_tty);
737
738 char *append_resumption (char *p, char *endp,
739 ptid_t ptid, int step, gdb_signal siggnal);
740 int remote_resume_with_vcont (ptid_t 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 struct 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 (__FILE__, __LINE__,
1597 _("Invalid value for interrupt_sequence_mode: %s."),
1598 interrupt_sequence_mode);
1599 }
1600
1601 /* This boolean variable specifies whether interrupt_sequence is sent
1602 to the remote target when gdb connects to it.
1603 This is mostly needed when you debug the Linux kernel: The Linux kernel
1604 expects BREAK g which is Magic SysRq g for connecting gdb. */
1605 static bool interrupt_on_connect = false;
1606
1607 /* This variable is used to implement the "set/show remotebreak" commands.
1608 Since these commands are now deprecated in favor of "set/show remote
1609 interrupt-sequence", it no longer has any effect on the code. */
1610 static bool remote_break;
1611
1612 static void
1613 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1614 {
1615 if (remote_break)
1616 interrupt_sequence_mode = interrupt_sequence_break;
1617 else
1618 interrupt_sequence_mode = interrupt_sequence_control_c;
1619 }
1620
1621 static void
1622 show_remotebreak (struct ui_file *file, int from_tty,
1623 struct cmd_list_element *c,
1624 const char *value)
1625 {
1626 }
1627
1628 /* This variable sets the number of bits in an address that are to be
1629 sent in a memory ("M" or "m") packet. Normally, after stripping
1630 leading zeros, the entire address would be sent. This variable
1631 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1632 initial implementation of remote.c restricted the address sent in
1633 memory packets to ``host::sizeof long'' bytes - (typically 32
1634 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1635 address was never sent. Since fixing this bug may cause a break in
1636 some remote targets this variable is principally provided to
1637 facilitate backward compatibility. */
1638
1639 static unsigned int remote_address_size;
1640
1641 \f
1642 /* User configurable variables for the number of characters in a
1643 memory read/write packet. MIN (rsa->remote_packet_size,
1644 rsa->sizeof_g_packet) is the default. Some targets need smaller
1645 values (fifo overruns, et.al.) and some users need larger values
1646 (speed up transfers). The variables ``preferred_*'' (the user
1647 request), ``current_*'' (what was actually set) and ``forced_*''
1648 (Positive - a soft limit, negative - a hard limit). */
1649
1650 struct memory_packet_config
1651 {
1652 const char *name;
1653 long size;
1654 int fixed_p;
1655 };
1656
1657 /* The default max memory-write-packet-size, when the setting is
1658 "fixed". The 16k is historical. (It came from older GDB's using
1659 alloca for buffers and the knowledge (folklore?) that some hosts
1660 don't cope very well with large alloca calls.) */
1661 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1662
1663 /* The minimum remote packet size for memory transfers. Ensures we
1664 can write at least one byte. */
1665 #define MIN_MEMORY_PACKET_SIZE 20
1666
1667 /* Get the memory packet size, assuming it is fixed. */
1668
1669 static long
1670 get_fixed_memory_packet_size (struct memory_packet_config *config)
1671 {
1672 gdb_assert (config->fixed_p);
1673
1674 if (config->size <= 0)
1675 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1676 else
1677 return config->size;
1678 }
1679
1680 /* Compute the current size of a read/write packet. Since this makes
1681 use of ``actual_register_packet_size'' the computation is dynamic. */
1682
1683 long
1684 remote_target::get_memory_packet_size (struct memory_packet_config *config)
1685 {
1686 struct remote_state *rs = get_remote_state ();
1687 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1688
1689 long what_they_get;
1690 if (config->fixed_p)
1691 what_they_get = get_fixed_memory_packet_size (config);
1692 else
1693 {
1694 what_they_get = get_remote_packet_size ();
1695 /* Limit the packet to the size specified by the user. */
1696 if (config->size > 0
1697 && what_they_get > config->size)
1698 what_they_get = config->size;
1699
1700 /* Limit it to the size of the targets ``g'' response unless we have
1701 permission from the stub to use a larger packet size. */
1702 if (rs->explicit_packet_size == 0
1703 && rsa->actual_register_packet_size > 0
1704 && what_they_get > rsa->actual_register_packet_size)
1705 what_they_get = rsa->actual_register_packet_size;
1706 }
1707 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1708 what_they_get = MIN_MEMORY_PACKET_SIZE;
1709
1710 /* Make sure there is room in the global buffer for this packet
1711 (including its trailing NUL byte). */
1712 if (rs->buf.size () < what_they_get + 1)
1713 rs->buf.resize (2 * what_they_get);
1714
1715 return what_they_get;
1716 }
1717
1718 /* Update the size of a read/write packet. If they user wants
1719 something really big then do a sanity check. */
1720
1721 static void
1722 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1723 {
1724 int fixed_p = config->fixed_p;
1725 long size = config->size;
1726
1727 if (args == NULL)
1728 error (_("Argument required (integer, `fixed' or `limited')."));
1729 else if (strcmp (args, "hard") == 0
1730 || strcmp (args, "fixed") == 0)
1731 fixed_p = 1;
1732 else if (strcmp (args, "soft") == 0
1733 || strcmp (args, "limit") == 0)
1734 fixed_p = 0;
1735 else
1736 {
1737 char *end;
1738
1739 size = strtoul (args, &end, 0);
1740 if (args == end)
1741 error (_("Invalid %s (bad syntax)."), config->name);
1742
1743 /* Instead of explicitly capping the size of a packet to or
1744 disallowing it, the user is allowed to set the size to
1745 something arbitrarily large. */
1746 }
1747
1748 /* Extra checks? */
1749 if (fixed_p && !config->fixed_p)
1750 {
1751 /* So that the query shows the correct value. */
1752 long query_size = (size <= 0
1753 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1754 : size);
1755
1756 if (! query (_("The target may not be able to correctly handle a %s\n"
1757 "of %ld bytes. Change the packet size? "),
1758 config->name, query_size))
1759 error (_("Packet size not changed."));
1760 }
1761 /* Update the config. */
1762 config->fixed_p = fixed_p;
1763 config->size = size;
1764 }
1765
1766 static void
1767 show_memory_packet_size (struct memory_packet_config *config)
1768 {
1769 if (config->size == 0)
1770 gdb_printf (_("The %s is 0 (default). "), config->name);
1771 else
1772 gdb_printf (_("The %s is %ld. "), config->name, config->size);
1773 if (config->fixed_p)
1774 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
1775 get_fixed_memory_packet_size (config));
1776 else
1777 {
1778 remote_target *remote = get_current_remote_target ();
1779
1780 if (remote != NULL)
1781 gdb_printf (_("Packets are limited to %ld bytes.\n"),
1782 remote->get_memory_packet_size (config));
1783 else
1784 gdb_puts ("The actual limit will be further reduced "
1785 "dependent on the target.\n");
1786 }
1787 }
1788
1789 /* FIXME: needs to be per-remote-target. */
1790 static struct memory_packet_config memory_write_packet_config =
1791 {
1792 "memory-write-packet-size",
1793 };
1794
1795 static void
1796 set_memory_write_packet_size (const char *args, int from_tty)
1797 {
1798 set_memory_packet_size (args, &memory_write_packet_config);
1799 }
1800
1801 static void
1802 show_memory_write_packet_size (const char *args, int from_tty)
1803 {
1804 show_memory_packet_size (&memory_write_packet_config);
1805 }
1806
1807 /* Show the number of hardware watchpoints that can be used. */
1808
1809 static void
1810 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
1811 struct cmd_list_element *c,
1812 const char *value)
1813 {
1814 gdb_printf (file, _("The maximum number of target hardware "
1815 "watchpoints is %s.\n"), value);
1816 }
1817
1818 /* Show the length limit (in bytes) for hardware watchpoints. */
1819
1820 static void
1821 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
1822 struct cmd_list_element *c,
1823 const char *value)
1824 {
1825 gdb_printf (file, _("The maximum length (in bytes) of a target "
1826 "hardware watchpoint is %s.\n"), value);
1827 }
1828
1829 /* Show the number of hardware breakpoints that can be used. */
1830
1831 static void
1832 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
1833 struct cmd_list_element *c,
1834 const char *value)
1835 {
1836 gdb_printf (file, _("The maximum number of target hardware "
1837 "breakpoints is %s.\n"), value);
1838 }
1839
1840 /* Controls the maximum number of characters to display in the debug output
1841 for each remote packet. The remaining characters are omitted. */
1842
1843 static int remote_packet_max_chars = 512;
1844
1845 /* Show the maximum number of characters to display for each remote packet
1846 when remote debugging is enabled. */
1847
1848 static void
1849 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
1850 struct cmd_list_element *c,
1851 const char *value)
1852 {
1853 gdb_printf (file, _("Number of remote packet characters to "
1854 "display is %s.\n"), value);
1855 }
1856
1857 long
1858 remote_target::get_memory_write_packet_size ()
1859 {
1860 return get_memory_packet_size (&memory_write_packet_config);
1861 }
1862
1863 /* FIXME: needs to be per-remote-target. */
1864 static struct memory_packet_config memory_read_packet_config =
1865 {
1866 "memory-read-packet-size",
1867 };
1868
1869 static void
1870 set_memory_read_packet_size (const char *args, int from_tty)
1871 {
1872 set_memory_packet_size (args, &memory_read_packet_config);
1873 }
1874
1875 static void
1876 show_memory_read_packet_size (const char *args, int from_tty)
1877 {
1878 show_memory_packet_size (&memory_read_packet_config);
1879 }
1880
1881 long
1882 remote_target::get_memory_read_packet_size ()
1883 {
1884 long size = get_memory_packet_size (&memory_read_packet_config);
1885
1886 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1887 extra buffer size argument before the memory read size can be
1888 increased beyond this. */
1889 if (size > get_remote_packet_size ())
1890 size = get_remote_packet_size ();
1891 return size;
1892 }
1893
1894 \f
1895
1896 struct packet_config
1897 {
1898 const char *name;
1899 const char *title;
1900
1901 /* If auto, GDB auto-detects support for this packet or feature,
1902 either through qSupported, or by trying the packet and looking
1903 at the response. If true, GDB assumes the target supports this
1904 packet. If false, the packet is disabled. Configs that don't
1905 have an associated command always have this set to auto. */
1906 enum auto_boolean detect;
1907
1908 /* The "show remote foo-packet" command created for this packet. */
1909 cmd_list_element *show_cmd;
1910
1911 /* Does the target support this packet? */
1912 enum packet_support support;
1913 };
1914
1915 static enum packet_support packet_config_support (struct packet_config *config);
1916 static enum packet_support packet_support (int packet);
1917
1918 static void
1919 show_packet_config_cmd (ui_file *file, struct packet_config *config)
1920 {
1921 const char *support = "internal-error";
1922
1923 switch (packet_config_support (config))
1924 {
1925 case PACKET_ENABLE:
1926 support = "enabled";
1927 break;
1928 case PACKET_DISABLE:
1929 support = "disabled";
1930 break;
1931 case PACKET_SUPPORT_UNKNOWN:
1932 support = "unknown";
1933 break;
1934 }
1935 switch (config->detect)
1936 {
1937 case AUTO_BOOLEAN_AUTO:
1938 gdb_printf (file,
1939 _("Support for the `%s' packet "
1940 "is auto-detected, currently %s.\n"),
1941 config->name, support);
1942 break;
1943 case AUTO_BOOLEAN_TRUE:
1944 case AUTO_BOOLEAN_FALSE:
1945 gdb_printf (file,
1946 _("Support for the `%s' packet is currently %s.\n"),
1947 config->name, support);
1948 break;
1949 }
1950 }
1951
1952 static void
1953 add_packet_config_cmd (struct packet_config *config, const char *name,
1954 const char *title, int legacy)
1955 {
1956 config->name = name;
1957 config->title = title;
1958 gdb::unique_xmalloc_ptr<char> set_doc
1959 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
1960 name, title);
1961 gdb::unique_xmalloc_ptr<char> show_doc
1962 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
1963 name, title);
1964 /* set/show TITLE-packet {auto,on,off} */
1965 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
1966 set_show_commands cmds
1967 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
1968 &config->detect, set_doc.get (),
1969 show_doc.get (), NULL, /* help_doc */
1970 NULL,
1971 show_remote_protocol_packet_cmd,
1972 &remote_set_cmdlist, &remote_show_cmdlist);
1973 config->show_cmd = cmds.show;
1974
1975 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1976 if (legacy)
1977 {
1978 /* It's not clear who should take ownership of the LEGACY_NAME string
1979 created below, so, for now, place the string into a static vector
1980 which ensures the strings is released when GDB exits. */
1981 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
1982 gdb::unique_xmalloc_ptr<char> legacy_name
1983 = xstrprintf ("%s-packet", name);
1984 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
1985 &remote_set_cmdlist);
1986 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
1987 &remote_show_cmdlist);
1988 legacy_names.emplace_back (std::move (legacy_name));
1989 }
1990 }
1991
1992 static enum packet_result
1993 packet_check_result (const char *buf)
1994 {
1995 if (buf[0] != '\0')
1996 {
1997 /* The stub recognized the packet request. Check that the
1998 operation succeeded. */
1999 if (buf[0] == 'E'
2000 && isxdigit (buf[1]) && isxdigit (buf[2])
2001 && buf[3] == '\0')
2002 /* "Enn" - definitely an error. */
2003 return PACKET_ERROR;
2004
2005 /* Always treat "E." as an error. This will be used for
2006 more verbose error messages, such as E.memtypes. */
2007 if (buf[0] == 'E' && buf[1] == '.')
2008 return PACKET_ERROR;
2009
2010 /* The packet may or may not be OK. Just assume it is. */
2011 return PACKET_OK;
2012 }
2013 else
2014 /* The stub does not support the packet. */
2015 return PACKET_UNKNOWN;
2016 }
2017
2018 static enum packet_result
2019 packet_check_result (const gdb::char_vector &buf)
2020 {
2021 return packet_check_result (buf.data ());
2022 }
2023
2024 static enum packet_result
2025 packet_ok (const char *buf, struct packet_config *config)
2026 {
2027 enum packet_result result;
2028
2029 if (config->detect != AUTO_BOOLEAN_TRUE
2030 && config->support == PACKET_DISABLE)
2031 internal_error (__FILE__, __LINE__,
2032 _("packet_ok: attempt to use a disabled packet"));
2033
2034 result = packet_check_result (buf);
2035 switch (result)
2036 {
2037 case PACKET_OK:
2038 case PACKET_ERROR:
2039 /* The stub recognized the packet request. */
2040 if (config->support == PACKET_SUPPORT_UNKNOWN)
2041 {
2042 remote_debug_printf ("Packet %s (%s) is supported",
2043 config->name, config->title);
2044 config->support = PACKET_ENABLE;
2045 }
2046 break;
2047 case PACKET_UNKNOWN:
2048 /* The stub does not support the packet. */
2049 if (config->detect == AUTO_BOOLEAN_AUTO
2050 && config->support == PACKET_ENABLE)
2051 {
2052 /* If the stub previously indicated that the packet was
2053 supported then there is a protocol error. */
2054 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2055 config->name, config->title);
2056 }
2057 else if (config->detect == AUTO_BOOLEAN_TRUE)
2058 {
2059 /* The user set it wrong. */
2060 error (_("Enabled packet %s (%s) not recognized by stub"),
2061 config->name, config->title);
2062 }
2063
2064 remote_debug_printf ("Packet %s (%s) is NOT supported",
2065 config->name, config->title);
2066 config->support = PACKET_DISABLE;
2067 break;
2068 }
2069
2070 return result;
2071 }
2072
2073 static enum packet_result
2074 packet_ok (const gdb::char_vector &buf, struct packet_config *config)
2075 {
2076 return packet_ok (buf.data (), config);
2077 }
2078
2079 enum {
2080 PACKET_vCont = 0,
2081 PACKET_X,
2082 PACKET_qSymbol,
2083 PACKET_P,
2084 PACKET_p,
2085 PACKET_Z0,
2086 PACKET_Z1,
2087 PACKET_Z2,
2088 PACKET_Z3,
2089 PACKET_Z4,
2090 PACKET_vFile_setfs,
2091 PACKET_vFile_open,
2092 PACKET_vFile_pread,
2093 PACKET_vFile_pwrite,
2094 PACKET_vFile_close,
2095 PACKET_vFile_unlink,
2096 PACKET_vFile_readlink,
2097 PACKET_vFile_fstat,
2098 PACKET_qXfer_auxv,
2099 PACKET_qXfer_features,
2100 PACKET_qXfer_exec_file,
2101 PACKET_qXfer_libraries,
2102 PACKET_qXfer_libraries_svr4,
2103 PACKET_qXfer_memory_map,
2104 PACKET_qXfer_osdata,
2105 PACKET_qXfer_threads,
2106 PACKET_qXfer_statictrace_read,
2107 PACKET_qXfer_traceframe_info,
2108 PACKET_qXfer_uib,
2109 PACKET_qGetTIBAddr,
2110 PACKET_qGetTLSAddr,
2111 PACKET_qSupported,
2112 PACKET_qTStatus,
2113 PACKET_QPassSignals,
2114 PACKET_QCatchSyscalls,
2115 PACKET_QProgramSignals,
2116 PACKET_QSetWorkingDir,
2117 PACKET_QStartupWithShell,
2118 PACKET_QEnvironmentHexEncoded,
2119 PACKET_QEnvironmentReset,
2120 PACKET_QEnvironmentUnset,
2121 PACKET_qCRC,
2122 PACKET_qSearch_memory,
2123 PACKET_vAttach,
2124 PACKET_vRun,
2125 PACKET_QStartNoAckMode,
2126 PACKET_vKill,
2127 PACKET_qXfer_siginfo_read,
2128 PACKET_qXfer_siginfo_write,
2129 PACKET_qAttached,
2130
2131 /* Support for conditional tracepoints. */
2132 PACKET_ConditionalTracepoints,
2133
2134 /* Support for target-side breakpoint conditions. */
2135 PACKET_ConditionalBreakpoints,
2136
2137 /* Support for target-side breakpoint commands. */
2138 PACKET_BreakpointCommands,
2139
2140 /* Support for fast tracepoints. */
2141 PACKET_FastTracepoints,
2142
2143 /* Support for static tracepoints. */
2144 PACKET_StaticTracepoints,
2145
2146 /* Support for installing tracepoints while a trace experiment is
2147 running. */
2148 PACKET_InstallInTrace,
2149
2150 PACKET_bc,
2151 PACKET_bs,
2152 PACKET_TracepointSource,
2153 PACKET_QAllow,
2154 PACKET_qXfer_fdpic,
2155 PACKET_QDisableRandomization,
2156 PACKET_QAgent,
2157 PACKET_QTBuffer_size,
2158 PACKET_Qbtrace_off,
2159 PACKET_Qbtrace_bts,
2160 PACKET_Qbtrace_pt,
2161 PACKET_qXfer_btrace,
2162
2163 /* Support for the QNonStop packet. */
2164 PACKET_QNonStop,
2165
2166 /* Support for the QThreadEvents packet. */
2167 PACKET_QThreadEvents,
2168
2169 /* Support for multi-process extensions. */
2170 PACKET_multiprocess_feature,
2171
2172 /* Support for enabling and disabling tracepoints while a trace
2173 experiment is running. */
2174 PACKET_EnableDisableTracepoints_feature,
2175
2176 /* Support for collecting strings using the tracenz bytecode. */
2177 PACKET_tracenz_feature,
2178
2179 /* Support for continuing to run a trace experiment while GDB is
2180 disconnected. */
2181 PACKET_DisconnectedTracing_feature,
2182
2183 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2184 PACKET_augmented_libraries_svr4_read_feature,
2185
2186 /* Support for the qXfer:btrace-conf:read packet. */
2187 PACKET_qXfer_btrace_conf,
2188
2189 /* Support for the Qbtrace-conf:bts:size packet. */
2190 PACKET_Qbtrace_conf_bts_size,
2191
2192 /* Support for swbreak+ feature. */
2193 PACKET_swbreak_feature,
2194
2195 /* Support for hwbreak+ feature. */
2196 PACKET_hwbreak_feature,
2197
2198 /* Support for fork events. */
2199 PACKET_fork_event_feature,
2200
2201 /* Support for vfork events. */
2202 PACKET_vfork_event_feature,
2203
2204 /* Support for the Qbtrace-conf:pt:size packet. */
2205 PACKET_Qbtrace_conf_pt_size,
2206
2207 /* Support for exec events. */
2208 PACKET_exec_event_feature,
2209
2210 /* Support for query supported vCont actions. */
2211 PACKET_vContSupported,
2212
2213 /* Support remote CTRL-C. */
2214 PACKET_vCtrlC,
2215
2216 /* Support TARGET_WAITKIND_NO_RESUMED. */
2217 PACKET_no_resumed,
2218
2219 /* Support for memory tagging, allocation tag fetch/store
2220 packets and the tag violation stop replies. */
2221 PACKET_memory_tagging_feature,
2222
2223 PACKET_MAX
2224 };
2225
2226 /* FIXME: needs to be per-remote-target. Ignoring this for now,
2227 assuming all remote targets are the same server (thus all support
2228 the same packets). */
2229 static struct packet_config remote_protocol_packets[PACKET_MAX];
2230
2231 /* Returns the packet's corresponding "set remote foo-packet" command
2232 state. See struct packet_config for more details. */
2233
2234 static enum auto_boolean
2235 packet_set_cmd_state (int packet)
2236 {
2237 return remote_protocol_packets[packet].detect;
2238 }
2239
2240 /* Returns whether a given packet or feature is supported. This takes
2241 into account the state of the corresponding "set remote foo-packet"
2242 command, which may be used to bypass auto-detection. */
2243
2244 static enum packet_support
2245 packet_config_support (struct packet_config *config)
2246 {
2247 switch (config->detect)
2248 {
2249 case AUTO_BOOLEAN_TRUE:
2250 return PACKET_ENABLE;
2251 case AUTO_BOOLEAN_FALSE:
2252 return PACKET_DISABLE;
2253 case AUTO_BOOLEAN_AUTO:
2254 return config->support;
2255 default:
2256 gdb_assert_not_reached ("bad switch");
2257 }
2258 }
2259
2260 /* Same as packet_config_support, but takes the packet's enum value as
2261 argument. */
2262
2263 static enum packet_support
2264 packet_support (int packet)
2265 {
2266 struct packet_config *config = &remote_protocol_packets[packet];
2267
2268 return packet_config_support (config);
2269 }
2270
2271 static void
2272 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2273 struct cmd_list_element *c,
2274 const char *value)
2275 {
2276 struct packet_config *packet;
2277 gdb_assert (c->var.has_value ());
2278
2279 for (packet = remote_protocol_packets;
2280 packet < &remote_protocol_packets[PACKET_MAX];
2281 packet++)
2282 {
2283 if (c == packet->show_cmd)
2284 {
2285 show_packet_config_cmd (file, packet);
2286 return;
2287 }
2288 }
2289 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
2290 c->name);
2291 }
2292
2293 /* Should we try one of the 'Z' requests? */
2294
2295 enum Z_packet_type
2296 {
2297 Z_PACKET_SOFTWARE_BP,
2298 Z_PACKET_HARDWARE_BP,
2299 Z_PACKET_WRITE_WP,
2300 Z_PACKET_READ_WP,
2301 Z_PACKET_ACCESS_WP,
2302 NR_Z_PACKET_TYPES
2303 };
2304
2305 /* For compatibility with older distributions. Provide a ``set remote
2306 Z-packet ...'' command that updates all the Z packet types. */
2307
2308 static enum auto_boolean remote_Z_packet_detect;
2309
2310 static void
2311 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2312 struct cmd_list_element *c)
2313 {
2314 int i;
2315
2316 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2317 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2318 }
2319
2320 static void
2321 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2322 struct cmd_list_element *c,
2323 const char *value)
2324 {
2325 int i;
2326
2327 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2328 {
2329 show_packet_config_cmd (file, &remote_protocol_packets[PACKET_Z0 + i]);
2330 }
2331 }
2332
2333 /* Returns true if the multi-process extensions are in effect. */
2334
2335 static int
2336 remote_multi_process_p (struct remote_state *rs)
2337 {
2338 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2339 }
2340
2341 /* Returns true if fork events are supported. */
2342
2343 static int
2344 remote_fork_event_p (struct remote_state *rs)
2345 {
2346 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2347 }
2348
2349 /* Returns true if vfork events are supported. */
2350
2351 static int
2352 remote_vfork_event_p (struct remote_state *rs)
2353 {
2354 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2355 }
2356
2357 /* Returns true if exec events are supported. */
2358
2359 static int
2360 remote_exec_event_p (struct remote_state *rs)
2361 {
2362 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2363 }
2364
2365 /* Returns true if memory tagging is supported, false otherwise. */
2366
2367 static bool
2368 remote_memory_tagging_p ()
2369 {
2370 return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE;
2371 }
2372
2373 /* Insert fork catchpoint target routine. If fork events are enabled
2374 then return success, nothing more to do. */
2375
2376 int
2377 remote_target::insert_fork_catchpoint (int pid)
2378 {
2379 struct remote_state *rs = get_remote_state ();
2380
2381 return !remote_fork_event_p (rs);
2382 }
2383
2384 /* Remove fork catchpoint target routine. Nothing to do, just
2385 return success. */
2386
2387 int
2388 remote_target::remove_fork_catchpoint (int pid)
2389 {
2390 return 0;
2391 }
2392
2393 /* Insert vfork catchpoint target routine. If vfork events are enabled
2394 then return success, nothing more to do. */
2395
2396 int
2397 remote_target::insert_vfork_catchpoint (int pid)
2398 {
2399 struct remote_state *rs = get_remote_state ();
2400
2401 return !remote_vfork_event_p (rs);
2402 }
2403
2404 /* Remove vfork catchpoint target routine. Nothing to do, just
2405 return success. */
2406
2407 int
2408 remote_target::remove_vfork_catchpoint (int pid)
2409 {
2410 return 0;
2411 }
2412
2413 /* Insert exec catchpoint target routine. If exec events are
2414 enabled, just return success. */
2415
2416 int
2417 remote_target::insert_exec_catchpoint (int pid)
2418 {
2419 struct remote_state *rs = get_remote_state ();
2420
2421 return !remote_exec_event_p (rs);
2422 }
2423
2424 /* Remove exec catchpoint target routine. Nothing to do, just
2425 return success. */
2426
2427 int
2428 remote_target::remove_exec_catchpoint (int pid)
2429 {
2430 return 0;
2431 }
2432
2433 \f
2434
2435 /* Take advantage of the fact that the TID field is not used, to tag
2436 special ptids with it set to != 0. */
2437 static const ptid_t magic_null_ptid (42000, -1, 1);
2438 static const ptid_t not_sent_ptid (42000, -2, 1);
2439 static const ptid_t any_thread_ptid (42000, 0, 1);
2440
2441 /* Find out if the stub attached to PID (and hence GDB should offer to
2442 detach instead of killing it when bailing out). */
2443
2444 int
2445 remote_target::remote_query_attached (int pid)
2446 {
2447 struct remote_state *rs = get_remote_state ();
2448 size_t size = get_remote_packet_size ();
2449
2450 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2451 return 0;
2452
2453 if (remote_multi_process_p (rs))
2454 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2455 else
2456 xsnprintf (rs->buf.data (), size, "qAttached");
2457
2458 putpkt (rs->buf);
2459 getpkt (&rs->buf, 0);
2460
2461 switch (packet_ok (rs->buf,
2462 &remote_protocol_packets[PACKET_qAttached]))
2463 {
2464 case PACKET_OK:
2465 if (strcmp (rs->buf.data (), "1") == 0)
2466 return 1;
2467 break;
2468 case PACKET_ERROR:
2469 warning (_("Remote failure reply: %s"), rs->buf.data ());
2470 break;
2471 case PACKET_UNKNOWN:
2472 break;
2473 }
2474
2475 return 0;
2476 }
2477
2478 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2479 has been invented by GDB, instead of reported by the target. Since
2480 we can be connected to a remote system before before knowing about
2481 any inferior, mark the target with execution when we find the first
2482 inferior. If ATTACHED is 1, then we had just attached to this
2483 inferior. If it is 0, then we just created this inferior. If it
2484 is -1, then try querying the remote stub to find out if it had
2485 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2486 attempt to open this inferior's executable as the main executable
2487 if no main executable is open already. */
2488
2489 inferior *
2490 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2491 int try_open_exec)
2492 {
2493 struct inferior *inf;
2494
2495 /* Check whether this process we're learning about is to be
2496 considered attached, or if is to be considered to have been
2497 spawned by the stub. */
2498 if (attached == -1)
2499 attached = remote_query_attached (pid);
2500
2501 if (gdbarch_has_global_solist (target_gdbarch ()))
2502 {
2503 /* If the target shares code across all inferiors, then every
2504 attach adds a new inferior. */
2505 inf = add_inferior (pid);
2506
2507 /* ... and every inferior is bound to the same program space.
2508 However, each inferior may still have its own address
2509 space. */
2510 inf->aspace = maybe_new_address_space ();
2511 inf->pspace = current_program_space;
2512 }
2513 else
2514 {
2515 /* In the traditional debugging scenario, there's a 1-1 match
2516 between program/address spaces. We simply bind the inferior
2517 to the program space's address space. */
2518 inf = current_inferior ();
2519
2520 /* However, if the current inferior is already bound to a
2521 process, find some other empty inferior. */
2522 if (inf->pid != 0)
2523 {
2524 inf = nullptr;
2525 for (inferior *it : all_inferiors ())
2526 if (it->pid == 0)
2527 {
2528 inf = it;
2529 break;
2530 }
2531 }
2532 if (inf == nullptr)
2533 {
2534 /* Since all inferiors were already bound to a process, add
2535 a new inferior. */
2536 inf = add_inferior_with_spaces ();
2537 }
2538 switch_to_inferior_no_thread (inf);
2539 inf->push_target (this);
2540 inferior_appeared (inf, pid);
2541 }
2542
2543 inf->attach_flag = attached;
2544 inf->fake_pid_p = fake_pid_p;
2545
2546 /* If no main executable is currently open then attempt to
2547 open the file that was executed to create this inferior. */
2548 if (try_open_exec && get_exec_file (0) == NULL)
2549 exec_file_locate_attach (pid, 0, 1);
2550
2551 /* Check for exec file mismatch, and let the user solve it. */
2552 validate_exec_file (1);
2553
2554 return inf;
2555 }
2556
2557 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2558 static remote_thread_info *get_remote_thread_info (remote_target *target,
2559 ptid_t ptid);
2560
2561 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2562 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2563 remote_state::starting_up flag) is true then the new thread is added
2564 silently, otherwise the new thread will be announced to the user. */
2565
2566 thread_info *
2567 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2568 bool silent_p)
2569 {
2570 struct remote_state *rs = get_remote_state ();
2571 struct thread_info *thread;
2572
2573 /* GDB historically didn't pull threads in the initial connection
2574 setup. If the remote target doesn't even have a concept of
2575 threads (e.g., a bare-metal target), even if internally we
2576 consider that a single-threaded target, mentioning a new thread
2577 might be confusing to the user. Be silent then, preserving the
2578 age old behavior. */
2579 if (rs->starting_up || silent_p)
2580 thread = add_thread_silent (this, ptid);
2581 else
2582 thread = add_thread (this, ptid);
2583
2584 /* We start by assuming threads are resumed. That state then gets updated
2585 when we process a matching stop reply. */
2586 get_remote_thread_info (thread)->set_resumed ();
2587
2588 set_executing (this, ptid, executing);
2589 set_running (this, ptid, running);
2590
2591 return thread;
2592 }
2593
2594 /* Come here when we learn about a thread id from the remote target.
2595 It may be the first time we hear about such thread, so take the
2596 opportunity to add it to GDB's thread list. In case this is the
2597 first time we're noticing its corresponding inferior, add it to
2598 GDB's inferior list as well. EXECUTING indicates whether the
2599 thread is (internally) executing or stopped. */
2600
2601 void
2602 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2603 {
2604 /* In non-stop mode, we assume new found threads are (externally)
2605 running until proven otherwise with a stop reply. In all-stop,
2606 we can only get here if all threads are stopped. */
2607 bool running = target_is_non_stop_p ();
2608
2609 /* If this is a new thread, add it to GDB's thread list.
2610 If we leave it up to WFI to do this, bad things will happen. */
2611
2612 thread_info *tp = find_thread_ptid (this, currthread);
2613 if (tp != NULL && tp->state == THREAD_EXITED)
2614 {
2615 /* We're seeing an event on a thread id we knew had exited.
2616 This has to be a new thread reusing the old id. Add it. */
2617 remote_add_thread (currthread, running, executing, false);
2618 return;
2619 }
2620
2621 if (!in_thread_list (this, currthread))
2622 {
2623 struct inferior *inf = NULL;
2624 int pid = currthread.pid ();
2625
2626 if (inferior_ptid.is_pid ()
2627 && pid == inferior_ptid.pid ())
2628 {
2629 /* inferior_ptid has no thread member yet. This can happen
2630 with the vAttach -> remote_wait,"TAAthread:" path if the
2631 stub doesn't support qC. This is the first stop reported
2632 after an attach, so this is the main thread. Update the
2633 ptid in the thread list. */
2634 if (in_thread_list (this, ptid_t (pid)))
2635 thread_change_ptid (this, inferior_ptid, currthread);
2636 else
2637 {
2638 thread_info *thr
2639 = remote_add_thread (currthread, running, executing, false);
2640 switch_to_thread (thr);
2641 }
2642 return;
2643 }
2644
2645 if (magic_null_ptid == inferior_ptid)
2646 {
2647 /* inferior_ptid is not set yet. This can happen with the
2648 vRun -> remote_wait,"TAAthread:" path if the stub
2649 doesn't support qC. This is the first stop reported
2650 after an attach, so this is the main thread. Update the
2651 ptid in the thread list. */
2652 thread_change_ptid (this, inferior_ptid, currthread);
2653 return;
2654 }
2655
2656 /* When connecting to a target remote, or to a target
2657 extended-remote which already was debugging an inferior, we
2658 may not know about it yet. Add it before adding its child
2659 thread, so notifications are emitted in a sensible order. */
2660 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2661 {
2662 struct remote_state *rs = get_remote_state ();
2663 bool fake_pid_p = !remote_multi_process_p (rs);
2664
2665 inf = remote_add_inferior (fake_pid_p,
2666 currthread.pid (), -1, 1);
2667 }
2668
2669 /* This is really a new thread. Add it. */
2670 thread_info *new_thr
2671 = remote_add_thread (currthread, running, executing, false);
2672
2673 /* If we found a new inferior, let the common code do whatever
2674 it needs to with it (e.g., read shared libraries, insert
2675 breakpoints), unless we're just setting up an all-stop
2676 connection. */
2677 if (inf != NULL)
2678 {
2679 struct remote_state *rs = get_remote_state ();
2680
2681 if (!rs->starting_up)
2682 notice_new_inferior (new_thr, executing, 0);
2683 }
2684 }
2685 }
2686
2687 /* Return THREAD's private thread data, creating it if necessary. */
2688
2689 static remote_thread_info *
2690 get_remote_thread_info (thread_info *thread)
2691 {
2692 gdb_assert (thread != NULL);
2693
2694 if (thread->priv == NULL)
2695 thread->priv.reset (new remote_thread_info);
2696
2697 return static_cast<remote_thread_info *> (thread->priv.get ());
2698 }
2699
2700 /* Return PTID's private thread data, creating it if necessary. */
2701
2702 static remote_thread_info *
2703 get_remote_thread_info (remote_target *target, ptid_t ptid)
2704 {
2705 thread_info *thr = find_thread_ptid (target, ptid);
2706 return get_remote_thread_info (thr);
2707 }
2708
2709 /* Call this function as a result of
2710 1) A halt indication (T packet) containing a thread id
2711 2) A direct query of currthread
2712 3) Successful execution of set thread */
2713
2714 static void
2715 record_currthread (struct remote_state *rs, ptid_t currthread)
2716 {
2717 rs->general_thread = currthread;
2718 }
2719
2720 /* If 'QPassSignals' is supported, tell the remote stub what signals
2721 it can simply pass through to the inferior without reporting. */
2722
2723 void
2724 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2725 {
2726 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2727 {
2728 char *pass_packet, *p;
2729 int count = 0;
2730 struct remote_state *rs = get_remote_state ();
2731
2732 gdb_assert (pass_signals.size () < 256);
2733 for (size_t i = 0; i < pass_signals.size (); i++)
2734 {
2735 if (pass_signals[i])
2736 count++;
2737 }
2738 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2739 strcpy (pass_packet, "QPassSignals:");
2740 p = pass_packet + strlen (pass_packet);
2741 for (size_t i = 0; i < pass_signals.size (); i++)
2742 {
2743 if (pass_signals[i])
2744 {
2745 if (i >= 16)
2746 *p++ = tohex (i >> 4);
2747 *p++ = tohex (i & 15);
2748 if (count)
2749 *p++ = ';';
2750 else
2751 break;
2752 count--;
2753 }
2754 }
2755 *p = 0;
2756 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2757 {
2758 putpkt (pass_packet);
2759 getpkt (&rs->buf, 0);
2760 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2761 xfree (rs->last_pass_packet);
2762 rs->last_pass_packet = pass_packet;
2763 }
2764 else
2765 xfree (pass_packet);
2766 }
2767 }
2768
2769 /* If 'QCatchSyscalls' is supported, tell the remote stub
2770 to report syscalls to GDB. */
2771
2772 int
2773 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2774 gdb::array_view<const int> syscall_counts)
2775 {
2776 const char *catch_packet;
2777 enum packet_result result;
2778 int n_sysno = 0;
2779
2780 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2781 {
2782 /* Not supported. */
2783 return 1;
2784 }
2785
2786 if (needed && any_count == 0)
2787 {
2788 /* Count how many syscalls are to be caught. */
2789 for (size_t i = 0; i < syscall_counts.size (); i++)
2790 {
2791 if (syscall_counts[i] != 0)
2792 n_sysno++;
2793 }
2794 }
2795
2796 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
2797 pid, needed, any_count, n_sysno);
2798
2799 std::string built_packet;
2800 if (needed)
2801 {
2802 /* Prepare a packet with the sysno list, assuming max 8+1
2803 characters for a sysno. If the resulting packet size is too
2804 big, fallback on the non-selective packet. */
2805 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2806 built_packet.reserve (maxpktsz);
2807 built_packet = "QCatchSyscalls:1";
2808 if (any_count == 0)
2809 {
2810 /* Add in each syscall to be caught. */
2811 for (size_t i = 0; i < syscall_counts.size (); i++)
2812 {
2813 if (syscall_counts[i] != 0)
2814 string_appendf (built_packet, ";%zx", i);
2815 }
2816 }
2817 if (built_packet.size () > get_remote_packet_size ())
2818 {
2819 /* catch_packet too big. Fallback to less efficient
2820 non selective mode, with GDB doing the filtering. */
2821 catch_packet = "QCatchSyscalls:1";
2822 }
2823 else
2824 catch_packet = built_packet.c_str ();
2825 }
2826 else
2827 catch_packet = "QCatchSyscalls:0";
2828
2829 struct remote_state *rs = get_remote_state ();
2830
2831 putpkt (catch_packet);
2832 getpkt (&rs->buf, 0);
2833 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2834 if (result == PACKET_OK)
2835 return 0;
2836 else
2837 return -1;
2838 }
2839
2840 /* If 'QProgramSignals' is supported, tell the remote stub what
2841 signals it should pass through to the inferior when detaching. */
2842
2843 void
2844 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
2845 {
2846 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2847 {
2848 char *packet, *p;
2849 int count = 0;
2850 struct remote_state *rs = get_remote_state ();
2851
2852 gdb_assert (signals.size () < 256);
2853 for (size_t i = 0; i < signals.size (); i++)
2854 {
2855 if (signals[i])
2856 count++;
2857 }
2858 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2859 strcpy (packet, "QProgramSignals:");
2860 p = packet + strlen (packet);
2861 for (size_t i = 0; i < signals.size (); i++)
2862 {
2863 if (signal_pass_state (i))
2864 {
2865 if (i >= 16)
2866 *p++ = tohex (i >> 4);
2867 *p++ = tohex (i & 15);
2868 if (count)
2869 *p++ = ';';
2870 else
2871 break;
2872 count--;
2873 }
2874 }
2875 *p = 0;
2876 if (!rs->last_program_signals_packet
2877 || strcmp (rs->last_program_signals_packet, packet) != 0)
2878 {
2879 putpkt (packet);
2880 getpkt (&rs->buf, 0);
2881 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2882 xfree (rs->last_program_signals_packet);
2883 rs->last_program_signals_packet = packet;
2884 }
2885 else
2886 xfree (packet);
2887 }
2888 }
2889
2890 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2891 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2892 thread. If GEN is set, set the general thread, if not, then set
2893 the step/continue thread. */
2894 void
2895 remote_target::set_thread (ptid_t ptid, int gen)
2896 {
2897 struct remote_state *rs = get_remote_state ();
2898 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2899 char *buf = rs->buf.data ();
2900 char *endbuf = buf + get_remote_packet_size ();
2901
2902 if (state == ptid)
2903 return;
2904
2905 *buf++ = 'H';
2906 *buf++ = gen ? 'g' : 'c';
2907 if (ptid == magic_null_ptid)
2908 xsnprintf (buf, endbuf - buf, "0");
2909 else if (ptid == any_thread_ptid)
2910 xsnprintf (buf, endbuf - buf, "0");
2911 else if (ptid == minus_one_ptid)
2912 xsnprintf (buf, endbuf - buf, "-1");
2913 else
2914 write_ptid (buf, endbuf, ptid);
2915 putpkt (rs->buf);
2916 getpkt (&rs->buf, 0);
2917 if (gen)
2918 rs->general_thread = ptid;
2919 else
2920 rs->continue_thread = ptid;
2921 }
2922
2923 void
2924 remote_target::set_general_thread (ptid_t ptid)
2925 {
2926 set_thread (ptid, 1);
2927 }
2928
2929 void
2930 remote_target::set_continue_thread (ptid_t ptid)
2931 {
2932 set_thread (ptid, 0);
2933 }
2934
2935 /* Change the remote current process. Which thread within the process
2936 ends up selected isn't important, as long as it is the same process
2937 as what INFERIOR_PTID points to.
2938
2939 This comes from that fact that there is no explicit notion of
2940 "selected process" in the protocol. The selected process for
2941 general operations is the process the selected general thread
2942 belongs to. */
2943
2944 void
2945 remote_target::set_general_process ()
2946 {
2947 struct remote_state *rs = get_remote_state ();
2948
2949 /* If the remote can't handle multiple processes, don't bother. */
2950 if (!remote_multi_process_p (rs))
2951 return;
2952
2953 /* We only need to change the remote current thread if it's pointing
2954 at some other process. */
2955 if (rs->general_thread.pid () != inferior_ptid.pid ())
2956 set_general_thread (inferior_ptid);
2957 }
2958
2959 \f
2960 /* Return nonzero if this is the main thread that we made up ourselves
2961 to model non-threaded targets as single-threaded. */
2962
2963 static int
2964 remote_thread_always_alive (ptid_t ptid)
2965 {
2966 if (ptid == magic_null_ptid)
2967 /* The main thread is always alive. */
2968 return 1;
2969
2970 if (ptid.pid () != 0 && ptid.lwp () == 0)
2971 /* The main thread is always alive. This can happen after a
2972 vAttach, if the remote side doesn't support
2973 multi-threading. */
2974 return 1;
2975
2976 return 0;
2977 }
2978
2979 /* Return nonzero if the thread PTID is still alive on the remote
2980 system. */
2981
2982 bool
2983 remote_target::thread_alive (ptid_t ptid)
2984 {
2985 struct remote_state *rs = get_remote_state ();
2986 char *p, *endp;
2987
2988 /* Check if this is a thread that we made up ourselves to model
2989 non-threaded targets as single-threaded. */
2990 if (remote_thread_always_alive (ptid))
2991 return 1;
2992
2993 p = rs->buf.data ();
2994 endp = p + get_remote_packet_size ();
2995
2996 *p++ = 'T';
2997 write_ptid (p, endp, ptid);
2998
2999 putpkt (rs->buf);
3000 getpkt (&rs->buf, 0);
3001 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
3002 }
3003
3004 /* Return a pointer to a thread name if we know it and NULL otherwise.
3005 The thread_info object owns the memory for the name. */
3006
3007 const char *
3008 remote_target::thread_name (struct thread_info *info)
3009 {
3010 if (info->priv != NULL)
3011 {
3012 const std::string &name = get_remote_thread_info (info)->name;
3013 return !name.empty () ? name.c_str () : NULL;
3014 }
3015
3016 return NULL;
3017 }
3018
3019 /* About these extended threadlist and threadinfo packets. They are
3020 variable length packets but, the fields within them are often fixed
3021 length. They are redundant enough to send over UDP as is the
3022 remote protocol in general. There is a matching unit test module
3023 in libstub. */
3024
3025 /* WARNING: This threadref data structure comes from the remote O.S.,
3026 libstub protocol encoding, and remote.c. It is not particularly
3027 changable. */
3028
3029 /* Right now, the internal structure is int. We want it to be bigger.
3030 Plan to fix this. */
3031
3032 typedef int gdb_threadref; /* Internal GDB thread reference. */
3033
3034 /* gdb_ext_thread_info is an internal GDB data structure which is
3035 equivalent to the reply of the remote threadinfo packet. */
3036
3037 struct gdb_ext_thread_info
3038 {
3039 threadref threadid; /* External form of thread reference. */
3040 int active; /* Has state interesting to GDB?
3041 regs, stack. */
3042 char display[256]; /* Brief state display, name,
3043 blocked/suspended. */
3044 char shortname[32]; /* To be used to name threads. */
3045 char more_display[256]; /* Long info, statistics, queue depth,
3046 whatever. */
3047 };
3048
3049 /* The volume of remote transfers can be limited by submitting
3050 a mask containing bits specifying the desired information.
3051 Use a union of these values as the 'selection' parameter to
3052 get_thread_info. FIXME: Make these TAG names more thread specific. */
3053
3054 #define TAG_THREADID 1
3055 #define TAG_EXISTS 2
3056 #define TAG_DISPLAY 4
3057 #define TAG_THREADNAME 8
3058 #define TAG_MOREDISPLAY 16
3059
3060 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3061
3062 static const char *unpack_nibble (const char *buf, int *val);
3063
3064 static const char *unpack_byte (const char *buf, int *value);
3065
3066 static char *pack_int (char *buf, int value);
3067
3068 static const char *unpack_int (const char *buf, int *value);
3069
3070 static const char *unpack_string (const char *src, char *dest, int length);
3071
3072 static char *pack_threadid (char *pkt, threadref *id);
3073
3074 static const char *unpack_threadid (const char *inbuf, threadref *id);
3075
3076 void int_to_threadref (threadref *id, int value);
3077
3078 static int threadref_to_int (threadref *ref);
3079
3080 static void copy_threadref (threadref *dest, threadref *src);
3081
3082 static int threadmatch (threadref *dest, threadref *src);
3083
3084 static char *pack_threadinfo_request (char *pkt, int mode,
3085 threadref *id);
3086
3087 static char *pack_threadlist_request (char *pkt, int startflag,
3088 int threadcount,
3089 threadref *nextthread);
3090
3091 static int remote_newthread_step (threadref *ref, void *context);
3092
3093
3094 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3095 buffer we're allowed to write to. Returns
3096 BUF+CHARACTERS_WRITTEN. */
3097
3098 char *
3099 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3100 {
3101 int pid, tid;
3102 struct remote_state *rs = get_remote_state ();
3103
3104 if (remote_multi_process_p (rs))
3105 {
3106 pid = ptid.pid ();
3107 if (pid < 0)
3108 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3109 else
3110 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3111 }
3112 tid = ptid.lwp ();
3113 if (tid < 0)
3114 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3115 else
3116 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3117
3118 return buf;
3119 }
3120
3121 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3122 last parsed char. Returns null_ptid if no thread id is found, and
3123 throws an error if the thread id has an invalid format. */
3124
3125 static ptid_t
3126 read_ptid (const char *buf, const char **obuf)
3127 {
3128 const char *p = buf;
3129 const char *pp;
3130 ULONGEST pid = 0, tid = 0;
3131
3132 if (*p == 'p')
3133 {
3134 /* Multi-process ptid. */
3135 pp = unpack_varlen_hex (p + 1, &pid);
3136 if (*pp != '.')
3137 error (_("invalid remote ptid: %s"), p);
3138
3139 p = pp;
3140 pp = unpack_varlen_hex (p + 1, &tid);
3141 if (obuf)
3142 *obuf = pp;
3143 return ptid_t (pid, tid);
3144 }
3145
3146 /* No multi-process. Just a tid. */
3147 pp = unpack_varlen_hex (p, &tid);
3148
3149 /* Return null_ptid when no thread id is found. */
3150 if (p == pp)
3151 {
3152 if (obuf)
3153 *obuf = pp;
3154 return null_ptid;
3155 }
3156
3157 /* Since the stub is not sending a process id, default to what's
3158 current_inferior, unless it doesn't have a PID yet. If so,
3159 then since there's no way to know the pid of the reported
3160 threads, use the magic number. */
3161 inferior *inf = current_inferior ();
3162 if (inf->pid == 0)
3163 pid = magic_null_ptid.pid ();
3164 else
3165 pid = inf->pid;
3166
3167 if (obuf)
3168 *obuf = pp;
3169 return ptid_t (pid, tid);
3170 }
3171
3172 static int
3173 stubhex (int ch)
3174 {
3175 if (ch >= 'a' && ch <= 'f')
3176 return ch - 'a' + 10;
3177 if (ch >= '0' && ch <= '9')
3178 return ch - '0';
3179 if (ch >= 'A' && ch <= 'F')
3180 return ch - 'A' + 10;
3181 return -1;
3182 }
3183
3184 static int
3185 stub_unpack_int (const char *buff, int fieldlength)
3186 {
3187 int nibble;
3188 int retval = 0;
3189
3190 while (fieldlength)
3191 {
3192 nibble = stubhex (*buff++);
3193 retval |= nibble;
3194 fieldlength--;
3195 if (fieldlength)
3196 retval = retval << 4;
3197 }
3198 return retval;
3199 }
3200
3201 static const char *
3202 unpack_nibble (const char *buf, int *val)
3203 {
3204 *val = fromhex (*buf++);
3205 return buf;
3206 }
3207
3208 static const char *
3209 unpack_byte (const char *buf, int *value)
3210 {
3211 *value = stub_unpack_int (buf, 2);
3212 return buf + 2;
3213 }
3214
3215 static char *
3216 pack_int (char *buf, int value)
3217 {
3218 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3219 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3220 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3221 buf = pack_hex_byte (buf, (value & 0xff));
3222 return buf;
3223 }
3224
3225 static const char *
3226 unpack_int (const char *buf, int *value)
3227 {
3228 *value = stub_unpack_int (buf, 8);
3229 return buf + 8;
3230 }
3231
3232 #if 0 /* Currently unused, uncomment when needed. */
3233 static char *pack_string (char *pkt, char *string);
3234
3235 static char *
3236 pack_string (char *pkt, char *string)
3237 {
3238 char ch;
3239 int len;
3240
3241 len = strlen (string);
3242 if (len > 200)
3243 len = 200; /* Bigger than most GDB packets, junk??? */
3244 pkt = pack_hex_byte (pkt, len);
3245 while (len-- > 0)
3246 {
3247 ch = *string++;
3248 if ((ch == '\0') || (ch == '#'))
3249 ch = '*'; /* Protect encapsulation. */
3250 *pkt++ = ch;
3251 }
3252 return pkt;
3253 }
3254 #endif /* 0 (unused) */
3255
3256 static const char *
3257 unpack_string (const char *src, char *dest, int length)
3258 {
3259 while (length--)
3260 *dest++ = *src++;
3261 *dest = '\0';
3262 return src;
3263 }
3264
3265 static char *
3266 pack_threadid (char *pkt, threadref *id)
3267 {
3268 char *limit;
3269 unsigned char *altid;
3270
3271 altid = (unsigned char *) id;
3272 limit = pkt + BUF_THREAD_ID_SIZE;
3273 while (pkt < limit)
3274 pkt = pack_hex_byte (pkt, *altid++);
3275 return pkt;
3276 }
3277
3278
3279 static const char *
3280 unpack_threadid (const char *inbuf, threadref *id)
3281 {
3282 char *altref;
3283 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3284 int x, y;
3285
3286 altref = (char *) id;
3287
3288 while (inbuf < limit)
3289 {
3290 x = stubhex (*inbuf++);
3291 y = stubhex (*inbuf++);
3292 *altref++ = (x << 4) | y;
3293 }
3294 return inbuf;
3295 }
3296
3297 /* Externally, threadrefs are 64 bits but internally, they are still
3298 ints. This is due to a mismatch of specifications. We would like
3299 to use 64bit thread references internally. This is an adapter
3300 function. */
3301
3302 void
3303 int_to_threadref (threadref *id, int value)
3304 {
3305 unsigned char *scan;
3306
3307 scan = (unsigned char *) id;
3308 {
3309 int i = 4;
3310 while (i--)
3311 *scan++ = 0;
3312 }
3313 *scan++ = (value >> 24) & 0xff;
3314 *scan++ = (value >> 16) & 0xff;
3315 *scan++ = (value >> 8) & 0xff;
3316 *scan++ = (value & 0xff);
3317 }
3318
3319 static int
3320 threadref_to_int (threadref *ref)
3321 {
3322 int i, value = 0;
3323 unsigned char *scan;
3324
3325 scan = *ref;
3326 scan += 4;
3327 i = 4;
3328 while (i-- > 0)
3329 value = (value << 8) | ((*scan++) & 0xff);
3330 return value;
3331 }
3332
3333 static void
3334 copy_threadref (threadref *dest, threadref *src)
3335 {
3336 int i;
3337 unsigned char *csrc, *cdest;
3338
3339 csrc = (unsigned char *) src;
3340 cdest = (unsigned char *) dest;
3341 i = 8;
3342 while (i--)
3343 *cdest++ = *csrc++;
3344 }
3345
3346 static int
3347 threadmatch (threadref *dest, threadref *src)
3348 {
3349 /* Things are broken right now, so just assume we got a match. */
3350 #if 0
3351 unsigned char *srcp, *destp;
3352 int i, result;
3353 srcp = (char *) src;
3354 destp = (char *) dest;
3355
3356 result = 1;
3357 while (i-- > 0)
3358 result &= (*srcp++ == *destp++) ? 1 : 0;
3359 return result;
3360 #endif
3361 return 1;
3362 }
3363
3364 /*
3365 threadid:1, # always request threadid
3366 context_exists:2,
3367 display:4,
3368 unique_name:8,
3369 more_display:16
3370 */
3371
3372 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3373
3374 static char *
3375 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3376 {
3377 *pkt++ = 'q'; /* Info Query */
3378 *pkt++ = 'P'; /* process or thread info */
3379 pkt = pack_int (pkt, mode); /* mode */
3380 pkt = pack_threadid (pkt, id); /* threadid */
3381 *pkt = '\0'; /* terminate */
3382 return pkt;
3383 }
3384
3385 /* These values tag the fields in a thread info response packet. */
3386 /* Tagging the fields allows us to request specific fields and to
3387 add more fields as time goes by. */
3388
3389 #define TAG_THREADID 1 /* Echo the thread identifier. */
3390 #define TAG_EXISTS 2 /* Is this process defined enough to
3391 fetch registers and its stack? */
3392 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3393 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3394 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3395 the process. */
3396
3397 int
3398 remote_target::remote_unpack_thread_info_response (const char *pkt,
3399 threadref *expectedref,
3400 gdb_ext_thread_info *info)
3401 {
3402 struct remote_state *rs = get_remote_state ();
3403 int mask, length;
3404 int tag;
3405 threadref ref;
3406 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3407 int retval = 1;
3408
3409 /* info->threadid = 0; FIXME: implement zero_threadref. */
3410 info->active = 0;
3411 info->display[0] = '\0';
3412 info->shortname[0] = '\0';
3413 info->more_display[0] = '\0';
3414
3415 /* Assume the characters indicating the packet type have been
3416 stripped. */
3417 pkt = unpack_int (pkt, &mask); /* arg mask */
3418 pkt = unpack_threadid (pkt, &ref);
3419
3420 if (mask == 0)
3421 warning (_("Incomplete response to threadinfo request."));
3422 if (!threadmatch (&ref, expectedref))
3423 { /* This is an answer to a different request. */
3424 warning (_("ERROR RMT Thread info mismatch."));
3425 return 0;
3426 }
3427 copy_threadref (&info->threadid, &ref);
3428
3429 /* Loop on tagged fields , try to bail if something goes wrong. */
3430
3431 /* Packets are terminated with nulls. */
3432 while ((pkt < limit) && mask && *pkt)
3433 {
3434 pkt = unpack_int (pkt, &tag); /* tag */
3435 pkt = unpack_byte (pkt, &length); /* length */
3436 if (!(tag & mask)) /* Tags out of synch with mask. */
3437 {
3438 warning (_("ERROR RMT: threadinfo tag mismatch."));
3439 retval = 0;
3440 break;
3441 }
3442 if (tag == TAG_THREADID)
3443 {
3444 if (length != 16)
3445 {
3446 warning (_("ERROR RMT: length of threadid is not 16."));
3447 retval = 0;
3448 break;
3449 }
3450 pkt = unpack_threadid (pkt, &ref);
3451 mask = mask & ~TAG_THREADID;
3452 continue;
3453 }
3454 if (tag == TAG_EXISTS)
3455 {
3456 info->active = stub_unpack_int (pkt, length);
3457 pkt += length;
3458 mask = mask & ~(TAG_EXISTS);
3459 if (length > 8)
3460 {
3461 warning (_("ERROR RMT: 'exists' length too long."));
3462 retval = 0;
3463 break;
3464 }
3465 continue;
3466 }
3467 if (tag == TAG_THREADNAME)
3468 {
3469 pkt = unpack_string (pkt, &info->shortname[0], length);
3470 mask = mask & ~TAG_THREADNAME;
3471 continue;
3472 }
3473 if (tag == TAG_DISPLAY)
3474 {
3475 pkt = unpack_string (pkt, &info->display[0], length);
3476 mask = mask & ~TAG_DISPLAY;
3477 continue;
3478 }
3479 if (tag == TAG_MOREDISPLAY)
3480 {
3481 pkt = unpack_string (pkt, &info->more_display[0], length);
3482 mask = mask & ~TAG_MOREDISPLAY;
3483 continue;
3484 }
3485 warning (_("ERROR RMT: unknown thread info tag."));
3486 break; /* Not a tag we know about. */
3487 }
3488 return retval;
3489 }
3490
3491 int
3492 remote_target::remote_get_threadinfo (threadref *threadid,
3493 int fieldset,
3494 gdb_ext_thread_info *info)
3495 {
3496 struct remote_state *rs = get_remote_state ();
3497 int result;
3498
3499 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3500 putpkt (rs->buf);
3501 getpkt (&rs->buf, 0);
3502
3503 if (rs->buf[0] == '\0')
3504 return 0;
3505
3506 result = remote_unpack_thread_info_response (&rs->buf[2],
3507 threadid, info);
3508 return result;
3509 }
3510
3511 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3512
3513 static char *
3514 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3515 threadref *nextthread)
3516 {
3517 *pkt++ = 'q'; /* info query packet */
3518 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3519 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3520 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3521 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3522 *pkt = '\0';
3523 return pkt;
3524 }
3525
3526 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3527
3528 int
3529 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3530 threadref *original_echo,
3531 threadref *resultlist,
3532 int *doneflag)
3533 {
3534 struct remote_state *rs = get_remote_state ();
3535 int count, resultcount, done;
3536
3537 resultcount = 0;
3538 /* Assume the 'q' and 'M chars have been stripped. */
3539 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3540 /* done parse past here */
3541 pkt = unpack_byte (pkt, &count); /* count field */
3542 pkt = unpack_nibble (pkt, &done);
3543 /* The first threadid is the argument threadid. */
3544 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3545 while ((count-- > 0) && (pkt < limit))
3546 {
3547 pkt = unpack_threadid (pkt, resultlist++);
3548 if (resultcount++ >= result_limit)
3549 break;
3550 }
3551 if (doneflag)
3552 *doneflag = done;
3553 return resultcount;
3554 }
3555
3556 /* Fetch the next batch of threads from the remote. Returns -1 if the
3557 qL packet is not supported, 0 on error and 1 on success. */
3558
3559 int
3560 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3561 int result_limit, int *done, int *result_count,
3562 threadref *threadlist)
3563 {
3564 struct remote_state *rs = get_remote_state ();
3565 int result = 1;
3566
3567 /* Truncate result limit to be smaller than the packet size. */
3568 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3569 >= get_remote_packet_size ())
3570 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3571
3572 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3573 nextthread);
3574 putpkt (rs->buf);
3575 getpkt (&rs->buf, 0);
3576 if (rs->buf[0] == '\0')
3577 {
3578 /* Packet not supported. */
3579 return -1;
3580 }
3581
3582 *result_count =
3583 parse_threadlist_response (&rs->buf[2], result_limit,
3584 &rs->echo_nextthread, threadlist, done);
3585
3586 if (!threadmatch (&rs->echo_nextthread, nextthread))
3587 {
3588 /* FIXME: This is a good reason to drop the packet. */
3589 /* Possibly, there is a duplicate response. */
3590 /* Possibilities :
3591 retransmit immediatly - race conditions
3592 retransmit after timeout - yes
3593 exit
3594 wait for packet, then exit
3595 */
3596 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3597 return 0; /* I choose simply exiting. */
3598 }
3599 if (*result_count <= 0)
3600 {
3601 if (*done != 1)
3602 {
3603 warning (_("RMT ERROR : failed to get remote thread list."));
3604 result = 0;
3605 }
3606 return result; /* break; */
3607 }
3608 if (*result_count > result_limit)
3609 {
3610 *result_count = 0;
3611 warning (_("RMT ERROR: threadlist response longer than requested."));
3612 return 0;
3613 }
3614 return result;
3615 }
3616
3617 /* Fetch the list of remote threads, with the qL packet, and call
3618 STEPFUNCTION for each thread found. Stops iterating and returns 1
3619 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3620 STEPFUNCTION returns false. If the packet is not supported,
3621 returns -1. */
3622
3623 int
3624 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3625 void *context, int looplimit)
3626 {
3627 struct remote_state *rs = get_remote_state ();
3628 int done, i, result_count;
3629 int startflag = 1;
3630 int result = 1;
3631 int loopcount = 0;
3632
3633 done = 0;
3634 while (!done)
3635 {
3636 if (loopcount++ > looplimit)
3637 {
3638 result = 0;
3639 warning (_("Remote fetch threadlist -infinite loop-."));
3640 break;
3641 }
3642 result = remote_get_threadlist (startflag, &rs->nextthread,
3643 MAXTHREADLISTRESULTS,
3644 &done, &result_count,
3645 rs->resultthreadlist);
3646 if (result <= 0)
3647 break;
3648 /* Clear for later iterations. */
3649 startflag = 0;
3650 /* Setup to resume next batch of thread references, set nextthread. */
3651 if (result_count >= 1)
3652 copy_threadref (&rs->nextthread,
3653 &rs->resultthreadlist[result_count - 1]);
3654 i = 0;
3655 while (result_count--)
3656 {
3657 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3658 {
3659 result = 0;
3660 break;
3661 }
3662 }
3663 }
3664 return result;
3665 }
3666
3667 /* A thread found on the remote target. */
3668
3669 struct thread_item
3670 {
3671 explicit thread_item (ptid_t ptid_)
3672 : ptid (ptid_)
3673 {}
3674
3675 thread_item (thread_item &&other) = default;
3676 thread_item &operator= (thread_item &&other) = default;
3677
3678 DISABLE_COPY_AND_ASSIGN (thread_item);
3679
3680 /* The thread's PTID. */
3681 ptid_t ptid;
3682
3683 /* The thread's extra info. */
3684 std::string extra;
3685
3686 /* The thread's name. */
3687 std::string name;
3688
3689 /* The core the thread was running on. -1 if not known. */
3690 int core = -1;
3691
3692 /* The thread handle associated with the thread. */
3693 gdb::byte_vector thread_handle;
3694 };
3695
3696 /* Context passed around to the various methods listing remote
3697 threads. As new threads are found, they're added to the ITEMS
3698 vector. */
3699
3700 struct threads_listing_context
3701 {
3702 /* Return true if this object contains an entry for a thread with ptid
3703 PTID. */
3704
3705 bool contains_thread (ptid_t ptid) const
3706 {
3707 auto match_ptid = [&] (const thread_item &item)
3708 {
3709 return item.ptid == ptid;
3710 };
3711
3712 auto it = std::find_if (this->items.begin (),
3713 this->items.end (),
3714 match_ptid);
3715
3716 return it != this->items.end ();
3717 }
3718
3719 /* Remove the thread with ptid PTID. */
3720
3721 void remove_thread (ptid_t ptid)
3722 {
3723 auto match_ptid = [&] (const thread_item &item)
3724 {
3725 return item.ptid == ptid;
3726 };
3727
3728 auto it = std::remove_if (this->items.begin (),
3729 this->items.end (),
3730 match_ptid);
3731
3732 if (it != this->items.end ())
3733 this->items.erase (it);
3734 }
3735
3736 /* The threads found on the remote target. */
3737 std::vector<thread_item> items;
3738 };
3739
3740 static int
3741 remote_newthread_step (threadref *ref, void *data)
3742 {
3743 struct threads_listing_context *context
3744 = (struct threads_listing_context *) data;
3745 int pid = inferior_ptid.pid ();
3746 int lwp = threadref_to_int (ref);
3747 ptid_t ptid (pid, lwp);
3748
3749 context->items.emplace_back (ptid);
3750
3751 return 1; /* continue iterator */
3752 }
3753
3754 #define CRAZY_MAX_THREADS 1000
3755
3756 ptid_t
3757 remote_target::remote_current_thread (ptid_t oldpid)
3758 {
3759 struct remote_state *rs = get_remote_state ();
3760
3761 putpkt ("qC");
3762 getpkt (&rs->buf, 0);
3763 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3764 {
3765 const char *obuf;
3766 ptid_t result;
3767
3768 result = read_ptid (&rs->buf[2], &obuf);
3769 if (*obuf != '\0')
3770 remote_debug_printf ("warning: garbage in qC reply");
3771
3772 return result;
3773 }
3774 else
3775 return oldpid;
3776 }
3777
3778 /* List remote threads using the deprecated qL packet. */
3779
3780 int
3781 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3782 {
3783 if (remote_threadlist_iterator (remote_newthread_step, context,
3784 CRAZY_MAX_THREADS) >= 0)
3785 return 1;
3786
3787 return 0;
3788 }
3789
3790 #if defined(HAVE_LIBEXPAT)
3791
3792 static void
3793 start_thread (struct gdb_xml_parser *parser,
3794 const struct gdb_xml_element *element,
3795 void *user_data,
3796 std::vector<gdb_xml_value> &attributes)
3797 {
3798 struct threads_listing_context *data
3799 = (struct threads_listing_context *) user_data;
3800 struct gdb_xml_value *attr;
3801
3802 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3803 ptid_t ptid = read_ptid (id, NULL);
3804
3805 data->items.emplace_back (ptid);
3806 thread_item &item = data->items.back ();
3807
3808 attr = xml_find_attribute (attributes, "core");
3809 if (attr != NULL)
3810 item.core = *(ULONGEST *) attr->value.get ();
3811
3812 attr = xml_find_attribute (attributes, "name");
3813 if (attr != NULL)
3814 item.name = (const char *) attr->value.get ();
3815
3816 attr = xml_find_attribute (attributes, "handle");
3817 if (attr != NULL)
3818 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3819 }
3820
3821 static void
3822 end_thread (struct gdb_xml_parser *parser,
3823 const struct gdb_xml_element *element,
3824 void *user_data, const char *body_text)
3825 {
3826 struct threads_listing_context *data
3827 = (struct threads_listing_context *) user_data;
3828
3829 if (body_text != NULL && *body_text != '\0')
3830 data->items.back ().extra = body_text;
3831 }
3832
3833 const struct gdb_xml_attribute thread_attributes[] = {
3834 { "id", GDB_XML_AF_NONE, NULL, NULL },
3835 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3836 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3837 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3838 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3839 };
3840
3841 const struct gdb_xml_element thread_children[] = {
3842 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3843 };
3844
3845 const struct gdb_xml_element threads_children[] = {
3846 { "thread", thread_attributes, thread_children,
3847 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3848 start_thread, end_thread },
3849 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3850 };
3851
3852 const struct gdb_xml_element threads_elements[] = {
3853 { "threads", NULL, threads_children,
3854 GDB_XML_EF_NONE, NULL, NULL },
3855 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3856 };
3857
3858 #endif
3859
3860 /* List remote threads using qXfer:threads:read. */
3861
3862 int
3863 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
3864 {
3865 #if defined(HAVE_LIBEXPAT)
3866 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3867 {
3868 gdb::optional<gdb::char_vector> xml
3869 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
3870
3871 if (xml && (*xml)[0] != '\0')
3872 {
3873 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3874 threads_elements, xml->data (), context);
3875 }
3876
3877 return 1;
3878 }
3879 #endif
3880
3881 return 0;
3882 }
3883
3884 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3885
3886 int
3887 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
3888 {
3889 struct remote_state *rs = get_remote_state ();
3890
3891 if (rs->use_threadinfo_query)
3892 {
3893 const char *bufp;
3894
3895 putpkt ("qfThreadInfo");
3896 getpkt (&rs->buf, 0);
3897 bufp = rs->buf.data ();
3898 if (bufp[0] != '\0') /* q packet recognized */
3899 {
3900 while (*bufp++ == 'm') /* reply contains one or more TID */
3901 {
3902 do
3903 {
3904 ptid_t ptid = read_ptid (bufp, &bufp);
3905 context->items.emplace_back (ptid);
3906 }
3907 while (*bufp++ == ','); /* comma-separated list */
3908 putpkt ("qsThreadInfo");
3909 getpkt (&rs->buf, 0);
3910 bufp = rs->buf.data ();
3911 }
3912 return 1;
3913 }
3914 else
3915 {
3916 /* Packet not recognized. */
3917 rs->use_threadinfo_query = 0;
3918 }
3919 }
3920
3921 return 0;
3922 }
3923
3924 /* Return true if INF only has one non-exited thread. */
3925
3926 static bool
3927 has_single_non_exited_thread (inferior *inf)
3928 {
3929 int count = 0;
3930 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
3931 if (++count > 1)
3932 break;
3933 return count == 1;
3934 }
3935
3936 /* Implement the to_update_thread_list function for the remote
3937 targets. */
3938
3939 void
3940 remote_target::update_thread_list ()
3941 {
3942 struct threads_listing_context context;
3943 int got_list = 0;
3944
3945 /* We have a few different mechanisms to fetch the thread list. Try
3946 them all, starting with the most preferred one first, falling
3947 back to older methods. */
3948 if (remote_get_threads_with_qxfer (&context)
3949 || remote_get_threads_with_qthreadinfo (&context)
3950 || remote_get_threads_with_ql (&context))
3951 {
3952 got_list = 1;
3953
3954 if (context.items.empty ()
3955 && remote_thread_always_alive (inferior_ptid))
3956 {
3957 /* Some targets don't really support threads, but still
3958 reply an (empty) thread list in response to the thread
3959 listing packets, instead of replying "packet not
3960 supported". Exit early so we don't delete the main
3961 thread. */
3962 return;
3963 }
3964
3965 /* CONTEXT now holds the current thread list on the remote
3966 target end. Delete GDB-side threads no longer found on the
3967 target. */
3968 for (thread_info *tp : all_threads_safe ())
3969 {
3970 if (tp->inf->process_target () != this)
3971 continue;
3972
3973 if (!context.contains_thread (tp->ptid))
3974 {
3975 /* Do not remove the thread if it is the last thread in
3976 the inferior. This situation happens when we have a
3977 pending exit process status to process. Otherwise we
3978 may end up with a seemingly live inferior (i.e. pid
3979 != 0) that has no threads. */
3980 if (has_single_non_exited_thread (tp->inf))
3981 continue;
3982
3983 /* Not found. */
3984 delete_thread (tp);
3985 }
3986 }
3987
3988 /* Remove any unreported fork child threads from CONTEXT so
3989 that we don't interfere with follow fork, which is where
3990 creation of such threads is handled. */
3991 remove_new_fork_children (&context);
3992
3993 /* And now add threads we don't know about yet to our list. */
3994 for (thread_item &item : context.items)
3995 {
3996 if (item.ptid != null_ptid)
3997 {
3998 /* In non-stop mode, we assume new found threads are
3999 executing until proven otherwise with a stop reply.
4000 In all-stop, we can only get here if all threads are
4001 stopped. */
4002 bool executing = target_is_non_stop_p ();
4003
4004 remote_notice_new_inferior (item.ptid, executing);
4005
4006 thread_info *tp = find_thread_ptid (this, item.ptid);
4007 remote_thread_info *info = get_remote_thread_info (tp);
4008 info->core = item.core;
4009 info->extra = std::move (item.extra);
4010 info->name = std::move (item.name);
4011 info->thread_handle = std::move (item.thread_handle);
4012 }
4013 }
4014 }
4015
4016 if (!got_list)
4017 {
4018 /* If no thread listing method is supported, then query whether
4019 each known thread is alive, one by one, with the T packet.
4020 If the target doesn't support threads at all, then this is a
4021 no-op. See remote_thread_alive. */
4022 prune_threads ();
4023 }
4024 }
4025
4026 /*
4027 * Collect a descriptive string about the given thread.
4028 * The target may say anything it wants to about the thread
4029 * (typically info about its blocked / runnable state, name, etc.).
4030 * This string will appear in the info threads display.
4031 *
4032 * Optional: targets are not required to implement this function.
4033 */
4034
4035 const char *
4036 remote_target::extra_thread_info (thread_info *tp)
4037 {
4038 struct remote_state *rs = get_remote_state ();
4039 int set;
4040 threadref id;
4041 struct gdb_ext_thread_info threadinfo;
4042
4043 if (rs->remote_desc == 0) /* paranoia */
4044 internal_error (__FILE__, __LINE__,
4045 _("remote_threads_extra_info"));
4046
4047 if (tp->ptid == magic_null_ptid
4048 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4049 /* This is the main thread which was added by GDB. The remote
4050 server doesn't know about it. */
4051 return NULL;
4052
4053 std::string &extra = get_remote_thread_info (tp)->extra;
4054
4055 /* If already have cached info, use it. */
4056 if (!extra.empty ())
4057 return extra.c_str ();
4058
4059 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4060 {
4061 /* If we're using qXfer:threads:read, then the extra info is
4062 included in the XML. So if we didn't have anything cached,
4063 it's because there's really no extra info. */
4064 return NULL;
4065 }
4066
4067 if (rs->use_threadextra_query)
4068 {
4069 char *b = rs->buf.data ();
4070 char *endb = b + get_remote_packet_size ();
4071
4072 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4073 b += strlen (b);
4074 write_ptid (b, endb, tp->ptid);
4075
4076 putpkt (rs->buf);
4077 getpkt (&rs->buf, 0);
4078 if (rs->buf[0] != 0)
4079 {
4080 extra.resize (strlen (rs->buf.data ()) / 2);
4081 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4082 return extra.c_str ();
4083 }
4084 }
4085
4086 /* If the above query fails, fall back to the old method. */
4087 rs->use_threadextra_query = 0;
4088 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4089 | TAG_MOREDISPLAY | TAG_DISPLAY;
4090 int_to_threadref (&id, tp->ptid.lwp ());
4091 if (remote_get_threadinfo (&id, set, &threadinfo))
4092 if (threadinfo.active)
4093 {
4094 if (*threadinfo.shortname)
4095 string_appendf (extra, " Name: %s", threadinfo.shortname);
4096 if (*threadinfo.display)
4097 {
4098 if (!extra.empty ())
4099 extra += ',';
4100 string_appendf (extra, " State: %s", threadinfo.display);
4101 }
4102 if (*threadinfo.more_display)
4103 {
4104 if (!extra.empty ())
4105 extra += ',';
4106 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4107 }
4108 return extra.c_str ();
4109 }
4110 return NULL;
4111 }
4112 \f
4113
4114 bool
4115 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4116 struct static_tracepoint_marker *marker)
4117 {
4118 struct remote_state *rs = get_remote_state ();
4119 char *p = rs->buf.data ();
4120
4121 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4122 p += strlen (p);
4123 p += hexnumstr (p, addr);
4124 putpkt (rs->buf);
4125 getpkt (&rs->buf, 0);
4126 p = rs->buf.data ();
4127
4128 if (*p == 'E')
4129 error (_("Remote failure reply: %s"), p);
4130
4131 if (*p++ == 'm')
4132 {
4133 parse_static_tracepoint_marker_definition (p, NULL, marker);
4134 return true;
4135 }
4136
4137 return false;
4138 }
4139
4140 std::vector<static_tracepoint_marker>
4141 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4142 {
4143 struct remote_state *rs = get_remote_state ();
4144 std::vector<static_tracepoint_marker> markers;
4145 const char *p;
4146 static_tracepoint_marker marker;
4147
4148 /* Ask for a first packet of static tracepoint marker
4149 definition. */
4150 putpkt ("qTfSTM");
4151 getpkt (&rs->buf, 0);
4152 p = rs->buf.data ();
4153 if (*p == 'E')
4154 error (_("Remote failure reply: %s"), p);
4155
4156 while (*p++ == 'm')
4157 {
4158 do
4159 {
4160 parse_static_tracepoint_marker_definition (p, &p, &marker);
4161
4162 if (strid == NULL || marker.str_id == strid)
4163 markers.push_back (std::move (marker));
4164 }
4165 while (*p++ == ','); /* comma-separated list */
4166 /* Ask for another packet of static tracepoint definition. */
4167 putpkt ("qTsSTM");
4168 getpkt (&rs->buf, 0);
4169 p = rs->buf.data ();
4170 }
4171
4172 return markers;
4173 }
4174
4175 \f
4176 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4177
4178 ptid_t
4179 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4180 {
4181 return ptid_t (inferior_ptid.pid (), lwp);
4182 }
4183 \f
4184
4185 /* Restart the remote side; this is an extended protocol operation. */
4186
4187 void
4188 remote_target::extended_remote_restart ()
4189 {
4190 struct remote_state *rs = get_remote_state ();
4191
4192 /* Send the restart command; for reasons I don't understand the
4193 remote side really expects a number after the "R". */
4194 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4195 putpkt (rs->buf);
4196
4197 remote_fileio_reset ();
4198 }
4199 \f
4200 /* Clean up connection to a remote debugger. */
4201
4202 void
4203 remote_target::close ()
4204 {
4205 /* Make sure we leave stdin registered in the event loop. */
4206 terminal_ours ();
4207
4208 trace_reset_local_state ();
4209
4210 delete this;
4211 }
4212
4213 remote_target::~remote_target ()
4214 {
4215 struct remote_state *rs = get_remote_state ();
4216
4217 /* Check for NULL because we may get here with a partially
4218 constructed target/connection. */
4219 if (rs->remote_desc == nullptr)
4220 return;
4221
4222 serial_close (rs->remote_desc);
4223
4224 /* We are destroying the remote target, so we should discard
4225 everything of this target. */
4226 discard_pending_stop_replies_in_queue ();
4227
4228 if (rs->remote_async_inferior_event_token)
4229 delete_async_event_handler (&rs->remote_async_inferior_event_token);
4230
4231 delete rs->notif_state;
4232 }
4233
4234 /* Query the remote side for the text, data and bss offsets. */
4235
4236 void
4237 remote_target::get_offsets ()
4238 {
4239 struct remote_state *rs = get_remote_state ();
4240 char *buf;
4241 char *ptr;
4242 int lose, num_segments = 0, do_sections, do_segments;
4243 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4244
4245 if (current_program_space->symfile_object_file == NULL)
4246 return;
4247
4248 putpkt ("qOffsets");
4249 getpkt (&rs->buf, 0);
4250 buf = rs->buf.data ();
4251
4252 if (buf[0] == '\000')
4253 return; /* Return silently. Stub doesn't support
4254 this command. */
4255 if (buf[0] == 'E')
4256 {
4257 warning (_("Remote failure reply: %s"), buf);
4258 return;
4259 }
4260
4261 /* Pick up each field in turn. This used to be done with scanf, but
4262 scanf will make trouble if CORE_ADDR size doesn't match
4263 conversion directives correctly. The following code will work
4264 with any size of CORE_ADDR. */
4265 text_addr = data_addr = bss_addr = 0;
4266 ptr = buf;
4267 lose = 0;
4268
4269 if (startswith (ptr, "Text="))
4270 {
4271 ptr += 5;
4272 /* Don't use strtol, could lose on big values. */
4273 while (*ptr && *ptr != ';')
4274 text_addr = (text_addr << 4) + fromhex (*ptr++);
4275
4276 if (startswith (ptr, ";Data="))
4277 {
4278 ptr += 6;
4279 while (*ptr && *ptr != ';')
4280 data_addr = (data_addr << 4) + fromhex (*ptr++);
4281 }
4282 else
4283 lose = 1;
4284
4285 if (!lose && startswith (ptr, ";Bss="))
4286 {
4287 ptr += 5;
4288 while (*ptr && *ptr != ';')
4289 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4290
4291 if (bss_addr != data_addr)
4292 warning (_("Target reported unsupported offsets: %s"), buf);
4293 }
4294 else
4295 lose = 1;
4296 }
4297 else if (startswith (ptr, "TextSeg="))
4298 {
4299 ptr += 8;
4300 /* Don't use strtol, could lose on big values. */
4301 while (*ptr && *ptr != ';')
4302 text_addr = (text_addr << 4) + fromhex (*ptr++);
4303 num_segments = 1;
4304
4305 if (startswith (ptr, ";DataSeg="))
4306 {
4307 ptr += 9;
4308 while (*ptr && *ptr != ';')
4309 data_addr = (data_addr << 4) + fromhex (*ptr++);
4310 num_segments++;
4311 }
4312 }
4313 else
4314 lose = 1;
4315
4316 if (lose)
4317 error (_("Malformed response to offset query, %s"), buf);
4318 else if (*ptr != '\0')
4319 warning (_("Target reported unsupported offsets: %s"), buf);
4320
4321 objfile *objf = current_program_space->symfile_object_file;
4322 section_offsets offs = objf->section_offsets;
4323
4324 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd);
4325 do_segments = (data != NULL);
4326 do_sections = num_segments == 0;
4327
4328 if (num_segments > 0)
4329 {
4330 segments[0] = text_addr;
4331 segments[1] = data_addr;
4332 }
4333 /* If we have two segments, we can still try to relocate everything
4334 by assuming that the .text and .data offsets apply to the whole
4335 text and data segments. Convert the offsets given in the packet
4336 to base addresses for symfile_map_offsets_to_segments. */
4337 else if (data != nullptr && data->segments.size () == 2)
4338 {
4339 segments[0] = data->segments[0].base + text_addr;
4340 segments[1] = data->segments[1].base + data_addr;
4341 num_segments = 2;
4342 }
4343 /* If the object file has only one segment, assume that it is text
4344 rather than data; main programs with no writable data are rare,
4345 but programs with no code are useless. Of course the code might
4346 have ended up in the data segment... to detect that we would need
4347 the permissions here. */
4348 else if (data && data->segments.size () == 1)
4349 {
4350 segments[0] = data->segments[0].base + text_addr;
4351 num_segments = 1;
4352 }
4353 /* There's no way to relocate by segment. */
4354 else
4355 do_segments = 0;
4356
4357 if (do_segments)
4358 {
4359 int ret = symfile_map_offsets_to_segments (objf->obfd,
4360 data.get (), offs,
4361 num_segments, segments);
4362
4363 if (ret == 0 && !do_sections)
4364 error (_("Can not handle qOffsets TextSeg "
4365 "response with this symbol file"));
4366
4367 if (ret > 0)
4368 do_sections = 0;
4369 }
4370
4371 if (do_sections)
4372 {
4373 offs[SECT_OFF_TEXT (objf)] = text_addr;
4374
4375 /* This is a temporary kludge to force data and bss to use the
4376 same offsets because that's what nlmconv does now. The real
4377 solution requires changes to the stub and remote.c that I
4378 don't have time to do right now. */
4379
4380 offs[SECT_OFF_DATA (objf)] = data_addr;
4381 offs[SECT_OFF_BSS (objf)] = data_addr;
4382 }
4383
4384 objfile_relocate (objf, offs);
4385 }
4386
4387 /* Send interrupt_sequence to remote target. */
4388
4389 void
4390 remote_target::send_interrupt_sequence ()
4391 {
4392 struct remote_state *rs = get_remote_state ();
4393
4394 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4395 remote_serial_write ("\x03", 1);
4396 else if (interrupt_sequence_mode == interrupt_sequence_break)
4397 serial_send_break (rs->remote_desc);
4398 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4399 {
4400 serial_send_break (rs->remote_desc);
4401 remote_serial_write ("g", 1);
4402 }
4403 else
4404 internal_error (__FILE__, __LINE__,
4405 _("Invalid value for interrupt_sequence_mode: %s."),
4406 interrupt_sequence_mode);
4407 }
4408
4409
4410 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4411 and extract the PTID. Returns NULL_PTID if not found. */
4412
4413 static ptid_t
4414 stop_reply_extract_thread (const char *stop_reply)
4415 {
4416 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4417 {
4418 const char *p;
4419
4420 /* Txx r:val ; r:val (...) */
4421 p = &stop_reply[3];
4422
4423 /* Look for "register" named "thread". */
4424 while (*p != '\0')
4425 {
4426 const char *p1;
4427
4428 p1 = strchr (p, ':');
4429 if (p1 == NULL)
4430 return null_ptid;
4431
4432 if (strncmp (p, "thread", p1 - p) == 0)
4433 return read_ptid (++p1, &p);
4434
4435 p1 = strchr (p, ';');
4436 if (p1 == NULL)
4437 return null_ptid;
4438 p1++;
4439
4440 p = p1;
4441 }
4442 }
4443
4444 return null_ptid;
4445 }
4446
4447 /* Determine the remote side's current thread. If we have a stop
4448 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4449 "thread" register we can extract the current thread from. If not,
4450 ask the remote which is the current thread with qC. The former
4451 method avoids a roundtrip. */
4452
4453 ptid_t
4454 remote_target::get_current_thread (const char *wait_status)
4455 {
4456 ptid_t ptid = null_ptid;
4457
4458 /* Note we don't use remote_parse_stop_reply as that makes use of
4459 the target architecture, which we haven't yet fully determined at
4460 this point. */
4461 if (wait_status != NULL)
4462 ptid = stop_reply_extract_thread (wait_status);
4463 if (ptid == null_ptid)
4464 ptid = remote_current_thread (inferior_ptid);
4465
4466 return ptid;
4467 }
4468
4469 /* Query the remote target for which is the current thread/process,
4470 add it to our tables, and update INFERIOR_PTID. The caller is
4471 responsible for setting the state such that the remote end is ready
4472 to return the current thread.
4473
4474 This function is called after handling the '?' or 'vRun' packets,
4475 whose response is a stop reply from which we can also try
4476 extracting the thread. If the target doesn't support the explicit
4477 qC query, we infer the current thread from that stop reply, passed
4478 in in WAIT_STATUS, which may be NULL.
4479
4480 The function returns pointer to the main thread of the inferior. */
4481
4482 thread_info *
4483 remote_target::add_current_inferior_and_thread (const char *wait_status)
4484 {
4485 struct remote_state *rs = get_remote_state ();
4486 bool fake_pid_p = false;
4487
4488 switch_to_no_thread ();
4489
4490 /* Now, if we have thread information, update the current thread's
4491 ptid. */
4492 ptid_t curr_ptid = get_current_thread (wait_status);
4493
4494 if (curr_ptid != null_ptid)
4495 {
4496 if (!remote_multi_process_p (rs))
4497 fake_pid_p = true;
4498 }
4499 else
4500 {
4501 /* Without this, some commands which require an active target
4502 (such as kill) won't work. This variable serves (at least)
4503 double duty as both the pid of the target process (if it has
4504 such), and as a flag indicating that a target is active. */
4505 curr_ptid = magic_null_ptid;
4506 fake_pid_p = true;
4507 }
4508
4509 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4510
4511 /* Add the main thread and switch to it. Don't try reading
4512 registers yet, since we haven't fetched the target description
4513 yet. */
4514 thread_info *tp = add_thread_silent (this, curr_ptid);
4515 switch_to_thread_no_regs (tp);
4516
4517 return tp;
4518 }
4519
4520 /* Print info about a thread that was found already stopped on
4521 connection. */
4522
4523 void
4524 remote_target::print_one_stopped_thread (thread_info *thread)
4525 {
4526 target_waitstatus ws;
4527
4528 /* If there is a pending waitstatus, use it. If there isn't it's because
4529 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4530 and process_initial_stop_replies decided it wasn't interesting to save
4531 and report to the core. */
4532 if (thread->has_pending_waitstatus ())
4533 {
4534 ws = thread->pending_waitstatus ();
4535 thread->clear_pending_waitstatus ();
4536 }
4537 else
4538 {
4539 ws.set_stopped (GDB_SIGNAL_0);
4540 }
4541
4542 switch_to_thread (thread);
4543 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4544 set_current_sal_from_frame (get_current_frame ());
4545
4546 /* For "info program". */
4547 set_last_target_status (this, thread->ptid, ws);
4548
4549 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4550 {
4551 enum gdb_signal sig = ws.sig ();
4552
4553 if (signal_print_state (sig))
4554 gdb::observers::signal_received.notify (sig);
4555 }
4556 gdb::observers::normal_stop.notify (NULL, 1);
4557 }
4558
4559 /* Process all initial stop replies the remote side sent in response
4560 to the ? packet. These indicate threads that were already stopped
4561 on initial connection. We mark these threads as stopped and print
4562 their current frame before giving the user the prompt. */
4563
4564 void
4565 remote_target::process_initial_stop_replies (int from_tty)
4566 {
4567 int pending_stop_replies = stop_reply_queue_length ();
4568 struct thread_info *selected = NULL;
4569 struct thread_info *lowest_stopped = NULL;
4570 struct thread_info *first = NULL;
4571
4572 /* This is only used when the target is non-stop. */
4573 gdb_assert (target_is_non_stop_p ());
4574
4575 /* Consume the initial pending events. */
4576 while (pending_stop_replies-- > 0)
4577 {
4578 ptid_t waiton_ptid = minus_one_ptid;
4579 ptid_t event_ptid;
4580 struct target_waitstatus ws;
4581 int ignore_event = 0;
4582
4583 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4584 if (remote_debug)
4585 print_target_wait_results (waiton_ptid, event_ptid, ws);
4586
4587 switch (ws.kind ())
4588 {
4589 case TARGET_WAITKIND_IGNORE:
4590 case TARGET_WAITKIND_NO_RESUMED:
4591 case TARGET_WAITKIND_SIGNALLED:
4592 case TARGET_WAITKIND_EXITED:
4593 /* We shouldn't see these, but if we do, just ignore. */
4594 remote_debug_printf ("event ignored");
4595 ignore_event = 1;
4596 break;
4597
4598 default:
4599 break;
4600 }
4601
4602 if (ignore_event)
4603 continue;
4604
4605 thread_info *evthread = find_thread_ptid (this, event_ptid);
4606
4607 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4608 {
4609 enum gdb_signal sig = ws.sig ();
4610
4611 /* Stubs traditionally report SIGTRAP as initial signal,
4612 instead of signal 0. Suppress it. */
4613 if (sig == GDB_SIGNAL_TRAP)
4614 sig = GDB_SIGNAL_0;
4615 evthread->set_stop_signal (sig);
4616 ws.set_stopped (sig);
4617 }
4618
4619 if (ws.kind () != TARGET_WAITKIND_STOPPED
4620 || ws.sig () != GDB_SIGNAL_0)
4621 evthread->set_pending_waitstatus (ws);
4622
4623 set_executing (this, event_ptid, false);
4624 set_running (this, event_ptid, false);
4625 get_remote_thread_info (evthread)->set_not_resumed ();
4626 }
4627
4628 /* "Notice" the new inferiors before anything related to
4629 registers/memory. */
4630 for (inferior *inf : all_non_exited_inferiors (this))
4631 {
4632 inf->needs_setup = 1;
4633
4634 if (non_stop)
4635 {
4636 thread_info *thread = any_live_thread_of_inferior (inf);
4637 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4638 from_tty);
4639 }
4640 }
4641
4642 /* If all-stop on top of non-stop, pause all threads. Note this
4643 records the threads' stop pc, so must be done after "noticing"
4644 the inferiors. */
4645 if (!non_stop)
4646 {
4647 {
4648 /* At this point, the remote target is not async. It needs to be for
4649 the poll in stop_all_threads to consider events from it, so enable
4650 it temporarily. */
4651 gdb_assert (!this->is_async_p ());
4652 SCOPE_EXIT { target_async (0); };
4653 target_async (1);
4654 stop_all_threads ("remote connect in all-stop");
4655 }
4656
4657 /* If all threads of an inferior were already stopped, we
4658 haven't setup the inferior yet. */
4659 for (inferior *inf : all_non_exited_inferiors (this))
4660 {
4661 if (inf->needs_setup)
4662 {
4663 thread_info *thread = any_live_thread_of_inferior (inf);
4664 switch_to_thread_no_regs (thread);
4665 setup_inferior (0);
4666 }
4667 }
4668 }
4669
4670 /* Now go over all threads that are stopped, and print their current
4671 frame. If all-stop, then if there's a signalled thread, pick
4672 that as current. */
4673 for (thread_info *thread : all_non_exited_threads (this))
4674 {
4675 if (first == NULL)
4676 first = thread;
4677
4678 if (!non_stop)
4679 thread->set_running (false);
4680 else if (thread->state != THREAD_STOPPED)
4681 continue;
4682
4683 if (selected == nullptr && thread->has_pending_waitstatus ())
4684 selected = thread;
4685
4686 if (lowest_stopped == NULL
4687 || thread->inf->num < lowest_stopped->inf->num
4688 || thread->per_inf_num < lowest_stopped->per_inf_num)
4689 lowest_stopped = thread;
4690
4691 if (non_stop)
4692 print_one_stopped_thread (thread);
4693 }
4694
4695 /* In all-stop, we only print the status of one thread, and leave
4696 others with their status pending. */
4697 if (!non_stop)
4698 {
4699 thread_info *thread = selected;
4700 if (thread == NULL)
4701 thread = lowest_stopped;
4702 if (thread == NULL)
4703 thread = first;
4704
4705 print_one_stopped_thread (thread);
4706 }
4707 }
4708
4709 /* Mark a remote_target as marking (by setting the starting_up flag within
4710 its remote_state) for the lifetime of this object. The reference count
4711 on the remote target is temporarily incremented, to prevent the target
4712 being deleted under our feet. */
4713
4714 struct scoped_mark_target_starting
4715 {
4716 /* Constructor, TARGET is the target to be marked as starting, its
4717 reference count will be incremented. */
4718 scoped_mark_target_starting (remote_target *target)
4719 : m_remote_target (target)
4720 {
4721 m_remote_target->incref ();
4722 remote_state *rs = m_remote_target->get_remote_state ();
4723 rs->starting_up = true;
4724 }
4725
4726 /* Destructor, mark the target being worked on as no longer starting, and
4727 decrement the reference count. */
4728 ~scoped_mark_target_starting ()
4729 {
4730 remote_state *rs = m_remote_target->get_remote_state ();
4731 rs->starting_up = false;
4732 decref_target (m_remote_target);
4733 }
4734
4735 private:
4736
4737 /* The target on which we are operating. */
4738 remote_target *m_remote_target;
4739 };
4740
4741 /* Helper for remote_target::start_remote, start the remote connection and
4742 sync state. Return true if everything goes OK, otherwise, return false.
4743 This function exists so that the scoped_restore created within it will
4744 expire before we return to remote_target::start_remote. */
4745
4746 bool
4747 remote_target::start_remote_1 (int from_tty, int extended_p)
4748 {
4749 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4750
4751 struct remote_state *rs = get_remote_state ();
4752 struct packet_config *noack_config;
4753
4754 /* Signal other parts that we're going through the initial setup,
4755 and so things may not be stable yet. E.g., we don't try to
4756 install tracepoints until we've relocated symbols. Also, a
4757 Ctrl-C before we're connected and synced up can't interrupt the
4758 target. Instead, it offers to drop the (potentially wedged)
4759 connection. */
4760 scoped_mark_target_starting target_is_starting (this);
4761
4762 QUIT;
4763
4764 if (interrupt_on_connect)
4765 send_interrupt_sequence ();
4766
4767 /* Ack any packet which the remote side has already sent. */
4768 remote_serial_write ("+", 1);
4769
4770 /* The first packet we send to the target is the optional "supported
4771 packets" request. If the target can answer this, it will tell us
4772 which later probes to skip. */
4773 remote_query_supported ();
4774
4775 /* If the stub wants to get a QAllow, compose one and send it. */
4776 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4777 set_permissions ();
4778
4779 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4780 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4781 as a reply to known packet. For packet "vFile:setfs:" it is an
4782 invalid reply and GDB would return error in
4783 remote_hostio_set_filesystem, making remote files access impossible.
4784 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4785 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4786 {
4787 const char v_mustreplyempty[] = "vMustReplyEmpty";
4788
4789 putpkt (v_mustreplyempty);
4790 getpkt (&rs->buf, 0);
4791 if (strcmp (rs->buf.data (), "OK") == 0)
4792 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4793 else if (strcmp (rs->buf.data (), "") != 0)
4794 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4795 rs->buf.data ());
4796 }
4797
4798 /* Next, we possibly activate noack mode.
4799
4800 If the QStartNoAckMode packet configuration is set to AUTO,
4801 enable noack mode if the stub reported a wish for it with
4802 qSupported.
4803
4804 If set to TRUE, then enable noack mode even if the stub didn't
4805 report it in qSupported. If the stub doesn't reply OK, the
4806 session ends with an error.
4807
4808 If FALSE, then don't activate noack mode, regardless of what the
4809 stub claimed should be the default with qSupported. */
4810
4811 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4812 if (packet_config_support (noack_config) != PACKET_DISABLE)
4813 {
4814 putpkt ("QStartNoAckMode");
4815 getpkt (&rs->buf, 0);
4816 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4817 rs->noack_mode = 1;
4818 }
4819
4820 if (extended_p)
4821 {
4822 /* Tell the remote that we are using the extended protocol. */
4823 putpkt ("!");
4824 getpkt (&rs->buf, 0);
4825 }
4826
4827 /* Let the target know which signals it is allowed to pass down to
4828 the program. */
4829 update_signals_program_target ();
4830
4831 /* Next, if the target can specify a description, read it. We do
4832 this before anything involving memory or registers. */
4833 target_find_description ();
4834
4835 /* Next, now that we know something about the target, update the
4836 address spaces in the program spaces. */
4837 update_address_spaces ();
4838
4839 /* On OSs where the list of libraries is global to all
4840 processes, we fetch them early. */
4841 if (gdbarch_has_global_solist (target_gdbarch ()))
4842 solib_add (NULL, from_tty, auto_solib_add);
4843
4844 if (target_is_non_stop_p ())
4845 {
4846 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4847 error (_("Non-stop mode requested, but remote "
4848 "does not support non-stop"));
4849
4850 putpkt ("QNonStop:1");
4851 getpkt (&rs->buf, 0);
4852
4853 if (strcmp (rs->buf.data (), "OK") != 0)
4854 error (_("Remote refused setting non-stop mode with: %s"),
4855 rs->buf.data ());
4856
4857 /* Find about threads and processes the stub is already
4858 controlling. We default to adding them in the running state.
4859 The '?' query below will then tell us about which threads are
4860 stopped. */
4861 this->update_thread_list ();
4862 }
4863 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4864 {
4865 /* Don't assume that the stub can operate in all-stop mode.
4866 Request it explicitly. */
4867 putpkt ("QNonStop:0");
4868 getpkt (&rs->buf, 0);
4869
4870 if (strcmp (rs->buf.data (), "OK") != 0)
4871 error (_("Remote refused setting all-stop mode with: %s"),
4872 rs->buf.data ());
4873 }
4874
4875 /* Upload TSVs regardless of whether the target is running or not. The
4876 remote stub, such as GDBserver, may have some predefined or builtin
4877 TSVs, even if the target is not running. */
4878 if (get_trace_status (current_trace_status ()) != -1)
4879 {
4880 struct uploaded_tsv *uploaded_tsvs = NULL;
4881
4882 upload_trace_state_variables (&uploaded_tsvs);
4883 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4884 }
4885
4886 /* Check whether the target is running now. */
4887 putpkt ("?");
4888 getpkt (&rs->buf, 0);
4889
4890 if (!target_is_non_stop_p ())
4891 {
4892 char *wait_status = NULL;
4893
4894 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4895 {
4896 if (!extended_p)
4897 error (_("The target is not running (try extended-remote?)"));
4898 return false;
4899 }
4900 else
4901 {
4902 /* Save the reply for later. */
4903 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
4904 strcpy (wait_status, rs->buf.data ());
4905 }
4906
4907 /* Fetch thread list. */
4908 target_update_thread_list ();
4909
4910 /* Let the stub know that we want it to return the thread. */
4911 set_continue_thread (minus_one_ptid);
4912
4913 if (thread_count (this) == 0)
4914 {
4915 /* Target has no concept of threads at all. GDB treats
4916 non-threaded target as single-threaded; add a main
4917 thread. */
4918 thread_info *tp = add_current_inferior_and_thread (wait_status);
4919 get_remote_thread_info (tp)->set_resumed ();
4920 }
4921 else
4922 {
4923 /* We have thread information; select the thread the target
4924 says should be current. If we're reconnecting to a
4925 multi-threaded program, this will ideally be the thread
4926 that last reported an event before GDB disconnected. */
4927 ptid_t curr_thread = get_current_thread (wait_status);
4928 if (curr_thread == null_ptid)
4929 {
4930 /* Odd... The target was able to list threads, but not
4931 tell us which thread was current (no "thread"
4932 register in T stop reply?). Just pick the first
4933 thread in the thread list then. */
4934
4935 remote_debug_printf ("warning: couldn't determine remote "
4936 "current thread; picking first in list.");
4937
4938 for (thread_info *tp : all_non_exited_threads (this,
4939 minus_one_ptid))
4940 {
4941 switch_to_thread (tp);
4942 break;
4943 }
4944 }
4945 else
4946 switch_to_thread (find_thread_ptid (this, curr_thread));
4947 }
4948
4949 /* init_wait_for_inferior should be called before get_offsets in order
4950 to manage `inserted' flag in bp loc in a correct state.
4951 breakpoint_init_inferior, called from init_wait_for_inferior, set
4952 `inserted' flag to 0, while before breakpoint_re_set, called from
4953 start_remote, set `inserted' flag to 1. In the initialization of
4954 inferior, breakpoint_init_inferior should be called first, and then
4955 breakpoint_re_set can be called. If this order is broken, state of
4956 `inserted' flag is wrong, and cause some problems on breakpoint
4957 manipulation. */
4958 init_wait_for_inferior ();
4959
4960 get_offsets (); /* Get text, data & bss offsets. */
4961
4962 /* If we could not find a description using qXfer, and we know
4963 how to do it some other way, try again. This is not
4964 supported for non-stop; it could be, but it is tricky if
4965 there are no stopped threads when we connect. */
4966 if (remote_read_description_p (this)
4967 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4968 {
4969 target_clear_description ();
4970 target_find_description ();
4971 }
4972
4973 /* Use the previously fetched status. */
4974 gdb_assert (wait_status != NULL);
4975 struct notif_event *reply
4976 = remote_notif_parse (this, &notif_client_stop, wait_status);
4977 push_stop_reply ((struct stop_reply *) reply);
4978
4979 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
4980 }
4981 else
4982 {
4983 /* Clear WFI global state. Do this before finding about new
4984 threads and inferiors, and setting the current inferior.
4985 Otherwise we would clear the proceed status of the current
4986 inferior when we want its stop_soon state to be preserved
4987 (see notice_new_inferior). */
4988 init_wait_for_inferior ();
4989
4990 /* In non-stop, we will either get an "OK", meaning that there
4991 are no stopped threads at this time; or, a regular stop
4992 reply. In the latter case, there may be more than one thread
4993 stopped --- we pull them all out using the vStopped
4994 mechanism. */
4995 if (strcmp (rs->buf.data (), "OK") != 0)
4996 {
4997 struct notif_client *notif = &notif_client_stop;
4998
4999 /* remote_notif_get_pending_replies acks this one, and gets
5000 the rest out. */
5001 rs->notif_state->pending_event[notif_client_stop.id]
5002 = remote_notif_parse (this, notif, rs->buf.data ());
5003 remote_notif_get_pending_events (notif);
5004 }
5005
5006 if (thread_count (this) == 0)
5007 {
5008 if (!extended_p)
5009 error (_("The target is not running (try extended-remote?)"));
5010 return false;
5011 }
5012
5013 /* Report all signals during attach/startup. */
5014 pass_signals ({});
5015
5016 /* If there are already stopped threads, mark them stopped and
5017 report their stops before giving the prompt to the user. */
5018 process_initial_stop_replies (from_tty);
5019
5020 if (target_can_async_p ())
5021 target_async (1);
5022 }
5023
5024 /* If we connected to a live target, do some additional setup. */
5025 if (target_has_execution ())
5026 {
5027 /* No use without a symbol-file. */
5028 if (current_program_space->symfile_object_file)
5029 remote_check_symbols ();
5030 }
5031
5032 /* Possibly the target has been engaged in a trace run started
5033 previously; find out where things are at. */
5034 if (get_trace_status (current_trace_status ()) != -1)
5035 {
5036 struct uploaded_tp *uploaded_tps = NULL;
5037
5038 if (current_trace_status ()->running)
5039 gdb_printf (_("Trace is already running on the target.\n"));
5040
5041 upload_tracepoints (&uploaded_tps);
5042
5043 merge_uploaded_tracepoints (&uploaded_tps);
5044 }
5045
5046 /* Possibly the target has been engaged in a btrace record started
5047 previously; find out where things are at. */
5048 remote_btrace_maybe_reopen ();
5049
5050 return true;
5051 }
5052
5053 /* Start the remote connection and sync state. */
5054
5055 void
5056 remote_target::start_remote (int from_tty, int extended_p)
5057 {
5058 if (start_remote_1 (from_tty, extended_p)
5059 && breakpoints_should_be_inserted_now ())
5060 insert_breakpoints ();
5061 }
5062
5063 const char *
5064 remote_target::connection_string ()
5065 {
5066 remote_state *rs = get_remote_state ();
5067
5068 if (rs->remote_desc->name != NULL)
5069 return rs->remote_desc->name;
5070 else
5071 return NULL;
5072 }
5073
5074 /* Open a connection to a remote debugger.
5075 NAME is the filename used for communication. */
5076
5077 void
5078 remote_target::open (const char *name, int from_tty)
5079 {
5080 open_1 (name, from_tty, 0);
5081 }
5082
5083 /* Open a connection to a remote debugger using the extended
5084 remote gdb protocol. NAME is the filename used for communication. */
5085
5086 void
5087 extended_remote_target::open (const char *name, int from_tty)
5088 {
5089 open_1 (name, from_tty, 1 /*extended_p */);
5090 }
5091
5092 /* Reset all packets back to "unknown support". Called when opening a
5093 new connection to a remote target. */
5094
5095 static void
5096 reset_all_packet_configs_support (void)
5097 {
5098 int i;
5099
5100 for (i = 0; i < PACKET_MAX; i++)
5101 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5102 }
5103
5104 /* Initialize all packet configs. */
5105
5106 static void
5107 init_all_packet_configs (void)
5108 {
5109 int i;
5110
5111 for (i = 0; i < PACKET_MAX; i++)
5112 {
5113 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5114 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5115 }
5116 }
5117
5118 /* Symbol look-up. */
5119
5120 void
5121 remote_target::remote_check_symbols ()
5122 {
5123 char *tmp;
5124 int end;
5125
5126 /* It doesn't make sense to send a qSymbol packet for an inferior that
5127 doesn't have execution, because the remote side doesn't know about
5128 inferiors without execution. */
5129 gdb_assert (target_has_execution ());
5130
5131 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5132 return;
5133
5134 /* Make sure the remote is pointing at the right process. Note
5135 there's no way to select "no process". */
5136 set_general_process ();
5137
5138 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5139 because we need both at the same time. */
5140 gdb::char_vector msg (get_remote_packet_size ());
5141 gdb::char_vector reply (get_remote_packet_size ());
5142
5143 /* Invite target to request symbol lookups. */
5144
5145 putpkt ("qSymbol::");
5146 getpkt (&reply, 0);
5147 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
5148
5149 while (startswith (reply.data (), "qSymbol:"))
5150 {
5151 struct bound_minimal_symbol sym;
5152
5153 tmp = &reply[8];
5154 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5155 strlen (tmp) / 2);
5156 msg[end] = '\0';
5157 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5158 if (sym.minsym == NULL)
5159 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5160 &reply[8]);
5161 else
5162 {
5163 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5164 CORE_ADDR sym_addr = sym.value_address ();
5165
5166 /* If this is a function address, return the start of code
5167 instead of any data function descriptor. */
5168 sym_addr = gdbarch_convert_from_func_ptr_addr
5169 (target_gdbarch (), sym_addr, current_inferior ()->top_target ());
5170
5171 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5172 phex_nz (sym_addr, addr_size), &reply[8]);
5173 }
5174
5175 putpkt (msg.data ());
5176 getpkt (&reply, 0);
5177 }
5178 }
5179
5180 static struct serial *
5181 remote_serial_open (const char *name)
5182 {
5183 static int udp_warning = 0;
5184
5185 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5186 of in ser-tcp.c, because it is the remote protocol assuming that the
5187 serial connection is reliable and not the serial connection promising
5188 to be. */
5189 if (!udp_warning && startswith (name, "udp:"))
5190 {
5191 warning (_("The remote protocol may be unreliable over UDP.\n"
5192 "Some events may be lost, rendering further debugging "
5193 "impossible."));
5194 udp_warning = 1;
5195 }
5196
5197 return serial_open (name);
5198 }
5199
5200 /* Inform the target of our permission settings. The permission flags
5201 work without this, but if the target knows the settings, it can do
5202 a couple things. First, it can add its own check, to catch cases
5203 that somehow manage to get by the permissions checks in target
5204 methods. Second, if the target is wired to disallow particular
5205 settings (for instance, a system in the field that is not set up to
5206 be able to stop at a breakpoint), it can object to any unavailable
5207 permissions. */
5208
5209 void
5210 remote_target::set_permissions ()
5211 {
5212 struct remote_state *rs = get_remote_state ();
5213
5214 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5215 "WriteReg:%x;WriteMem:%x;"
5216 "InsertBreak:%x;InsertTrace:%x;"
5217 "InsertFastTrace:%x;Stop:%x",
5218 may_write_registers, may_write_memory,
5219 may_insert_breakpoints, may_insert_tracepoints,
5220 may_insert_fast_tracepoints, may_stop);
5221 putpkt (rs->buf);
5222 getpkt (&rs->buf, 0);
5223
5224 /* If the target didn't like the packet, warn the user. Do not try
5225 to undo the user's settings, that would just be maddening. */
5226 if (strcmp (rs->buf.data (), "OK") != 0)
5227 warning (_("Remote refused setting permissions with: %s"),
5228 rs->buf.data ());
5229 }
5230
5231 /* This type describes each known response to the qSupported
5232 packet. */
5233 struct protocol_feature
5234 {
5235 /* The name of this protocol feature. */
5236 const char *name;
5237
5238 /* The default for this protocol feature. */
5239 enum packet_support default_support;
5240
5241 /* The function to call when this feature is reported, or after
5242 qSupported processing if the feature is not supported.
5243 The first argument points to this structure. The second
5244 argument indicates whether the packet requested support be
5245 enabled, disabled, or probed (or the default, if this function
5246 is being called at the end of processing and this feature was
5247 not reported). The third argument may be NULL; if not NULL, it
5248 is a NUL-terminated string taken from the packet following
5249 this feature's name and an equals sign. */
5250 void (*func) (remote_target *remote, const struct protocol_feature *,
5251 enum packet_support, const char *);
5252
5253 /* The corresponding packet for this feature. Only used if
5254 FUNC is remote_supported_packet. */
5255 int packet;
5256 };
5257
5258 static void
5259 remote_supported_packet (remote_target *remote,
5260 const struct protocol_feature *feature,
5261 enum packet_support support,
5262 const char *argument)
5263 {
5264 if (argument)
5265 {
5266 warning (_("Remote qSupported response supplied an unexpected value for"
5267 " \"%s\"."), feature->name);
5268 return;
5269 }
5270
5271 remote_protocol_packets[feature->packet].support = support;
5272 }
5273
5274 void
5275 remote_target::remote_packet_size (const protocol_feature *feature,
5276 enum packet_support support, const char *value)
5277 {
5278 struct remote_state *rs = get_remote_state ();
5279
5280 int packet_size;
5281 char *value_end;
5282
5283 if (support != PACKET_ENABLE)
5284 return;
5285
5286 if (value == NULL || *value == '\0')
5287 {
5288 warning (_("Remote target reported \"%s\" without a size."),
5289 feature->name);
5290 return;
5291 }
5292
5293 errno = 0;
5294 packet_size = strtol (value, &value_end, 16);
5295 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5296 {
5297 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5298 feature->name, value);
5299 return;
5300 }
5301
5302 /* Record the new maximum packet size. */
5303 rs->explicit_packet_size = packet_size;
5304 }
5305
5306 static void
5307 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5308 enum packet_support support, const char *value)
5309 {
5310 remote->remote_packet_size (feature, support, value);
5311 }
5312
5313 static const struct protocol_feature remote_protocol_features[] = {
5314 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5315 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5316 PACKET_qXfer_auxv },
5317 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5318 PACKET_qXfer_exec_file },
5319 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5320 PACKET_qXfer_features },
5321 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5322 PACKET_qXfer_libraries },
5323 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5324 PACKET_qXfer_libraries_svr4 },
5325 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5326 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5327 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5328 PACKET_qXfer_memory_map },
5329 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5330 PACKET_qXfer_osdata },
5331 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5332 PACKET_qXfer_threads },
5333 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5334 PACKET_qXfer_traceframe_info },
5335 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5336 PACKET_QPassSignals },
5337 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5338 PACKET_QCatchSyscalls },
5339 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5340 PACKET_QProgramSignals },
5341 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5342 PACKET_QSetWorkingDir },
5343 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5344 PACKET_QStartupWithShell },
5345 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5346 PACKET_QEnvironmentHexEncoded },
5347 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5348 PACKET_QEnvironmentReset },
5349 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5350 PACKET_QEnvironmentUnset },
5351 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5352 PACKET_QStartNoAckMode },
5353 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5354 PACKET_multiprocess_feature },
5355 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5356 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5357 PACKET_qXfer_siginfo_read },
5358 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5359 PACKET_qXfer_siginfo_write },
5360 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5361 PACKET_ConditionalTracepoints },
5362 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5363 PACKET_ConditionalBreakpoints },
5364 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5365 PACKET_BreakpointCommands },
5366 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5367 PACKET_FastTracepoints },
5368 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5369 PACKET_StaticTracepoints },
5370 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5371 PACKET_InstallInTrace},
5372 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5373 PACKET_DisconnectedTracing_feature },
5374 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5375 PACKET_bc },
5376 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5377 PACKET_bs },
5378 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5379 PACKET_TracepointSource },
5380 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5381 PACKET_QAllow },
5382 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5383 PACKET_EnableDisableTracepoints_feature },
5384 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5385 PACKET_qXfer_fdpic },
5386 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5387 PACKET_qXfer_uib },
5388 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5389 PACKET_QDisableRandomization },
5390 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5391 { "QTBuffer:size", PACKET_DISABLE,
5392 remote_supported_packet, PACKET_QTBuffer_size},
5393 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5394 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5395 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5396 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5397 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5398 PACKET_qXfer_btrace },
5399 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5400 PACKET_qXfer_btrace_conf },
5401 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5402 PACKET_Qbtrace_conf_bts_size },
5403 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5404 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5405 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5406 PACKET_fork_event_feature },
5407 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5408 PACKET_vfork_event_feature },
5409 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5410 PACKET_exec_event_feature },
5411 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5412 PACKET_Qbtrace_conf_pt_size },
5413 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5414 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5415 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5416 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5417 PACKET_memory_tagging_feature },
5418 };
5419
5420 static char *remote_support_xml;
5421
5422 /* Register string appended to "xmlRegisters=" in qSupported query. */
5423
5424 void
5425 register_remote_support_xml (const char *xml)
5426 {
5427 #if defined(HAVE_LIBEXPAT)
5428 if (remote_support_xml == NULL)
5429 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5430 else
5431 {
5432 char *copy = xstrdup (remote_support_xml + 13);
5433 char *saveptr;
5434 char *p = strtok_r (copy, ",", &saveptr);
5435
5436 do
5437 {
5438 if (strcmp (p, xml) == 0)
5439 {
5440 /* already there */
5441 xfree (copy);
5442 return;
5443 }
5444 }
5445 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5446 xfree (copy);
5447
5448 remote_support_xml = reconcat (remote_support_xml,
5449 remote_support_xml, ",", xml,
5450 (char *) NULL);
5451 }
5452 #endif
5453 }
5454
5455 static void
5456 remote_query_supported_append (std::string *msg, const char *append)
5457 {
5458 if (!msg->empty ())
5459 msg->append (";");
5460 msg->append (append);
5461 }
5462
5463 void
5464 remote_target::remote_query_supported ()
5465 {
5466 struct remote_state *rs = get_remote_state ();
5467 char *next;
5468 int i;
5469 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5470
5471 /* The packet support flags are handled differently for this packet
5472 than for most others. We treat an error, a disabled packet, and
5473 an empty response identically: any features which must be reported
5474 to be used will be automatically disabled. An empty buffer
5475 accomplishes this, since that is also the representation for a list
5476 containing no features. */
5477
5478 rs->buf[0] = 0;
5479 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5480 {
5481 std::string q;
5482
5483 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5484 remote_query_supported_append (&q, "multiprocess+");
5485
5486 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5487 remote_query_supported_append (&q, "swbreak+");
5488 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5489 remote_query_supported_append (&q, "hwbreak+");
5490
5491 remote_query_supported_append (&q, "qRelocInsn+");
5492
5493 if (packet_set_cmd_state (PACKET_fork_event_feature)
5494 != AUTO_BOOLEAN_FALSE)
5495 remote_query_supported_append (&q, "fork-events+");
5496 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5497 != AUTO_BOOLEAN_FALSE)
5498 remote_query_supported_append (&q, "vfork-events+");
5499 if (packet_set_cmd_state (PACKET_exec_event_feature)
5500 != AUTO_BOOLEAN_FALSE)
5501 remote_query_supported_append (&q, "exec-events+");
5502
5503 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5504 remote_query_supported_append (&q, "vContSupported+");
5505
5506 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5507 remote_query_supported_append (&q, "QThreadEvents+");
5508
5509 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5510 remote_query_supported_append (&q, "no-resumed+");
5511
5512 if (packet_set_cmd_state (PACKET_memory_tagging_feature)
5513 != AUTO_BOOLEAN_FALSE)
5514 remote_query_supported_append (&q, "memory-tagging+");
5515
5516 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5517 the qSupported:xmlRegisters=i386 handling. */
5518 if (remote_support_xml != NULL
5519 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5520 remote_query_supported_append (&q, remote_support_xml);
5521
5522 q = "qSupported:" + q;
5523 putpkt (q.c_str ());
5524
5525 getpkt (&rs->buf, 0);
5526
5527 /* If an error occured, warn, but do not return - just reset the
5528 buffer to empty and go on to disable features. */
5529 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5530 == PACKET_ERROR)
5531 {
5532 warning (_("Remote failure reply: %s"), rs->buf.data ());
5533 rs->buf[0] = 0;
5534 }
5535 }
5536
5537 memset (seen, 0, sizeof (seen));
5538
5539 next = rs->buf.data ();
5540 while (*next)
5541 {
5542 enum packet_support is_supported;
5543 char *p, *end, *name_end, *value;
5544
5545 /* First separate out this item from the rest of the packet. If
5546 there's another item after this, we overwrite the separator
5547 (terminated strings are much easier to work with). */
5548 p = next;
5549 end = strchr (p, ';');
5550 if (end == NULL)
5551 {
5552 end = p + strlen (p);
5553 next = end;
5554 }
5555 else
5556 {
5557 *end = '\0';
5558 next = end + 1;
5559
5560 if (end == p)
5561 {
5562 warning (_("empty item in \"qSupported\" response"));
5563 continue;
5564 }
5565 }
5566
5567 name_end = strchr (p, '=');
5568 if (name_end)
5569 {
5570 /* This is a name=value entry. */
5571 is_supported = PACKET_ENABLE;
5572 value = name_end + 1;
5573 *name_end = '\0';
5574 }
5575 else
5576 {
5577 value = NULL;
5578 switch (end[-1])
5579 {
5580 case '+':
5581 is_supported = PACKET_ENABLE;
5582 break;
5583
5584 case '-':
5585 is_supported = PACKET_DISABLE;
5586 break;
5587
5588 case '?':
5589 is_supported = PACKET_SUPPORT_UNKNOWN;
5590 break;
5591
5592 default:
5593 warning (_("unrecognized item \"%s\" "
5594 "in \"qSupported\" response"), p);
5595 continue;
5596 }
5597 end[-1] = '\0';
5598 }
5599
5600 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5601 if (strcmp (remote_protocol_features[i].name, p) == 0)
5602 {
5603 const struct protocol_feature *feature;
5604
5605 seen[i] = 1;
5606 feature = &remote_protocol_features[i];
5607 feature->func (this, feature, is_supported, value);
5608 break;
5609 }
5610 }
5611
5612 /* If we increased the packet size, make sure to increase the global
5613 buffer size also. We delay this until after parsing the entire
5614 qSupported packet, because this is the same buffer we were
5615 parsing. */
5616 if (rs->buf.size () < rs->explicit_packet_size)
5617 rs->buf.resize (rs->explicit_packet_size);
5618
5619 /* Handle the defaults for unmentioned features. */
5620 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5621 if (!seen[i])
5622 {
5623 const struct protocol_feature *feature;
5624
5625 feature = &remote_protocol_features[i];
5626 feature->func (this, feature, feature->default_support, NULL);
5627 }
5628 }
5629
5630 /* Serial QUIT handler for the remote serial descriptor.
5631
5632 Defers handling a Ctrl-C until we're done with the current
5633 command/response packet sequence, unless:
5634
5635 - We're setting up the connection. Don't send a remote interrupt
5636 request, as we're not fully synced yet. Quit immediately
5637 instead.
5638
5639 - The target has been resumed in the foreground
5640 (target_terminal::is_ours is false) with a synchronous resume
5641 packet, and we're blocked waiting for the stop reply, thus a
5642 Ctrl-C should be immediately sent to the target.
5643
5644 - We get a second Ctrl-C while still within the same serial read or
5645 write. In that case the serial is seemingly wedged --- offer to
5646 quit/disconnect.
5647
5648 - We see a second Ctrl-C without target response, after having
5649 previously interrupted the target. In that case the target/stub
5650 is probably wedged --- offer to quit/disconnect.
5651 */
5652
5653 void
5654 remote_target::remote_serial_quit_handler ()
5655 {
5656 struct remote_state *rs = get_remote_state ();
5657
5658 if (check_quit_flag ())
5659 {
5660 /* If we're starting up, we're not fully synced yet. Quit
5661 immediately. */
5662 if (rs->starting_up)
5663 quit ();
5664 else if (rs->got_ctrlc_during_io)
5665 {
5666 if (query (_("The target is not responding to GDB commands.\n"
5667 "Stop debugging it? ")))
5668 remote_unpush_and_throw (this);
5669 }
5670 /* If ^C has already been sent once, offer to disconnect. */
5671 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5672 interrupt_query ();
5673 /* All-stop protocol, and blocked waiting for stop reply. Send
5674 an interrupt request. */
5675 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5676 target_interrupt ();
5677 else
5678 rs->got_ctrlc_during_io = 1;
5679 }
5680 }
5681
5682 /* The remote_target that is current while the quit handler is
5683 overridden with remote_serial_quit_handler. */
5684 static remote_target *curr_quit_handler_target;
5685
5686 static void
5687 remote_serial_quit_handler ()
5688 {
5689 curr_quit_handler_target->remote_serial_quit_handler ();
5690 }
5691
5692 /* Remove the remote target from the target stack of each inferior
5693 that is using it. Upper targets depend on it so remove them
5694 first. */
5695
5696 static void
5697 remote_unpush_target (remote_target *target)
5698 {
5699 /* We have to unpush the target from all inferiors, even those that
5700 aren't running. */
5701 scoped_restore_current_inferior restore_current_inferior;
5702
5703 for (inferior *inf : all_inferiors (target))
5704 {
5705 switch_to_inferior_no_thread (inf);
5706 pop_all_targets_at_and_above (process_stratum);
5707 generic_mourn_inferior ();
5708 }
5709
5710 /* Don't rely on target_close doing this when the target is popped
5711 from the last remote inferior above, because something may be
5712 holding a reference to the target higher up on the stack, meaning
5713 target_close won't be called yet. We lost the connection to the
5714 target, so clear these now, otherwise we may later throw
5715 TARGET_CLOSE_ERROR while trying to tell the remote target to
5716 close the file. */
5717 fileio_handles_invalidate_target (target);
5718 }
5719
5720 static void
5721 remote_unpush_and_throw (remote_target *target)
5722 {
5723 remote_unpush_target (target);
5724 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5725 }
5726
5727 void
5728 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5729 {
5730 remote_target *curr_remote = get_current_remote_target ();
5731
5732 if (name == 0)
5733 error (_("To open a remote debug connection, you need to specify what\n"
5734 "serial device is attached to the remote system\n"
5735 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5736
5737 /* If we're connected to a running target, target_preopen will kill it.
5738 Ask this question first, before target_preopen has a chance to kill
5739 anything. */
5740 if (curr_remote != NULL && !target_has_execution ())
5741 {
5742 if (from_tty
5743 && !query (_("Already connected to a remote target. Disconnect? ")))
5744 error (_("Still connected."));
5745 }
5746
5747 /* Here the possibly existing remote target gets unpushed. */
5748 target_preopen (from_tty);
5749
5750 remote_fileio_reset ();
5751 reopen_exec_file ();
5752 reread_symbols (from_tty);
5753
5754 remote_target *remote
5755 = (extended_p ? new extended_remote_target () : new remote_target ());
5756 target_ops_up target_holder (remote);
5757
5758 remote_state *rs = remote->get_remote_state ();
5759
5760 /* See FIXME above. */
5761 if (!target_async_permitted)
5762 rs->wait_forever_enabled_p = 1;
5763
5764 rs->remote_desc = remote_serial_open (name);
5765 if (!rs->remote_desc)
5766 perror_with_name (name);
5767
5768 if (baud_rate != -1)
5769 {
5770 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5771 {
5772 /* The requested speed could not be set. Error out to
5773 top level after closing remote_desc. Take care to
5774 set remote_desc to NULL to avoid closing remote_desc
5775 more than once. */
5776 serial_close (rs->remote_desc);
5777 rs->remote_desc = NULL;
5778 perror_with_name (name);
5779 }
5780 }
5781
5782 serial_setparity (rs->remote_desc, serial_parity);
5783 serial_raw (rs->remote_desc);
5784
5785 /* If there is something sitting in the buffer we might take it as a
5786 response to a command, which would be bad. */
5787 serial_flush_input (rs->remote_desc);
5788
5789 if (from_tty)
5790 {
5791 gdb_puts ("Remote debugging using ");
5792 gdb_puts (name);
5793 gdb_puts ("\n");
5794 }
5795
5796 /* Switch to using the remote target now. */
5797 current_inferior ()->push_target (std::move (target_holder));
5798
5799 /* Register extra event sources in the event loop. */
5800 rs->remote_async_inferior_event_token
5801 = create_async_event_handler (remote_async_inferior_event_handler, nullptr,
5802 "remote");
5803 rs->notif_state = remote_notif_state_allocate (remote);
5804
5805 /* Reset the target state; these things will be queried either by
5806 remote_query_supported or as they are needed. */
5807 reset_all_packet_configs_support ();
5808 rs->explicit_packet_size = 0;
5809 rs->noack_mode = 0;
5810 rs->extended = extended_p;
5811 rs->waiting_for_stop_reply = 0;
5812 rs->ctrlc_pending_p = 0;
5813 rs->got_ctrlc_during_io = 0;
5814
5815 rs->general_thread = not_sent_ptid;
5816 rs->continue_thread = not_sent_ptid;
5817 rs->remote_traceframe_number = -1;
5818
5819 rs->last_resume_exec_dir = EXEC_FORWARD;
5820
5821 /* Probe for ability to use "ThreadInfo" query, as required. */
5822 rs->use_threadinfo_query = 1;
5823 rs->use_threadextra_query = 1;
5824
5825 rs->readahead_cache.invalidate ();
5826
5827 if (target_async_permitted)
5828 {
5829 /* FIXME: cagney/1999-09-23: During the initial connection it is
5830 assumed that the target is already ready and able to respond to
5831 requests. Unfortunately remote_start_remote() eventually calls
5832 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5833 around this. Eventually a mechanism that allows
5834 wait_for_inferior() to expect/get timeouts will be
5835 implemented. */
5836 rs->wait_forever_enabled_p = 0;
5837 }
5838
5839 /* First delete any symbols previously loaded from shared libraries. */
5840 no_shared_libraries (NULL, 0);
5841
5842 /* Start the remote connection. If error() or QUIT, discard this
5843 target (we'd otherwise be in an inconsistent state) and then
5844 propogate the error on up the exception chain. This ensures that
5845 the caller doesn't stumble along blindly assuming that the
5846 function succeeded. The CLI doesn't have this problem but other
5847 UI's, such as MI do.
5848
5849 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5850 this function should return an error indication letting the
5851 caller restore the previous state. Unfortunately the command
5852 ``target remote'' is directly wired to this function making that
5853 impossible. On a positive note, the CLI side of this problem has
5854 been fixed - the function set_cmd_context() makes it possible for
5855 all the ``target ....'' commands to share a common callback
5856 function. See cli-dump.c. */
5857 {
5858
5859 try
5860 {
5861 remote->start_remote (from_tty, extended_p);
5862 }
5863 catch (const gdb_exception &ex)
5864 {
5865 /* Pop the partially set up target - unless something else did
5866 already before throwing the exception. */
5867 if (ex.error != TARGET_CLOSE_ERROR)
5868 remote_unpush_target (remote);
5869 throw;
5870 }
5871 }
5872
5873 remote_btrace_reset (rs);
5874
5875 if (target_async_permitted)
5876 rs->wait_forever_enabled_p = 1;
5877 }
5878
5879 /* Determine if WS represents a fork status. */
5880
5881 static bool
5882 is_fork_status (target_waitkind kind)
5883 {
5884 return (kind == TARGET_WAITKIND_FORKED
5885 || kind == TARGET_WAITKIND_VFORKED);
5886 }
5887
5888 /* Return THREAD's pending status if it is a pending fork parent, else
5889 return nullptr. */
5890
5891 static const target_waitstatus *
5892 thread_pending_fork_status (struct thread_info *thread)
5893 {
5894 const target_waitstatus &ws
5895 = (thread->has_pending_waitstatus ()
5896 ? thread->pending_waitstatus ()
5897 : thread->pending_follow);
5898
5899 if (!is_fork_status (ws.kind ()))
5900 return nullptr;
5901
5902 return &ws;
5903 }
5904
5905 /* Detach the specified process. */
5906
5907 void
5908 remote_target::remote_detach_pid (int pid)
5909 {
5910 struct remote_state *rs = get_remote_state ();
5911
5912 /* This should not be necessary, but the handling for D;PID in
5913 GDBserver versions prior to 8.2 incorrectly assumes that the
5914 selected process points to the same process we're detaching,
5915 leading to misbehavior (and possibly GDBserver crashing) when it
5916 does not. Since it's easy and cheap, work around it by forcing
5917 GDBserver to select GDB's current process. */
5918 set_general_process ();
5919
5920 if (remote_multi_process_p (rs))
5921 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
5922 else
5923 strcpy (rs->buf.data (), "D");
5924
5925 putpkt (rs->buf);
5926 getpkt (&rs->buf, 0);
5927
5928 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5929 ;
5930 else if (rs->buf[0] == '\0')
5931 error (_("Remote doesn't know how to detach"));
5932 else
5933 error (_("Can't detach process."));
5934 }
5935
5936 /* This detaches a program to which we previously attached, using
5937 inferior_ptid to identify the process. After this is done, GDB
5938 can be used to debug some other program. We better not have left
5939 any breakpoints in the target program or it'll die when it hits
5940 one. */
5941
5942 void
5943 remote_target::remote_detach_1 (inferior *inf, int from_tty)
5944 {
5945 int pid = inferior_ptid.pid ();
5946 struct remote_state *rs = get_remote_state ();
5947 int is_fork_parent;
5948
5949 if (!target_has_execution ())
5950 error (_("No process to detach from."));
5951
5952 target_announce_detach (from_tty);
5953
5954 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
5955 {
5956 /* If we're in breakpoints-always-inserted mode, or the inferior
5957 is running, we have to remove breakpoints before detaching.
5958 We don't do this in common code instead because not all
5959 targets support removing breakpoints while the target is
5960 running. The remote target / gdbserver does, though. */
5961 remove_breakpoints_inf (current_inferior ());
5962 }
5963
5964 /* Tell the remote target to detach. */
5965 remote_detach_pid (pid);
5966
5967 /* Exit only if this is the only active inferior. */
5968 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
5969 gdb_puts (_("Ending remote debugging.\n"));
5970
5971 /* See if any thread of the inferior we are detaching has a pending fork
5972 status. In that case, we must detach from the child resulting from
5973 that fork. */
5974 for (thread_info *thread : inf->non_exited_threads ())
5975 {
5976 const target_waitstatus *ws = thread_pending_fork_status (thread);
5977
5978 if (ws == nullptr)
5979 continue;
5980
5981 remote_detach_pid (ws->child_ptid ().pid ());
5982 }
5983
5984 /* Check also for any pending fork events in the stop reply queue. */
5985 remote_notif_get_pending_events (&notif_client_stop);
5986 for (stop_reply_up &reply : rs->stop_reply_queue)
5987 {
5988 if (reply->ptid.pid () != pid)
5989 continue;
5990
5991 if (!is_fork_status (reply->ws.kind ()))
5992 continue;
5993
5994 remote_detach_pid (reply->ws.child_ptid ().pid ());
5995 }
5996
5997 thread_info *tp = find_thread_ptid (this, inferior_ptid);
5998
5999 /* Check to see if we are detaching a fork parent. Note that if we
6000 are detaching a fork child, tp == NULL. */
6001 is_fork_parent = (tp != NULL
6002 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
6003
6004 /* If doing detach-on-fork, we don't mourn, because that will delete
6005 breakpoints that should be available for the followed inferior. */
6006 if (!is_fork_parent)
6007 {
6008 /* Save the pid as a string before mourning, since that will
6009 unpush the remote target, and we need the string after. */
6010 std::string infpid = target_pid_to_str (ptid_t (pid));
6011
6012 target_mourn_inferior (inferior_ptid);
6013 if (print_inferior_events)
6014 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6015 inf->num, infpid.c_str ());
6016 }
6017 else
6018 {
6019 switch_to_no_thread ();
6020 detach_inferior (current_inferior ());
6021 }
6022 }
6023
6024 void
6025 remote_target::detach (inferior *inf, int from_tty)
6026 {
6027 remote_detach_1 (inf, from_tty);
6028 }
6029
6030 void
6031 extended_remote_target::detach (inferior *inf, int from_tty)
6032 {
6033 remote_detach_1 (inf, from_tty);
6034 }
6035
6036 /* Target follow-fork function for remote targets. On entry, and
6037 at return, the current inferior is the fork parent.
6038
6039 Note that although this is currently only used for extended-remote,
6040 it is named remote_follow_fork in anticipation of using it for the
6041 remote target as well. */
6042
6043 void
6044 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6045 target_waitkind fork_kind, bool follow_child,
6046 bool detach_fork)
6047 {
6048 process_stratum_target::follow_fork (child_inf, child_ptid,
6049 fork_kind, follow_child, detach_fork);
6050
6051 struct remote_state *rs = get_remote_state ();
6052
6053 if ((fork_kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
6054 || (fork_kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
6055 {
6056 /* When following the parent and detaching the child, we detach
6057 the child here. For the case of following the child and
6058 detaching the parent, the detach is done in the target-
6059 independent follow fork code in infrun.c. We can't use
6060 target_detach when detaching an unfollowed child because
6061 the client side doesn't know anything about the child. */
6062 if (detach_fork && !follow_child)
6063 {
6064 /* Detach the fork child. */
6065 remote_detach_pid (child_ptid.pid ());
6066 }
6067 }
6068 }
6069
6070 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6071 in the program space of the new inferior. */
6072
6073 void
6074 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6075 const char *execd_pathname)
6076 {
6077 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6078
6079 /* We know that this is a target file name, so if it has the "target:"
6080 prefix we strip it off before saving it in the program space. */
6081 if (is_target_filename (execd_pathname))
6082 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6083
6084 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6085 }
6086
6087 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6088
6089 void
6090 remote_target::disconnect (const char *args, int from_tty)
6091 {
6092 if (args)
6093 error (_("Argument given to \"disconnect\" when remotely debugging."));
6094
6095 /* Make sure we unpush even the extended remote targets. Calling
6096 target_mourn_inferior won't unpush, and
6097 remote_target::mourn_inferior won't unpush if there is more than
6098 one inferior left. */
6099 remote_unpush_target (this);
6100
6101 if (from_tty)
6102 gdb_puts ("Ending remote debugging.\n");
6103 }
6104
6105 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6106 be chatty about it. */
6107
6108 void
6109 extended_remote_target::attach (const char *args, int from_tty)
6110 {
6111 struct remote_state *rs = get_remote_state ();
6112 int pid;
6113 char *wait_status = NULL;
6114
6115 pid = parse_pid_to_attach (args);
6116
6117 /* Remote PID can be freely equal to getpid, do not check it here the same
6118 way as in other targets. */
6119
6120 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
6121 error (_("This target does not support attaching to a process"));
6122
6123 target_announce_attach (from_tty, pid);
6124
6125 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6126 putpkt (rs->buf);
6127 getpkt (&rs->buf, 0);
6128
6129 switch (packet_ok (rs->buf,
6130 &remote_protocol_packets[PACKET_vAttach]))
6131 {
6132 case PACKET_OK:
6133 if (!target_is_non_stop_p ())
6134 {
6135 /* Save the reply for later. */
6136 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6137 strcpy (wait_status, rs->buf.data ());
6138 }
6139 else if (strcmp (rs->buf.data (), "OK") != 0)
6140 error (_("Attaching to %s failed with: %s"),
6141 target_pid_to_str (ptid_t (pid)).c_str (),
6142 rs->buf.data ());
6143 break;
6144 case PACKET_UNKNOWN:
6145 error (_("This target does not support attaching to a process"));
6146 default:
6147 error (_("Attaching to %s failed"),
6148 target_pid_to_str (ptid_t (pid)).c_str ());
6149 }
6150
6151 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6152
6153 inferior_ptid = ptid_t (pid);
6154
6155 if (target_is_non_stop_p ())
6156 {
6157 /* Get list of threads. */
6158 update_thread_list ();
6159
6160 thread_info *thread = first_thread_of_inferior (current_inferior ());
6161 if (thread != nullptr)
6162 switch_to_thread (thread);
6163
6164 /* Invalidate our notion of the remote current thread. */
6165 record_currthread (rs, minus_one_ptid);
6166 }
6167 else
6168 {
6169 /* Now, if we have thread information, update the main thread's
6170 ptid. */
6171 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6172
6173 /* Add the main thread to the thread list. We add the thread
6174 silently in this case (the final true parameter). */
6175 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
6176
6177 switch_to_thread (thr);
6178 }
6179
6180 /* Next, if the target can specify a description, read it. We do
6181 this before anything involving memory or registers. */
6182 target_find_description ();
6183
6184 if (!target_is_non_stop_p ())
6185 {
6186 /* Use the previously fetched status. */
6187 gdb_assert (wait_status != NULL);
6188
6189 struct notif_event *reply
6190 = remote_notif_parse (this, &notif_client_stop, wait_status);
6191
6192 push_stop_reply ((struct stop_reply *) reply);
6193 }
6194 else
6195 {
6196 gdb_assert (wait_status == NULL);
6197
6198 gdb_assert (target_can_async_p ());
6199 }
6200 }
6201
6202 /* Implementation of the to_post_attach method. */
6203
6204 void
6205 extended_remote_target::post_attach (int pid)
6206 {
6207 /* Get text, data & bss offsets. */
6208 get_offsets ();
6209
6210 /* In certain cases GDB might not have had the chance to start
6211 symbol lookup up until now. This could happen if the debugged
6212 binary is not using shared libraries, the vsyscall page is not
6213 present (on Linux) and the binary itself hadn't changed since the
6214 debugging process was started. */
6215 if (current_program_space->symfile_object_file != NULL)
6216 remote_check_symbols();
6217 }
6218
6219 \f
6220 /* Check for the availability of vCont. This function should also check
6221 the response. */
6222
6223 void
6224 remote_target::remote_vcont_probe ()
6225 {
6226 remote_state *rs = get_remote_state ();
6227 char *buf;
6228
6229 strcpy (rs->buf.data (), "vCont?");
6230 putpkt (rs->buf);
6231 getpkt (&rs->buf, 0);
6232 buf = rs->buf.data ();
6233
6234 /* Make sure that the features we assume are supported. */
6235 if (startswith (buf, "vCont"))
6236 {
6237 char *p = &buf[5];
6238 int support_c, support_C;
6239
6240 rs->supports_vCont.s = 0;
6241 rs->supports_vCont.S = 0;
6242 support_c = 0;
6243 support_C = 0;
6244 rs->supports_vCont.t = 0;
6245 rs->supports_vCont.r = 0;
6246 while (p && *p == ';')
6247 {
6248 p++;
6249 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6250 rs->supports_vCont.s = 1;
6251 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6252 rs->supports_vCont.S = 1;
6253 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6254 support_c = 1;
6255 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6256 support_C = 1;
6257 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6258 rs->supports_vCont.t = 1;
6259 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6260 rs->supports_vCont.r = 1;
6261
6262 p = strchr (p, ';');
6263 }
6264
6265 /* If c, and C are not all supported, we can't use vCont. Clearing
6266 BUF will make packet_ok disable the packet. */
6267 if (!support_c || !support_C)
6268 buf[0] = 0;
6269 }
6270
6271 packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCont]);
6272 rs->supports_vCont_probed = true;
6273 }
6274
6275 /* Helper function for building "vCont" resumptions. Write a
6276 resumption to P. ENDP points to one-passed-the-end of the buffer
6277 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6278 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6279 resumed thread should be single-stepped and/or signalled. If PTID
6280 equals minus_one_ptid, then all threads are resumed; if PTID
6281 represents a process, then all threads of the process are
6282 resumed. */
6283
6284 char *
6285 remote_target::append_resumption (char *p, char *endp,
6286 ptid_t ptid, int step, gdb_signal siggnal)
6287 {
6288 struct remote_state *rs = get_remote_state ();
6289
6290 if (step && siggnal != GDB_SIGNAL_0)
6291 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6292 else if (step
6293 /* GDB is willing to range step. */
6294 && use_range_stepping
6295 /* Target supports range stepping. */
6296 && rs->supports_vCont.r
6297 /* We don't currently support range stepping multiple
6298 threads with a wildcard (though the protocol allows it,
6299 so stubs shouldn't make an active effort to forbid
6300 it). */
6301 && !(remote_multi_process_p (rs) && ptid.is_pid ()))
6302 {
6303 struct thread_info *tp;
6304
6305 if (ptid == minus_one_ptid)
6306 {
6307 /* If we don't know about the target thread's tid, then
6308 we're resuming magic_null_ptid (see caller). */
6309 tp = find_thread_ptid (this, magic_null_ptid);
6310 }
6311 else
6312 tp = find_thread_ptid (this, ptid);
6313 gdb_assert (tp != NULL);
6314
6315 if (tp->control.may_range_step)
6316 {
6317 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6318
6319 p += xsnprintf (p, endp - p, ";r%s,%s",
6320 phex_nz (tp->control.step_range_start,
6321 addr_size),
6322 phex_nz (tp->control.step_range_end,
6323 addr_size));
6324 }
6325 else
6326 p += xsnprintf (p, endp - p, ";s");
6327 }
6328 else if (step)
6329 p += xsnprintf (p, endp - p, ";s");
6330 else if (siggnal != GDB_SIGNAL_0)
6331 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6332 else
6333 p += xsnprintf (p, endp - p, ";c");
6334
6335 if (remote_multi_process_p (rs) && ptid.is_pid ())
6336 {
6337 ptid_t nptid;
6338
6339 /* All (-1) threads of process. */
6340 nptid = ptid_t (ptid.pid (), -1);
6341
6342 p += xsnprintf (p, endp - p, ":");
6343 p = write_ptid (p, endp, nptid);
6344 }
6345 else if (ptid != minus_one_ptid)
6346 {
6347 p += xsnprintf (p, endp - p, ":");
6348 p = write_ptid (p, endp, ptid);
6349 }
6350
6351 return p;
6352 }
6353
6354 /* Clear the thread's private info on resume. */
6355
6356 static void
6357 resume_clear_thread_private_info (struct thread_info *thread)
6358 {
6359 if (thread->priv != NULL)
6360 {
6361 remote_thread_info *priv = get_remote_thread_info (thread);
6362
6363 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6364 priv->watch_data_address = 0;
6365 }
6366 }
6367
6368 /* Append a vCont continue-with-signal action for threads that have a
6369 non-zero stop signal. */
6370
6371 char *
6372 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6373 ptid_t ptid)
6374 {
6375 for (thread_info *thread : all_non_exited_threads (this, ptid))
6376 if (inferior_ptid != thread->ptid
6377 && thread->stop_signal () != GDB_SIGNAL_0)
6378 {
6379 p = append_resumption (p, endp, thread->ptid,
6380 0, thread->stop_signal ());
6381 thread->set_stop_signal (GDB_SIGNAL_0);
6382 resume_clear_thread_private_info (thread);
6383 }
6384
6385 return p;
6386 }
6387
6388 /* Set the target running, using the packets that use Hc
6389 (c/s/C/S). */
6390
6391 void
6392 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6393 gdb_signal siggnal)
6394 {
6395 struct remote_state *rs = get_remote_state ();
6396 char *buf;
6397
6398 rs->last_sent_signal = siggnal;
6399 rs->last_sent_step = step;
6400
6401 /* The c/s/C/S resume packets use Hc, so set the continue
6402 thread. */
6403 if (ptid == minus_one_ptid)
6404 set_continue_thread (any_thread_ptid);
6405 else
6406 set_continue_thread (ptid);
6407
6408 for (thread_info *thread : all_non_exited_threads (this))
6409 resume_clear_thread_private_info (thread);
6410
6411 buf = rs->buf.data ();
6412 if (::execution_direction == EXEC_REVERSE)
6413 {
6414 /* We don't pass signals to the target in reverse exec mode. */
6415 if (info_verbose && siggnal != GDB_SIGNAL_0)
6416 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6417 siggnal);
6418
6419 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6420 error (_("Remote reverse-step not supported."));
6421 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6422 error (_("Remote reverse-continue not supported."));
6423
6424 strcpy (buf, step ? "bs" : "bc");
6425 }
6426 else if (siggnal != GDB_SIGNAL_0)
6427 {
6428 buf[0] = step ? 'S' : 'C';
6429 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6430 buf[2] = tohex (((int) siggnal) & 0xf);
6431 buf[3] = '\0';
6432 }
6433 else
6434 strcpy (buf, step ? "s" : "c");
6435
6436 putpkt (buf);
6437 }
6438
6439 /* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6440 STEP, and SIGGNAL have the same meaning as in target_resume. This
6441 function returns non-zero iff it resumes the inferior.
6442
6443 This function issues a strict subset of all possible vCont commands
6444 at the moment. */
6445
6446 int
6447 remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6448 enum gdb_signal siggnal)
6449 {
6450 struct remote_state *rs = get_remote_state ();
6451 char *p;
6452 char *endp;
6453
6454 /* No reverse execution actions defined for vCont. */
6455 if (::execution_direction == EXEC_REVERSE)
6456 return 0;
6457
6458 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6459 remote_vcont_probe ();
6460
6461 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6462 return 0;
6463
6464 p = rs->buf.data ();
6465 endp = p + get_remote_packet_size ();
6466
6467 /* If we could generate a wider range of packets, we'd have to worry
6468 about overflowing BUF. Should there be a generic
6469 "multi-part-packet" packet? */
6470
6471 p += xsnprintf (p, endp - p, "vCont");
6472
6473 if (scope_ptid == magic_null_ptid)
6474 {
6475 /* MAGIC_NULL_PTID means that we don't have any active threads,
6476 so we don't have any TID numbers the inferior will
6477 understand. Make sure to only send forms that do not specify
6478 a TID. */
6479 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6480 }
6481 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
6482 {
6483 /* Resume all threads (of all processes, or of a single
6484 process), with preference for INFERIOR_PTID. This assumes
6485 inferior_ptid belongs to the set of all threads we are about
6486 to resume. */
6487 if (step || siggnal != GDB_SIGNAL_0)
6488 {
6489 /* Step inferior_ptid, with or without signal. */
6490 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6491 }
6492
6493 /* Also pass down any pending signaled resumption for other
6494 threads not the current. */
6495 p = append_pending_thread_resumptions (p, endp, scope_ptid);
6496
6497 /* And continue others without a signal. */
6498 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
6499 }
6500 else
6501 {
6502 /* Scheduler locking; resume only SCOPE_PTID. */
6503 append_resumption (p, endp, scope_ptid, step, siggnal);
6504 }
6505
6506 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6507 putpkt (rs->buf);
6508
6509 if (target_is_non_stop_p ())
6510 {
6511 /* In non-stop, the stub replies to vCont with "OK". The stop
6512 reply will be reported asynchronously by means of a `%Stop'
6513 notification. */
6514 getpkt (&rs->buf, 0);
6515 if (strcmp (rs->buf.data (), "OK") != 0)
6516 error (_("Unexpected vCont reply in non-stop mode: %s"),
6517 rs->buf.data ());
6518 }
6519
6520 return 1;
6521 }
6522
6523 /* Tell the remote machine to resume. */
6524
6525 void
6526 remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
6527 {
6528 struct remote_state *rs = get_remote_state ();
6529
6530 /* When connected in non-stop mode, the core resumes threads
6531 individually. Resuming remote threads directly in target_resume
6532 would thus result in sending one packet per thread. Instead, to
6533 minimize roundtrip latency, here we just store the resume
6534 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6535 resumption will be done in remote_target::commit_resume, where we'll be
6536 able to do vCont action coalescing. */
6537 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6538 {
6539 remote_thread_info *remote_thr
6540 = get_remote_thread_info (inferior_thread ());
6541
6542 /* We don't expect the core to ask to resume an already resumed (from
6543 its point of view) thread. */
6544 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6545
6546 remote_thr->set_resumed_pending_vcont (step, siggnal);
6547
6548 /* There's actually nothing that says that the core can't
6549 request a wildcard resume in non-stop mode, though. It's
6550 just that we know it doesn't currently, so we don't bother
6551 with it. */
6552 gdb_assert (scope_ptid == inferior_ptid);
6553 return;
6554 }
6555
6556 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6557 (explained in remote-notif.c:handle_notification) so
6558 remote_notif_process is not called. We need find a place where
6559 it is safe to start a 'vNotif' sequence. It is good to do it
6560 before resuming inferior, because inferior was stopped and no RSP
6561 traffic at that moment. */
6562 if (!target_is_non_stop_p ())
6563 remote_notif_process (rs->notif_state, &notif_client_stop);
6564
6565 rs->last_resume_exec_dir = ::execution_direction;
6566
6567 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6568 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
6569 remote_resume_with_hc (scope_ptid, step, siggnal);
6570
6571 /* Update resumed state tracked by the remote target. */
6572 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
6573 get_remote_thread_info (tp)->set_resumed ();
6574
6575 /* We've just told the target to resume. The remote server will
6576 wait for the inferior to stop, and then send a stop reply. In
6577 the mean time, we can't start another command/query ourselves
6578 because the stub wouldn't be ready to process it. This applies
6579 only to the base all-stop protocol, however. In non-stop (which
6580 only supports vCont), the stub replies with an "OK", and is
6581 immediate able to process further serial input. */
6582 if (!target_is_non_stop_p ())
6583 rs->waiting_for_stop_reply = 1;
6584 }
6585
6586 /* Private per-inferior info for target remote processes. */
6587
6588 struct remote_inferior : public private_inferior
6589 {
6590 /* Whether we can send a wildcard vCont for this process. */
6591 bool may_wildcard_vcont = true;
6592 };
6593
6594 /* Get the remote private inferior data associated to INF. */
6595
6596 static remote_inferior *
6597 get_remote_inferior (inferior *inf)
6598 {
6599 if (inf->priv == NULL)
6600 inf->priv.reset (new remote_inferior);
6601
6602 return static_cast<remote_inferior *> (inf->priv.get ());
6603 }
6604
6605 /* Class used to track the construction of a vCont packet in the
6606 outgoing packet buffer. This is used to send multiple vCont
6607 packets if we have more actions than would fit a single packet. */
6608
6609 class vcont_builder
6610 {
6611 public:
6612 explicit vcont_builder (remote_target *remote)
6613 : m_remote (remote)
6614 {
6615 restart ();
6616 }
6617
6618 void flush ();
6619 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6620
6621 private:
6622 void restart ();
6623
6624 /* The remote target. */
6625 remote_target *m_remote;
6626
6627 /* Pointer to the first action. P points here if no action has been
6628 appended yet. */
6629 char *m_first_action;
6630
6631 /* Where the next action will be appended. */
6632 char *m_p;
6633
6634 /* The end of the buffer. Must never write past this. */
6635 char *m_endp;
6636 };
6637
6638 /* Prepare the outgoing buffer for a new vCont packet. */
6639
6640 void
6641 vcont_builder::restart ()
6642 {
6643 struct remote_state *rs = m_remote->get_remote_state ();
6644
6645 m_p = rs->buf.data ();
6646 m_endp = m_p + m_remote->get_remote_packet_size ();
6647 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6648 m_first_action = m_p;
6649 }
6650
6651 /* If the vCont packet being built has any action, send it to the
6652 remote end. */
6653
6654 void
6655 vcont_builder::flush ()
6656 {
6657 struct remote_state *rs;
6658
6659 if (m_p == m_first_action)
6660 return;
6661
6662 rs = m_remote->get_remote_state ();
6663 m_remote->putpkt (rs->buf);
6664 m_remote->getpkt (&rs->buf, 0);
6665 if (strcmp (rs->buf.data (), "OK") != 0)
6666 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
6667 }
6668
6669 /* The largest action is range-stepping, with its two addresses. This
6670 is more than sufficient. If a new, bigger action is created, it'll
6671 quickly trigger a failed assertion in append_resumption (and we'll
6672 just bump this). */
6673 #define MAX_ACTION_SIZE 200
6674
6675 /* Append a new vCont action in the outgoing packet being built. If
6676 the action doesn't fit the packet along with previous actions, push
6677 what we've got so far to the remote end and start over a new vCont
6678 packet (with the new action). */
6679
6680 void
6681 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6682 {
6683 char buf[MAX_ACTION_SIZE + 1];
6684
6685 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6686 ptid, step, siggnal);
6687
6688 /* Check whether this new action would fit in the vCont packet along
6689 with previous actions. If not, send what we've got so far and
6690 start a new vCont packet. */
6691 size_t rsize = endp - buf;
6692 if (rsize > m_endp - m_p)
6693 {
6694 flush ();
6695 restart ();
6696
6697 /* Should now fit. */
6698 gdb_assert (rsize <= m_endp - m_p);
6699 }
6700
6701 memcpy (m_p, buf, rsize);
6702 m_p += rsize;
6703 *m_p = '\0';
6704 }
6705
6706 /* to_commit_resume implementation. */
6707
6708 void
6709 remote_target::commit_resumed ()
6710 {
6711 /* If connected in all-stop mode, we'd send the remote resume
6712 request directly from remote_resume. Likewise if
6713 reverse-debugging, as there are no defined vCont actions for
6714 reverse execution. */
6715 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6716 return;
6717
6718 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6719 instead of resuming all threads of each process individually.
6720 However, if any thread of a process must remain halted, we can't
6721 send wildcard resumes and must send one action per thread.
6722
6723 Care must be taken to not resume threads/processes the server
6724 side already told us are stopped, but the core doesn't know about
6725 yet, because the events are still in the vStopped notification
6726 queue. For example:
6727
6728 #1 => vCont s:p1.1;c
6729 #2 <= OK
6730 #3 <= %Stopped T05 p1.1
6731 #4 => vStopped
6732 #5 <= T05 p1.2
6733 #6 => vStopped
6734 #7 <= OK
6735 #8 (infrun handles the stop for p1.1 and continues stepping)
6736 #9 => vCont s:p1.1;c
6737
6738 The last vCont above would resume thread p1.2 by mistake, because
6739 the server has no idea that the event for p1.2 had not been
6740 handled yet.
6741
6742 The server side must similarly ignore resume actions for the
6743 thread that has a pending %Stopped notification (and any other
6744 threads with events pending), until GDB acks the notification
6745 with vStopped. Otherwise, e.g., the following case is
6746 mishandled:
6747
6748 #1 => g (or any other packet)
6749 #2 <= [registers]
6750 #3 <= %Stopped T05 p1.2
6751 #4 => vCont s:p1.1;c
6752 #5 <= OK
6753
6754 Above, the server must not resume thread p1.2. GDB can't know
6755 that p1.2 stopped until it acks the %Stopped notification, and
6756 since from GDB's perspective all threads should be running, it
6757 sends a "c" action.
6758
6759 Finally, special care must also be given to handling fork/vfork
6760 events. A (v)fork event actually tells us that two processes
6761 stopped -- the parent and the child. Until we follow the fork,
6762 we must not resume the child. Therefore, if we have a pending
6763 fork follow, we must not send a global wildcard resume action
6764 (vCont;c). We can still send process-wide wildcards though. */
6765
6766 /* Start by assuming a global wildcard (vCont;c) is possible. */
6767 bool may_global_wildcard_vcont = true;
6768
6769 /* And assume every process is individually wildcard-able too. */
6770 for (inferior *inf : all_non_exited_inferiors (this))
6771 {
6772 remote_inferior *priv = get_remote_inferior (inf);
6773
6774 priv->may_wildcard_vcont = true;
6775 }
6776
6777 /* Check for any pending events (not reported or processed yet) and
6778 disable process and global wildcard resumes appropriately. */
6779 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6780
6781 bool any_pending_vcont_resume = false;
6782
6783 for (thread_info *tp : all_non_exited_threads (this))
6784 {
6785 remote_thread_info *priv = get_remote_thread_info (tp);
6786
6787 /* If a thread of a process is not meant to be resumed, then we
6788 can't wildcard that process. */
6789 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
6790 {
6791 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6792
6793 /* And if we can't wildcard a process, we can't wildcard
6794 everything either. */
6795 may_global_wildcard_vcont = false;
6796 continue;
6797 }
6798
6799 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
6800 any_pending_vcont_resume = true;
6801
6802 /* If a thread is the parent of an unfollowed fork, then we
6803 can't do a global wildcard, as that would resume the fork
6804 child. */
6805 if (thread_pending_fork_status (tp) != nullptr)
6806 may_global_wildcard_vcont = false;
6807 }
6808
6809 /* We didn't have any resumed thread pending a vCont resume, so nothing to
6810 do. */
6811 if (!any_pending_vcont_resume)
6812 return;
6813
6814 /* Now let's build the vCont packet(s). Actions must be appended
6815 from narrower to wider scopes (thread -> process -> global). If
6816 we end up with too many actions for a single packet vcont_builder
6817 flushes the current vCont packet to the remote side and starts a
6818 new one. */
6819 struct vcont_builder vcont_builder (this);
6820
6821 /* Threads first. */
6822 for (thread_info *tp : all_non_exited_threads (this))
6823 {
6824 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6825
6826 /* If the thread was previously vCont-resumed, no need to send a specific
6827 action for it. If we didn't receive a resume request for it, don't
6828 send an action for it either. */
6829 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
6830 continue;
6831
6832 gdb_assert (!thread_is_in_step_over_chain (tp));
6833
6834 /* We should never be commit-resuming a thread that has a stop reply.
6835 Otherwise, we would end up reporting a stop event for a thread while
6836 it is running on the remote target. */
6837 remote_state *rs = get_remote_state ();
6838 for (const auto &stop_reply : rs->stop_reply_queue)
6839 gdb_assert (stop_reply->ptid != tp->ptid);
6840
6841 const resumed_pending_vcont_info &info
6842 = remote_thr->resumed_pending_vcont_info ();
6843
6844 /* Check if we need to send a specific action for this thread. If not,
6845 it will be included in a wildcard resume instead. */
6846 if (info.step || info.sig != GDB_SIGNAL_0
6847 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
6848 vcont_builder.push_action (tp->ptid, info.step, info.sig);
6849
6850 remote_thr->set_resumed ();
6851 }
6852
6853 /* Now check whether we can send any process-wide wildcard. This is
6854 to avoid sending a global wildcard in the case nothing is
6855 supposed to be resumed. */
6856 bool any_process_wildcard = false;
6857
6858 for (inferior *inf : all_non_exited_inferiors (this))
6859 {
6860 if (get_remote_inferior (inf)->may_wildcard_vcont)
6861 {
6862 any_process_wildcard = true;
6863 break;
6864 }
6865 }
6866
6867 if (any_process_wildcard)
6868 {
6869 /* If all processes are wildcard-able, then send a single "c"
6870 action, otherwise, send an "all (-1) threads of process"
6871 continue action for each running process, if any. */
6872 if (may_global_wildcard_vcont)
6873 {
6874 vcont_builder.push_action (minus_one_ptid,
6875 false, GDB_SIGNAL_0);
6876 }
6877 else
6878 {
6879 for (inferior *inf : all_non_exited_inferiors (this))
6880 {
6881 if (get_remote_inferior (inf)->may_wildcard_vcont)
6882 {
6883 vcont_builder.push_action (ptid_t (inf->pid),
6884 false, GDB_SIGNAL_0);
6885 }
6886 }
6887 }
6888 }
6889
6890 vcont_builder.flush ();
6891 }
6892
6893 /* Implementation of target_has_pending_events. */
6894
6895 bool
6896 remote_target::has_pending_events ()
6897 {
6898 if (target_can_async_p ())
6899 {
6900 remote_state *rs = get_remote_state ();
6901
6902 if (async_event_handler_marked (rs->remote_async_inferior_event_token))
6903 return true;
6904
6905 /* Note that BUFCNT can be negative, indicating sticky
6906 error. */
6907 if (rs->remote_desc->bufcnt != 0)
6908 return true;
6909 }
6910 return false;
6911 }
6912
6913 \f
6914
6915 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6916 thread, all threads of a remote process, or all threads of all
6917 processes. */
6918
6919 void
6920 remote_target::remote_stop_ns (ptid_t ptid)
6921 {
6922 struct remote_state *rs = get_remote_state ();
6923 char *p = rs->buf.data ();
6924 char *endp = p + get_remote_packet_size ();
6925
6926 /* If any thread that needs to stop was resumed but pending a vCont
6927 resume, generate a phony stop_reply. However, first check
6928 whether the thread wasn't resumed with a signal. Generating a
6929 phony stop in that case would result in losing the signal. */
6930 bool needs_commit = false;
6931 for (thread_info *tp : all_non_exited_threads (this, ptid))
6932 {
6933 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6934
6935 if (remote_thr->get_resume_state ()
6936 == resume_state::RESUMED_PENDING_VCONT)
6937 {
6938 const resumed_pending_vcont_info &info
6939 = remote_thr->resumed_pending_vcont_info ();
6940 if (info.sig != GDB_SIGNAL_0)
6941 {
6942 /* This signal must be forwarded to the inferior. We
6943 could commit-resume just this thread, but its simpler
6944 to just commit-resume everything. */
6945 needs_commit = true;
6946 break;
6947 }
6948 }
6949 }
6950
6951 if (needs_commit)
6952 commit_resumed ();
6953 else
6954 for (thread_info *tp : all_non_exited_threads (this, ptid))
6955 {
6956 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6957
6958 if (remote_thr->get_resume_state ()
6959 == resume_state::RESUMED_PENDING_VCONT)
6960 {
6961 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
6962 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
6963 tp->ptid.lwp (),
6964 pulongest (tp->ptid.tid ()));
6965
6966 /* Check that the thread wasn't resumed with a signal.
6967 Generating a phony stop would result in losing the
6968 signal. */
6969 const resumed_pending_vcont_info &info
6970 = remote_thr->resumed_pending_vcont_info ();
6971 gdb_assert (info.sig == GDB_SIGNAL_0);
6972
6973 stop_reply *sr = new stop_reply ();
6974 sr->ptid = tp->ptid;
6975 sr->rs = rs;
6976 sr->ws.set_stopped (GDB_SIGNAL_0);
6977 sr->arch = tp->inf->gdbarch;
6978 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6979 sr->watch_data_address = 0;
6980 sr->core = 0;
6981 this->push_stop_reply (sr);
6982
6983 /* Pretend that this thread was actually resumed on the
6984 remote target, then stopped. If we leave it in the
6985 RESUMED_PENDING_VCONT state and the commit_resumed
6986 method is called while the stop reply is still in the
6987 queue, we'll end up reporting a stop event to the core
6988 for that thread while it is running on the remote
6989 target... that would be bad. */
6990 remote_thr->set_resumed ();
6991 }
6992 }
6993
6994 /* FIXME: This supports_vCont_probed check is a workaround until
6995 packet_support is per-connection. */
6996 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN
6997 || !rs->supports_vCont_probed)
6998 remote_vcont_probe ();
6999
7000 if (!rs->supports_vCont.t)
7001 error (_("Remote server does not support stopping threads"));
7002
7003 if (ptid == minus_one_ptid
7004 || (!remote_multi_process_p (rs) && ptid.is_pid ()))
7005 p += xsnprintf (p, endp - p, "vCont;t");
7006 else
7007 {
7008 ptid_t nptid;
7009
7010 p += xsnprintf (p, endp - p, "vCont;t:");
7011
7012 if (ptid.is_pid ())
7013 /* All (-1) threads of process. */
7014 nptid = ptid_t (ptid.pid (), -1);
7015 else
7016 {
7017 /* Small optimization: if we already have a stop reply for
7018 this thread, no use in telling the stub we want this
7019 stopped. */
7020 if (peek_stop_reply (ptid))
7021 return;
7022
7023 nptid = ptid;
7024 }
7025
7026 write_ptid (p, endp, nptid);
7027 }
7028
7029 /* In non-stop, we get an immediate OK reply. The stop reply will
7030 come in asynchronously by notification. */
7031 putpkt (rs->buf);
7032 getpkt (&rs->buf, 0);
7033 if (strcmp (rs->buf.data (), "OK") != 0)
7034 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7035 rs->buf.data ());
7036 }
7037
7038 /* All-stop version of target_interrupt. Sends a break or a ^C to
7039 interrupt the remote target. It is undefined which thread of which
7040 process reports the interrupt. */
7041
7042 void
7043 remote_target::remote_interrupt_as ()
7044 {
7045 struct remote_state *rs = get_remote_state ();
7046
7047 rs->ctrlc_pending_p = 1;
7048
7049 /* If the inferior is stopped already, but the core didn't know
7050 about it yet, just ignore the request. The pending stop events
7051 will be collected in remote_wait. */
7052 if (stop_reply_queue_length () > 0)
7053 return;
7054
7055 /* Send interrupt_sequence to remote target. */
7056 send_interrupt_sequence ();
7057 }
7058
7059 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7060 the remote target. It is undefined which thread of which process
7061 reports the interrupt. Throws an error if the packet is not
7062 supported by the server. */
7063
7064 void
7065 remote_target::remote_interrupt_ns ()
7066 {
7067 struct remote_state *rs = get_remote_state ();
7068 char *p = rs->buf.data ();
7069 char *endp = p + get_remote_packet_size ();
7070
7071 xsnprintf (p, endp - p, "vCtrlC");
7072
7073 /* In non-stop, we get an immediate OK reply. The stop reply will
7074 come in asynchronously by notification. */
7075 putpkt (rs->buf);
7076 getpkt (&rs->buf, 0);
7077
7078 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
7079 {
7080 case PACKET_OK:
7081 break;
7082 case PACKET_UNKNOWN:
7083 error (_("No support for interrupting the remote target."));
7084 case PACKET_ERROR:
7085 error (_("Interrupting target failed: %s"), rs->buf.data ());
7086 }
7087 }
7088
7089 /* Implement the to_stop function for the remote targets. */
7090
7091 void
7092 remote_target::stop (ptid_t ptid)
7093 {
7094 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7095
7096 if (target_is_non_stop_p ())
7097 remote_stop_ns (ptid);
7098 else
7099 {
7100 /* We don't currently have a way to transparently pause the
7101 remote target in all-stop mode. Interrupt it instead. */
7102 remote_interrupt_as ();
7103 }
7104 }
7105
7106 /* Implement the to_interrupt function for the remote targets. */
7107
7108 void
7109 remote_target::interrupt ()
7110 {
7111 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7112
7113 if (target_is_non_stop_p ())
7114 remote_interrupt_ns ();
7115 else
7116 remote_interrupt_as ();
7117 }
7118
7119 /* Implement the to_pass_ctrlc function for the remote targets. */
7120
7121 void
7122 remote_target::pass_ctrlc ()
7123 {
7124 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7125
7126 struct remote_state *rs = get_remote_state ();
7127
7128 /* If we're starting up, we're not fully synced yet. Quit
7129 immediately. */
7130 if (rs->starting_up)
7131 quit ();
7132 /* If ^C has already been sent once, offer to disconnect. */
7133 else if (rs->ctrlc_pending_p)
7134 interrupt_query ();
7135 else
7136 target_interrupt ();
7137 }
7138
7139 /* Ask the user what to do when an interrupt is received. */
7140
7141 void
7142 remote_target::interrupt_query ()
7143 {
7144 struct remote_state *rs = get_remote_state ();
7145
7146 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7147 {
7148 if (query (_("The target is not responding to interrupt requests.\n"
7149 "Stop debugging it? ")))
7150 {
7151 remote_unpush_target (this);
7152 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7153 }
7154 }
7155 else
7156 {
7157 if (query (_("Interrupted while waiting for the program.\n"
7158 "Give up waiting? ")))
7159 quit ();
7160 }
7161 }
7162
7163 /* Enable/disable target terminal ownership. Most targets can use
7164 terminal groups to control terminal ownership. Remote targets are
7165 different in that explicit transfer of ownership to/from GDB/target
7166 is required. */
7167
7168 void
7169 remote_target::terminal_inferior ()
7170 {
7171 /* NOTE: At this point we could also register our selves as the
7172 recipient of all input. Any characters typed could then be
7173 passed on down to the target. */
7174 }
7175
7176 void
7177 remote_target::terminal_ours ()
7178 {
7179 }
7180
7181 static void
7182 remote_console_output (const char *msg)
7183 {
7184 const char *p;
7185
7186 for (p = msg; p[0] && p[1]; p += 2)
7187 {
7188 char tb[2];
7189 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7190
7191 tb[0] = c;
7192 tb[1] = 0;
7193 gdb_stdtarg->puts (tb);
7194 }
7195 gdb_stdtarg->flush ();
7196 }
7197
7198 /* Return the length of the stop reply queue. */
7199
7200 int
7201 remote_target::stop_reply_queue_length ()
7202 {
7203 remote_state *rs = get_remote_state ();
7204 return rs->stop_reply_queue.size ();
7205 }
7206
7207 static void
7208 remote_notif_stop_parse (remote_target *remote,
7209 struct notif_client *self, const char *buf,
7210 struct notif_event *event)
7211 {
7212 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7213 }
7214
7215 static void
7216 remote_notif_stop_ack (remote_target *remote,
7217 struct notif_client *self, const char *buf,
7218 struct notif_event *event)
7219 {
7220 struct stop_reply *stop_reply = (struct stop_reply *) event;
7221
7222 /* acknowledge */
7223 putpkt (remote, self->ack_command);
7224
7225 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7226 the notification. It was left in the queue because we need to
7227 acknowledge it and pull the rest of the notifications out. */
7228 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7229 remote->push_stop_reply (stop_reply);
7230 }
7231
7232 static int
7233 remote_notif_stop_can_get_pending_events (remote_target *remote,
7234 struct notif_client *self)
7235 {
7236 /* We can't get pending events in remote_notif_process for
7237 notification stop, and we have to do this in remote_wait_ns
7238 instead. If we fetch all queued events from stub, remote stub
7239 may exit and we have no chance to process them back in
7240 remote_wait_ns. */
7241 remote_state *rs = remote->get_remote_state ();
7242 mark_async_event_handler (rs->remote_async_inferior_event_token);
7243 return 0;
7244 }
7245
7246 stop_reply::~stop_reply ()
7247 {
7248 for (cached_reg_t &reg : regcache)
7249 xfree (reg.data);
7250 }
7251
7252 static notif_event_up
7253 remote_notif_stop_alloc_reply ()
7254 {
7255 return notif_event_up (new struct stop_reply ());
7256 }
7257
7258 /* A client of notification Stop. */
7259
7260 struct notif_client notif_client_stop =
7261 {
7262 "Stop",
7263 "vStopped",
7264 remote_notif_stop_parse,
7265 remote_notif_stop_ack,
7266 remote_notif_stop_can_get_pending_events,
7267 remote_notif_stop_alloc_reply,
7268 REMOTE_NOTIF_STOP,
7269 };
7270
7271 /* If CONTEXT contains any fork child threads that have not been
7272 reported yet, remove them from the CONTEXT list. If such a
7273 thread exists it is because we are stopped at a fork catchpoint
7274 and have not yet called follow_fork, which will set up the
7275 host-side data structures for the new process. */
7276
7277 void
7278 remote_target::remove_new_fork_children (threads_listing_context *context)
7279 {
7280 struct notif_client *notif = &notif_client_stop;
7281
7282 /* For any threads stopped at a fork event, remove the corresponding
7283 fork child threads from the CONTEXT list. */
7284 for (thread_info *thread : all_non_exited_threads (this))
7285 {
7286 const target_waitstatus *ws = thread_pending_fork_status (thread);
7287
7288 if (ws == nullptr)
7289 continue;
7290
7291 context->remove_thread (ws->child_ptid ());
7292 }
7293
7294 /* Check for any pending fork events (not reported or processed yet)
7295 in process PID and remove those fork child threads from the
7296 CONTEXT list as well. */
7297 remote_notif_get_pending_events (notif);
7298 for (auto &event : get_remote_state ()->stop_reply_queue)
7299 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7300 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7301 context->remove_thread (event->ws.child_ptid ());
7302 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7303 context->remove_thread (event->ptid);
7304 }
7305
7306 /* Check whether any event pending in the vStopped queue would prevent a
7307 global or process wildcard vCont action. Set *may_global_wildcard to
7308 false if we can't do a global wildcard (vCont;c), and clear the event
7309 inferior's may_wildcard_vcont flag if we can't do a process-wide
7310 wildcard resume (vCont;c:pPID.-1). */
7311
7312 void
7313 remote_target::check_pending_events_prevent_wildcard_vcont
7314 (bool *may_global_wildcard)
7315 {
7316 struct notif_client *notif = &notif_client_stop;
7317
7318 remote_notif_get_pending_events (notif);
7319 for (auto &event : get_remote_state ()->stop_reply_queue)
7320 {
7321 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7322 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7323 continue;
7324
7325 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7326 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7327 *may_global_wildcard = false;
7328
7329 /* This may be the first time we heard about this process.
7330 Regardless, we must not do a global wildcard resume, otherwise
7331 we'd resume this process too. */
7332 *may_global_wildcard = false;
7333 if (event->ptid != null_ptid)
7334 {
7335 inferior *inf = find_inferior_ptid (this, event->ptid);
7336 if (inf != NULL)
7337 get_remote_inferior (inf)->may_wildcard_vcont = false;
7338 }
7339 }
7340 }
7341
7342 /* Discard all pending stop replies of inferior INF. */
7343
7344 void
7345 remote_target::discard_pending_stop_replies (struct inferior *inf)
7346 {
7347 struct stop_reply *reply;
7348 struct remote_state *rs = get_remote_state ();
7349 struct remote_notif_state *rns = rs->notif_state;
7350
7351 /* This function can be notified when an inferior exists. When the
7352 target is not remote, the notification state is NULL. */
7353 if (rs->remote_desc == NULL)
7354 return;
7355
7356 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7357
7358 /* Discard the in-flight notification. */
7359 if (reply != NULL && reply->ptid.pid () == inf->pid)
7360 {
7361 /* Leave the notification pending, since the server expects that
7362 we acknowledge it with vStopped. But clear its contents, so
7363 that later on when we acknowledge it, we also discard it. */
7364 remote_debug_printf
7365 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7366 reply->ptid.to_string().c_str(),
7367 reply->ws.to_string ().c_str ());
7368 reply->ws.set_ignore ();
7369 }
7370
7371 /* Discard the stop replies we have already pulled with
7372 vStopped. */
7373 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7374 rs->stop_reply_queue.end (),
7375 [=] (const stop_reply_up &event)
7376 {
7377 return event->ptid.pid () == inf->pid;
7378 });
7379 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7380 remote_debug_printf
7381 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7382 reply->ptid.to_string().c_str(),
7383 reply->ws.to_string ().c_str ());
7384 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7385 }
7386
7387 /* Discard the stop replies for RS in stop_reply_queue. */
7388
7389 void
7390 remote_target::discard_pending_stop_replies_in_queue ()
7391 {
7392 remote_state *rs = get_remote_state ();
7393
7394 /* Discard the stop replies we have already pulled with
7395 vStopped. */
7396 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7397 rs->stop_reply_queue.end (),
7398 [=] (const stop_reply_up &event)
7399 {
7400 return event->rs == rs;
7401 });
7402 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7403 }
7404
7405 /* Remove the first reply in 'stop_reply_queue' which matches
7406 PTID. */
7407
7408 struct stop_reply *
7409 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7410 {
7411 remote_state *rs = get_remote_state ();
7412
7413 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7414 rs->stop_reply_queue.end (),
7415 [=] (const stop_reply_up &event)
7416 {
7417 return event->ptid.matches (ptid);
7418 });
7419 struct stop_reply *result;
7420 if (iter == rs->stop_reply_queue.end ())
7421 result = nullptr;
7422 else
7423 {
7424 result = iter->release ();
7425 rs->stop_reply_queue.erase (iter);
7426 }
7427
7428 if (notif_debug)
7429 gdb_printf (gdb_stdlog,
7430 "notif: discard queued event: 'Stop' in %s\n",
7431 ptid.to_string ().c_str ());
7432
7433 return result;
7434 }
7435
7436 /* Look for a queued stop reply belonging to PTID. If one is found,
7437 remove it from the queue, and return it. Returns NULL if none is
7438 found. If there are still queued events left to process, tell the
7439 event loop to get back to target_wait soon. */
7440
7441 struct stop_reply *
7442 remote_target::queued_stop_reply (ptid_t ptid)
7443 {
7444 remote_state *rs = get_remote_state ();
7445 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7446
7447 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7448 {
7449 /* There's still at least an event left. */
7450 mark_async_event_handler (rs->remote_async_inferior_event_token);
7451 }
7452
7453 return r;
7454 }
7455
7456 /* Push a fully parsed stop reply in the stop reply queue. Since we
7457 know that we now have at least one queued event left to pass to the
7458 core side, tell the event loop to get back to target_wait soon. */
7459
7460 void
7461 remote_target::push_stop_reply (struct stop_reply *new_event)
7462 {
7463 remote_state *rs = get_remote_state ();
7464 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7465
7466 if (notif_debug)
7467 gdb_printf (gdb_stdlog,
7468 "notif: push 'Stop' %s to queue %d\n",
7469 new_event->ptid.to_string ().c_str (),
7470 int (rs->stop_reply_queue.size ()));
7471
7472 /* Mark the pending event queue only if async mode is currently enabled.
7473 If async mode is not currently enabled, then, if it later becomes
7474 enabled, and there are events in this queue, we will mark the event
7475 token at that point, see remote_target::async. */
7476 if (target_is_async_p ())
7477 mark_async_event_handler (rs->remote_async_inferior_event_token);
7478 }
7479
7480 /* Returns true if we have a stop reply for PTID. */
7481
7482 int
7483 remote_target::peek_stop_reply (ptid_t ptid)
7484 {
7485 remote_state *rs = get_remote_state ();
7486 for (auto &event : rs->stop_reply_queue)
7487 if (ptid == event->ptid
7488 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7489 return 1;
7490 return 0;
7491 }
7492
7493 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7494 starting with P and ending with PEND matches PREFIX. */
7495
7496 static int
7497 strprefix (const char *p, const char *pend, const char *prefix)
7498 {
7499 for ( ; p < pend; p++, prefix++)
7500 if (*p != *prefix)
7501 return 0;
7502 return *prefix == '\0';
7503 }
7504
7505 /* Parse the stop reply in BUF. Either the function succeeds, and the
7506 result is stored in EVENT, or throws an error. */
7507
7508 void
7509 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7510 {
7511 remote_arch_state *rsa = NULL;
7512 ULONGEST addr;
7513 const char *p;
7514 int skipregs = 0;
7515
7516 event->ptid = null_ptid;
7517 event->rs = get_remote_state ();
7518 event->ws.set_ignore ();
7519 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7520 event->regcache.clear ();
7521 event->core = -1;
7522
7523 switch (buf[0])
7524 {
7525 case 'T': /* Status with PC, SP, FP, ... */
7526 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7527 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7528 ss = signal number
7529 n... = register number
7530 r... = register contents
7531 */
7532
7533 p = &buf[3]; /* after Txx */
7534 while (*p)
7535 {
7536 const char *p1;
7537 int fieldsize;
7538
7539 p1 = strchr (p, ':');
7540 if (p1 == NULL)
7541 error (_("Malformed packet(a) (missing colon): %s\n\
7542 Packet: '%s'\n"),
7543 p, buf);
7544 if (p == p1)
7545 error (_("Malformed packet(a) (missing register number): %s\n\
7546 Packet: '%s'\n"),
7547 p, buf);
7548
7549 /* Some "registers" are actually extended stop information.
7550 Note if you're adding a new entry here: GDB 7.9 and
7551 earlier assume that all register "numbers" that start
7552 with an hex digit are real register numbers. Make sure
7553 the server only sends such a packet if it knows the
7554 client understands it. */
7555
7556 if (strprefix (p, p1, "thread"))
7557 event->ptid = read_ptid (++p1, &p);
7558 else if (strprefix (p, p1, "syscall_entry"))
7559 {
7560 ULONGEST sysno;
7561
7562 p = unpack_varlen_hex (++p1, &sysno);
7563 event->ws.set_syscall_entry ((int) sysno);
7564 }
7565 else if (strprefix (p, p1, "syscall_return"))
7566 {
7567 ULONGEST sysno;
7568
7569 p = unpack_varlen_hex (++p1, &sysno);
7570 event->ws.set_syscall_return ((int) sysno);
7571 }
7572 else if (strprefix (p, p1, "watch")
7573 || strprefix (p, p1, "rwatch")
7574 || strprefix (p, p1, "awatch"))
7575 {
7576 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7577 p = unpack_varlen_hex (++p1, &addr);
7578 event->watch_data_address = (CORE_ADDR) addr;
7579 }
7580 else if (strprefix (p, p1, "swbreak"))
7581 {
7582 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7583
7584 /* Make sure the stub doesn't forget to indicate support
7585 with qSupported. */
7586 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7587 error (_("Unexpected swbreak stop reason"));
7588
7589 /* The value part is documented as "must be empty",
7590 though we ignore it, in case we ever decide to make
7591 use of it in a backward compatible way. */
7592 p = strchrnul (p1 + 1, ';');
7593 }
7594 else if (strprefix (p, p1, "hwbreak"))
7595 {
7596 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7597
7598 /* Make sure the stub doesn't forget to indicate support
7599 with qSupported. */
7600 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7601 error (_("Unexpected hwbreak stop reason"));
7602
7603 /* See above. */
7604 p = strchrnul (p1 + 1, ';');
7605 }
7606 else if (strprefix (p, p1, "library"))
7607 {
7608 event->ws.set_loaded ();
7609 p = strchrnul (p1 + 1, ';');
7610 }
7611 else if (strprefix (p, p1, "replaylog"))
7612 {
7613 event->ws.set_no_history ();
7614 /* p1 will indicate "begin" or "end", but it makes
7615 no difference for now, so ignore it. */
7616 p = strchrnul (p1 + 1, ';');
7617 }
7618 else if (strprefix (p, p1, "core"))
7619 {
7620 ULONGEST c;
7621
7622 p = unpack_varlen_hex (++p1, &c);
7623 event->core = c;
7624 }
7625 else if (strprefix (p, p1, "fork"))
7626 event->ws.set_forked (read_ptid (++p1, &p));
7627 else if (strprefix (p, p1, "vfork"))
7628 event->ws.set_vforked (read_ptid (++p1, &p));
7629 else if (strprefix (p, p1, "vforkdone"))
7630 {
7631 event->ws.set_vfork_done ();
7632 p = strchrnul (p1 + 1, ';');
7633 }
7634 else if (strprefix (p, p1, "exec"))
7635 {
7636 ULONGEST ignored;
7637 int pathlen;
7638
7639 /* Determine the length of the execd pathname. */
7640 p = unpack_varlen_hex (++p1, &ignored);
7641 pathlen = (p - p1) / 2;
7642
7643 /* Save the pathname for event reporting and for
7644 the next run command. */
7645 gdb::unique_xmalloc_ptr<char> pathname
7646 ((char *) xmalloc (pathlen + 1));
7647 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
7648 pathname.get ()[pathlen] = '\0';
7649
7650 /* This is freed during event handling. */
7651 event->ws.set_execd (std::move (pathname));
7652
7653 /* Skip the registers included in this packet, since
7654 they may be for an architecture different from the
7655 one used by the original program. */
7656 skipregs = 1;
7657 }
7658 else if (strprefix (p, p1, "create"))
7659 {
7660 event->ws.set_thread_created ();
7661 p = strchrnul (p1 + 1, ';');
7662 }
7663 else
7664 {
7665 ULONGEST pnum;
7666 const char *p_temp;
7667
7668 if (skipregs)
7669 {
7670 p = strchrnul (p1 + 1, ';');
7671 p++;
7672 continue;
7673 }
7674
7675 /* Maybe a real ``P'' register number. */
7676 p_temp = unpack_varlen_hex (p, &pnum);
7677 /* If the first invalid character is the colon, we got a
7678 register number. Otherwise, it's an unknown stop
7679 reason. */
7680 if (p_temp == p1)
7681 {
7682 /* If we haven't parsed the event's thread yet, find
7683 it now, in order to find the architecture of the
7684 reported expedited registers. */
7685 if (event->ptid == null_ptid)
7686 {
7687 /* If there is no thread-id information then leave
7688 the event->ptid as null_ptid. Later in
7689 process_stop_reply we will pick a suitable
7690 thread. */
7691 const char *thr = strstr (p1 + 1, ";thread:");
7692 if (thr != NULL)
7693 event->ptid = read_ptid (thr + strlen (";thread:"),
7694 NULL);
7695 }
7696
7697 if (rsa == NULL)
7698 {
7699 inferior *inf
7700 = (event->ptid == null_ptid
7701 ? NULL
7702 : find_inferior_ptid (this, event->ptid));
7703 /* If this is the first time we learn anything
7704 about this process, skip the registers
7705 included in this packet, since we don't yet
7706 know which architecture to use to parse them.
7707 We'll determine the architecture later when
7708 we process the stop reply and retrieve the
7709 target description, via
7710 remote_notice_new_inferior ->
7711 post_create_inferior. */
7712 if (inf == NULL)
7713 {
7714 p = strchrnul (p1 + 1, ';');
7715 p++;
7716 continue;
7717 }
7718
7719 event->arch = inf->gdbarch;
7720 rsa = event->rs->get_remote_arch_state (event->arch);
7721 }
7722
7723 packet_reg *reg
7724 = packet_reg_from_pnum (event->arch, rsa, pnum);
7725 cached_reg_t cached_reg;
7726
7727 if (reg == NULL)
7728 error (_("Remote sent bad register number %s: %s\n\
7729 Packet: '%s'\n"),
7730 hex_string (pnum), p, buf);
7731
7732 cached_reg.num = reg->regnum;
7733 cached_reg.data = (gdb_byte *)
7734 xmalloc (register_size (event->arch, reg->regnum));
7735
7736 p = p1 + 1;
7737 fieldsize = hex2bin (p, cached_reg.data,
7738 register_size (event->arch, reg->regnum));
7739 p += 2 * fieldsize;
7740 if (fieldsize < register_size (event->arch, reg->regnum))
7741 warning (_("Remote reply is too short: %s"), buf);
7742
7743 event->regcache.push_back (cached_reg);
7744 }
7745 else
7746 {
7747 /* Not a number. Silently skip unknown optional
7748 info. */
7749 p = strchrnul (p1 + 1, ';');
7750 }
7751 }
7752
7753 if (*p != ';')
7754 error (_("Remote register badly formatted: %s\nhere: %s"),
7755 buf, p);
7756 ++p;
7757 }
7758
7759 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
7760 break;
7761
7762 /* fall through */
7763 case 'S': /* Old style status, just signal only. */
7764 {
7765 int sig;
7766
7767 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7768 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7769 event->ws.set_stopped ((enum gdb_signal) sig);
7770 else
7771 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
7772 }
7773 break;
7774 case 'w': /* Thread exited. */
7775 {
7776 ULONGEST value;
7777
7778 p = unpack_varlen_hex (&buf[1], &value);
7779 event->ws.set_thread_exited (value);
7780 if (*p != ';')
7781 error (_("stop reply packet badly formatted: %s"), buf);
7782 event->ptid = read_ptid (++p, NULL);
7783 break;
7784 }
7785 case 'W': /* Target exited. */
7786 case 'X':
7787 {
7788 ULONGEST value;
7789
7790 /* GDB used to accept only 2 hex chars here. Stubs should
7791 only send more if they detect GDB supports multi-process
7792 support. */
7793 p = unpack_varlen_hex (&buf[1], &value);
7794
7795 if (buf[0] == 'W')
7796 {
7797 /* The remote process exited. */
7798 event->ws.set_exited (value);
7799 }
7800 else
7801 {
7802 /* The remote process exited with a signal. */
7803 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7804 event->ws.set_signalled ((enum gdb_signal) value);
7805 else
7806 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
7807 }
7808
7809 /* If no process is specified, return null_ptid, and let the
7810 caller figure out the right process to use. */
7811 int pid = 0;
7812 if (*p == '\0')
7813 ;
7814 else if (*p == ';')
7815 {
7816 p++;
7817
7818 if (*p == '\0')
7819 ;
7820 else if (startswith (p, "process:"))
7821 {
7822 ULONGEST upid;
7823
7824 p += sizeof ("process:") - 1;
7825 unpack_varlen_hex (p, &upid);
7826 pid = upid;
7827 }
7828 else
7829 error (_("unknown stop reply packet: %s"), buf);
7830 }
7831 else
7832 error (_("unknown stop reply packet: %s"), buf);
7833 event->ptid = ptid_t (pid);
7834 }
7835 break;
7836 case 'N':
7837 event->ws.set_no_resumed ();
7838 event->ptid = minus_one_ptid;
7839 break;
7840 }
7841 }
7842
7843 /* When the stub wants to tell GDB about a new notification reply, it
7844 sends a notification (%Stop, for example). Those can come it at
7845 any time, hence, we have to make sure that any pending
7846 putpkt/getpkt sequence we're making is finished, before querying
7847 the stub for more events with the corresponding ack command
7848 (vStopped, for example). E.g., if we started a vStopped sequence
7849 immediately upon receiving the notification, something like this
7850 could happen:
7851
7852 1.1) --> Hg 1
7853 1.2) <-- OK
7854 1.3) --> g
7855 1.4) <-- %Stop
7856 1.5) --> vStopped
7857 1.6) <-- (registers reply to step #1.3)
7858
7859 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7860 query.
7861
7862 To solve this, whenever we parse a %Stop notification successfully,
7863 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7864 doing whatever we were doing:
7865
7866 2.1) --> Hg 1
7867 2.2) <-- OK
7868 2.3) --> g
7869 2.4) <-- %Stop
7870 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7871 2.5) <-- (registers reply to step #2.3)
7872
7873 Eventually after step #2.5, we return to the event loop, which
7874 notices there's an event on the
7875 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7876 associated callback --- the function below. At this point, we're
7877 always safe to start a vStopped sequence. :
7878
7879 2.6) --> vStopped
7880 2.7) <-- T05 thread:2
7881 2.8) --> vStopped
7882 2.9) --> OK
7883 */
7884
7885 void
7886 remote_target::remote_notif_get_pending_events (notif_client *nc)
7887 {
7888 struct remote_state *rs = get_remote_state ();
7889
7890 if (rs->notif_state->pending_event[nc->id] != NULL)
7891 {
7892 if (notif_debug)
7893 gdb_printf (gdb_stdlog,
7894 "notif: process: '%s' ack pending event\n",
7895 nc->name);
7896
7897 /* acknowledge */
7898 nc->ack (this, nc, rs->buf.data (),
7899 rs->notif_state->pending_event[nc->id]);
7900 rs->notif_state->pending_event[nc->id] = NULL;
7901
7902 while (1)
7903 {
7904 getpkt (&rs->buf, 0);
7905 if (strcmp (rs->buf.data (), "OK") == 0)
7906 break;
7907 else
7908 remote_notif_ack (this, nc, rs->buf.data ());
7909 }
7910 }
7911 else
7912 {
7913 if (notif_debug)
7914 gdb_printf (gdb_stdlog,
7915 "notif: process: '%s' no pending reply\n",
7916 nc->name);
7917 }
7918 }
7919
7920 /* Wrapper around remote_target::remote_notif_get_pending_events to
7921 avoid having to export the whole remote_target class. */
7922
7923 void
7924 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7925 {
7926 remote->remote_notif_get_pending_events (nc);
7927 }
7928
7929 /* Called from process_stop_reply when the stop packet we are responding
7930 to didn't include a process-id or thread-id. STATUS is the stop event
7931 we are responding to.
7932
7933 It is the task of this function to select a suitable thread (or process)
7934 and return its ptid, this is the thread (or process) we will assume the
7935 stop event came from.
7936
7937 In some cases there isn't really any choice about which thread (or
7938 process) is selected, a basic remote with a single process containing a
7939 single thread might choose not to send any process-id or thread-id in
7940 its stop packets, this function will select and return the one and only
7941 thread.
7942
7943 However, if a target supports multiple threads (or processes) and still
7944 doesn't include a thread-id (or process-id) in its stop packet then
7945 first, this is a badly behaving target, and second, we're going to have
7946 to select a thread (or process) at random and use that. This function
7947 will print a warning to the user if it detects that there is the
7948 possibility that GDB is guessing which thread (or process) to
7949 report.
7950
7951 Note that this is called before GDB fetches the updated thread list from the
7952 target. So it's possible for the stop reply to be ambiguous and for GDB to
7953 not realize it. For example, if there's initially one thread, the target
7954 spawns a second thread, and then sends a stop reply without an id that
7955 concerns the first thread. GDB will assume the stop reply is about the
7956 first thread - the only thread it knows about - without printing a warning.
7957 Anyway, if the remote meant for the stop reply to be about the second thread,
7958 then it would be really broken, because GDB doesn't know about that thread
7959 yet. */
7960
7961 ptid_t
7962 remote_target::select_thread_for_ambiguous_stop_reply
7963 (const target_waitstatus &status)
7964 {
7965 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7966
7967 /* Some stop events apply to all threads in an inferior, while others
7968 only apply to a single thread. */
7969 bool process_wide_stop
7970 = (status.kind () == TARGET_WAITKIND_EXITED
7971 || status.kind () == TARGET_WAITKIND_SIGNALLED);
7972
7973 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
7974
7975 thread_info *first_resumed_thread = nullptr;
7976 bool ambiguous = false;
7977
7978 /* Consider all non-exited threads of the target, find the first resumed
7979 one. */
7980 for (thread_info *thr : all_non_exited_threads (this))
7981 {
7982 remote_thread_info *remote_thr = get_remote_thread_info (thr);
7983
7984 if (remote_thr->get_resume_state () != resume_state::RESUMED)
7985 continue;
7986
7987 if (first_resumed_thread == nullptr)
7988 first_resumed_thread = thr;
7989 else if (!process_wide_stop
7990 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
7991 ambiguous = true;
7992 }
7993
7994 gdb_assert (first_resumed_thread != nullptr);
7995
7996 remote_debug_printf ("first resumed thread is %s",
7997 pid_to_str (first_resumed_thread->ptid).c_str ());
7998 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
7999
8000 /* Warn if the remote target is sending ambiguous stop replies. */
8001 if (ambiguous)
8002 {
8003 static bool warned = false;
8004
8005 if (!warned)
8006 {
8007 /* If you are seeing this warning then the remote target has
8008 stopped without specifying a thread-id, but the target
8009 does have multiple threads (or inferiors), and so GDB is
8010 having to guess which thread stopped.
8011
8012 Examples of what might cause this are the target sending
8013 and 'S' stop packet, or a 'T' stop packet and not
8014 including a thread-id.
8015
8016 Additionally, the target might send a 'W' or 'X packet
8017 without including a process-id, when the target has
8018 multiple running inferiors. */
8019 if (process_wide_stop)
8020 warning (_("multi-inferior target stopped without "
8021 "sending a process-id, using first "
8022 "non-exited inferior"));
8023 else
8024 warning (_("multi-threaded target stopped without "
8025 "sending a thread-id, using first "
8026 "non-exited thread"));
8027 warned = true;
8028 }
8029 }
8030
8031 /* If this is a stop for all threads then don't use a particular threads
8032 ptid, instead create a new ptid where only the pid field is set. */
8033 if (process_wide_stop)
8034 return ptid_t (first_resumed_thread->ptid.pid ());
8035 else
8036 return first_resumed_thread->ptid;
8037 }
8038
8039 /* Called when it is decided that STOP_REPLY holds the info of the
8040 event that is to be returned to the core. This function always
8041 destroys STOP_REPLY. */
8042
8043 ptid_t
8044 remote_target::process_stop_reply (struct stop_reply *stop_reply,
8045 struct target_waitstatus *status)
8046 {
8047 *status = stop_reply->ws;
8048 ptid_t ptid = stop_reply->ptid;
8049
8050 /* If no thread/process was reported by the stub then select a suitable
8051 thread/process. */
8052 if (ptid == null_ptid)
8053 ptid = select_thread_for_ambiguous_stop_reply (*status);
8054 gdb_assert (ptid != null_ptid);
8055
8056 if (status->kind () != TARGET_WAITKIND_EXITED
8057 && status->kind () != TARGET_WAITKIND_SIGNALLED
8058 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8059 {
8060 /* Expedited registers. */
8061 if (!stop_reply->regcache.empty ())
8062 {
8063 struct regcache *regcache
8064 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
8065
8066 for (cached_reg_t &reg : stop_reply->regcache)
8067 {
8068 regcache->raw_supply (reg.num, reg.data);
8069 xfree (reg.data);
8070 }
8071
8072 stop_reply->regcache.clear ();
8073 }
8074
8075 remote_notice_new_inferior (ptid, false);
8076 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8077 remote_thr->core = stop_reply->core;
8078 remote_thr->stop_reason = stop_reply->stop_reason;
8079 remote_thr->watch_data_address = stop_reply->watch_data_address;
8080
8081 if (target_is_non_stop_p ())
8082 {
8083 /* If the target works in non-stop mode, a stop-reply indicates that
8084 only this thread stopped. */
8085 remote_thr->set_not_resumed ();
8086 }
8087 else
8088 {
8089 /* If the target works in all-stop mode, a stop-reply indicates that
8090 all the target's threads stopped. */
8091 for (thread_info *tp : all_non_exited_threads (this))
8092 get_remote_thread_info (tp)->set_not_resumed ();
8093 }
8094 }
8095
8096 delete stop_reply;
8097 return ptid;
8098 }
8099
8100 /* The non-stop mode version of target_wait. */
8101
8102 ptid_t
8103 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8104 target_wait_flags options)
8105 {
8106 struct remote_state *rs = get_remote_state ();
8107 struct stop_reply *stop_reply;
8108 int ret;
8109 int is_notif = 0;
8110
8111 /* If in non-stop mode, get out of getpkt even if a
8112 notification is received. */
8113
8114 ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
8115 while (1)
8116 {
8117 if (ret != -1 && !is_notif)
8118 switch (rs->buf[0])
8119 {
8120 case 'E': /* Error of some sort. */
8121 /* We're out of sync with the target now. Did it continue
8122 or not? We can't tell which thread it was in non-stop,
8123 so just ignore this. */
8124 warning (_("Remote failure reply: %s"), rs->buf.data ());
8125 break;
8126 case 'O': /* Console output. */
8127 remote_console_output (&rs->buf[1]);
8128 break;
8129 default:
8130 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8131 break;
8132 }
8133
8134 /* Acknowledge a pending stop reply that may have arrived in the
8135 mean time. */
8136 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8137 remote_notif_get_pending_events (&notif_client_stop);
8138
8139 /* If indeed we noticed a stop reply, we're done. */
8140 stop_reply = queued_stop_reply (ptid);
8141 if (stop_reply != NULL)
8142 return process_stop_reply (stop_reply, status);
8143
8144 /* Still no event. If we're just polling for an event, then
8145 return to the event loop. */
8146 if (options & TARGET_WNOHANG)
8147 {
8148 status->set_ignore ();
8149 return minus_one_ptid;
8150 }
8151
8152 /* Otherwise do a blocking wait. */
8153 ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
8154 }
8155 }
8156
8157 /* Return the first resumed thread. */
8158
8159 static ptid_t
8160 first_remote_resumed_thread (remote_target *target)
8161 {
8162 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8163 if (tp->resumed ())
8164 return tp->ptid;
8165 return null_ptid;
8166 }
8167
8168 /* Wait until the remote machine stops, then return, storing status in
8169 STATUS just as `wait' would. */
8170
8171 ptid_t
8172 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8173 target_wait_flags options)
8174 {
8175 struct remote_state *rs = get_remote_state ();
8176 ptid_t event_ptid = null_ptid;
8177 char *buf;
8178 struct stop_reply *stop_reply;
8179
8180 again:
8181
8182 status->set_ignore ();
8183
8184 stop_reply = queued_stop_reply (ptid);
8185 if (stop_reply != NULL)
8186 {
8187 /* None of the paths that push a stop reply onto the queue should
8188 have set the waiting_for_stop_reply flag. */
8189 gdb_assert (!rs->waiting_for_stop_reply);
8190 event_ptid = process_stop_reply (stop_reply, status);
8191 }
8192 else
8193 {
8194 int forever = ((options & TARGET_WNOHANG) == 0
8195 && rs->wait_forever_enabled_p);
8196
8197 if (!rs->waiting_for_stop_reply)
8198 {
8199 status->set_no_resumed ();
8200 return minus_one_ptid;
8201 }
8202
8203 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8204 _never_ wait for ever -> test on target_is_async_p().
8205 However, before we do that we need to ensure that the caller
8206 knows how to take the target into/out of async mode. */
8207 int is_notif;
8208 int ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
8209
8210 /* GDB gets a notification. Return to core as this event is
8211 not interesting. */
8212 if (ret != -1 && is_notif)
8213 return minus_one_ptid;
8214
8215 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8216 return minus_one_ptid;
8217
8218 buf = rs->buf.data ();
8219
8220 /* Assume that the target has acknowledged Ctrl-C unless we receive
8221 an 'F' or 'O' packet. */
8222 if (buf[0] != 'F' && buf[0] != 'O')
8223 rs->ctrlc_pending_p = 0;
8224
8225 switch (buf[0])
8226 {
8227 case 'E': /* Error of some sort. */
8228 /* We're out of sync with the target now. Did it continue or
8229 not? Not is more likely, so report a stop. */
8230 rs->waiting_for_stop_reply = 0;
8231
8232 warning (_("Remote failure reply: %s"), buf);
8233 status->set_stopped (GDB_SIGNAL_0);
8234 break;
8235 case 'F': /* File-I/O request. */
8236 /* GDB may access the inferior memory while handling the File-I/O
8237 request, but we don't want GDB accessing memory while waiting
8238 for a stop reply. See the comments in putpkt_binary. Set
8239 waiting_for_stop_reply to 0 temporarily. */
8240 rs->waiting_for_stop_reply = 0;
8241 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8242 rs->ctrlc_pending_p = 0;
8243 /* GDB handled the File-I/O request, and the target is running
8244 again. Keep waiting for events. */
8245 rs->waiting_for_stop_reply = 1;
8246 break;
8247 case 'N': case 'T': case 'S': case 'X': case 'W':
8248 {
8249 /* There is a stop reply to handle. */
8250 rs->waiting_for_stop_reply = 0;
8251
8252 stop_reply
8253 = (struct stop_reply *) remote_notif_parse (this,
8254 &notif_client_stop,
8255 rs->buf.data ());
8256
8257 event_ptid = process_stop_reply (stop_reply, status);
8258 break;
8259 }
8260 case 'O': /* Console output. */
8261 remote_console_output (buf + 1);
8262 break;
8263 case '\0':
8264 if (rs->last_sent_signal != GDB_SIGNAL_0)
8265 {
8266 /* Zero length reply means that we tried 'S' or 'C' and the
8267 remote system doesn't support it. */
8268 target_terminal::ours_for_output ();
8269 gdb_printf
8270 ("Can't send signals to this remote system. %s not sent.\n",
8271 gdb_signal_to_name (rs->last_sent_signal));
8272 rs->last_sent_signal = GDB_SIGNAL_0;
8273 target_terminal::inferior ();
8274
8275 strcpy (buf, rs->last_sent_step ? "s" : "c");
8276 putpkt (buf);
8277 break;
8278 }
8279 /* fallthrough */
8280 default:
8281 warning (_("Invalid remote reply: %s"), buf);
8282 break;
8283 }
8284 }
8285
8286 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8287 return minus_one_ptid;
8288 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8289 {
8290 /* Nothing interesting happened. If we're doing a non-blocking
8291 poll, we're done. Otherwise, go back to waiting. */
8292 if (options & TARGET_WNOHANG)
8293 return minus_one_ptid;
8294 else
8295 goto again;
8296 }
8297 else if (status->kind () != TARGET_WAITKIND_EXITED
8298 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8299 {
8300 if (event_ptid != null_ptid)
8301 record_currthread (rs, event_ptid);
8302 else
8303 event_ptid = first_remote_resumed_thread (this);
8304 }
8305 else
8306 {
8307 /* A process exit. Invalidate our notion of current thread. */
8308 record_currthread (rs, minus_one_ptid);
8309 /* It's possible that the packet did not include a pid. */
8310 if (event_ptid == null_ptid)
8311 event_ptid = first_remote_resumed_thread (this);
8312 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8313 if (event_ptid == null_ptid)
8314 event_ptid = magic_null_ptid;
8315 }
8316
8317 return event_ptid;
8318 }
8319
8320 /* Wait until the remote machine stops, then return, storing status in
8321 STATUS just as `wait' would. */
8322
8323 ptid_t
8324 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8325 target_wait_flags options)
8326 {
8327 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8328
8329 remote_state *rs = get_remote_state ();
8330
8331 /* Start by clearing the flag that asks for our wait method to be called,
8332 we'll mark it again at the end if needed. If the target is not in
8333 async mode then the async token should not be marked. */
8334 if (target_is_async_p ())
8335 clear_async_event_handler (rs->remote_async_inferior_event_token);
8336 else
8337 gdb_assert (!async_event_handler_marked
8338 (rs->remote_async_inferior_event_token));
8339
8340 ptid_t event_ptid;
8341
8342 if (target_is_non_stop_p ())
8343 event_ptid = wait_ns (ptid, status, options);
8344 else
8345 event_ptid = wait_as (ptid, status, options);
8346
8347 if (target_is_async_p ())
8348 {
8349 /* If there are events left in the queue, or unacknowledged
8350 notifications, then tell the event loop to call us again. */
8351 if (!rs->stop_reply_queue.empty ()
8352 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8353 mark_async_event_handler (rs->remote_async_inferior_event_token);
8354 }
8355
8356 return event_ptid;
8357 }
8358
8359 /* Fetch a single register using a 'p' packet. */
8360
8361 int
8362 remote_target::fetch_register_using_p (struct regcache *regcache,
8363 packet_reg *reg)
8364 {
8365 struct gdbarch *gdbarch = regcache->arch ();
8366 struct remote_state *rs = get_remote_state ();
8367 char *buf, *p;
8368 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8369 int i;
8370
8371 if (packet_support (PACKET_p) == PACKET_DISABLE)
8372 return 0;
8373
8374 if (reg->pnum == -1)
8375 return 0;
8376
8377 p = rs->buf.data ();
8378 *p++ = 'p';
8379 p += hexnumstr (p, reg->pnum);
8380 *p++ = '\0';
8381 putpkt (rs->buf);
8382 getpkt (&rs->buf, 0);
8383
8384 buf = rs->buf.data ();
8385
8386 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_p]))
8387 {
8388 case PACKET_OK:
8389 break;
8390 case PACKET_UNKNOWN:
8391 return 0;
8392 case PACKET_ERROR:
8393 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8394 gdbarch_register_name (regcache->arch (),
8395 reg->regnum),
8396 buf);
8397 }
8398
8399 /* If this register is unfetchable, tell the regcache. */
8400 if (buf[0] == 'x')
8401 {
8402 regcache->raw_supply (reg->regnum, NULL);
8403 return 1;
8404 }
8405
8406 /* Otherwise, parse and supply the value. */
8407 p = buf;
8408 i = 0;
8409 while (p[0] != 0)
8410 {
8411 if (p[1] == 0)
8412 error (_("fetch_register_using_p: early buf termination"));
8413
8414 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8415 p += 2;
8416 }
8417 regcache->raw_supply (reg->regnum, regp);
8418 return 1;
8419 }
8420
8421 /* Fetch the registers included in the target's 'g' packet. */
8422
8423 int
8424 remote_target::send_g_packet ()
8425 {
8426 struct remote_state *rs = get_remote_state ();
8427 int buf_len;
8428
8429 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8430 putpkt (rs->buf);
8431 getpkt (&rs->buf, 0);
8432 if (packet_check_result (rs->buf) == PACKET_ERROR)
8433 error (_("Could not read registers; remote failure reply '%s'"),
8434 rs->buf.data ());
8435
8436 /* We can get out of synch in various cases. If the first character
8437 in the buffer is not a hex character, assume that has happened
8438 and try to fetch another packet to read. */
8439 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8440 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8441 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8442 && rs->buf[0] != 'x') /* New: unavailable register value. */
8443 {
8444 remote_debug_printf ("Bad register packet; fetching a new packet");
8445 getpkt (&rs->buf, 0);
8446 }
8447
8448 buf_len = strlen (rs->buf.data ());
8449
8450 /* Sanity check the received packet. */
8451 if (buf_len % 2 != 0)
8452 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8453
8454 return buf_len / 2;
8455 }
8456
8457 void
8458 remote_target::process_g_packet (struct regcache *regcache)
8459 {
8460 struct gdbarch *gdbarch = regcache->arch ();
8461 struct remote_state *rs = get_remote_state ();
8462 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8463 int i, buf_len;
8464 char *p;
8465 char *regs;
8466
8467 buf_len = strlen (rs->buf.data ());
8468
8469 /* Further sanity checks, with knowledge of the architecture. */
8470 if (buf_len > 2 * rsa->sizeof_g_packet)
8471 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8472 "bytes): %s"),
8473 rsa->sizeof_g_packet, buf_len / 2,
8474 rs->buf.data ());
8475
8476 /* Save the size of the packet sent to us by the target. It is used
8477 as a heuristic when determining the max size of packets that the
8478 target can safely receive. */
8479 if (rsa->actual_register_packet_size == 0)
8480 rsa->actual_register_packet_size = buf_len;
8481
8482 /* If this is smaller than we guessed the 'g' packet would be,
8483 update our records. A 'g' reply that doesn't include a register's
8484 value implies either that the register is not available, or that
8485 the 'p' packet must be used. */
8486 if (buf_len < 2 * rsa->sizeof_g_packet)
8487 {
8488 long sizeof_g_packet = buf_len / 2;
8489
8490 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8491 {
8492 long offset = rsa->regs[i].offset;
8493 long reg_size = register_size (gdbarch, i);
8494
8495 if (rsa->regs[i].pnum == -1)
8496 continue;
8497
8498 if (offset >= sizeof_g_packet)
8499 rsa->regs[i].in_g_packet = 0;
8500 else if (offset + reg_size > sizeof_g_packet)
8501 error (_("Truncated register %d in remote 'g' packet"), i);
8502 else
8503 rsa->regs[i].in_g_packet = 1;
8504 }
8505
8506 /* Looks valid enough, we can assume this is the correct length
8507 for a 'g' packet. It's important not to adjust
8508 rsa->sizeof_g_packet if we have truncated registers otherwise
8509 this "if" won't be run the next time the method is called
8510 with a packet of the same size and one of the internal errors
8511 below will trigger instead. */
8512 rsa->sizeof_g_packet = sizeof_g_packet;
8513 }
8514
8515 regs = (char *) alloca (rsa->sizeof_g_packet);
8516
8517 /* Unimplemented registers read as all bits zero. */
8518 memset (regs, 0, rsa->sizeof_g_packet);
8519
8520 /* Reply describes registers byte by byte, each byte encoded as two
8521 hex characters. Suck them all up, then supply them to the
8522 register cacheing/storage mechanism. */
8523
8524 p = rs->buf.data ();
8525 for (i = 0; i < rsa->sizeof_g_packet; i++)
8526 {
8527 if (p[0] == 0 || p[1] == 0)
8528 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8529 internal_error (__FILE__, __LINE__,
8530 _("unexpected end of 'g' packet reply"));
8531
8532 if (p[0] == 'x' && p[1] == 'x')
8533 regs[i] = 0; /* 'x' */
8534 else
8535 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8536 p += 2;
8537 }
8538
8539 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8540 {
8541 struct packet_reg *r = &rsa->regs[i];
8542 long reg_size = register_size (gdbarch, i);
8543
8544 if (r->in_g_packet)
8545 {
8546 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8547 /* This shouldn't happen - we adjusted in_g_packet above. */
8548 internal_error (__FILE__, __LINE__,
8549 _("unexpected end of 'g' packet reply"));
8550 else if (rs->buf[r->offset * 2] == 'x')
8551 {
8552 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8553 /* The register isn't available, mark it as such (at
8554 the same time setting the value to zero). */
8555 regcache->raw_supply (r->regnum, NULL);
8556 }
8557 else
8558 regcache->raw_supply (r->regnum, regs + r->offset);
8559 }
8560 }
8561 }
8562
8563 void
8564 remote_target::fetch_registers_using_g (struct regcache *regcache)
8565 {
8566 send_g_packet ();
8567 process_g_packet (regcache);
8568 }
8569
8570 /* Make the remote selected traceframe match GDB's selected
8571 traceframe. */
8572
8573 void
8574 remote_target::set_remote_traceframe ()
8575 {
8576 int newnum;
8577 struct remote_state *rs = get_remote_state ();
8578
8579 if (rs->remote_traceframe_number == get_traceframe_number ())
8580 return;
8581
8582 /* Avoid recursion, remote_trace_find calls us again. */
8583 rs->remote_traceframe_number = get_traceframe_number ();
8584
8585 newnum = target_trace_find (tfind_number,
8586 get_traceframe_number (), 0, 0, NULL);
8587
8588 /* Should not happen. If it does, all bets are off. */
8589 if (newnum != get_traceframe_number ())
8590 warning (_("could not set remote traceframe"));
8591 }
8592
8593 void
8594 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8595 {
8596 struct gdbarch *gdbarch = regcache->arch ();
8597 struct remote_state *rs = get_remote_state ();
8598 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8599 int i;
8600
8601 set_remote_traceframe ();
8602 set_general_thread (regcache->ptid ());
8603
8604 if (regnum >= 0)
8605 {
8606 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8607
8608 gdb_assert (reg != NULL);
8609
8610 /* If this register might be in the 'g' packet, try that first -
8611 we are likely to read more than one register. If this is the
8612 first 'g' packet, we might be overly optimistic about its
8613 contents, so fall back to 'p'. */
8614 if (reg->in_g_packet)
8615 {
8616 fetch_registers_using_g (regcache);
8617 if (reg->in_g_packet)
8618 return;
8619 }
8620
8621 if (fetch_register_using_p (regcache, reg))
8622 return;
8623
8624 /* This register is not available. */
8625 regcache->raw_supply (reg->regnum, NULL);
8626
8627 return;
8628 }
8629
8630 fetch_registers_using_g (regcache);
8631
8632 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8633 if (!rsa->regs[i].in_g_packet)
8634 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8635 {
8636 /* This register is not available. */
8637 regcache->raw_supply (i, NULL);
8638 }
8639 }
8640
8641 /* Prepare to store registers. Since we may send them all (using a
8642 'G' request), we have to read out the ones we don't want to change
8643 first. */
8644
8645 void
8646 remote_target::prepare_to_store (struct regcache *regcache)
8647 {
8648 struct remote_state *rs = get_remote_state ();
8649 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8650 int i;
8651
8652 /* Make sure the entire registers array is valid. */
8653 switch (packet_support (PACKET_P))
8654 {
8655 case PACKET_DISABLE:
8656 case PACKET_SUPPORT_UNKNOWN:
8657 /* Make sure all the necessary registers are cached. */
8658 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8659 if (rsa->regs[i].in_g_packet)
8660 regcache->raw_update (rsa->regs[i].regnum);
8661 break;
8662 case PACKET_ENABLE:
8663 break;
8664 }
8665 }
8666
8667 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8668 packet was not recognized. */
8669
8670 int
8671 remote_target::store_register_using_P (const struct regcache *regcache,
8672 packet_reg *reg)
8673 {
8674 struct gdbarch *gdbarch = regcache->arch ();
8675 struct remote_state *rs = get_remote_state ();
8676 /* Try storing a single register. */
8677 char *buf = rs->buf.data ();
8678 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8679 char *p;
8680
8681 if (packet_support (PACKET_P) == PACKET_DISABLE)
8682 return 0;
8683
8684 if (reg->pnum == -1)
8685 return 0;
8686
8687 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8688 p = buf + strlen (buf);
8689 regcache->raw_collect (reg->regnum, regp);
8690 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8691 putpkt (rs->buf);
8692 getpkt (&rs->buf, 0);
8693
8694 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8695 {
8696 case PACKET_OK:
8697 return 1;
8698 case PACKET_ERROR:
8699 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8700 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
8701 case PACKET_UNKNOWN:
8702 return 0;
8703 default:
8704 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8705 }
8706 }
8707
8708 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8709 contents of the register cache buffer. FIXME: ignores errors. */
8710
8711 void
8712 remote_target::store_registers_using_G (const struct regcache *regcache)
8713 {
8714 struct remote_state *rs = get_remote_state ();
8715 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8716 gdb_byte *regs;
8717 char *p;
8718
8719 /* Extract all the registers in the regcache copying them into a
8720 local buffer. */
8721 {
8722 int i;
8723
8724 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8725 memset (regs, 0, rsa->sizeof_g_packet);
8726 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8727 {
8728 struct packet_reg *r = &rsa->regs[i];
8729
8730 if (r->in_g_packet)
8731 regcache->raw_collect (r->regnum, regs + r->offset);
8732 }
8733 }
8734
8735 /* Command describes registers byte by byte,
8736 each byte encoded as two hex characters. */
8737 p = rs->buf.data ();
8738 *p++ = 'G';
8739 bin2hex (regs, p, rsa->sizeof_g_packet);
8740 putpkt (rs->buf);
8741 getpkt (&rs->buf, 0);
8742 if (packet_check_result (rs->buf) == PACKET_ERROR)
8743 error (_("Could not write registers; remote failure reply '%s'"),
8744 rs->buf.data ());
8745 }
8746
8747 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8748 of the register cache buffer. FIXME: ignores errors. */
8749
8750 void
8751 remote_target::store_registers (struct regcache *regcache, int regnum)
8752 {
8753 struct gdbarch *gdbarch = regcache->arch ();
8754 struct remote_state *rs = get_remote_state ();
8755 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8756 int i;
8757
8758 set_remote_traceframe ();
8759 set_general_thread (regcache->ptid ());
8760
8761 if (regnum >= 0)
8762 {
8763 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8764
8765 gdb_assert (reg != NULL);
8766
8767 /* Always prefer to store registers using the 'P' packet if
8768 possible; we often change only a small number of registers.
8769 Sometimes we change a larger number; we'd need help from a
8770 higher layer to know to use 'G'. */
8771 if (store_register_using_P (regcache, reg))
8772 return;
8773
8774 /* For now, don't complain if we have no way to write the
8775 register. GDB loses track of unavailable registers too
8776 easily. Some day, this may be an error. We don't have
8777 any way to read the register, either... */
8778 if (!reg->in_g_packet)
8779 return;
8780
8781 store_registers_using_G (regcache);
8782 return;
8783 }
8784
8785 store_registers_using_G (regcache);
8786
8787 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8788 if (!rsa->regs[i].in_g_packet)
8789 if (!store_register_using_P (regcache, &rsa->regs[i]))
8790 /* See above for why we do not issue an error here. */
8791 continue;
8792 }
8793 \f
8794
8795 /* Return the number of hex digits in num. */
8796
8797 static int
8798 hexnumlen (ULONGEST num)
8799 {
8800 int i;
8801
8802 for (i = 0; num != 0; i++)
8803 num >>= 4;
8804
8805 return std::max (i, 1);
8806 }
8807
8808 /* Set BUF to the minimum number of hex digits representing NUM. */
8809
8810 static int
8811 hexnumstr (char *buf, ULONGEST num)
8812 {
8813 int len = hexnumlen (num);
8814
8815 return hexnumnstr (buf, num, len);
8816 }
8817
8818
8819 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
8820
8821 static int
8822 hexnumnstr (char *buf, ULONGEST num, int width)
8823 {
8824 int i;
8825
8826 buf[width] = '\0';
8827
8828 for (i = width - 1; i >= 0; i--)
8829 {
8830 buf[i] = "0123456789abcdef"[(num & 0xf)];
8831 num >>= 4;
8832 }
8833
8834 return width;
8835 }
8836
8837 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8838
8839 static CORE_ADDR
8840 remote_address_masked (CORE_ADDR addr)
8841 {
8842 unsigned int address_size = remote_address_size;
8843
8844 /* If "remoteaddresssize" was not set, default to target address size. */
8845 if (!address_size)
8846 address_size = gdbarch_addr_bit (target_gdbarch ());
8847
8848 if (address_size > 0
8849 && address_size < (sizeof (ULONGEST) * 8))
8850 {
8851 /* Only create a mask when that mask can safely be constructed
8852 in a ULONGEST variable. */
8853 ULONGEST mask = 1;
8854
8855 mask = (mask << address_size) - 1;
8856 addr &= mask;
8857 }
8858 return addr;
8859 }
8860
8861 /* Determine whether the remote target supports binary downloading.
8862 This is accomplished by sending a no-op memory write of zero length
8863 to the target at the specified address. It does not suffice to send
8864 the whole packet, since many stubs strip the eighth bit and
8865 subsequently compute a wrong checksum, which causes real havoc with
8866 remote_write_bytes.
8867
8868 NOTE: This can still lose if the serial line is not eight-bit
8869 clean. In cases like this, the user should clear "remote
8870 X-packet". */
8871
8872 void
8873 remote_target::check_binary_download (CORE_ADDR addr)
8874 {
8875 struct remote_state *rs = get_remote_state ();
8876
8877 switch (packet_support (PACKET_X))
8878 {
8879 case PACKET_DISABLE:
8880 break;
8881 case PACKET_ENABLE:
8882 break;
8883 case PACKET_SUPPORT_UNKNOWN:
8884 {
8885 char *p;
8886
8887 p = rs->buf.data ();
8888 *p++ = 'X';
8889 p += hexnumstr (p, (ULONGEST) addr);
8890 *p++ = ',';
8891 p += hexnumstr (p, (ULONGEST) 0);
8892 *p++ = ':';
8893 *p = '\0';
8894
8895 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
8896 getpkt (&rs->buf, 0);
8897
8898 if (rs->buf[0] == '\0')
8899 {
8900 remote_debug_printf ("binary downloading NOT supported by target");
8901 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8902 }
8903 else
8904 {
8905 remote_debug_printf ("binary downloading supported by target");
8906 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8907 }
8908 break;
8909 }
8910 }
8911 }
8912
8913 /* Helper function to resize the payload in order to try to get a good
8914 alignment. We try to write an amount of data such that the next write will
8915 start on an address aligned on REMOTE_ALIGN_WRITES. */
8916
8917 static int
8918 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8919 {
8920 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8921 }
8922
8923 /* Write memory data directly to the remote machine.
8924 This does not inform the data cache; the data cache uses this.
8925 HEADER is the starting part of the packet.
8926 MEMADDR is the address in the remote memory space.
8927 MYADDR is the address of the buffer in our space.
8928 LEN_UNITS is the number of addressable units to write.
8929 UNIT_SIZE is the length in bytes of an addressable unit.
8930 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8931 should send data as binary ('X'), or hex-encoded ('M').
8932
8933 The function creates packet of the form
8934 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8935
8936 where encoding of <DATA> is terminated by PACKET_FORMAT.
8937
8938 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8939 are omitted.
8940
8941 Return the transferred status, error or OK (an
8942 'enum target_xfer_status' value). Save the number of addressable units
8943 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8944
8945 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8946 exchange between gdb and the stub could look like (?? in place of the
8947 checksum):
8948
8949 -> $m1000,4#??
8950 <- aaaabbbbccccdddd
8951
8952 -> $M1000,3:eeeeffffeeee#??
8953 <- OK
8954
8955 -> $m1000,4#??
8956 <- eeeeffffeeeedddd */
8957
8958 target_xfer_status
8959 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8960 const gdb_byte *myaddr,
8961 ULONGEST len_units,
8962 int unit_size,
8963 ULONGEST *xfered_len_units,
8964 char packet_format, int use_length)
8965 {
8966 struct remote_state *rs = get_remote_state ();
8967 char *p;
8968 char *plen = NULL;
8969 int plenlen = 0;
8970 int todo_units;
8971 int units_written;
8972 int payload_capacity_bytes;
8973 int payload_length_bytes;
8974
8975 if (packet_format != 'X' && packet_format != 'M')
8976 internal_error (__FILE__, __LINE__,
8977 _("remote_write_bytes_aux: bad packet format"));
8978
8979 if (len_units == 0)
8980 return TARGET_XFER_EOF;
8981
8982 payload_capacity_bytes = get_memory_write_packet_size ();
8983
8984 /* The packet buffer will be large enough for the payload;
8985 get_memory_packet_size ensures this. */
8986 rs->buf[0] = '\0';
8987
8988 /* Compute the size of the actual payload by subtracting out the
8989 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8990
8991 payload_capacity_bytes -= strlen ("$,:#NN");
8992 if (!use_length)
8993 /* The comma won't be used. */
8994 payload_capacity_bytes += 1;
8995 payload_capacity_bytes -= strlen (header);
8996 payload_capacity_bytes -= hexnumlen (memaddr);
8997
8998 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
8999
9000 strcat (rs->buf.data (), header);
9001 p = rs->buf.data () + strlen (header);
9002
9003 /* Compute a best guess of the number of bytes actually transfered. */
9004 if (packet_format == 'X')
9005 {
9006 /* Best guess at number of bytes that will fit. */
9007 todo_units = std::min (len_units,
9008 (ULONGEST) payload_capacity_bytes / unit_size);
9009 if (use_length)
9010 payload_capacity_bytes -= hexnumlen (todo_units);
9011 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9012 }
9013 else
9014 {
9015 /* Number of bytes that will fit. */
9016 todo_units
9017 = std::min (len_units,
9018 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9019 if (use_length)
9020 payload_capacity_bytes -= hexnumlen (todo_units);
9021 todo_units = std::min (todo_units,
9022 (payload_capacity_bytes / unit_size) / 2);
9023 }
9024
9025 if (todo_units <= 0)
9026 internal_error (__FILE__, __LINE__,
9027 _("minimum packet size too small to write data"));
9028
9029 /* If we already need another packet, then try to align the end
9030 of this packet to a useful boundary. */
9031 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9032 todo_units = align_for_efficient_write (todo_units, memaddr);
9033
9034 /* Append "<memaddr>". */
9035 memaddr = remote_address_masked (memaddr);
9036 p += hexnumstr (p, (ULONGEST) memaddr);
9037
9038 if (use_length)
9039 {
9040 /* Append ",". */
9041 *p++ = ',';
9042
9043 /* Append the length and retain its location and size. It may need to be
9044 adjusted once the packet body has been created. */
9045 plen = p;
9046 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9047 p += plenlen;
9048 }
9049
9050 /* Append ":". */
9051 *p++ = ':';
9052 *p = '\0';
9053
9054 /* Append the packet body. */
9055 if (packet_format == 'X')
9056 {
9057 /* Binary mode. Send target system values byte by byte, in
9058 increasing byte addresses. Only escape certain critical
9059 characters. */
9060 payload_length_bytes =
9061 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9062 &units_written, payload_capacity_bytes);
9063
9064 /* If not all TODO units fit, then we'll need another packet. Make
9065 a second try to keep the end of the packet aligned. Don't do
9066 this if the packet is tiny. */
9067 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9068 {
9069 int new_todo_units;
9070
9071 new_todo_units = align_for_efficient_write (units_written, memaddr);
9072
9073 if (new_todo_units != units_written)
9074 payload_length_bytes =
9075 remote_escape_output (myaddr, new_todo_units, unit_size,
9076 (gdb_byte *) p, &units_written,
9077 payload_capacity_bytes);
9078 }
9079
9080 p += payload_length_bytes;
9081 if (use_length && units_written < todo_units)
9082 {
9083 /* Escape chars have filled up the buffer prematurely,
9084 and we have actually sent fewer units than planned.
9085 Fix-up the length field of the packet. Use the same
9086 number of characters as before. */
9087 plen += hexnumnstr (plen, (ULONGEST) units_written,
9088 plenlen);
9089 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9090 }
9091 }
9092 else
9093 {
9094 /* Normal mode: Send target system values byte by byte, in
9095 increasing byte addresses. Each byte is encoded as a two hex
9096 value. */
9097 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9098 units_written = todo_units;
9099 }
9100
9101 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9102 getpkt (&rs->buf, 0);
9103
9104 if (rs->buf[0] == 'E')
9105 return TARGET_XFER_E_IO;
9106
9107 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9108 send fewer units than we'd planned. */
9109 *xfered_len_units = (ULONGEST) units_written;
9110 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9111 }
9112
9113 /* Write memory data directly to the remote machine.
9114 This does not inform the data cache; the data cache uses this.
9115 MEMADDR is the address in the remote memory space.
9116 MYADDR is the address of the buffer in our space.
9117 LEN is the number of bytes.
9118
9119 Return the transferred status, error or OK (an
9120 'enum target_xfer_status' value). Save the number of bytes
9121 transferred in *XFERED_LEN. Only transfer a single packet. */
9122
9123 target_xfer_status
9124 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9125 ULONGEST len, int unit_size,
9126 ULONGEST *xfered_len)
9127 {
9128 const char *packet_format = NULL;
9129
9130 /* Check whether the target supports binary download. */
9131 check_binary_download (memaddr);
9132
9133 switch (packet_support (PACKET_X))
9134 {
9135 case PACKET_ENABLE:
9136 packet_format = "X";
9137 break;
9138 case PACKET_DISABLE:
9139 packet_format = "M";
9140 break;
9141 case PACKET_SUPPORT_UNKNOWN:
9142 internal_error (__FILE__, __LINE__,
9143 _("remote_write_bytes: bad internal state"));
9144 default:
9145 internal_error (__FILE__, __LINE__, _("bad switch"));
9146 }
9147
9148 return remote_write_bytes_aux (packet_format,
9149 memaddr, myaddr, len, unit_size, xfered_len,
9150 packet_format[0], 1);
9151 }
9152
9153 /* Read memory data directly from the remote machine.
9154 This does not use the data cache; the data cache uses this.
9155 MEMADDR is the address in the remote memory space.
9156 MYADDR is the address of the buffer in our space.
9157 LEN_UNITS is the number of addressable memory units to read..
9158 UNIT_SIZE is the length in bytes of an addressable unit.
9159
9160 Return the transferred status, error or OK (an
9161 'enum target_xfer_status' value). Save the number of bytes
9162 transferred in *XFERED_LEN_UNITS.
9163
9164 See the comment of remote_write_bytes_aux for an example of
9165 memory read/write exchange between gdb and the stub. */
9166
9167 target_xfer_status
9168 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9169 ULONGEST len_units,
9170 int unit_size, ULONGEST *xfered_len_units)
9171 {
9172 struct remote_state *rs = get_remote_state ();
9173 int buf_size_bytes; /* Max size of packet output buffer. */
9174 char *p;
9175 int todo_units;
9176 int decoded_bytes;
9177
9178 buf_size_bytes = get_memory_read_packet_size ();
9179 /* The packet buffer will be large enough for the payload;
9180 get_memory_packet_size ensures this. */
9181
9182 /* Number of units that will fit. */
9183 todo_units = std::min (len_units,
9184 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9185
9186 /* Construct "m"<memaddr>","<len>". */
9187 memaddr = remote_address_masked (memaddr);
9188 p = rs->buf.data ();
9189 *p++ = 'm';
9190 p += hexnumstr (p, (ULONGEST) memaddr);
9191 *p++ = ',';
9192 p += hexnumstr (p, (ULONGEST) todo_units);
9193 *p = '\0';
9194 putpkt (rs->buf);
9195 getpkt (&rs->buf, 0);
9196 if (rs->buf[0] == 'E'
9197 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9198 && rs->buf[3] == '\0')
9199 return TARGET_XFER_E_IO;
9200 /* Reply describes memory byte by byte, each byte encoded as two hex
9201 characters. */
9202 p = rs->buf.data ();
9203 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9204 /* Return what we have. Let higher layers handle partial reads. */
9205 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9206 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9207 }
9208
9209 /* Using the set of read-only target sections of remote, read live
9210 read-only memory.
9211
9212 For interface/parameters/return description see target.h,
9213 to_xfer_partial. */
9214
9215 target_xfer_status
9216 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9217 ULONGEST memaddr,
9218 ULONGEST len,
9219 int unit_size,
9220 ULONGEST *xfered_len)
9221 {
9222 const struct target_section *secp;
9223
9224 secp = target_section_by_addr (this, memaddr);
9225 if (secp != NULL
9226 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9227 {
9228 ULONGEST memend = memaddr + len;
9229
9230 const target_section_table *table = target_get_section_table (this);
9231 for (const target_section &p : *table)
9232 {
9233 if (memaddr >= p.addr)
9234 {
9235 if (memend <= p.endaddr)
9236 {
9237 /* Entire transfer is within this section. */
9238 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9239 xfered_len);
9240 }
9241 else if (memaddr >= p.endaddr)
9242 {
9243 /* This section ends before the transfer starts. */
9244 continue;
9245 }
9246 else
9247 {
9248 /* This section overlaps the transfer. Just do half. */
9249 len = p.endaddr - memaddr;
9250 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9251 xfered_len);
9252 }
9253 }
9254 }
9255 }
9256
9257 return TARGET_XFER_EOF;
9258 }
9259
9260 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9261 first if the requested memory is unavailable in traceframe.
9262 Otherwise, fall back to remote_read_bytes_1. */
9263
9264 target_xfer_status
9265 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9266 gdb_byte *myaddr, ULONGEST len, int unit_size,
9267 ULONGEST *xfered_len)
9268 {
9269 if (len == 0)
9270 return TARGET_XFER_EOF;
9271
9272 if (get_traceframe_number () != -1)
9273 {
9274 std::vector<mem_range> available;
9275
9276 /* If we fail to get the set of available memory, then the
9277 target does not support querying traceframe info, and so we
9278 attempt reading from the traceframe anyway (assuming the
9279 target implements the old QTro packet then). */
9280 if (traceframe_available_memory (&available, memaddr, len))
9281 {
9282 if (available.empty () || available[0].start != memaddr)
9283 {
9284 enum target_xfer_status res;
9285
9286 /* Don't read into the traceframe's available
9287 memory. */
9288 if (!available.empty ())
9289 {
9290 LONGEST oldlen = len;
9291
9292 len = available[0].start - memaddr;
9293 gdb_assert (len <= oldlen);
9294 }
9295
9296 /* This goes through the topmost target again. */
9297 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9298 len, unit_size, xfered_len);
9299 if (res == TARGET_XFER_OK)
9300 return TARGET_XFER_OK;
9301 else
9302 {
9303 /* No use trying further, we know some memory starting
9304 at MEMADDR isn't available. */
9305 *xfered_len = len;
9306 return (*xfered_len != 0) ?
9307 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9308 }
9309 }
9310
9311 /* Don't try to read more than how much is available, in
9312 case the target implements the deprecated QTro packet to
9313 cater for older GDBs (the target's knowledge of read-only
9314 sections may be outdated by now). */
9315 len = available[0].length;
9316 }
9317 }
9318
9319 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9320 }
9321
9322 \f
9323
9324 /* Sends a packet with content determined by the printf format string
9325 FORMAT and the remaining arguments, then gets the reply. Returns
9326 whether the packet was a success, a failure, or unknown. */
9327
9328 packet_result
9329 remote_target::remote_send_printf (const char *format, ...)
9330 {
9331 struct remote_state *rs = get_remote_state ();
9332 int max_size = get_remote_packet_size ();
9333 va_list ap;
9334
9335 va_start (ap, format);
9336
9337 rs->buf[0] = '\0';
9338 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9339
9340 va_end (ap);
9341
9342 if (size >= max_size)
9343 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
9344
9345 if (putpkt (rs->buf) < 0)
9346 error (_("Communication problem with target."));
9347
9348 rs->buf[0] = '\0';
9349 getpkt (&rs->buf, 0);
9350
9351 return packet_check_result (rs->buf);
9352 }
9353
9354 /* Flash writing can take quite some time. We'll set
9355 effectively infinite timeout for flash operations.
9356 In future, we'll need to decide on a better approach. */
9357 static const int remote_flash_timeout = 1000;
9358
9359 void
9360 remote_target::flash_erase (ULONGEST address, LONGEST length)
9361 {
9362 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9363 enum packet_result ret;
9364 scoped_restore restore_timeout
9365 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9366
9367 ret = remote_send_printf ("vFlashErase:%s,%s",
9368 phex (address, addr_size),
9369 phex (length, 4));
9370 switch (ret)
9371 {
9372 case PACKET_UNKNOWN:
9373 error (_("Remote target does not support flash erase"));
9374 case PACKET_ERROR:
9375 error (_("Error erasing flash with vFlashErase packet"));
9376 default:
9377 break;
9378 }
9379 }
9380
9381 target_xfer_status
9382 remote_target::remote_flash_write (ULONGEST address,
9383 ULONGEST length, ULONGEST *xfered_len,
9384 const gdb_byte *data)
9385 {
9386 scoped_restore restore_timeout
9387 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9388 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9389 xfered_len,'X', 0);
9390 }
9391
9392 void
9393 remote_target::flash_done ()
9394 {
9395 int ret;
9396
9397 scoped_restore restore_timeout
9398 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9399
9400 ret = remote_send_printf ("vFlashDone");
9401
9402 switch (ret)
9403 {
9404 case PACKET_UNKNOWN:
9405 error (_("Remote target does not support vFlashDone"));
9406 case PACKET_ERROR:
9407 error (_("Error finishing flash operation"));
9408 default:
9409 break;
9410 }
9411 }
9412
9413 \f
9414 /* Stuff for dealing with the packets which are part of this protocol.
9415 See comment at top of file for details. */
9416
9417 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9418 error to higher layers. Called when a serial error is detected.
9419 The exception message is STRING, followed by a colon and a blank,
9420 the system error message for errno at function entry and final dot
9421 for output compatibility with throw_perror_with_name. */
9422
9423 static void
9424 unpush_and_perror (remote_target *target, const char *string)
9425 {
9426 int saved_errno = errno;
9427
9428 remote_unpush_target (target);
9429 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9430 safe_strerror (saved_errno));
9431 }
9432
9433 /* Read a single character from the remote end. The current quit
9434 handler is overridden to avoid quitting in the middle of packet
9435 sequence, as that would break communication with the remote server.
9436 See remote_serial_quit_handler for more detail. */
9437
9438 int
9439 remote_target::readchar (int timeout)
9440 {
9441 int ch;
9442 struct remote_state *rs = get_remote_state ();
9443
9444 {
9445 scoped_restore restore_quit_target
9446 = make_scoped_restore (&curr_quit_handler_target, this);
9447 scoped_restore restore_quit
9448 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9449
9450 rs->got_ctrlc_during_io = 0;
9451
9452 ch = serial_readchar (rs->remote_desc, timeout);
9453
9454 if (rs->got_ctrlc_during_io)
9455 set_quit_flag ();
9456 }
9457
9458 if (ch >= 0)
9459 return ch;
9460
9461 switch ((enum serial_rc) ch)
9462 {
9463 case SERIAL_EOF:
9464 remote_unpush_target (this);
9465 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9466 /* no return */
9467 case SERIAL_ERROR:
9468 unpush_and_perror (this, _("Remote communication error. "
9469 "Target disconnected."));
9470 /* no return */
9471 case SERIAL_TIMEOUT:
9472 break;
9473 }
9474 return ch;
9475 }
9476
9477 /* Wrapper for serial_write that closes the target and throws if
9478 writing fails. The current quit handler is overridden to avoid
9479 quitting in the middle of packet sequence, as that would break
9480 communication with the remote server. See
9481 remote_serial_quit_handler for more detail. */
9482
9483 void
9484 remote_target::remote_serial_write (const char *str, int len)
9485 {
9486 struct remote_state *rs = get_remote_state ();
9487
9488 scoped_restore restore_quit_target
9489 = make_scoped_restore (&curr_quit_handler_target, this);
9490 scoped_restore restore_quit
9491 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9492
9493 rs->got_ctrlc_during_io = 0;
9494
9495 if (serial_write (rs->remote_desc, str, len))
9496 {
9497 unpush_and_perror (this, _("Remote communication error. "
9498 "Target disconnected."));
9499 }
9500
9501 if (rs->got_ctrlc_during_io)
9502 set_quit_flag ();
9503 }
9504
9505 /* Return a string representing an escaped version of BUF, of len N.
9506 E.g. \n is converted to \\n, \t to \\t, etc. */
9507
9508 static std::string
9509 escape_buffer (const char *buf, int n)
9510 {
9511 string_file stb;
9512
9513 stb.putstrn (buf, n, '\\');
9514 return stb.release ();
9515 }
9516
9517 int
9518 remote_target::putpkt (const char *buf)
9519 {
9520 return putpkt_binary (buf, strlen (buf));
9521 }
9522
9523 /* Wrapper around remote_target::putpkt to avoid exporting
9524 remote_target. */
9525
9526 int
9527 putpkt (remote_target *remote, const char *buf)
9528 {
9529 return remote->putpkt (buf);
9530 }
9531
9532 /* Send a packet to the remote machine, with error checking. The data
9533 of the packet is in BUF. The string in BUF can be at most
9534 get_remote_packet_size () - 5 to account for the $, # and checksum,
9535 and for a possible /0 if we are debugging (remote_debug) and want
9536 to print the sent packet as a string. */
9537
9538 int
9539 remote_target::putpkt_binary (const char *buf, int cnt)
9540 {
9541 struct remote_state *rs = get_remote_state ();
9542 int i;
9543 unsigned char csum = 0;
9544 gdb::def_vector<char> data (cnt + 6);
9545 char *buf2 = data.data ();
9546
9547 int ch;
9548 int tcount = 0;
9549 char *p;
9550
9551 /* Catch cases like trying to read memory or listing threads while
9552 we're waiting for a stop reply. The remote server wouldn't be
9553 ready to handle this request, so we'd hang and timeout. We don't
9554 have to worry about this in synchronous mode, because in that
9555 case it's not possible to issue a command while the target is
9556 running. This is not a problem in non-stop mode, because in that
9557 case, the stub is always ready to process serial input. */
9558 if (!target_is_non_stop_p ()
9559 && target_is_async_p ()
9560 && rs->waiting_for_stop_reply)
9561 {
9562 error (_("Cannot execute this command while the target is running.\n"
9563 "Use the \"interrupt\" command to stop the target\n"
9564 "and then try again."));
9565 }
9566
9567 /* Copy the packet into buffer BUF2, encapsulating it
9568 and giving it a checksum. */
9569
9570 p = buf2;
9571 *p++ = '$';
9572
9573 for (i = 0; i < cnt; i++)
9574 {
9575 csum += buf[i];
9576 *p++ = buf[i];
9577 }
9578 *p++ = '#';
9579 *p++ = tohex ((csum >> 4) & 0xf);
9580 *p++ = tohex (csum & 0xf);
9581
9582 /* Send it over and over until we get a positive ack. */
9583
9584 while (1)
9585 {
9586 if (remote_debug)
9587 {
9588 *p = '\0';
9589
9590 int len = (int) (p - buf2);
9591 int max_chars;
9592
9593 if (remote_packet_max_chars < 0)
9594 max_chars = len;
9595 else
9596 max_chars = remote_packet_max_chars;
9597
9598 std::string str
9599 = escape_buffer (buf2, std::min (len, max_chars));
9600
9601 if (len > max_chars)
9602 remote_debug_printf_nofunc
9603 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9604 len - max_chars);
9605 else
9606 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9607 }
9608 remote_serial_write (buf2, p - buf2);
9609
9610 /* If this is a no acks version of the remote protocol, send the
9611 packet and move on. */
9612 if (rs->noack_mode)
9613 break;
9614
9615 /* Read until either a timeout occurs (-2) or '+' is read.
9616 Handle any notification that arrives in the mean time. */
9617 while (1)
9618 {
9619 ch = readchar (remote_timeout);
9620
9621 switch (ch)
9622 {
9623 case '+':
9624 remote_debug_printf_nofunc ("Received Ack");
9625 return 1;
9626 case '-':
9627 remote_debug_printf_nofunc ("Received Nak");
9628 /* FALLTHROUGH */
9629 case SERIAL_TIMEOUT:
9630 tcount++;
9631 if (tcount > 3)
9632 return 0;
9633 break; /* Retransmit buffer. */
9634 case '$':
9635 {
9636 remote_debug_printf ("Packet instead of Ack, ignoring it");
9637 /* It's probably an old response sent because an ACK
9638 was lost. Gobble up the packet and ack it so it
9639 doesn't get retransmitted when we resend this
9640 packet. */
9641 skip_frame ();
9642 remote_serial_write ("+", 1);
9643 continue; /* Now, go look for +. */
9644 }
9645
9646 case '%':
9647 {
9648 int val;
9649
9650 /* If we got a notification, handle it, and go back to looking
9651 for an ack. */
9652 /* We've found the start of a notification. Now
9653 collect the data. */
9654 val = read_frame (&rs->buf);
9655 if (val >= 0)
9656 {
9657 remote_debug_printf_nofunc
9658 (" Notification received: %s",
9659 escape_buffer (rs->buf.data (), val).c_str ());
9660
9661 handle_notification (rs->notif_state, rs->buf.data ());
9662 /* We're in sync now, rewait for the ack. */
9663 tcount = 0;
9664 }
9665 else
9666 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9667 rs->buf.data ());
9668 continue;
9669 }
9670 /* fall-through */
9671 default:
9672 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9673 rs->buf.data ());
9674 continue;
9675 }
9676 break; /* Here to retransmit. */
9677 }
9678
9679 #if 0
9680 /* This is wrong. If doing a long backtrace, the user should be
9681 able to get out next time we call QUIT, without anything as
9682 violent as interrupt_query. If we want to provide a way out of
9683 here without getting to the next QUIT, it should be based on
9684 hitting ^C twice as in remote_wait. */
9685 if (quit_flag)
9686 {
9687 quit_flag = 0;
9688 interrupt_query ();
9689 }
9690 #endif
9691 }
9692
9693 return 0;
9694 }
9695
9696 /* Come here after finding the start of a frame when we expected an
9697 ack. Do our best to discard the rest of this packet. */
9698
9699 void
9700 remote_target::skip_frame ()
9701 {
9702 int c;
9703
9704 while (1)
9705 {
9706 c = readchar (remote_timeout);
9707 switch (c)
9708 {
9709 case SERIAL_TIMEOUT:
9710 /* Nothing we can do. */
9711 return;
9712 case '#':
9713 /* Discard the two bytes of checksum and stop. */
9714 c = readchar (remote_timeout);
9715 if (c >= 0)
9716 c = readchar (remote_timeout);
9717
9718 return;
9719 case '*': /* Run length encoding. */
9720 /* Discard the repeat count. */
9721 c = readchar (remote_timeout);
9722 if (c < 0)
9723 return;
9724 break;
9725 default:
9726 /* A regular character. */
9727 break;
9728 }
9729 }
9730 }
9731
9732 /* Come here after finding the start of the frame. Collect the rest
9733 into *BUF, verifying the checksum, length, and handling run-length
9734 compression. NUL terminate the buffer. If there is not enough room,
9735 expand *BUF.
9736
9737 Returns -1 on error, number of characters in buffer (ignoring the
9738 trailing NULL) on success. (could be extended to return one of the
9739 SERIAL status indications). */
9740
9741 long
9742 remote_target::read_frame (gdb::char_vector *buf_p)
9743 {
9744 unsigned char csum;
9745 long bc;
9746 int c;
9747 char *buf = buf_p->data ();
9748 struct remote_state *rs = get_remote_state ();
9749
9750 csum = 0;
9751 bc = 0;
9752
9753 while (1)
9754 {
9755 c = readchar (remote_timeout);
9756 switch (c)
9757 {
9758 case SERIAL_TIMEOUT:
9759 remote_debug_printf ("Timeout in mid-packet, retrying");
9760 return -1;
9761
9762 case '$':
9763 remote_debug_printf ("Saw new packet start in middle of old one");
9764 return -1; /* Start a new packet, count retries. */
9765
9766 case '#':
9767 {
9768 unsigned char pktcsum;
9769 int check_0 = 0;
9770 int check_1 = 0;
9771
9772 buf[bc] = '\0';
9773
9774 check_0 = readchar (remote_timeout);
9775 if (check_0 >= 0)
9776 check_1 = readchar (remote_timeout);
9777
9778 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9779 {
9780 remote_debug_printf ("Timeout in checksum, retrying");
9781 return -1;
9782 }
9783 else if (check_0 < 0 || check_1 < 0)
9784 {
9785 remote_debug_printf ("Communication error in checksum");
9786 return -1;
9787 }
9788
9789 /* Don't recompute the checksum; with no ack packets we
9790 don't have any way to indicate a packet retransmission
9791 is necessary. */
9792 if (rs->noack_mode)
9793 return bc;
9794
9795 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9796 if (csum == pktcsum)
9797 return bc;
9798
9799 remote_debug_printf
9800 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
9801 pktcsum, csum, escape_buffer (buf, bc).c_str ());
9802
9803 /* Number of characters in buffer ignoring trailing
9804 NULL. */
9805 return -1;
9806 }
9807 case '*': /* Run length encoding. */
9808 {
9809 int repeat;
9810
9811 csum += c;
9812 c = readchar (remote_timeout);
9813 csum += c;
9814 repeat = c - ' ' + 3; /* Compute repeat count. */
9815
9816 /* The character before ``*'' is repeated. */
9817
9818 if (repeat > 0 && repeat <= 255 && bc > 0)
9819 {
9820 if (bc + repeat - 1 >= buf_p->size () - 1)
9821 {
9822 /* Make some more room in the buffer. */
9823 buf_p->resize (buf_p->size () + repeat);
9824 buf = buf_p->data ();
9825 }
9826
9827 memset (&buf[bc], buf[bc - 1], repeat);
9828 bc += repeat;
9829 continue;
9830 }
9831
9832 buf[bc] = '\0';
9833 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
9834 return -1;
9835 }
9836 default:
9837 if (bc >= buf_p->size () - 1)
9838 {
9839 /* Make some more room in the buffer. */
9840 buf_p->resize (buf_p->size () * 2);
9841 buf = buf_p->data ();
9842 }
9843
9844 buf[bc++] = c;
9845 csum += c;
9846 continue;
9847 }
9848 }
9849 }
9850
9851 /* Set this to the maximum number of seconds to wait instead of waiting forever
9852 in target_wait(). If this timer times out, then it generates an error and
9853 the command is aborted. This replaces most of the need for timeouts in the
9854 GDB test suite, and makes it possible to distinguish between a hung target
9855 and one with slow communications. */
9856
9857 static int watchdog = 0;
9858 static void
9859 show_watchdog (struct ui_file *file, int from_tty,
9860 struct cmd_list_element *c, const char *value)
9861 {
9862 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
9863 }
9864
9865 /* Read a packet from the remote machine, with error checking, and
9866 store it in *BUF. Resize *BUF if necessary to hold the result. If
9867 FOREVER, wait forever rather than timing out; this is used (in
9868 synchronous mode) to wait for a target that is is executing user
9869 code to stop. */
9870 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9871 don't have to change all the calls to getpkt to deal with the
9872 return value, because at the moment I don't know what the right
9873 thing to do it for those. */
9874
9875 void
9876 remote_target::getpkt (gdb::char_vector *buf, int forever)
9877 {
9878 getpkt_sane (buf, forever);
9879 }
9880
9881
9882 /* Read a packet from the remote machine, with error checking, and
9883 store it in *BUF. Resize *BUF if necessary to hold the result. If
9884 FOREVER, wait forever rather than timing out; this is used (in
9885 synchronous mode) to wait for a target that is is executing user
9886 code to stop. If FOREVER == 0, this function is allowed to time
9887 out gracefully and return an indication of this to the caller.
9888 Otherwise return the number of bytes read. If EXPECTING_NOTIF,
9889 consider receiving a notification enough reason to return to the
9890 caller. *IS_NOTIF is an output boolean that indicates whether *BUF
9891 holds a notification or not (a regular packet). */
9892
9893 int
9894 remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
9895 int forever, int expecting_notif,
9896 int *is_notif)
9897 {
9898 struct remote_state *rs = get_remote_state ();
9899 int c;
9900 int tries;
9901 int timeout;
9902 int val = -1;
9903
9904 strcpy (buf->data (), "timeout");
9905
9906 if (forever)
9907 timeout = watchdog > 0 ? watchdog : -1;
9908 else if (expecting_notif)
9909 timeout = 0; /* There should already be a char in the buffer. If
9910 not, bail out. */
9911 else
9912 timeout = remote_timeout;
9913
9914 #define MAX_TRIES 3
9915
9916 /* Process any number of notifications, and then return when
9917 we get a packet. */
9918 for (;;)
9919 {
9920 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9921 times. */
9922 for (tries = 1; tries <= MAX_TRIES; tries++)
9923 {
9924 /* This can loop forever if the remote side sends us
9925 characters continuously, but if it pauses, we'll get
9926 SERIAL_TIMEOUT from readchar because of timeout. Then
9927 we'll count that as a retry.
9928
9929 Note that even when forever is set, we will only wait
9930 forever prior to the start of a packet. After that, we
9931 expect characters to arrive at a brisk pace. They should
9932 show up within remote_timeout intervals. */
9933 do
9934 c = readchar (timeout);
9935 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9936
9937 if (c == SERIAL_TIMEOUT)
9938 {
9939 if (expecting_notif)
9940 return -1; /* Don't complain, it's normal to not get
9941 anything in this case. */
9942
9943 if (forever) /* Watchdog went off? Kill the target. */
9944 {
9945 remote_unpush_target (this);
9946 throw_error (TARGET_CLOSE_ERROR,
9947 _("Watchdog timeout has expired. "
9948 "Target detached."));
9949 }
9950
9951 remote_debug_printf ("Timed out.");
9952 }
9953 else
9954 {
9955 /* We've found the start of a packet or notification.
9956 Now collect the data. */
9957 val = read_frame (buf);
9958 if (val >= 0)
9959 break;
9960 }
9961
9962 remote_serial_write ("-", 1);
9963 }
9964
9965 if (tries > MAX_TRIES)
9966 {
9967 /* We have tried hard enough, and just can't receive the
9968 packet/notification. Give up. */
9969 gdb_printf (_("Ignoring packet error, continuing...\n"));
9970
9971 /* Skip the ack char if we're in no-ack mode. */
9972 if (!rs->noack_mode)
9973 remote_serial_write ("+", 1);
9974 return -1;
9975 }
9976
9977 /* If we got an ordinary packet, return that to our caller. */
9978 if (c == '$')
9979 {
9980 if (remote_debug)
9981 {
9982 int max_chars;
9983
9984 if (remote_packet_max_chars < 0)
9985 max_chars = val;
9986 else
9987 max_chars = remote_packet_max_chars;
9988
9989 std::string str
9990 = escape_buffer (buf->data (),
9991 std::min (val, max_chars));
9992
9993 if (val > max_chars)
9994 remote_debug_printf_nofunc
9995 ("Packet received: %s [%d bytes omitted]", str.c_str (),
9996 val - max_chars);
9997 else
9998 remote_debug_printf_nofunc ("Packet received: %s",
9999 str.c_str ());
10000 }
10001
10002 /* Skip the ack char if we're in no-ack mode. */
10003 if (!rs->noack_mode)
10004 remote_serial_write ("+", 1);
10005 if (is_notif != NULL)
10006 *is_notif = 0;
10007 return val;
10008 }
10009
10010 /* If we got a notification, handle it, and go back to looking
10011 for a packet. */
10012 else
10013 {
10014 gdb_assert (c == '%');
10015
10016 remote_debug_printf_nofunc
10017 (" Notification received: %s",
10018 escape_buffer (buf->data (), val).c_str ());
10019
10020 if (is_notif != NULL)
10021 *is_notif = 1;
10022
10023 handle_notification (rs->notif_state, buf->data ());
10024
10025 /* Notifications require no acknowledgement. */
10026
10027 if (expecting_notif)
10028 return val;
10029 }
10030 }
10031 }
10032
10033 int
10034 remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
10035 {
10036 return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
10037 }
10038
10039 int
10040 remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
10041 int *is_notif)
10042 {
10043 return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
10044 }
10045
10046 /* Kill any new fork children of inferior INF that haven't been
10047 processed by follow_fork. */
10048
10049 void
10050 remote_target::kill_new_fork_children (inferior *inf)
10051 {
10052 remote_state *rs = get_remote_state ();
10053 struct notif_client *notif = &notif_client_stop;
10054
10055 /* Kill the fork child threads of any threads in inferior INF that are stopped
10056 at a fork event. */
10057 for (thread_info *thread : inf->non_exited_threads ())
10058 {
10059 const target_waitstatus *ws = thread_pending_fork_status (thread);
10060
10061 if (ws == nullptr)
10062 continue;
10063
10064 int child_pid = ws->child_ptid ().pid ();
10065 int res = remote_vkill (child_pid);
10066
10067 if (res != 0)
10068 error (_("Can't kill fork child process %d"), child_pid);
10069 }
10070
10071 /* Check for any pending fork events (not reported or processed yet)
10072 in inferior INF and kill those fork child threads as well. */
10073 remote_notif_get_pending_events (notif);
10074 for (auto &event : rs->stop_reply_queue)
10075 {
10076 if (event->ptid.pid () != inf->pid)
10077 continue;
10078
10079 if (!is_fork_status (event->ws.kind ()))
10080 continue;
10081
10082 int child_pid = event->ws.child_ptid ().pid ();
10083 int res = remote_vkill (child_pid);
10084
10085 if (res != 0)
10086 error (_("Can't kill fork child process %d"), child_pid);
10087 }
10088 }
10089
10090 \f
10091 /* Target hook to kill the current inferior. */
10092
10093 void
10094 remote_target::kill ()
10095 {
10096 int res = -1;
10097 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10098 struct remote_state *rs = get_remote_state ();
10099
10100 gdb_assert (inf != nullptr);
10101
10102 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
10103 {
10104 /* If we're stopped while forking and we haven't followed yet,
10105 kill the child task. We need to do this before killing the
10106 parent task because if this is a vfork then the parent will
10107 be sleeping. */
10108 kill_new_fork_children (inf);
10109
10110 res = remote_vkill (inf->pid);
10111 if (res == 0)
10112 {
10113 target_mourn_inferior (inferior_ptid);
10114 return;
10115 }
10116 }
10117
10118 /* If we are in 'target remote' mode and we are killing the only
10119 inferior, then we will tell gdbserver to exit and unpush the
10120 target. */
10121 if (res == -1 && !remote_multi_process_p (rs)
10122 && number_of_live_inferiors (this) == 1)
10123 {
10124 remote_kill_k ();
10125
10126 /* We've killed the remote end, we get to mourn it. If we are
10127 not in extended mode, mourning the inferior also unpushes
10128 remote_ops from the target stack, which closes the remote
10129 connection. */
10130 target_mourn_inferior (inferior_ptid);
10131
10132 return;
10133 }
10134
10135 error (_("Can't kill process"));
10136 }
10137
10138 /* Send a kill request to the target using the 'vKill' packet. */
10139
10140 int
10141 remote_target::remote_vkill (int pid)
10142 {
10143 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
10144 return -1;
10145
10146 remote_state *rs = get_remote_state ();
10147
10148 /* Tell the remote target to detach. */
10149 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10150 putpkt (rs->buf);
10151 getpkt (&rs->buf, 0);
10152
10153 switch (packet_ok (rs->buf,
10154 &remote_protocol_packets[PACKET_vKill]))
10155 {
10156 case PACKET_OK:
10157 return 0;
10158 case PACKET_ERROR:
10159 return 1;
10160 case PACKET_UNKNOWN:
10161 return -1;
10162 default:
10163 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
10164 }
10165 }
10166
10167 /* Send a kill request to the target using the 'k' packet. */
10168
10169 void
10170 remote_target::remote_kill_k ()
10171 {
10172 /* Catch errors so the user can quit from gdb even when we
10173 aren't on speaking terms with the remote system. */
10174 try
10175 {
10176 putpkt ("k");
10177 }
10178 catch (const gdb_exception_error &ex)
10179 {
10180 if (ex.error == TARGET_CLOSE_ERROR)
10181 {
10182 /* If we got an (EOF) error that caused the target
10183 to go away, then we're done, that's what we wanted.
10184 "k" is susceptible to cause a premature EOF, given
10185 that the remote server isn't actually required to
10186 reply to "k", and it can happen that it doesn't
10187 even get to reply ACK to the "k". */
10188 return;
10189 }
10190
10191 /* Otherwise, something went wrong. We didn't actually kill
10192 the target. Just propagate the exception, and let the
10193 user or higher layers decide what to do. */
10194 throw;
10195 }
10196 }
10197
10198 void
10199 remote_target::mourn_inferior ()
10200 {
10201 struct remote_state *rs = get_remote_state ();
10202
10203 /* We're no longer interested in notification events of an inferior
10204 that exited or was killed/detached. */
10205 discard_pending_stop_replies (current_inferior ());
10206
10207 /* In 'target remote' mode with one inferior, we close the connection. */
10208 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10209 {
10210 remote_unpush_target (this);
10211 return;
10212 }
10213
10214 /* In case we got here due to an error, but we're going to stay
10215 connected. */
10216 rs->waiting_for_stop_reply = 0;
10217
10218 /* If the current general thread belonged to the process we just
10219 detached from or has exited, the remote side current general
10220 thread becomes undefined. Considering a case like this:
10221
10222 - We just got here due to a detach.
10223 - The process that we're detaching from happens to immediately
10224 report a global breakpoint being hit in non-stop mode, in the
10225 same thread we had selected before.
10226 - GDB attaches to this process again.
10227 - This event happens to be the next event we handle.
10228
10229 GDB would consider that the current general thread didn't need to
10230 be set on the stub side (with Hg), since for all it knew,
10231 GENERAL_THREAD hadn't changed.
10232
10233 Notice that although in all-stop mode, the remote server always
10234 sets the current thread to the thread reporting the stop event,
10235 that doesn't happen in non-stop mode; in non-stop, the stub *must
10236 not* change the current thread when reporting a breakpoint hit,
10237 due to the decoupling of event reporting and event handling.
10238
10239 To keep things simple, we always invalidate our notion of the
10240 current thread. */
10241 record_currthread (rs, minus_one_ptid);
10242
10243 /* Call common code to mark the inferior as not running. */
10244 generic_mourn_inferior ();
10245 }
10246
10247 bool
10248 extended_remote_target::supports_disable_randomization ()
10249 {
10250 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
10251 }
10252
10253 void
10254 remote_target::extended_remote_disable_randomization (int val)
10255 {
10256 struct remote_state *rs = get_remote_state ();
10257 char *reply;
10258
10259 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10260 "QDisableRandomization:%x", val);
10261 putpkt (rs->buf);
10262 reply = remote_get_noisy_reply ();
10263 if (*reply == '\0')
10264 error (_("Target does not support QDisableRandomization."));
10265 if (strcmp (reply, "OK") != 0)
10266 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10267 }
10268
10269 int
10270 remote_target::extended_remote_run (const std::string &args)
10271 {
10272 struct remote_state *rs = get_remote_state ();
10273 int len;
10274 const char *remote_exec_file = get_remote_exec_file ();
10275
10276 /* If the user has disabled vRun support, or we have detected that
10277 support is not available, do not try it. */
10278 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
10279 return -1;
10280
10281 strcpy (rs->buf.data (), "vRun;");
10282 len = strlen (rs->buf.data ());
10283
10284 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10285 error (_("Remote file name too long for run packet"));
10286 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10287 strlen (remote_exec_file));
10288
10289 if (!args.empty ())
10290 {
10291 int i;
10292
10293 gdb_argv argv (args.c_str ());
10294 for (i = 0; argv[i] != NULL; i++)
10295 {
10296 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10297 error (_("Argument list too long for run packet"));
10298 rs->buf[len++] = ';';
10299 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10300 strlen (argv[i]));
10301 }
10302 }
10303
10304 rs->buf[len++] = '\0';
10305
10306 putpkt (rs->buf);
10307 getpkt (&rs->buf, 0);
10308
10309 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
10310 {
10311 case PACKET_OK:
10312 /* We have a wait response. All is well. */
10313 return 0;
10314 case PACKET_UNKNOWN:
10315 return -1;
10316 case PACKET_ERROR:
10317 if (remote_exec_file[0] == '\0')
10318 error (_("Running the default executable on the remote target failed; "
10319 "try \"set remote exec-file\"?"));
10320 else
10321 error (_("Running \"%s\" on the remote target failed"),
10322 remote_exec_file);
10323 default:
10324 gdb_assert_not_reached ("bad switch");
10325 }
10326 }
10327
10328 /* Helper function to send set/unset environment packets. ACTION is
10329 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10330 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10331 sent. */
10332
10333 void
10334 remote_target::send_environment_packet (const char *action,
10335 const char *packet,
10336 const char *value)
10337 {
10338 remote_state *rs = get_remote_state ();
10339
10340 /* Convert the environment variable to an hex string, which
10341 is the best format to be transmitted over the wire. */
10342 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10343 strlen (value));
10344
10345 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10346 "%s:%s", packet, encoded_value.c_str ());
10347
10348 putpkt (rs->buf);
10349 getpkt (&rs->buf, 0);
10350 if (strcmp (rs->buf.data (), "OK") != 0)
10351 warning (_("Unable to %s environment variable '%s' on remote."),
10352 action, value);
10353 }
10354
10355 /* Helper function to handle the QEnvironment* packets. */
10356
10357 void
10358 remote_target::extended_remote_environment_support ()
10359 {
10360 remote_state *rs = get_remote_state ();
10361
10362 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10363 {
10364 putpkt ("QEnvironmentReset");
10365 getpkt (&rs->buf, 0);
10366 if (strcmp (rs->buf.data (), "OK") != 0)
10367 warning (_("Unable to reset environment on remote."));
10368 }
10369
10370 gdb_environ *e = &current_inferior ()->environment;
10371
10372 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10373 for (const std::string &el : e->user_set_env ())
10374 send_environment_packet ("set", "QEnvironmentHexEncoded",
10375 el.c_str ());
10376
10377 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10378 for (const std::string &el : e->user_unset_env ())
10379 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10380 }
10381
10382 /* Helper function to set the current working directory for the
10383 inferior in the remote target. */
10384
10385 void
10386 remote_target::extended_remote_set_inferior_cwd ()
10387 {
10388 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10389 {
10390 const std::string &inferior_cwd = current_inferior ()->cwd ();
10391 remote_state *rs = get_remote_state ();
10392
10393 if (!inferior_cwd.empty ())
10394 {
10395 std::string hexpath
10396 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10397 inferior_cwd.size ());
10398
10399 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10400 "QSetWorkingDir:%s", hexpath.c_str ());
10401 }
10402 else
10403 {
10404 /* An empty inferior_cwd means that the user wants us to
10405 reset the remote server's inferior's cwd. */
10406 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10407 "QSetWorkingDir:");
10408 }
10409
10410 putpkt (rs->buf);
10411 getpkt (&rs->buf, 0);
10412 if (packet_ok (rs->buf,
10413 &remote_protocol_packets[PACKET_QSetWorkingDir])
10414 != PACKET_OK)
10415 error (_("\
10416 Remote replied unexpectedly while setting the inferior's working\n\
10417 directory: %s"),
10418 rs->buf.data ());
10419
10420 }
10421 }
10422
10423 /* In the extended protocol we want to be able to do things like
10424 "run" and have them basically work as expected. So we need
10425 a special create_inferior function. We support changing the
10426 executable file and the command line arguments, but not the
10427 environment. */
10428
10429 void
10430 extended_remote_target::create_inferior (const char *exec_file,
10431 const std::string &args,
10432 char **env, int from_tty)
10433 {
10434 int run_worked;
10435 char *stop_reply;
10436 struct remote_state *rs = get_remote_state ();
10437 const char *remote_exec_file = get_remote_exec_file ();
10438
10439 /* If running asynchronously, register the target file descriptor
10440 with the event loop. */
10441 if (target_can_async_p ())
10442 target_async (1);
10443
10444 /* Disable address space randomization if requested (and supported). */
10445 if (supports_disable_randomization ())
10446 extended_remote_disable_randomization (disable_randomization);
10447
10448 /* If startup-with-shell is on, we inform gdbserver to start the
10449 remote inferior using a shell. */
10450 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10451 {
10452 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10453 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10454 putpkt (rs->buf);
10455 getpkt (&rs->buf, 0);
10456 if (strcmp (rs->buf.data (), "OK") != 0)
10457 error (_("\
10458 Remote replied unexpectedly while setting startup-with-shell: %s"),
10459 rs->buf.data ());
10460 }
10461
10462 extended_remote_environment_support ();
10463
10464 extended_remote_set_inferior_cwd ();
10465
10466 /* Now restart the remote server. */
10467 run_worked = extended_remote_run (args) != -1;
10468 if (!run_worked)
10469 {
10470 /* vRun was not supported. Fail if we need it to do what the
10471 user requested. */
10472 if (remote_exec_file[0])
10473 error (_("Remote target does not support \"set remote exec-file\""));
10474 if (!args.empty ())
10475 error (_("Remote target does not support \"set args\" or run ARGS"));
10476
10477 /* Fall back to "R". */
10478 extended_remote_restart ();
10479 }
10480
10481 /* vRun's success return is a stop reply. */
10482 stop_reply = run_worked ? rs->buf.data () : NULL;
10483 add_current_inferior_and_thread (stop_reply);
10484
10485 /* Get updated offsets, if the stub uses qOffsets. */
10486 get_offsets ();
10487 }
10488 \f
10489
10490 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10491 the list of conditions (in agent expression bytecode format), if any, the
10492 target needs to evaluate. The output is placed into the packet buffer
10493 started from BUF and ended at BUF_END. */
10494
10495 static int
10496 remote_add_target_side_condition (struct gdbarch *gdbarch,
10497 struct bp_target_info *bp_tgt, char *buf,
10498 char *buf_end)
10499 {
10500 if (bp_tgt->conditions.empty ())
10501 return 0;
10502
10503 buf += strlen (buf);
10504 xsnprintf (buf, buf_end - buf, "%s", ";");
10505 buf++;
10506
10507 /* Send conditions to the target. */
10508 for (agent_expr *aexpr : bp_tgt->conditions)
10509 {
10510 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10511 buf += strlen (buf);
10512 for (int i = 0; i < aexpr->len; ++i)
10513 buf = pack_hex_byte (buf, aexpr->buf[i]);
10514 *buf = '\0';
10515 }
10516 return 0;
10517 }
10518
10519 static void
10520 remote_add_target_side_commands (struct gdbarch *gdbarch,
10521 struct bp_target_info *bp_tgt, char *buf)
10522 {
10523 if (bp_tgt->tcommands.empty ())
10524 return;
10525
10526 buf += strlen (buf);
10527
10528 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10529 buf += strlen (buf);
10530
10531 /* Concatenate all the agent expressions that are commands into the
10532 cmds parameter. */
10533 for (agent_expr *aexpr : bp_tgt->tcommands)
10534 {
10535 sprintf (buf, "X%x,", aexpr->len);
10536 buf += strlen (buf);
10537 for (int i = 0; i < aexpr->len; ++i)
10538 buf = pack_hex_byte (buf, aexpr->buf[i]);
10539 *buf = '\0';
10540 }
10541 }
10542
10543 /* Insert a breakpoint. On targets that have software breakpoint
10544 support, we ask the remote target to do the work; on targets
10545 which don't, we insert a traditional memory breakpoint. */
10546
10547 int
10548 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10549 struct bp_target_info *bp_tgt)
10550 {
10551 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10552 If it succeeds, then set the support to PACKET_ENABLE. If it
10553 fails, and the user has explicitly requested the Z support then
10554 report an error, otherwise, mark it disabled and go on. */
10555
10556 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10557 {
10558 CORE_ADDR addr = bp_tgt->reqstd_address;
10559 struct remote_state *rs;
10560 char *p, *endbuf;
10561
10562 /* Make sure the remote is pointing at the right process, if
10563 necessary. */
10564 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10565 set_general_process ();
10566
10567 rs = get_remote_state ();
10568 p = rs->buf.data ();
10569 endbuf = p + get_remote_packet_size ();
10570
10571 *(p++) = 'Z';
10572 *(p++) = '0';
10573 *(p++) = ',';
10574 addr = (ULONGEST) remote_address_masked (addr);
10575 p += hexnumstr (p, addr);
10576 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10577
10578 if (supports_evaluation_of_breakpoint_conditions ())
10579 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10580
10581 if (can_run_breakpoint_commands ())
10582 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10583
10584 putpkt (rs->buf);
10585 getpkt (&rs->buf, 0);
10586
10587 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10588 {
10589 case PACKET_ERROR:
10590 return -1;
10591 case PACKET_OK:
10592 return 0;
10593 case PACKET_UNKNOWN:
10594 break;
10595 }
10596 }
10597
10598 /* If this breakpoint has target-side commands but this stub doesn't
10599 support Z0 packets, throw error. */
10600 if (!bp_tgt->tcommands.empty ())
10601 throw_error (NOT_SUPPORTED_ERROR, _("\
10602 Target doesn't support breakpoints that have target side commands."));
10603
10604 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10605 }
10606
10607 int
10608 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10609 struct bp_target_info *bp_tgt,
10610 enum remove_bp_reason reason)
10611 {
10612 CORE_ADDR addr = bp_tgt->placed_address;
10613 struct remote_state *rs = get_remote_state ();
10614
10615 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10616 {
10617 char *p = rs->buf.data ();
10618 char *endbuf = p + get_remote_packet_size ();
10619
10620 /* Make sure the remote is pointing at the right process, if
10621 necessary. */
10622 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10623 set_general_process ();
10624
10625 *(p++) = 'z';
10626 *(p++) = '0';
10627 *(p++) = ',';
10628
10629 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10630 p += hexnumstr (p, addr);
10631 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10632
10633 putpkt (rs->buf);
10634 getpkt (&rs->buf, 0);
10635
10636 return (rs->buf[0] == 'E');
10637 }
10638
10639 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10640 }
10641
10642 static enum Z_packet_type
10643 watchpoint_to_Z_packet (int type)
10644 {
10645 switch (type)
10646 {
10647 case hw_write:
10648 return Z_PACKET_WRITE_WP;
10649 break;
10650 case hw_read:
10651 return Z_PACKET_READ_WP;
10652 break;
10653 case hw_access:
10654 return Z_PACKET_ACCESS_WP;
10655 break;
10656 default:
10657 internal_error (__FILE__, __LINE__,
10658 _("hw_bp_to_z: bad watchpoint type %d"), type);
10659 }
10660 }
10661
10662 int
10663 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10664 enum target_hw_bp_type type, struct expression *cond)
10665 {
10666 struct remote_state *rs = get_remote_state ();
10667 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10668 char *p;
10669 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10670
10671 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10672 return 1;
10673
10674 /* Make sure the remote is pointing at the right process, if
10675 necessary. */
10676 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10677 set_general_process ();
10678
10679 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10680 p = strchr (rs->buf.data (), '\0');
10681 addr = remote_address_masked (addr);
10682 p += hexnumstr (p, (ULONGEST) addr);
10683 xsnprintf (p, endbuf - p, ",%x", len);
10684
10685 putpkt (rs->buf);
10686 getpkt (&rs->buf, 0);
10687
10688 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10689 {
10690 case PACKET_ERROR:
10691 return -1;
10692 case PACKET_UNKNOWN:
10693 return 1;
10694 case PACKET_OK:
10695 return 0;
10696 }
10697 internal_error (__FILE__, __LINE__,
10698 _("remote_insert_watchpoint: reached end of function"));
10699 }
10700
10701 bool
10702 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10703 CORE_ADDR start, int length)
10704 {
10705 CORE_ADDR diff = remote_address_masked (addr - start);
10706
10707 return diff < length;
10708 }
10709
10710
10711 int
10712 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10713 enum target_hw_bp_type type, struct expression *cond)
10714 {
10715 struct remote_state *rs = get_remote_state ();
10716 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10717 char *p;
10718 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10719
10720 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10721 return -1;
10722
10723 /* Make sure the remote is pointing at the right process, if
10724 necessary. */
10725 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10726 set_general_process ();
10727
10728 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10729 p = strchr (rs->buf.data (), '\0');
10730 addr = remote_address_masked (addr);
10731 p += hexnumstr (p, (ULONGEST) addr);
10732 xsnprintf (p, endbuf - p, ",%x", len);
10733 putpkt (rs->buf);
10734 getpkt (&rs->buf, 0);
10735
10736 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10737 {
10738 case PACKET_ERROR:
10739 case PACKET_UNKNOWN:
10740 return -1;
10741 case PACKET_OK:
10742 return 0;
10743 }
10744 internal_error (__FILE__, __LINE__,
10745 _("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 (__FILE__, __LINE__,
10915 _("remote_insert_hw_breakpoint: reached end of function"));
10916 }
10917
10918
10919 int
10920 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10921 struct bp_target_info *bp_tgt)
10922 {
10923 CORE_ADDR addr;
10924 struct remote_state *rs = get_remote_state ();
10925 char *p = rs->buf.data ();
10926 char *endbuf = p + get_remote_packet_size ();
10927
10928 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10929 return -1;
10930
10931 /* Make sure the remote is pointing at the right process, if
10932 necessary. */
10933 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10934 set_general_process ();
10935
10936 *(p++) = 'z';
10937 *(p++) = '1';
10938 *(p++) = ',';
10939
10940 addr = remote_address_masked (bp_tgt->placed_address);
10941 p += hexnumstr (p, (ULONGEST) addr);
10942 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10943
10944 putpkt (rs->buf);
10945 getpkt (&rs->buf, 0);
10946
10947 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10948 {
10949 case PACKET_ERROR:
10950 case PACKET_UNKNOWN:
10951 return -1;
10952 case PACKET_OK:
10953 return 0;
10954 }
10955 internal_error (__FILE__, __LINE__,
10956 _("remote_remove_hw_breakpoint: reached end of function"));
10957 }
10958
10959 /* Verify memory using the "qCRC:" request. */
10960
10961 int
10962 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10963 {
10964 struct remote_state *rs = get_remote_state ();
10965 unsigned long host_crc, target_crc;
10966 char *tmp;
10967
10968 /* It doesn't make sense to use qCRC if the remote target is
10969 connected but not running. */
10970 if (target_has_execution ()
10971 && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10972 {
10973 enum packet_result result;
10974
10975 /* Make sure the remote is pointing at the right process. */
10976 set_general_process ();
10977
10978 /* FIXME: assumes lma can fit into long. */
10979 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
10980 (long) lma, (long) size);
10981 putpkt (rs->buf);
10982
10983 /* Be clever; compute the host_crc before waiting for target
10984 reply. */
10985 host_crc = xcrc32 (data, size, 0xffffffff);
10986
10987 getpkt (&rs->buf, 0);
10988
10989 result = packet_ok (rs->buf,
10990 &remote_protocol_packets[PACKET_qCRC]);
10991 if (result == PACKET_ERROR)
10992 return -1;
10993 else if (result == PACKET_OK)
10994 {
10995 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10996 target_crc = target_crc * 16 + fromhex (*tmp);
10997
10998 return (host_crc == target_crc);
10999 }
11000 }
11001
11002 return simple_verify_memory (this, data, lma, size);
11003 }
11004
11005 /* compare-sections command
11006
11007 With no arguments, compares each loadable section in the exec bfd
11008 with the same memory range on the target, and reports mismatches.
11009 Useful for verifying the image on the target against the exec file. */
11010
11011 static void
11012 compare_sections_command (const char *args, int from_tty)
11013 {
11014 asection *s;
11015 const char *sectname;
11016 bfd_size_type size;
11017 bfd_vma lma;
11018 int matched = 0;
11019 int mismatched = 0;
11020 int res;
11021 int read_only = 0;
11022
11023 if (!current_program_space->exec_bfd ())
11024 error (_("command cannot be used without an exec file"));
11025
11026 if (args != NULL && strcmp (args, "-r") == 0)
11027 {
11028 read_only = 1;
11029 args = NULL;
11030 }
11031
11032 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11033 {
11034 if (!(s->flags & SEC_LOAD))
11035 continue; /* Skip non-loadable section. */
11036
11037 if (read_only && (s->flags & SEC_READONLY) == 0)
11038 continue; /* Skip writeable sections */
11039
11040 size = bfd_section_size (s);
11041 if (size == 0)
11042 continue; /* Skip zero-length section. */
11043
11044 sectname = bfd_section_name (s);
11045 if (args && strcmp (args, sectname) != 0)
11046 continue; /* Not the section selected by user. */
11047
11048 matched = 1; /* Do this section. */
11049 lma = s->lma;
11050
11051 gdb::byte_vector sectdata (size);
11052 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11053 sectdata.data (), 0, size);
11054
11055 res = target_verify_memory (sectdata.data (), lma, size);
11056
11057 if (res == -1)
11058 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11059 paddress (target_gdbarch (), lma),
11060 paddress (target_gdbarch (), lma + size));
11061
11062 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11063 paddress (target_gdbarch (), lma),
11064 paddress (target_gdbarch (), lma + size));
11065 if (res)
11066 gdb_printf ("matched.\n");
11067 else
11068 {
11069 gdb_printf ("MIS-MATCHED!\n");
11070 mismatched++;
11071 }
11072 }
11073 if (mismatched > 0)
11074 warning (_("One or more sections of the target image does not match\n\
11075 the loaded file\n"));
11076 if (args && !matched)
11077 gdb_printf (_("No loaded section named '%s'.\n"), args);
11078 }
11079
11080 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11081 into remote target. The number of bytes written to the remote
11082 target is returned, or -1 for error. */
11083
11084 target_xfer_status
11085 remote_target::remote_write_qxfer (const char *object_name,
11086 const char *annex, const gdb_byte *writebuf,
11087 ULONGEST offset, LONGEST len,
11088 ULONGEST *xfered_len,
11089 struct packet_config *packet)
11090 {
11091 int i, buf_len;
11092 ULONGEST n;
11093 struct remote_state *rs = get_remote_state ();
11094 int max_size = get_memory_write_packet_size ();
11095
11096 if (packet_config_support (packet) == PACKET_DISABLE)
11097 return TARGET_XFER_E_IO;
11098
11099 /* Insert header. */
11100 i = snprintf (rs->buf.data (), max_size,
11101 "qXfer:%s:write:%s:%s:",
11102 object_name, annex ? annex : "",
11103 phex_nz (offset, sizeof offset));
11104 max_size -= (i + 1);
11105
11106 /* Escape as much data as fits into rs->buf. */
11107 buf_len = remote_escape_output
11108 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11109
11110 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11111 || getpkt_sane (&rs->buf, 0) < 0
11112 || packet_ok (rs->buf, packet) != PACKET_OK)
11113 return TARGET_XFER_E_IO;
11114
11115 unpack_varlen_hex (rs->buf.data (), &n);
11116
11117 *xfered_len = n;
11118 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11119 }
11120
11121 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11122 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11123 number of bytes read is returned, or 0 for EOF, or -1 for error.
11124 The number of bytes read may be less than LEN without indicating an
11125 EOF. PACKET is checked and updated to indicate whether the remote
11126 target supports this object. */
11127
11128 target_xfer_status
11129 remote_target::remote_read_qxfer (const char *object_name,
11130 const char *annex,
11131 gdb_byte *readbuf, ULONGEST offset,
11132 LONGEST len,
11133 ULONGEST *xfered_len,
11134 struct packet_config *packet)
11135 {
11136 struct remote_state *rs = get_remote_state ();
11137 LONGEST i, n, packet_len;
11138
11139 if (packet_config_support (packet) == PACKET_DISABLE)
11140 return TARGET_XFER_E_IO;
11141
11142 /* Check whether we've cached an end-of-object packet that matches
11143 this request. */
11144 if (rs->finished_object)
11145 {
11146 if (strcmp (object_name, rs->finished_object) == 0
11147 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11148 && offset == rs->finished_offset)
11149 return TARGET_XFER_EOF;
11150
11151
11152 /* Otherwise, we're now reading something different. Discard
11153 the cache. */
11154 xfree (rs->finished_object);
11155 xfree (rs->finished_annex);
11156 rs->finished_object = NULL;
11157 rs->finished_annex = NULL;
11158 }
11159
11160 /* Request only enough to fit in a single packet. The actual data
11161 may not, since we don't know how much of it will need to be escaped;
11162 the target is free to respond with slightly less data. We subtract
11163 five to account for the response type and the protocol frame. */
11164 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11165 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11166 "qXfer:%s:read:%s:%s,%s",
11167 object_name, annex ? annex : "",
11168 phex_nz (offset, sizeof offset),
11169 phex_nz (n, sizeof n));
11170 i = putpkt (rs->buf);
11171 if (i < 0)
11172 return TARGET_XFER_E_IO;
11173
11174 rs->buf[0] = '\0';
11175 packet_len = getpkt_sane (&rs->buf, 0);
11176 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
11177 return TARGET_XFER_E_IO;
11178
11179 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11180 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11181
11182 /* 'm' means there is (or at least might be) more data after this
11183 batch. That does not make sense unless there's at least one byte
11184 of data in this reply. */
11185 if (rs->buf[0] == 'm' && packet_len == 1)
11186 error (_("Remote qXfer reply contained no data."));
11187
11188 /* Got some data. */
11189 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11190 packet_len - 1, readbuf, n);
11191
11192 /* 'l' is an EOF marker, possibly including a final block of data,
11193 or possibly empty. If we have the final block of a non-empty
11194 object, record this fact to bypass a subsequent partial read. */
11195 if (rs->buf[0] == 'l' && offset + i > 0)
11196 {
11197 rs->finished_object = xstrdup (object_name);
11198 rs->finished_annex = xstrdup (annex ? annex : "");
11199 rs->finished_offset = offset + i;
11200 }
11201
11202 if (i == 0)
11203 return TARGET_XFER_EOF;
11204 else
11205 {
11206 *xfered_len = i;
11207 return TARGET_XFER_OK;
11208 }
11209 }
11210
11211 enum target_xfer_status
11212 remote_target::xfer_partial (enum target_object object,
11213 const char *annex, gdb_byte *readbuf,
11214 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11215 ULONGEST *xfered_len)
11216 {
11217 struct remote_state *rs;
11218 int i;
11219 char *p2;
11220 char query_type;
11221 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
11222
11223 set_remote_traceframe ();
11224 set_general_thread (inferior_ptid);
11225
11226 rs = get_remote_state ();
11227
11228 /* Handle memory using the standard memory routines. */
11229 if (object == TARGET_OBJECT_MEMORY)
11230 {
11231 /* If the remote target is connected but not running, we should
11232 pass this request down to a lower stratum (e.g. the executable
11233 file). */
11234 if (!target_has_execution ())
11235 return TARGET_XFER_EOF;
11236
11237 if (writebuf != NULL)
11238 return remote_write_bytes (offset, writebuf, len, unit_size,
11239 xfered_len);
11240 else
11241 return remote_read_bytes (offset, readbuf, len, unit_size,
11242 xfered_len);
11243 }
11244
11245 /* Handle extra signal info using qxfer packets. */
11246 if (object == TARGET_OBJECT_SIGNAL_INFO)
11247 {
11248 if (readbuf)
11249 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11250 xfered_len, &remote_protocol_packets
11251 [PACKET_qXfer_siginfo_read]);
11252 else
11253 return remote_write_qxfer ("siginfo", annex,
11254 writebuf, offset, len, xfered_len,
11255 &remote_protocol_packets
11256 [PACKET_qXfer_siginfo_write]);
11257 }
11258
11259 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11260 {
11261 if (readbuf)
11262 return remote_read_qxfer ("statictrace", annex,
11263 readbuf, offset, len, xfered_len,
11264 &remote_protocol_packets
11265 [PACKET_qXfer_statictrace_read]);
11266 else
11267 return TARGET_XFER_E_IO;
11268 }
11269
11270 /* Only handle flash writes. */
11271 if (writebuf != NULL)
11272 {
11273 switch (object)
11274 {
11275 case TARGET_OBJECT_FLASH:
11276 return remote_flash_write (offset, len, xfered_len,
11277 writebuf);
11278
11279 default:
11280 return TARGET_XFER_E_IO;
11281 }
11282 }
11283
11284 /* Map pre-existing objects onto letters. DO NOT do this for new
11285 objects!!! Instead specify new query packets. */
11286 switch (object)
11287 {
11288 case TARGET_OBJECT_AVR:
11289 query_type = 'R';
11290 break;
11291
11292 case TARGET_OBJECT_AUXV:
11293 gdb_assert (annex == NULL);
11294 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
11295 xfered_len,
11296 &remote_protocol_packets[PACKET_qXfer_auxv]);
11297
11298 case TARGET_OBJECT_AVAILABLE_FEATURES:
11299 return remote_read_qxfer
11300 ("features", annex, readbuf, offset, len, xfered_len,
11301 &remote_protocol_packets[PACKET_qXfer_features]);
11302
11303 case TARGET_OBJECT_LIBRARIES:
11304 return remote_read_qxfer
11305 ("libraries", annex, readbuf, offset, len, xfered_len,
11306 &remote_protocol_packets[PACKET_qXfer_libraries]);
11307
11308 case TARGET_OBJECT_LIBRARIES_SVR4:
11309 return remote_read_qxfer
11310 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11311 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
11312
11313 case TARGET_OBJECT_MEMORY_MAP:
11314 gdb_assert (annex == NULL);
11315 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
11316 xfered_len,
11317 &remote_protocol_packets[PACKET_qXfer_memory_map]);
11318
11319 case TARGET_OBJECT_OSDATA:
11320 /* Should only get here if we're connected. */
11321 gdb_assert (rs->remote_desc);
11322 return remote_read_qxfer
11323 ("osdata", annex, readbuf, offset, len, xfered_len,
11324 &remote_protocol_packets[PACKET_qXfer_osdata]);
11325
11326 case TARGET_OBJECT_THREADS:
11327 gdb_assert (annex == NULL);
11328 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
11329 xfered_len,
11330 &remote_protocol_packets[PACKET_qXfer_threads]);
11331
11332 case TARGET_OBJECT_TRACEFRAME_INFO:
11333 gdb_assert (annex == NULL);
11334 return remote_read_qxfer
11335 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11336 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
11337
11338 case TARGET_OBJECT_FDPIC:
11339 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
11340 xfered_len,
11341 &remote_protocol_packets[PACKET_qXfer_fdpic]);
11342
11343 case TARGET_OBJECT_OPENVMS_UIB:
11344 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
11345 xfered_len,
11346 &remote_protocol_packets[PACKET_qXfer_uib]);
11347
11348 case TARGET_OBJECT_BTRACE:
11349 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
11350 xfered_len,
11351 &remote_protocol_packets[PACKET_qXfer_btrace]);
11352
11353 case TARGET_OBJECT_BTRACE_CONF:
11354 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
11355 len, xfered_len,
11356 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11357
11358 case TARGET_OBJECT_EXEC_FILE:
11359 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
11360 len, xfered_len,
11361 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11362
11363 default:
11364 return TARGET_XFER_E_IO;
11365 }
11366
11367 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11368 large enough let the caller deal with it. */
11369 if (len < get_remote_packet_size ())
11370 return TARGET_XFER_E_IO;
11371 len = get_remote_packet_size ();
11372
11373 /* Except for querying the minimum buffer size, target must be open. */
11374 if (!rs->remote_desc)
11375 error (_("remote query is only available after target open"));
11376
11377 gdb_assert (annex != NULL);
11378 gdb_assert (readbuf != NULL);
11379
11380 p2 = rs->buf.data ();
11381 *p2++ = 'q';
11382 *p2++ = query_type;
11383
11384 /* We used one buffer char for the remote protocol q command and
11385 another for the query type. As the remote protocol encapsulation
11386 uses 4 chars plus one extra in case we are debugging
11387 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11388 string. */
11389 i = 0;
11390 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11391 {
11392 /* Bad caller may have sent forbidden characters. */
11393 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11394 *p2++ = annex[i];
11395 i++;
11396 }
11397 *p2 = '\0';
11398 gdb_assert (annex[i] == '\0');
11399
11400 i = putpkt (rs->buf);
11401 if (i < 0)
11402 return TARGET_XFER_E_IO;
11403
11404 getpkt (&rs->buf, 0);
11405 strcpy ((char *) readbuf, rs->buf.data ());
11406
11407 *xfered_len = strlen ((char *) readbuf);
11408 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11409 }
11410
11411 /* Implementation of to_get_memory_xfer_limit. */
11412
11413 ULONGEST
11414 remote_target::get_memory_xfer_limit ()
11415 {
11416 return get_memory_write_packet_size ();
11417 }
11418
11419 int
11420 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11421 const gdb_byte *pattern, ULONGEST pattern_len,
11422 CORE_ADDR *found_addrp)
11423 {
11424 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11425 struct remote_state *rs = get_remote_state ();
11426 int max_size = get_memory_write_packet_size ();
11427 struct packet_config *packet =
11428 &remote_protocol_packets[PACKET_qSearch_memory];
11429 /* Number of packet bytes used to encode the pattern;
11430 this could be more than PATTERN_LEN due to escape characters. */
11431 int escaped_pattern_len;
11432 /* Amount of pattern that was encodable in the packet. */
11433 int used_pattern_len;
11434 int i;
11435 int found;
11436 ULONGEST found_addr;
11437
11438 auto read_memory = [=] (CORE_ADDR addr, gdb_byte *result, size_t len)
11439 {
11440 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11441 == len);
11442 };
11443
11444 /* Don't go to the target if we don't have to. This is done before
11445 checking packet_config_support to avoid the possibility that a
11446 success for this edge case means the facility works in
11447 general. */
11448 if (pattern_len > search_space_len)
11449 return 0;
11450 if (pattern_len == 0)
11451 {
11452 *found_addrp = start_addr;
11453 return 1;
11454 }
11455
11456 /* If we already know the packet isn't supported, fall back to the simple
11457 way of searching memory. */
11458
11459 if (packet_config_support (packet) == PACKET_DISABLE)
11460 {
11461 /* Target doesn't provided special support, fall back and use the
11462 standard support (copy memory and do the search here). */
11463 return simple_search_memory (read_memory, start_addr, search_space_len,
11464 pattern, pattern_len, found_addrp);
11465 }
11466
11467 /* Make sure the remote is pointing at the right process. */
11468 set_general_process ();
11469
11470 /* Insert header. */
11471 i = snprintf (rs->buf.data (), max_size,
11472 "qSearch:memory:%s;%s;",
11473 phex_nz (start_addr, addr_size),
11474 phex_nz (search_space_len, sizeof (search_space_len)));
11475 max_size -= (i + 1);
11476
11477 /* Escape as much data as fits into rs->buf. */
11478 escaped_pattern_len =
11479 remote_escape_output (pattern, pattern_len, 1,
11480 (gdb_byte *) rs->buf.data () + i,
11481 &used_pattern_len, max_size);
11482
11483 /* Bail if the pattern is too large. */
11484 if (used_pattern_len != pattern_len)
11485 error (_("Pattern is too large to transmit to remote target."));
11486
11487 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11488 || getpkt_sane (&rs->buf, 0) < 0
11489 || packet_ok (rs->buf, packet) != PACKET_OK)
11490 {
11491 /* The request may not have worked because the command is not
11492 supported. If so, fall back to the simple way. */
11493 if (packet_config_support (packet) == PACKET_DISABLE)
11494 {
11495 return simple_search_memory (read_memory, start_addr, search_space_len,
11496 pattern, pattern_len, found_addrp);
11497 }
11498 return -1;
11499 }
11500
11501 if (rs->buf[0] == '0')
11502 found = 0;
11503 else if (rs->buf[0] == '1')
11504 {
11505 found = 1;
11506 if (rs->buf[1] != ',')
11507 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11508 unpack_varlen_hex (&rs->buf[2], &found_addr);
11509 *found_addrp = found_addr;
11510 }
11511 else
11512 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11513
11514 return found;
11515 }
11516
11517 void
11518 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11519 {
11520 struct remote_state *rs = get_remote_state ();
11521 char *p = rs->buf.data ();
11522
11523 if (!rs->remote_desc)
11524 error (_("remote rcmd is only available after target open"));
11525
11526 /* Send a NULL command across as an empty command. */
11527 if (command == NULL)
11528 command = "";
11529
11530 /* The query prefix. */
11531 strcpy (rs->buf.data (), "qRcmd,");
11532 p = strchr (rs->buf.data (), '\0');
11533
11534 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11535 > get_remote_packet_size ())
11536 error (_("\"monitor\" command ``%s'' is too long."), command);
11537
11538 /* Encode the actual command. */
11539 bin2hex ((const gdb_byte *) command, p, strlen (command));
11540
11541 if (putpkt (rs->buf) < 0)
11542 error (_("Communication problem with target."));
11543
11544 /* get/display the response */
11545 while (1)
11546 {
11547 char *buf;
11548
11549 /* XXX - see also remote_get_noisy_reply(). */
11550 QUIT; /* Allow user to bail out with ^C. */
11551 rs->buf[0] = '\0';
11552 if (getpkt_sane (&rs->buf, 0) == -1)
11553 {
11554 /* Timeout. Continue to (try to) read responses.
11555 This is better than stopping with an error, assuming the stub
11556 is still executing the (long) monitor command.
11557 If needed, the user can interrupt gdb using C-c, obtaining
11558 an effect similar to stop on timeout. */
11559 continue;
11560 }
11561 buf = rs->buf.data ();
11562 if (buf[0] == '\0')
11563 error (_("Target does not support this command."));
11564 if (buf[0] == 'O' && buf[1] != 'K')
11565 {
11566 remote_console_output (buf + 1); /* 'O' message from stub. */
11567 continue;
11568 }
11569 if (strcmp (buf, "OK") == 0)
11570 break;
11571 if (strlen (buf) == 3 && buf[0] == 'E'
11572 && isxdigit (buf[1]) && isxdigit (buf[2]))
11573 {
11574 error (_("Protocol error with Rcmd"));
11575 }
11576 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11577 {
11578 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11579
11580 gdb_putc (c, outbuf);
11581 }
11582 break;
11583 }
11584 }
11585
11586 std::vector<mem_region>
11587 remote_target::memory_map ()
11588 {
11589 std::vector<mem_region> result;
11590 gdb::optional<gdb::char_vector> text
11591 = target_read_stralloc (current_inferior ()->top_target (),
11592 TARGET_OBJECT_MEMORY_MAP, NULL);
11593
11594 if (text)
11595 result = parse_memory_map (text->data ());
11596
11597 return result;
11598 }
11599
11600 /* Set of callbacks used to implement the 'maint packet' command. */
11601
11602 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
11603 {
11604 /* Called before the packet is sent. BUF is the packet content before
11605 the protocol specific prefix, suffix, and escaping is added. */
11606
11607 void sending (gdb::array_view<const char> &buf) override
11608 {
11609 gdb_puts ("sending: ");
11610 print_packet (buf);
11611 gdb_puts ("\n");
11612 }
11613
11614 /* Called with BUF, the reply from the remote target. */
11615
11616 void received (gdb::array_view<const char> &buf) override
11617 {
11618 gdb_puts ("received: \"");
11619 print_packet (buf);
11620 gdb_puts ("\"\n");
11621 }
11622
11623 private:
11624
11625 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11626 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11627
11628 static void
11629 print_packet (gdb::array_view<const char> &buf)
11630 {
11631 string_file stb;
11632
11633 for (int i = 0; i < buf.size (); ++i)
11634 {
11635 gdb_byte c = buf[i];
11636 if (isprint (c))
11637 gdb_putc (c, &stb);
11638 else
11639 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
11640 }
11641
11642 gdb_puts (stb.string ().c_str ());
11643 }
11644 };
11645
11646 /* See remote.h. */
11647
11648 void
11649 send_remote_packet (gdb::array_view<const char> &buf,
11650 send_remote_packet_callbacks *callbacks)
11651 {
11652 if (buf.size () == 0 || buf.data ()[0] == '\0')
11653 error (_("a remote packet must not be empty"));
11654
11655 remote_target *remote = get_current_remote_target ();
11656 if (remote == nullptr)
11657 error (_("packets can only be sent to a remote target"));
11658
11659 callbacks->sending (buf);
11660
11661 remote->putpkt_binary (buf.data (), buf.size ());
11662 remote_state *rs = remote->get_remote_state ();
11663 int bytes = remote->getpkt_sane (&rs->buf, 0);
11664
11665 if (bytes < 0)
11666 error (_("error while fetching packet from remote target"));
11667
11668 gdb::array_view<const char> view (&rs->buf[0], bytes);
11669 callbacks->received (view);
11670 }
11671
11672 /* Entry point for the 'maint packet' command. */
11673
11674 static void
11675 cli_packet_command (const char *args, int from_tty)
11676 {
11677 cli_packet_command_callbacks cb;
11678 gdb::array_view<const char> view
11679 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11680 send_remote_packet (view, &cb);
11681 }
11682
11683 #if 0
11684 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11685
11686 static void display_thread_info (struct gdb_ext_thread_info *info);
11687
11688 static void threadset_test_cmd (char *cmd, int tty);
11689
11690 static void threadalive_test (char *cmd, int tty);
11691
11692 static void threadlist_test_cmd (char *cmd, int tty);
11693
11694 int get_and_display_threadinfo (threadref *ref);
11695
11696 static void threadinfo_test_cmd (char *cmd, int tty);
11697
11698 static int thread_display_step (threadref *ref, void *context);
11699
11700 static void threadlist_update_test_cmd (char *cmd, int tty);
11701
11702 static void init_remote_threadtests (void);
11703
11704 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11705
11706 static void
11707 threadset_test_cmd (const char *cmd, int tty)
11708 {
11709 int sample_thread = SAMPLE_THREAD;
11710
11711 gdb_printf (_("Remote threadset test\n"));
11712 set_general_thread (sample_thread);
11713 }
11714
11715
11716 static void
11717 threadalive_test (const char *cmd, int tty)
11718 {
11719 int sample_thread = SAMPLE_THREAD;
11720 int pid = inferior_ptid.pid ();
11721 ptid_t ptid = ptid_t (pid, sample_thread, 0);
11722
11723 if (remote_thread_alive (ptid))
11724 gdb_printf ("PASS: Thread alive test\n");
11725 else
11726 gdb_printf ("FAIL: Thread alive test\n");
11727 }
11728
11729 void output_threadid (char *title, threadref *ref);
11730
11731 void
11732 output_threadid (char *title, threadref *ref)
11733 {
11734 char hexid[20];
11735
11736 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
11737 hexid[16] = 0;
11738 gdb_printf ("%s %s\n", title, (&hexid[0]));
11739 }
11740
11741 static void
11742 threadlist_test_cmd (const char *cmd, int tty)
11743 {
11744 int startflag = 1;
11745 threadref nextthread;
11746 int done, result_count;
11747 threadref threadlist[3];
11748
11749 gdb_printf ("Remote Threadlist test\n");
11750 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11751 &result_count, &threadlist[0]))
11752 gdb_printf ("FAIL: threadlist test\n");
11753 else
11754 {
11755 threadref *scan = threadlist;
11756 threadref *limit = scan + result_count;
11757
11758 while (scan < limit)
11759 output_threadid (" thread ", scan++);
11760 }
11761 }
11762
11763 void
11764 display_thread_info (struct gdb_ext_thread_info *info)
11765 {
11766 output_threadid ("Threadid: ", &info->threadid);
11767 gdb_printf ("Name: %s\n ", info->shortname);
11768 gdb_printf ("State: %s\n", info->display);
11769 gdb_printf ("other: %s\n\n", info->more_display);
11770 }
11771
11772 int
11773 get_and_display_threadinfo (threadref *ref)
11774 {
11775 int result;
11776 int set;
11777 struct gdb_ext_thread_info threadinfo;
11778
11779 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11780 | TAG_MOREDISPLAY | TAG_DISPLAY;
11781 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11782 display_thread_info (&threadinfo);
11783 return result;
11784 }
11785
11786 static void
11787 threadinfo_test_cmd (const char *cmd, int tty)
11788 {
11789 int athread = SAMPLE_THREAD;
11790 threadref thread;
11791 int set;
11792
11793 int_to_threadref (&thread, athread);
11794 gdb_printf ("Remote Threadinfo test\n");
11795 if (!get_and_display_threadinfo (&thread))
11796 gdb_printf ("FAIL cannot get thread info\n");
11797 }
11798
11799 static int
11800 thread_display_step (threadref *ref, void *context)
11801 {
11802 /* output_threadid(" threadstep ",ref); *//* simple test */
11803 return get_and_display_threadinfo (ref);
11804 }
11805
11806 static void
11807 threadlist_update_test_cmd (const char *cmd, int tty)
11808 {
11809 gdb_printf ("Remote Threadlist update test\n");
11810 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11811 }
11812
11813 static void
11814 init_remote_threadtests (void)
11815 {
11816 add_com ("tlist", class_obscure, threadlist_test_cmd,
11817 _("Fetch and print the remote list of "
11818 "thread identifiers, one pkt only."));
11819 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11820 _("Fetch and display info about one thread."));
11821 add_com ("tset", class_obscure, threadset_test_cmd,
11822 _("Test setting to a different thread."));
11823 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11824 _("Iterate through updating all remote thread info."));
11825 add_com ("talive", class_obscure, threadalive_test,
11826 _("Remote thread alive test."));
11827 }
11828
11829 #endif /* 0 */
11830
11831 /* Convert a thread ID to a string. */
11832
11833 std::string
11834 remote_target::pid_to_str (ptid_t ptid)
11835 {
11836 struct remote_state *rs = get_remote_state ();
11837
11838 if (ptid == null_ptid)
11839 return normal_pid_to_str (ptid);
11840 else if (ptid.is_pid ())
11841 {
11842 /* Printing an inferior target id. */
11843
11844 /* When multi-process extensions are off, there's no way in the
11845 remote protocol to know the remote process id, if there's any
11846 at all. There's one exception --- when we're connected with
11847 target extended-remote, and we manually attached to a process
11848 with "attach PID". We don't record anywhere a flag that
11849 allows us to distinguish that case from the case of
11850 connecting with extended-remote and the stub already being
11851 attached to a process, and reporting yes to qAttached, hence
11852 no smart special casing here. */
11853 if (!remote_multi_process_p (rs))
11854 return "Remote target";
11855
11856 return normal_pid_to_str (ptid);
11857 }
11858 else
11859 {
11860 if (magic_null_ptid == ptid)
11861 return "Thread <main>";
11862 else if (remote_multi_process_p (rs))
11863 if (ptid.lwp () == 0)
11864 return normal_pid_to_str (ptid);
11865 else
11866 return string_printf ("Thread %d.%ld",
11867 ptid.pid (), ptid.lwp ());
11868 else
11869 return string_printf ("Thread %ld", ptid.lwp ());
11870 }
11871 }
11872
11873 /* Get the address of the thread local variable in OBJFILE which is
11874 stored at OFFSET within the thread local storage for thread PTID. */
11875
11876 CORE_ADDR
11877 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11878 CORE_ADDR offset)
11879 {
11880 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11881 {
11882 struct remote_state *rs = get_remote_state ();
11883 char *p = rs->buf.data ();
11884 char *endp = p + get_remote_packet_size ();
11885 enum packet_result result;
11886
11887 strcpy (p, "qGetTLSAddr:");
11888 p += strlen (p);
11889 p = write_ptid (p, endp, ptid);
11890 *p++ = ',';
11891 p += hexnumstr (p, offset);
11892 *p++ = ',';
11893 p += hexnumstr (p, lm);
11894 *p++ = '\0';
11895
11896 putpkt (rs->buf);
11897 getpkt (&rs->buf, 0);
11898 result = packet_ok (rs->buf,
11899 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11900 if (result == PACKET_OK)
11901 {
11902 ULONGEST addr;
11903
11904 unpack_varlen_hex (rs->buf.data (), &addr);
11905 return addr;
11906 }
11907 else if (result == PACKET_UNKNOWN)
11908 throw_error (TLS_GENERIC_ERROR,
11909 _("Remote target doesn't support qGetTLSAddr packet"));
11910 else
11911 throw_error (TLS_GENERIC_ERROR,
11912 _("Remote target failed to process qGetTLSAddr request"));
11913 }
11914 else
11915 throw_error (TLS_GENERIC_ERROR,
11916 _("TLS not supported or disabled on this target"));
11917 /* Not reached. */
11918 return 0;
11919 }
11920
11921 /* Provide thread local base, i.e. Thread Information Block address.
11922 Returns 1 if ptid is found and thread_local_base is non zero. */
11923
11924 bool
11925 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11926 {
11927 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11928 {
11929 struct remote_state *rs = get_remote_state ();
11930 char *p = rs->buf.data ();
11931 char *endp = p + get_remote_packet_size ();
11932 enum packet_result result;
11933
11934 strcpy (p, "qGetTIBAddr:");
11935 p += strlen (p);
11936 p = write_ptid (p, endp, ptid);
11937 *p++ = '\0';
11938
11939 putpkt (rs->buf);
11940 getpkt (&rs->buf, 0);
11941 result = packet_ok (rs->buf,
11942 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11943 if (result == PACKET_OK)
11944 {
11945 ULONGEST val;
11946 unpack_varlen_hex (rs->buf.data (), &val);
11947 if (addr)
11948 *addr = (CORE_ADDR) val;
11949 return true;
11950 }
11951 else if (result == PACKET_UNKNOWN)
11952 error (_("Remote target doesn't support qGetTIBAddr packet"));
11953 else
11954 error (_("Remote target failed to process qGetTIBAddr request"));
11955 }
11956 else
11957 error (_("qGetTIBAddr not supported or disabled on this target"));
11958 /* Not reached. */
11959 return false;
11960 }
11961
11962 /* Support for inferring a target description based on the current
11963 architecture and the size of a 'g' packet. While the 'g' packet
11964 can have any size (since optional registers can be left off the
11965 end), some sizes are easily recognizable given knowledge of the
11966 approximate architecture. */
11967
11968 struct remote_g_packet_guess
11969 {
11970 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
11971 : bytes (bytes_),
11972 tdesc (tdesc_)
11973 {
11974 }
11975
11976 int bytes;
11977 const struct target_desc *tdesc;
11978 };
11979
11980 struct remote_g_packet_data : public allocate_on_obstack
11981 {
11982 std::vector<remote_g_packet_guess> guesses;
11983 };
11984
11985 static struct gdbarch_data *remote_g_packet_data_handle;
11986
11987 static void *
11988 remote_g_packet_data_init (struct obstack *obstack)
11989 {
11990 return new (obstack) remote_g_packet_data;
11991 }
11992
11993 void
11994 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11995 const struct target_desc *tdesc)
11996 {
11997 struct remote_g_packet_data *data
11998 = ((struct remote_g_packet_data *)
11999 gdbarch_data (gdbarch, remote_g_packet_data_handle));
12000
12001 gdb_assert (tdesc != NULL);
12002
12003 for (const remote_g_packet_guess &guess : data->guesses)
12004 if (guess.bytes == bytes)
12005 internal_error (__FILE__, __LINE__,
12006 _("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
12019 = ((struct remote_g_packet_data *)
12020 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
12021
12022 return !data->guesses.empty ();
12023 }
12024
12025 const struct target_desc *
12026 remote_target::read_description ()
12027 {
12028 struct remote_g_packet_data *data
12029 = ((struct remote_g_packet_data *)
12030 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
12031
12032 /* Do not try this during initial connection, when we do not know
12033 whether there is a running but stopped thread. */
12034 if (!target_has_execution () || inferior_ptid == null_ptid)
12035 return beneath ()->read_description ();
12036
12037 if (!data->guesses.empty ())
12038 {
12039 int bytes = send_g_packet ();
12040
12041 for (const remote_g_packet_guess &guess : data->guesses)
12042 if (guess.bytes == bytes)
12043 return guess.tdesc;
12044
12045 /* We discard the g packet. A minor optimization would be to
12046 hold on to it, and fill the register cache once we have selected
12047 an architecture, but it's too tricky to do safely. */
12048 }
12049
12050 return beneath ()->read_description ();
12051 }
12052
12053 /* Remote file transfer support. This is host-initiated I/O, not
12054 target-initiated; for target-initiated, see remote-fileio.c. */
12055
12056 /* If *LEFT is at least the length of STRING, copy STRING to
12057 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12058 decrease *LEFT. Otherwise raise an error. */
12059
12060 static void
12061 remote_buffer_add_string (char **buffer, int *left, const char *string)
12062 {
12063 int len = strlen (string);
12064
12065 if (len > *left)
12066 error (_("Packet too long for target."));
12067
12068 memcpy (*buffer, string, len);
12069 *buffer += len;
12070 *left -= len;
12071
12072 /* NUL-terminate the buffer as a convenience, if there is
12073 room. */
12074 if (*left)
12075 **buffer = '\0';
12076 }
12077
12078 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12079 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12080 decrease *LEFT. Otherwise raise an error. */
12081
12082 static void
12083 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12084 int len)
12085 {
12086 if (2 * len > *left)
12087 error (_("Packet too long for target."));
12088
12089 bin2hex (bytes, *buffer, len);
12090 *buffer += 2 * len;
12091 *left -= 2 * len;
12092
12093 /* NUL-terminate the buffer as a convenience, if there is
12094 room. */
12095 if (*left)
12096 **buffer = '\0';
12097 }
12098
12099 /* If *LEFT is large enough, convert VALUE to hex and add it to
12100 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12101 decrease *LEFT. Otherwise raise an error. */
12102
12103 static void
12104 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12105 {
12106 int len = hexnumlen (value);
12107
12108 if (len > *left)
12109 error (_("Packet too long for target."));
12110
12111 hexnumstr (*buffer, value);
12112 *buffer += len;
12113 *left -= len;
12114
12115 /* NUL-terminate the buffer as a convenience, if there is
12116 room. */
12117 if (*left)
12118 **buffer = '\0';
12119 }
12120
12121 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12122 value, *REMOTE_ERRNO to the remote error number or zero if none
12123 was included, and *ATTACHMENT to point to the start of the annex
12124 if any. The length of the packet isn't needed here; there may
12125 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12126
12127 Return 0 if the packet could be parsed, -1 if it could not. If
12128 -1 is returned, the other variables may not be initialized. */
12129
12130 static int
12131 remote_hostio_parse_result (const char *buffer, int *retcode,
12132 int *remote_errno, const char **attachment)
12133 {
12134 char *p, *p2;
12135
12136 *remote_errno = 0;
12137 *attachment = NULL;
12138
12139 if (buffer[0] != 'F')
12140 return -1;
12141
12142 errno = 0;
12143 *retcode = strtol (&buffer[1], &p, 16);
12144 if (errno != 0 || p == &buffer[1])
12145 return -1;
12146
12147 /* Check for ",errno". */
12148 if (*p == ',')
12149 {
12150 errno = 0;
12151 *remote_errno = strtol (p + 1, &p2, 16);
12152 if (errno != 0 || p + 1 == p2)
12153 return -1;
12154 p = p2;
12155 }
12156
12157 /* Check for ";attachment". If there is no attachment, the
12158 packet should end here. */
12159 if (*p == ';')
12160 {
12161 *attachment = p + 1;
12162 return 0;
12163 }
12164 else if (*p == '\0')
12165 return 0;
12166 else
12167 return -1;
12168 }
12169
12170 /* Send a prepared I/O packet to the target and read its response.
12171 The prepared packet is in the global RS->BUF before this function
12172 is called, and the answer is there when we return.
12173
12174 COMMAND_BYTES is the length of the request to send, which may include
12175 binary data. WHICH_PACKET is the packet configuration to check
12176 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12177 is set to the error number and -1 is returned. Otherwise the value
12178 returned by the function is returned.
12179
12180 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12181 attachment is expected; an error will be reported if there's a
12182 mismatch. If one is found, *ATTACHMENT will be set to point into
12183 the packet buffer and *ATTACHMENT_LEN will be set to the
12184 attachment's length. */
12185
12186 int
12187 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12188 int *remote_errno, const char **attachment,
12189 int *attachment_len)
12190 {
12191 struct remote_state *rs = get_remote_state ();
12192 int ret, bytes_read;
12193 const char *attachment_tmp;
12194
12195 if (packet_support (which_packet) == PACKET_DISABLE)
12196 {
12197 *remote_errno = FILEIO_ENOSYS;
12198 return -1;
12199 }
12200
12201 putpkt_binary (rs->buf.data (), command_bytes);
12202 bytes_read = getpkt_sane (&rs->buf, 0);
12203
12204 /* If it timed out, something is wrong. Don't try to parse the
12205 buffer. */
12206 if (bytes_read < 0)
12207 {
12208 *remote_errno = FILEIO_EINVAL;
12209 return -1;
12210 }
12211
12212 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
12213 {
12214 case PACKET_ERROR:
12215 *remote_errno = FILEIO_EINVAL;
12216 return -1;
12217 case PACKET_UNKNOWN:
12218 *remote_errno = FILEIO_ENOSYS;
12219 return -1;
12220 case PACKET_OK:
12221 break;
12222 }
12223
12224 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12225 &attachment_tmp))
12226 {
12227 *remote_errno = FILEIO_EINVAL;
12228 return -1;
12229 }
12230
12231 /* Make sure we saw an attachment if and only if we expected one. */
12232 if ((attachment_tmp == NULL && attachment != NULL)
12233 || (attachment_tmp != NULL && attachment == NULL))
12234 {
12235 *remote_errno = FILEIO_EINVAL;
12236 return -1;
12237 }
12238
12239 /* If an attachment was found, it must point into the packet buffer;
12240 work out how many bytes there were. */
12241 if (attachment_tmp != NULL)
12242 {
12243 *attachment = attachment_tmp;
12244 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12245 }
12246
12247 return ret;
12248 }
12249
12250 /* See declaration.h. */
12251
12252 void
12253 readahead_cache::invalidate ()
12254 {
12255 this->fd = -1;
12256 }
12257
12258 /* See declaration.h. */
12259
12260 void
12261 readahead_cache::invalidate_fd (int fd)
12262 {
12263 if (this->fd == fd)
12264 this->fd = -1;
12265 }
12266
12267 /* Set the filesystem remote_hostio functions that take FILENAME
12268 arguments will use. Return 0 on success, or -1 if an error
12269 occurs (and set *REMOTE_ERRNO). */
12270
12271 int
12272 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12273 int *remote_errno)
12274 {
12275 struct remote_state *rs = get_remote_state ();
12276 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12277 char *p = rs->buf.data ();
12278 int left = get_remote_packet_size () - 1;
12279 char arg[9];
12280 int ret;
12281
12282 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12283 return 0;
12284
12285 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12286 return 0;
12287
12288 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12289
12290 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12291 remote_buffer_add_string (&p, &left, arg);
12292
12293 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12294 remote_errno, NULL, NULL);
12295
12296 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12297 return 0;
12298
12299 if (ret == 0)
12300 rs->fs_pid = required_pid;
12301
12302 return ret;
12303 }
12304
12305 /* Implementation of to_fileio_open. */
12306
12307 int
12308 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12309 int flags, int mode, int warn_if_slow,
12310 int *remote_errno)
12311 {
12312 struct remote_state *rs = get_remote_state ();
12313 char *p = rs->buf.data ();
12314 int left = get_remote_packet_size () - 1;
12315
12316 if (warn_if_slow)
12317 {
12318 static int warning_issued = 0;
12319
12320 gdb_printf (_("Reading %s from remote target...\n"),
12321 filename);
12322
12323 if (!warning_issued)
12324 {
12325 warning (_("File transfers from remote targets can be slow."
12326 " Use \"set sysroot\" to access files locally"
12327 " instead."));
12328 warning_issued = 1;
12329 }
12330 }
12331
12332 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12333 return -1;
12334
12335 remote_buffer_add_string (&p, &left, "vFile:open:");
12336
12337 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12338 strlen (filename));
12339 remote_buffer_add_string (&p, &left, ",");
12340
12341 remote_buffer_add_int (&p, &left, flags);
12342 remote_buffer_add_string (&p, &left, ",");
12343
12344 remote_buffer_add_int (&p, &left, mode);
12345
12346 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12347 remote_errno, NULL, NULL);
12348 }
12349
12350 int
12351 remote_target::fileio_open (struct inferior *inf, const char *filename,
12352 int flags, int mode, int warn_if_slow,
12353 int *remote_errno)
12354 {
12355 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12356 remote_errno);
12357 }
12358
12359 /* Implementation of to_fileio_pwrite. */
12360
12361 int
12362 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12363 ULONGEST offset, int *remote_errno)
12364 {
12365 struct remote_state *rs = get_remote_state ();
12366 char *p = rs->buf.data ();
12367 int left = get_remote_packet_size ();
12368 int out_len;
12369
12370 rs->readahead_cache.invalidate_fd (fd);
12371
12372 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12373
12374 remote_buffer_add_int (&p, &left, fd);
12375 remote_buffer_add_string (&p, &left, ",");
12376
12377 remote_buffer_add_int (&p, &left, offset);
12378 remote_buffer_add_string (&p, &left, ",");
12379
12380 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12381 (get_remote_packet_size ()
12382 - (p - rs->buf.data ())));
12383
12384 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12385 remote_errno, NULL, NULL);
12386 }
12387
12388 int
12389 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12390 ULONGEST offset, int *remote_errno)
12391 {
12392 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12393 }
12394
12395 /* Helper for the implementation of to_fileio_pread. Read the file
12396 from the remote side with vFile:pread. */
12397
12398 int
12399 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12400 ULONGEST offset, int *remote_errno)
12401 {
12402 struct remote_state *rs = get_remote_state ();
12403 char *p = rs->buf.data ();
12404 const char *attachment;
12405 int left = get_remote_packet_size ();
12406 int ret, attachment_len;
12407 int read_len;
12408
12409 remote_buffer_add_string (&p, &left, "vFile:pread:");
12410
12411 remote_buffer_add_int (&p, &left, fd);
12412 remote_buffer_add_string (&p, &left, ",");
12413
12414 remote_buffer_add_int (&p, &left, len);
12415 remote_buffer_add_string (&p, &left, ",");
12416
12417 remote_buffer_add_int (&p, &left, offset);
12418
12419 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12420 remote_errno, &attachment,
12421 &attachment_len);
12422
12423 if (ret < 0)
12424 return ret;
12425
12426 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12427 read_buf, len);
12428 if (read_len != ret)
12429 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12430
12431 return ret;
12432 }
12433
12434 /* See declaration.h. */
12435
12436 int
12437 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12438 ULONGEST offset)
12439 {
12440 if (this->fd == fd
12441 && this->offset <= offset
12442 && offset < this->offset + this->bufsize)
12443 {
12444 ULONGEST max = this->offset + this->bufsize;
12445
12446 if (offset + len > max)
12447 len = max - offset;
12448
12449 memcpy (read_buf, this->buf + offset - this->offset, len);
12450 return len;
12451 }
12452
12453 return 0;
12454 }
12455
12456 /* Implementation of to_fileio_pread. */
12457
12458 int
12459 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12460 ULONGEST offset, int *remote_errno)
12461 {
12462 int ret;
12463 struct remote_state *rs = get_remote_state ();
12464 readahead_cache *cache = &rs->readahead_cache;
12465
12466 ret = cache->pread (fd, read_buf, len, offset);
12467 if (ret > 0)
12468 {
12469 cache->hit_count++;
12470
12471 remote_debug_printf ("readahead cache hit %s",
12472 pulongest (cache->hit_count));
12473 return ret;
12474 }
12475
12476 cache->miss_count++;
12477
12478 remote_debug_printf ("readahead cache miss %s",
12479 pulongest (cache->miss_count));
12480
12481 cache->fd = fd;
12482 cache->offset = offset;
12483 cache->bufsize = get_remote_packet_size ();
12484 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12485
12486 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12487 cache->offset, remote_errno);
12488 if (ret <= 0)
12489 {
12490 cache->invalidate_fd (fd);
12491 return ret;
12492 }
12493
12494 cache->bufsize = ret;
12495 return cache->pread (fd, read_buf, len, offset);
12496 }
12497
12498 int
12499 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12500 ULONGEST offset, int *remote_errno)
12501 {
12502 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12503 }
12504
12505 /* Implementation of to_fileio_close. */
12506
12507 int
12508 remote_target::remote_hostio_close (int fd, int *remote_errno)
12509 {
12510 struct remote_state *rs = get_remote_state ();
12511 char *p = rs->buf.data ();
12512 int left = get_remote_packet_size () - 1;
12513
12514 rs->readahead_cache.invalidate_fd (fd);
12515
12516 remote_buffer_add_string (&p, &left, "vFile:close:");
12517
12518 remote_buffer_add_int (&p, &left, fd);
12519
12520 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12521 remote_errno, NULL, NULL);
12522 }
12523
12524 int
12525 remote_target::fileio_close (int fd, int *remote_errno)
12526 {
12527 return remote_hostio_close (fd, remote_errno);
12528 }
12529
12530 /* Implementation of to_fileio_unlink. */
12531
12532 int
12533 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12534 int *remote_errno)
12535 {
12536 struct remote_state *rs = get_remote_state ();
12537 char *p = rs->buf.data ();
12538 int left = get_remote_packet_size () - 1;
12539
12540 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12541 return -1;
12542
12543 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12544
12545 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12546 strlen (filename));
12547
12548 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12549 remote_errno, NULL, NULL);
12550 }
12551
12552 int
12553 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12554 int *remote_errno)
12555 {
12556 return remote_hostio_unlink (inf, filename, remote_errno);
12557 }
12558
12559 /* Implementation of to_fileio_readlink. */
12560
12561 gdb::optional<std::string>
12562 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12563 int *remote_errno)
12564 {
12565 struct remote_state *rs = get_remote_state ();
12566 char *p = rs->buf.data ();
12567 const char *attachment;
12568 int left = get_remote_packet_size ();
12569 int len, attachment_len;
12570 int read_len;
12571
12572 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12573 return {};
12574
12575 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12576
12577 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12578 strlen (filename));
12579
12580 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12581 remote_errno, &attachment,
12582 &attachment_len);
12583
12584 if (len < 0)
12585 return {};
12586
12587 std::string ret (len, '\0');
12588
12589 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12590 (gdb_byte *) &ret[0], len);
12591 if (read_len != len)
12592 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12593
12594 return ret;
12595 }
12596
12597 /* Implementation of to_fileio_fstat. */
12598
12599 int
12600 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12601 {
12602 struct remote_state *rs = get_remote_state ();
12603 char *p = rs->buf.data ();
12604 int left = get_remote_packet_size ();
12605 int attachment_len, ret;
12606 const char *attachment;
12607 struct fio_stat fst;
12608 int read_len;
12609
12610 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12611
12612 remote_buffer_add_int (&p, &left, fd);
12613
12614 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12615 remote_errno, &attachment,
12616 &attachment_len);
12617 if (ret < 0)
12618 {
12619 if (*remote_errno != FILEIO_ENOSYS)
12620 return ret;
12621
12622 /* Strictly we should return -1, ENOSYS here, but when
12623 "set sysroot remote:" was implemented in August 2008
12624 BFD's need for a stat function was sidestepped with
12625 this hack. This was not remedied until March 2015
12626 so we retain the previous behavior to avoid breaking
12627 compatibility.
12628
12629 Note that the memset is a March 2015 addition; older
12630 GDBs set st_size *and nothing else* so the structure
12631 would have garbage in all other fields. This might
12632 break something but retaining the previous behavior
12633 here would be just too wrong. */
12634
12635 memset (st, 0, sizeof (struct stat));
12636 st->st_size = INT_MAX;
12637 return 0;
12638 }
12639
12640 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12641 (gdb_byte *) &fst, sizeof (fst));
12642
12643 if (read_len != ret)
12644 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12645
12646 if (read_len != sizeof (fst))
12647 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12648 read_len, (int) sizeof (fst));
12649
12650 remote_fileio_to_host_stat (&fst, st);
12651
12652 return 0;
12653 }
12654
12655 /* Implementation of to_filesystem_is_local. */
12656
12657 bool
12658 remote_target::filesystem_is_local ()
12659 {
12660 /* Valgrind GDB presents itself as a remote target but works
12661 on the local filesystem: it does not implement remote get
12662 and users are not expected to set a sysroot. To handle
12663 this case we treat the remote filesystem as local if the
12664 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12665 does not support vFile:open. */
12666 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
12667 {
12668 enum packet_support ps = packet_support (PACKET_vFile_open);
12669
12670 if (ps == PACKET_SUPPORT_UNKNOWN)
12671 {
12672 int fd, remote_errno;
12673
12674 /* Try opening a file to probe support. The supplied
12675 filename is irrelevant, we only care about whether
12676 the stub recognizes the packet or not. */
12677 fd = remote_hostio_open (NULL, "just probing",
12678 FILEIO_O_RDONLY, 0700, 0,
12679 &remote_errno);
12680
12681 if (fd >= 0)
12682 remote_hostio_close (fd, &remote_errno);
12683
12684 ps = packet_support (PACKET_vFile_open);
12685 }
12686
12687 if (ps == PACKET_DISABLE)
12688 {
12689 static int warning_issued = 0;
12690
12691 if (!warning_issued)
12692 {
12693 warning (_("remote target does not support file"
12694 " transfer, attempting to access files"
12695 " from local filesystem."));
12696 warning_issued = 1;
12697 }
12698
12699 return true;
12700 }
12701 }
12702
12703 return false;
12704 }
12705
12706 static int
12707 remote_fileio_errno_to_host (int errnum)
12708 {
12709 switch (errnum)
12710 {
12711 case FILEIO_EPERM:
12712 return EPERM;
12713 case FILEIO_ENOENT:
12714 return ENOENT;
12715 case FILEIO_EINTR:
12716 return EINTR;
12717 case FILEIO_EIO:
12718 return EIO;
12719 case FILEIO_EBADF:
12720 return EBADF;
12721 case FILEIO_EACCES:
12722 return EACCES;
12723 case FILEIO_EFAULT:
12724 return EFAULT;
12725 case FILEIO_EBUSY:
12726 return EBUSY;
12727 case FILEIO_EEXIST:
12728 return EEXIST;
12729 case FILEIO_ENODEV:
12730 return ENODEV;
12731 case FILEIO_ENOTDIR:
12732 return ENOTDIR;
12733 case FILEIO_EISDIR:
12734 return EISDIR;
12735 case FILEIO_EINVAL:
12736 return EINVAL;
12737 case FILEIO_ENFILE:
12738 return ENFILE;
12739 case FILEIO_EMFILE:
12740 return EMFILE;
12741 case FILEIO_EFBIG:
12742 return EFBIG;
12743 case FILEIO_ENOSPC:
12744 return ENOSPC;
12745 case FILEIO_ESPIPE:
12746 return ESPIPE;
12747 case FILEIO_EROFS:
12748 return EROFS;
12749 case FILEIO_ENOSYS:
12750 return ENOSYS;
12751 case FILEIO_ENAMETOOLONG:
12752 return ENAMETOOLONG;
12753 }
12754 return -1;
12755 }
12756
12757 static char *
12758 remote_hostio_error (int errnum)
12759 {
12760 int host_error = remote_fileio_errno_to_host (errnum);
12761
12762 if (host_error == -1)
12763 error (_("Unknown remote I/O error %d"), errnum);
12764 else
12765 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12766 }
12767
12768 /* A RAII wrapper around a remote file descriptor. */
12769
12770 class scoped_remote_fd
12771 {
12772 public:
12773 scoped_remote_fd (remote_target *remote, int fd)
12774 : m_remote (remote), m_fd (fd)
12775 {
12776 }
12777
12778 ~scoped_remote_fd ()
12779 {
12780 if (m_fd != -1)
12781 {
12782 try
12783 {
12784 int remote_errno;
12785 m_remote->remote_hostio_close (m_fd, &remote_errno);
12786 }
12787 catch (...)
12788 {
12789 /* Swallow exception before it escapes the dtor. If
12790 something goes wrong, likely the connection is gone,
12791 and there's nothing else that can be done. */
12792 }
12793 }
12794 }
12795
12796 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12797
12798 /* Release ownership of the file descriptor, and return it. */
12799 ATTRIBUTE_UNUSED_RESULT int release () noexcept
12800 {
12801 int fd = m_fd;
12802 m_fd = -1;
12803 return fd;
12804 }
12805
12806 /* Return the owned file descriptor. */
12807 int get () const noexcept
12808 {
12809 return m_fd;
12810 }
12811
12812 private:
12813 /* The remote target. */
12814 remote_target *m_remote;
12815
12816 /* The owned remote I/O file descriptor. */
12817 int m_fd;
12818 };
12819
12820 void
12821 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12822 {
12823 remote_target *remote = get_current_remote_target ();
12824
12825 if (remote == nullptr)
12826 error (_("command can only be used with remote target"));
12827
12828 remote->remote_file_put (local_file, remote_file, from_tty);
12829 }
12830
12831 void
12832 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12833 int from_tty)
12834 {
12835 int retcode, remote_errno, bytes, io_size;
12836 int bytes_in_buffer;
12837 int saw_eof;
12838 ULONGEST offset;
12839
12840 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12841 if (file == NULL)
12842 perror_with_name (local_file);
12843
12844 scoped_remote_fd fd
12845 (this, remote_hostio_open (NULL,
12846 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12847 | FILEIO_O_TRUNC),
12848 0700, 0, &remote_errno));
12849 if (fd.get () == -1)
12850 remote_hostio_error (remote_errno);
12851
12852 /* Send up to this many bytes at once. They won't all fit in the
12853 remote packet limit, so we'll transfer slightly fewer. */
12854 io_size = get_remote_packet_size ();
12855 gdb::byte_vector buffer (io_size);
12856
12857 bytes_in_buffer = 0;
12858 saw_eof = 0;
12859 offset = 0;
12860 while (bytes_in_buffer || !saw_eof)
12861 {
12862 if (!saw_eof)
12863 {
12864 bytes = fread (buffer.data () + bytes_in_buffer, 1,
12865 io_size - bytes_in_buffer,
12866 file.get ());
12867 if (bytes == 0)
12868 {
12869 if (ferror (file.get ()))
12870 error (_("Error reading %s."), local_file);
12871 else
12872 {
12873 /* EOF. Unless there is something still in the
12874 buffer from the last iteration, we are done. */
12875 saw_eof = 1;
12876 if (bytes_in_buffer == 0)
12877 break;
12878 }
12879 }
12880 }
12881 else
12882 bytes = 0;
12883
12884 bytes += bytes_in_buffer;
12885 bytes_in_buffer = 0;
12886
12887 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12888 offset, &remote_errno);
12889
12890 if (retcode < 0)
12891 remote_hostio_error (remote_errno);
12892 else if (retcode == 0)
12893 error (_("Remote write of %d bytes returned 0!"), bytes);
12894 else if (retcode < bytes)
12895 {
12896 /* Short write. Save the rest of the read data for the next
12897 write. */
12898 bytes_in_buffer = bytes - retcode;
12899 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
12900 }
12901
12902 offset += retcode;
12903 }
12904
12905 if (remote_hostio_close (fd.release (), &remote_errno))
12906 remote_hostio_error (remote_errno);
12907
12908 if (from_tty)
12909 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
12910 }
12911
12912 void
12913 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12914 {
12915 remote_target *remote = get_current_remote_target ();
12916
12917 if (remote == nullptr)
12918 error (_("command can only be used with remote target"));
12919
12920 remote->remote_file_get (remote_file, local_file, from_tty);
12921 }
12922
12923 void
12924 remote_target::remote_file_get (const char *remote_file, const char *local_file,
12925 int from_tty)
12926 {
12927 int remote_errno, bytes, io_size;
12928 ULONGEST offset;
12929
12930 scoped_remote_fd fd
12931 (this, remote_hostio_open (NULL,
12932 remote_file, FILEIO_O_RDONLY, 0, 0,
12933 &remote_errno));
12934 if (fd.get () == -1)
12935 remote_hostio_error (remote_errno);
12936
12937 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12938 if (file == NULL)
12939 perror_with_name (local_file);
12940
12941 /* Send up to this many bytes at once. They won't all fit in the
12942 remote packet limit, so we'll transfer slightly fewer. */
12943 io_size = get_remote_packet_size ();
12944 gdb::byte_vector buffer (io_size);
12945
12946 offset = 0;
12947 while (1)
12948 {
12949 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
12950 &remote_errno);
12951 if (bytes == 0)
12952 /* Success, but no bytes, means end-of-file. */
12953 break;
12954 if (bytes == -1)
12955 remote_hostio_error (remote_errno);
12956
12957 offset += bytes;
12958
12959 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
12960 if (bytes == 0)
12961 perror_with_name (local_file);
12962 }
12963
12964 if (remote_hostio_close (fd.release (), &remote_errno))
12965 remote_hostio_error (remote_errno);
12966
12967 if (from_tty)
12968 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
12969 }
12970
12971 void
12972 remote_file_delete (const char *remote_file, int from_tty)
12973 {
12974 remote_target *remote = get_current_remote_target ();
12975
12976 if (remote == nullptr)
12977 error (_("command can only be used with remote target"));
12978
12979 remote->remote_file_delete (remote_file, from_tty);
12980 }
12981
12982 void
12983 remote_target::remote_file_delete (const char *remote_file, int from_tty)
12984 {
12985 int retcode, remote_errno;
12986
12987 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
12988 if (retcode == -1)
12989 remote_hostio_error (remote_errno);
12990
12991 if (from_tty)
12992 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
12993 }
12994
12995 static void
12996 remote_put_command (const char *args, int from_tty)
12997 {
12998 if (args == NULL)
12999 error_no_arg (_("file to put"));
13000
13001 gdb_argv argv (args);
13002 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13003 error (_("Invalid parameters to remote put"));
13004
13005 remote_file_put (argv[0], argv[1], from_tty);
13006 }
13007
13008 static void
13009 remote_get_command (const char *args, int from_tty)
13010 {
13011 if (args == NULL)
13012 error_no_arg (_("file to get"));
13013
13014 gdb_argv argv (args);
13015 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13016 error (_("Invalid parameters to remote get"));
13017
13018 remote_file_get (argv[0], argv[1], from_tty);
13019 }
13020
13021 static void
13022 remote_delete_command (const char *args, int from_tty)
13023 {
13024 if (args == NULL)
13025 error_no_arg (_("file to delete"));
13026
13027 gdb_argv argv (args);
13028 if (argv[0] == NULL || argv[1] != NULL)
13029 error (_("Invalid parameters to remote delete"));
13030
13031 remote_file_delete (argv[0], from_tty);
13032 }
13033
13034 bool
13035 remote_target::can_execute_reverse ()
13036 {
13037 if (packet_support (PACKET_bs) == PACKET_ENABLE
13038 || packet_support (PACKET_bc) == PACKET_ENABLE)
13039 return true;
13040 else
13041 return false;
13042 }
13043
13044 bool
13045 remote_target::supports_non_stop ()
13046 {
13047 return true;
13048 }
13049
13050 bool
13051 remote_target::supports_disable_randomization ()
13052 {
13053 /* Only supported in extended mode. */
13054 return false;
13055 }
13056
13057 bool
13058 remote_target::supports_multi_process ()
13059 {
13060 struct remote_state *rs = get_remote_state ();
13061
13062 return remote_multi_process_p (rs);
13063 }
13064
13065 static int
13066 remote_supports_cond_tracepoints ()
13067 {
13068 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
13069 }
13070
13071 bool
13072 remote_target::supports_evaluation_of_breakpoint_conditions ()
13073 {
13074 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
13075 }
13076
13077 static int
13078 remote_supports_fast_tracepoints ()
13079 {
13080 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13081 }
13082
13083 static int
13084 remote_supports_static_tracepoints ()
13085 {
13086 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13087 }
13088
13089 static int
13090 remote_supports_install_in_trace ()
13091 {
13092 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13093 }
13094
13095 bool
13096 remote_target::supports_enable_disable_tracepoint ()
13097 {
13098 return (packet_support (PACKET_EnableDisableTracepoints_feature)
13099 == PACKET_ENABLE);
13100 }
13101
13102 bool
13103 remote_target::supports_string_tracing ()
13104 {
13105 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13106 }
13107
13108 bool
13109 remote_target::can_run_breakpoint_commands ()
13110 {
13111 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13112 }
13113
13114 void
13115 remote_target::trace_init ()
13116 {
13117 struct remote_state *rs = get_remote_state ();
13118
13119 putpkt ("QTinit");
13120 remote_get_noisy_reply ();
13121 if (strcmp (rs->buf.data (), "OK") != 0)
13122 error (_("Target does not support this command."));
13123 }
13124
13125 /* Recursive routine to walk through command list including loops, and
13126 download packets for each command. */
13127
13128 void
13129 remote_target::remote_download_command_source (int num, ULONGEST addr,
13130 struct command_line *cmds)
13131 {
13132 struct remote_state *rs = get_remote_state ();
13133 struct command_line *cmd;
13134
13135 for (cmd = cmds; cmd; cmd = cmd->next)
13136 {
13137 QUIT; /* Allow user to bail out with ^C. */
13138 strcpy (rs->buf.data (), "QTDPsrc:");
13139 encode_source_string (num, addr, "cmd", cmd->line,
13140 rs->buf.data () + strlen (rs->buf.data ()),
13141 rs->buf.size () - strlen (rs->buf.data ()));
13142 putpkt (rs->buf);
13143 remote_get_noisy_reply ();
13144 if (strcmp (rs->buf.data (), "OK"))
13145 warning (_("Target does not support source download."));
13146
13147 if (cmd->control_type == while_control
13148 || cmd->control_type == while_stepping_control)
13149 {
13150 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13151
13152 QUIT; /* Allow user to bail out with ^C. */
13153 strcpy (rs->buf.data (), "QTDPsrc:");
13154 encode_source_string (num, addr, "cmd", "end",
13155 rs->buf.data () + strlen (rs->buf.data ()),
13156 rs->buf.size () - strlen (rs->buf.data ()));
13157 putpkt (rs->buf);
13158 remote_get_noisy_reply ();
13159 if (strcmp (rs->buf.data (), "OK"))
13160 warning (_("Target does not support source download."));
13161 }
13162 }
13163 }
13164
13165 void
13166 remote_target::download_tracepoint (struct bp_location *loc)
13167 {
13168 CORE_ADDR tpaddr;
13169 char addrbuf[40];
13170 std::vector<std::string> tdp_actions;
13171 std::vector<std::string> stepping_actions;
13172 char *pkt;
13173 struct breakpoint *b = loc->owner;
13174 struct tracepoint *t = (struct tracepoint *) b;
13175 struct remote_state *rs = get_remote_state ();
13176 int ret;
13177 const char *err_msg = _("Tracepoint packet too large for target.");
13178 size_t size_left;
13179
13180 /* We use a buffer other than rs->buf because we'll build strings
13181 across multiple statements, and other statements in between could
13182 modify rs->buf. */
13183 gdb::char_vector buf (get_remote_packet_size ());
13184
13185 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13186
13187 tpaddr = loc->address;
13188 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13189 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13190 b->number, addrbuf, /* address */
13191 (b->enable_state == bp_enabled ? 'E' : 'D'),
13192 t->step_count, t->pass_count);
13193
13194 if (ret < 0 || ret >= buf.size ())
13195 error ("%s", err_msg);
13196
13197 /* Fast tracepoints are mostly handled by the target, but we can
13198 tell the target how big of an instruction block should be moved
13199 around. */
13200 if (b->type == bp_fast_tracepoint)
13201 {
13202 /* Only test for support at download time; we may not know
13203 target capabilities at definition time. */
13204 if (remote_supports_fast_tracepoints ())
13205 {
13206 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13207 NULL))
13208 {
13209 size_left = buf.size () - strlen (buf.data ());
13210 ret = snprintf (buf.data () + strlen (buf.data ()),
13211 size_left, ":F%x",
13212 gdb_insn_length (loc->gdbarch, tpaddr));
13213
13214 if (ret < 0 || ret >= size_left)
13215 error ("%s", err_msg);
13216 }
13217 else
13218 /* If it passed validation at definition but fails now,
13219 something is very wrong. */
13220 internal_error (__FILE__, __LINE__,
13221 _("Fast tracepoint not "
13222 "valid during download"));
13223 }
13224 else
13225 /* Fast tracepoints are functionally identical to regular
13226 tracepoints, so don't take lack of support as a reason to
13227 give up on the trace run. */
13228 warning (_("Target does not support fast tracepoints, "
13229 "downloading %d as regular tracepoint"), b->number);
13230 }
13231 else if (b->type == bp_static_tracepoint
13232 || b->type == bp_static_marker_tracepoint)
13233 {
13234 /* Only test for support at download time; we may not know
13235 target capabilities at definition time. */
13236 if (remote_supports_static_tracepoints ())
13237 {
13238 struct static_tracepoint_marker marker;
13239
13240 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13241 {
13242 size_left = buf.size () - strlen (buf.data ());
13243 ret = snprintf (buf.data () + strlen (buf.data ()),
13244 size_left, ":S");
13245
13246 if (ret < 0 || ret >= size_left)
13247 error ("%s", err_msg);
13248 }
13249 else
13250 error (_("Static tracepoint not valid during download"));
13251 }
13252 else
13253 /* Fast tracepoints are functionally identical to regular
13254 tracepoints, so don't take lack of support as a reason
13255 to give up on the trace run. */
13256 error (_("Target does not support static tracepoints"));
13257 }
13258 /* If the tracepoint has a conditional, make it into an agent
13259 expression and append to the definition. */
13260 if (loc->cond)
13261 {
13262 /* Only test support at download time, we may not know target
13263 capabilities at definition time. */
13264 if (remote_supports_cond_tracepoints ())
13265 {
13266 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13267 loc->cond.get ());
13268
13269 size_left = buf.size () - strlen (buf.data ());
13270
13271 ret = snprintf (buf.data () + strlen (buf.data ()),
13272 size_left, ":X%x,", aexpr->len);
13273
13274 if (ret < 0 || ret >= size_left)
13275 error ("%s", err_msg);
13276
13277 size_left = buf.size () - strlen (buf.data ());
13278
13279 /* Two bytes to encode each aexpr byte, plus the terminating
13280 null byte. */
13281 if (aexpr->len * 2 + 1 > size_left)
13282 error ("%s", err_msg);
13283
13284 pkt = buf.data () + strlen (buf.data ());
13285
13286 for (int ndx = 0; ndx < aexpr->len; ++ndx)
13287 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13288 *pkt = '\0';
13289 }
13290 else
13291 warning (_("Target does not support conditional tracepoints, "
13292 "ignoring tp %d cond"), b->number);
13293 }
13294
13295 if (b->commands || !default_collect.empty ())
13296 {
13297 size_left = buf.size () - strlen (buf.data ());
13298
13299 ret = snprintf (buf.data () + strlen (buf.data ()),
13300 size_left, "-");
13301
13302 if (ret < 0 || ret >= size_left)
13303 error ("%s", err_msg);
13304 }
13305
13306 putpkt (buf.data ());
13307 remote_get_noisy_reply ();
13308 if (strcmp (rs->buf.data (), "OK"))
13309 error (_("Target does not support tracepoints."));
13310
13311 /* do_single_steps (t); */
13312 for (auto action_it = tdp_actions.begin ();
13313 action_it != tdp_actions.end (); action_it++)
13314 {
13315 QUIT; /* Allow user to bail out with ^C. */
13316
13317 bool has_more = ((action_it + 1) != tdp_actions.end ()
13318 || !stepping_actions.empty ());
13319
13320 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13321 b->number, addrbuf, /* address */
13322 action_it->c_str (),
13323 has_more ? '-' : 0);
13324
13325 if (ret < 0 || ret >= buf.size ())
13326 error ("%s", err_msg);
13327
13328 putpkt (buf.data ());
13329 remote_get_noisy_reply ();
13330 if (strcmp (rs->buf.data (), "OK"))
13331 error (_("Error on target while setting tracepoints."));
13332 }
13333
13334 for (auto action_it = stepping_actions.begin ();
13335 action_it != stepping_actions.end (); action_it++)
13336 {
13337 QUIT; /* Allow user to bail out with ^C. */
13338
13339 bool is_first = action_it == stepping_actions.begin ();
13340 bool has_more = (action_it + 1) != stepping_actions.end ();
13341
13342 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13343 b->number, addrbuf, /* address */
13344 is_first ? "S" : "",
13345 action_it->c_str (),
13346 has_more ? "-" : "");
13347
13348 if (ret < 0 || ret >= buf.size ())
13349 error ("%s", err_msg);
13350
13351 putpkt (buf.data ());
13352 remote_get_noisy_reply ();
13353 if (strcmp (rs->buf.data (), "OK"))
13354 error (_("Error on target while setting tracepoints."));
13355 }
13356
13357 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13358 {
13359 if (b->location != NULL)
13360 {
13361 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13362
13363 if (ret < 0 || ret >= buf.size ())
13364 error ("%s", err_msg);
13365
13366 encode_source_string (b->number, loc->address, "at",
13367 event_location_to_string (b->location.get ()),
13368 buf.data () + strlen (buf.data ()),
13369 buf.size () - strlen (buf.data ()));
13370 putpkt (buf.data ());
13371 remote_get_noisy_reply ();
13372 if (strcmp (rs->buf.data (), "OK"))
13373 warning (_("Target does not support source download."));
13374 }
13375 if (b->cond_string)
13376 {
13377 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13378
13379 if (ret < 0 || ret >= buf.size ())
13380 error ("%s", err_msg);
13381
13382 encode_source_string (b->number, loc->address,
13383 "cond", b->cond_string.get (),
13384 buf.data () + strlen (buf.data ()),
13385 buf.size () - strlen (buf.data ()));
13386 putpkt (buf.data ());
13387 remote_get_noisy_reply ();
13388 if (strcmp (rs->buf.data (), "OK"))
13389 warning (_("Target does not support source download."));
13390 }
13391 remote_download_command_source (b->number, loc->address,
13392 breakpoint_commands (b));
13393 }
13394 }
13395
13396 bool
13397 remote_target::can_download_tracepoint ()
13398 {
13399 struct remote_state *rs = get_remote_state ();
13400 struct trace_status *ts;
13401 int status;
13402
13403 /* Don't try to install tracepoints until we've relocated our
13404 symbols, and fetched and merged the target's tracepoint list with
13405 ours. */
13406 if (rs->starting_up)
13407 return false;
13408
13409 ts = current_trace_status ();
13410 status = get_trace_status (ts);
13411
13412 if (status == -1 || !ts->running_known || !ts->running)
13413 return false;
13414
13415 /* If we are in a tracing experiment, but remote stub doesn't support
13416 installing tracepoint in trace, we have to return. */
13417 if (!remote_supports_install_in_trace ())
13418 return false;
13419
13420 return true;
13421 }
13422
13423
13424 void
13425 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13426 {
13427 struct remote_state *rs = get_remote_state ();
13428 char *p;
13429
13430 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13431 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13432 tsv.builtin);
13433 p = rs->buf.data () + strlen (rs->buf.data ());
13434 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13435 >= get_remote_packet_size ())
13436 error (_("Trace state variable name too long for tsv definition packet"));
13437 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13438 *p++ = '\0';
13439 putpkt (rs->buf);
13440 remote_get_noisy_reply ();
13441 if (rs->buf[0] == '\0')
13442 error (_("Target does not support this command."));
13443 if (strcmp (rs->buf.data (), "OK") != 0)
13444 error (_("Error on target while downloading trace state variable."));
13445 }
13446
13447 void
13448 remote_target::enable_tracepoint (struct bp_location *location)
13449 {
13450 struct remote_state *rs = get_remote_state ();
13451
13452 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13453 location->owner->number,
13454 phex (location->address, sizeof (CORE_ADDR)));
13455 putpkt (rs->buf);
13456 remote_get_noisy_reply ();
13457 if (rs->buf[0] == '\0')
13458 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13459 if (strcmp (rs->buf.data (), "OK") != 0)
13460 error (_("Error on target while enabling tracepoint."));
13461 }
13462
13463 void
13464 remote_target::disable_tracepoint (struct bp_location *location)
13465 {
13466 struct remote_state *rs = get_remote_state ();
13467
13468 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13469 location->owner->number,
13470 phex (location->address, sizeof (CORE_ADDR)));
13471 putpkt (rs->buf);
13472 remote_get_noisy_reply ();
13473 if (rs->buf[0] == '\0')
13474 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13475 if (strcmp (rs->buf.data (), "OK") != 0)
13476 error (_("Error on target while disabling tracepoint."));
13477 }
13478
13479 void
13480 remote_target::trace_set_readonly_regions ()
13481 {
13482 asection *s;
13483 bfd_size_type size;
13484 bfd_vma vma;
13485 int anysecs = 0;
13486 int offset = 0;
13487
13488 if (!current_program_space->exec_bfd ())
13489 return; /* No information to give. */
13490
13491 struct remote_state *rs = get_remote_state ();
13492
13493 strcpy (rs->buf.data (), "QTro");
13494 offset = strlen (rs->buf.data ());
13495 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
13496 {
13497 char tmp1[40], tmp2[40];
13498 int sec_length;
13499
13500 if ((s->flags & SEC_LOAD) == 0 ||
13501 /* (s->flags & SEC_CODE) == 0 || */
13502 (s->flags & SEC_READONLY) == 0)
13503 continue;
13504
13505 anysecs = 1;
13506 vma = bfd_section_vma (s);
13507 size = bfd_section_size (s);
13508 sprintf_vma (tmp1, vma);
13509 sprintf_vma (tmp2, vma + size);
13510 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13511 if (offset + sec_length + 1 > rs->buf.size ())
13512 {
13513 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
13514 warning (_("\
13515 Too many sections for read-only sections definition packet."));
13516 break;
13517 }
13518 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13519 tmp1, tmp2);
13520 offset += sec_length;
13521 }
13522 if (anysecs)
13523 {
13524 putpkt (rs->buf);
13525 getpkt (&rs->buf, 0);
13526 }
13527 }
13528
13529 void
13530 remote_target::trace_start ()
13531 {
13532 struct remote_state *rs = get_remote_state ();
13533
13534 putpkt ("QTStart");
13535 remote_get_noisy_reply ();
13536 if (rs->buf[0] == '\0')
13537 error (_("Target does not support this command."));
13538 if (strcmp (rs->buf.data (), "OK") != 0)
13539 error (_("Bogus reply from target: %s"), rs->buf.data ());
13540 }
13541
13542 int
13543 remote_target::get_trace_status (struct trace_status *ts)
13544 {
13545 /* Initialize it just to avoid a GCC false warning. */
13546 char *p = NULL;
13547 enum packet_result result;
13548 struct remote_state *rs = get_remote_state ();
13549
13550 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13551 return -1;
13552
13553 /* FIXME we need to get register block size some other way. */
13554 trace_regblock_size
13555 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13556
13557 putpkt ("qTStatus");
13558
13559 try
13560 {
13561 p = remote_get_noisy_reply ();
13562 }
13563 catch (const gdb_exception_error &ex)
13564 {
13565 if (ex.error != TARGET_CLOSE_ERROR)
13566 {
13567 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13568 return -1;
13569 }
13570 throw;
13571 }
13572
13573 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13574
13575 /* If the remote target doesn't do tracing, flag it. */
13576 if (result == PACKET_UNKNOWN)
13577 return -1;
13578
13579 /* We're working with a live target. */
13580 ts->filename = NULL;
13581
13582 if (*p++ != 'T')
13583 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13584
13585 /* Function 'parse_trace_status' sets default value of each field of
13586 'ts' at first, so we don't have to do it here. */
13587 parse_trace_status (p, ts);
13588
13589 return ts->running;
13590 }
13591
13592 void
13593 remote_target::get_tracepoint_status (struct breakpoint *bp,
13594 struct uploaded_tp *utp)
13595 {
13596 struct remote_state *rs = get_remote_state ();
13597 char *reply;
13598 struct tracepoint *tp = (struct tracepoint *) bp;
13599 size_t size = get_remote_packet_size ();
13600
13601 if (tp)
13602 {
13603 tp->hit_count = 0;
13604 tp->traceframe_usage = 0;
13605 for (bp_location *loc : tp->locations ())
13606 {
13607 /* If the tracepoint was never downloaded, don't go asking for
13608 any status. */
13609 if (tp->number_on_target == 0)
13610 continue;
13611 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13612 phex_nz (loc->address, 0));
13613 putpkt (rs->buf);
13614 reply = remote_get_noisy_reply ();
13615 if (reply && *reply)
13616 {
13617 if (*reply == 'V')
13618 parse_tracepoint_status (reply + 1, bp, utp);
13619 }
13620 }
13621 }
13622 else if (utp)
13623 {
13624 utp->hit_count = 0;
13625 utp->traceframe_usage = 0;
13626 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13627 phex_nz (utp->addr, 0));
13628 putpkt (rs->buf);
13629 reply = remote_get_noisy_reply ();
13630 if (reply && *reply)
13631 {
13632 if (*reply == 'V')
13633 parse_tracepoint_status (reply + 1, bp, utp);
13634 }
13635 }
13636 }
13637
13638 void
13639 remote_target::trace_stop ()
13640 {
13641 struct remote_state *rs = get_remote_state ();
13642
13643 putpkt ("QTStop");
13644 remote_get_noisy_reply ();
13645 if (rs->buf[0] == '\0')
13646 error (_("Target does not support this command."));
13647 if (strcmp (rs->buf.data (), "OK") != 0)
13648 error (_("Bogus reply from target: %s"), rs->buf.data ());
13649 }
13650
13651 int
13652 remote_target::trace_find (enum trace_find_type type, int num,
13653 CORE_ADDR addr1, CORE_ADDR addr2,
13654 int *tpp)
13655 {
13656 struct remote_state *rs = get_remote_state ();
13657 char *endbuf = rs->buf.data () + get_remote_packet_size ();
13658 char *p, *reply;
13659 int target_frameno = -1, target_tracept = -1;
13660
13661 /* Lookups other than by absolute frame number depend on the current
13662 trace selected, so make sure it is correct on the remote end
13663 first. */
13664 if (type != tfind_number)
13665 set_remote_traceframe ();
13666
13667 p = rs->buf.data ();
13668 strcpy (p, "QTFrame:");
13669 p = strchr (p, '\0');
13670 switch (type)
13671 {
13672 case tfind_number:
13673 xsnprintf (p, endbuf - p, "%x", num);
13674 break;
13675 case tfind_pc:
13676 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13677 break;
13678 case tfind_tp:
13679 xsnprintf (p, endbuf - p, "tdp:%x", num);
13680 break;
13681 case tfind_range:
13682 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13683 phex_nz (addr2, 0));
13684 break;
13685 case tfind_outside:
13686 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13687 phex_nz (addr2, 0));
13688 break;
13689 default:
13690 error (_("Unknown trace find type %d"), type);
13691 }
13692
13693 putpkt (rs->buf);
13694 reply = remote_get_noisy_reply ();
13695 if (*reply == '\0')
13696 error (_("Target does not support this command."));
13697
13698 while (reply && *reply)
13699 switch (*reply)
13700 {
13701 case 'F':
13702 p = ++reply;
13703 target_frameno = (int) strtol (p, &reply, 16);
13704 if (reply == p)
13705 error (_("Unable to parse trace frame number"));
13706 /* Don't update our remote traceframe number cache on failure
13707 to select a remote traceframe. */
13708 if (target_frameno == -1)
13709 return -1;
13710 break;
13711 case 'T':
13712 p = ++reply;
13713 target_tracept = (int) strtol (p, &reply, 16);
13714 if (reply == p)
13715 error (_("Unable to parse tracepoint number"));
13716 break;
13717 case 'O': /* "OK"? */
13718 if (reply[1] == 'K' && reply[2] == '\0')
13719 reply += 2;
13720 else
13721 error (_("Bogus reply from target: %s"), reply);
13722 break;
13723 default:
13724 error (_("Bogus reply from target: %s"), reply);
13725 }
13726 if (tpp)
13727 *tpp = target_tracept;
13728
13729 rs->remote_traceframe_number = target_frameno;
13730 return target_frameno;
13731 }
13732
13733 bool
13734 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13735 {
13736 struct remote_state *rs = get_remote_state ();
13737 char *reply;
13738 ULONGEST uval;
13739
13740 set_remote_traceframe ();
13741
13742 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
13743 putpkt (rs->buf);
13744 reply = remote_get_noisy_reply ();
13745 if (reply && *reply)
13746 {
13747 if (*reply == 'V')
13748 {
13749 unpack_varlen_hex (reply + 1, &uval);
13750 *val = (LONGEST) uval;
13751 return true;
13752 }
13753 }
13754 return false;
13755 }
13756
13757 int
13758 remote_target::save_trace_data (const char *filename)
13759 {
13760 struct remote_state *rs = get_remote_state ();
13761 char *p, *reply;
13762
13763 p = rs->buf.data ();
13764 strcpy (p, "QTSave:");
13765 p += strlen (p);
13766 if ((p - rs->buf.data ()) + strlen (filename) * 2
13767 >= get_remote_packet_size ())
13768 error (_("Remote file name too long for trace save packet"));
13769 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13770 *p++ = '\0';
13771 putpkt (rs->buf);
13772 reply = remote_get_noisy_reply ();
13773 if (*reply == '\0')
13774 error (_("Target does not support this command."));
13775 if (strcmp (reply, "OK") != 0)
13776 error (_("Bogus reply from target: %s"), reply);
13777 return 0;
13778 }
13779
13780 /* This is basically a memory transfer, but needs to be its own packet
13781 because we don't know how the target actually organizes its trace
13782 memory, plus we want to be able to ask for as much as possible, but
13783 not be unhappy if we don't get as much as we ask for. */
13784
13785 LONGEST
13786 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13787 {
13788 struct remote_state *rs = get_remote_state ();
13789 char *reply;
13790 char *p;
13791 int rslt;
13792
13793 p = rs->buf.data ();
13794 strcpy (p, "qTBuffer:");
13795 p += strlen (p);
13796 p += hexnumstr (p, offset);
13797 *p++ = ',';
13798 p += hexnumstr (p, len);
13799 *p++ = '\0';
13800
13801 putpkt (rs->buf);
13802 reply = remote_get_noisy_reply ();
13803 if (reply && *reply)
13804 {
13805 /* 'l' by itself means we're at the end of the buffer and
13806 there is nothing more to get. */
13807 if (*reply == 'l')
13808 return 0;
13809
13810 /* Convert the reply into binary. Limit the number of bytes to
13811 convert according to our passed-in buffer size, rather than
13812 what was returned in the packet; if the target is
13813 unexpectedly generous and gives us a bigger reply than we
13814 asked for, we don't want to crash. */
13815 rslt = hex2bin (reply, buf, len);
13816 return rslt;
13817 }
13818
13819 /* Something went wrong, flag as an error. */
13820 return -1;
13821 }
13822
13823 void
13824 remote_target::set_disconnected_tracing (int val)
13825 {
13826 struct remote_state *rs = get_remote_state ();
13827
13828 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13829 {
13830 char *reply;
13831
13832 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13833 "QTDisconnected:%x", val);
13834 putpkt (rs->buf);
13835 reply = remote_get_noisy_reply ();
13836 if (*reply == '\0')
13837 error (_("Target does not support this command."));
13838 if (strcmp (reply, "OK") != 0)
13839 error (_("Bogus reply from target: %s"), reply);
13840 }
13841 else if (val)
13842 warning (_("Target does not support disconnected tracing."));
13843 }
13844
13845 int
13846 remote_target::core_of_thread (ptid_t ptid)
13847 {
13848 thread_info *info = find_thread_ptid (this, ptid);
13849
13850 if (info != NULL && info->priv != NULL)
13851 return get_remote_thread_info (info)->core;
13852
13853 return -1;
13854 }
13855
13856 void
13857 remote_target::set_circular_trace_buffer (int val)
13858 {
13859 struct remote_state *rs = get_remote_state ();
13860 char *reply;
13861
13862 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13863 "QTBuffer:circular:%x", val);
13864 putpkt (rs->buf);
13865 reply = remote_get_noisy_reply ();
13866 if (*reply == '\0')
13867 error (_("Target does not support this command."));
13868 if (strcmp (reply, "OK") != 0)
13869 error (_("Bogus reply from target: %s"), reply);
13870 }
13871
13872 traceframe_info_up
13873 remote_target::traceframe_info ()
13874 {
13875 gdb::optional<gdb::char_vector> text
13876 = target_read_stralloc (current_inferior ()->top_target (),
13877 TARGET_OBJECT_TRACEFRAME_INFO,
13878 NULL);
13879 if (text)
13880 return parse_traceframe_info (text->data ());
13881
13882 return NULL;
13883 }
13884
13885 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13886 instruction on which a fast tracepoint may be placed. Returns -1
13887 if the packet is not supported, and 0 if the minimum instruction
13888 length is unknown. */
13889
13890 int
13891 remote_target::get_min_fast_tracepoint_insn_len ()
13892 {
13893 struct remote_state *rs = get_remote_state ();
13894 char *reply;
13895
13896 /* If we're not debugging a process yet, the IPA can't be
13897 loaded. */
13898 if (!target_has_execution ())
13899 return 0;
13900
13901 /* Make sure the remote is pointing at the right process. */
13902 set_general_process ();
13903
13904 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
13905 putpkt (rs->buf);
13906 reply = remote_get_noisy_reply ();
13907 if (*reply == '\0')
13908 return -1;
13909 else
13910 {
13911 ULONGEST min_insn_len;
13912
13913 unpack_varlen_hex (reply, &min_insn_len);
13914
13915 return (int) min_insn_len;
13916 }
13917 }
13918
13919 void
13920 remote_target::set_trace_buffer_size (LONGEST val)
13921 {
13922 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13923 {
13924 struct remote_state *rs = get_remote_state ();
13925 char *buf = rs->buf.data ();
13926 char *endbuf = buf + get_remote_packet_size ();
13927 enum packet_result result;
13928
13929 gdb_assert (val >= 0 || val == -1);
13930 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13931 /* Send -1 as literal "-1" to avoid host size dependency. */
13932 if (val < 0)
13933 {
13934 *buf++ = '-';
13935 buf += hexnumstr (buf, (ULONGEST) -val);
13936 }
13937 else
13938 buf += hexnumstr (buf, (ULONGEST) val);
13939
13940 putpkt (rs->buf);
13941 remote_get_noisy_reply ();
13942 result = packet_ok (rs->buf,
13943 &remote_protocol_packets[PACKET_QTBuffer_size]);
13944
13945 if (result != PACKET_OK)
13946 warning (_("Bogus reply from target: %s"), rs->buf.data ());
13947 }
13948 }
13949
13950 bool
13951 remote_target::set_trace_notes (const char *user, const char *notes,
13952 const char *stop_notes)
13953 {
13954 struct remote_state *rs = get_remote_state ();
13955 char *reply;
13956 char *buf = rs->buf.data ();
13957 char *endbuf = buf + get_remote_packet_size ();
13958 int nbytes;
13959
13960 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13961 if (user)
13962 {
13963 buf += xsnprintf (buf, endbuf - buf, "user:");
13964 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13965 buf += 2 * nbytes;
13966 *buf++ = ';';
13967 }
13968 if (notes)
13969 {
13970 buf += xsnprintf (buf, endbuf - buf, "notes:");
13971 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13972 buf += 2 * nbytes;
13973 *buf++ = ';';
13974 }
13975 if (stop_notes)
13976 {
13977 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13978 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13979 buf += 2 * nbytes;
13980 *buf++ = ';';
13981 }
13982 /* Ensure the buffer is terminated. */
13983 *buf = '\0';
13984
13985 putpkt (rs->buf);
13986 reply = remote_get_noisy_reply ();
13987 if (*reply == '\0')
13988 return false;
13989
13990 if (strcmp (reply, "OK") != 0)
13991 error (_("Bogus reply from target: %s"), reply);
13992
13993 return true;
13994 }
13995
13996 bool
13997 remote_target::use_agent (bool use)
13998 {
13999 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
14000 {
14001 struct remote_state *rs = get_remote_state ();
14002
14003 /* If the stub supports QAgent. */
14004 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
14005 putpkt (rs->buf);
14006 getpkt (&rs->buf, 0);
14007
14008 if (strcmp (rs->buf.data (), "OK") == 0)
14009 {
14010 ::use_agent = use;
14011 return true;
14012 }
14013 }
14014
14015 return false;
14016 }
14017
14018 bool
14019 remote_target::can_use_agent ()
14020 {
14021 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
14022 }
14023
14024 struct btrace_target_info
14025 {
14026 /* The ptid of the traced thread. */
14027 ptid_t ptid;
14028
14029 /* The obtained branch trace configuration. */
14030 struct btrace_config conf;
14031 };
14032
14033 /* Reset our idea of our target's btrace configuration. */
14034
14035 static void
14036 remote_btrace_reset (remote_state *rs)
14037 {
14038 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14039 }
14040
14041 /* Synchronize the configuration with the target. */
14042
14043 void
14044 remote_target::btrace_sync_conf (const btrace_config *conf)
14045 {
14046 struct packet_config *packet;
14047 struct remote_state *rs;
14048 char *buf, *pos, *endbuf;
14049
14050 rs = get_remote_state ();
14051 buf = rs->buf.data ();
14052 endbuf = buf + get_remote_packet_size ();
14053
14054 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
14055 if (packet_config_support (packet) == PACKET_ENABLE
14056 && conf->bts.size != rs->btrace_config.bts.size)
14057 {
14058 pos = buf;
14059 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
14060 conf->bts.size);
14061
14062 putpkt (buf);
14063 getpkt (&rs->buf, 0);
14064
14065 if (packet_ok (buf, packet) == PACKET_ERROR)
14066 {
14067 if (buf[0] == 'E' && buf[1] == '.')
14068 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14069 else
14070 error (_("Failed to configure the BTS buffer size."));
14071 }
14072
14073 rs->btrace_config.bts.size = conf->bts.size;
14074 }
14075
14076 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
14077 if (packet_config_support (packet) == PACKET_ENABLE
14078 && conf->pt.size != rs->btrace_config.pt.size)
14079 {
14080 pos = buf;
14081 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
14082 conf->pt.size);
14083
14084 putpkt (buf);
14085 getpkt (&rs->buf, 0);
14086
14087 if (packet_ok (buf, packet) == PACKET_ERROR)
14088 {
14089 if (buf[0] == 'E' && buf[1] == '.')
14090 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14091 else
14092 error (_("Failed to configure the trace buffer size."));
14093 }
14094
14095 rs->btrace_config.pt.size = conf->pt.size;
14096 }
14097 }
14098
14099 /* Read TP's btrace configuration from the target and store it into CONF. */
14100
14101 static void
14102 btrace_read_config (thread_info *tp, struct btrace_config *conf)
14103 {
14104 /* target_read_stralloc relies on INFERIOR_PTID. */
14105 scoped_restore_current_thread restore_thread;
14106 switch_to_thread (tp);
14107
14108 gdb::optional<gdb::char_vector> xml
14109 = target_read_stralloc (current_inferior ()->top_target (),
14110 TARGET_OBJECT_BTRACE_CONF, "");
14111 if (xml)
14112 parse_xml_btrace_conf (conf, xml->data ());
14113 }
14114
14115 /* Maybe reopen target btrace. */
14116
14117 void
14118 remote_target::remote_btrace_maybe_reopen ()
14119 {
14120 struct remote_state *rs = get_remote_state ();
14121 int btrace_target_pushed = 0;
14122 #if !defined (HAVE_LIBIPT)
14123 int warned = 0;
14124 #endif
14125
14126 /* Don't bother walking the entirety of the remote thread list when
14127 we know the feature isn't supported by the remote. */
14128 if (packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14129 return;
14130
14131 for (thread_info *tp : all_non_exited_threads (this))
14132 {
14133 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14134 btrace_read_config (tp, &rs->btrace_config);
14135
14136 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14137 continue;
14138
14139 #if !defined (HAVE_LIBIPT)
14140 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14141 {
14142 if (!warned)
14143 {
14144 warned = 1;
14145 warning (_("Target is recording using Intel Processor Trace "
14146 "but support was disabled at compile time."));
14147 }
14148
14149 continue;
14150 }
14151 #endif /* !defined (HAVE_LIBIPT) */
14152
14153 /* Push target, once, but before anything else happens. This way our
14154 changes to the threads will be cleaned up by unpushing the target
14155 in case btrace_read_config () throws. */
14156 if (!btrace_target_pushed)
14157 {
14158 btrace_target_pushed = 1;
14159 record_btrace_push_target ();
14160 gdb_printf (_("Target is recording using %s.\n"),
14161 btrace_format_string (rs->btrace_config.format));
14162 }
14163
14164 tp->btrace.target = XCNEW (struct btrace_target_info);
14165 tp->btrace.target->ptid = tp->ptid;
14166 tp->btrace.target->conf = rs->btrace_config;
14167 }
14168 }
14169
14170 /* Enable branch tracing. */
14171
14172 struct btrace_target_info *
14173 remote_target::enable_btrace (thread_info *tp,
14174 const struct btrace_config *conf)
14175 {
14176 struct btrace_target_info *tinfo = NULL;
14177 struct packet_config *packet = NULL;
14178 struct remote_state *rs = get_remote_state ();
14179 char *buf = rs->buf.data ();
14180 char *endbuf = buf + get_remote_packet_size ();
14181
14182 switch (conf->format)
14183 {
14184 case BTRACE_FORMAT_BTS:
14185 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
14186 break;
14187
14188 case BTRACE_FORMAT_PT:
14189 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
14190 break;
14191 }
14192
14193 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14194 error (_("Target does not support branch tracing."));
14195
14196 btrace_sync_conf (conf);
14197
14198 ptid_t ptid = tp->ptid;
14199 set_general_thread (ptid);
14200
14201 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14202 putpkt (rs->buf);
14203 getpkt (&rs->buf, 0);
14204
14205 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14206 {
14207 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14208 error (_("Could not enable branch tracing for %s: %s"),
14209 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14210 else
14211 error (_("Could not enable branch tracing for %s."),
14212 target_pid_to_str (ptid).c_str ());
14213 }
14214
14215 tinfo = XCNEW (struct btrace_target_info);
14216 tinfo->ptid = ptid;
14217
14218 /* If we fail to read the configuration, we lose some information, but the
14219 tracing itself is not impacted. */
14220 try
14221 {
14222 btrace_read_config (tp, &tinfo->conf);
14223 }
14224 catch (const gdb_exception_error &err)
14225 {
14226 if (err.message != NULL)
14227 warning ("%s", err.what ());
14228 }
14229
14230 return tinfo;
14231 }
14232
14233 /* Disable branch tracing. */
14234
14235 void
14236 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14237 {
14238 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
14239 struct remote_state *rs = get_remote_state ();
14240 char *buf = rs->buf.data ();
14241 char *endbuf = buf + get_remote_packet_size ();
14242
14243 if (packet_config_support (packet) != PACKET_ENABLE)
14244 error (_("Target does not support branch tracing."));
14245
14246 set_general_thread (tinfo->ptid);
14247
14248 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14249 putpkt (rs->buf);
14250 getpkt (&rs->buf, 0);
14251
14252 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14253 {
14254 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14255 error (_("Could not disable branch tracing for %s: %s"),
14256 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14257 else
14258 error (_("Could not disable branch tracing for %s."),
14259 target_pid_to_str (tinfo->ptid).c_str ());
14260 }
14261
14262 xfree (tinfo);
14263 }
14264
14265 /* Teardown branch tracing. */
14266
14267 void
14268 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14269 {
14270 /* We must not talk to the target during teardown. */
14271 xfree (tinfo);
14272 }
14273
14274 /* Read the branch trace. */
14275
14276 enum btrace_error
14277 remote_target::read_btrace (struct btrace_data *btrace,
14278 struct btrace_target_info *tinfo,
14279 enum btrace_read_type type)
14280 {
14281 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
14282 const char *annex;
14283
14284 if (packet_config_support (packet) != PACKET_ENABLE)
14285 error (_("Target does not support branch tracing."));
14286
14287 #if !defined(HAVE_LIBEXPAT)
14288 error (_("Cannot process branch tracing result. XML parsing not supported."));
14289 #endif
14290
14291 switch (type)
14292 {
14293 case BTRACE_READ_ALL:
14294 annex = "all";
14295 break;
14296 case BTRACE_READ_NEW:
14297 annex = "new";
14298 break;
14299 case BTRACE_READ_DELTA:
14300 annex = "delta";
14301 break;
14302 default:
14303 internal_error (__FILE__, __LINE__,
14304 _("Bad branch tracing read type: %u."),
14305 (unsigned int) type);
14306 }
14307
14308 gdb::optional<gdb::char_vector> xml
14309 = target_read_stralloc (current_inferior ()->top_target (),
14310 TARGET_OBJECT_BTRACE, annex);
14311 if (!xml)
14312 return BTRACE_ERR_UNKNOWN;
14313
14314 parse_xml_btrace (btrace, xml->data ());
14315
14316 return BTRACE_ERR_NONE;
14317 }
14318
14319 const struct btrace_config *
14320 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14321 {
14322 return &tinfo->conf;
14323 }
14324
14325 bool
14326 remote_target::augmented_libraries_svr4_read ()
14327 {
14328 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
14329 == PACKET_ENABLE);
14330 }
14331
14332 /* Implementation of to_load. */
14333
14334 void
14335 remote_target::load (const char *name, int from_tty)
14336 {
14337 generic_load (name, from_tty);
14338 }
14339
14340 /* Accepts an integer PID; returns a string representing a file that
14341 can be opened on the remote side to get the symbols for the child
14342 process. Returns NULL if the operation is not supported. */
14343
14344 char *
14345 remote_target::pid_to_exec_file (int pid)
14346 {
14347 static gdb::optional<gdb::char_vector> filename;
14348 char *annex = NULL;
14349
14350 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14351 return NULL;
14352
14353 inferior *inf = find_inferior_pid (this, pid);
14354 if (inf == NULL)
14355 internal_error (__FILE__, __LINE__,
14356 _("not currently attached to process %d"), pid);
14357
14358 if (!inf->fake_pid_p)
14359 {
14360 const int annex_size = 9;
14361
14362 annex = (char *) alloca (annex_size);
14363 xsnprintf (annex, annex_size, "%x", pid);
14364 }
14365
14366 filename = target_read_stralloc (current_inferior ()->top_target (),
14367 TARGET_OBJECT_EXEC_FILE, annex);
14368
14369 return filename ? filename->data () : nullptr;
14370 }
14371
14372 /* Implement the to_can_do_single_step target_ops method. */
14373
14374 int
14375 remote_target::can_do_single_step ()
14376 {
14377 /* We can only tell whether target supports single step or not by
14378 supported s and S vCont actions if the stub supports vContSupported
14379 feature. If the stub doesn't support vContSupported feature,
14380 we have conservatively to think target doesn't supports single
14381 step. */
14382 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14383 {
14384 struct remote_state *rs = get_remote_state ();
14385
14386 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14387 remote_vcont_probe ();
14388
14389 return rs->supports_vCont.s && rs->supports_vCont.S;
14390 }
14391 else
14392 return 0;
14393 }
14394
14395 /* Implementation of the to_execution_direction method for the remote
14396 target. */
14397
14398 enum exec_direction_kind
14399 remote_target::execution_direction ()
14400 {
14401 struct remote_state *rs = get_remote_state ();
14402
14403 return rs->last_resume_exec_dir;
14404 }
14405
14406 /* Return pointer to the thread_info struct which corresponds to
14407 THREAD_HANDLE (having length HANDLE_LEN). */
14408
14409 thread_info *
14410 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14411 int handle_len,
14412 inferior *inf)
14413 {
14414 for (thread_info *tp : all_non_exited_threads (this))
14415 {
14416 remote_thread_info *priv = get_remote_thread_info (tp);
14417
14418 if (tp->inf == inf && priv != NULL)
14419 {
14420 if (handle_len != priv->thread_handle.size ())
14421 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14422 handle_len, priv->thread_handle.size ());
14423 if (memcmp (thread_handle, priv->thread_handle.data (),
14424 handle_len) == 0)
14425 return tp;
14426 }
14427 }
14428
14429 return NULL;
14430 }
14431
14432 gdb::byte_vector
14433 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14434 {
14435 remote_thread_info *priv = get_remote_thread_info (tp);
14436 return priv->thread_handle;
14437 }
14438
14439 bool
14440 remote_target::can_async_p ()
14441 {
14442 /* This flag should be checked in the common target.c code. */
14443 gdb_assert (target_async_permitted);
14444
14445 /* We're async whenever the serial device can. */
14446 struct remote_state *rs = get_remote_state ();
14447 return serial_can_async_p (rs->remote_desc);
14448 }
14449
14450 bool
14451 remote_target::is_async_p ()
14452 {
14453 /* We're async whenever the serial device is. */
14454 struct remote_state *rs = get_remote_state ();
14455 return serial_is_async_p (rs->remote_desc);
14456 }
14457
14458 /* Pass the SERIAL event on and up to the client. One day this code
14459 will be able to delay notifying the client of an event until the
14460 point where an entire packet has been received. */
14461
14462 static serial_event_ftype remote_async_serial_handler;
14463
14464 static void
14465 remote_async_serial_handler (struct serial *scb, void *context)
14466 {
14467 /* Don't propogate error information up to the client. Instead let
14468 the client find out about the error by querying the target. */
14469 inferior_event_handler (INF_REG_EVENT);
14470 }
14471
14472 static void
14473 remote_async_inferior_event_handler (gdb_client_data data)
14474 {
14475 inferior_event_handler (INF_REG_EVENT);
14476 }
14477
14478 int
14479 remote_target::async_wait_fd ()
14480 {
14481 struct remote_state *rs = get_remote_state ();
14482 return rs->remote_desc->fd;
14483 }
14484
14485 void
14486 remote_target::async (int enable)
14487 {
14488 struct remote_state *rs = get_remote_state ();
14489
14490 if (enable)
14491 {
14492 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14493
14494 /* If there are pending events in the stop reply queue tell the
14495 event loop to process them. */
14496 if (!rs->stop_reply_queue.empty ())
14497 mark_async_event_handler (rs->remote_async_inferior_event_token);
14498 /* For simplicity, below we clear the pending events token
14499 without remembering whether it is marked, so here we always
14500 mark it. If there's actually no pending notification to
14501 process, this ends up being a no-op (other than a spurious
14502 event-loop wakeup). */
14503 if (target_is_non_stop_p ())
14504 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14505 }
14506 else
14507 {
14508 serial_async (rs->remote_desc, NULL, NULL);
14509 /* If the core is disabling async, it doesn't want to be
14510 disturbed with target events. Clear all async event sources
14511 too. */
14512 clear_async_event_handler (rs->remote_async_inferior_event_token);
14513 if (target_is_non_stop_p ())
14514 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14515 }
14516 }
14517
14518 /* Implementation of the to_thread_events method. */
14519
14520 void
14521 remote_target::thread_events (int enable)
14522 {
14523 struct remote_state *rs = get_remote_state ();
14524 size_t size = get_remote_packet_size ();
14525
14526 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14527 return;
14528
14529 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
14530 putpkt (rs->buf);
14531 getpkt (&rs->buf, 0);
14532
14533 switch (packet_ok (rs->buf,
14534 &remote_protocol_packets[PACKET_QThreadEvents]))
14535 {
14536 case PACKET_OK:
14537 if (strcmp (rs->buf.data (), "OK") != 0)
14538 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
14539 break;
14540 case PACKET_ERROR:
14541 warning (_("Remote failure reply: %s"), rs->buf.data ());
14542 break;
14543 case PACKET_UNKNOWN:
14544 break;
14545 }
14546 }
14547
14548 static void
14549 show_remote_cmd (const char *args, int from_tty)
14550 {
14551 /* We can't just use cmd_show_list here, because we want to skip
14552 the redundant "show remote Z-packet" and the legacy aliases. */
14553 struct cmd_list_element *list = remote_show_cmdlist;
14554 struct ui_out *uiout = current_uiout;
14555
14556 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14557 for (; list != NULL; list = list->next)
14558 if (strcmp (list->name, "Z-packet") == 0)
14559 continue;
14560 else if (list->type == not_set_cmd)
14561 /* Alias commands are exactly like the original, except they
14562 don't have the normal type. */
14563 continue;
14564 else
14565 {
14566 ui_out_emit_tuple option_emitter (uiout, "option");
14567
14568 uiout->field_string ("name", list->name);
14569 uiout->text (": ");
14570 if (list->type == show_cmd)
14571 do_show_command (NULL, from_tty, list);
14572 else
14573 cmd_func (list, NULL, from_tty);
14574 }
14575 }
14576
14577
14578 /* Function to be called whenever a new objfile (shlib) is detected. */
14579 static void
14580 remote_new_objfile (struct objfile *objfile)
14581 {
14582 /* The objfile change happened in that program space. */
14583 program_space *pspace = current_program_space;
14584
14585 /* The affected program space is possibly shared by multiple inferiors.
14586 Consider sending a qSymbol packet for each of the inferiors using that
14587 program space. */
14588 for (inferior *inf : all_inferiors ())
14589 {
14590 if (inf->pspace != pspace)
14591 continue;
14592
14593 /* Check whether the inferior's process target is a remote target. */
14594 remote_target *remote = as_remote_target (inf->process_target ());
14595 if (remote == nullptr)
14596 continue;
14597
14598 /* When we are attaching or handling a fork child and the shared library
14599 subsystem reads the list of loaded libraries, we receive new objfile
14600 events in between each found library. The libraries are read in an
14601 undefined order, so if we gave the remote side a chance to look up
14602 symbols between each objfile, we might give it an inconsistent picture
14603 of the inferior. It could appear that a library A appears loaded but
14604 a library B does not, even though library A requires library B. That
14605 would present a state that couldn't normally exist in the inferior.
14606
14607 So, skip these events, we'll give the remote a chance to look up
14608 symbols once all the loaded libraries and their symbols are known to
14609 GDB. */
14610 if (inf->in_initial_library_scan)
14611 continue;
14612
14613 if (!remote->has_execution (inf))
14614 continue;
14615
14616 /* Need to switch to a specific thread, because remote_check_symbols will
14617 set the general thread using INFERIOR_PTID.
14618
14619 It's possible to have inferiors with no thread here, because we are
14620 called very early in the connection process, while the inferior is
14621 being set up, before threads are added. Just skip it, start_remote_1
14622 also calls remote_check_symbols when it's done setting things up. */
14623 thread_info *thread = any_thread_of_inferior (inf);
14624 if (thread != nullptr)
14625 {
14626 scoped_restore_current_thread restore_thread;
14627 switch_to_thread (thread);
14628 remote->remote_check_symbols ();
14629 }
14630 }
14631 }
14632
14633 /* Pull all the tracepoints defined on the target and create local
14634 data structures representing them. We don't want to create real
14635 tracepoints yet, we don't want to mess up the user's existing
14636 collection. */
14637
14638 int
14639 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14640 {
14641 struct remote_state *rs = get_remote_state ();
14642 char *p;
14643
14644 /* Ask for a first packet of tracepoint definition. */
14645 putpkt ("qTfP");
14646 getpkt (&rs->buf, 0);
14647 p = rs->buf.data ();
14648 while (*p && *p != 'l')
14649 {
14650 parse_tracepoint_definition (p, utpp);
14651 /* Ask for another packet of tracepoint definition. */
14652 putpkt ("qTsP");
14653 getpkt (&rs->buf, 0);
14654 p = rs->buf.data ();
14655 }
14656 return 0;
14657 }
14658
14659 int
14660 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14661 {
14662 struct remote_state *rs = get_remote_state ();
14663 char *p;
14664
14665 /* Ask for a first packet of variable definition. */
14666 putpkt ("qTfV");
14667 getpkt (&rs->buf, 0);
14668 p = rs->buf.data ();
14669 while (*p && *p != 'l')
14670 {
14671 parse_tsv_definition (p, utsvp);
14672 /* Ask for another packet of variable definition. */
14673 putpkt ("qTsV");
14674 getpkt (&rs->buf, 0);
14675 p = rs->buf.data ();
14676 }
14677 return 0;
14678 }
14679
14680 /* The "set/show range-stepping" show hook. */
14681
14682 static void
14683 show_range_stepping (struct ui_file *file, int from_tty,
14684 struct cmd_list_element *c,
14685 const char *value)
14686 {
14687 gdb_printf (file,
14688 _("Debugger's willingness to use range stepping "
14689 "is %s.\n"), value);
14690 }
14691
14692 /* Return true if the vCont;r action is supported by the remote
14693 stub. */
14694
14695 bool
14696 remote_target::vcont_r_supported ()
14697 {
14698 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14699 remote_vcont_probe ();
14700
14701 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14702 && get_remote_state ()->supports_vCont.r);
14703 }
14704
14705 /* The "set/show range-stepping" set hook. */
14706
14707 static void
14708 set_range_stepping (const char *ignore_args, int from_tty,
14709 struct cmd_list_element *c)
14710 {
14711 /* When enabling, check whether range stepping is actually supported
14712 by the target, and warn if not. */
14713 if (use_range_stepping)
14714 {
14715 remote_target *remote = get_current_remote_target ();
14716 if (remote == NULL
14717 || !remote->vcont_r_supported ())
14718 warning (_("Range stepping is not supported by the current target"));
14719 }
14720 }
14721
14722 static void
14723 show_remote_debug (struct ui_file *file, int from_tty,
14724 struct cmd_list_element *c, const char *value)
14725 {
14726 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
14727 value);
14728 }
14729
14730 static void
14731 show_remote_timeout (struct ui_file *file, int from_tty,
14732 struct cmd_list_element *c, const char *value)
14733 {
14734 gdb_printf (file,
14735 _("Timeout limit to wait for target to respond is %s.\n"),
14736 value);
14737 }
14738
14739 /* Implement the "supports_memory_tagging" target_ops method. */
14740
14741 bool
14742 remote_target::supports_memory_tagging ()
14743 {
14744 return remote_memory_tagging_p ();
14745 }
14746
14747 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
14748
14749 static void
14750 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14751 size_t len, int type)
14752 {
14753 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14754
14755 std::string request = string_printf ("qMemTags:%s,%s:%s",
14756 phex_nz (address, addr_size),
14757 phex_nz (len, sizeof (len)),
14758 phex_nz (type, sizeof (type)));
14759
14760 strcpy (packet.data (), request.c_str ());
14761 }
14762
14763 /* Parse the qMemTags packet reply into TAGS.
14764
14765 Return true if successful, false otherwise. */
14766
14767 static bool
14768 parse_fetch_memtags_reply (const gdb::char_vector &reply,
14769 gdb::byte_vector &tags)
14770 {
14771 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
14772 return false;
14773
14774 /* Copy the tag data. */
14775 tags = hex2bin (reply.data () + 1);
14776
14777 return true;
14778 }
14779
14780 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
14781
14782 static void
14783 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14784 size_t len, int type,
14785 const gdb::byte_vector &tags)
14786 {
14787 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14788
14789 /* Put together the main packet, address and length. */
14790 std::string request = string_printf ("QMemTags:%s,%s:%s:",
14791 phex_nz (address, addr_size),
14792 phex_nz (len, sizeof (len)),
14793 phex_nz (type, sizeof (type)));
14794 request += bin2hex (tags.data (), tags.size ());
14795
14796 /* Check if we have exceeded the maximum packet size. */
14797 if (packet.size () < request.length ())
14798 error (_("Contents too big for packet QMemTags."));
14799
14800 strcpy (packet.data (), request.c_str ());
14801 }
14802
14803 /* Implement the "fetch_memtags" target_ops method. */
14804
14805 bool
14806 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
14807 gdb::byte_vector &tags, int type)
14808 {
14809 /* Make sure the qMemTags packet is supported. */
14810 if (!remote_memory_tagging_p ())
14811 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
14812
14813 struct remote_state *rs = get_remote_state ();
14814
14815 create_fetch_memtags_request (rs->buf, address, len, type);
14816
14817 putpkt (rs->buf);
14818 getpkt (&rs->buf, 0);
14819
14820 return parse_fetch_memtags_reply (rs->buf, tags);
14821 }
14822
14823 /* Implement the "store_memtags" target_ops method. */
14824
14825 bool
14826 remote_target::store_memtags (CORE_ADDR address, size_t len,
14827 const gdb::byte_vector &tags, int type)
14828 {
14829 /* Make sure the QMemTags packet is supported. */
14830 if (!remote_memory_tagging_p ())
14831 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
14832
14833 struct remote_state *rs = get_remote_state ();
14834
14835 create_store_memtags_request (rs->buf, address, len, type, tags);
14836
14837 putpkt (rs->buf);
14838 getpkt (&rs->buf, 0);
14839
14840 /* Verify if the request was successful. */
14841 return packet_check_result (rs->buf.data ()) == PACKET_OK;
14842 }
14843
14844 /* Return true if remote target T is non-stop. */
14845
14846 bool
14847 remote_target_is_non_stop_p (remote_target *t)
14848 {
14849 scoped_restore_current_thread restore_thread;
14850 switch_to_target_no_thread (t);
14851
14852 return target_is_non_stop_p ();
14853 }
14854
14855 #if GDB_SELF_TEST
14856
14857 namespace selftests {
14858
14859 static void
14860 test_memory_tagging_functions ()
14861 {
14862 remote_target remote;
14863
14864 struct packet_config *config
14865 = &remote_protocol_packets[PACKET_memory_tagging_feature];
14866
14867 scoped_restore restore_memtag_support_
14868 = make_scoped_restore (&config->support);
14869
14870 /* Test memory tagging packet support. */
14871 config->support = PACKET_SUPPORT_UNKNOWN;
14872 SELF_CHECK (remote.supports_memory_tagging () == false);
14873 config->support = PACKET_DISABLE;
14874 SELF_CHECK (remote.supports_memory_tagging () == false);
14875 config->support = PACKET_ENABLE;
14876 SELF_CHECK (remote.supports_memory_tagging () == true);
14877
14878 /* Setup testing. */
14879 gdb::char_vector packet;
14880 gdb::byte_vector tags, bv;
14881 std::string expected, reply;
14882 packet.resize (32000);
14883
14884 /* Test creating a qMemTags request. */
14885
14886 expected = "qMemTags:0,0:0";
14887 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
14888 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14889
14890 expected = "qMemTags:deadbeef,10:1";
14891 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
14892 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14893
14894 /* Test parsing a qMemTags reply. */
14895
14896 /* Error reply, tags vector unmodified. */
14897 reply = "E00";
14898 strcpy (packet.data (), reply.c_str ());
14899 tags.resize (0);
14900 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
14901 SELF_CHECK (tags.size () == 0);
14902
14903 /* Valid reply, tags vector updated. */
14904 tags.resize (0);
14905 bv.resize (0);
14906
14907 for (int i = 0; i < 5; i++)
14908 bv.push_back (i);
14909
14910 reply = "m" + bin2hex (bv.data (), bv.size ());
14911 strcpy (packet.data (), reply.c_str ());
14912
14913 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
14914 SELF_CHECK (tags.size () == 5);
14915
14916 for (int i = 0; i < 5; i++)
14917 SELF_CHECK (tags[i] == i);
14918
14919 /* Test creating a QMemTags request. */
14920
14921 /* Empty tag data. */
14922 tags.resize (0);
14923 expected = "QMemTags:0,0:0:";
14924 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
14925 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14926 expected.length ()) == 0);
14927
14928 /* Non-empty tag data. */
14929 tags.resize (0);
14930 for (int i = 0; i < 5; i++)
14931 tags.push_back (i);
14932 expected = "QMemTags:deadbeef,ff:1:0001020304";
14933 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
14934 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14935 expected.length ()) == 0);
14936 }
14937
14938 } // namespace selftests
14939 #endif /* GDB_SELF_TEST */
14940
14941 void _initialize_remote ();
14942 void
14943 _initialize_remote ()
14944 {
14945 /* architecture specific data */
14946 remote_g_packet_data_handle =
14947 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14948
14949 add_target (remote_target_info, remote_target::open);
14950 add_target (extended_remote_target_info, extended_remote_target::open);
14951
14952 /* Hook into new objfile notification. */
14953 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
14954
14955 #if 0
14956 init_remote_threadtests ();
14957 #endif
14958
14959 /* set/show remote ... */
14960
14961 add_basic_prefix_cmd ("remote", class_maintenance, _("\
14962 Remote protocol specific variables.\n\
14963 Configure various remote-protocol specific variables such as\n\
14964 the packets being used."),
14965 &remote_set_cmdlist,
14966 0 /* allow-unknown */, &setlist);
14967 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14968 Remote protocol specific variables.\n\
14969 Configure various remote-protocol specific variables such as\n\
14970 the packets being used."),
14971 &remote_show_cmdlist,
14972 0 /* allow-unknown */, &showlist);
14973
14974 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14975 Compare section data on target to the exec file.\n\
14976 Argument is a single section name (default: all loaded sections).\n\
14977 To compare only read-only loaded sections, specify the -r option."),
14978 &cmdlist);
14979
14980 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
14981 Send an arbitrary packet to a remote target.\n\
14982 maintenance packet TEXT\n\
14983 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14984 this command sends the string TEXT to the inferior, and displays the\n\
14985 response packet. GDB supplies the initial `$' character, and the\n\
14986 terminating `#' character and checksum."),
14987 &maintenancelist);
14988
14989 set_show_commands remotebreak_cmds
14990 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14991 Set whether to send break if interrupted."), _("\
14992 Show whether to send break if interrupted."), _("\
14993 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14994 set_remotebreak, show_remotebreak,
14995 &setlist, &showlist);
14996 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
14997 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
14998
14999 add_setshow_enum_cmd ("interrupt-sequence", class_support,
15000 interrupt_sequence_modes, &interrupt_sequence_mode,
15001 _("\
15002 Set interrupt sequence to remote target."), _("\
15003 Show interrupt sequence to remote target."), _("\
15004 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
15005 NULL, show_interrupt_sequence,
15006 &remote_set_cmdlist,
15007 &remote_show_cmdlist);
15008
15009 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
15010 &interrupt_on_connect, _("\
15011 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15012 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15013 If set, interrupt sequence is sent to remote target."),
15014 NULL, NULL,
15015 &remote_set_cmdlist, &remote_show_cmdlist);
15016
15017 /* Install commands for configuring memory read/write packets. */
15018
15019 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
15020 Set the maximum number of bytes per memory write packet (deprecated)."),
15021 &setlist);
15022 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
15023 Show the maximum number of bytes per memory write packet (deprecated)."),
15024 &showlist);
15025 add_cmd ("memory-write-packet-size", no_class,
15026 set_memory_write_packet_size, _("\
15027 Set the maximum number of bytes per memory-write packet.\n\
15028 Specify the number of bytes in a packet or 0 (zero) for the\n\
15029 default packet size. The actual limit is further reduced\n\
15030 dependent on the target. Specify ``fixed'' to disable the\n\
15031 further restriction and ``limit'' to enable that restriction."),
15032 &remote_set_cmdlist);
15033 add_cmd ("memory-read-packet-size", no_class,
15034 set_memory_read_packet_size, _("\
15035 Set the maximum number of bytes per memory-read packet.\n\
15036 Specify the number of bytes in a packet or 0 (zero) for the\n\
15037 default packet size. The actual limit is further reduced\n\
15038 dependent on the target. Specify ``fixed'' to disable the\n\
15039 further restriction and ``limit'' to enable that restriction."),
15040 &remote_set_cmdlist);
15041 add_cmd ("memory-write-packet-size", no_class,
15042 show_memory_write_packet_size,
15043 _("Show the maximum number of bytes per memory-write packet."),
15044 &remote_show_cmdlist);
15045 add_cmd ("memory-read-packet-size", no_class,
15046 show_memory_read_packet_size,
15047 _("Show the maximum number of bytes per memory-read packet."),
15048 &remote_show_cmdlist);
15049
15050 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
15051 &remote_hw_watchpoint_limit, _("\
15052 Set the maximum number of target hardware watchpoints."), _("\
15053 Show the maximum number of target hardware watchpoints."), _("\
15054 Specify \"unlimited\" for unlimited hardware watchpoints."),
15055 NULL, show_hardware_watchpoint_limit,
15056 &remote_set_cmdlist,
15057 &remote_show_cmdlist);
15058 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15059 no_class,
15060 &remote_hw_watchpoint_length_limit, _("\
15061 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15062 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15063 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15064 NULL, show_hardware_watchpoint_length_limit,
15065 &remote_set_cmdlist, &remote_show_cmdlist);
15066 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
15067 &remote_hw_breakpoint_limit, _("\
15068 Set the maximum number of target hardware breakpoints."), _("\
15069 Show the maximum number of target hardware breakpoints."), _("\
15070 Specify \"unlimited\" for unlimited hardware breakpoints."),
15071 NULL, show_hardware_breakpoint_limit,
15072 &remote_set_cmdlist, &remote_show_cmdlist);
15073
15074 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15075 &remote_address_size, _("\
15076 Set the maximum size of the address (in bits) in a memory packet."), _("\
15077 Show the maximum size of the address (in bits) in a memory packet."), NULL,
15078 NULL,
15079 NULL, /* FIXME: i18n: */
15080 &setlist, &showlist);
15081
15082 init_all_packet_configs ();
15083
15084 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
15085 "X", "binary-download", 1);
15086
15087 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
15088 "vCont", "verbose-resume", 0);
15089
15090 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
15091 "QPassSignals", "pass-signals", 0);
15092
15093 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
15094 "QCatchSyscalls", "catch-syscalls", 0);
15095
15096 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
15097 "QProgramSignals", "program-signals", 0);
15098
15099 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
15100 "QSetWorkingDir", "set-working-dir", 0);
15101
15102 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
15103 "QStartupWithShell", "startup-with-shell", 0);
15104
15105 add_packet_config_cmd (&remote_protocol_packets
15106 [PACKET_QEnvironmentHexEncoded],
15107 "QEnvironmentHexEncoded", "environment-hex-encoded",
15108 0);
15109
15110 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
15111 "QEnvironmentReset", "environment-reset",
15112 0);
15113
15114 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
15115 "QEnvironmentUnset", "environment-unset",
15116 0);
15117
15118 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
15119 "qSymbol", "symbol-lookup", 0);
15120
15121 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
15122 "P", "set-register", 1);
15123
15124 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
15125 "p", "fetch-register", 1);
15126
15127 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
15128 "Z0", "software-breakpoint", 0);
15129
15130 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
15131 "Z1", "hardware-breakpoint", 0);
15132
15133 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
15134 "Z2", "write-watchpoint", 0);
15135
15136 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
15137 "Z3", "read-watchpoint", 0);
15138
15139 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
15140 "Z4", "access-watchpoint", 0);
15141
15142 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
15143 "qXfer:auxv:read", "read-aux-vector", 0);
15144
15145 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
15146 "qXfer:exec-file:read", "pid-to-exec-file", 0);
15147
15148 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
15149 "qXfer:features:read", "target-features", 0);
15150
15151 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
15152 "qXfer:libraries:read", "library-info", 0);
15153
15154 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
15155 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15156
15157 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
15158 "qXfer:memory-map:read", "memory-map", 0);
15159
15160 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
15161 "qXfer:osdata:read", "osdata", 0);
15162
15163 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
15164 "qXfer:threads:read", "threads", 0);
15165
15166 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
15167 "qXfer:siginfo:read", "read-siginfo-object", 0);
15168
15169 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
15170 "qXfer:siginfo:write", "write-siginfo-object", 0);
15171
15172 add_packet_config_cmd
15173 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
15174 "qXfer:traceframe-info:read", "traceframe-info", 0);
15175
15176 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
15177 "qXfer:uib:read", "unwind-info-block", 0);
15178
15179 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
15180 "qGetTLSAddr", "get-thread-local-storage-address",
15181 0);
15182
15183 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
15184 "qGetTIBAddr", "get-thread-information-block-address",
15185 0);
15186
15187 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
15188 "bc", "reverse-continue", 0);
15189
15190 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
15191 "bs", "reverse-step", 0);
15192
15193 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
15194 "qSupported", "supported-packets", 0);
15195
15196 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
15197 "qSearch:memory", "search-memory", 0);
15198
15199 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
15200 "qTStatus", "trace-status", 0);
15201
15202 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
15203 "vFile:setfs", "hostio-setfs", 0);
15204
15205 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
15206 "vFile:open", "hostio-open", 0);
15207
15208 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
15209 "vFile:pread", "hostio-pread", 0);
15210
15211 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
15212 "vFile:pwrite", "hostio-pwrite", 0);
15213
15214 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
15215 "vFile:close", "hostio-close", 0);
15216
15217 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
15218 "vFile:unlink", "hostio-unlink", 0);
15219
15220 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
15221 "vFile:readlink", "hostio-readlink", 0);
15222
15223 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
15224 "vFile:fstat", "hostio-fstat", 0);
15225
15226 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
15227 "vAttach", "attach", 0);
15228
15229 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
15230 "vRun", "run", 0);
15231
15232 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
15233 "QStartNoAckMode", "noack", 0);
15234
15235 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
15236 "vKill", "kill", 0);
15237
15238 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
15239 "qAttached", "query-attached", 0);
15240
15241 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
15242 "ConditionalTracepoints",
15243 "conditional-tracepoints", 0);
15244
15245 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
15246 "ConditionalBreakpoints",
15247 "conditional-breakpoints", 0);
15248
15249 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
15250 "BreakpointCommands",
15251 "breakpoint-commands", 0);
15252
15253 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
15254 "FastTracepoints", "fast-tracepoints", 0);
15255
15256 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
15257 "TracepointSource", "TracepointSource", 0);
15258
15259 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
15260 "QAllow", "allow", 0);
15261
15262 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
15263 "StaticTracepoints", "static-tracepoints", 0);
15264
15265 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
15266 "InstallInTrace", "install-in-trace", 0);
15267
15268 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
15269 "qXfer:statictrace:read", "read-sdata-object", 0);
15270
15271 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
15272 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
15273
15274 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
15275 "QDisableRandomization", "disable-randomization", 0);
15276
15277 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
15278 "QAgent", "agent", 0);
15279
15280 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
15281 "QTBuffer:size", "trace-buffer-size", 0);
15282
15283 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
15284 "Qbtrace:off", "disable-btrace", 0);
15285
15286 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
15287 "Qbtrace:bts", "enable-btrace-bts", 0);
15288
15289 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
15290 "Qbtrace:pt", "enable-btrace-pt", 0);
15291
15292 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
15293 "qXfer:btrace", "read-btrace", 0);
15294
15295 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
15296 "qXfer:btrace-conf", "read-btrace-conf", 0);
15297
15298 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
15299 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
15300
15301 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
15302 "multiprocess-feature", "multiprocess-feature", 0);
15303
15304 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
15305 "swbreak-feature", "swbreak-feature", 0);
15306
15307 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
15308 "hwbreak-feature", "hwbreak-feature", 0);
15309
15310 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
15311 "fork-event-feature", "fork-event-feature", 0);
15312
15313 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
15314 "vfork-event-feature", "vfork-event-feature", 0);
15315
15316 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
15317 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
15318
15319 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
15320 "vContSupported", "verbose-resume-supported", 0);
15321
15322 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
15323 "exec-event-feature", "exec-event-feature", 0);
15324
15325 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
15326 "vCtrlC", "ctrl-c", 0);
15327
15328 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
15329 "QThreadEvents", "thread-events", 0);
15330
15331 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
15332 "N stop reply", "no-resumed-stop-reply", 0);
15333
15334 add_packet_config_cmd (&remote_protocol_packets[PACKET_memory_tagging_feature],
15335 "memory-tagging-feature", "memory-tagging-feature", 0);
15336
15337 /* Assert that we've registered "set remote foo-packet" commands
15338 for all packet configs. */
15339 {
15340 int i;
15341
15342 for (i = 0; i < PACKET_MAX; i++)
15343 {
15344 /* Ideally all configs would have a command associated. Some
15345 still don't though. */
15346 int excepted;
15347
15348 switch (i)
15349 {
15350 case PACKET_QNonStop:
15351 case PACKET_EnableDisableTracepoints_feature:
15352 case PACKET_tracenz_feature:
15353 case PACKET_DisconnectedTracing_feature:
15354 case PACKET_augmented_libraries_svr4_read_feature:
15355 case PACKET_qCRC:
15356 /* Additions to this list need to be well justified:
15357 pre-existing packets are OK; new packets are not. */
15358 excepted = 1;
15359 break;
15360 default:
15361 excepted = 0;
15362 break;
15363 }
15364
15365 /* This catches both forgetting to add a config command, and
15366 forgetting to remove a packet from the exception list. */
15367 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
15368 }
15369 }
15370
15371 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15372 Z sub-packet has its own set and show commands, but users may
15373 have sets to this variable in their .gdbinit files (or in their
15374 documentation). */
15375 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
15376 &remote_Z_packet_detect, _("\
15377 Set use of remote protocol `Z' packets."), _("\
15378 Show use of remote protocol `Z' packets."), _("\
15379 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
15380 packets."),
15381 set_remote_protocol_Z_packet_cmd,
15382 show_remote_protocol_Z_packet_cmd,
15383 /* FIXME: i18n: Use of remote protocol
15384 `Z' packets is %s. */
15385 &remote_set_cmdlist, &remote_show_cmdlist);
15386
15387 add_basic_prefix_cmd ("remote", class_files, _("\
15388 Manipulate files on the remote system.\n\
15389 Transfer files to and from the remote target system."),
15390 &remote_cmdlist,
15391 0 /* allow-unknown */, &cmdlist);
15392
15393 add_cmd ("put", class_files, remote_put_command,
15394 _("Copy a local file to the remote system."),
15395 &remote_cmdlist);
15396
15397 add_cmd ("get", class_files, remote_get_command,
15398 _("Copy a remote file to the local system."),
15399 &remote_cmdlist);
15400
15401 add_cmd ("delete", class_files, remote_delete_command,
15402 _("Delete a remote file."),
15403 &remote_cmdlist);
15404
15405 add_setshow_string_noescape_cmd ("exec-file", class_files,
15406 &remote_exec_file_var, _("\
15407 Set the remote pathname for \"run\"."), _("\
15408 Show the remote pathname for \"run\"."), NULL,
15409 set_remote_exec_file,
15410 show_remote_exec_file,
15411 &remote_set_cmdlist,
15412 &remote_show_cmdlist);
15413
15414 add_setshow_boolean_cmd ("range-stepping", class_run,
15415 &use_range_stepping, _("\
15416 Enable or disable range stepping."), _("\
15417 Show whether target-assisted range stepping is enabled."), _("\
15418 If on, and the target supports it, when stepping a source line, GDB\n\
15419 tells the target to step the corresponding range of addresses itself instead\n\
15420 of issuing multiple single-steps. This speeds up source level\n\
15421 stepping. If off, GDB always issues single-steps, even if range\n\
15422 stepping is supported by the target. The default is on."),
15423 set_range_stepping,
15424 show_range_stepping,
15425 &setlist,
15426 &showlist);
15427
15428 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15429 Set watchdog timer."), _("\
15430 Show watchdog timer."), _("\
15431 When non-zero, this timeout is used instead of waiting forever for a target\n\
15432 to finish a low-level step or continue operation. If the specified amount\n\
15433 of time passes without a response from the target, an error occurs."),
15434 NULL,
15435 show_watchdog,
15436 &setlist, &showlist);
15437
15438 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15439 &remote_packet_max_chars, _("\
15440 Set the maximum number of characters to display for each remote packet."), _("\
15441 Show the maximum number of characters to display for each remote packet."), _("\
15442 Specify \"unlimited\" to display all the characters."),
15443 NULL, show_remote_packet_max_chars,
15444 &setdebuglist, &showdebuglist);
15445
15446 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15447 _("Set debugging of remote protocol."),
15448 _("Show debugging of remote protocol."),
15449 _("\
15450 When enabled, each packet sent or received with the remote target\n\
15451 is displayed."),
15452 NULL,
15453 show_remote_debug,
15454 &setdebuglist, &showdebuglist);
15455
15456 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15457 &remote_timeout, _("\
15458 Set timeout limit to wait for target to respond."), _("\
15459 Show timeout limit to wait for target to respond."), _("\
15460 This value is used to set the time limit for gdb to wait for a response\n\
15461 from the target."),
15462 NULL,
15463 show_remote_timeout,
15464 &setlist, &showlist);
15465
15466 /* Eventually initialize fileio. See fileio.c */
15467 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
15468
15469 #if GDB_SELF_TEST
15470 selftests::register_test ("remote_memory_tagging",
15471 selftests::test_memory_tagging_functions);
15472 #endif
15473 }