6ccfa3365b0d624b78998d010143f83c01b3c0ac
[binutils-gdb.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3 Copyright (C) 1988-2021 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 /* remote_wait is normally called when the target is running and
262 waits for a stop reply packet. But sometimes we need to call it
263 when the target is already stopped. We can send a "?" packet
264 and have remote_wait read the response. Or, if we already have
265 the response, we can stash it in BUF and tell remote_wait to
266 skip calling getpkt. This flag is set when BUF contains a
267 stop reply packet and the target is not waiting. */
268 int cached_wait_status = 0;
269
270 /* True, if in no ack mode. That is, neither GDB nor the stub will
271 expect acks from each other. The connection is assumed to be
272 reliable. */
273 bool noack_mode = false;
274
275 /* True if we're connected in extended remote mode. */
276 bool extended = false;
277
278 /* True if we resumed the target and we're waiting for the target to
279 stop. In the mean time, we can't start another command/query.
280 The remote server wouldn't be ready to process it, so we'd
281 timeout waiting for a reply that would never come and eventually
282 we'd close the connection. This can happen in asynchronous mode
283 because we allow GDB commands while the target is running. */
284 bool waiting_for_stop_reply = false;
285
286 /* The status of the stub support for the various vCont actions. */
287 vCont_action_support supports_vCont;
288 /* Whether vCont support was probed already. This is a workaround
289 until packet_support is per-connection. */
290 bool supports_vCont_probed;
291
292 /* True if the user has pressed Ctrl-C, but the target hasn't
293 responded to that. */
294 bool ctrlc_pending_p = false;
295
296 /* True if we saw a Ctrl-C while reading or writing from/to the
297 remote descriptor. At that point it is not safe to send a remote
298 interrupt packet, so we instead remember we saw the Ctrl-C and
299 process it once we're done with sending/receiving the current
300 packet, which should be shortly. If however that takes too long,
301 and the user presses Ctrl-C again, we offer to disconnect. */
302 bool got_ctrlc_during_io = false;
303
304 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
305 remote_open knows that we don't have a file open when the program
306 starts. */
307 struct serial *remote_desc = nullptr;
308
309 /* These are the threads which we last sent to the remote system. The
310 TID member will be -1 for all or -2 for not sent yet. */
311 ptid_t general_thread = null_ptid;
312 ptid_t continue_thread = null_ptid;
313
314 /* This is the traceframe which we last selected on the remote system.
315 It will be -1 if no traceframe is selected. */
316 int remote_traceframe_number = -1;
317
318 char *last_pass_packet = nullptr;
319
320 /* The last QProgramSignals packet sent to the target. We bypass
321 sending a new program signals list down to the target if the new
322 packet is exactly the same as the last we sent. IOW, we only let
323 the target know about program signals list changes. */
324 char *last_program_signals_packet = nullptr;
325
326 gdb_signal last_sent_signal = GDB_SIGNAL_0;
327
328 bool last_sent_step = false;
329
330 /* The execution direction of the last resume we got. */
331 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
332
333 char *finished_object = nullptr;
334 char *finished_annex = nullptr;
335 ULONGEST finished_offset = 0;
336
337 /* Should we try the 'ThreadInfo' query packet?
338
339 This variable (NOT available to the user: auto-detect only!)
340 determines whether GDB will use the new, simpler "ThreadInfo"
341 query or the older, more complex syntax for thread queries.
342 This is an auto-detect variable (set to true at each connect,
343 and set to false when the target fails to recognize it). */
344 bool use_threadinfo_query = false;
345 bool use_threadextra_query = false;
346
347 threadref echo_nextthread {};
348 threadref nextthread {};
349 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
350
351 /* The state of remote notification. */
352 struct remote_notif_state *notif_state = nullptr;
353
354 /* The branch trace configuration. */
355 struct btrace_config btrace_config {};
356
357 /* The argument to the last "vFile:setfs:" packet we sent, used
358 to avoid sending repeated unnecessary "vFile:setfs:" packets.
359 Initialized to -1 to indicate that no "vFile:setfs:" packet
360 has yet been sent. */
361 int fs_pid = -1;
362
363 /* A readahead cache for vFile:pread. Often, reading a binary
364 involves a sequence of small reads. E.g., when parsing an ELF
365 file. A readahead cache helps mostly the case of remote
366 debugging on a connection with higher latency, due to the
367 request/reply nature of the RSP. We only cache data for a single
368 file descriptor at a time. */
369 struct readahead_cache readahead_cache;
370
371 /* The list of already fetched and acknowledged stop events. This
372 queue is used for notification Stop, and other notifications
373 don't need queue for their events, because the notification
374 events of Stop can't be consumed immediately, so that events
375 should be queued first, and be consumed by remote_wait_{ns,as}
376 one per time. Other notifications can consume their events
377 immediately, so queue is not needed for them. */
378 std::vector<stop_reply_up> stop_reply_queue;
379
380 /* Asynchronous signal handle registered as event loop source for
381 when we have pending events ready to be passed to the core. */
382 struct async_event_handler *remote_async_inferior_event_token = nullptr;
383
384 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
385 ``forever'' still use the normal timeout mechanism. This is
386 currently used by the ASYNC code to guarentee that target reads
387 during the initial connect always time-out. Once getpkt has been
388 modified to return a timeout indication and, in turn
389 remote_wait()/wait_for_inferior() have gained a timeout parameter
390 this can go away. */
391 int wait_forever_enabled_p = 1;
392
393 private:
394 /* Mapping of remote protocol data for each gdbarch. Usually there
395 is only one entry here, though we may see more with stubs that
396 support multi-process. */
397 std::unordered_map<struct gdbarch *, remote_arch_state>
398 m_arch_states;
399 };
400
401 static const target_info remote_target_info = {
402 "remote",
403 N_("Remote serial target in gdb-specific protocol"),
404 remote_doc
405 };
406
407 class remote_target : public process_stratum_target
408 {
409 public:
410 remote_target () = default;
411 ~remote_target () override;
412
413 const target_info &info () const override
414 { return remote_target_info; }
415
416 const char *connection_string () override;
417
418 thread_control_capabilities get_thread_control_capabilities () override
419 { return tc_schedlock; }
420
421 /* Open a remote connection. */
422 static void open (const char *, int);
423
424 void close () override;
425
426 void detach (inferior *, int) override;
427 void disconnect (const char *, int) override;
428
429 void commit_resume () override;
430 void resume (ptid_t, int, enum gdb_signal) override;
431 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
432
433 void fetch_registers (struct regcache *, int) override;
434 void store_registers (struct regcache *, int) override;
435 void prepare_to_store (struct regcache *) override;
436
437 void files_info () override;
438
439 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
440
441 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
442 enum remove_bp_reason) override;
443
444
445 bool stopped_by_sw_breakpoint () override;
446 bool supports_stopped_by_sw_breakpoint () override;
447
448 bool stopped_by_hw_breakpoint () override;
449
450 bool supports_stopped_by_hw_breakpoint () override;
451
452 bool stopped_by_watchpoint () override;
453
454 bool stopped_data_address (CORE_ADDR *) override;
455
456 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
457
458 int can_use_hw_breakpoint (enum bptype, int, int) override;
459
460 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
461
462 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
463
464 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
465
466 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
467 struct expression *) override;
468
469 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
470 struct expression *) override;
471
472 void kill () override;
473
474 void load (const char *, int) override;
475
476 void mourn_inferior () override;
477
478 void pass_signals (gdb::array_view<const unsigned char>) override;
479
480 int set_syscall_catchpoint (int, bool, int,
481 gdb::array_view<const int>) override;
482
483 void program_signals (gdb::array_view<const unsigned char>) override;
484
485 bool thread_alive (ptid_t ptid) override;
486
487 const char *thread_name (struct thread_info *) override;
488
489 void update_thread_list () override;
490
491 std::string pid_to_str (ptid_t) override;
492
493 const char *extra_thread_info (struct thread_info *) override;
494
495 ptid_t get_ada_task_ptid (long lwp, long thread) override;
496
497 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
498 int handle_len,
499 inferior *inf) override;
500
501 gdb::byte_vector thread_info_to_thread_handle (struct thread_info *tp)
502 override;
503
504 void stop (ptid_t) override;
505
506 void interrupt () override;
507
508 void pass_ctrlc () override;
509
510 enum target_xfer_status xfer_partial (enum target_object object,
511 const char *annex,
512 gdb_byte *readbuf,
513 const gdb_byte *writebuf,
514 ULONGEST offset, ULONGEST len,
515 ULONGEST *xfered_len) override;
516
517 ULONGEST get_memory_xfer_limit () override;
518
519 void rcmd (const char *command, struct ui_file *output) override;
520
521 char *pid_to_exec_file (int pid) override;
522
523 void log_command (const char *cmd) override
524 {
525 serial_log_command (this, cmd);
526 }
527
528 CORE_ADDR get_thread_local_address (ptid_t ptid,
529 CORE_ADDR load_module_addr,
530 CORE_ADDR offset) override;
531
532 bool can_execute_reverse () override;
533
534 std::vector<mem_region> memory_map () override;
535
536 void flash_erase (ULONGEST address, LONGEST length) override;
537
538 void flash_done () override;
539
540 const struct target_desc *read_description () override;
541
542 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
543 const gdb_byte *pattern, ULONGEST pattern_len,
544 CORE_ADDR *found_addrp) override;
545
546 bool can_async_p () override;
547
548 bool is_async_p () override;
549
550 void async (int) override;
551
552 int async_wait_fd () override;
553
554 void thread_events (int) override;
555
556 int can_do_single_step () override;
557
558 void terminal_inferior () override;
559
560 void terminal_ours () override;
561
562 bool supports_non_stop () override;
563
564 bool supports_multi_process () override;
565
566 bool supports_disable_randomization () override;
567
568 bool filesystem_is_local () override;
569
570
571 int fileio_open (struct inferior *inf, const char *filename,
572 int flags, int mode, int warn_if_slow,
573 int *target_errno) override;
574
575 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
576 ULONGEST offset, int *target_errno) override;
577
578 int fileio_pread (int fd, gdb_byte *read_buf, int len,
579 ULONGEST offset, int *target_errno) override;
580
581 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
582
583 int fileio_close (int fd, int *target_errno) override;
584
585 int fileio_unlink (struct inferior *inf,
586 const char *filename,
587 int *target_errno) override;
588
589 gdb::optional<std::string>
590 fileio_readlink (struct inferior *inf,
591 const char *filename,
592 int *target_errno) override;
593
594 bool supports_enable_disable_tracepoint () override;
595
596 bool supports_string_tracing () override;
597
598 bool supports_evaluation_of_breakpoint_conditions () override;
599
600 bool can_run_breakpoint_commands () override;
601
602 void trace_init () override;
603
604 void download_tracepoint (struct bp_location *location) override;
605
606 bool can_download_tracepoint () override;
607
608 void download_trace_state_variable (const trace_state_variable &tsv) override;
609
610 void enable_tracepoint (struct bp_location *location) override;
611
612 void disable_tracepoint (struct bp_location *location) override;
613
614 void trace_set_readonly_regions () override;
615
616 void trace_start () override;
617
618 int get_trace_status (struct trace_status *ts) override;
619
620 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
621 override;
622
623 void trace_stop () override;
624
625 int trace_find (enum trace_find_type type, int num,
626 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
627
628 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
629
630 int save_trace_data (const char *filename) override;
631
632 int upload_tracepoints (struct uploaded_tp **utpp) override;
633
634 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
635
636 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
637
638 int get_min_fast_tracepoint_insn_len () override;
639
640 void set_disconnected_tracing (int val) override;
641
642 void set_circular_trace_buffer (int val) override;
643
644 void set_trace_buffer_size (LONGEST val) override;
645
646 bool set_trace_notes (const char *user, const char *notes,
647 const char *stopnotes) override;
648
649 int core_of_thread (ptid_t ptid) override;
650
651 int verify_memory (const gdb_byte *data,
652 CORE_ADDR memaddr, ULONGEST size) override;
653
654
655 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
656
657 void set_permissions () override;
658
659 bool static_tracepoint_marker_at (CORE_ADDR,
660 struct static_tracepoint_marker *marker)
661 override;
662
663 std::vector<static_tracepoint_marker>
664 static_tracepoint_markers_by_strid (const char *id) override;
665
666 traceframe_info_up traceframe_info () override;
667
668 bool use_agent (bool use) override;
669 bool can_use_agent () override;
670
671 struct btrace_target_info *enable_btrace (ptid_t ptid,
672 const struct btrace_config *conf) override;
673
674 void disable_btrace (struct btrace_target_info *tinfo) override;
675
676 void teardown_btrace (struct btrace_target_info *tinfo) override;
677
678 enum btrace_error read_btrace (struct btrace_data *data,
679 struct btrace_target_info *btinfo,
680 enum btrace_read_type type) override;
681
682 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
683 bool augmented_libraries_svr4_read () override;
684 bool follow_fork (bool, bool) override;
685 void follow_exec (struct inferior *, const char *) override;
686 int insert_fork_catchpoint (int) override;
687 int remove_fork_catchpoint (int) override;
688 int insert_vfork_catchpoint (int) override;
689 int remove_vfork_catchpoint (int) override;
690 int insert_exec_catchpoint (int) override;
691 int remove_exec_catchpoint (int) override;
692 enum exec_direction_kind execution_direction () override;
693
694 bool supports_memory_tagging () override;
695
696 bool fetch_memtags (CORE_ADDR address, size_t len,
697 gdb::byte_vector &tags, int type) override;
698
699 bool store_memtags (CORE_ADDR address, size_t len,
700 const gdb::byte_vector &tags, int type) override;
701
702 public: /* Remote specific methods. */
703
704 void remote_download_command_source (int num, ULONGEST addr,
705 struct command_line *cmds);
706
707 void remote_file_put (const char *local_file, const char *remote_file,
708 int from_tty);
709 void remote_file_get (const char *remote_file, const char *local_file,
710 int from_tty);
711 void remote_file_delete (const char *remote_file, int from_tty);
712
713 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
714 ULONGEST offset, int *remote_errno);
715 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
716 ULONGEST offset, int *remote_errno);
717 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
718 ULONGEST offset, int *remote_errno);
719
720 int remote_hostio_send_command (int command_bytes, int which_packet,
721 int *remote_errno, const char **attachment,
722 int *attachment_len);
723 int remote_hostio_set_filesystem (struct inferior *inf,
724 int *remote_errno);
725 /* We should get rid of this and use fileio_open directly. */
726 int remote_hostio_open (struct inferior *inf, const char *filename,
727 int flags, int mode, int warn_if_slow,
728 int *remote_errno);
729 int remote_hostio_close (int fd, int *remote_errno);
730
731 int remote_hostio_unlink (inferior *inf, const char *filename,
732 int *remote_errno);
733
734 struct remote_state *get_remote_state ();
735
736 long get_remote_packet_size (void);
737 long get_memory_packet_size (struct memory_packet_config *config);
738
739 long get_memory_write_packet_size ();
740 long get_memory_read_packet_size ();
741
742 char *append_pending_thread_resumptions (char *p, char *endp,
743 ptid_t ptid);
744 static void open_1 (const char *name, int from_tty, int extended_p);
745 void start_remote (int from_tty, int extended_p);
746 void remote_detach_1 (struct inferior *inf, int from_tty);
747
748 char *append_resumption (char *p, char *endp,
749 ptid_t ptid, int step, gdb_signal siggnal);
750 int remote_resume_with_vcont (ptid_t ptid, int step,
751 gdb_signal siggnal);
752
753 thread_info *add_current_inferior_and_thread (const char *wait_status);
754
755 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
756 target_wait_flags options);
757 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
758 target_wait_flags options);
759
760 ptid_t process_stop_reply (struct stop_reply *stop_reply,
761 target_waitstatus *status);
762
763 ptid_t select_thread_for_ambiguous_stop_reply
764 (const struct target_waitstatus *status);
765
766 void remote_notice_new_inferior (ptid_t currthread, int executing);
767
768 void process_initial_stop_replies (int from_tty);
769
770 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing);
771
772 void btrace_sync_conf (const btrace_config *conf);
773
774 void remote_btrace_maybe_reopen ();
775
776 void remove_new_fork_children (threads_listing_context *context);
777 void kill_new_fork_children (int pid);
778 void discard_pending_stop_replies (struct inferior *inf);
779 int stop_reply_queue_length ();
780
781 void check_pending_events_prevent_wildcard_vcont
782 (int *may_global_wildcard_vcont);
783
784 void discard_pending_stop_replies_in_queue ();
785 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
786 struct stop_reply *queued_stop_reply (ptid_t ptid);
787 int peek_stop_reply (ptid_t ptid);
788 void remote_parse_stop_reply (const char *buf, stop_reply *event);
789
790 void remote_stop_ns (ptid_t ptid);
791 void remote_interrupt_as ();
792 void remote_interrupt_ns ();
793
794 char *remote_get_noisy_reply ();
795 int remote_query_attached (int pid);
796 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
797 int try_open_exec);
798
799 ptid_t remote_current_thread (ptid_t oldpid);
800 ptid_t get_current_thread (const char *wait_status);
801
802 void set_thread (ptid_t ptid, int gen);
803 void set_general_thread (ptid_t ptid);
804 void set_continue_thread (ptid_t ptid);
805 void set_general_process ();
806
807 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
808
809 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
810 gdb_ext_thread_info *info);
811 int remote_get_threadinfo (threadref *threadid, int fieldset,
812 gdb_ext_thread_info *info);
813
814 int parse_threadlist_response (const char *pkt, int result_limit,
815 threadref *original_echo,
816 threadref *resultlist,
817 int *doneflag);
818 int remote_get_threadlist (int startflag, threadref *nextthread,
819 int result_limit, int *done, int *result_count,
820 threadref *threadlist);
821
822 int remote_threadlist_iterator (rmt_thread_action stepfunction,
823 void *context, int looplimit);
824
825 int remote_get_threads_with_ql (threads_listing_context *context);
826 int remote_get_threads_with_qxfer (threads_listing_context *context);
827 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
828
829 void extended_remote_restart ();
830
831 void get_offsets ();
832
833 void remote_check_symbols ();
834
835 void remote_supported_packet (const struct protocol_feature *feature,
836 enum packet_support support,
837 const char *argument);
838
839 void remote_query_supported ();
840
841 void remote_packet_size (const protocol_feature *feature,
842 packet_support support, const char *value);
843
844 void remote_serial_quit_handler ();
845
846 void remote_detach_pid (int pid);
847
848 void remote_vcont_probe ();
849
850 void remote_resume_with_hc (ptid_t ptid, int step,
851 gdb_signal siggnal);
852
853 void send_interrupt_sequence ();
854 void interrupt_query ();
855
856 void remote_notif_get_pending_events (notif_client *nc);
857
858 int fetch_register_using_p (struct regcache *regcache,
859 packet_reg *reg);
860 int send_g_packet ();
861 void process_g_packet (struct regcache *regcache);
862 void fetch_registers_using_g (struct regcache *regcache);
863 int store_register_using_P (const struct regcache *regcache,
864 packet_reg *reg);
865 void store_registers_using_G (const struct regcache *regcache);
866
867 void set_remote_traceframe ();
868
869 void check_binary_download (CORE_ADDR addr);
870
871 target_xfer_status remote_write_bytes_aux (const char *header,
872 CORE_ADDR memaddr,
873 const gdb_byte *myaddr,
874 ULONGEST len_units,
875 int unit_size,
876 ULONGEST *xfered_len_units,
877 char packet_format,
878 int use_length);
879
880 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
881 const gdb_byte *myaddr, ULONGEST len,
882 int unit_size, ULONGEST *xfered_len);
883
884 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
885 ULONGEST len_units,
886 int unit_size, ULONGEST *xfered_len_units);
887
888 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
889 ULONGEST memaddr,
890 ULONGEST len,
891 int unit_size,
892 ULONGEST *xfered_len);
893
894 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
895 gdb_byte *myaddr, ULONGEST len,
896 int unit_size,
897 ULONGEST *xfered_len);
898
899 packet_result remote_send_printf (const char *format, ...)
900 ATTRIBUTE_PRINTF (2, 3);
901
902 target_xfer_status remote_flash_write (ULONGEST address,
903 ULONGEST length, ULONGEST *xfered_len,
904 const gdb_byte *data);
905
906 int readchar (int timeout);
907
908 void remote_serial_write (const char *str, int len);
909
910 int putpkt (const char *buf);
911 int putpkt_binary (const char *buf, int cnt);
912
913 int putpkt (const gdb::char_vector &buf)
914 {
915 return putpkt (buf.data ());
916 }
917
918 void skip_frame ();
919 long read_frame (gdb::char_vector *buf_p);
920 void getpkt (gdb::char_vector *buf, int forever);
921 int getpkt_or_notif_sane_1 (gdb::char_vector *buf, int forever,
922 int expecting_notif, int *is_notif);
923 int getpkt_sane (gdb::char_vector *buf, int forever);
924 int getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
925 int *is_notif);
926 int remote_vkill (int pid);
927 void remote_kill_k ();
928
929 void extended_remote_disable_randomization (int val);
930 int extended_remote_run (const std::string &args);
931
932 void send_environment_packet (const char *action,
933 const char *packet,
934 const char *value);
935
936 void extended_remote_environment_support ();
937 void extended_remote_set_inferior_cwd ();
938
939 target_xfer_status remote_write_qxfer (const char *object_name,
940 const char *annex,
941 const gdb_byte *writebuf,
942 ULONGEST offset, LONGEST len,
943 ULONGEST *xfered_len,
944 struct packet_config *packet);
945
946 target_xfer_status remote_read_qxfer (const char *object_name,
947 const char *annex,
948 gdb_byte *readbuf, ULONGEST offset,
949 LONGEST len,
950 ULONGEST *xfered_len,
951 struct packet_config *packet);
952
953 void push_stop_reply (struct stop_reply *new_event);
954
955 bool vcont_r_supported ();
956
957 void packet_command (const char *args, int from_tty);
958
959 private: /* data fields */
960
961 /* The remote state. Don't reference this directly. Use the
962 get_remote_state method instead. */
963 remote_state m_remote_state;
964 };
965
966 static const target_info extended_remote_target_info = {
967 "extended-remote",
968 N_("Extended remote serial target in gdb-specific protocol"),
969 remote_doc
970 };
971
972 /* Set up the extended remote target by extending the standard remote
973 target and adding to it. */
974
975 class extended_remote_target final : public remote_target
976 {
977 public:
978 const target_info &info () const override
979 { return extended_remote_target_info; }
980
981 /* Open an extended-remote connection. */
982 static void open (const char *, int);
983
984 bool can_create_inferior () override { return true; }
985 void create_inferior (const char *, const std::string &,
986 char **, int) override;
987
988 void detach (inferior *, int) override;
989
990 bool can_attach () override { return true; }
991 void attach (const char *, int) override;
992
993 void post_attach (int) override;
994 bool supports_disable_randomization () override;
995 };
996
997 /* Per-program-space data key. */
998 static const struct program_space_key<char, gdb::xfree_deleter<char>>
999 remote_pspace_data;
1000
1001 /* The variable registered as the control variable used by the
1002 remote exec-file commands. While the remote exec-file setting is
1003 per-program-space, the set/show machinery uses this as the
1004 location of the remote exec-file value. */
1005 static char *remote_exec_file_var;
1006
1007 /* The size to align memory write packets, when practical. The protocol
1008 does not guarantee any alignment, and gdb will generate short
1009 writes and unaligned writes, but even as a best-effort attempt this
1010 can improve bulk transfers. For instance, if a write is misaligned
1011 relative to the target's data bus, the stub may need to make an extra
1012 round trip fetching data from the target. This doesn't make a
1013 huge difference, but it's easy to do, so we try to be helpful.
1014
1015 The alignment chosen is arbitrary; usually data bus width is
1016 important here, not the possibly larger cache line size. */
1017 enum { REMOTE_ALIGN_WRITES = 16 };
1018
1019 /* Prototypes for local functions. */
1020
1021 static int hexnumlen (ULONGEST num);
1022
1023 static int stubhex (int ch);
1024
1025 static int hexnumstr (char *, ULONGEST);
1026
1027 static int hexnumnstr (char *, ULONGEST, int);
1028
1029 static CORE_ADDR remote_address_masked (CORE_ADDR);
1030
1031 static void print_packet (const char *);
1032
1033 static int stub_unpack_int (const char *buff, int fieldlength);
1034
1035 struct packet_config;
1036
1037 static void show_packet_config_cmd (struct packet_config *config);
1038
1039 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1040 int from_tty,
1041 struct cmd_list_element *c,
1042 const char *value);
1043
1044 static ptid_t read_ptid (const char *buf, const char **obuf);
1045
1046 static void remote_async_inferior_event_handler (gdb_client_data);
1047
1048 static bool remote_read_description_p (struct target_ops *target);
1049
1050 static void remote_console_output (const char *msg);
1051
1052 static void remote_btrace_reset (remote_state *rs);
1053
1054 static void remote_unpush_and_throw (remote_target *target);
1055
1056 /* For "remote". */
1057
1058 static struct cmd_list_element *remote_cmdlist;
1059
1060 /* For "set remote" and "show remote". */
1061
1062 static struct cmd_list_element *remote_set_cmdlist;
1063 static struct cmd_list_element *remote_show_cmdlist;
1064
1065 /* Controls whether GDB is willing to use range stepping. */
1066
1067 static bool use_range_stepping = true;
1068
1069 /* From the remote target's point of view, each thread is in one of these three
1070 states. */
1071 enum class resume_state
1072 {
1073 /* Not resumed - we haven't been asked to resume this thread. */
1074 NOT_RESUMED,
1075
1076 /* We have been asked to resume this thread, but haven't sent a vCont action
1077 for it yet. We'll need to consider it next time commit_resume is
1078 called. */
1079 RESUMED_PENDING_VCONT,
1080
1081 /* We have been asked to resume this thread, and we have sent a vCont action
1082 for it. */
1083 RESUMED,
1084 };
1085
1086 /* Information about a thread's pending vCont-resume. Used when a thread is in
1087 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1088 stores this information which is then picked up by
1089 remote_target::commit_resume to know which is the proper action for this
1090 thread to include in the vCont packet. */
1091 struct resumed_pending_vcont_info
1092 {
1093 /* True if the last resume call for this thread was a step request, false
1094 if a continue request. */
1095 bool step;
1096
1097 /* The signal specified in the last resume call for this thread. */
1098 gdb_signal sig;
1099 };
1100
1101 /* Private data that we'll store in (struct thread_info)->priv. */
1102 struct remote_thread_info : public private_thread_info
1103 {
1104 std::string extra;
1105 std::string name;
1106 int core = -1;
1107
1108 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1109 sequence of bytes. */
1110 gdb::byte_vector thread_handle;
1111
1112 /* Whether the target stopped for a breakpoint/watchpoint. */
1113 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1114
1115 /* This is set to the data address of the access causing the target
1116 to stop for a watchpoint. */
1117 CORE_ADDR watch_data_address = 0;
1118
1119 /* Get the thread's resume state. */
1120 enum resume_state get_resume_state () const
1121 {
1122 return m_resume_state;
1123 }
1124
1125 /* Put the thread in the NOT_RESUMED state. */
1126 void set_not_resumed ()
1127 {
1128 m_resume_state = resume_state::NOT_RESUMED;
1129 }
1130
1131 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1132 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1133 {
1134 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1135 m_resumed_pending_vcont_info.step = step;
1136 m_resumed_pending_vcont_info.sig = sig;
1137 }
1138
1139 /* Get the information this thread's pending vCont-resumption.
1140
1141 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1142 state. */
1143 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1144 {
1145 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1146
1147 return m_resumed_pending_vcont_info;
1148 }
1149
1150 /* Put the thread in the VCONT_RESUMED state. */
1151 void set_resumed ()
1152 {
1153 m_resume_state = resume_state::RESUMED;
1154 }
1155
1156 private:
1157 /* Resume state for this thread. This is used to implement vCont action
1158 coalescing (only when the target operates in non-stop mode).
1159
1160 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1161 which notes that this thread must be considered in the next commit_resume
1162 call.
1163
1164 remote_target::commit_resume sends a vCont packet with actions for the
1165 threads in the RESUMED_PENDING_VCONT state and moves them to the
1166 VCONT_RESUMED state.
1167
1168 When reporting a stop to the core for a thread, that thread is moved back
1169 to the NOT_RESUMED state. */
1170 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1171
1172 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1173 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1174 };
1175
1176 remote_state::remote_state ()
1177 : buf (400)
1178 {
1179 }
1180
1181 remote_state::~remote_state ()
1182 {
1183 xfree (this->last_pass_packet);
1184 xfree (this->last_program_signals_packet);
1185 xfree (this->finished_object);
1186 xfree (this->finished_annex);
1187 }
1188
1189 /* Utility: generate error from an incoming stub packet. */
1190 static void
1191 trace_error (char *buf)
1192 {
1193 if (*buf++ != 'E')
1194 return; /* not an error msg */
1195 switch (*buf)
1196 {
1197 case '1': /* malformed packet error */
1198 if (*++buf == '0') /* general case: */
1199 error (_("remote.c: error in outgoing packet."));
1200 else
1201 error (_("remote.c: error in outgoing packet at field #%ld."),
1202 strtol (buf, NULL, 16));
1203 default:
1204 error (_("Target returns error code '%s'."), buf);
1205 }
1206 }
1207
1208 /* Utility: wait for reply from stub, while accepting "O" packets. */
1209
1210 char *
1211 remote_target::remote_get_noisy_reply ()
1212 {
1213 struct remote_state *rs = get_remote_state ();
1214
1215 do /* Loop on reply from remote stub. */
1216 {
1217 char *buf;
1218
1219 QUIT; /* Allow user to bail out with ^C. */
1220 getpkt (&rs->buf, 0);
1221 buf = rs->buf.data ();
1222 if (buf[0] == 'E')
1223 trace_error (buf);
1224 else if (startswith (buf, "qRelocInsn:"))
1225 {
1226 ULONGEST ul;
1227 CORE_ADDR from, to, org_to;
1228 const char *p, *pp;
1229 int adjusted_size = 0;
1230 int relocated = 0;
1231
1232 p = buf + strlen ("qRelocInsn:");
1233 pp = unpack_varlen_hex (p, &ul);
1234 if (*pp != ';')
1235 error (_("invalid qRelocInsn packet: %s"), buf);
1236 from = ul;
1237
1238 p = pp + 1;
1239 unpack_varlen_hex (p, &ul);
1240 to = ul;
1241
1242 org_to = to;
1243
1244 try
1245 {
1246 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
1247 relocated = 1;
1248 }
1249 catch (const gdb_exception &ex)
1250 {
1251 if (ex.error == MEMORY_ERROR)
1252 {
1253 /* Propagate memory errors silently back to the
1254 target. The stub may have limited the range of
1255 addresses we can write to, for example. */
1256 }
1257 else
1258 {
1259 /* Something unexpectedly bad happened. Be verbose
1260 so we can tell what, and propagate the error back
1261 to the stub, so it doesn't get stuck waiting for
1262 a response. */
1263 exception_fprintf (gdb_stderr, ex,
1264 _("warning: relocating instruction: "));
1265 }
1266 putpkt ("E01");
1267 }
1268
1269 if (relocated)
1270 {
1271 adjusted_size = to - org_to;
1272
1273 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1274 putpkt (buf);
1275 }
1276 }
1277 else if (buf[0] == 'O' && buf[1] != 'K')
1278 remote_console_output (buf + 1); /* 'O' message from stub */
1279 else
1280 return buf; /* Here's the actual reply. */
1281 }
1282 while (1);
1283 }
1284
1285 struct remote_arch_state *
1286 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1287 {
1288 remote_arch_state *rsa;
1289
1290 auto it = this->m_arch_states.find (gdbarch);
1291 if (it == this->m_arch_states.end ())
1292 {
1293 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1294 std::forward_as_tuple (gdbarch),
1295 std::forward_as_tuple (gdbarch));
1296 rsa = &p.first->second;
1297
1298 /* Make sure that the packet buffer is plenty big enough for
1299 this architecture. */
1300 if (this->buf.size () < rsa->remote_packet_size)
1301 this->buf.resize (2 * rsa->remote_packet_size);
1302 }
1303 else
1304 rsa = &it->second;
1305
1306 return rsa;
1307 }
1308
1309 /* Fetch the global remote target state. */
1310
1311 remote_state *
1312 remote_target::get_remote_state ()
1313 {
1314 /* Make sure that the remote architecture state has been
1315 initialized, because doing so might reallocate rs->buf. Any
1316 function which calls getpkt also needs to be mindful of changes
1317 to rs->buf, but this call limits the number of places which run
1318 into trouble. */
1319 m_remote_state.get_remote_arch_state (target_gdbarch ());
1320
1321 return &m_remote_state;
1322 }
1323
1324 /* Fetch the remote exec-file from the current program space. */
1325
1326 static const char *
1327 get_remote_exec_file (void)
1328 {
1329 char *remote_exec_file;
1330
1331 remote_exec_file = remote_pspace_data.get (current_program_space);
1332 if (remote_exec_file == NULL)
1333 return "";
1334
1335 return remote_exec_file;
1336 }
1337
1338 /* Set the remote exec file for PSPACE. */
1339
1340 static void
1341 set_pspace_remote_exec_file (struct program_space *pspace,
1342 const char *remote_exec_file)
1343 {
1344 char *old_file = remote_pspace_data.get (pspace);
1345
1346 xfree (old_file);
1347 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1348 }
1349
1350 /* The "set/show remote exec-file" set command hook. */
1351
1352 static void
1353 set_remote_exec_file (const char *ignored, int from_tty,
1354 struct cmd_list_element *c)
1355 {
1356 gdb_assert (remote_exec_file_var != NULL);
1357 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
1358 }
1359
1360 /* The "set/show remote exec-file" show command hook. */
1361
1362 static void
1363 show_remote_exec_file (struct ui_file *file, int from_tty,
1364 struct cmd_list_element *cmd, const char *value)
1365 {
1366 fprintf_filtered (file, "%s\n", get_remote_exec_file ());
1367 }
1368
1369 static int
1370 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1371 {
1372 int regnum, num_remote_regs, offset;
1373 struct packet_reg **remote_regs;
1374
1375 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1376 {
1377 struct packet_reg *r = &regs[regnum];
1378
1379 if (register_size (gdbarch, regnum) == 0)
1380 /* Do not try to fetch zero-sized (placeholder) registers. */
1381 r->pnum = -1;
1382 else
1383 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1384
1385 r->regnum = regnum;
1386 }
1387
1388 /* Define the g/G packet format as the contents of each register
1389 with a remote protocol number, in order of ascending protocol
1390 number. */
1391
1392 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1393 for (num_remote_regs = 0, regnum = 0;
1394 regnum < gdbarch_num_regs (gdbarch);
1395 regnum++)
1396 if (regs[regnum].pnum != -1)
1397 remote_regs[num_remote_regs++] = &regs[regnum];
1398
1399 std::sort (remote_regs, remote_regs + num_remote_regs,
1400 [] (const packet_reg *a, const packet_reg *b)
1401 { return a->pnum < b->pnum; });
1402
1403 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1404 {
1405 remote_regs[regnum]->in_g_packet = 1;
1406 remote_regs[regnum]->offset = offset;
1407 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1408 }
1409
1410 return offset;
1411 }
1412
1413 /* Given the architecture described by GDBARCH, return the remote
1414 protocol register's number and the register's offset in the g/G
1415 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1416 If the target does not have a mapping for REGNUM, return false,
1417 otherwise, return true. */
1418
1419 int
1420 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1421 int *pnum, int *poffset)
1422 {
1423 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1424
1425 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1426
1427 map_regcache_remote_table (gdbarch, regs.data ());
1428
1429 *pnum = regs[regnum].pnum;
1430 *poffset = regs[regnum].offset;
1431
1432 return *pnum != -1;
1433 }
1434
1435 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1436 {
1437 /* Use the architecture to build a regnum<->pnum table, which will be
1438 1:1 unless a feature set specifies otherwise. */
1439 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1440
1441 /* Record the maximum possible size of the g packet - it may turn out
1442 to be smaller. */
1443 this->sizeof_g_packet
1444 = map_regcache_remote_table (gdbarch, this->regs.get ());
1445
1446 /* Default maximum number of characters in a packet body. Many
1447 remote stubs have a hardwired buffer size of 400 bytes
1448 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1449 as the maximum packet-size to ensure that the packet and an extra
1450 NUL character can always fit in the buffer. This stops GDB
1451 trashing stubs that try to squeeze an extra NUL into what is
1452 already a full buffer (As of 1999-12-04 that was most stubs). */
1453 this->remote_packet_size = 400 - 1;
1454
1455 /* This one is filled in when a ``g'' packet is received. */
1456 this->actual_register_packet_size = 0;
1457
1458 /* Should rsa->sizeof_g_packet needs more space than the
1459 default, adjust the size accordingly. Remember that each byte is
1460 encoded as two characters. 32 is the overhead for the packet
1461 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1462 (``$NN:G...#NN'') is a better guess, the below has been padded a
1463 little. */
1464 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1465 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1466 }
1467
1468 /* Get a pointer to the current remote target. If not connected to a
1469 remote target, return NULL. */
1470
1471 static remote_target *
1472 get_current_remote_target ()
1473 {
1474 target_ops *proc_target = current_inferior ()->process_target ();
1475 return dynamic_cast<remote_target *> (proc_target);
1476 }
1477
1478 /* Return the current allowed size of a remote packet. This is
1479 inferred from the current architecture, and should be used to
1480 limit the length of outgoing packets. */
1481 long
1482 remote_target::get_remote_packet_size ()
1483 {
1484 struct remote_state *rs = get_remote_state ();
1485 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1486
1487 if (rs->explicit_packet_size)
1488 return rs->explicit_packet_size;
1489
1490 return rsa->remote_packet_size;
1491 }
1492
1493 static struct packet_reg *
1494 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1495 long regnum)
1496 {
1497 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1498 return NULL;
1499 else
1500 {
1501 struct packet_reg *r = &rsa->regs[regnum];
1502
1503 gdb_assert (r->regnum == regnum);
1504 return r;
1505 }
1506 }
1507
1508 static struct packet_reg *
1509 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1510 LONGEST pnum)
1511 {
1512 int i;
1513
1514 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1515 {
1516 struct packet_reg *r = &rsa->regs[i];
1517
1518 if (r->pnum == pnum)
1519 return r;
1520 }
1521 return NULL;
1522 }
1523
1524 /* Allow the user to specify what sequence to send to the remote
1525 when he requests a program interruption: Although ^C is usually
1526 what remote systems expect (this is the default, here), it is
1527 sometimes preferable to send a break. On other systems such
1528 as the Linux kernel, a break followed by g, which is Magic SysRq g
1529 is required in order to interrupt the execution. */
1530 const char interrupt_sequence_control_c[] = "Ctrl-C";
1531 const char interrupt_sequence_break[] = "BREAK";
1532 const char interrupt_sequence_break_g[] = "BREAK-g";
1533 static const char *const interrupt_sequence_modes[] =
1534 {
1535 interrupt_sequence_control_c,
1536 interrupt_sequence_break,
1537 interrupt_sequence_break_g,
1538 NULL
1539 };
1540 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1541
1542 static void
1543 show_interrupt_sequence (struct ui_file *file, int from_tty,
1544 struct cmd_list_element *c,
1545 const char *value)
1546 {
1547 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1548 fprintf_filtered (file,
1549 _("Send the ASCII ETX character (Ctrl-c) "
1550 "to the remote target to interrupt the "
1551 "execution of the program.\n"));
1552 else if (interrupt_sequence_mode == interrupt_sequence_break)
1553 fprintf_filtered (file,
1554 _("send a break signal to the remote target "
1555 "to interrupt the execution of the program.\n"));
1556 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1557 fprintf_filtered (file,
1558 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1559 "the remote target to interrupt the execution "
1560 "of Linux kernel.\n"));
1561 else
1562 internal_error (__FILE__, __LINE__,
1563 _("Invalid value for interrupt_sequence_mode: %s."),
1564 interrupt_sequence_mode);
1565 }
1566
1567 /* This boolean variable specifies whether interrupt_sequence is sent
1568 to the remote target when gdb connects to it.
1569 This is mostly needed when you debug the Linux kernel: The Linux kernel
1570 expects BREAK g which is Magic SysRq g for connecting gdb. */
1571 static bool interrupt_on_connect = false;
1572
1573 /* This variable is used to implement the "set/show remotebreak" commands.
1574 Since these commands are now deprecated in favor of "set/show remote
1575 interrupt-sequence", it no longer has any effect on the code. */
1576 static bool remote_break;
1577
1578 static void
1579 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1580 {
1581 if (remote_break)
1582 interrupt_sequence_mode = interrupt_sequence_break;
1583 else
1584 interrupt_sequence_mode = interrupt_sequence_control_c;
1585 }
1586
1587 static void
1588 show_remotebreak (struct ui_file *file, int from_tty,
1589 struct cmd_list_element *c,
1590 const char *value)
1591 {
1592 }
1593
1594 /* This variable sets the number of bits in an address that are to be
1595 sent in a memory ("M" or "m") packet. Normally, after stripping
1596 leading zeros, the entire address would be sent. This variable
1597 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1598 initial implementation of remote.c restricted the address sent in
1599 memory packets to ``host::sizeof long'' bytes - (typically 32
1600 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1601 address was never sent. Since fixing this bug may cause a break in
1602 some remote targets this variable is principally provided to
1603 facilitate backward compatibility. */
1604
1605 static unsigned int remote_address_size;
1606
1607 \f
1608 /* User configurable variables for the number of characters in a
1609 memory read/write packet. MIN (rsa->remote_packet_size,
1610 rsa->sizeof_g_packet) is the default. Some targets need smaller
1611 values (fifo overruns, et.al.) and some users need larger values
1612 (speed up transfers). The variables ``preferred_*'' (the user
1613 request), ``current_*'' (what was actually set) and ``forced_*''
1614 (Positive - a soft limit, negative - a hard limit). */
1615
1616 struct memory_packet_config
1617 {
1618 const char *name;
1619 long size;
1620 int fixed_p;
1621 };
1622
1623 /* The default max memory-write-packet-size, when the setting is
1624 "fixed". The 16k is historical. (It came from older GDB's using
1625 alloca for buffers and the knowledge (folklore?) that some hosts
1626 don't cope very well with large alloca calls.) */
1627 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1628
1629 /* The minimum remote packet size for memory transfers. Ensures we
1630 can write at least one byte. */
1631 #define MIN_MEMORY_PACKET_SIZE 20
1632
1633 /* Get the memory packet size, assuming it is fixed. */
1634
1635 static long
1636 get_fixed_memory_packet_size (struct memory_packet_config *config)
1637 {
1638 gdb_assert (config->fixed_p);
1639
1640 if (config->size <= 0)
1641 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1642 else
1643 return config->size;
1644 }
1645
1646 /* Compute the current size of a read/write packet. Since this makes
1647 use of ``actual_register_packet_size'' the computation is dynamic. */
1648
1649 long
1650 remote_target::get_memory_packet_size (struct memory_packet_config *config)
1651 {
1652 struct remote_state *rs = get_remote_state ();
1653 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1654
1655 long what_they_get;
1656 if (config->fixed_p)
1657 what_they_get = get_fixed_memory_packet_size (config);
1658 else
1659 {
1660 what_they_get = get_remote_packet_size ();
1661 /* Limit the packet to the size specified by the user. */
1662 if (config->size > 0
1663 && what_they_get > config->size)
1664 what_they_get = config->size;
1665
1666 /* Limit it to the size of the targets ``g'' response unless we have
1667 permission from the stub to use a larger packet size. */
1668 if (rs->explicit_packet_size == 0
1669 && rsa->actual_register_packet_size > 0
1670 && what_they_get > rsa->actual_register_packet_size)
1671 what_they_get = rsa->actual_register_packet_size;
1672 }
1673 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1674 what_they_get = MIN_MEMORY_PACKET_SIZE;
1675
1676 /* Make sure there is room in the global buffer for this packet
1677 (including its trailing NUL byte). */
1678 if (rs->buf.size () < what_they_get + 1)
1679 rs->buf.resize (2 * what_they_get);
1680
1681 return what_they_get;
1682 }
1683
1684 /* Update the size of a read/write packet. If they user wants
1685 something really big then do a sanity check. */
1686
1687 static void
1688 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1689 {
1690 int fixed_p = config->fixed_p;
1691 long size = config->size;
1692
1693 if (args == NULL)
1694 error (_("Argument required (integer, `fixed' or `limited')."));
1695 else if (strcmp (args, "hard") == 0
1696 || strcmp (args, "fixed") == 0)
1697 fixed_p = 1;
1698 else if (strcmp (args, "soft") == 0
1699 || strcmp (args, "limit") == 0)
1700 fixed_p = 0;
1701 else
1702 {
1703 char *end;
1704
1705 size = strtoul (args, &end, 0);
1706 if (args == end)
1707 error (_("Invalid %s (bad syntax)."), config->name);
1708
1709 /* Instead of explicitly capping the size of a packet to or
1710 disallowing it, the user is allowed to set the size to
1711 something arbitrarily large. */
1712 }
1713
1714 /* Extra checks? */
1715 if (fixed_p && !config->fixed_p)
1716 {
1717 /* So that the query shows the correct value. */
1718 long query_size = (size <= 0
1719 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1720 : size);
1721
1722 if (! query (_("The target may not be able to correctly handle a %s\n"
1723 "of %ld bytes. Change the packet size? "),
1724 config->name, query_size))
1725 error (_("Packet size not changed."));
1726 }
1727 /* Update the config. */
1728 config->fixed_p = fixed_p;
1729 config->size = size;
1730 }
1731
1732 static void
1733 show_memory_packet_size (struct memory_packet_config *config)
1734 {
1735 if (config->size == 0)
1736 printf_filtered (_("The %s is 0 (default). "), config->name);
1737 else
1738 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1739 if (config->fixed_p)
1740 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1741 get_fixed_memory_packet_size (config));
1742 else
1743 {
1744 remote_target *remote = get_current_remote_target ();
1745
1746 if (remote != NULL)
1747 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1748 remote->get_memory_packet_size (config));
1749 else
1750 puts_filtered ("The actual limit will be further reduced "
1751 "dependent on the target.\n");
1752 }
1753 }
1754
1755 /* FIXME: needs to be per-remote-target. */
1756 static struct memory_packet_config memory_write_packet_config =
1757 {
1758 "memory-write-packet-size",
1759 };
1760
1761 static void
1762 set_memory_write_packet_size (const char *args, int from_tty)
1763 {
1764 set_memory_packet_size (args, &memory_write_packet_config);
1765 }
1766
1767 static void
1768 show_memory_write_packet_size (const char *args, int from_tty)
1769 {
1770 show_memory_packet_size (&memory_write_packet_config);
1771 }
1772
1773 /* Show the number of hardware watchpoints that can be used. */
1774
1775 static void
1776 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
1777 struct cmd_list_element *c,
1778 const char *value)
1779 {
1780 fprintf_filtered (file, _("The maximum number of target hardware "
1781 "watchpoints is %s.\n"), value);
1782 }
1783
1784 /* Show the length limit (in bytes) for hardware watchpoints. */
1785
1786 static void
1787 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
1788 struct cmd_list_element *c,
1789 const char *value)
1790 {
1791 fprintf_filtered (file, _("The maximum length (in bytes) of a target "
1792 "hardware watchpoint is %s.\n"), value);
1793 }
1794
1795 /* Show the number of hardware breakpoints that can be used. */
1796
1797 static void
1798 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
1799 struct cmd_list_element *c,
1800 const char *value)
1801 {
1802 fprintf_filtered (file, _("The maximum number of target hardware "
1803 "breakpoints is %s.\n"), value);
1804 }
1805
1806 /* Controls the maximum number of characters to display in the debug output
1807 for each remote packet. The remaining characters are omitted. */
1808
1809 static int remote_packet_max_chars = 512;
1810
1811 /* Show the maximum number of characters to display for each remote packet
1812 when remote debugging is enabled. */
1813
1814 static void
1815 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
1816 struct cmd_list_element *c,
1817 const char *value)
1818 {
1819 fprintf_filtered (file, _("Number of remote packet characters to "
1820 "display is %s.\n"), value);
1821 }
1822
1823 long
1824 remote_target::get_memory_write_packet_size ()
1825 {
1826 return get_memory_packet_size (&memory_write_packet_config);
1827 }
1828
1829 /* FIXME: needs to be per-remote-target. */
1830 static struct memory_packet_config memory_read_packet_config =
1831 {
1832 "memory-read-packet-size",
1833 };
1834
1835 static void
1836 set_memory_read_packet_size (const char *args, int from_tty)
1837 {
1838 set_memory_packet_size (args, &memory_read_packet_config);
1839 }
1840
1841 static void
1842 show_memory_read_packet_size (const char *args, int from_tty)
1843 {
1844 show_memory_packet_size (&memory_read_packet_config);
1845 }
1846
1847 long
1848 remote_target::get_memory_read_packet_size ()
1849 {
1850 long size = get_memory_packet_size (&memory_read_packet_config);
1851
1852 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1853 extra buffer size argument before the memory read size can be
1854 increased beyond this. */
1855 if (size > get_remote_packet_size ())
1856 size = get_remote_packet_size ();
1857 return size;
1858 }
1859
1860 \f
1861
1862 struct packet_config
1863 {
1864 const char *name;
1865 const char *title;
1866
1867 /* If auto, GDB auto-detects support for this packet or feature,
1868 either through qSupported, or by trying the packet and looking
1869 at the response. If true, GDB assumes the target supports this
1870 packet. If false, the packet is disabled. Configs that don't
1871 have an associated command always have this set to auto. */
1872 enum auto_boolean detect;
1873
1874 /* Does the target support this packet? */
1875 enum packet_support support;
1876 };
1877
1878 static enum packet_support packet_config_support (struct packet_config *config);
1879 static enum packet_support packet_support (int packet);
1880
1881 static void
1882 show_packet_config_cmd (struct packet_config *config)
1883 {
1884 const char *support = "internal-error";
1885
1886 switch (packet_config_support (config))
1887 {
1888 case PACKET_ENABLE:
1889 support = "enabled";
1890 break;
1891 case PACKET_DISABLE:
1892 support = "disabled";
1893 break;
1894 case PACKET_SUPPORT_UNKNOWN:
1895 support = "unknown";
1896 break;
1897 }
1898 switch (config->detect)
1899 {
1900 case AUTO_BOOLEAN_AUTO:
1901 printf_filtered (_("Support for the `%s' packet "
1902 "is auto-detected, currently %s.\n"),
1903 config->name, support);
1904 break;
1905 case AUTO_BOOLEAN_TRUE:
1906 case AUTO_BOOLEAN_FALSE:
1907 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1908 config->name, support);
1909 break;
1910 }
1911 }
1912
1913 static void
1914 add_packet_config_cmd (struct packet_config *config, const char *name,
1915 const char *title, int legacy)
1916 {
1917 char *set_doc;
1918 char *show_doc;
1919 char *cmd_name;
1920
1921 config->name = name;
1922 config->title = title;
1923 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
1924 name, title);
1925 show_doc = xstrprintf ("Show current use of remote "
1926 "protocol `%s' (%s) packet.",
1927 name, title);
1928 /* set/show TITLE-packet {auto,on,off} */
1929 cmd_name = xstrprintf ("%s-packet", title);
1930 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1931 &config->detect, set_doc,
1932 show_doc, NULL, /* help_doc */
1933 NULL,
1934 show_remote_protocol_packet_cmd,
1935 &remote_set_cmdlist, &remote_show_cmdlist);
1936 /* The command code copies the documentation strings. */
1937 xfree (set_doc);
1938 xfree (show_doc);
1939 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1940 if (legacy)
1941 {
1942 char *legacy_name;
1943
1944 legacy_name = xstrprintf ("%s-packet", name);
1945 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1946 &remote_set_cmdlist);
1947 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1948 &remote_show_cmdlist);
1949 }
1950 }
1951
1952 static enum packet_result
1953 packet_check_result (const char *buf)
1954 {
1955 if (buf[0] != '\0')
1956 {
1957 /* The stub recognized the packet request. Check that the
1958 operation succeeded. */
1959 if (buf[0] == 'E'
1960 && isxdigit (buf[1]) && isxdigit (buf[2])
1961 && buf[3] == '\0')
1962 /* "Enn" - definitely an error. */
1963 return PACKET_ERROR;
1964
1965 /* Always treat "E." as an error. This will be used for
1966 more verbose error messages, such as E.memtypes. */
1967 if (buf[0] == 'E' && buf[1] == '.')
1968 return PACKET_ERROR;
1969
1970 /* The packet may or may not be OK. Just assume it is. */
1971 return PACKET_OK;
1972 }
1973 else
1974 /* The stub does not support the packet. */
1975 return PACKET_UNKNOWN;
1976 }
1977
1978 static enum packet_result
1979 packet_check_result (const gdb::char_vector &buf)
1980 {
1981 return packet_check_result (buf.data ());
1982 }
1983
1984 static enum packet_result
1985 packet_ok (const char *buf, struct packet_config *config)
1986 {
1987 enum packet_result result;
1988
1989 if (config->detect != AUTO_BOOLEAN_TRUE
1990 && config->support == PACKET_DISABLE)
1991 internal_error (__FILE__, __LINE__,
1992 _("packet_ok: attempt to use a disabled packet"));
1993
1994 result = packet_check_result (buf);
1995 switch (result)
1996 {
1997 case PACKET_OK:
1998 case PACKET_ERROR:
1999 /* The stub recognized the packet request. */
2000 if (config->support == PACKET_SUPPORT_UNKNOWN)
2001 {
2002 remote_debug_printf ("Packet %s (%s) is supported",
2003 config->name, config->title);
2004 config->support = PACKET_ENABLE;
2005 }
2006 break;
2007 case PACKET_UNKNOWN:
2008 /* The stub does not support the packet. */
2009 if (config->detect == AUTO_BOOLEAN_AUTO
2010 && config->support == PACKET_ENABLE)
2011 {
2012 /* If the stub previously indicated that the packet was
2013 supported then there is a protocol error. */
2014 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2015 config->name, config->title);
2016 }
2017 else if (config->detect == AUTO_BOOLEAN_TRUE)
2018 {
2019 /* The user set it wrong. */
2020 error (_("Enabled packet %s (%s) not recognized by stub"),
2021 config->name, config->title);
2022 }
2023
2024 remote_debug_printf ("Packet %s (%s) is NOT supported",
2025 config->name, config->title);
2026 config->support = PACKET_DISABLE;
2027 break;
2028 }
2029
2030 return result;
2031 }
2032
2033 static enum packet_result
2034 packet_ok (const gdb::char_vector &buf, struct packet_config *config)
2035 {
2036 return packet_ok (buf.data (), config);
2037 }
2038
2039 enum {
2040 PACKET_vCont = 0,
2041 PACKET_X,
2042 PACKET_qSymbol,
2043 PACKET_P,
2044 PACKET_p,
2045 PACKET_Z0,
2046 PACKET_Z1,
2047 PACKET_Z2,
2048 PACKET_Z3,
2049 PACKET_Z4,
2050 PACKET_vFile_setfs,
2051 PACKET_vFile_open,
2052 PACKET_vFile_pread,
2053 PACKET_vFile_pwrite,
2054 PACKET_vFile_close,
2055 PACKET_vFile_unlink,
2056 PACKET_vFile_readlink,
2057 PACKET_vFile_fstat,
2058 PACKET_qXfer_auxv,
2059 PACKET_qXfer_features,
2060 PACKET_qXfer_exec_file,
2061 PACKET_qXfer_libraries,
2062 PACKET_qXfer_libraries_svr4,
2063 PACKET_qXfer_memory_map,
2064 PACKET_qXfer_osdata,
2065 PACKET_qXfer_threads,
2066 PACKET_qXfer_statictrace_read,
2067 PACKET_qXfer_traceframe_info,
2068 PACKET_qXfer_uib,
2069 PACKET_qGetTIBAddr,
2070 PACKET_qGetTLSAddr,
2071 PACKET_qSupported,
2072 PACKET_qTStatus,
2073 PACKET_QPassSignals,
2074 PACKET_QCatchSyscalls,
2075 PACKET_QProgramSignals,
2076 PACKET_QSetWorkingDir,
2077 PACKET_QStartupWithShell,
2078 PACKET_QEnvironmentHexEncoded,
2079 PACKET_QEnvironmentReset,
2080 PACKET_QEnvironmentUnset,
2081 PACKET_qCRC,
2082 PACKET_qSearch_memory,
2083 PACKET_vAttach,
2084 PACKET_vRun,
2085 PACKET_QStartNoAckMode,
2086 PACKET_vKill,
2087 PACKET_qXfer_siginfo_read,
2088 PACKET_qXfer_siginfo_write,
2089 PACKET_qAttached,
2090
2091 /* Support for conditional tracepoints. */
2092 PACKET_ConditionalTracepoints,
2093
2094 /* Support for target-side breakpoint conditions. */
2095 PACKET_ConditionalBreakpoints,
2096
2097 /* Support for target-side breakpoint commands. */
2098 PACKET_BreakpointCommands,
2099
2100 /* Support for fast tracepoints. */
2101 PACKET_FastTracepoints,
2102
2103 /* Support for static tracepoints. */
2104 PACKET_StaticTracepoints,
2105
2106 /* Support for installing tracepoints while a trace experiment is
2107 running. */
2108 PACKET_InstallInTrace,
2109
2110 PACKET_bc,
2111 PACKET_bs,
2112 PACKET_TracepointSource,
2113 PACKET_QAllow,
2114 PACKET_qXfer_fdpic,
2115 PACKET_QDisableRandomization,
2116 PACKET_QAgent,
2117 PACKET_QTBuffer_size,
2118 PACKET_Qbtrace_off,
2119 PACKET_Qbtrace_bts,
2120 PACKET_Qbtrace_pt,
2121 PACKET_qXfer_btrace,
2122
2123 /* Support for the QNonStop packet. */
2124 PACKET_QNonStop,
2125
2126 /* Support for the QThreadEvents packet. */
2127 PACKET_QThreadEvents,
2128
2129 /* Support for multi-process extensions. */
2130 PACKET_multiprocess_feature,
2131
2132 /* Support for enabling and disabling tracepoints while a trace
2133 experiment is running. */
2134 PACKET_EnableDisableTracepoints_feature,
2135
2136 /* Support for collecting strings using the tracenz bytecode. */
2137 PACKET_tracenz_feature,
2138
2139 /* Support for continuing to run a trace experiment while GDB is
2140 disconnected. */
2141 PACKET_DisconnectedTracing_feature,
2142
2143 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2144 PACKET_augmented_libraries_svr4_read_feature,
2145
2146 /* Support for the qXfer:btrace-conf:read packet. */
2147 PACKET_qXfer_btrace_conf,
2148
2149 /* Support for the Qbtrace-conf:bts:size packet. */
2150 PACKET_Qbtrace_conf_bts_size,
2151
2152 /* Support for swbreak+ feature. */
2153 PACKET_swbreak_feature,
2154
2155 /* Support for hwbreak+ feature. */
2156 PACKET_hwbreak_feature,
2157
2158 /* Support for fork events. */
2159 PACKET_fork_event_feature,
2160
2161 /* Support for vfork events. */
2162 PACKET_vfork_event_feature,
2163
2164 /* Support for the Qbtrace-conf:pt:size packet. */
2165 PACKET_Qbtrace_conf_pt_size,
2166
2167 /* Support for exec events. */
2168 PACKET_exec_event_feature,
2169
2170 /* Support for query supported vCont actions. */
2171 PACKET_vContSupported,
2172
2173 /* Support remote CTRL-C. */
2174 PACKET_vCtrlC,
2175
2176 /* Support TARGET_WAITKIND_NO_RESUMED. */
2177 PACKET_no_resumed,
2178
2179 /* Support for memory tagging, allocation tag fetch/store
2180 packets and the tag violation stop replies. */
2181 PACKET_memory_tagging_feature,
2182
2183 PACKET_MAX
2184 };
2185
2186 /* FIXME: needs to be per-remote-target. Ignoring this for now,
2187 assuming all remote targets are the same server (thus all support
2188 the same packets). */
2189 static struct packet_config remote_protocol_packets[PACKET_MAX];
2190
2191 /* Returns the packet's corresponding "set remote foo-packet" command
2192 state. See struct packet_config for more details. */
2193
2194 static enum auto_boolean
2195 packet_set_cmd_state (int packet)
2196 {
2197 return remote_protocol_packets[packet].detect;
2198 }
2199
2200 /* Returns whether a given packet or feature is supported. This takes
2201 into account the state of the corresponding "set remote foo-packet"
2202 command, which may be used to bypass auto-detection. */
2203
2204 static enum packet_support
2205 packet_config_support (struct packet_config *config)
2206 {
2207 switch (config->detect)
2208 {
2209 case AUTO_BOOLEAN_TRUE:
2210 return PACKET_ENABLE;
2211 case AUTO_BOOLEAN_FALSE:
2212 return PACKET_DISABLE;
2213 case AUTO_BOOLEAN_AUTO:
2214 return config->support;
2215 default:
2216 gdb_assert_not_reached (_("bad switch"));
2217 }
2218 }
2219
2220 /* Same as packet_config_support, but takes the packet's enum value as
2221 argument. */
2222
2223 static enum packet_support
2224 packet_support (int packet)
2225 {
2226 struct packet_config *config = &remote_protocol_packets[packet];
2227
2228 return packet_config_support (config);
2229 }
2230
2231 static void
2232 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2233 struct cmd_list_element *c,
2234 const char *value)
2235 {
2236 struct packet_config *packet;
2237
2238 for (packet = remote_protocol_packets;
2239 packet < &remote_protocol_packets[PACKET_MAX];
2240 packet++)
2241 {
2242 if (&packet->detect == c->var)
2243 {
2244 show_packet_config_cmd (packet);
2245 return;
2246 }
2247 }
2248 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
2249 c->name);
2250 }
2251
2252 /* Should we try one of the 'Z' requests? */
2253
2254 enum Z_packet_type
2255 {
2256 Z_PACKET_SOFTWARE_BP,
2257 Z_PACKET_HARDWARE_BP,
2258 Z_PACKET_WRITE_WP,
2259 Z_PACKET_READ_WP,
2260 Z_PACKET_ACCESS_WP,
2261 NR_Z_PACKET_TYPES
2262 };
2263
2264 /* For compatibility with older distributions. Provide a ``set remote
2265 Z-packet ...'' command that updates all the Z packet types. */
2266
2267 static enum auto_boolean remote_Z_packet_detect;
2268
2269 static void
2270 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2271 struct cmd_list_element *c)
2272 {
2273 int i;
2274
2275 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2276 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2277 }
2278
2279 static void
2280 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2281 struct cmd_list_element *c,
2282 const char *value)
2283 {
2284 int i;
2285
2286 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2287 {
2288 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
2289 }
2290 }
2291
2292 /* Returns true if the multi-process extensions are in effect. */
2293
2294 static int
2295 remote_multi_process_p (struct remote_state *rs)
2296 {
2297 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2298 }
2299
2300 /* Returns true if fork events are supported. */
2301
2302 static int
2303 remote_fork_event_p (struct remote_state *rs)
2304 {
2305 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2306 }
2307
2308 /* Returns true if vfork events are supported. */
2309
2310 static int
2311 remote_vfork_event_p (struct remote_state *rs)
2312 {
2313 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2314 }
2315
2316 /* Returns true if exec events are supported. */
2317
2318 static int
2319 remote_exec_event_p (struct remote_state *rs)
2320 {
2321 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2322 }
2323
2324 /* Returns true if memory tagging is supported, false otherwise. */
2325
2326 static bool
2327 remote_memory_tagging_p ()
2328 {
2329 return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE;
2330 }
2331
2332 /* Insert fork catchpoint target routine. If fork events are enabled
2333 then return success, nothing more to do. */
2334
2335 int
2336 remote_target::insert_fork_catchpoint (int pid)
2337 {
2338 struct remote_state *rs = get_remote_state ();
2339
2340 return !remote_fork_event_p (rs);
2341 }
2342
2343 /* Remove fork catchpoint target routine. Nothing to do, just
2344 return success. */
2345
2346 int
2347 remote_target::remove_fork_catchpoint (int pid)
2348 {
2349 return 0;
2350 }
2351
2352 /* Insert vfork catchpoint target routine. If vfork events are enabled
2353 then return success, nothing more to do. */
2354
2355 int
2356 remote_target::insert_vfork_catchpoint (int pid)
2357 {
2358 struct remote_state *rs = get_remote_state ();
2359
2360 return !remote_vfork_event_p (rs);
2361 }
2362
2363 /* Remove vfork catchpoint target routine. Nothing to do, just
2364 return success. */
2365
2366 int
2367 remote_target::remove_vfork_catchpoint (int pid)
2368 {
2369 return 0;
2370 }
2371
2372 /* Insert exec catchpoint target routine. If exec events are
2373 enabled, just return success. */
2374
2375 int
2376 remote_target::insert_exec_catchpoint (int pid)
2377 {
2378 struct remote_state *rs = get_remote_state ();
2379
2380 return !remote_exec_event_p (rs);
2381 }
2382
2383 /* Remove exec catchpoint target routine. Nothing to do, just
2384 return success. */
2385
2386 int
2387 remote_target::remove_exec_catchpoint (int pid)
2388 {
2389 return 0;
2390 }
2391
2392 \f
2393
2394 /* Take advantage of the fact that the TID field is not used, to tag
2395 special ptids with it set to != 0. */
2396 static const ptid_t magic_null_ptid (42000, -1, 1);
2397 static const ptid_t not_sent_ptid (42000, -2, 1);
2398 static const ptid_t any_thread_ptid (42000, 0, 1);
2399
2400 /* Find out if the stub attached to PID (and hence GDB should offer to
2401 detach instead of killing it when bailing out). */
2402
2403 int
2404 remote_target::remote_query_attached (int pid)
2405 {
2406 struct remote_state *rs = get_remote_state ();
2407 size_t size = get_remote_packet_size ();
2408
2409 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2410 return 0;
2411
2412 if (remote_multi_process_p (rs))
2413 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2414 else
2415 xsnprintf (rs->buf.data (), size, "qAttached");
2416
2417 putpkt (rs->buf);
2418 getpkt (&rs->buf, 0);
2419
2420 switch (packet_ok (rs->buf,
2421 &remote_protocol_packets[PACKET_qAttached]))
2422 {
2423 case PACKET_OK:
2424 if (strcmp (rs->buf.data (), "1") == 0)
2425 return 1;
2426 break;
2427 case PACKET_ERROR:
2428 warning (_("Remote failure reply: %s"), rs->buf.data ());
2429 break;
2430 case PACKET_UNKNOWN:
2431 break;
2432 }
2433
2434 return 0;
2435 }
2436
2437 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2438 has been invented by GDB, instead of reported by the target. Since
2439 we can be connected to a remote system before before knowing about
2440 any inferior, mark the target with execution when we find the first
2441 inferior. If ATTACHED is 1, then we had just attached to this
2442 inferior. If it is 0, then we just created this inferior. If it
2443 is -1, then try querying the remote stub to find out if it had
2444 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2445 attempt to open this inferior's executable as the main executable
2446 if no main executable is open already. */
2447
2448 inferior *
2449 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2450 int try_open_exec)
2451 {
2452 struct inferior *inf;
2453
2454 /* Check whether this process we're learning about is to be
2455 considered attached, or if is to be considered to have been
2456 spawned by the stub. */
2457 if (attached == -1)
2458 attached = remote_query_attached (pid);
2459
2460 if (gdbarch_has_global_solist (target_gdbarch ()))
2461 {
2462 /* If the target shares code across all inferiors, then every
2463 attach adds a new inferior. */
2464 inf = add_inferior (pid);
2465
2466 /* ... and every inferior is bound to the same program space.
2467 However, each inferior may still have its own address
2468 space. */
2469 inf->aspace = maybe_new_address_space ();
2470 inf->pspace = current_program_space;
2471 }
2472 else
2473 {
2474 /* In the traditional debugging scenario, there's a 1-1 match
2475 between program/address spaces. We simply bind the inferior
2476 to the program space's address space. */
2477 inf = current_inferior ();
2478
2479 /* However, if the current inferior is already bound to a
2480 process, find some other empty inferior. */
2481 if (inf->pid != 0)
2482 {
2483 inf = nullptr;
2484 for (inferior *it : all_inferiors ())
2485 if (it->pid == 0)
2486 {
2487 inf = it;
2488 break;
2489 }
2490 }
2491 if (inf == nullptr)
2492 {
2493 /* Since all inferiors were already bound to a process, add
2494 a new inferior. */
2495 inf = add_inferior_with_spaces ();
2496 }
2497 switch_to_inferior_no_thread (inf);
2498 inf->push_target (this);
2499 inferior_appeared (inf, pid);
2500 }
2501
2502 inf->attach_flag = attached;
2503 inf->fake_pid_p = fake_pid_p;
2504
2505 /* If no main executable is currently open then attempt to
2506 open the file that was executed to create this inferior. */
2507 if (try_open_exec && get_exec_file (0) == NULL)
2508 exec_file_locate_attach (pid, 0, 1);
2509
2510 /* Check for exec file mismatch, and let the user solve it. */
2511 validate_exec_file (1);
2512
2513 return inf;
2514 }
2515
2516 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2517 static remote_thread_info *get_remote_thread_info (remote_target *target,
2518 ptid_t ptid);
2519
2520 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2521 according to RUNNING. */
2522
2523 thread_info *
2524 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing)
2525 {
2526 struct remote_state *rs = get_remote_state ();
2527 struct thread_info *thread;
2528
2529 /* GDB historically didn't pull threads in the initial connection
2530 setup. If the remote target doesn't even have a concept of
2531 threads (e.g., a bare-metal target), even if internally we
2532 consider that a single-threaded target, mentioning a new thread
2533 might be confusing to the user. Be silent then, preserving the
2534 age old behavior. */
2535 if (rs->starting_up)
2536 thread = add_thread_silent (this, ptid);
2537 else
2538 thread = add_thread (this, ptid);
2539
2540 /* We start by assuming threads are resumed. That state then gets updated
2541 when we process a matching stop reply. */
2542 get_remote_thread_info (thread)->set_resumed ();
2543
2544 set_executing (this, ptid, executing);
2545 set_running (this, ptid, running);
2546
2547 return thread;
2548 }
2549
2550 /* Come here when we learn about a thread id from the remote target.
2551 It may be the first time we hear about such thread, so take the
2552 opportunity to add it to GDB's thread list. In case this is the
2553 first time we're noticing its corresponding inferior, add it to
2554 GDB's inferior list as well. EXECUTING indicates whether the
2555 thread is (internally) executing or stopped. */
2556
2557 void
2558 remote_target::remote_notice_new_inferior (ptid_t currthread, int executing)
2559 {
2560 /* In non-stop mode, we assume new found threads are (externally)
2561 running until proven otherwise with a stop reply. In all-stop,
2562 we can only get here if all threads are stopped. */
2563 int running = target_is_non_stop_p () ? 1 : 0;
2564
2565 /* If this is a new thread, add it to GDB's thread list.
2566 If we leave it up to WFI to do this, bad things will happen. */
2567
2568 thread_info *tp = find_thread_ptid (this, currthread);
2569 if (tp != NULL && tp->state == THREAD_EXITED)
2570 {
2571 /* We're seeing an event on a thread id we knew had exited.
2572 This has to be a new thread reusing the old id. Add it. */
2573 remote_add_thread (currthread, running, executing);
2574 return;
2575 }
2576
2577 if (!in_thread_list (this, currthread))
2578 {
2579 struct inferior *inf = NULL;
2580 int pid = currthread.pid ();
2581
2582 if (inferior_ptid.is_pid ()
2583 && pid == inferior_ptid.pid ())
2584 {
2585 /* inferior_ptid has no thread member yet. This can happen
2586 with the vAttach -> remote_wait,"TAAthread:" path if the
2587 stub doesn't support qC. This is the first stop reported
2588 after an attach, so this is the main thread. Update the
2589 ptid in the thread list. */
2590 if (in_thread_list (this, ptid_t (pid)))
2591 thread_change_ptid (this, inferior_ptid, currthread);
2592 else
2593 {
2594 thread_info *thr
2595 = remote_add_thread (currthread, running, executing);
2596 switch_to_thread (thr);
2597 }
2598 return;
2599 }
2600
2601 if (magic_null_ptid == inferior_ptid)
2602 {
2603 /* inferior_ptid is not set yet. This can happen with the
2604 vRun -> remote_wait,"TAAthread:" path if the stub
2605 doesn't support qC. This is the first stop reported
2606 after an attach, so this is the main thread. Update the
2607 ptid in the thread list. */
2608 thread_change_ptid (this, inferior_ptid, currthread);
2609 return;
2610 }
2611
2612 /* When connecting to a target remote, or to a target
2613 extended-remote which already was debugging an inferior, we
2614 may not know about it yet. Add it before adding its child
2615 thread, so notifications are emitted in a sensible order. */
2616 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2617 {
2618 struct remote_state *rs = get_remote_state ();
2619 bool fake_pid_p = !remote_multi_process_p (rs);
2620
2621 inf = remote_add_inferior (fake_pid_p,
2622 currthread.pid (), -1, 1);
2623 }
2624
2625 /* This is really a new thread. Add it. */
2626 thread_info *new_thr
2627 = remote_add_thread (currthread, running, executing);
2628
2629 /* If we found a new inferior, let the common code do whatever
2630 it needs to with it (e.g., read shared libraries, insert
2631 breakpoints), unless we're just setting up an all-stop
2632 connection. */
2633 if (inf != NULL)
2634 {
2635 struct remote_state *rs = get_remote_state ();
2636
2637 if (!rs->starting_up)
2638 notice_new_inferior (new_thr, executing, 0);
2639 }
2640 }
2641 }
2642
2643 /* Return THREAD's private thread data, creating it if necessary. */
2644
2645 static remote_thread_info *
2646 get_remote_thread_info (thread_info *thread)
2647 {
2648 gdb_assert (thread != NULL);
2649
2650 if (thread->priv == NULL)
2651 thread->priv.reset (new remote_thread_info);
2652
2653 return static_cast<remote_thread_info *> (thread->priv.get ());
2654 }
2655
2656 /* Return PTID's private thread data, creating it if necessary. */
2657
2658 static remote_thread_info *
2659 get_remote_thread_info (remote_target *target, ptid_t ptid)
2660 {
2661 thread_info *thr = find_thread_ptid (target, ptid);
2662 return get_remote_thread_info (thr);
2663 }
2664
2665 /* Call this function as a result of
2666 1) A halt indication (T packet) containing a thread id
2667 2) A direct query of currthread
2668 3) Successful execution of set thread */
2669
2670 static void
2671 record_currthread (struct remote_state *rs, ptid_t currthread)
2672 {
2673 rs->general_thread = currthread;
2674 }
2675
2676 /* If 'QPassSignals' is supported, tell the remote stub what signals
2677 it can simply pass through to the inferior without reporting. */
2678
2679 void
2680 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2681 {
2682 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2683 {
2684 char *pass_packet, *p;
2685 int count = 0;
2686 struct remote_state *rs = get_remote_state ();
2687
2688 gdb_assert (pass_signals.size () < 256);
2689 for (size_t i = 0; i < pass_signals.size (); i++)
2690 {
2691 if (pass_signals[i])
2692 count++;
2693 }
2694 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2695 strcpy (pass_packet, "QPassSignals:");
2696 p = pass_packet + strlen (pass_packet);
2697 for (size_t i = 0; i < pass_signals.size (); i++)
2698 {
2699 if (pass_signals[i])
2700 {
2701 if (i >= 16)
2702 *p++ = tohex (i >> 4);
2703 *p++ = tohex (i & 15);
2704 if (count)
2705 *p++ = ';';
2706 else
2707 break;
2708 count--;
2709 }
2710 }
2711 *p = 0;
2712 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2713 {
2714 putpkt (pass_packet);
2715 getpkt (&rs->buf, 0);
2716 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2717 xfree (rs->last_pass_packet);
2718 rs->last_pass_packet = pass_packet;
2719 }
2720 else
2721 xfree (pass_packet);
2722 }
2723 }
2724
2725 /* If 'QCatchSyscalls' is supported, tell the remote stub
2726 to report syscalls to GDB. */
2727
2728 int
2729 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2730 gdb::array_view<const int> syscall_counts)
2731 {
2732 const char *catch_packet;
2733 enum packet_result result;
2734 int n_sysno = 0;
2735
2736 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2737 {
2738 /* Not supported. */
2739 return 1;
2740 }
2741
2742 if (needed && any_count == 0)
2743 {
2744 /* Count how many syscalls are to be caught. */
2745 for (size_t i = 0; i < syscall_counts.size (); i++)
2746 {
2747 if (syscall_counts[i] != 0)
2748 n_sysno++;
2749 }
2750 }
2751
2752 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
2753 pid, needed, any_count, n_sysno);
2754
2755 std::string built_packet;
2756 if (needed)
2757 {
2758 /* Prepare a packet with the sysno list, assuming max 8+1
2759 characters for a sysno. If the resulting packet size is too
2760 big, fallback on the non-selective packet. */
2761 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2762 built_packet.reserve (maxpktsz);
2763 built_packet = "QCatchSyscalls:1";
2764 if (any_count == 0)
2765 {
2766 /* Add in each syscall to be caught. */
2767 for (size_t i = 0; i < syscall_counts.size (); i++)
2768 {
2769 if (syscall_counts[i] != 0)
2770 string_appendf (built_packet, ";%zx", i);
2771 }
2772 }
2773 if (built_packet.size () > get_remote_packet_size ())
2774 {
2775 /* catch_packet too big. Fallback to less efficient
2776 non selective mode, with GDB doing the filtering. */
2777 catch_packet = "QCatchSyscalls:1";
2778 }
2779 else
2780 catch_packet = built_packet.c_str ();
2781 }
2782 else
2783 catch_packet = "QCatchSyscalls:0";
2784
2785 struct remote_state *rs = get_remote_state ();
2786
2787 putpkt (catch_packet);
2788 getpkt (&rs->buf, 0);
2789 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2790 if (result == PACKET_OK)
2791 return 0;
2792 else
2793 return -1;
2794 }
2795
2796 /* If 'QProgramSignals' is supported, tell the remote stub what
2797 signals it should pass through to the inferior when detaching. */
2798
2799 void
2800 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
2801 {
2802 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2803 {
2804 char *packet, *p;
2805 int count = 0;
2806 struct remote_state *rs = get_remote_state ();
2807
2808 gdb_assert (signals.size () < 256);
2809 for (size_t i = 0; i < signals.size (); i++)
2810 {
2811 if (signals[i])
2812 count++;
2813 }
2814 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2815 strcpy (packet, "QProgramSignals:");
2816 p = packet + strlen (packet);
2817 for (size_t i = 0; i < signals.size (); i++)
2818 {
2819 if (signal_pass_state (i))
2820 {
2821 if (i >= 16)
2822 *p++ = tohex (i >> 4);
2823 *p++ = tohex (i & 15);
2824 if (count)
2825 *p++ = ';';
2826 else
2827 break;
2828 count--;
2829 }
2830 }
2831 *p = 0;
2832 if (!rs->last_program_signals_packet
2833 || strcmp (rs->last_program_signals_packet, packet) != 0)
2834 {
2835 putpkt (packet);
2836 getpkt (&rs->buf, 0);
2837 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2838 xfree (rs->last_program_signals_packet);
2839 rs->last_program_signals_packet = packet;
2840 }
2841 else
2842 xfree (packet);
2843 }
2844 }
2845
2846 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2847 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2848 thread. If GEN is set, set the general thread, if not, then set
2849 the step/continue thread. */
2850 void
2851 remote_target::set_thread (ptid_t ptid, int gen)
2852 {
2853 struct remote_state *rs = get_remote_state ();
2854 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2855 char *buf = rs->buf.data ();
2856 char *endbuf = buf + get_remote_packet_size ();
2857
2858 if (state == ptid)
2859 return;
2860
2861 *buf++ = 'H';
2862 *buf++ = gen ? 'g' : 'c';
2863 if (ptid == magic_null_ptid)
2864 xsnprintf (buf, endbuf - buf, "0");
2865 else if (ptid == any_thread_ptid)
2866 xsnprintf (buf, endbuf - buf, "0");
2867 else if (ptid == minus_one_ptid)
2868 xsnprintf (buf, endbuf - buf, "-1");
2869 else
2870 write_ptid (buf, endbuf, ptid);
2871 putpkt (rs->buf);
2872 getpkt (&rs->buf, 0);
2873 if (gen)
2874 rs->general_thread = ptid;
2875 else
2876 rs->continue_thread = ptid;
2877 }
2878
2879 void
2880 remote_target::set_general_thread (ptid_t ptid)
2881 {
2882 set_thread (ptid, 1);
2883 }
2884
2885 void
2886 remote_target::set_continue_thread (ptid_t ptid)
2887 {
2888 set_thread (ptid, 0);
2889 }
2890
2891 /* Change the remote current process. Which thread within the process
2892 ends up selected isn't important, as long as it is the same process
2893 as what INFERIOR_PTID points to.
2894
2895 This comes from that fact that there is no explicit notion of
2896 "selected process" in the protocol. The selected process for
2897 general operations is the process the selected general thread
2898 belongs to. */
2899
2900 void
2901 remote_target::set_general_process ()
2902 {
2903 struct remote_state *rs = get_remote_state ();
2904
2905 /* If the remote can't handle multiple processes, don't bother. */
2906 if (!remote_multi_process_p (rs))
2907 return;
2908
2909 /* We only need to change the remote current thread if it's pointing
2910 at some other process. */
2911 if (rs->general_thread.pid () != inferior_ptid.pid ())
2912 set_general_thread (inferior_ptid);
2913 }
2914
2915 \f
2916 /* Return nonzero if this is the main thread that we made up ourselves
2917 to model non-threaded targets as single-threaded. */
2918
2919 static int
2920 remote_thread_always_alive (ptid_t ptid)
2921 {
2922 if (ptid == magic_null_ptid)
2923 /* The main thread is always alive. */
2924 return 1;
2925
2926 if (ptid.pid () != 0 && ptid.lwp () == 0)
2927 /* The main thread is always alive. This can happen after a
2928 vAttach, if the remote side doesn't support
2929 multi-threading. */
2930 return 1;
2931
2932 return 0;
2933 }
2934
2935 /* Return nonzero if the thread PTID is still alive on the remote
2936 system. */
2937
2938 bool
2939 remote_target::thread_alive (ptid_t ptid)
2940 {
2941 struct remote_state *rs = get_remote_state ();
2942 char *p, *endp;
2943
2944 /* Check if this is a thread that we made up ourselves to model
2945 non-threaded targets as single-threaded. */
2946 if (remote_thread_always_alive (ptid))
2947 return 1;
2948
2949 p = rs->buf.data ();
2950 endp = p + get_remote_packet_size ();
2951
2952 *p++ = 'T';
2953 write_ptid (p, endp, ptid);
2954
2955 putpkt (rs->buf);
2956 getpkt (&rs->buf, 0);
2957 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2958 }
2959
2960 /* Return a pointer to a thread name if we know it and NULL otherwise.
2961 The thread_info object owns the memory for the name. */
2962
2963 const char *
2964 remote_target::thread_name (struct thread_info *info)
2965 {
2966 if (info->priv != NULL)
2967 {
2968 const std::string &name = get_remote_thread_info (info)->name;
2969 return !name.empty () ? name.c_str () : NULL;
2970 }
2971
2972 return NULL;
2973 }
2974
2975 /* About these extended threadlist and threadinfo packets. They are
2976 variable length packets but, the fields within them are often fixed
2977 length. They are redundant enough to send over UDP as is the
2978 remote protocol in general. There is a matching unit test module
2979 in libstub. */
2980
2981 /* WARNING: This threadref data structure comes from the remote O.S.,
2982 libstub protocol encoding, and remote.c. It is not particularly
2983 changable. */
2984
2985 /* Right now, the internal structure is int. We want it to be bigger.
2986 Plan to fix this. */
2987
2988 typedef int gdb_threadref; /* Internal GDB thread reference. */
2989
2990 /* gdb_ext_thread_info is an internal GDB data structure which is
2991 equivalent to the reply of the remote threadinfo packet. */
2992
2993 struct gdb_ext_thread_info
2994 {
2995 threadref threadid; /* External form of thread reference. */
2996 int active; /* Has state interesting to GDB?
2997 regs, stack. */
2998 char display[256]; /* Brief state display, name,
2999 blocked/suspended. */
3000 char shortname[32]; /* To be used to name threads. */
3001 char more_display[256]; /* Long info, statistics, queue depth,
3002 whatever. */
3003 };
3004
3005 /* The volume of remote transfers can be limited by submitting
3006 a mask containing bits specifying the desired information.
3007 Use a union of these values as the 'selection' parameter to
3008 get_thread_info. FIXME: Make these TAG names more thread specific. */
3009
3010 #define TAG_THREADID 1
3011 #define TAG_EXISTS 2
3012 #define TAG_DISPLAY 4
3013 #define TAG_THREADNAME 8
3014 #define TAG_MOREDISPLAY 16
3015
3016 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3017
3018 static const char *unpack_nibble (const char *buf, int *val);
3019
3020 static const char *unpack_byte (const char *buf, int *value);
3021
3022 static char *pack_int (char *buf, int value);
3023
3024 static const char *unpack_int (const char *buf, int *value);
3025
3026 static const char *unpack_string (const char *src, char *dest, int length);
3027
3028 static char *pack_threadid (char *pkt, threadref *id);
3029
3030 static const char *unpack_threadid (const char *inbuf, threadref *id);
3031
3032 void int_to_threadref (threadref *id, int value);
3033
3034 static int threadref_to_int (threadref *ref);
3035
3036 static void copy_threadref (threadref *dest, threadref *src);
3037
3038 static int threadmatch (threadref *dest, threadref *src);
3039
3040 static char *pack_threadinfo_request (char *pkt, int mode,
3041 threadref *id);
3042
3043 static char *pack_threadlist_request (char *pkt, int startflag,
3044 int threadcount,
3045 threadref *nextthread);
3046
3047 static int remote_newthread_step (threadref *ref, void *context);
3048
3049
3050 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3051 buffer we're allowed to write to. Returns
3052 BUF+CHARACTERS_WRITTEN. */
3053
3054 char *
3055 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3056 {
3057 int pid, tid;
3058 struct remote_state *rs = get_remote_state ();
3059
3060 if (remote_multi_process_p (rs))
3061 {
3062 pid = ptid.pid ();
3063 if (pid < 0)
3064 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3065 else
3066 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3067 }
3068 tid = ptid.lwp ();
3069 if (tid < 0)
3070 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3071 else
3072 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3073
3074 return buf;
3075 }
3076
3077 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3078 last parsed char. Returns null_ptid if no thread id is found, and
3079 throws an error if the thread id has an invalid format. */
3080
3081 static ptid_t
3082 read_ptid (const char *buf, const char **obuf)
3083 {
3084 const char *p = buf;
3085 const char *pp;
3086 ULONGEST pid = 0, tid = 0;
3087
3088 if (*p == 'p')
3089 {
3090 /* Multi-process ptid. */
3091 pp = unpack_varlen_hex (p + 1, &pid);
3092 if (*pp != '.')
3093 error (_("invalid remote ptid: %s"), p);
3094
3095 p = pp;
3096 pp = unpack_varlen_hex (p + 1, &tid);
3097 if (obuf)
3098 *obuf = pp;
3099 return ptid_t (pid, tid, 0);
3100 }
3101
3102 /* No multi-process. Just a tid. */
3103 pp = unpack_varlen_hex (p, &tid);
3104
3105 /* Return null_ptid when no thread id is found. */
3106 if (p == pp)
3107 {
3108 if (obuf)
3109 *obuf = pp;
3110 return null_ptid;
3111 }
3112
3113 /* Since the stub is not sending a process id, then default to
3114 what's in inferior_ptid, unless it's null at this point. If so,
3115 then since there's no way to know the pid of the reported
3116 threads, use the magic number. */
3117 if (inferior_ptid == null_ptid)
3118 pid = magic_null_ptid.pid ();
3119 else
3120 pid = inferior_ptid.pid ();
3121
3122 if (obuf)
3123 *obuf = pp;
3124 return ptid_t (pid, tid, 0);
3125 }
3126
3127 static int
3128 stubhex (int ch)
3129 {
3130 if (ch >= 'a' && ch <= 'f')
3131 return ch - 'a' + 10;
3132 if (ch >= '0' && ch <= '9')
3133 return ch - '0';
3134 if (ch >= 'A' && ch <= 'F')
3135 return ch - 'A' + 10;
3136 return -1;
3137 }
3138
3139 static int
3140 stub_unpack_int (const char *buff, int fieldlength)
3141 {
3142 int nibble;
3143 int retval = 0;
3144
3145 while (fieldlength)
3146 {
3147 nibble = stubhex (*buff++);
3148 retval |= nibble;
3149 fieldlength--;
3150 if (fieldlength)
3151 retval = retval << 4;
3152 }
3153 return retval;
3154 }
3155
3156 static const char *
3157 unpack_nibble (const char *buf, int *val)
3158 {
3159 *val = fromhex (*buf++);
3160 return buf;
3161 }
3162
3163 static const char *
3164 unpack_byte (const char *buf, int *value)
3165 {
3166 *value = stub_unpack_int (buf, 2);
3167 return buf + 2;
3168 }
3169
3170 static char *
3171 pack_int (char *buf, int value)
3172 {
3173 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3174 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3175 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3176 buf = pack_hex_byte (buf, (value & 0xff));
3177 return buf;
3178 }
3179
3180 static const char *
3181 unpack_int (const char *buf, int *value)
3182 {
3183 *value = stub_unpack_int (buf, 8);
3184 return buf + 8;
3185 }
3186
3187 #if 0 /* Currently unused, uncomment when needed. */
3188 static char *pack_string (char *pkt, char *string);
3189
3190 static char *
3191 pack_string (char *pkt, char *string)
3192 {
3193 char ch;
3194 int len;
3195
3196 len = strlen (string);
3197 if (len > 200)
3198 len = 200; /* Bigger than most GDB packets, junk??? */
3199 pkt = pack_hex_byte (pkt, len);
3200 while (len-- > 0)
3201 {
3202 ch = *string++;
3203 if ((ch == '\0') || (ch == '#'))
3204 ch = '*'; /* Protect encapsulation. */
3205 *pkt++ = ch;
3206 }
3207 return pkt;
3208 }
3209 #endif /* 0 (unused) */
3210
3211 static const char *
3212 unpack_string (const char *src, char *dest, int length)
3213 {
3214 while (length--)
3215 *dest++ = *src++;
3216 *dest = '\0';
3217 return src;
3218 }
3219
3220 static char *
3221 pack_threadid (char *pkt, threadref *id)
3222 {
3223 char *limit;
3224 unsigned char *altid;
3225
3226 altid = (unsigned char *) id;
3227 limit = pkt + BUF_THREAD_ID_SIZE;
3228 while (pkt < limit)
3229 pkt = pack_hex_byte (pkt, *altid++);
3230 return pkt;
3231 }
3232
3233
3234 static const char *
3235 unpack_threadid (const char *inbuf, threadref *id)
3236 {
3237 char *altref;
3238 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3239 int x, y;
3240
3241 altref = (char *) id;
3242
3243 while (inbuf < limit)
3244 {
3245 x = stubhex (*inbuf++);
3246 y = stubhex (*inbuf++);
3247 *altref++ = (x << 4) | y;
3248 }
3249 return inbuf;
3250 }
3251
3252 /* Externally, threadrefs are 64 bits but internally, they are still
3253 ints. This is due to a mismatch of specifications. We would like
3254 to use 64bit thread references internally. This is an adapter
3255 function. */
3256
3257 void
3258 int_to_threadref (threadref *id, int value)
3259 {
3260 unsigned char *scan;
3261
3262 scan = (unsigned char *) id;
3263 {
3264 int i = 4;
3265 while (i--)
3266 *scan++ = 0;
3267 }
3268 *scan++ = (value >> 24) & 0xff;
3269 *scan++ = (value >> 16) & 0xff;
3270 *scan++ = (value >> 8) & 0xff;
3271 *scan++ = (value & 0xff);
3272 }
3273
3274 static int
3275 threadref_to_int (threadref *ref)
3276 {
3277 int i, value = 0;
3278 unsigned char *scan;
3279
3280 scan = *ref;
3281 scan += 4;
3282 i = 4;
3283 while (i-- > 0)
3284 value = (value << 8) | ((*scan++) & 0xff);
3285 return value;
3286 }
3287
3288 static void
3289 copy_threadref (threadref *dest, threadref *src)
3290 {
3291 int i;
3292 unsigned char *csrc, *cdest;
3293
3294 csrc = (unsigned char *) src;
3295 cdest = (unsigned char *) dest;
3296 i = 8;
3297 while (i--)
3298 *cdest++ = *csrc++;
3299 }
3300
3301 static int
3302 threadmatch (threadref *dest, threadref *src)
3303 {
3304 /* Things are broken right now, so just assume we got a match. */
3305 #if 0
3306 unsigned char *srcp, *destp;
3307 int i, result;
3308 srcp = (char *) src;
3309 destp = (char *) dest;
3310
3311 result = 1;
3312 while (i-- > 0)
3313 result &= (*srcp++ == *destp++) ? 1 : 0;
3314 return result;
3315 #endif
3316 return 1;
3317 }
3318
3319 /*
3320 threadid:1, # always request threadid
3321 context_exists:2,
3322 display:4,
3323 unique_name:8,
3324 more_display:16
3325 */
3326
3327 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3328
3329 static char *
3330 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3331 {
3332 *pkt++ = 'q'; /* Info Query */
3333 *pkt++ = 'P'; /* process or thread info */
3334 pkt = pack_int (pkt, mode); /* mode */
3335 pkt = pack_threadid (pkt, id); /* threadid */
3336 *pkt = '\0'; /* terminate */
3337 return pkt;
3338 }
3339
3340 /* These values tag the fields in a thread info response packet. */
3341 /* Tagging the fields allows us to request specific fields and to
3342 add more fields as time goes by. */
3343
3344 #define TAG_THREADID 1 /* Echo the thread identifier. */
3345 #define TAG_EXISTS 2 /* Is this process defined enough to
3346 fetch registers and its stack? */
3347 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3348 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3349 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3350 the process. */
3351
3352 int
3353 remote_target::remote_unpack_thread_info_response (const char *pkt,
3354 threadref *expectedref,
3355 gdb_ext_thread_info *info)
3356 {
3357 struct remote_state *rs = get_remote_state ();
3358 int mask, length;
3359 int tag;
3360 threadref ref;
3361 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3362 int retval = 1;
3363
3364 /* info->threadid = 0; FIXME: implement zero_threadref. */
3365 info->active = 0;
3366 info->display[0] = '\0';
3367 info->shortname[0] = '\0';
3368 info->more_display[0] = '\0';
3369
3370 /* Assume the characters indicating the packet type have been
3371 stripped. */
3372 pkt = unpack_int (pkt, &mask); /* arg mask */
3373 pkt = unpack_threadid (pkt, &ref);
3374
3375 if (mask == 0)
3376 warning (_("Incomplete response to threadinfo request."));
3377 if (!threadmatch (&ref, expectedref))
3378 { /* This is an answer to a different request. */
3379 warning (_("ERROR RMT Thread info mismatch."));
3380 return 0;
3381 }
3382 copy_threadref (&info->threadid, &ref);
3383
3384 /* Loop on tagged fields , try to bail if something goes wrong. */
3385
3386 /* Packets are terminated with nulls. */
3387 while ((pkt < limit) && mask && *pkt)
3388 {
3389 pkt = unpack_int (pkt, &tag); /* tag */
3390 pkt = unpack_byte (pkt, &length); /* length */
3391 if (!(tag & mask)) /* Tags out of synch with mask. */
3392 {
3393 warning (_("ERROR RMT: threadinfo tag mismatch."));
3394 retval = 0;
3395 break;
3396 }
3397 if (tag == TAG_THREADID)
3398 {
3399 if (length != 16)
3400 {
3401 warning (_("ERROR RMT: length of threadid is not 16."));
3402 retval = 0;
3403 break;
3404 }
3405 pkt = unpack_threadid (pkt, &ref);
3406 mask = mask & ~TAG_THREADID;
3407 continue;
3408 }
3409 if (tag == TAG_EXISTS)
3410 {
3411 info->active = stub_unpack_int (pkt, length);
3412 pkt += length;
3413 mask = mask & ~(TAG_EXISTS);
3414 if (length > 8)
3415 {
3416 warning (_("ERROR RMT: 'exists' length too long."));
3417 retval = 0;
3418 break;
3419 }
3420 continue;
3421 }
3422 if (tag == TAG_THREADNAME)
3423 {
3424 pkt = unpack_string (pkt, &info->shortname[0], length);
3425 mask = mask & ~TAG_THREADNAME;
3426 continue;
3427 }
3428 if (tag == TAG_DISPLAY)
3429 {
3430 pkt = unpack_string (pkt, &info->display[0], length);
3431 mask = mask & ~TAG_DISPLAY;
3432 continue;
3433 }
3434 if (tag == TAG_MOREDISPLAY)
3435 {
3436 pkt = unpack_string (pkt, &info->more_display[0], length);
3437 mask = mask & ~TAG_MOREDISPLAY;
3438 continue;
3439 }
3440 warning (_("ERROR RMT: unknown thread info tag."));
3441 break; /* Not a tag we know about. */
3442 }
3443 return retval;
3444 }
3445
3446 int
3447 remote_target::remote_get_threadinfo (threadref *threadid,
3448 int fieldset,
3449 gdb_ext_thread_info *info)
3450 {
3451 struct remote_state *rs = get_remote_state ();
3452 int result;
3453
3454 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3455 putpkt (rs->buf);
3456 getpkt (&rs->buf, 0);
3457
3458 if (rs->buf[0] == '\0')
3459 return 0;
3460
3461 result = remote_unpack_thread_info_response (&rs->buf[2],
3462 threadid, info);
3463 return result;
3464 }
3465
3466 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3467
3468 static char *
3469 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3470 threadref *nextthread)
3471 {
3472 *pkt++ = 'q'; /* info query packet */
3473 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3474 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3475 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3476 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3477 *pkt = '\0';
3478 return pkt;
3479 }
3480
3481 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3482
3483 int
3484 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3485 threadref *original_echo,
3486 threadref *resultlist,
3487 int *doneflag)
3488 {
3489 struct remote_state *rs = get_remote_state ();
3490 int count, resultcount, done;
3491
3492 resultcount = 0;
3493 /* Assume the 'q' and 'M chars have been stripped. */
3494 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3495 /* done parse past here */
3496 pkt = unpack_byte (pkt, &count); /* count field */
3497 pkt = unpack_nibble (pkt, &done);
3498 /* The first threadid is the argument threadid. */
3499 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3500 while ((count-- > 0) && (pkt < limit))
3501 {
3502 pkt = unpack_threadid (pkt, resultlist++);
3503 if (resultcount++ >= result_limit)
3504 break;
3505 }
3506 if (doneflag)
3507 *doneflag = done;
3508 return resultcount;
3509 }
3510
3511 /* Fetch the next batch of threads from the remote. Returns -1 if the
3512 qL packet is not supported, 0 on error and 1 on success. */
3513
3514 int
3515 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3516 int result_limit, int *done, int *result_count,
3517 threadref *threadlist)
3518 {
3519 struct remote_state *rs = get_remote_state ();
3520 int result = 1;
3521
3522 /* Truncate result limit to be smaller than the packet size. */
3523 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3524 >= get_remote_packet_size ())
3525 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3526
3527 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3528 nextthread);
3529 putpkt (rs->buf);
3530 getpkt (&rs->buf, 0);
3531 if (rs->buf[0] == '\0')
3532 {
3533 /* Packet not supported. */
3534 return -1;
3535 }
3536
3537 *result_count =
3538 parse_threadlist_response (&rs->buf[2], result_limit,
3539 &rs->echo_nextthread, threadlist, done);
3540
3541 if (!threadmatch (&rs->echo_nextthread, nextthread))
3542 {
3543 /* FIXME: This is a good reason to drop the packet. */
3544 /* Possibly, there is a duplicate response. */
3545 /* Possibilities :
3546 retransmit immediatly - race conditions
3547 retransmit after timeout - yes
3548 exit
3549 wait for packet, then exit
3550 */
3551 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3552 return 0; /* I choose simply exiting. */
3553 }
3554 if (*result_count <= 0)
3555 {
3556 if (*done != 1)
3557 {
3558 warning (_("RMT ERROR : failed to get remote thread list."));
3559 result = 0;
3560 }
3561 return result; /* break; */
3562 }
3563 if (*result_count > result_limit)
3564 {
3565 *result_count = 0;
3566 warning (_("RMT ERROR: threadlist response longer than requested."));
3567 return 0;
3568 }
3569 return result;
3570 }
3571
3572 /* Fetch the list of remote threads, with the qL packet, and call
3573 STEPFUNCTION for each thread found. Stops iterating and returns 1
3574 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3575 STEPFUNCTION returns false. If the packet is not supported,
3576 returns -1. */
3577
3578 int
3579 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3580 void *context, int looplimit)
3581 {
3582 struct remote_state *rs = get_remote_state ();
3583 int done, i, result_count;
3584 int startflag = 1;
3585 int result = 1;
3586 int loopcount = 0;
3587
3588 done = 0;
3589 while (!done)
3590 {
3591 if (loopcount++ > looplimit)
3592 {
3593 result = 0;
3594 warning (_("Remote fetch threadlist -infinite loop-."));
3595 break;
3596 }
3597 result = remote_get_threadlist (startflag, &rs->nextthread,
3598 MAXTHREADLISTRESULTS,
3599 &done, &result_count,
3600 rs->resultthreadlist);
3601 if (result <= 0)
3602 break;
3603 /* Clear for later iterations. */
3604 startflag = 0;
3605 /* Setup to resume next batch of thread references, set nextthread. */
3606 if (result_count >= 1)
3607 copy_threadref (&rs->nextthread,
3608 &rs->resultthreadlist[result_count - 1]);
3609 i = 0;
3610 while (result_count--)
3611 {
3612 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3613 {
3614 result = 0;
3615 break;
3616 }
3617 }
3618 }
3619 return result;
3620 }
3621
3622 /* A thread found on the remote target. */
3623
3624 struct thread_item
3625 {
3626 explicit thread_item (ptid_t ptid_)
3627 : ptid (ptid_)
3628 {}
3629
3630 thread_item (thread_item &&other) = default;
3631 thread_item &operator= (thread_item &&other) = default;
3632
3633 DISABLE_COPY_AND_ASSIGN (thread_item);
3634
3635 /* The thread's PTID. */
3636 ptid_t ptid;
3637
3638 /* The thread's extra info. */
3639 std::string extra;
3640
3641 /* The thread's name. */
3642 std::string name;
3643
3644 /* The core the thread was running on. -1 if not known. */
3645 int core = -1;
3646
3647 /* The thread handle associated with the thread. */
3648 gdb::byte_vector thread_handle;
3649 };
3650
3651 /* Context passed around to the various methods listing remote
3652 threads. As new threads are found, they're added to the ITEMS
3653 vector. */
3654
3655 struct threads_listing_context
3656 {
3657 /* Return true if this object contains an entry for a thread with ptid
3658 PTID. */
3659
3660 bool contains_thread (ptid_t ptid) const
3661 {
3662 auto match_ptid = [&] (const thread_item &item)
3663 {
3664 return item.ptid == ptid;
3665 };
3666
3667 auto it = std::find_if (this->items.begin (),
3668 this->items.end (),
3669 match_ptid);
3670
3671 return it != this->items.end ();
3672 }
3673
3674 /* Remove the thread with ptid PTID. */
3675
3676 void remove_thread (ptid_t ptid)
3677 {
3678 auto match_ptid = [&] (const thread_item &item)
3679 {
3680 return item.ptid == ptid;
3681 };
3682
3683 auto it = std::remove_if (this->items.begin (),
3684 this->items.end (),
3685 match_ptid);
3686
3687 if (it != this->items.end ())
3688 this->items.erase (it);
3689 }
3690
3691 /* The threads found on the remote target. */
3692 std::vector<thread_item> items;
3693 };
3694
3695 static int
3696 remote_newthread_step (threadref *ref, void *data)
3697 {
3698 struct threads_listing_context *context
3699 = (struct threads_listing_context *) data;
3700 int pid = inferior_ptid.pid ();
3701 int lwp = threadref_to_int (ref);
3702 ptid_t ptid (pid, lwp);
3703
3704 context->items.emplace_back (ptid);
3705
3706 return 1; /* continue iterator */
3707 }
3708
3709 #define CRAZY_MAX_THREADS 1000
3710
3711 ptid_t
3712 remote_target::remote_current_thread (ptid_t oldpid)
3713 {
3714 struct remote_state *rs = get_remote_state ();
3715
3716 putpkt ("qC");
3717 getpkt (&rs->buf, 0);
3718 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3719 {
3720 const char *obuf;
3721 ptid_t result;
3722
3723 result = read_ptid (&rs->buf[2], &obuf);
3724 if (*obuf != '\0')
3725 remote_debug_printf ("warning: garbage in qC reply");
3726
3727 return result;
3728 }
3729 else
3730 return oldpid;
3731 }
3732
3733 /* List remote threads using the deprecated qL packet. */
3734
3735 int
3736 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3737 {
3738 if (remote_threadlist_iterator (remote_newthread_step, context,
3739 CRAZY_MAX_THREADS) >= 0)
3740 return 1;
3741
3742 return 0;
3743 }
3744
3745 #if defined(HAVE_LIBEXPAT)
3746
3747 static void
3748 start_thread (struct gdb_xml_parser *parser,
3749 const struct gdb_xml_element *element,
3750 void *user_data,
3751 std::vector<gdb_xml_value> &attributes)
3752 {
3753 struct threads_listing_context *data
3754 = (struct threads_listing_context *) user_data;
3755 struct gdb_xml_value *attr;
3756
3757 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3758 ptid_t ptid = read_ptid (id, NULL);
3759
3760 data->items.emplace_back (ptid);
3761 thread_item &item = data->items.back ();
3762
3763 attr = xml_find_attribute (attributes, "core");
3764 if (attr != NULL)
3765 item.core = *(ULONGEST *) attr->value.get ();
3766
3767 attr = xml_find_attribute (attributes, "name");
3768 if (attr != NULL)
3769 item.name = (const char *) attr->value.get ();
3770
3771 attr = xml_find_attribute (attributes, "handle");
3772 if (attr != NULL)
3773 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3774 }
3775
3776 static void
3777 end_thread (struct gdb_xml_parser *parser,
3778 const struct gdb_xml_element *element,
3779 void *user_data, const char *body_text)
3780 {
3781 struct threads_listing_context *data
3782 = (struct threads_listing_context *) user_data;
3783
3784 if (body_text != NULL && *body_text != '\0')
3785 data->items.back ().extra = body_text;
3786 }
3787
3788 const struct gdb_xml_attribute thread_attributes[] = {
3789 { "id", GDB_XML_AF_NONE, NULL, NULL },
3790 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3791 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3792 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3793 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3794 };
3795
3796 const struct gdb_xml_element thread_children[] = {
3797 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3798 };
3799
3800 const struct gdb_xml_element threads_children[] = {
3801 { "thread", thread_attributes, thread_children,
3802 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3803 start_thread, end_thread },
3804 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3805 };
3806
3807 const struct gdb_xml_element threads_elements[] = {
3808 { "threads", NULL, threads_children,
3809 GDB_XML_EF_NONE, NULL, NULL },
3810 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3811 };
3812
3813 #endif
3814
3815 /* List remote threads using qXfer:threads:read. */
3816
3817 int
3818 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
3819 {
3820 #if defined(HAVE_LIBEXPAT)
3821 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3822 {
3823 gdb::optional<gdb::char_vector> xml
3824 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
3825
3826 if (xml && (*xml)[0] != '\0')
3827 {
3828 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3829 threads_elements, xml->data (), context);
3830 }
3831
3832 return 1;
3833 }
3834 #endif
3835
3836 return 0;
3837 }
3838
3839 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3840
3841 int
3842 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
3843 {
3844 struct remote_state *rs = get_remote_state ();
3845
3846 if (rs->use_threadinfo_query)
3847 {
3848 const char *bufp;
3849
3850 putpkt ("qfThreadInfo");
3851 getpkt (&rs->buf, 0);
3852 bufp = rs->buf.data ();
3853 if (bufp[0] != '\0') /* q packet recognized */
3854 {
3855 while (*bufp++ == 'm') /* reply contains one or more TID */
3856 {
3857 do
3858 {
3859 ptid_t ptid = read_ptid (bufp, &bufp);
3860 context->items.emplace_back (ptid);
3861 }
3862 while (*bufp++ == ','); /* comma-separated list */
3863 putpkt ("qsThreadInfo");
3864 getpkt (&rs->buf, 0);
3865 bufp = rs->buf.data ();
3866 }
3867 return 1;
3868 }
3869 else
3870 {
3871 /* Packet not recognized. */
3872 rs->use_threadinfo_query = 0;
3873 }
3874 }
3875
3876 return 0;
3877 }
3878
3879 /* Return true if INF only has one non-exited thread. */
3880
3881 static bool
3882 has_single_non_exited_thread (inferior *inf)
3883 {
3884 int count = 0;
3885 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
3886 if (++count > 1)
3887 break;
3888 return count == 1;
3889 }
3890
3891 /* Implement the to_update_thread_list function for the remote
3892 targets. */
3893
3894 void
3895 remote_target::update_thread_list ()
3896 {
3897 struct threads_listing_context context;
3898 int got_list = 0;
3899
3900 /* We have a few different mechanisms to fetch the thread list. Try
3901 them all, starting with the most preferred one first, falling
3902 back to older methods. */
3903 if (remote_get_threads_with_qxfer (&context)
3904 || remote_get_threads_with_qthreadinfo (&context)
3905 || remote_get_threads_with_ql (&context))
3906 {
3907 got_list = 1;
3908
3909 if (context.items.empty ()
3910 && remote_thread_always_alive (inferior_ptid))
3911 {
3912 /* Some targets don't really support threads, but still
3913 reply an (empty) thread list in response to the thread
3914 listing packets, instead of replying "packet not
3915 supported". Exit early so we don't delete the main
3916 thread. */
3917 return;
3918 }
3919
3920 /* CONTEXT now holds the current thread list on the remote
3921 target end. Delete GDB-side threads no longer found on the
3922 target. */
3923 for (thread_info *tp : all_threads_safe ())
3924 {
3925 if (tp->inf->process_target () != this)
3926 continue;
3927
3928 if (!context.contains_thread (tp->ptid))
3929 {
3930 /* Do not remove the thread if it is the last thread in
3931 the inferior. This situation happens when we have a
3932 pending exit process status to process. Otherwise we
3933 may end up with a seemingly live inferior (i.e. pid
3934 != 0) that has no threads. */
3935 if (has_single_non_exited_thread (tp->inf))
3936 continue;
3937
3938 /* Not found. */
3939 delete_thread (tp);
3940 }
3941 }
3942
3943 /* Remove any unreported fork child threads from CONTEXT so
3944 that we don't interfere with follow fork, which is where
3945 creation of such threads is handled. */
3946 remove_new_fork_children (&context);
3947
3948 /* And now add threads we don't know about yet to our list. */
3949 for (thread_item &item : context.items)
3950 {
3951 if (item.ptid != null_ptid)
3952 {
3953 /* In non-stop mode, we assume new found threads are
3954 executing until proven otherwise with a stop reply.
3955 In all-stop, we can only get here if all threads are
3956 stopped. */
3957 int executing = target_is_non_stop_p () ? 1 : 0;
3958
3959 remote_notice_new_inferior (item.ptid, executing);
3960
3961 thread_info *tp = find_thread_ptid (this, item.ptid);
3962 remote_thread_info *info = get_remote_thread_info (tp);
3963 info->core = item.core;
3964 info->extra = std::move (item.extra);
3965 info->name = std::move (item.name);
3966 info->thread_handle = std::move (item.thread_handle);
3967 }
3968 }
3969 }
3970
3971 if (!got_list)
3972 {
3973 /* If no thread listing method is supported, then query whether
3974 each known thread is alive, one by one, with the T packet.
3975 If the target doesn't support threads at all, then this is a
3976 no-op. See remote_thread_alive. */
3977 prune_threads ();
3978 }
3979 }
3980
3981 /*
3982 * Collect a descriptive string about the given thread.
3983 * The target may say anything it wants to about the thread
3984 * (typically info about its blocked / runnable state, name, etc.).
3985 * This string will appear in the info threads display.
3986 *
3987 * Optional: targets are not required to implement this function.
3988 */
3989
3990 const char *
3991 remote_target::extra_thread_info (thread_info *tp)
3992 {
3993 struct remote_state *rs = get_remote_state ();
3994 int set;
3995 threadref id;
3996 struct gdb_ext_thread_info threadinfo;
3997
3998 if (rs->remote_desc == 0) /* paranoia */
3999 internal_error (__FILE__, __LINE__,
4000 _("remote_threads_extra_info"));
4001
4002 if (tp->ptid == magic_null_ptid
4003 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4004 /* This is the main thread which was added by GDB. The remote
4005 server doesn't know about it. */
4006 return NULL;
4007
4008 std::string &extra = get_remote_thread_info (tp)->extra;
4009
4010 /* If already have cached info, use it. */
4011 if (!extra.empty ())
4012 return extra.c_str ();
4013
4014 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4015 {
4016 /* If we're using qXfer:threads:read, then the extra info is
4017 included in the XML. So if we didn't have anything cached,
4018 it's because there's really no extra info. */
4019 return NULL;
4020 }
4021
4022 if (rs->use_threadextra_query)
4023 {
4024 char *b = rs->buf.data ();
4025 char *endb = b + get_remote_packet_size ();
4026
4027 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4028 b += strlen (b);
4029 write_ptid (b, endb, tp->ptid);
4030
4031 putpkt (rs->buf);
4032 getpkt (&rs->buf, 0);
4033 if (rs->buf[0] != 0)
4034 {
4035 extra.resize (strlen (rs->buf.data ()) / 2);
4036 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4037 return extra.c_str ();
4038 }
4039 }
4040
4041 /* If the above query fails, fall back to the old method. */
4042 rs->use_threadextra_query = 0;
4043 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4044 | TAG_MOREDISPLAY | TAG_DISPLAY;
4045 int_to_threadref (&id, tp->ptid.lwp ());
4046 if (remote_get_threadinfo (&id, set, &threadinfo))
4047 if (threadinfo.active)
4048 {
4049 if (*threadinfo.shortname)
4050 string_appendf (extra, " Name: %s", threadinfo.shortname);
4051 if (*threadinfo.display)
4052 {
4053 if (!extra.empty ())
4054 extra += ',';
4055 string_appendf (extra, " State: %s", threadinfo.display);
4056 }
4057 if (*threadinfo.more_display)
4058 {
4059 if (!extra.empty ())
4060 extra += ',';
4061 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4062 }
4063 return extra.c_str ();
4064 }
4065 return NULL;
4066 }
4067 \f
4068
4069 bool
4070 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4071 struct static_tracepoint_marker *marker)
4072 {
4073 struct remote_state *rs = get_remote_state ();
4074 char *p = rs->buf.data ();
4075
4076 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4077 p += strlen (p);
4078 p += hexnumstr (p, addr);
4079 putpkt (rs->buf);
4080 getpkt (&rs->buf, 0);
4081 p = rs->buf.data ();
4082
4083 if (*p == 'E')
4084 error (_("Remote failure reply: %s"), p);
4085
4086 if (*p++ == 'm')
4087 {
4088 parse_static_tracepoint_marker_definition (p, NULL, marker);
4089 return true;
4090 }
4091
4092 return false;
4093 }
4094
4095 std::vector<static_tracepoint_marker>
4096 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4097 {
4098 struct remote_state *rs = get_remote_state ();
4099 std::vector<static_tracepoint_marker> markers;
4100 const char *p;
4101 static_tracepoint_marker marker;
4102
4103 /* Ask for a first packet of static tracepoint marker
4104 definition. */
4105 putpkt ("qTfSTM");
4106 getpkt (&rs->buf, 0);
4107 p = rs->buf.data ();
4108 if (*p == 'E')
4109 error (_("Remote failure reply: %s"), p);
4110
4111 while (*p++ == 'm')
4112 {
4113 do
4114 {
4115 parse_static_tracepoint_marker_definition (p, &p, &marker);
4116
4117 if (strid == NULL || marker.str_id == strid)
4118 markers.push_back (std::move (marker));
4119 }
4120 while (*p++ == ','); /* comma-separated list */
4121 /* Ask for another packet of static tracepoint definition. */
4122 putpkt ("qTsSTM");
4123 getpkt (&rs->buf, 0);
4124 p = rs->buf.data ();
4125 }
4126
4127 return markers;
4128 }
4129
4130 \f
4131 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4132
4133 ptid_t
4134 remote_target::get_ada_task_ptid (long lwp, long thread)
4135 {
4136 return ptid_t (inferior_ptid.pid (), lwp, 0);
4137 }
4138 \f
4139
4140 /* Restart the remote side; this is an extended protocol operation. */
4141
4142 void
4143 remote_target::extended_remote_restart ()
4144 {
4145 struct remote_state *rs = get_remote_state ();
4146
4147 /* Send the restart command; for reasons I don't understand the
4148 remote side really expects a number after the "R". */
4149 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4150 putpkt (rs->buf);
4151
4152 remote_fileio_reset ();
4153 }
4154 \f
4155 /* Clean up connection to a remote debugger. */
4156
4157 void
4158 remote_target::close ()
4159 {
4160 /* Make sure we leave stdin registered in the event loop. */
4161 terminal_ours ();
4162
4163 trace_reset_local_state ();
4164
4165 delete this;
4166 }
4167
4168 remote_target::~remote_target ()
4169 {
4170 struct remote_state *rs = get_remote_state ();
4171
4172 /* Check for NULL because we may get here with a partially
4173 constructed target/connection. */
4174 if (rs->remote_desc == nullptr)
4175 return;
4176
4177 serial_close (rs->remote_desc);
4178
4179 /* We are destroying the remote target, so we should discard
4180 everything of this target. */
4181 discard_pending_stop_replies_in_queue ();
4182
4183 if (rs->remote_async_inferior_event_token)
4184 delete_async_event_handler (&rs->remote_async_inferior_event_token);
4185
4186 delete rs->notif_state;
4187 }
4188
4189 /* Query the remote side for the text, data and bss offsets. */
4190
4191 void
4192 remote_target::get_offsets ()
4193 {
4194 struct remote_state *rs = get_remote_state ();
4195 char *buf;
4196 char *ptr;
4197 int lose, num_segments = 0, do_sections, do_segments;
4198 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4199
4200 if (current_program_space->symfile_object_file == NULL)
4201 return;
4202
4203 putpkt ("qOffsets");
4204 getpkt (&rs->buf, 0);
4205 buf = rs->buf.data ();
4206
4207 if (buf[0] == '\000')
4208 return; /* Return silently. Stub doesn't support
4209 this command. */
4210 if (buf[0] == 'E')
4211 {
4212 warning (_("Remote failure reply: %s"), buf);
4213 return;
4214 }
4215
4216 /* Pick up each field in turn. This used to be done with scanf, but
4217 scanf will make trouble if CORE_ADDR size doesn't match
4218 conversion directives correctly. The following code will work
4219 with any size of CORE_ADDR. */
4220 text_addr = data_addr = bss_addr = 0;
4221 ptr = buf;
4222 lose = 0;
4223
4224 if (startswith (ptr, "Text="))
4225 {
4226 ptr += 5;
4227 /* Don't use strtol, could lose on big values. */
4228 while (*ptr && *ptr != ';')
4229 text_addr = (text_addr << 4) + fromhex (*ptr++);
4230
4231 if (startswith (ptr, ";Data="))
4232 {
4233 ptr += 6;
4234 while (*ptr && *ptr != ';')
4235 data_addr = (data_addr << 4) + fromhex (*ptr++);
4236 }
4237 else
4238 lose = 1;
4239
4240 if (!lose && startswith (ptr, ";Bss="))
4241 {
4242 ptr += 5;
4243 while (*ptr && *ptr != ';')
4244 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4245
4246 if (bss_addr != data_addr)
4247 warning (_("Target reported unsupported offsets: %s"), buf);
4248 }
4249 else
4250 lose = 1;
4251 }
4252 else if (startswith (ptr, "TextSeg="))
4253 {
4254 ptr += 8;
4255 /* Don't use strtol, could lose on big values. */
4256 while (*ptr && *ptr != ';')
4257 text_addr = (text_addr << 4) + fromhex (*ptr++);
4258 num_segments = 1;
4259
4260 if (startswith (ptr, ";DataSeg="))
4261 {
4262 ptr += 9;
4263 while (*ptr && *ptr != ';')
4264 data_addr = (data_addr << 4) + fromhex (*ptr++);
4265 num_segments++;
4266 }
4267 }
4268 else
4269 lose = 1;
4270
4271 if (lose)
4272 error (_("Malformed response to offset query, %s"), buf);
4273 else if (*ptr != '\0')
4274 warning (_("Target reported unsupported offsets: %s"), buf);
4275
4276 objfile *objf = current_program_space->symfile_object_file;
4277 section_offsets offs = objf->section_offsets;
4278
4279 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd);
4280 do_segments = (data != NULL);
4281 do_sections = num_segments == 0;
4282
4283 if (num_segments > 0)
4284 {
4285 segments[0] = text_addr;
4286 segments[1] = data_addr;
4287 }
4288 /* If we have two segments, we can still try to relocate everything
4289 by assuming that the .text and .data offsets apply to the whole
4290 text and data segments. Convert the offsets given in the packet
4291 to base addresses for symfile_map_offsets_to_segments. */
4292 else if (data != nullptr && data->segments.size () == 2)
4293 {
4294 segments[0] = data->segments[0].base + text_addr;
4295 segments[1] = data->segments[1].base + data_addr;
4296 num_segments = 2;
4297 }
4298 /* If the object file has only one segment, assume that it is text
4299 rather than data; main programs with no writable data are rare,
4300 but programs with no code are useless. Of course the code might
4301 have ended up in the data segment... to detect that we would need
4302 the permissions here. */
4303 else if (data && data->segments.size () == 1)
4304 {
4305 segments[0] = data->segments[0].base + text_addr;
4306 num_segments = 1;
4307 }
4308 /* There's no way to relocate by segment. */
4309 else
4310 do_segments = 0;
4311
4312 if (do_segments)
4313 {
4314 int ret = symfile_map_offsets_to_segments (objf->obfd,
4315 data.get (), offs,
4316 num_segments, segments);
4317
4318 if (ret == 0 && !do_sections)
4319 error (_("Can not handle qOffsets TextSeg "
4320 "response with this symbol file"));
4321
4322 if (ret > 0)
4323 do_sections = 0;
4324 }
4325
4326 if (do_sections)
4327 {
4328 offs[SECT_OFF_TEXT (objf)] = text_addr;
4329
4330 /* This is a temporary kludge to force data and bss to use the
4331 same offsets because that's what nlmconv does now. The real
4332 solution requires changes to the stub and remote.c that I
4333 don't have time to do right now. */
4334
4335 offs[SECT_OFF_DATA (objf)] = data_addr;
4336 offs[SECT_OFF_BSS (objf)] = data_addr;
4337 }
4338
4339 objfile_relocate (objf, offs);
4340 }
4341
4342 /* Send interrupt_sequence to remote target. */
4343
4344 void
4345 remote_target::send_interrupt_sequence ()
4346 {
4347 struct remote_state *rs = get_remote_state ();
4348
4349 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4350 remote_serial_write ("\x03", 1);
4351 else if (interrupt_sequence_mode == interrupt_sequence_break)
4352 serial_send_break (rs->remote_desc);
4353 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4354 {
4355 serial_send_break (rs->remote_desc);
4356 remote_serial_write ("g", 1);
4357 }
4358 else
4359 internal_error (__FILE__, __LINE__,
4360 _("Invalid value for interrupt_sequence_mode: %s."),
4361 interrupt_sequence_mode);
4362 }
4363
4364
4365 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4366 and extract the PTID. Returns NULL_PTID if not found. */
4367
4368 static ptid_t
4369 stop_reply_extract_thread (const char *stop_reply)
4370 {
4371 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4372 {
4373 const char *p;
4374
4375 /* Txx r:val ; r:val (...) */
4376 p = &stop_reply[3];
4377
4378 /* Look for "register" named "thread". */
4379 while (*p != '\0')
4380 {
4381 const char *p1;
4382
4383 p1 = strchr (p, ':');
4384 if (p1 == NULL)
4385 return null_ptid;
4386
4387 if (strncmp (p, "thread", p1 - p) == 0)
4388 return read_ptid (++p1, &p);
4389
4390 p1 = strchr (p, ';');
4391 if (p1 == NULL)
4392 return null_ptid;
4393 p1++;
4394
4395 p = p1;
4396 }
4397 }
4398
4399 return null_ptid;
4400 }
4401
4402 /* Determine the remote side's current thread. If we have a stop
4403 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4404 "thread" register we can extract the current thread from. If not,
4405 ask the remote which is the current thread with qC. The former
4406 method avoids a roundtrip. */
4407
4408 ptid_t
4409 remote_target::get_current_thread (const char *wait_status)
4410 {
4411 ptid_t ptid = null_ptid;
4412
4413 /* Note we don't use remote_parse_stop_reply as that makes use of
4414 the target architecture, which we haven't yet fully determined at
4415 this point. */
4416 if (wait_status != NULL)
4417 ptid = stop_reply_extract_thread (wait_status);
4418 if (ptid == null_ptid)
4419 ptid = remote_current_thread (inferior_ptid);
4420
4421 return ptid;
4422 }
4423
4424 /* Query the remote target for which is the current thread/process,
4425 add it to our tables, and update INFERIOR_PTID. The caller is
4426 responsible for setting the state such that the remote end is ready
4427 to return the current thread.
4428
4429 This function is called after handling the '?' or 'vRun' packets,
4430 whose response is a stop reply from which we can also try
4431 extracting the thread. If the target doesn't support the explicit
4432 qC query, we infer the current thread from that stop reply, passed
4433 in in WAIT_STATUS, which may be NULL.
4434
4435 The function returns pointer to the main thread of the inferior. */
4436
4437 thread_info *
4438 remote_target::add_current_inferior_and_thread (const char *wait_status)
4439 {
4440 struct remote_state *rs = get_remote_state ();
4441 bool fake_pid_p = false;
4442
4443 switch_to_no_thread ();
4444
4445 /* Now, if we have thread information, update the current thread's
4446 ptid. */
4447 ptid_t curr_ptid = get_current_thread (wait_status);
4448
4449 if (curr_ptid != null_ptid)
4450 {
4451 if (!remote_multi_process_p (rs))
4452 fake_pid_p = true;
4453 }
4454 else
4455 {
4456 /* Without this, some commands which require an active target
4457 (such as kill) won't work. This variable serves (at least)
4458 double duty as both the pid of the target process (if it has
4459 such), and as a flag indicating that a target is active. */
4460 curr_ptid = magic_null_ptid;
4461 fake_pid_p = true;
4462 }
4463
4464 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4465
4466 /* Add the main thread and switch to it. Don't try reading
4467 registers yet, since we haven't fetched the target description
4468 yet. */
4469 thread_info *tp = add_thread_silent (this, curr_ptid);
4470 switch_to_thread_no_regs (tp);
4471
4472 return tp;
4473 }
4474
4475 /* Print info about a thread that was found already stopped on
4476 connection. */
4477
4478 static void
4479 print_one_stopped_thread (struct thread_info *thread)
4480 {
4481 struct target_waitstatus *ws = &thread->suspend.waitstatus;
4482
4483 switch_to_thread (thread);
4484 thread->suspend.stop_pc = get_frame_pc (get_current_frame ());
4485 set_current_sal_from_frame (get_current_frame ());
4486
4487 thread->suspend.waitstatus_pending_p = 0;
4488
4489 if (ws->kind == TARGET_WAITKIND_STOPPED)
4490 {
4491 enum gdb_signal sig = ws->value.sig;
4492
4493 if (signal_print_state (sig))
4494 gdb::observers::signal_received.notify (sig);
4495 }
4496 gdb::observers::normal_stop.notify (NULL, 1);
4497 }
4498
4499 /* Process all initial stop replies the remote side sent in response
4500 to the ? packet. These indicate threads that were already stopped
4501 on initial connection. We mark these threads as stopped and print
4502 their current frame before giving the user the prompt. */
4503
4504 void
4505 remote_target::process_initial_stop_replies (int from_tty)
4506 {
4507 int pending_stop_replies = stop_reply_queue_length ();
4508 struct thread_info *selected = NULL;
4509 struct thread_info *lowest_stopped = NULL;
4510 struct thread_info *first = NULL;
4511
4512 /* Consume the initial pending events. */
4513 while (pending_stop_replies-- > 0)
4514 {
4515 ptid_t waiton_ptid = minus_one_ptid;
4516 ptid_t event_ptid;
4517 struct target_waitstatus ws;
4518 int ignore_event = 0;
4519
4520 memset (&ws, 0, sizeof (ws));
4521 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4522 if (remote_debug)
4523 print_target_wait_results (waiton_ptid, event_ptid, &ws);
4524
4525 switch (ws.kind)
4526 {
4527 case TARGET_WAITKIND_IGNORE:
4528 case TARGET_WAITKIND_NO_RESUMED:
4529 case TARGET_WAITKIND_SIGNALLED:
4530 case TARGET_WAITKIND_EXITED:
4531 /* We shouldn't see these, but if we do, just ignore. */
4532 remote_debug_printf ("event ignored");
4533 ignore_event = 1;
4534 break;
4535
4536 case TARGET_WAITKIND_EXECD:
4537 xfree (ws.value.execd_pathname);
4538 break;
4539 default:
4540 break;
4541 }
4542
4543 if (ignore_event)
4544 continue;
4545
4546 thread_info *evthread = find_thread_ptid (this, event_ptid);
4547
4548 if (ws.kind == TARGET_WAITKIND_STOPPED)
4549 {
4550 enum gdb_signal sig = ws.value.sig;
4551
4552 /* Stubs traditionally report SIGTRAP as initial signal,
4553 instead of signal 0. Suppress it. */
4554 if (sig == GDB_SIGNAL_TRAP)
4555 sig = GDB_SIGNAL_0;
4556 evthread->suspend.stop_signal = sig;
4557 ws.value.sig = sig;
4558 }
4559
4560 evthread->suspend.waitstatus = ws;
4561
4562 if (ws.kind != TARGET_WAITKIND_STOPPED
4563 || ws.value.sig != GDB_SIGNAL_0)
4564 evthread->suspend.waitstatus_pending_p = 1;
4565
4566 set_executing (this, event_ptid, false);
4567 set_running (this, event_ptid, false);
4568 get_remote_thread_info (evthread)->set_not_resumed ();
4569 }
4570
4571 /* "Notice" the new inferiors before anything related to
4572 registers/memory. */
4573 for (inferior *inf : all_non_exited_inferiors (this))
4574 {
4575 inf->needs_setup = 1;
4576
4577 if (non_stop)
4578 {
4579 thread_info *thread = any_live_thread_of_inferior (inf);
4580 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4581 from_tty);
4582 }
4583 }
4584
4585 /* If all-stop on top of non-stop, pause all threads. Note this
4586 records the threads' stop pc, so must be done after "noticing"
4587 the inferiors. */
4588 if (!non_stop)
4589 {
4590 stop_all_threads ();
4591
4592 /* If all threads of an inferior were already stopped, we
4593 haven't setup the inferior yet. */
4594 for (inferior *inf : all_non_exited_inferiors (this))
4595 {
4596 if (inf->needs_setup)
4597 {
4598 thread_info *thread = any_live_thread_of_inferior (inf);
4599 switch_to_thread_no_regs (thread);
4600 setup_inferior (0);
4601 }
4602 }
4603 }
4604
4605 /* Now go over all threads that are stopped, and print their current
4606 frame. If all-stop, then if there's a signalled thread, pick
4607 that as current. */
4608 for (thread_info *thread : all_non_exited_threads (this))
4609 {
4610 if (first == NULL)
4611 first = thread;
4612
4613 if (!non_stop)
4614 thread->set_running (false);
4615 else if (thread->state != THREAD_STOPPED)
4616 continue;
4617
4618 if (selected == NULL
4619 && thread->suspend.waitstatus_pending_p)
4620 selected = thread;
4621
4622 if (lowest_stopped == NULL
4623 || thread->inf->num < lowest_stopped->inf->num
4624 || thread->per_inf_num < lowest_stopped->per_inf_num)
4625 lowest_stopped = thread;
4626
4627 if (non_stop)
4628 print_one_stopped_thread (thread);
4629 }
4630
4631 /* In all-stop, we only print the status of one thread, and leave
4632 others with their status pending. */
4633 if (!non_stop)
4634 {
4635 thread_info *thread = selected;
4636 if (thread == NULL)
4637 thread = lowest_stopped;
4638 if (thread == NULL)
4639 thread = first;
4640
4641 print_one_stopped_thread (thread);
4642 }
4643
4644 /* For "info program". */
4645 thread_info *thread = inferior_thread ();
4646 if (thread->state == THREAD_STOPPED)
4647 set_last_target_status (this, inferior_ptid, thread->suspend.waitstatus);
4648 }
4649
4650 /* Start the remote connection and sync state. */
4651
4652 void
4653 remote_target::start_remote (int from_tty, int extended_p)
4654 {
4655 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4656
4657 struct remote_state *rs = get_remote_state ();
4658 struct packet_config *noack_config;
4659
4660 /* Signal other parts that we're going through the initial setup,
4661 and so things may not be stable yet. E.g., we don't try to
4662 install tracepoints until we've relocated symbols. Also, a
4663 Ctrl-C before we're connected and synced up can't interrupt the
4664 target. Instead, it offers to drop the (potentially wedged)
4665 connection. */
4666 rs->starting_up = 1;
4667
4668 QUIT;
4669
4670 if (interrupt_on_connect)
4671 send_interrupt_sequence ();
4672
4673 /* Ack any packet which the remote side has already sent. */
4674 remote_serial_write ("+", 1);
4675
4676 /* The first packet we send to the target is the optional "supported
4677 packets" request. If the target can answer this, it will tell us
4678 which later probes to skip. */
4679 remote_query_supported ();
4680
4681 /* If the stub wants to get a QAllow, compose one and send it. */
4682 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4683 set_permissions ();
4684
4685 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4686 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4687 as a reply to known packet. For packet "vFile:setfs:" it is an
4688 invalid reply and GDB would return error in
4689 remote_hostio_set_filesystem, making remote files access impossible.
4690 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4691 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4692 {
4693 const char v_mustreplyempty[] = "vMustReplyEmpty";
4694
4695 putpkt (v_mustreplyempty);
4696 getpkt (&rs->buf, 0);
4697 if (strcmp (rs->buf.data (), "OK") == 0)
4698 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4699 else if (strcmp (rs->buf.data (), "") != 0)
4700 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4701 rs->buf.data ());
4702 }
4703
4704 /* Next, we possibly activate noack mode.
4705
4706 If the QStartNoAckMode packet configuration is set to AUTO,
4707 enable noack mode if the stub reported a wish for it with
4708 qSupported.
4709
4710 If set to TRUE, then enable noack mode even if the stub didn't
4711 report it in qSupported. If the stub doesn't reply OK, the
4712 session ends with an error.
4713
4714 If FALSE, then don't activate noack mode, regardless of what the
4715 stub claimed should be the default with qSupported. */
4716
4717 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4718 if (packet_config_support (noack_config) != PACKET_DISABLE)
4719 {
4720 putpkt ("QStartNoAckMode");
4721 getpkt (&rs->buf, 0);
4722 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4723 rs->noack_mode = 1;
4724 }
4725
4726 if (extended_p)
4727 {
4728 /* Tell the remote that we are using the extended protocol. */
4729 putpkt ("!");
4730 getpkt (&rs->buf, 0);
4731 }
4732
4733 /* Let the target know which signals it is allowed to pass down to
4734 the program. */
4735 update_signals_program_target ();
4736
4737 /* Next, if the target can specify a description, read it. We do
4738 this before anything involving memory or registers. */
4739 target_find_description ();
4740
4741 /* Next, now that we know something about the target, update the
4742 address spaces in the program spaces. */
4743 update_address_spaces ();
4744
4745 /* On OSs where the list of libraries is global to all
4746 processes, we fetch them early. */
4747 if (gdbarch_has_global_solist (target_gdbarch ()))
4748 solib_add (NULL, from_tty, auto_solib_add);
4749
4750 if (target_is_non_stop_p ())
4751 {
4752 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4753 error (_("Non-stop mode requested, but remote "
4754 "does not support non-stop"));
4755
4756 putpkt ("QNonStop:1");
4757 getpkt (&rs->buf, 0);
4758
4759 if (strcmp (rs->buf.data (), "OK") != 0)
4760 error (_("Remote refused setting non-stop mode with: %s"),
4761 rs->buf.data ());
4762
4763 /* Find about threads and processes the stub is already
4764 controlling. We default to adding them in the running state.
4765 The '?' query below will then tell us about which threads are
4766 stopped. */
4767 this->update_thread_list ();
4768 }
4769 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4770 {
4771 /* Don't assume that the stub can operate in all-stop mode.
4772 Request it explicitly. */
4773 putpkt ("QNonStop:0");
4774 getpkt (&rs->buf, 0);
4775
4776 if (strcmp (rs->buf.data (), "OK") != 0)
4777 error (_("Remote refused setting all-stop mode with: %s"),
4778 rs->buf.data ());
4779 }
4780
4781 /* Upload TSVs regardless of whether the target is running or not. The
4782 remote stub, such as GDBserver, may have some predefined or builtin
4783 TSVs, even if the target is not running. */
4784 if (get_trace_status (current_trace_status ()) != -1)
4785 {
4786 struct uploaded_tsv *uploaded_tsvs = NULL;
4787
4788 upload_trace_state_variables (&uploaded_tsvs);
4789 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4790 }
4791
4792 /* Check whether the target is running now. */
4793 putpkt ("?");
4794 getpkt (&rs->buf, 0);
4795
4796 if (!target_is_non_stop_p ())
4797 {
4798 char *wait_status = NULL;
4799
4800 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4801 {
4802 if (!extended_p)
4803 error (_("The target is not running (try extended-remote?)"));
4804
4805 /* We're connected, but not running. Drop out before we
4806 call start_remote. */
4807 rs->starting_up = 0;
4808 return;
4809 }
4810 else
4811 {
4812 /* Save the reply for later. */
4813 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
4814 strcpy (wait_status, rs->buf.data ());
4815 }
4816
4817 /* Fetch thread list. */
4818 target_update_thread_list ();
4819
4820 /* Let the stub know that we want it to return the thread. */
4821 set_continue_thread (minus_one_ptid);
4822
4823 if (thread_count (this) == 0)
4824 {
4825 /* Target has no concept of threads at all. GDB treats
4826 non-threaded target as single-threaded; add a main
4827 thread. */
4828 thread_info *tp = add_current_inferior_and_thread (wait_status);
4829 get_remote_thread_info (tp)->set_resumed ();
4830 }
4831 else
4832 {
4833 /* We have thread information; select the thread the target
4834 says should be current. If we're reconnecting to a
4835 multi-threaded program, this will ideally be the thread
4836 that last reported an event before GDB disconnected. */
4837 ptid_t curr_thread = get_current_thread (wait_status);
4838 if (curr_thread == null_ptid)
4839 {
4840 /* Odd... The target was able to list threads, but not
4841 tell us which thread was current (no "thread"
4842 register in T stop reply?). Just pick the first
4843 thread in the thread list then. */
4844
4845 remote_debug_printf ("warning: couldn't determine remote "
4846 "current thread; picking first in list.");
4847
4848 for (thread_info *tp : all_non_exited_threads (this,
4849 minus_one_ptid))
4850 {
4851 switch_to_thread (tp);
4852 break;
4853 }
4854 }
4855 else
4856 switch_to_thread (find_thread_ptid (this, curr_thread));
4857 }
4858
4859 /* init_wait_for_inferior should be called before get_offsets in order
4860 to manage `inserted' flag in bp loc in a correct state.
4861 breakpoint_init_inferior, called from init_wait_for_inferior, set
4862 `inserted' flag to 0, while before breakpoint_re_set, called from
4863 start_remote, set `inserted' flag to 1. In the initialization of
4864 inferior, breakpoint_init_inferior should be called first, and then
4865 breakpoint_re_set can be called. If this order is broken, state of
4866 `inserted' flag is wrong, and cause some problems on breakpoint
4867 manipulation. */
4868 init_wait_for_inferior ();
4869
4870 get_offsets (); /* Get text, data & bss offsets. */
4871
4872 /* If we could not find a description using qXfer, and we know
4873 how to do it some other way, try again. This is not
4874 supported for non-stop; it could be, but it is tricky if
4875 there are no stopped threads when we connect. */
4876 if (remote_read_description_p (this)
4877 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4878 {
4879 target_clear_description ();
4880 target_find_description ();
4881 }
4882
4883 /* Use the previously fetched status. */
4884 gdb_assert (wait_status != NULL);
4885 strcpy (rs->buf.data (), wait_status);
4886 rs->cached_wait_status = 1;
4887
4888 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
4889 }
4890 else
4891 {
4892 /* Clear WFI global state. Do this before finding about new
4893 threads and inferiors, and setting the current inferior.
4894 Otherwise we would clear the proceed status of the current
4895 inferior when we want its stop_soon state to be preserved
4896 (see notice_new_inferior). */
4897 init_wait_for_inferior ();
4898
4899 /* In non-stop, we will either get an "OK", meaning that there
4900 are no stopped threads at this time; or, a regular stop
4901 reply. In the latter case, there may be more than one thread
4902 stopped --- we pull them all out using the vStopped
4903 mechanism. */
4904 if (strcmp (rs->buf.data (), "OK") != 0)
4905 {
4906 struct notif_client *notif = &notif_client_stop;
4907
4908 /* remote_notif_get_pending_replies acks this one, and gets
4909 the rest out. */
4910 rs->notif_state->pending_event[notif_client_stop.id]
4911 = remote_notif_parse (this, notif, rs->buf.data ());
4912 remote_notif_get_pending_events (notif);
4913 }
4914
4915 if (thread_count (this) == 0)
4916 {
4917 if (!extended_p)
4918 error (_("The target is not running (try extended-remote?)"));
4919
4920 /* We're connected, but not running. Drop out before we
4921 call start_remote. */
4922 rs->starting_up = 0;
4923 return;
4924 }
4925
4926 /* Report all signals during attach/startup. */
4927 pass_signals ({});
4928
4929 /* If there are already stopped threads, mark them stopped and
4930 report their stops before giving the prompt to the user. */
4931 process_initial_stop_replies (from_tty);
4932
4933 if (target_can_async_p ())
4934 target_async (1);
4935 }
4936
4937 /* If we connected to a live target, do some additional setup. */
4938 if (target_has_execution ())
4939 {
4940 /* No use without a symbol-file. */
4941 if (current_program_space->symfile_object_file)
4942 remote_check_symbols ();
4943 }
4944
4945 /* Possibly the target has been engaged in a trace run started
4946 previously; find out where things are at. */
4947 if (get_trace_status (current_trace_status ()) != -1)
4948 {
4949 struct uploaded_tp *uploaded_tps = NULL;
4950
4951 if (current_trace_status ()->running)
4952 printf_filtered (_("Trace is already running on the target.\n"));
4953
4954 upload_tracepoints (&uploaded_tps);
4955
4956 merge_uploaded_tracepoints (&uploaded_tps);
4957 }
4958
4959 /* Possibly the target has been engaged in a btrace record started
4960 previously; find out where things are at. */
4961 remote_btrace_maybe_reopen ();
4962
4963 /* The thread and inferior lists are now synchronized with the
4964 target, our symbols have been relocated, and we're merged the
4965 target's tracepoints with ours. We're done with basic start
4966 up. */
4967 rs->starting_up = 0;
4968
4969 /* Maybe breakpoints are global and need to be inserted now. */
4970 if (breakpoints_should_be_inserted_now ())
4971 insert_breakpoints ();
4972 }
4973
4974 const char *
4975 remote_target::connection_string ()
4976 {
4977 remote_state *rs = get_remote_state ();
4978
4979 if (rs->remote_desc->name != NULL)
4980 return rs->remote_desc->name;
4981 else
4982 return NULL;
4983 }
4984
4985 /* Open a connection to a remote debugger.
4986 NAME is the filename used for communication. */
4987
4988 void
4989 remote_target::open (const char *name, int from_tty)
4990 {
4991 open_1 (name, from_tty, 0);
4992 }
4993
4994 /* Open a connection to a remote debugger using the extended
4995 remote gdb protocol. NAME is the filename used for communication. */
4996
4997 void
4998 extended_remote_target::open (const char *name, int from_tty)
4999 {
5000 open_1 (name, from_tty, 1 /*extended_p */);
5001 }
5002
5003 /* Reset all packets back to "unknown support". Called when opening a
5004 new connection to a remote target. */
5005
5006 static void
5007 reset_all_packet_configs_support (void)
5008 {
5009 int i;
5010
5011 for (i = 0; i < PACKET_MAX; i++)
5012 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5013 }
5014
5015 /* Initialize all packet configs. */
5016
5017 static void
5018 init_all_packet_configs (void)
5019 {
5020 int i;
5021
5022 for (i = 0; i < PACKET_MAX; i++)
5023 {
5024 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5025 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5026 }
5027 }
5028
5029 /* Symbol look-up. */
5030
5031 void
5032 remote_target::remote_check_symbols ()
5033 {
5034 char *tmp;
5035 int end;
5036
5037 /* The remote side has no concept of inferiors that aren't running
5038 yet, it only knows about running processes. If we're connected
5039 but our current inferior is not running, we should not invite the
5040 remote target to request symbol lookups related to its
5041 (unrelated) current process. */
5042 if (!target_has_execution ())
5043 return;
5044
5045 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5046 return;
5047
5048 /* Make sure the remote is pointing at the right process. Note
5049 there's no way to select "no process". */
5050 set_general_process ();
5051
5052 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5053 because we need both at the same time. */
5054 gdb::char_vector msg (get_remote_packet_size ());
5055 gdb::char_vector reply (get_remote_packet_size ());
5056
5057 /* Invite target to request symbol lookups. */
5058
5059 putpkt ("qSymbol::");
5060 getpkt (&reply, 0);
5061 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
5062
5063 while (startswith (reply.data (), "qSymbol:"))
5064 {
5065 struct bound_minimal_symbol sym;
5066
5067 tmp = &reply[8];
5068 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5069 strlen (tmp) / 2);
5070 msg[end] = '\0';
5071 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5072 if (sym.minsym == NULL)
5073 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5074 &reply[8]);
5075 else
5076 {
5077 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5078 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
5079
5080 /* If this is a function address, return the start of code
5081 instead of any data function descriptor. */
5082 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
5083 sym_addr,
5084 current_top_target ());
5085
5086 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5087 phex_nz (sym_addr, addr_size), &reply[8]);
5088 }
5089
5090 putpkt (msg.data ());
5091 getpkt (&reply, 0);
5092 }
5093 }
5094
5095 static struct serial *
5096 remote_serial_open (const char *name)
5097 {
5098 static int udp_warning = 0;
5099
5100 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5101 of in ser-tcp.c, because it is the remote protocol assuming that the
5102 serial connection is reliable and not the serial connection promising
5103 to be. */
5104 if (!udp_warning && startswith (name, "udp:"))
5105 {
5106 warning (_("The remote protocol may be unreliable over UDP.\n"
5107 "Some events may be lost, rendering further debugging "
5108 "impossible."));
5109 udp_warning = 1;
5110 }
5111
5112 return serial_open (name);
5113 }
5114
5115 /* Inform the target of our permission settings. The permission flags
5116 work without this, but if the target knows the settings, it can do
5117 a couple things. First, it can add its own check, to catch cases
5118 that somehow manage to get by the permissions checks in target
5119 methods. Second, if the target is wired to disallow particular
5120 settings (for instance, a system in the field that is not set up to
5121 be able to stop at a breakpoint), it can object to any unavailable
5122 permissions. */
5123
5124 void
5125 remote_target::set_permissions ()
5126 {
5127 struct remote_state *rs = get_remote_state ();
5128
5129 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5130 "WriteReg:%x;WriteMem:%x;"
5131 "InsertBreak:%x;InsertTrace:%x;"
5132 "InsertFastTrace:%x;Stop:%x",
5133 may_write_registers, may_write_memory,
5134 may_insert_breakpoints, may_insert_tracepoints,
5135 may_insert_fast_tracepoints, may_stop);
5136 putpkt (rs->buf);
5137 getpkt (&rs->buf, 0);
5138
5139 /* If the target didn't like the packet, warn the user. Do not try
5140 to undo the user's settings, that would just be maddening. */
5141 if (strcmp (rs->buf.data (), "OK") != 0)
5142 warning (_("Remote refused setting permissions with: %s"),
5143 rs->buf.data ());
5144 }
5145
5146 /* This type describes each known response to the qSupported
5147 packet. */
5148 struct protocol_feature
5149 {
5150 /* The name of this protocol feature. */
5151 const char *name;
5152
5153 /* The default for this protocol feature. */
5154 enum packet_support default_support;
5155
5156 /* The function to call when this feature is reported, or after
5157 qSupported processing if the feature is not supported.
5158 The first argument points to this structure. The second
5159 argument indicates whether the packet requested support be
5160 enabled, disabled, or probed (or the default, if this function
5161 is being called at the end of processing and this feature was
5162 not reported). The third argument may be NULL; if not NULL, it
5163 is a NUL-terminated string taken from the packet following
5164 this feature's name and an equals sign. */
5165 void (*func) (remote_target *remote, const struct protocol_feature *,
5166 enum packet_support, const char *);
5167
5168 /* The corresponding packet for this feature. Only used if
5169 FUNC is remote_supported_packet. */
5170 int packet;
5171 };
5172
5173 static void
5174 remote_supported_packet (remote_target *remote,
5175 const struct protocol_feature *feature,
5176 enum packet_support support,
5177 const char *argument)
5178 {
5179 if (argument)
5180 {
5181 warning (_("Remote qSupported response supplied an unexpected value for"
5182 " \"%s\"."), feature->name);
5183 return;
5184 }
5185
5186 remote_protocol_packets[feature->packet].support = support;
5187 }
5188
5189 void
5190 remote_target::remote_packet_size (const protocol_feature *feature,
5191 enum packet_support support, const char *value)
5192 {
5193 struct remote_state *rs = get_remote_state ();
5194
5195 int packet_size;
5196 char *value_end;
5197
5198 if (support != PACKET_ENABLE)
5199 return;
5200
5201 if (value == NULL || *value == '\0')
5202 {
5203 warning (_("Remote target reported \"%s\" without a size."),
5204 feature->name);
5205 return;
5206 }
5207
5208 errno = 0;
5209 packet_size = strtol (value, &value_end, 16);
5210 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5211 {
5212 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5213 feature->name, value);
5214 return;
5215 }
5216
5217 /* Record the new maximum packet size. */
5218 rs->explicit_packet_size = packet_size;
5219 }
5220
5221 static void
5222 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5223 enum packet_support support, const char *value)
5224 {
5225 remote->remote_packet_size (feature, support, value);
5226 }
5227
5228 static const struct protocol_feature remote_protocol_features[] = {
5229 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5230 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5231 PACKET_qXfer_auxv },
5232 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5233 PACKET_qXfer_exec_file },
5234 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5235 PACKET_qXfer_features },
5236 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5237 PACKET_qXfer_libraries },
5238 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5239 PACKET_qXfer_libraries_svr4 },
5240 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5241 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5242 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5243 PACKET_qXfer_memory_map },
5244 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5245 PACKET_qXfer_osdata },
5246 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5247 PACKET_qXfer_threads },
5248 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5249 PACKET_qXfer_traceframe_info },
5250 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5251 PACKET_QPassSignals },
5252 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5253 PACKET_QCatchSyscalls },
5254 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5255 PACKET_QProgramSignals },
5256 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5257 PACKET_QSetWorkingDir },
5258 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5259 PACKET_QStartupWithShell },
5260 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5261 PACKET_QEnvironmentHexEncoded },
5262 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5263 PACKET_QEnvironmentReset },
5264 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5265 PACKET_QEnvironmentUnset },
5266 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5267 PACKET_QStartNoAckMode },
5268 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5269 PACKET_multiprocess_feature },
5270 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5271 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5272 PACKET_qXfer_siginfo_read },
5273 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5274 PACKET_qXfer_siginfo_write },
5275 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5276 PACKET_ConditionalTracepoints },
5277 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5278 PACKET_ConditionalBreakpoints },
5279 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5280 PACKET_BreakpointCommands },
5281 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5282 PACKET_FastTracepoints },
5283 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5284 PACKET_StaticTracepoints },
5285 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5286 PACKET_InstallInTrace},
5287 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5288 PACKET_DisconnectedTracing_feature },
5289 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5290 PACKET_bc },
5291 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5292 PACKET_bs },
5293 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5294 PACKET_TracepointSource },
5295 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5296 PACKET_QAllow },
5297 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5298 PACKET_EnableDisableTracepoints_feature },
5299 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5300 PACKET_qXfer_fdpic },
5301 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5302 PACKET_qXfer_uib },
5303 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5304 PACKET_QDisableRandomization },
5305 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5306 { "QTBuffer:size", PACKET_DISABLE,
5307 remote_supported_packet, PACKET_QTBuffer_size},
5308 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5309 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5310 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5311 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5312 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5313 PACKET_qXfer_btrace },
5314 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5315 PACKET_qXfer_btrace_conf },
5316 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5317 PACKET_Qbtrace_conf_bts_size },
5318 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5319 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5320 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5321 PACKET_fork_event_feature },
5322 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5323 PACKET_vfork_event_feature },
5324 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5325 PACKET_exec_event_feature },
5326 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5327 PACKET_Qbtrace_conf_pt_size },
5328 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5329 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5330 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5331 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5332 PACKET_memory_tagging_feature },
5333 };
5334
5335 static char *remote_support_xml;
5336
5337 /* Register string appended to "xmlRegisters=" in qSupported query. */
5338
5339 void
5340 register_remote_support_xml (const char *xml)
5341 {
5342 #if defined(HAVE_LIBEXPAT)
5343 if (remote_support_xml == NULL)
5344 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5345 else
5346 {
5347 char *copy = xstrdup (remote_support_xml + 13);
5348 char *saveptr;
5349 char *p = strtok_r (copy, ",", &saveptr);
5350
5351 do
5352 {
5353 if (strcmp (p, xml) == 0)
5354 {
5355 /* already there */
5356 xfree (copy);
5357 return;
5358 }
5359 }
5360 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5361 xfree (copy);
5362
5363 remote_support_xml = reconcat (remote_support_xml,
5364 remote_support_xml, ",", xml,
5365 (char *) NULL);
5366 }
5367 #endif
5368 }
5369
5370 static void
5371 remote_query_supported_append (std::string *msg, const char *append)
5372 {
5373 if (!msg->empty ())
5374 msg->append (";");
5375 msg->append (append);
5376 }
5377
5378 void
5379 remote_target::remote_query_supported ()
5380 {
5381 struct remote_state *rs = get_remote_state ();
5382 char *next;
5383 int i;
5384 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5385
5386 /* The packet support flags are handled differently for this packet
5387 than for most others. We treat an error, a disabled packet, and
5388 an empty response identically: any features which must be reported
5389 to be used will be automatically disabled. An empty buffer
5390 accomplishes this, since that is also the representation for a list
5391 containing no features. */
5392
5393 rs->buf[0] = 0;
5394 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5395 {
5396 std::string q;
5397
5398 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5399 remote_query_supported_append (&q, "multiprocess+");
5400
5401 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5402 remote_query_supported_append (&q, "swbreak+");
5403 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5404 remote_query_supported_append (&q, "hwbreak+");
5405
5406 remote_query_supported_append (&q, "qRelocInsn+");
5407
5408 if (packet_set_cmd_state (PACKET_fork_event_feature)
5409 != AUTO_BOOLEAN_FALSE)
5410 remote_query_supported_append (&q, "fork-events+");
5411 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5412 != AUTO_BOOLEAN_FALSE)
5413 remote_query_supported_append (&q, "vfork-events+");
5414 if (packet_set_cmd_state (PACKET_exec_event_feature)
5415 != AUTO_BOOLEAN_FALSE)
5416 remote_query_supported_append (&q, "exec-events+");
5417
5418 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5419 remote_query_supported_append (&q, "vContSupported+");
5420
5421 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5422 remote_query_supported_append (&q, "QThreadEvents+");
5423
5424 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5425 remote_query_supported_append (&q, "no-resumed+");
5426
5427 if (packet_set_cmd_state (PACKET_memory_tagging_feature)
5428 != AUTO_BOOLEAN_FALSE)
5429 remote_query_supported_append (&q, "memory-tagging+");
5430
5431 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5432 the qSupported:xmlRegisters=i386 handling. */
5433 if (remote_support_xml != NULL
5434 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5435 remote_query_supported_append (&q, remote_support_xml);
5436
5437 q = "qSupported:" + q;
5438 putpkt (q.c_str ());
5439
5440 getpkt (&rs->buf, 0);
5441
5442 /* If an error occured, warn, but do not return - just reset the
5443 buffer to empty and go on to disable features. */
5444 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5445 == PACKET_ERROR)
5446 {
5447 warning (_("Remote failure reply: %s"), rs->buf.data ());
5448 rs->buf[0] = 0;
5449 }
5450 }
5451
5452 memset (seen, 0, sizeof (seen));
5453
5454 next = rs->buf.data ();
5455 while (*next)
5456 {
5457 enum packet_support is_supported;
5458 char *p, *end, *name_end, *value;
5459
5460 /* First separate out this item from the rest of the packet. If
5461 there's another item after this, we overwrite the separator
5462 (terminated strings are much easier to work with). */
5463 p = next;
5464 end = strchr (p, ';');
5465 if (end == NULL)
5466 {
5467 end = p + strlen (p);
5468 next = end;
5469 }
5470 else
5471 {
5472 *end = '\0';
5473 next = end + 1;
5474
5475 if (end == p)
5476 {
5477 warning (_("empty item in \"qSupported\" response"));
5478 continue;
5479 }
5480 }
5481
5482 name_end = strchr (p, '=');
5483 if (name_end)
5484 {
5485 /* This is a name=value entry. */
5486 is_supported = PACKET_ENABLE;
5487 value = name_end + 1;
5488 *name_end = '\0';
5489 }
5490 else
5491 {
5492 value = NULL;
5493 switch (end[-1])
5494 {
5495 case '+':
5496 is_supported = PACKET_ENABLE;
5497 break;
5498
5499 case '-':
5500 is_supported = PACKET_DISABLE;
5501 break;
5502
5503 case '?':
5504 is_supported = PACKET_SUPPORT_UNKNOWN;
5505 break;
5506
5507 default:
5508 warning (_("unrecognized item \"%s\" "
5509 "in \"qSupported\" response"), p);
5510 continue;
5511 }
5512 end[-1] = '\0';
5513 }
5514
5515 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5516 if (strcmp (remote_protocol_features[i].name, p) == 0)
5517 {
5518 const struct protocol_feature *feature;
5519
5520 seen[i] = 1;
5521 feature = &remote_protocol_features[i];
5522 feature->func (this, feature, is_supported, value);
5523 break;
5524 }
5525 }
5526
5527 /* If we increased the packet size, make sure to increase the global
5528 buffer size also. We delay this until after parsing the entire
5529 qSupported packet, because this is the same buffer we were
5530 parsing. */
5531 if (rs->buf.size () < rs->explicit_packet_size)
5532 rs->buf.resize (rs->explicit_packet_size);
5533
5534 /* Handle the defaults for unmentioned features. */
5535 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5536 if (!seen[i])
5537 {
5538 const struct protocol_feature *feature;
5539
5540 feature = &remote_protocol_features[i];
5541 feature->func (this, feature, feature->default_support, NULL);
5542 }
5543 }
5544
5545 /* Serial QUIT handler for the remote serial descriptor.
5546
5547 Defers handling a Ctrl-C until we're done with the current
5548 command/response packet sequence, unless:
5549
5550 - We're setting up the connection. Don't send a remote interrupt
5551 request, as we're not fully synced yet. Quit immediately
5552 instead.
5553
5554 - The target has been resumed in the foreground
5555 (target_terminal::is_ours is false) with a synchronous resume
5556 packet, and we're blocked waiting for the stop reply, thus a
5557 Ctrl-C should be immediately sent to the target.
5558
5559 - We get a second Ctrl-C while still within the same serial read or
5560 write. In that case the serial is seemingly wedged --- offer to
5561 quit/disconnect.
5562
5563 - We see a second Ctrl-C without target response, after having
5564 previously interrupted the target. In that case the target/stub
5565 is probably wedged --- offer to quit/disconnect.
5566 */
5567
5568 void
5569 remote_target::remote_serial_quit_handler ()
5570 {
5571 struct remote_state *rs = get_remote_state ();
5572
5573 if (check_quit_flag ())
5574 {
5575 /* If we're starting up, we're not fully synced yet. Quit
5576 immediately. */
5577 if (rs->starting_up)
5578 quit ();
5579 else if (rs->got_ctrlc_during_io)
5580 {
5581 if (query (_("The target is not responding to GDB commands.\n"
5582 "Stop debugging it? ")))
5583 remote_unpush_and_throw (this);
5584 }
5585 /* If ^C has already been sent once, offer to disconnect. */
5586 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5587 interrupt_query ();
5588 /* All-stop protocol, and blocked waiting for stop reply. Send
5589 an interrupt request. */
5590 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5591 target_interrupt ();
5592 else
5593 rs->got_ctrlc_during_io = 1;
5594 }
5595 }
5596
5597 /* The remote_target that is current while the quit handler is
5598 overridden with remote_serial_quit_handler. */
5599 static remote_target *curr_quit_handler_target;
5600
5601 static void
5602 remote_serial_quit_handler ()
5603 {
5604 curr_quit_handler_target->remote_serial_quit_handler ();
5605 }
5606
5607 /* Remove the remote target from the target stack of each inferior
5608 that is using it. Upper targets depend on it so remove them
5609 first. */
5610
5611 static void
5612 remote_unpush_target (remote_target *target)
5613 {
5614 /* We have to unpush the target from all inferiors, even those that
5615 aren't running. */
5616 scoped_restore_current_inferior restore_current_inferior;
5617
5618 for (inferior *inf : all_inferiors (target))
5619 {
5620 switch_to_inferior_no_thread (inf);
5621 pop_all_targets_at_and_above (process_stratum);
5622 generic_mourn_inferior ();
5623 }
5624 }
5625
5626 static void
5627 remote_unpush_and_throw (remote_target *target)
5628 {
5629 remote_unpush_target (target);
5630 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5631 }
5632
5633 void
5634 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5635 {
5636 remote_target *curr_remote = get_current_remote_target ();
5637
5638 if (name == 0)
5639 error (_("To open a remote debug connection, you need to specify what\n"
5640 "serial device is attached to the remote system\n"
5641 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5642
5643 /* If we're connected to a running target, target_preopen will kill it.
5644 Ask this question first, before target_preopen has a chance to kill
5645 anything. */
5646 if (curr_remote != NULL && !target_has_execution ())
5647 {
5648 if (from_tty
5649 && !query (_("Already connected to a remote target. Disconnect? ")))
5650 error (_("Still connected."));
5651 }
5652
5653 /* Here the possibly existing remote target gets unpushed. */
5654 target_preopen (from_tty);
5655
5656 remote_fileio_reset ();
5657 reopen_exec_file ();
5658 reread_symbols ();
5659
5660 remote_target *remote
5661 = (extended_p ? new extended_remote_target () : new remote_target ());
5662 target_ops_up target_holder (remote);
5663
5664 remote_state *rs = remote->get_remote_state ();
5665
5666 /* See FIXME above. */
5667 if (!target_async_permitted)
5668 rs->wait_forever_enabled_p = 1;
5669
5670 rs->remote_desc = remote_serial_open (name);
5671 if (!rs->remote_desc)
5672 perror_with_name (name);
5673
5674 if (baud_rate != -1)
5675 {
5676 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5677 {
5678 /* The requested speed could not be set. Error out to
5679 top level after closing remote_desc. Take care to
5680 set remote_desc to NULL to avoid closing remote_desc
5681 more than once. */
5682 serial_close (rs->remote_desc);
5683 rs->remote_desc = NULL;
5684 perror_with_name (name);
5685 }
5686 }
5687
5688 serial_setparity (rs->remote_desc, serial_parity);
5689 serial_raw (rs->remote_desc);
5690
5691 /* If there is something sitting in the buffer we might take it as a
5692 response to a command, which would be bad. */
5693 serial_flush_input (rs->remote_desc);
5694
5695 if (from_tty)
5696 {
5697 puts_filtered ("Remote debugging using ");
5698 puts_filtered (name);
5699 puts_filtered ("\n");
5700 }
5701
5702 /* Switch to using the remote target now. */
5703 current_inferior ()->push_target (std::move (target_holder));
5704
5705 /* Register extra event sources in the event loop. */
5706 rs->remote_async_inferior_event_token
5707 = create_async_event_handler (remote_async_inferior_event_handler, nullptr,
5708 "remote");
5709 rs->notif_state = remote_notif_state_allocate (remote);
5710
5711 /* Reset the target state; these things will be queried either by
5712 remote_query_supported or as they are needed. */
5713 reset_all_packet_configs_support ();
5714 rs->cached_wait_status = 0;
5715 rs->explicit_packet_size = 0;
5716 rs->noack_mode = 0;
5717 rs->extended = extended_p;
5718 rs->waiting_for_stop_reply = 0;
5719 rs->ctrlc_pending_p = 0;
5720 rs->got_ctrlc_during_io = 0;
5721
5722 rs->general_thread = not_sent_ptid;
5723 rs->continue_thread = not_sent_ptid;
5724 rs->remote_traceframe_number = -1;
5725
5726 rs->last_resume_exec_dir = EXEC_FORWARD;
5727
5728 /* Probe for ability to use "ThreadInfo" query, as required. */
5729 rs->use_threadinfo_query = 1;
5730 rs->use_threadextra_query = 1;
5731
5732 rs->readahead_cache.invalidate ();
5733
5734 if (target_async_permitted)
5735 {
5736 /* FIXME: cagney/1999-09-23: During the initial connection it is
5737 assumed that the target is already ready and able to respond to
5738 requests. Unfortunately remote_start_remote() eventually calls
5739 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5740 around this. Eventually a mechanism that allows
5741 wait_for_inferior() to expect/get timeouts will be
5742 implemented. */
5743 rs->wait_forever_enabled_p = 0;
5744 }
5745
5746 /* First delete any symbols previously loaded from shared libraries. */
5747 no_shared_libraries (NULL, 0);
5748
5749 /* Start the remote connection. If error() or QUIT, discard this
5750 target (we'd otherwise be in an inconsistent state) and then
5751 propogate the error on up the exception chain. This ensures that
5752 the caller doesn't stumble along blindly assuming that the
5753 function succeeded. The CLI doesn't have this problem but other
5754 UI's, such as MI do.
5755
5756 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5757 this function should return an error indication letting the
5758 caller restore the previous state. Unfortunately the command
5759 ``target remote'' is directly wired to this function making that
5760 impossible. On a positive note, the CLI side of this problem has
5761 been fixed - the function set_cmd_context() makes it possible for
5762 all the ``target ....'' commands to share a common callback
5763 function. See cli-dump.c. */
5764 {
5765
5766 try
5767 {
5768 remote->start_remote (from_tty, extended_p);
5769 }
5770 catch (const gdb_exception &ex)
5771 {
5772 /* Pop the partially set up target - unless something else did
5773 already before throwing the exception. */
5774 if (ex.error != TARGET_CLOSE_ERROR)
5775 remote_unpush_target (remote);
5776 throw;
5777 }
5778 }
5779
5780 remote_btrace_reset (rs);
5781
5782 if (target_async_permitted)
5783 rs->wait_forever_enabled_p = 1;
5784 }
5785
5786 /* Detach the specified process. */
5787
5788 void
5789 remote_target::remote_detach_pid (int pid)
5790 {
5791 struct remote_state *rs = get_remote_state ();
5792
5793 /* This should not be necessary, but the handling for D;PID in
5794 GDBserver versions prior to 8.2 incorrectly assumes that the
5795 selected process points to the same process we're detaching,
5796 leading to misbehavior (and possibly GDBserver crashing) when it
5797 does not. Since it's easy and cheap, work around it by forcing
5798 GDBserver to select GDB's current process. */
5799 set_general_process ();
5800
5801 if (remote_multi_process_p (rs))
5802 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
5803 else
5804 strcpy (rs->buf.data (), "D");
5805
5806 putpkt (rs->buf);
5807 getpkt (&rs->buf, 0);
5808
5809 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5810 ;
5811 else if (rs->buf[0] == '\0')
5812 error (_("Remote doesn't know how to detach"));
5813 else
5814 error (_("Can't detach process."));
5815 }
5816
5817 /* This detaches a program to which we previously attached, using
5818 inferior_ptid to identify the process. After this is done, GDB
5819 can be used to debug some other program. We better not have left
5820 any breakpoints in the target program or it'll die when it hits
5821 one. */
5822
5823 void
5824 remote_target::remote_detach_1 (inferior *inf, int from_tty)
5825 {
5826 int pid = inferior_ptid.pid ();
5827 struct remote_state *rs = get_remote_state ();
5828 int is_fork_parent;
5829
5830 if (!target_has_execution ())
5831 error (_("No process to detach from."));
5832
5833 target_announce_detach (from_tty);
5834
5835 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
5836 {
5837 /* If we're in breakpoints-always-inserted mode, or the inferior
5838 is running, we have to remove breakpoints before detaching.
5839 We don't do this in common code instead because not all
5840 targets support removing breakpoints while the target is
5841 running. The remote target / gdbserver does, though. */
5842 remove_breakpoints_inf (current_inferior ());
5843 }
5844
5845 /* Tell the remote target to detach. */
5846 remote_detach_pid (pid);
5847
5848 /* Exit only if this is the only active inferior. */
5849 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
5850 puts_filtered (_("Ending remote debugging.\n"));
5851
5852 thread_info *tp = find_thread_ptid (this, inferior_ptid);
5853
5854 /* Check to see if we are detaching a fork parent. Note that if we
5855 are detaching a fork child, tp == NULL. */
5856 is_fork_parent = (tp != NULL
5857 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5858
5859 /* If doing detach-on-fork, we don't mourn, because that will delete
5860 breakpoints that should be available for the followed inferior. */
5861 if (!is_fork_parent)
5862 {
5863 /* Save the pid as a string before mourning, since that will
5864 unpush the remote target, and we need the string after. */
5865 std::string infpid = target_pid_to_str (ptid_t (pid));
5866
5867 target_mourn_inferior (inferior_ptid);
5868 if (print_inferior_events)
5869 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5870 inf->num, infpid.c_str ());
5871 }
5872 else
5873 {
5874 switch_to_no_thread ();
5875 detach_inferior (current_inferior ());
5876 }
5877 }
5878
5879 void
5880 remote_target::detach (inferior *inf, int from_tty)
5881 {
5882 remote_detach_1 (inf, from_tty);
5883 }
5884
5885 void
5886 extended_remote_target::detach (inferior *inf, int from_tty)
5887 {
5888 remote_detach_1 (inf, from_tty);
5889 }
5890
5891 /* Target follow-fork function for remote targets. On entry, and
5892 at return, the current inferior is the fork parent.
5893
5894 Note that although this is currently only used for extended-remote,
5895 it is named remote_follow_fork in anticipation of using it for the
5896 remote target as well. */
5897
5898 bool
5899 remote_target::follow_fork (bool follow_child, bool detach_fork)
5900 {
5901 struct remote_state *rs = get_remote_state ();
5902 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5903
5904 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5905 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5906 {
5907 /* When following the parent and detaching the child, we detach
5908 the child here. For the case of following the child and
5909 detaching the parent, the detach is done in the target-
5910 independent follow fork code in infrun.c. We can't use
5911 target_detach when detaching an unfollowed child because
5912 the client side doesn't know anything about the child. */
5913 if (detach_fork && !follow_child)
5914 {
5915 /* Detach the fork child. */
5916 ptid_t child_ptid;
5917 pid_t child_pid;
5918
5919 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5920 child_pid = child_ptid.pid ();
5921
5922 remote_detach_pid (child_pid);
5923 }
5924 }
5925
5926 return false;
5927 }
5928
5929 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5930 in the program space of the new inferior. On entry and at return the
5931 current inferior is the exec'ing inferior. INF is the new exec'd
5932 inferior, which may be the same as the exec'ing inferior unless
5933 follow-exec-mode is "new". */
5934
5935 void
5936 remote_target::follow_exec (struct inferior *inf, const char *execd_pathname)
5937 {
5938 /* We know that this is a target file name, so if it has the "target:"
5939 prefix we strip it off before saving it in the program space. */
5940 if (is_target_filename (execd_pathname))
5941 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5942
5943 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5944 }
5945
5946 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5947
5948 void
5949 remote_target::disconnect (const char *args, int from_tty)
5950 {
5951 if (args)
5952 error (_("Argument given to \"disconnect\" when remotely debugging."));
5953
5954 /* Make sure we unpush even the extended remote targets. Calling
5955 target_mourn_inferior won't unpush, and
5956 remote_target::mourn_inferior won't unpush if there is more than
5957 one inferior left. */
5958 remote_unpush_target (this);
5959
5960 if (from_tty)
5961 puts_filtered ("Ending remote debugging.\n");
5962 }
5963
5964 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5965 be chatty about it. */
5966
5967 void
5968 extended_remote_target::attach (const char *args, int from_tty)
5969 {
5970 struct remote_state *rs = get_remote_state ();
5971 int pid;
5972 char *wait_status = NULL;
5973
5974 pid = parse_pid_to_attach (args);
5975
5976 /* Remote PID can be freely equal to getpid, do not check it here the same
5977 way as in other targets. */
5978
5979 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5980 error (_("This target does not support attaching to a process"));
5981
5982 if (from_tty)
5983 {
5984 const char *exec_file = get_exec_file (0);
5985
5986 if (exec_file)
5987 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5988 target_pid_to_str (ptid_t (pid)).c_str ());
5989 else
5990 printf_unfiltered (_("Attaching to %s\n"),
5991 target_pid_to_str (ptid_t (pid)).c_str ());
5992 }
5993
5994 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
5995 putpkt (rs->buf);
5996 getpkt (&rs->buf, 0);
5997
5998 switch (packet_ok (rs->buf,
5999 &remote_protocol_packets[PACKET_vAttach]))
6000 {
6001 case PACKET_OK:
6002 if (!target_is_non_stop_p ())
6003 {
6004 /* Save the reply for later. */
6005 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6006 strcpy (wait_status, rs->buf.data ());
6007 }
6008 else if (strcmp (rs->buf.data (), "OK") != 0)
6009 error (_("Attaching to %s failed with: %s"),
6010 target_pid_to_str (ptid_t (pid)).c_str (),
6011 rs->buf.data ());
6012 break;
6013 case PACKET_UNKNOWN:
6014 error (_("This target does not support attaching to a process"));
6015 default:
6016 error (_("Attaching to %s failed"),
6017 target_pid_to_str (ptid_t (pid)).c_str ());
6018 }
6019
6020 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6021
6022 inferior_ptid = ptid_t (pid);
6023
6024 if (target_is_non_stop_p ())
6025 {
6026 /* Get list of threads. */
6027 update_thread_list ();
6028
6029 thread_info *thread = first_thread_of_inferior (current_inferior ());
6030 if (thread != nullptr)
6031 switch_to_thread (thread);
6032
6033 /* Invalidate our notion of the remote current thread. */
6034 record_currthread (rs, minus_one_ptid);
6035 }
6036 else
6037 {
6038 /* Now, if we have thread information, update the main thread's
6039 ptid. */
6040 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6041
6042 /* Add the main thread to the thread list. */
6043 thread_info *thr = add_thread_silent (this, curr_ptid);
6044
6045 switch_to_thread (thr);
6046
6047 /* Don't consider the thread stopped until we've processed the
6048 saved stop reply. */
6049 set_executing (this, thr->ptid, true);
6050 }
6051
6052 /* Next, if the target can specify a description, read it. We do
6053 this before anything involving memory or registers. */
6054 target_find_description ();
6055
6056 if (!target_is_non_stop_p ())
6057 {
6058 /* Use the previously fetched status. */
6059 gdb_assert (wait_status != NULL);
6060
6061 if (target_can_async_p ())
6062 {
6063 struct notif_event *reply
6064 = remote_notif_parse (this, &notif_client_stop, wait_status);
6065
6066 push_stop_reply ((struct stop_reply *) reply);
6067
6068 target_async (1);
6069 }
6070 else
6071 {
6072 gdb_assert (wait_status != NULL);
6073 strcpy (rs->buf.data (), wait_status);
6074 rs->cached_wait_status = 1;
6075 }
6076 }
6077 else
6078 {
6079 gdb_assert (wait_status == NULL);
6080
6081 gdb_assert (target_can_async_p ());
6082 target_async (1);
6083 }
6084 }
6085
6086 /* Implementation of the to_post_attach method. */
6087
6088 void
6089 extended_remote_target::post_attach (int pid)
6090 {
6091 /* Get text, data & bss offsets. */
6092 get_offsets ();
6093
6094 /* In certain cases GDB might not have had the chance to start
6095 symbol lookup up until now. This could happen if the debugged
6096 binary is not using shared libraries, the vsyscall page is not
6097 present (on Linux) and the binary itself hadn't changed since the
6098 debugging process was started. */
6099 if (current_program_space->symfile_object_file != NULL)
6100 remote_check_symbols();
6101 }
6102
6103 \f
6104 /* Check for the availability of vCont. This function should also check
6105 the response. */
6106
6107 void
6108 remote_target::remote_vcont_probe ()
6109 {
6110 remote_state *rs = get_remote_state ();
6111 char *buf;
6112
6113 strcpy (rs->buf.data (), "vCont?");
6114 putpkt (rs->buf);
6115 getpkt (&rs->buf, 0);
6116 buf = rs->buf.data ();
6117
6118 /* Make sure that the features we assume are supported. */
6119 if (startswith (buf, "vCont"))
6120 {
6121 char *p = &buf[5];
6122 int support_c, support_C;
6123
6124 rs->supports_vCont.s = 0;
6125 rs->supports_vCont.S = 0;
6126 support_c = 0;
6127 support_C = 0;
6128 rs->supports_vCont.t = 0;
6129 rs->supports_vCont.r = 0;
6130 while (p && *p == ';')
6131 {
6132 p++;
6133 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6134 rs->supports_vCont.s = 1;
6135 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6136 rs->supports_vCont.S = 1;
6137 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6138 support_c = 1;
6139 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6140 support_C = 1;
6141 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6142 rs->supports_vCont.t = 1;
6143 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6144 rs->supports_vCont.r = 1;
6145
6146 p = strchr (p, ';');
6147 }
6148
6149 /* If c, and C are not all supported, we can't use vCont. Clearing
6150 BUF will make packet_ok disable the packet. */
6151 if (!support_c || !support_C)
6152 buf[0] = 0;
6153 }
6154
6155 packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCont]);
6156 rs->supports_vCont_probed = true;
6157 }
6158
6159 /* Helper function for building "vCont" resumptions. Write a
6160 resumption to P. ENDP points to one-passed-the-end of the buffer
6161 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6162 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6163 resumed thread should be single-stepped and/or signalled. If PTID
6164 equals minus_one_ptid, then all threads are resumed; if PTID
6165 represents a process, then all threads of the process are resumed;
6166 the thread to be stepped and/or signalled is given in the global
6167 INFERIOR_PTID. */
6168
6169 char *
6170 remote_target::append_resumption (char *p, char *endp,
6171 ptid_t ptid, int step, gdb_signal siggnal)
6172 {
6173 struct remote_state *rs = get_remote_state ();
6174
6175 if (step && siggnal != GDB_SIGNAL_0)
6176 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6177 else if (step
6178 /* GDB is willing to range step. */
6179 && use_range_stepping
6180 /* Target supports range stepping. */
6181 && rs->supports_vCont.r
6182 /* We don't currently support range stepping multiple
6183 threads with a wildcard (though the protocol allows it,
6184 so stubs shouldn't make an active effort to forbid
6185 it). */
6186 && !(remote_multi_process_p (rs) && ptid.is_pid ()))
6187 {
6188 struct thread_info *tp;
6189
6190 if (ptid == minus_one_ptid)
6191 {
6192 /* If we don't know about the target thread's tid, then
6193 we're resuming magic_null_ptid (see caller). */
6194 tp = find_thread_ptid (this, magic_null_ptid);
6195 }
6196 else
6197 tp = find_thread_ptid (this, ptid);
6198 gdb_assert (tp != NULL);
6199
6200 if (tp->control.may_range_step)
6201 {
6202 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6203
6204 p += xsnprintf (p, endp - p, ";r%s,%s",
6205 phex_nz (tp->control.step_range_start,
6206 addr_size),
6207 phex_nz (tp->control.step_range_end,
6208 addr_size));
6209 }
6210 else
6211 p += xsnprintf (p, endp - p, ";s");
6212 }
6213 else if (step)
6214 p += xsnprintf (p, endp - p, ";s");
6215 else if (siggnal != GDB_SIGNAL_0)
6216 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6217 else
6218 p += xsnprintf (p, endp - p, ";c");
6219
6220 if (remote_multi_process_p (rs) && ptid.is_pid ())
6221 {
6222 ptid_t nptid;
6223
6224 /* All (-1) threads of process. */
6225 nptid = ptid_t (ptid.pid (), -1, 0);
6226
6227 p += xsnprintf (p, endp - p, ":");
6228 p = write_ptid (p, endp, nptid);
6229 }
6230 else if (ptid != minus_one_ptid)
6231 {
6232 p += xsnprintf (p, endp - p, ":");
6233 p = write_ptid (p, endp, ptid);
6234 }
6235
6236 return p;
6237 }
6238
6239 /* Clear the thread's private info on resume. */
6240
6241 static void
6242 resume_clear_thread_private_info (struct thread_info *thread)
6243 {
6244 if (thread->priv != NULL)
6245 {
6246 remote_thread_info *priv = get_remote_thread_info (thread);
6247
6248 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6249 priv->watch_data_address = 0;
6250 }
6251 }
6252
6253 /* Append a vCont continue-with-signal action for threads that have a
6254 non-zero stop signal. */
6255
6256 char *
6257 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6258 ptid_t ptid)
6259 {
6260 for (thread_info *thread : all_non_exited_threads (this, ptid))
6261 if (inferior_ptid != thread->ptid
6262 && thread->suspend.stop_signal != GDB_SIGNAL_0)
6263 {
6264 p = append_resumption (p, endp, thread->ptid,
6265 0, thread->suspend.stop_signal);
6266 thread->suspend.stop_signal = GDB_SIGNAL_0;
6267 resume_clear_thread_private_info (thread);
6268 }
6269
6270 return p;
6271 }
6272
6273 /* Set the target running, using the packets that use Hc
6274 (c/s/C/S). */
6275
6276 void
6277 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6278 gdb_signal siggnal)
6279 {
6280 struct remote_state *rs = get_remote_state ();
6281 char *buf;
6282
6283 rs->last_sent_signal = siggnal;
6284 rs->last_sent_step = step;
6285
6286 /* The c/s/C/S resume packets use Hc, so set the continue
6287 thread. */
6288 if (ptid == minus_one_ptid)
6289 set_continue_thread (any_thread_ptid);
6290 else
6291 set_continue_thread (ptid);
6292
6293 for (thread_info *thread : all_non_exited_threads (this))
6294 resume_clear_thread_private_info (thread);
6295
6296 buf = rs->buf.data ();
6297 if (::execution_direction == EXEC_REVERSE)
6298 {
6299 /* We don't pass signals to the target in reverse exec mode. */
6300 if (info_verbose && siggnal != GDB_SIGNAL_0)
6301 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6302 siggnal);
6303
6304 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6305 error (_("Remote reverse-step not supported."));
6306 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6307 error (_("Remote reverse-continue not supported."));
6308
6309 strcpy (buf, step ? "bs" : "bc");
6310 }
6311 else if (siggnal != GDB_SIGNAL_0)
6312 {
6313 buf[0] = step ? 'S' : 'C';
6314 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6315 buf[2] = tohex (((int) siggnal) & 0xf);
6316 buf[3] = '\0';
6317 }
6318 else
6319 strcpy (buf, step ? "s" : "c");
6320
6321 putpkt (buf);
6322 }
6323
6324 /* Resume the remote inferior by using a "vCont" packet. The thread
6325 to be resumed is PTID; STEP and SIGGNAL indicate whether the
6326 resumed thread should be single-stepped and/or signalled. If PTID
6327 equals minus_one_ptid, then all threads are resumed; the thread to
6328 be stepped and/or signalled is given in the global INFERIOR_PTID.
6329 This function returns non-zero iff it resumes the inferior.
6330
6331 This function issues a strict subset of all possible vCont commands
6332 at the moment. */
6333
6334 int
6335 remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6336 enum gdb_signal siggnal)
6337 {
6338 struct remote_state *rs = get_remote_state ();
6339 char *p;
6340 char *endp;
6341
6342 /* No reverse execution actions defined for vCont. */
6343 if (::execution_direction == EXEC_REVERSE)
6344 return 0;
6345
6346 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6347 remote_vcont_probe ();
6348
6349 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6350 return 0;
6351
6352 p = rs->buf.data ();
6353 endp = p + get_remote_packet_size ();
6354
6355 /* If we could generate a wider range of packets, we'd have to worry
6356 about overflowing BUF. Should there be a generic
6357 "multi-part-packet" packet? */
6358
6359 p += xsnprintf (p, endp - p, "vCont");
6360
6361 if (ptid == magic_null_ptid)
6362 {
6363 /* MAGIC_NULL_PTID means that we don't have any active threads,
6364 so we don't have any TID numbers the inferior will
6365 understand. Make sure to only send forms that do not specify
6366 a TID. */
6367 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6368 }
6369 else if (ptid == minus_one_ptid || ptid.is_pid ())
6370 {
6371 /* Resume all threads (of all processes, or of a single
6372 process), with preference for INFERIOR_PTID. This assumes
6373 inferior_ptid belongs to the set of all threads we are about
6374 to resume. */
6375 if (step || siggnal != GDB_SIGNAL_0)
6376 {
6377 /* Step inferior_ptid, with or without signal. */
6378 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6379 }
6380
6381 /* Also pass down any pending signaled resumption for other
6382 threads not the current. */
6383 p = append_pending_thread_resumptions (p, endp, ptid);
6384
6385 /* And continue others without a signal. */
6386 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
6387 }
6388 else
6389 {
6390 /* Scheduler locking; resume only PTID. */
6391 append_resumption (p, endp, ptid, step, siggnal);
6392 }
6393
6394 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6395 putpkt (rs->buf);
6396
6397 if (target_is_non_stop_p ())
6398 {
6399 /* In non-stop, the stub replies to vCont with "OK". The stop
6400 reply will be reported asynchronously by means of a `%Stop'
6401 notification. */
6402 getpkt (&rs->buf, 0);
6403 if (strcmp (rs->buf.data (), "OK") != 0)
6404 error (_("Unexpected vCont reply in non-stop mode: %s"),
6405 rs->buf.data ());
6406 }
6407
6408 return 1;
6409 }
6410
6411 /* Tell the remote machine to resume. */
6412
6413 void
6414 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
6415 {
6416 struct remote_state *rs = get_remote_state ();
6417
6418 /* When connected in non-stop mode, the core resumes threads
6419 individually. Resuming remote threads directly in target_resume
6420 would thus result in sending one packet per thread. Instead, to
6421 minimize roundtrip latency, here we just store the resume
6422 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6423 resumption will be done in remote_target::commit_resume, where we'll be
6424 able to do vCont action coalescing. */
6425 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6426 {
6427 remote_thread_info *remote_thr;
6428
6429 if (minus_one_ptid == ptid || ptid.is_pid ())
6430 remote_thr = get_remote_thread_info (this, inferior_ptid);
6431 else
6432 remote_thr = get_remote_thread_info (this, ptid);
6433
6434 /* We don't expect the core to ask to resume an already resumed (from
6435 its point of view) thread. */
6436 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6437
6438 remote_thr->set_resumed_pending_vcont (step, siggnal);
6439 return;
6440 }
6441
6442 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6443 (explained in remote-notif.c:handle_notification) so
6444 remote_notif_process is not called. We need find a place where
6445 it is safe to start a 'vNotif' sequence. It is good to do it
6446 before resuming inferior, because inferior was stopped and no RSP
6447 traffic at that moment. */
6448 if (!target_is_non_stop_p ())
6449 remote_notif_process (rs->notif_state, &notif_client_stop);
6450
6451 rs->last_resume_exec_dir = ::execution_direction;
6452
6453 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6454 if (!remote_resume_with_vcont (ptid, step, siggnal))
6455 remote_resume_with_hc (ptid, step, siggnal);
6456
6457 /* Update resumed state tracked by the remote target. */
6458 for (thread_info *tp : all_non_exited_threads (this, ptid))
6459 get_remote_thread_info (tp)->set_resumed ();
6460
6461 /* We are about to start executing the inferior, let's register it
6462 with the event loop. NOTE: this is the one place where all the
6463 execution commands end up. We could alternatively do this in each
6464 of the execution commands in infcmd.c. */
6465 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6466 into infcmd.c in order to allow inferior function calls to work
6467 NOT asynchronously. */
6468 if (target_can_async_p ())
6469 target_async (1);
6470
6471 /* We've just told the target to resume. The remote server will
6472 wait for the inferior to stop, and then send a stop reply. In
6473 the mean time, we can't start another command/query ourselves
6474 because the stub wouldn't be ready to process it. This applies
6475 only to the base all-stop protocol, however. In non-stop (which
6476 only supports vCont), the stub replies with an "OK", and is
6477 immediate able to process further serial input. */
6478 if (!target_is_non_stop_p ())
6479 rs->waiting_for_stop_reply = 1;
6480 }
6481
6482 static int is_pending_fork_parent_thread (struct thread_info *thread);
6483
6484 /* Private per-inferior info for target remote processes. */
6485
6486 struct remote_inferior : public private_inferior
6487 {
6488 /* Whether we can send a wildcard vCont for this process. */
6489 bool may_wildcard_vcont = true;
6490 };
6491
6492 /* Get the remote private inferior data associated to INF. */
6493
6494 static remote_inferior *
6495 get_remote_inferior (inferior *inf)
6496 {
6497 if (inf->priv == NULL)
6498 inf->priv.reset (new remote_inferior);
6499
6500 return static_cast<remote_inferior *> (inf->priv.get ());
6501 }
6502
6503 /* Class used to track the construction of a vCont packet in the
6504 outgoing packet buffer. This is used to send multiple vCont
6505 packets if we have more actions than would fit a single packet. */
6506
6507 class vcont_builder
6508 {
6509 public:
6510 explicit vcont_builder (remote_target *remote)
6511 : m_remote (remote)
6512 {
6513 restart ();
6514 }
6515
6516 void flush ();
6517 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6518
6519 private:
6520 void restart ();
6521
6522 /* The remote target. */
6523 remote_target *m_remote;
6524
6525 /* Pointer to the first action. P points here if no action has been
6526 appended yet. */
6527 char *m_first_action;
6528
6529 /* Where the next action will be appended. */
6530 char *m_p;
6531
6532 /* The end of the buffer. Must never write past this. */
6533 char *m_endp;
6534 };
6535
6536 /* Prepare the outgoing buffer for a new vCont packet. */
6537
6538 void
6539 vcont_builder::restart ()
6540 {
6541 struct remote_state *rs = m_remote->get_remote_state ();
6542
6543 m_p = rs->buf.data ();
6544 m_endp = m_p + m_remote->get_remote_packet_size ();
6545 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6546 m_first_action = m_p;
6547 }
6548
6549 /* If the vCont packet being built has any action, send it to the
6550 remote end. */
6551
6552 void
6553 vcont_builder::flush ()
6554 {
6555 struct remote_state *rs;
6556
6557 if (m_p == m_first_action)
6558 return;
6559
6560 rs = m_remote->get_remote_state ();
6561 m_remote->putpkt (rs->buf);
6562 m_remote->getpkt (&rs->buf, 0);
6563 if (strcmp (rs->buf.data (), "OK") != 0)
6564 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
6565 }
6566
6567 /* The largest action is range-stepping, with its two addresses. This
6568 is more than sufficient. If a new, bigger action is created, it'll
6569 quickly trigger a failed assertion in append_resumption (and we'll
6570 just bump this). */
6571 #define MAX_ACTION_SIZE 200
6572
6573 /* Append a new vCont action in the outgoing packet being built. If
6574 the action doesn't fit the packet along with previous actions, push
6575 what we've got so far to the remote end and start over a new vCont
6576 packet (with the new action). */
6577
6578 void
6579 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6580 {
6581 char buf[MAX_ACTION_SIZE + 1];
6582
6583 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6584 ptid, step, siggnal);
6585
6586 /* Check whether this new action would fit in the vCont packet along
6587 with previous actions. If not, send what we've got so far and
6588 start a new vCont packet. */
6589 size_t rsize = endp - buf;
6590 if (rsize > m_endp - m_p)
6591 {
6592 flush ();
6593 restart ();
6594
6595 /* Should now fit. */
6596 gdb_assert (rsize <= m_endp - m_p);
6597 }
6598
6599 memcpy (m_p, buf, rsize);
6600 m_p += rsize;
6601 *m_p = '\0';
6602 }
6603
6604 /* to_commit_resume implementation. */
6605
6606 void
6607 remote_target::commit_resume ()
6608 {
6609 int any_process_wildcard;
6610 int may_global_wildcard_vcont;
6611
6612 /* If connected in all-stop mode, we'd send the remote resume
6613 request directly from remote_resume. Likewise if
6614 reverse-debugging, as there are no defined vCont actions for
6615 reverse execution. */
6616 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6617 return;
6618
6619 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6620 instead of resuming all threads of each process individually.
6621 However, if any thread of a process must remain halted, we can't
6622 send wildcard resumes and must send one action per thread.
6623
6624 Care must be taken to not resume threads/processes the server
6625 side already told us are stopped, but the core doesn't know about
6626 yet, because the events are still in the vStopped notification
6627 queue. For example:
6628
6629 #1 => vCont s:p1.1;c
6630 #2 <= OK
6631 #3 <= %Stopped T05 p1.1
6632 #4 => vStopped
6633 #5 <= T05 p1.2
6634 #6 => vStopped
6635 #7 <= OK
6636 #8 (infrun handles the stop for p1.1 and continues stepping)
6637 #9 => vCont s:p1.1;c
6638
6639 The last vCont above would resume thread p1.2 by mistake, because
6640 the server has no idea that the event for p1.2 had not been
6641 handled yet.
6642
6643 The server side must similarly ignore resume actions for the
6644 thread that has a pending %Stopped notification (and any other
6645 threads with events pending), until GDB acks the notification
6646 with vStopped. Otherwise, e.g., the following case is
6647 mishandled:
6648
6649 #1 => g (or any other packet)
6650 #2 <= [registers]
6651 #3 <= %Stopped T05 p1.2
6652 #4 => vCont s:p1.1;c
6653 #5 <= OK
6654
6655 Above, the server must not resume thread p1.2. GDB can't know
6656 that p1.2 stopped until it acks the %Stopped notification, and
6657 since from GDB's perspective all threads should be running, it
6658 sends a "c" action.
6659
6660 Finally, special care must also be given to handling fork/vfork
6661 events. A (v)fork event actually tells us that two processes
6662 stopped -- the parent and the child. Until we follow the fork,
6663 we must not resume the child. Therefore, if we have a pending
6664 fork follow, we must not send a global wildcard resume action
6665 (vCont;c). We can still send process-wide wildcards though. */
6666
6667 /* Start by assuming a global wildcard (vCont;c) is possible. */
6668 may_global_wildcard_vcont = 1;
6669
6670 /* And assume every process is individually wildcard-able too. */
6671 for (inferior *inf : all_non_exited_inferiors (this))
6672 {
6673 remote_inferior *priv = get_remote_inferior (inf);
6674
6675 priv->may_wildcard_vcont = true;
6676 }
6677
6678 /* Check for any pending events (not reported or processed yet) and
6679 disable process and global wildcard resumes appropriately. */
6680 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6681
6682 for (thread_info *tp : all_non_exited_threads (this))
6683 {
6684 remote_thread_info *priv = get_remote_thread_info (tp);
6685
6686 /* If a thread of a process is not meant to be resumed, then we
6687 can't wildcard that process. */
6688 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
6689 {
6690 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6691
6692 /* And if we can't wildcard a process, we can't wildcard
6693 everything either. */
6694 may_global_wildcard_vcont = 0;
6695 continue;
6696 }
6697
6698 /* If a thread is the parent of an unfollowed fork, then we
6699 can't do a global wildcard, as that would resume the fork
6700 child. */
6701 if (is_pending_fork_parent_thread (tp))
6702 may_global_wildcard_vcont = 0;
6703 }
6704
6705 /* Now let's build the vCont packet(s). Actions must be appended
6706 from narrower to wider scopes (thread -> process -> global). If
6707 we end up with too many actions for a single packet vcont_builder
6708 flushes the current vCont packet to the remote side and starts a
6709 new one. */
6710 struct vcont_builder vcont_builder (this);
6711
6712 /* Threads first. */
6713 for (thread_info *tp : all_non_exited_threads (this))
6714 {
6715 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6716
6717 /* If the thread was previously vCont-resumed, no need to send a specific
6718 action for it. If we didn't receive a resume request for it, don't
6719 send an action for it either. */
6720 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
6721 continue;
6722
6723 gdb_assert (!thread_is_in_step_over_chain (tp));
6724
6725 const resumed_pending_vcont_info &info
6726 = remote_thr->resumed_pending_vcont_info ();
6727
6728 /* Check if we need to send a specific action for this thread. If not,
6729 it will be included in a wildcard resume instead. */
6730 if (info.step || info.sig != GDB_SIGNAL_0
6731 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
6732 vcont_builder.push_action (tp->ptid, info.step, info.sig);
6733
6734 remote_thr->set_resumed ();
6735 }
6736
6737 /* Now check whether we can send any process-wide wildcard. This is
6738 to avoid sending a global wildcard in the case nothing is
6739 supposed to be resumed. */
6740 any_process_wildcard = 0;
6741
6742 for (inferior *inf : all_non_exited_inferiors (this))
6743 {
6744 if (get_remote_inferior (inf)->may_wildcard_vcont)
6745 {
6746 any_process_wildcard = 1;
6747 break;
6748 }
6749 }
6750
6751 if (any_process_wildcard)
6752 {
6753 /* If all processes are wildcard-able, then send a single "c"
6754 action, otherwise, send an "all (-1) threads of process"
6755 continue action for each running process, if any. */
6756 if (may_global_wildcard_vcont)
6757 {
6758 vcont_builder.push_action (minus_one_ptid,
6759 false, GDB_SIGNAL_0);
6760 }
6761 else
6762 {
6763 for (inferior *inf : all_non_exited_inferiors (this))
6764 {
6765 if (get_remote_inferior (inf)->may_wildcard_vcont)
6766 {
6767 vcont_builder.push_action (ptid_t (inf->pid),
6768 false, GDB_SIGNAL_0);
6769 }
6770 }
6771 }
6772 }
6773
6774 vcont_builder.flush ();
6775 }
6776
6777 \f
6778
6779 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6780 thread, all threads of a remote process, or all threads of all
6781 processes. */
6782
6783 void
6784 remote_target::remote_stop_ns (ptid_t ptid)
6785 {
6786 struct remote_state *rs = get_remote_state ();
6787 char *p = rs->buf.data ();
6788 char *endp = p + get_remote_packet_size ();
6789
6790 /* FIXME: This supports_vCont_probed check is a workaround until
6791 packet_support is per-connection. */
6792 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN
6793 || !rs->supports_vCont_probed)
6794 remote_vcont_probe ();
6795
6796 if (!rs->supports_vCont.t)
6797 error (_("Remote server does not support stopping threads"));
6798
6799 if (ptid == minus_one_ptid
6800 || (!remote_multi_process_p (rs) && ptid.is_pid ()))
6801 p += xsnprintf (p, endp - p, "vCont;t");
6802 else
6803 {
6804 ptid_t nptid;
6805
6806 p += xsnprintf (p, endp - p, "vCont;t:");
6807
6808 if (ptid.is_pid ())
6809 /* All (-1) threads of process. */
6810 nptid = ptid_t (ptid.pid (), -1, 0);
6811 else
6812 {
6813 /* Small optimization: if we already have a stop reply for
6814 this thread, no use in telling the stub we want this
6815 stopped. */
6816 if (peek_stop_reply (ptid))
6817 return;
6818
6819 nptid = ptid;
6820 }
6821
6822 write_ptid (p, endp, nptid);
6823 }
6824
6825 /* In non-stop, we get an immediate OK reply. The stop reply will
6826 come in asynchronously by notification. */
6827 putpkt (rs->buf);
6828 getpkt (&rs->buf, 0);
6829 if (strcmp (rs->buf.data (), "OK") != 0)
6830 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
6831 rs->buf.data ());
6832 }
6833
6834 /* All-stop version of target_interrupt. Sends a break or a ^C to
6835 interrupt the remote target. It is undefined which thread of which
6836 process reports the interrupt. */
6837
6838 void
6839 remote_target::remote_interrupt_as ()
6840 {
6841 struct remote_state *rs = get_remote_state ();
6842
6843 rs->ctrlc_pending_p = 1;
6844
6845 /* If the inferior is stopped already, but the core didn't know
6846 about it yet, just ignore the request. The cached wait status
6847 will be collected in remote_wait. */
6848 if (rs->cached_wait_status)
6849 return;
6850
6851 /* Send interrupt_sequence to remote target. */
6852 send_interrupt_sequence ();
6853 }
6854
6855 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6856 the remote target. It is undefined which thread of which process
6857 reports the interrupt. Throws an error if the packet is not
6858 supported by the server. */
6859
6860 void
6861 remote_target::remote_interrupt_ns ()
6862 {
6863 struct remote_state *rs = get_remote_state ();
6864 char *p = rs->buf.data ();
6865 char *endp = p + get_remote_packet_size ();
6866
6867 xsnprintf (p, endp - p, "vCtrlC");
6868
6869 /* In non-stop, we get an immediate OK reply. The stop reply will
6870 come in asynchronously by notification. */
6871 putpkt (rs->buf);
6872 getpkt (&rs->buf, 0);
6873
6874 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6875 {
6876 case PACKET_OK:
6877 break;
6878 case PACKET_UNKNOWN:
6879 error (_("No support for interrupting the remote target."));
6880 case PACKET_ERROR:
6881 error (_("Interrupting target failed: %s"), rs->buf.data ());
6882 }
6883 }
6884
6885 /* Implement the to_stop function for the remote targets. */
6886
6887 void
6888 remote_target::stop (ptid_t ptid)
6889 {
6890 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
6891
6892 if (target_is_non_stop_p ())
6893 remote_stop_ns (ptid);
6894 else
6895 {
6896 /* We don't currently have a way to transparently pause the
6897 remote target in all-stop mode. Interrupt it instead. */
6898 remote_interrupt_as ();
6899 }
6900 }
6901
6902 /* Implement the to_interrupt function for the remote targets. */
6903
6904 void
6905 remote_target::interrupt ()
6906 {
6907 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
6908
6909 if (target_is_non_stop_p ())
6910 remote_interrupt_ns ();
6911 else
6912 remote_interrupt_as ();
6913 }
6914
6915 /* Implement the to_pass_ctrlc function for the remote targets. */
6916
6917 void
6918 remote_target::pass_ctrlc ()
6919 {
6920 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
6921
6922 struct remote_state *rs = get_remote_state ();
6923
6924 /* If we're starting up, we're not fully synced yet. Quit
6925 immediately. */
6926 if (rs->starting_up)
6927 quit ();
6928 /* If ^C has already been sent once, offer to disconnect. */
6929 else if (rs->ctrlc_pending_p)
6930 interrupt_query ();
6931 else
6932 target_interrupt ();
6933 }
6934
6935 /* Ask the user what to do when an interrupt is received. */
6936
6937 void
6938 remote_target::interrupt_query ()
6939 {
6940 struct remote_state *rs = get_remote_state ();
6941
6942 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6943 {
6944 if (query (_("The target is not responding to interrupt requests.\n"
6945 "Stop debugging it? ")))
6946 {
6947 remote_unpush_target (this);
6948 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6949 }
6950 }
6951 else
6952 {
6953 if (query (_("Interrupted while waiting for the program.\n"
6954 "Give up waiting? ")))
6955 quit ();
6956 }
6957 }
6958
6959 /* Enable/disable target terminal ownership. Most targets can use
6960 terminal groups to control terminal ownership. Remote targets are
6961 different in that explicit transfer of ownership to/from GDB/target
6962 is required. */
6963
6964 void
6965 remote_target::terminal_inferior ()
6966 {
6967 /* NOTE: At this point we could also register our selves as the
6968 recipient of all input. Any characters typed could then be
6969 passed on down to the target. */
6970 }
6971
6972 void
6973 remote_target::terminal_ours ()
6974 {
6975 }
6976
6977 static void
6978 remote_console_output (const char *msg)
6979 {
6980 const char *p;
6981
6982 for (p = msg; p[0] && p[1]; p += 2)
6983 {
6984 char tb[2];
6985 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6986
6987 tb[0] = c;
6988 tb[1] = 0;
6989 gdb_stdtarg->puts (tb);
6990 }
6991 gdb_stdtarg->flush ();
6992 }
6993
6994 struct stop_reply : public notif_event
6995 {
6996 ~stop_reply ();
6997
6998 /* The identifier of the thread about this event */
6999 ptid_t ptid;
7000
7001 /* The remote state this event is associated with. When the remote
7002 connection, represented by a remote_state object, is closed,
7003 all the associated stop_reply events should be released. */
7004 struct remote_state *rs;
7005
7006 struct target_waitstatus ws;
7007
7008 /* The architecture associated with the expedited registers. */
7009 gdbarch *arch;
7010
7011 /* Expedited registers. This makes remote debugging a bit more
7012 efficient for those targets that provide critical registers as
7013 part of their normal status mechanism (as another roundtrip to
7014 fetch them is avoided). */
7015 std::vector<cached_reg_t> regcache;
7016
7017 enum target_stop_reason stop_reason;
7018
7019 CORE_ADDR watch_data_address;
7020
7021 int core;
7022 };
7023
7024 /* Return the length of the stop reply queue. */
7025
7026 int
7027 remote_target::stop_reply_queue_length ()
7028 {
7029 remote_state *rs = get_remote_state ();
7030 return rs->stop_reply_queue.size ();
7031 }
7032
7033 static void
7034 remote_notif_stop_parse (remote_target *remote,
7035 struct notif_client *self, const char *buf,
7036 struct notif_event *event)
7037 {
7038 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7039 }
7040
7041 static void
7042 remote_notif_stop_ack (remote_target *remote,
7043 struct notif_client *self, const char *buf,
7044 struct notif_event *event)
7045 {
7046 struct stop_reply *stop_reply = (struct stop_reply *) event;
7047
7048 /* acknowledge */
7049 putpkt (remote, self->ack_command);
7050
7051 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7052 the notification. It was left in the queue because we need to
7053 acknowledge it and pull the rest of the notifications out. */
7054 if (stop_reply->ws.kind != TARGET_WAITKIND_IGNORE)
7055 remote->push_stop_reply (stop_reply);
7056 }
7057
7058 static int
7059 remote_notif_stop_can_get_pending_events (remote_target *remote,
7060 struct notif_client *self)
7061 {
7062 /* We can't get pending events in remote_notif_process for
7063 notification stop, and we have to do this in remote_wait_ns
7064 instead. If we fetch all queued events from stub, remote stub
7065 may exit and we have no chance to process them back in
7066 remote_wait_ns. */
7067 remote_state *rs = remote->get_remote_state ();
7068 mark_async_event_handler (rs->remote_async_inferior_event_token);
7069 return 0;
7070 }
7071
7072 stop_reply::~stop_reply ()
7073 {
7074 for (cached_reg_t &reg : regcache)
7075 xfree (reg.data);
7076 }
7077
7078 static notif_event_up
7079 remote_notif_stop_alloc_reply ()
7080 {
7081 return notif_event_up (new struct stop_reply ());
7082 }
7083
7084 /* A client of notification Stop. */
7085
7086 struct notif_client notif_client_stop =
7087 {
7088 "Stop",
7089 "vStopped",
7090 remote_notif_stop_parse,
7091 remote_notif_stop_ack,
7092 remote_notif_stop_can_get_pending_events,
7093 remote_notif_stop_alloc_reply,
7094 REMOTE_NOTIF_STOP,
7095 };
7096
7097 /* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
7098 the pid of the process that owns the threads we want to check, or
7099 -1 if we want to check all threads. */
7100
7101 static int
7102 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
7103 ptid_t thread_ptid)
7104 {
7105 if (ws->kind == TARGET_WAITKIND_FORKED
7106 || ws->kind == TARGET_WAITKIND_VFORKED)
7107 {
7108 if (event_pid == -1 || event_pid == thread_ptid.pid ())
7109 return 1;
7110 }
7111
7112 return 0;
7113 }
7114
7115 /* Return the thread's pending status used to determine whether the
7116 thread is a fork parent stopped at a fork event. */
7117
7118 static struct target_waitstatus *
7119 thread_pending_fork_status (struct thread_info *thread)
7120 {
7121 if (thread->suspend.waitstatus_pending_p)
7122 return &thread->suspend.waitstatus;
7123 else
7124 return &thread->pending_follow;
7125 }
7126
7127 /* Determine if THREAD is a pending fork parent thread. */
7128
7129 static int
7130 is_pending_fork_parent_thread (struct thread_info *thread)
7131 {
7132 struct target_waitstatus *ws = thread_pending_fork_status (thread);
7133 int pid = -1;
7134
7135 return is_pending_fork_parent (ws, pid, thread->ptid);
7136 }
7137
7138 /* If CONTEXT contains any fork child threads that have not been
7139 reported yet, remove them from the CONTEXT list. If such a
7140 thread exists it is because we are stopped at a fork catchpoint
7141 and have not yet called follow_fork, which will set up the
7142 host-side data structures for the new process. */
7143
7144 void
7145 remote_target::remove_new_fork_children (threads_listing_context *context)
7146 {
7147 int pid = -1;
7148 struct notif_client *notif = &notif_client_stop;
7149
7150 /* For any threads stopped at a fork event, remove the corresponding
7151 fork child threads from the CONTEXT list. */
7152 for (thread_info *thread : all_non_exited_threads (this))
7153 {
7154 struct target_waitstatus *ws = thread_pending_fork_status (thread);
7155
7156 if (is_pending_fork_parent (ws, pid, thread->ptid))
7157 context->remove_thread (ws->value.related_pid);
7158 }
7159
7160 /* Check for any pending fork events (not reported or processed yet)
7161 in process PID and remove those fork child threads from the
7162 CONTEXT list as well. */
7163 remote_notif_get_pending_events (notif);
7164 for (auto &event : get_remote_state ()->stop_reply_queue)
7165 if (event->ws.kind == TARGET_WAITKIND_FORKED
7166 || event->ws.kind == TARGET_WAITKIND_VFORKED
7167 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
7168 context->remove_thread (event->ws.value.related_pid);
7169 }
7170
7171 /* Check whether any event pending in the vStopped queue would prevent
7172 a global or process wildcard vCont action. Clear
7173 *may_global_wildcard if we can't do a global wildcard (vCont;c),
7174 and clear the event inferior's may_wildcard_vcont flag if we can't
7175 do a process-wide wildcard resume (vCont;c:pPID.-1). */
7176
7177 void
7178 remote_target::check_pending_events_prevent_wildcard_vcont
7179 (int *may_global_wildcard)
7180 {
7181 struct notif_client *notif = &notif_client_stop;
7182
7183 remote_notif_get_pending_events (notif);
7184 for (auto &event : get_remote_state ()->stop_reply_queue)
7185 {
7186 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
7187 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
7188 continue;
7189
7190 if (event->ws.kind == TARGET_WAITKIND_FORKED
7191 || event->ws.kind == TARGET_WAITKIND_VFORKED)
7192 *may_global_wildcard = 0;
7193
7194 struct inferior *inf = find_inferior_ptid (this, event->ptid);
7195
7196 /* This may be the first time we heard about this process.
7197 Regardless, we must not do a global wildcard resume, otherwise
7198 we'd resume this process too. */
7199 *may_global_wildcard = 0;
7200 if (inf != NULL)
7201 get_remote_inferior (inf)->may_wildcard_vcont = false;
7202 }
7203 }
7204
7205 /* Discard all pending stop replies of inferior INF. */
7206
7207 void
7208 remote_target::discard_pending_stop_replies (struct inferior *inf)
7209 {
7210 struct stop_reply *reply;
7211 struct remote_state *rs = get_remote_state ();
7212 struct remote_notif_state *rns = rs->notif_state;
7213
7214 /* This function can be notified when an inferior exists. When the
7215 target is not remote, the notification state is NULL. */
7216 if (rs->remote_desc == NULL)
7217 return;
7218
7219 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7220
7221 /* Discard the in-flight notification. */
7222 if (reply != NULL && reply->ptid.pid () == inf->pid)
7223 {
7224 /* Leave the notification pending, since the server expects that
7225 we acknowledge it with vStopped. But clear its contents, so
7226 that later on when we acknowledge it, we also discard it. */
7227 reply->ws.kind = TARGET_WAITKIND_IGNORE;
7228
7229 if (remote_debug)
7230 fprintf_unfiltered (gdb_stdlog,
7231 "discarded in-flight notification\n");
7232 }
7233
7234 /* Discard the stop replies we have already pulled with
7235 vStopped. */
7236 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7237 rs->stop_reply_queue.end (),
7238 [=] (const stop_reply_up &event)
7239 {
7240 return event->ptid.pid () == inf->pid;
7241 });
7242 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7243 }
7244
7245 /* Discard the stop replies for RS in stop_reply_queue. */
7246
7247 void
7248 remote_target::discard_pending_stop_replies_in_queue ()
7249 {
7250 remote_state *rs = get_remote_state ();
7251
7252 /* Discard the stop replies we have already pulled with
7253 vStopped. */
7254 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7255 rs->stop_reply_queue.end (),
7256 [=] (const stop_reply_up &event)
7257 {
7258 return event->rs == rs;
7259 });
7260 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7261 }
7262
7263 /* Remove the first reply in 'stop_reply_queue' which matches
7264 PTID. */
7265
7266 struct stop_reply *
7267 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7268 {
7269 remote_state *rs = get_remote_state ();
7270
7271 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7272 rs->stop_reply_queue.end (),
7273 [=] (const stop_reply_up &event)
7274 {
7275 return event->ptid.matches (ptid);
7276 });
7277 struct stop_reply *result;
7278 if (iter == rs->stop_reply_queue.end ())
7279 result = nullptr;
7280 else
7281 {
7282 result = iter->release ();
7283 rs->stop_reply_queue.erase (iter);
7284 }
7285
7286 if (notif_debug)
7287 fprintf_unfiltered (gdb_stdlog,
7288 "notif: discard queued event: 'Stop' in %s\n",
7289 target_pid_to_str (ptid).c_str ());
7290
7291 return result;
7292 }
7293
7294 /* Look for a queued stop reply belonging to PTID. If one is found,
7295 remove it from the queue, and return it. Returns NULL if none is
7296 found. If there are still queued events left to process, tell the
7297 event loop to get back to target_wait soon. */
7298
7299 struct stop_reply *
7300 remote_target::queued_stop_reply (ptid_t ptid)
7301 {
7302 remote_state *rs = get_remote_state ();
7303 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7304
7305 if (!rs->stop_reply_queue.empty ())
7306 {
7307 /* There's still at least an event left. */
7308 mark_async_event_handler (rs->remote_async_inferior_event_token);
7309 }
7310
7311 return r;
7312 }
7313
7314 /* Push a fully parsed stop reply in the stop reply queue. Since we
7315 know that we now have at least one queued event left to pass to the
7316 core side, tell the event loop to get back to target_wait soon. */
7317
7318 void
7319 remote_target::push_stop_reply (struct stop_reply *new_event)
7320 {
7321 remote_state *rs = get_remote_state ();
7322 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7323
7324 if (notif_debug)
7325 fprintf_unfiltered (gdb_stdlog,
7326 "notif: push 'Stop' %s to queue %d\n",
7327 target_pid_to_str (new_event->ptid).c_str (),
7328 int (rs->stop_reply_queue.size ()));
7329
7330 mark_async_event_handler (rs->remote_async_inferior_event_token);
7331 }
7332
7333 /* Returns true if we have a stop reply for PTID. */
7334
7335 int
7336 remote_target::peek_stop_reply (ptid_t ptid)
7337 {
7338 remote_state *rs = get_remote_state ();
7339 for (auto &event : rs->stop_reply_queue)
7340 if (ptid == event->ptid
7341 && event->ws.kind == TARGET_WAITKIND_STOPPED)
7342 return 1;
7343 return 0;
7344 }
7345
7346 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7347 starting with P and ending with PEND matches PREFIX. */
7348
7349 static int
7350 strprefix (const char *p, const char *pend, const char *prefix)
7351 {
7352 for ( ; p < pend; p++, prefix++)
7353 if (*p != *prefix)
7354 return 0;
7355 return *prefix == '\0';
7356 }
7357
7358 /* Parse the stop reply in BUF. Either the function succeeds, and the
7359 result is stored in EVENT, or throws an error. */
7360
7361 void
7362 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7363 {
7364 remote_arch_state *rsa = NULL;
7365 ULONGEST addr;
7366 const char *p;
7367 int skipregs = 0;
7368
7369 event->ptid = null_ptid;
7370 event->rs = get_remote_state ();
7371 event->ws.kind = TARGET_WAITKIND_IGNORE;
7372 event->ws.value.integer = 0;
7373 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7374 event->regcache.clear ();
7375 event->core = -1;
7376
7377 switch (buf[0])
7378 {
7379 case 'T': /* Status with PC, SP, FP, ... */
7380 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7381 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7382 ss = signal number
7383 n... = register number
7384 r... = register contents
7385 */
7386
7387 p = &buf[3]; /* after Txx */
7388 while (*p)
7389 {
7390 const char *p1;
7391 int fieldsize;
7392
7393 p1 = strchr (p, ':');
7394 if (p1 == NULL)
7395 error (_("Malformed packet(a) (missing colon): %s\n\
7396 Packet: '%s'\n"),
7397 p, buf);
7398 if (p == p1)
7399 error (_("Malformed packet(a) (missing register number): %s\n\
7400 Packet: '%s'\n"),
7401 p, buf);
7402
7403 /* Some "registers" are actually extended stop information.
7404 Note if you're adding a new entry here: GDB 7.9 and
7405 earlier assume that all register "numbers" that start
7406 with an hex digit are real register numbers. Make sure
7407 the server only sends such a packet if it knows the
7408 client understands it. */
7409
7410 if (strprefix (p, p1, "thread"))
7411 event->ptid = read_ptid (++p1, &p);
7412 else if (strprefix (p, p1, "syscall_entry"))
7413 {
7414 ULONGEST sysno;
7415
7416 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7417 p = unpack_varlen_hex (++p1, &sysno);
7418 event->ws.value.syscall_number = (int) sysno;
7419 }
7420 else if (strprefix (p, p1, "syscall_return"))
7421 {
7422 ULONGEST sysno;
7423
7424 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7425 p = unpack_varlen_hex (++p1, &sysno);
7426 event->ws.value.syscall_number = (int) sysno;
7427 }
7428 else if (strprefix (p, p1, "watch")
7429 || strprefix (p, p1, "rwatch")
7430 || strprefix (p, p1, "awatch"))
7431 {
7432 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7433 p = unpack_varlen_hex (++p1, &addr);
7434 event->watch_data_address = (CORE_ADDR) addr;
7435 }
7436 else if (strprefix (p, p1, "swbreak"))
7437 {
7438 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7439
7440 /* Make sure the stub doesn't forget to indicate support
7441 with qSupported. */
7442 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7443 error (_("Unexpected swbreak stop reason"));
7444
7445 /* The value part is documented as "must be empty",
7446 though we ignore it, in case we ever decide to make
7447 use of it in a backward compatible way. */
7448 p = strchrnul (p1 + 1, ';');
7449 }
7450 else if (strprefix (p, p1, "hwbreak"))
7451 {
7452 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7453
7454 /* Make sure the stub doesn't forget to indicate support
7455 with qSupported. */
7456 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7457 error (_("Unexpected hwbreak stop reason"));
7458
7459 /* See above. */
7460 p = strchrnul (p1 + 1, ';');
7461 }
7462 else if (strprefix (p, p1, "library"))
7463 {
7464 event->ws.kind = TARGET_WAITKIND_LOADED;
7465 p = strchrnul (p1 + 1, ';');
7466 }
7467 else if (strprefix (p, p1, "replaylog"))
7468 {
7469 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7470 /* p1 will indicate "begin" or "end", but it makes
7471 no difference for now, so ignore it. */
7472 p = strchrnul (p1 + 1, ';');
7473 }
7474 else if (strprefix (p, p1, "core"))
7475 {
7476 ULONGEST c;
7477
7478 p = unpack_varlen_hex (++p1, &c);
7479 event->core = c;
7480 }
7481 else if (strprefix (p, p1, "fork"))
7482 {
7483 event->ws.value.related_pid = read_ptid (++p1, &p);
7484 event->ws.kind = TARGET_WAITKIND_FORKED;
7485 }
7486 else if (strprefix (p, p1, "vfork"))
7487 {
7488 event->ws.value.related_pid = read_ptid (++p1, &p);
7489 event->ws.kind = TARGET_WAITKIND_VFORKED;
7490 }
7491 else if (strprefix (p, p1, "vforkdone"))
7492 {
7493 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
7494 p = strchrnul (p1 + 1, ';');
7495 }
7496 else if (strprefix (p, p1, "exec"))
7497 {
7498 ULONGEST ignored;
7499 int pathlen;
7500
7501 /* Determine the length of the execd pathname. */
7502 p = unpack_varlen_hex (++p1, &ignored);
7503 pathlen = (p - p1) / 2;
7504
7505 /* Save the pathname for event reporting and for
7506 the next run command. */
7507 gdb::unique_xmalloc_ptr<char[]> pathname
7508 ((char *) xmalloc (pathlen + 1));
7509 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
7510 pathname[pathlen] = '\0';
7511
7512 /* This is freed during event handling. */
7513 event->ws.value.execd_pathname = pathname.release ();
7514 event->ws.kind = TARGET_WAITKIND_EXECD;
7515
7516 /* Skip the registers included in this packet, since
7517 they may be for an architecture different from the
7518 one used by the original program. */
7519 skipregs = 1;
7520 }
7521 else if (strprefix (p, p1, "create"))
7522 {
7523 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
7524 p = strchrnul (p1 + 1, ';');
7525 }
7526 else
7527 {
7528 ULONGEST pnum;
7529 const char *p_temp;
7530
7531 if (skipregs)
7532 {
7533 p = strchrnul (p1 + 1, ';');
7534 p++;
7535 continue;
7536 }
7537
7538 /* Maybe a real ``P'' register number. */
7539 p_temp = unpack_varlen_hex (p, &pnum);
7540 /* If the first invalid character is the colon, we got a
7541 register number. Otherwise, it's an unknown stop
7542 reason. */
7543 if (p_temp == p1)
7544 {
7545 /* If we haven't parsed the event's thread yet, find
7546 it now, in order to find the architecture of the
7547 reported expedited registers. */
7548 if (event->ptid == null_ptid)
7549 {
7550 /* If there is no thread-id information then leave
7551 the event->ptid as null_ptid. Later in
7552 process_stop_reply we will pick a suitable
7553 thread. */
7554 const char *thr = strstr (p1 + 1, ";thread:");
7555 if (thr != NULL)
7556 event->ptid = read_ptid (thr + strlen (";thread:"),
7557 NULL);
7558 }
7559
7560 if (rsa == NULL)
7561 {
7562 inferior *inf
7563 = (event->ptid == null_ptid
7564 ? NULL
7565 : find_inferior_ptid (this, event->ptid));
7566 /* If this is the first time we learn anything
7567 about this process, skip the registers
7568 included in this packet, since we don't yet
7569 know which architecture to use to parse them.
7570 We'll determine the architecture later when
7571 we process the stop reply and retrieve the
7572 target description, via
7573 remote_notice_new_inferior ->
7574 post_create_inferior. */
7575 if (inf == NULL)
7576 {
7577 p = strchrnul (p1 + 1, ';');
7578 p++;
7579 continue;
7580 }
7581
7582 event->arch = inf->gdbarch;
7583 rsa = event->rs->get_remote_arch_state (event->arch);
7584 }
7585
7586 packet_reg *reg
7587 = packet_reg_from_pnum (event->arch, rsa, pnum);
7588 cached_reg_t cached_reg;
7589
7590 if (reg == NULL)
7591 error (_("Remote sent bad register number %s: %s\n\
7592 Packet: '%s'\n"),
7593 hex_string (pnum), p, buf);
7594
7595 cached_reg.num = reg->regnum;
7596 cached_reg.data = (gdb_byte *)
7597 xmalloc (register_size (event->arch, reg->regnum));
7598
7599 p = p1 + 1;
7600 fieldsize = hex2bin (p, cached_reg.data,
7601 register_size (event->arch, reg->regnum));
7602 p += 2 * fieldsize;
7603 if (fieldsize < register_size (event->arch, reg->regnum))
7604 warning (_("Remote reply is too short: %s"), buf);
7605
7606 event->regcache.push_back (cached_reg);
7607 }
7608 else
7609 {
7610 /* Not a number. Silently skip unknown optional
7611 info. */
7612 p = strchrnul (p1 + 1, ';');
7613 }
7614 }
7615
7616 if (*p != ';')
7617 error (_("Remote register badly formatted: %s\nhere: %s"),
7618 buf, p);
7619 ++p;
7620 }
7621
7622 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7623 break;
7624
7625 /* fall through */
7626 case 'S': /* Old style status, just signal only. */
7627 {
7628 int sig;
7629
7630 event->ws.kind = TARGET_WAITKIND_STOPPED;
7631 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7632 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7633 event->ws.value.sig = (enum gdb_signal) sig;
7634 else
7635 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7636 }
7637 break;
7638 case 'w': /* Thread exited. */
7639 {
7640 ULONGEST value;
7641
7642 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7643 p = unpack_varlen_hex (&buf[1], &value);
7644 event->ws.value.integer = value;
7645 if (*p != ';')
7646 error (_("stop reply packet badly formatted: %s"), buf);
7647 event->ptid = read_ptid (++p, NULL);
7648 break;
7649 }
7650 case 'W': /* Target exited. */
7651 case 'X':
7652 {
7653 ULONGEST value;
7654
7655 /* GDB used to accept only 2 hex chars here. Stubs should
7656 only send more if they detect GDB supports multi-process
7657 support. */
7658 p = unpack_varlen_hex (&buf[1], &value);
7659
7660 if (buf[0] == 'W')
7661 {
7662 /* The remote process exited. */
7663 event->ws.kind = TARGET_WAITKIND_EXITED;
7664 event->ws.value.integer = value;
7665 }
7666 else
7667 {
7668 /* The remote process exited with a signal. */
7669 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7670 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7671 event->ws.value.sig = (enum gdb_signal) value;
7672 else
7673 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7674 }
7675
7676 /* If no process is specified, return null_ptid, and let the
7677 caller figure out the right process to use. */
7678 int pid = 0;
7679 if (*p == '\0')
7680 ;
7681 else if (*p == ';')
7682 {
7683 p++;
7684
7685 if (*p == '\0')
7686 ;
7687 else if (startswith (p, "process:"))
7688 {
7689 ULONGEST upid;
7690
7691 p += sizeof ("process:") - 1;
7692 unpack_varlen_hex (p, &upid);
7693 pid = upid;
7694 }
7695 else
7696 error (_("unknown stop reply packet: %s"), buf);
7697 }
7698 else
7699 error (_("unknown stop reply packet: %s"), buf);
7700 event->ptid = ptid_t (pid);
7701 }
7702 break;
7703 case 'N':
7704 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7705 event->ptid = minus_one_ptid;
7706 break;
7707 }
7708 }
7709
7710 /* When the stub wants to tell GDB about a new notification reply, it
7711 sends a notification (%Stop, for example). Those can come it at
7712 any time, hence, we have to make sure that any pending
7713 putpkt/getpkt sequence we're making is finished, before querying
7714 the stub for more events with the corresponding ack command
7715 (vStopped, for example). E.g., if we started a vStopped sequence
7716 immediately upon receiving the notification, something like this
7717 could happen:
7718
7719 1.1) --> Hg 1
7720 1.2) <-- OK
7721 1.3) --> g
7722 1.4) <-- %Stop
7723 1.5) --> vStopped
7724 1.6) <-- (registers reply to step #1.3)
7725
7726 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7727 query.
7728
7729 To solve this, whenever we parse a %Stop notification successfully,
7730 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7731 doing whatever we were doing:
7732
7733 2.1) --> Hg 1
7734 2.2) <-- OK
7735 2.3) --> g
7736 2.4) <-- %Stop
7737 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7738 2.5) <-- (registers reply to step #2.3)
7739
7740 Eventually after step #2.5, we return to the event loop, which
7741 notices there's an event on the
7742 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7743 associated callback --- the function below. At this point, we're
7744 always safe to start a vStopped sequence. :
7745
7746 2.6) --> vStopped
7747 2.7) <-- T05 thread:2
7748 2.8) --> vStopped
7749 2.9) --> OK
7750 */
7751
7752 void
7753 remote_target::remote_notif_get_pending_events (notif_client *nc)
7754 {
7755 struct remote_state *rs = get_remote_state ();
7756
7757 if (rs->notif_state->pending_event[nc->id] != NULL)
7758 {
7759 if (notif_debug)
7760 fprintf_unfiltered (gdb_stdlog,
7761 "notif: process: '%s' ack pending event\n",
7762 nc->name);
7763
7764 /* acknowledge */
7765 nc->ack (this, nc, rs->buf.data (),
7766 rs->notif_state->pending_event[nc->id]);
7767 rs->notif_state->pending_event[nc->id] = NULL;
7768
7769 while (1)
7770 {
7771 getpkt (&rs->buf, 0);
7772 if (strcmp (rs->buf.data (), "OK") == 0)
7773 break;
7774 else
7775 remote_notif_ack (this, nc, rs->buf.data ());
7776 }
7777 }
7778 else
7779 {
7780 if (notif_debug)
7781 fprintf_unfiltered (gdb_stdlog,
7782 "notif: process: '%s' no pending reply\n",
7783 nc->name);
7784 }
7785 }
7786
7787 /* Wrapper around remote_target::remote_notif_get_pending_events to
7788 avoid having to export the whole remote_target class. */
7789
7790 void
7791 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7792 {
7793 remote->remote_notif_get_pending_events (nc);
7794 }
7795
7796 /* Called from process_stop_reply when the stop packet we are responding
7797 to didn't include a process-id or thread-id. STATUS is the stop event
7798 we are responding to.
7799
7800 It is the task of this function to select a suitable thread (or process)
7801 and return its ptid, this is the thread (or process) we will assume the
7802 stop event came from.
7803
7804 In some cases there isn't really any choice about which thread (or
7805 process) is selected, a basic remote with a single process containing a
7806 single thread might choose not to send any process-id or thread-id in
7807 its stop packets, this function will select and return the one and only
7808 thread.
7809
7810 However, if a target supports multiple threads (or processes) and still
7811 doesn't include a thread-id (or process-id) in its stop packet then
7812 first, this is a badly behaving target, and second, we're going to have
7813 to select a thread (or process) at random and use that. This function
7814 will print a warning to the user if it detects that there is the
7815 possibility that GDB is guessing which thread (or process) to
7816 report.
7817
7818 Note that this is called before GDB fetches the updated thread list from the
7819 target. So it's possible for the stop reply to be ambiguous and for GDB to
7820 not realize it. For example, if there's initially one thread, the target
7821 spawns a second thread, and then sends a stop reply without an id that
7822 concerns the first thread. GDB will assume the stop reply is about the
7823 first thread - the only thread it knows about - without printing a warning.
7824 Anyway, if the remote meant for the stop reply to be about the second thread,
7825 then it would be really broken, because GDB doesn't know about that thread
7826 yet. */
7827
7828 ptid_t
7829 remote_target::select_thread_for_ambiguous_stop_reply
7830 (const struct target_waitstatus *status)
7831 {
7832 /* Some stop events apply to all threads in an inferior, while others
7833 only apply to a single thread. */
7834 bool process_wide_stop
7835 = (status->kind == TARGET_WAITKIND_EXITED
7836 || status->kind == TARGET_WAITKIND_SIGNALLED);
7837
7838 thread_info *first_resumed_thread = nullptr;
7839 bool ambiguous = false;
7840
7841 /* Consider all non-exited threads of the target, find the first resumed
7842 one. */
7843 for (thread_info *thr : all_non_exited_threads (this))
7844 {
7845 remote_thread_info *remote_thr = get_remote_thread_info (thr);
7846
7847 if (remote_thr->get_resume_state () != resume_state::RESUMED)
7848 continue;
7849
7850 if (first_resumed_thread == nullptr)
7851 first_resumed_thread = thr;
7852 else if (!process_wide_stop
7853 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
7854 ambiguous = true;
7855 }
7856
7857 gdb_assert (first_resumed_thread != nullptr);
7858
7859 /* Warn if the remote target is sending ambiguous stop replies. */
7860 if (ambiguous)
7861 {
7862 static bool warned = false;
7863
7864 if (!warned)
7865 {
7866 /* If you are seeing this warning then the remote target has
7867 stopped without specifying a thread-id, but the target
7868 does have multiple threads (or inferiors), and so GDB is
7869 having to guess which thread stopped.
7870
7871 Examples of what might cause this are the target sending
7872 and 'S' stop packet, or a 'T' stop packet and not
7873 including a thread-id.
7874
7875 Additionally, the target might send a 'W' or 'X packet
7876 without including a process-id, when the target has
7877 multiple running inferiors. */
7878 if (process_wide_stop)
7879 warning (_("multi-inferior target stopped without "
7880 "sending a process-id, using first "
7881 "non-exited inferior"));
7882 else
7883 warning (_("multi-threaded target stopped without "
7884 "sending a thread-id, using first "
7885 "non-exited thread"));
7886 warned = true;
7887 }
7888 }
7889
7890 /* If this is a stop for all threads then don't use a particular threads
7891 ptid, instead create a new ptid where only the pid field is set. */
7892 if (process_wide_stop)
7893 return ptid_t (first_resumed_thread->ptid.pid ());
7894 else
7895 return first_resumed_thread->ptid;
7896 }
7897
7898 /* Called when it is decided that STOP_REPLY holds the info of the
7899 event that is to be returned to the core. This function always
7900 destroys STOP_REPLY. */
7901
7902 ptid_t
7903 remote_target::process_stop_reply (struct stop_reply *stop_reply,
7904 struct target_waitstatus *status)
7905 {
7906 *status = stop_reply->ws;
7907 ptid_t ptid = stop_reply->ptid;
7908
7909 /* If no thread/process was reported by the stub then select a suitable
7910 thread/process. */
7911 if (ptid == null_ptid)
7912 ptid = select_thread_for_ambiguous_stop_reply (status);
7913 gdb_assert (ptid != null_ptid);
7914
7915 if (status->kind != TARGET_WAITKIND_EXITED
7916 && status->kind != TARGET_WAITKIND_SIGNALLED
7917 && status->kind != TARGET_WAITKIND_NO_RESUMED)
7918 {
7919 /* Expedited registers. */
7920 if (!stop_reply->regcache.empty ())
7921 {
7922 struct regcache *regcache
7923 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
7924
7925 for (cached_reg_t &reg : stop_reply->regcache)
7926 {
7927 regcache->raw_supply (reg.num, reg.data);
7928 xfree (reg.data);
7929 }
7930
7931 stop_reply->regcache.clear ();
7932 }
7933
7934 remote_notice_new_inferior (ptid, 0);
7935 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
7936 remote_thr->core = stop_reply->core;
7937 remote_thr->stop_reason = stop_reply->stop_reason;
7938 remote_thr->watch_data_address = stop_reply->watch_data_address;
7939
7940 if (target_is_non_stop_p ())
7941 {
7942 /* If the target works in non-stop mode, a stop-reply indicates that
7943 only this thread stopped. */
7944 remote_thr->set_not_resumed ();
7945 }
7946 else
7947 {
7948 /* If the target works in all-stop mode, a stop-reply indicates that
7949 all the target's threads stopped. */
7950 for (thread_info *tp : all_non_exited_threads (this))
7951 get_remote_thread_info (tp)->set_not_resumed ();
7952 }
7953 }
7954
7955 delete stop_reply;
7956 return ptid;
7957 }
7958
7959 /* The non-stop mode version of target_wait. */
7960
7961 ptid_t
7962 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
7963 target_wait_flags options)
7964 {
7965 struct remote_state *rs = get_remote_state ();
7966 struct stop_reply *stop_reply;
7967 int ret;
7968 int is_notif = 0;
7969
7970 /* If in non-stop mode, get out of getpkt even if a
7971 notification is received. */
7972
7973 ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
7974 while (1)
7975 {
7976 if (ret != -1 && !is_notif)
7977 switch (rs->buf[0])
7978 {
7979 case 'E': /* Error of some sort. */
7980 /* We're out of sync with the target now. Did it continue
7981 or not? We can't tell which thread it was in non-stop,
7982 so just ignore this. */
7983 warning (_("Remote failure reply: %s"), rs->buf.data ());
7984 break;
7985 case 'O': /* Console output. */
7986 remote_console_output (&rs->buf[1]);
7987 break;
7988 default:
7989 warning (_("Invalid remote reply: %s"), rs->buf.data ());
7990 break;
7991 }
7992
7993 /* Acknowledge a pending stop reply that may have arrived in the
7994 mean time. */
7995 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7996 remote_notif_get_pending_events (&notif_client_stop);
7997
7998 /* If indeed we noticed a stop reply, we're done. */
7999 stop_reply = queued_stop_reply (ptid);
8000 if (stop_reply != NULL)
8001 return process_stop_reply (stop_reply, status);
8002
8003 /* Still no event. If we're just polling for an event, then
8004 return to the event loop. */
8005 if (options & TARGET_WNOHANG)
8006 {
8007 status->kind = TARGET_WAITKIND_IGNORE;
8008 return minus_one_ptid;
8009 }
8010
8011 /* Otherwise do a blocking wait. */
8012 ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
8013 }
8014 }
8015
8016 /* Return the first resumed thread. */
8017
8018 static ptid_t
8019 first_remote_resumed_thread (remote_target *target)
8020 {
8021 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8022 if (tp->resumed)
8023 return tp->ptid;
8024 return null_ptid;
8025 }
8026
8027 /* Wait until the remote machine stops, then return, storing status in
8028 STATUS just as `wait' would. */
8029
8030 ptid_t
8031 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8032 target_wait_flags options)
8033 {
8034 struct remote_state *rs = get_remote_state ();
8035 ptid_t event_ptid = null_ptid;
8036 char *buf;
8037 struct stop_reply *stop_reply;
8038
8039 again:
8040
8041 status->kind = TARGET_WAITKIND_IGNORE;
8042 status->value.integer = 0;
8043
8044 stop_reply = queued_stop_reply (ptid);
8045 if (stop_reply != NULL)
8046 return process_stop_reply (stop_reply, status);
8047
8048 if (rs->cached_wait_status)
8049 /* Use the cached wait status, but only once. */
8050 rs->cached_wait_status = 0;
8051 else
8052 {
8053 int ret;
8054 int is_notif;
8055 int forever = ((options & TARGET_WNOHANG) == 0
8056 && rs->wait_forever_enabled_p);
8057
8058 if (!rs->waiting_for_stop_reply)
8059 {
8060 status->kind = TARGET_WAITKIND_NO_RESUMED;
8061 return minus_one_ptid;
8062 }
8063
8064 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8065 _never_ wait for ever -> test on target_is_async_p().
8066 However, before we do that we need to ensure that the caller
8067 knows how to take the target into/out of async mode. */
8068 ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
8069
8070 /* GDB gets a notification. Return to core as this event is
8071 not interesting. */
8072 if (ret != -1 && is_notif)
8073 return minus_one_ptid;
8074
8075 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8076 return minus_one_ptid;
8077 }
8078
8079 buf = rs->buf.data ();
8080
8081 /* Assume that the target has acknowledged Ctrl-C unless we receive
8082 an 'F' or 'O' packet. */
8083 if (buf[0] != 'F' && buf[0] != 'O')
8084 rs->ctrlc_pending_p = 0;
8085
8086 switch (buf[0])
8087 {
8088 case 'E': /* Error of some sort. */
8089 /* We're out of sync with the target now. Did it continue or
8090 not? Not is more likely, so report a stop. */
8091 rs->waiting_for_stop_reply = 0;
8092
8093 warning (_("Remote failure reply: %s"), buf);
8094 status->kind = TARGET_WAITKIND_STOPPED;
8095 status->value.sig = GDB_SIGNAL_0;
8096 break;
8097 case 'F': /* File-I/O request. */
8098 /* GDB may access the inferior memory while handling the File-I/O
8099 request, but we don't want GDB accessing memory while waiting
8100 for a stop reply. See the comments in putpkt_binary. Set
8101 waiting_for_stop_reply to 0 temporarily. */
8102 rs->waiting_for_stop_reply = 0;
8103 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8104 rs->ctrlc_pending_p = 0;
8105 /* GDB handled the File-I/O request, and the target is running
8106 again. Keep waiting for events. */
8107 rs->waiting_for_stop_reply = 1;
8108 break;
8109 case 'N': case 'T': case 'S': case 'X': case 'W':
8110 {
8111 /* There is a stop reply to handle. */
8112 rs->waiting_for_stop_reply = 0;
8113
8114 stop_reply
8115 = (struct stop_reply *) remote_notif_parse (this,
8116 &notif_client_stop,
8117 rs->buf.data ());
8118
8119 event_ptid = process_stop_reply (stop_reply, status);
8120 break;
8121 }
8122 case 'O': /* Console output. */
8123 remote_console_output (buf + 1);
8124 break;
8125 case '\0':
8126 if (rs->last_sent_signal != GDB_SIGNAL_0)
8127 {
8128 /* Zero length reply means that we tried 'S' or 'C' and the
8129 remote system doesn't support it. */
8130 target_terminal::ours_for_output ();
8131 printf_filtered
8132 ("Can't send signals to this remote system. %s not sent.\n",
8133 gdb_signal_to_name (rs->last_sent_signal));
8134 rs->last_sent_signal = GDB_SIGNAL_0;
8135 target_terminal::inferior ();
8136
8137 strcpy (buf, rs->last_sent_step ? "s" : "c");
8138 putpkt (buf);
8139 break;
8140 }
8141 /* fallthrough */
8142 default:
8143 warning (_("Invalid remote reply: %s"), buf);
8144 break;
8145 }
8146
8147 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
8148 return minus_one_ptid;
8149 else if (status->kind == TARGET_WAITKIND_IGNORE)
8150 {
8151 /* Nothing interesting happened. If we're doing a non-blocking
8152 poll, we're done. Otherwise, go back to waiting. */
8153 if (options & TARGET_WNOHANG)
8154 return minus_one_ptid;
8155 else
8156 goto again;
8157 }
8158 else if (status->kind != TARGET_WAITKIND_EXITED
8159 && status->kind != TARGET_WAITKIND_SIGNALLED)
8160 {
8161 if (event_ptid != null_ptid)
8162 record_currthread (rs, event_ptid);
8163 else
8164 event_ptid = first_remote_resumed_thread (this);
8165 }
8166 else
8167 {
8168 /* A process exit. Invalidate our notion of current thread. */
8169 record_currthread (rs, minus_one_ptid);
8170 /* It's possible that the packet did not include a pid. */
8171 if (event_ptid == null_ptid)
8172 event_ptid = first_remote_resumed_thread (this);
8173 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8174 if (event_ptid == null_ptid)
8175 event_ptid = magic_null_ptid;
8176 }
8177
8178 return event_ptid;
8179 }
8180
8181 /* Wait until the remote machine stops, then return, storing status in
8182 STATUS just as `wait' would. */
8183
8184 ptid_t
8185 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8186 target_wait_flags options)
8187 {
8188 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8189
8190 remote_state *rs = get_remote_state ();
8191
8192 /* Start by clearing the flag that asks for our wait method to be called,
8193 we'll mark it again at the end if needed. */
8194 if (target_is_async_p ())
8195 clear_async_event_handler (rs->remote_async_inferior_event_token);
8196
8197 ptid_t event_ptid;
8198
8199 if (target_is_non_stop_p ())
8200 event_ptid = wait_ns (ptid, status, options);
8201 else
8202 event_ptid = wait_as (ptid, status, options);
8203
8204 if (target_is_async_p ())
8205 {
8206 /* If there are events left in the queue, or unacknowledged
8207 notifications, then tell the event loop to call us again. */
8208 if (!rs->stop_reply_queue.empty ()
8209 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8210 mark_async_event_handler (rs->remote_async_inferior_event_token);
8211 }
8212
8213 return event_ptid;
8214 }
8215
8216 /* Fetch a single register using a 'p' packet. */
8217
8218 int
8219 remote_target::fetch_register_using_p (struct regcache *regcache,
8220 packet_reg *reg)
8221 {
8222 struct gdbarch *gdbarch = regcache->arch ();
8223 struct remote_state *rs = get_remote_state ();
8224 char *buf, *p;
8225 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8226 int i;
8227
8228 if (packet_support (PACKET_p) == PACKET_DISABLE)
8229 return 0;
8230
8231 if (reg->pnum == -1)
8232 return 0;
8233
8234 p = rs->buf.data ();
8235 *p++ = 'p';
8236 p += hexnumstr (p, reg->pnum);
8237 *p++ = '\0';
8238 putpkt (rs->buf);
8239 getpkt (&rs->buf, 0);
8240
8241 buf = rs->buf.data ();
8242
8243 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_p]))
8244 {
8245 case PACKET_OK:
8246 break;
8247 case PACKET_UNKNOWN:
8248 return 0;
8249 case PACKET_ERROR:
8250 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8251 gdbarch_register_name (regcache->arch (),
8252 reg->regnum),
8253 buf);
8254 }
8255
8256 /* If this register is unfetchable, tell the regcache. */
8257 if (buf[0] == 'x')
8258 {
8259 regcache->raw_supply (reg->regnum, NULL);
8260 return 1;
8261 }
8262
8263 /* Otherwise, parse and supply the value. */
8264 p = buf;
8265 i = 0;
8266 while (p[0] != 0)
8267 {
8268 if (p[1] == 0)
8269 error (_("fetch_register_using_p: early buf termination"));
8270
8271 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8272 p += 2;
8273 }
8274 regcache->raw_supply (reg->regnum, regp);
8275 return 1;
8276 }
8277
8278 /* Fetch the registers included in the target's 'g' packet. */
8279
8280 int
8281 remote_target::send_g_packet ()
8282 {
8283 struct remote_state *rs = get_remote_state ();
8284 int buf_len;
8285
8286 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8287 putpkt (rs->buf);
8288 getpkt (&rs->buf, 0);
8289 if (packet_check_result (rs->buf) == PACKET_ERROR)
8290 error (_("Could not read registers; remote failure reply '%s'"),
8291 rs->buf.data ());
8292
8293 /* We can get out of synch in various cases. If the first character
8294 in the buffer is not a hex character, assume that has happened
8295 and try to fetch another packet to read. */
8296 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8297 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8298 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8299 && rs->buf[0] != 'x') /* New: unavailable register value. */
8300 {
8301 remote_debug_printf ("Bad register packet; fetching a new packet");
8302 getpkt (&rs->buf, 0);
8303 }
8304
8305 buf_len = strlen (rs->buf.data ());
8306
8307 /* Sanity check the received packet. */
8308 if (buf_len % 2 != 0)
8309 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8310
8311 return buf_len / 2;
8312 }
8313
8314 void
8315 remote_target::process_g_packet (struct regcache *regcache)
8316 {
8317 struct gdbarch *gdbarch = regcache->arch ();
8318 struct remote_state *rs = get_remote_state ();
8319 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8320 int i, buf_len;
8321 char *p;
8322 char *regs;
8323
8324 buf_len = strlen (rs->buf.data ());
8325
8326 /* Further sanity checks, with knowledge of the architecture. */
8327 if (buf_len > 2 * rsa->sizeof_g_packet)
8328 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8329 "bytes): %s"),
8330 rsa->sizeof_g_packet, buf_len / 2,
8331 rs->buf.data ());
8332
8333 /* Save the size of the packet sent to us by the target. It is used
8334 as a heuristic when determining the max size of packets that the
8335 target can safely receive. */
8336 if (rsa->actual_register_packet_size == 0)
8337 rsa->actual_register_packet_size = buf_len;
8338
8339 /* If this is smaller than we guessed the 'g' packet would be,
8340 update our records. A 'g' reply that doesn't include a register's
8341 value implies either that the register is not available, or that
8342 the 'p' packet must be used. */
8343 if (buf_len < 2 * rsa->sizeof_g_packet)
8344 {
8345 long sizeof_g_packet = buf_len / 2;
8346
8347 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8348 {
8349 long offset = rsa->regs[i].offset;
8350 long reg_size = register_size (gdbarch, i);
8351
8352 if (rsa->regs[i].pnum == -1)
8353 continue;
8354
8355 if (offset >= sizeof_g_packet)
8356 rsa->regs[i].in_g_packet = 0;
8357 else if (offset + reg_size > sizeof_g_packet)
8358 error (_("Truncated register %d in remote 'g' packet"), i);
8359 else
8360 rsa->regs[i].in_g_packet = 1;
8361 }
8362
8363 /* Looks valid enough, we can assume this is the correct length
8364 for a 'g' packet. It's important not to adjust
8365 rsa->sizeof_g_packet if we have truncated registers otherwise
8366 this "if" won't be run the next time the method is called
8367 with a packet of the same size and one of the internal errors
8368 below will trigger instead. */
8369 rsa->sizeof_g_packet = sizeof_g_packet;
8370 }
8371
8372 regs = (char *) alloca (rsa->sizeof_g_packet);
8373
8374 /* Unimplemented registers read as all bits zero. */
8375 memset (regs, 0, rsa->sizeof_g_packet);
8376
8377 /* Reply describes registers byte by byte, each byte encoded as two
8378 hex characters. Suck them all up, then supply them to the
8379 register cacheing/storage mechanism. */
8380
8381 p = rs->buf.data ();
8382 for (i = 0; i < rsa->sizeof_g_packet; i++)
8383 {
8384 if (p[0] == 0 || p[1] == 0)
8385 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8386 internal_error (__FILE__, __LINE__,
8387 _("unexpected end of 'g' packet reply"));
8388
8389 if (p[0] == 'x' && p[1] == 'x')
8390 regs[i] = 0; /* 'x' */
8391 else
8392 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8393 p += 2;
8394 }
8395
8396 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8397 {
8398 struct packet_reg *r = &rsa->regs[i];
8399 long reg_size = register_size (gdbarch, i);
8400
8401 if (r->in_g_packet)
8402 {
8403 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8404 /* This shouldn't happen - we adjusted in_g_packet above. */
8405 internal_error (__FILE__, __LINE__,
8406 _("unexpected end of 'g' packet reply"));
8407 else if (rs->buf[r->offset * 2] == 'x')
8408 {
8409 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8410 /* The register isn't available, mark it as such (at
8411 the same time setting the value to zero). */
8412 regcache->raw_supply (r->regnum, NULL);
8413 }
8414 else
8415 regcache->raw_supply (r->regnum, regs + r->offset);
8416 }
8417 }
8418 }
8419
8420 void
8421 remote_target::fetch_registers_using_g (struct regcache *regcache)
8422 {
8423 send_g_packet ();
8424 process_g_packet (regcache);
8425 }
8426
8427 /* Make the remote selected traceframe match GDB's selected
8428 traceframe. */
8429
8430 void
8431 remote_target::set_remote_traceframe ()
8432 {
8433 int newnum;
8434 struct remote_state *rs = get_remote_state ();
8435
8436 if (rs->remote_traceframe_number == get_traceframe_number ())
8437 return;
8438
8439 /* Avoid recursion, remote_trace_find calls us again. */
8440 rs->remote_traceframe_number = get_traceframe_number ();
8441
8442 newnum = target_trace_find (tfind_number,
8443 get_traceframe_number (), 0, 0, NULL);
8444
8445 /* Should not happen. If it does, all bets are off. */
8446 if (newnum != get_traceframe_number ())
8447 warning (_("could not set remote traceframe"));
8448 }
8449
8450 void
8451 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8452 {
8453 struct gdbarch *gdbarch = regcache->arch ();
8454 struct remote_state *rs = get_remote_state ();
8455 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8456 int i;
8457
8458 set_remote_traceframe ();
8459 set_general_thread (regcache->ptid ());
8460
8461 if (regnum >= 0)
8462 {
8463 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8464
8465 gdb_assert (reg != NULL);
8466
8467 /* If this register might be in the 'g' packet, try that first -
8468 we are likely to read more than one register. If this is the
8469 first 'g' packet, we might be overly optimistic about its
8470 contents, so fall back to 'p'. */
8471 if (reg->in_g_packet)
8472 {
8473 fetch_registers_using_g (regcache);
8474 if (reg->in_g_packet)
8475 return;
8476 }
8477
8478 if (fetch_register_using_p (regcache, reg))
8479 return;
8480
8481 /* This register is not available. */
8482 regcache->raw_supply (reg->regnum, NULL);
8483
8484 return;
8485 }
8486
8487 fetch_registers_using_g (regcache);
8488
8489 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8490 if (!rsa->regs[i].in_g_packet)
8491 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8492 {
8493 /* This register is not available. */
8494 regcache->raw_supply (i, NULL);
8495 }
8496 }
8497
8498 /* Prepare to store registers. Since we may send them all (using a
8499 'G' request), we have to read out the ones we don't want to change
8500 first. */
8501
8502 void
8503 remote_target::prepare_to_store (struct regcache *regcache)
8504 {
8505 struct remote_state *rs = get_remote_state ();
8506 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8507 int i;
8508
8509 /* Make sure the entire registers array is valid. */
8510 switch (packet_support (PACKET_P))
8511 {
8512 case PACKET_DISABLE:
8513 case PACKET_SUPPORT_UNKNOWN:
8514 /* Make sure all the necessary registers are cached. */
8515 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8516 if (rsa->regs[i].in_g_packet)
8517 regcache->raw_update (rsa->regs[i].regnum);
8518 break;
8519 case PACKET_ENABLE:
8520 break;
8521 }
8522 }
8523
8524 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8525 packet was not recognized. */
8526
8527 int
8528 remote_target::store_register_using_P (const struct regcache *regcache,
8529 packet_reg *reg)
8530 {
8531 struct gdbarch *gdbarch = regcache->arch ();
8532 struct remote_state *rs = get_remote_state ();
8533 /* Try storing a single register. */
8534 char *buf = rs->buf.data ();
8535 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8536 char *p;
8537
8538 if (packet_support (PACKET_P) == PACKET_DISABLE)
8539 return 0;
8540
8541 if (reg->pnum == -1)
8542 return 0;
8543
8544 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8545 p = buf + strlen (buf);
8546 regcache->raw_collect (reg->regnum, regp);
8547 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8548 putpkt (rs->buf);
8549 getpkt (&rs->buf, 0);
8550
8551 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8552 {
8553 case PACKET_OK:
8554 return 1;
8555 case PACKET_ERROR:
8556 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8557 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
8558 case PACKET_UNKNOWN:
8559 return 0;
8560 default:
8561 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8562 }
8563 }
8564
8565 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8566 contents of the register cache buffer. FIXME: ignores errors. */
8567
8568 void
8569 remote_target::store_registers_using_G (const struct regcache *regcache)
8570 {
8571 struct remote_state *rs = get_remote_state ();
8572 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8573 gdb_byte *regs;
8574 char *p;
8575
8576 /* Extract all the registers in the regcache copying them into a
8577 local buffer. */
8578 {
8579 int i;
8580
8581 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8582 memset (regs, 0, rsa->sizeof_g_packet);
8583 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8584 {
8585 struct packet_reg *r = &rsa->regs[i];
8586
8587 if (r->in_g_packet)
8588 regcache->raw_collect (r->regnum, regs + r->offset);
8589 }
8590 }
8591
8592 /* Command describes registers byte by byte,
8593 each byte encoded as two hex characters. */
8594 p = rs->buf.data ();
8595 *p++ = 'G';
8596 bin2hex (regs, p, rsa->sizeof_g_packet);
8597 putpkt (rs->buf);
8598 getpkt (&rs->buf, 0);
8599 if (packet_check_result (rs->buf) == PACKET_ERROR)
8600 error (_("Could not write registers; remote failure reply '%s'"),
8601 rs->buf.data ());
8602 }
8603
8604 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8605 of the register cache buffer. FIXME: ignores errors. */
8606
8607 void
8608 remote_target::store_registers (struct regcache *regcache, int regnum)
8609 {
8610 struct gdbarch *gdbarch = regcache->arch ();
8611 struct remote_state *rs = get_remote_state ();
8612 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8613 int i;
8614
8615 set_remote_traceframe ();
8616 set_general_thread (regcache->ptid ());
8617
8618 if (regnum >= 0)
8619 {
8620 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8621
8622 gdb_assert (reg != NULL);
8623
8624 /* Always prefer to store registers using the 'P' packet if
8625 possible; we often change only a small number of registers.
8626 Sometimes we change a larger number; we'd need help from a
8627 higher layer to know to use 'G'. */
8628 if (store_register_using_P (regcache, reg))
8629 return;
8630
8631 /* For now, don't complain if we have no way to write the
8632 register. GDB loses track of unavailable registers too
8633 easily. Some day, this may be an error. We don't have
8634 any way to read the register, either... */
8635 if (!reg->in_g_packet)
8636 return;
8637
8638 store_registers_using_G (regcache);
8639 return;
8640 }
8641
8642 store_registers_using_G (regcache);
8643
8644 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8645 if (!rsa->regs[i].in_g_packet)
8646 if (!store_register_using_P (regcache, &rsa->regs[i]))
8647 /* See above for why we do not issue an error here. */
8648 continue;
8649 }
8650 \f
8651
8652 /* Return the number of hex digits in num. */
8653
8654 static int
8655 hexnumlen (ULONGEST num)
8656 {
8657 int i;
8658
8659 for (i = 0; num != 0; i++)
8660 num >>= 4;
8661
8662 return std::max (i, 1);
8663 }
8664
8665 /* Set BUF to the minimum number of hex digits representing NUM. */
8666
8667 static int
8668 hexnumstr (char *buf, ULONGEST num)
8669 {
8670 int len = hexnumlen (num);
8671
8672 return hexnumnstr (buf, num, len);
8673 }
8674
8675
8676 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
8677
8678 static int
8679 hexnumnstr (char *buf, ULONGEST num, int width)
8680 {
8681 int i;
8682
8683 buf[width] = '\0';
8684
8685 for (i = width - 1; i >= 0; i--)
8686 {
8687 buf[i] = "0123456789abcdef"[(num & 0xf)];
8688 num >>= 4;
8689 }
8690
8691 return width;
8692 }
8693
8694 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8695
8696 static CORE_ADDR
8697 remote_address_masked (CORE_ADDR addr)
8698 {
8699 unsigned int address_size = remote_address_size;
8700
8701 /* If "remoteaddresssize" was not set, default to target address size. */
8702 if (!address_size)
8703 address_size = gdbarch_addr_bit (target_gdbarch ());
8704
8705 if (address_size > 0
8706 && address_size < (sizeof (ULONGEST) * 8))
8707 {
8708 /* Only create a mask when that mask can safely be constructed
8709 in a ULONGEST variable. */
8710 ULONGEST mask = 1;
8711
8712 mask = (mask << address_size) - 1;
8713 addr &= mask;
8714 }
8715 return addr;
8716 }
8717
8718 /* Determine whether the remote target supports binary downloading.
8719 This is accomplished by sending a no-op memory write of zero length
8720 to the target at the specified address. It does not suffice to send
8721 the whole packet, since many stubs strip the eighth bit and
8722 subsequently compute a wrong checksum, which causes real havoc with
8723 remote_write_bytes.
8724
8725 NOTE: This can still lose if the serial line is not eight-bit
8726 clean. In cases like this, the user should clear "remote
8727 X-packet". */
8728
8729 void
8730 remote_target::check_binary_download (CORE_ADDR addr)
8731 {
8732 struct remote_state *rs = get_remote_state ();
8733
8734 switch (packet_support (PACKET_X))
8735 {
8736 case PACKET_DISABLE:
8737 break;
8738 case PACKET_ENABLE:
8739 break;
8740 case PACKET_SUPPORT_UNKNOWN:
8741 {
8742 char *p;
8743
8744 p = rs->buf.data ();
8745 *p++ = 'X';
8746 p += hexnumstr (p, (ULONGEST) addr);
8747 *p++ = ',';
8748 p += hexnumstr (p, (ULONGEST) 0);
8749 *p++ = ':';
8750 *p = '\0';
8751
8752 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
8753 getpkt (&rs->buf, 0);
8754
8755 if (rs->buf[0] == '\0')
8756 {
8757 remote_debug_printf ("binary downloading NOT supported by target");
8758 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8759 }
8760 else
8761 {
8762 remote_debug_printf ("binary downloading supported by target");
8763 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8764 }
8765 break;
8766 }
8767 }
8768 }
8769
8770 /* Helper function to resize the payload in order to try to get a good
8771 alignment. We try to write an amount of data such that the next write will
8772 start on an address aligned on REMOTE_ALIGN_WRITES. */
8773
8774 static int
8775 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8776 {
8777 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8778 }
8779
8780 /* Write memory data directly to the remote machine.
8781 This does not inform the data cache; the data cache uses this.
8782 HEADER is the starting part of the packet.
8783 MEMADDR is the address in the remote memory space.
8784 MYADDR is the address of the buffer in our space.
8785 LEN_UNITS is the number of addressable units to write.
8786 UNIT_SIZE is the length in bytes of an addressable unit.
8787 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8788 should send data as binary ('X'), or hex-encoded ('M').
8789
8790 The function creates packet of the form
8791 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8792
8793 where encoding of <DATA> is terminated by PACKET_FORMAT.
8794
8795 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8796 are omitted.
8797
8798 Return the transferred status, error or OK (an
8799 'enum target_xfer_status' value). Save the number of addressable units
8800 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8801
8802 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8803 exchange between gdb and the stub could look like (?? in place of the
8804 checksum):
8805
8806 -> $m1000,4#??
8807 <- aaaabbbbccccdddd
8808
8809 -> $M1000,3:eeeeffffeeee#??
8810 <- OK
8811
8812 -> $m1000,4#??
8813 <- eeeeffffeeeedddd */
8814
8815 target_xfer_status
8816 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8817 const gdb_byte *myaddr,
8818 ULONGEST len_units,
8819 int unit_size,
8820 ULONGEST *xfered_len_units,
8821 char packet_format, int use_length)
8822 {
8823 struct remote_state *rs = get_remote_state ();
8824 char *p;
8825 char *plen = NULL;
8826 int plenlen = 0;
8827 int todo_units;
8828 int units_written;
8829 int payload_capacity_bytes;
8830 int payload_length_bytes;
8831
8832 if (packet_format != 'X' && packet_format != 'M')
8833 internal_error (__FILE__, __LINE__,
8834 _("remote_write_bytes_aux: bad packet format"));
8835
8836 if (len_units == 0)
8837 return TARGET_XFER_EOF;
8838
8839 payload_capacity_bytes = get_memory_write_packet_size ();
8840
8841 /* The packet buffer will be large enough for the payload;
8842 get_memory_packet_size ensures this. */
8843 rs->buf[0] = '\0';
8844
8845 /* Compute the size of the actual payload by subtracting out the
8846 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8847
8848 payload_capacity_bytes -= strlen ("$,:#NN");
8849 if (!use_length)
8850 /* The comma won't be used. */
8851 payload_capacity_bytes += 1;
8852 payload_capacity_bytes -= strlen (header);
8853 payload_capacity_bytes -= hexnumlen (memaddr);
8854
8855 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
8856
8857 strcat (rs->buf.data (), header);
8858 p = rs->buf.data () + strlen (header);
8859
8860 /* Compute a best guess of the number of bytes actually transfered. */
8861 if (packet_format == 'X')
8862 {
8863 /* Best guess at number of bytes that will fit. */
8864 todo_units = std::min (len_units,
8865 (ULONGEST) payload_capacity_bytes / unit_size);
8866 if (use_length)
8867 payload_capacity_bytes -= hexnumlen (todo_units);
8868 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8869 }
8870 else
8871 {
8872 /* Number of bytes that will fit. */
8873 todo_units
8874 = std::min (len_units,
8875 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8876 if (use_length)
8877 payload_capacity_bytes -= hexnumlen (todo_units);
8878 todo_units = std::min (todo_units,
8879 (payload_capacity_bytes / unit_size) / 2);
8880 }
8881
8882 if (todo_units <= 0)
8883 internal_error (__FILE__, __LINE__,
8884 _("minimum packet size too small to write data"));
8885
8886 /* If we already need another packet, then try to align the end
8887 of this packet to a useful boundary. */
8888 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8889 todo_units = align_for_efficient_write (todo_units, memaddr);
8890
8891 /* Append "<memaddr>". */
8892 memaddr = remote_address_masked (memaddr);
8893 p += hexnumstr (p, (ULONGEST) memaddr);
8894
8895 if (use_length)
8896 {
8897 /* Append ",". */
8898 *p++ = ',';
8899
8900 /* Append the length and retain its location and size. It may need to be
8901 adjusted once the packet body has been created. */
8902 plen = p;
8903 plenlen = hexnumstr (p, (ULONGEST) todo_units);
8904 p += plenlen;
8905 }
8906
8907 /* Append ":". */
8908 *p++ = ':';
8909 *p = '\0';
8910
8911 /* Append the packet body. */
8912 if (packet_format == 'X')
8913 {
8914 /* Binary mode. Send target system values byte by byte, in
8915 increasing byte addresses. Only escape certain critical
8916 characters. */
8917 payload_length_bytes =
8918 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8919 &units_written, payload_capacity_bytes);
8920
8921 /* If not all TODO units fit, then we'll need another packet. Make
8922 a second try to keep the end of the packet aligned. Don't do
8923 this if the packet is tiny. */
8924 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8925 {
8926 int new_todo_units;
8927
8928 new_todo_units = align_for_efficient_write (units_written, memaddr);
8929
8930 if (new_todo_units != units_written)
8931 payload_length_bytes =
8932 remote_escape_output (myaddr, new_todo_units, unit_size,
8933 (gdb_byte *) p, &units_written,
8934 payload_capacity_bytes);
8935 }
8936
8937 p += payload_length_bytes;
8938 if (use_length && units_written < todo_units)
8939 {
8940 /* Escape chars have filled up the buffer prematurely,
8941 and we have actually sent fewer units than planned.
8942 Fix-up the length field of the packet. Use the same
8943 number of characters as before. */
8944 plen += hexnumnstr (plen, (ULONGEST) units_written,
8945 plenlen);
8946 *plen = ':'; /* overwrite \0 from hexnumnstr() */
8947 }
8948 }
8949 else
8950 {
8951 /* Normal mode: Send target system values byte by byte, in
8952 increasing byte addresses. Each byte is encoded as a two hex
8953 value. */
8954 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8955 units_written = todo_units;
8956 }
8957
8958 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
8959 getpkt (&rs->buf, 0);
8960
8961 if (rs->buf[0] == 'E')
8962 return TARGET_XFER_E_IO;
8963
8964 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8965 send fewer units than we'd planned. */
8966 *xfered_len_units = (ULONGEST) units_written;
8967 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8968 }
8969
8970 /* Write memory data directly to the remote machine.
8971 This does not inform the data cache; the data cache uses this.
8972 MEMADDR is the address in the remote memory space.
8973 MYADDR is the address of the buffer in our space.
8974 LEN is the number of bytes.
8975
8976 Return the transferred status, error or OK (an
8977 'enum target_xfer_status' value). Save the number of bytes
8978 transferred in *XFERED_LEN. Only transfer a single packet. */
8979
8980 target_xfer_status
8981 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
8982 ULONGEST len, int unit_size,
8983 ULONGEST *xfered_len)
8984 {
8985 const char *packet_format = NULL;
8986
8987 /* Check whether the target supports binary download. */
8988 check_binary_download (memaddr);
8989
8990 switch (packet_support (PACKET_X))
8991 {
8992 case PACKET_ENABLE:
8993 packet_format = "X";
8994 break;
8995 case PACKET_DISABLE:
8996 packet_format = "M";
8997 break;
8998 case PACKET_SUPPORT_UNKNOWN:
8999 internal_error (__FILE__, __LINE__,
9000 _("remote_write_bytes: bad internal state"));
9001 default:
9002 internal_error (__FILE__, __LINE__, _("bad switch"));
9003 }
9004
9005 return remote_write_bytes_aux (packet_format,
9006 memaddr, myaddr, len, unit_size, xfered_len,
9007 packet_format[0], 1);
9008 }
9009
9010 /* Read memory data directly from the remote machine.
9011 This does not use the data cache; the data cache uses this.
9012 MEMADDR is the address in the remote memory space.
9013 MYADDR is the address of the buffer in our space.
9014 LEN_UNITS is the number of addressable memory units to read..
9015 UNIT_SIZE is the length in bytes of an addressable unit.
9016
9017 Return the transferred status, error or OK (an
9018 'enum target_xfer_status' value). Save the number of bytes
9019 transferred in *XFERED_LEN_UNITS.
9020
9021 See the comment of remote_write_bytes_aux for an example of
9022 memory read/write exchange between gdb and the stub. */
9023
9024 target_xfer_status
9025 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9026 ULONGEST len_units,
9027 int unit_size, ULONGEST *xfered_len_units)
9028 {
9029 struct remote_state *rs = get_remote_state ();
9030 int buf_size_bytes; /* Max size of packet output buffer. */
9031 char *p;
9032 int todo_units;
9033 int decoded_bytes;
9034
9035 buf_size_bytes = get_memory_read_packet_size ();
9036 /* The packet buffer will be large enough for the payload;
9037 get_memory_packet_size ensures this. */
9038
9039 /* Number of units that will fit. */
9040 todo_units = std::min (len_units,
9041 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9042
9043 /* Construct "m"<memaddr>","<len>". */
9044 memaddr = remote_address_masked (memaddr);
9045 p = rs->buf.data ();
9046 *p++ = 'm';
9047 p += hexnumstr (p, (ULONGEST) memaddr);
9048 *p++ = ',';
9049 p += hexnumstr (p, (ULONGEST) todo_units);
9050 *p = '\0';
9051 putpkt (rs->buf);
9052 getpkt (&rs->buf, 0);
9053 if (rs->buf[0] == 'E'
9054 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9055 && rs->buf[3] == '\0')
9056 return TARGET_XFER_E_IO;
9057 /* Reply describes memory byte by byte, each byte encoded as two hex
9058 characters. */
9059 p = rs->buf.data ();
9060 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9061 /* Return what we have. Let higher layers handle partial reads. */
9062 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9063 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9064 }
9065
9066 /* Using the set of read-only target sections of remote, read live
9067 read-only memory.
9068
9069 For interface/parameters/return description see target.h,
9070 to_xfer_partial. */
9071
9072 target_xfer_status
9073 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9074 ULONGEST memaddr,
9075 ULONGEST len,
9076 int unit_size,
9077 ULONGEST *xfered_len)
9078 {
9079 const struct target_section *secp;
9080
9081 secp = target_section_by_addr (this, memaddr);
9082 if (secp != NULL
9083 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9084 {
9085 ULONGEST memend = memaddr + len;
9086
9087 const target_section_table *table = target_get_section_table (this);
9088 for (const target_section &p : *table)
9089 {
9090 if (memaddr >= p.addr)
9091 {
9092 if (memend <= p.endaddr)
9093 {
9094 /* Entire transfer is within this section. */
9095 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9096 xfered_len);
9097 }
9098 else if (memaddr >= p.endaddr)
9099 {
9100 /* This section ends before the transfer starts. */
9101 continue;
9102 }
9103 else
9104 {
9105 /* This section overlaps the transfer. Just do half. */
9106 len = p.endaddr - memaddr;
9107 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9108 xfered_len);
9109 }
9110 }
9111 }
9112 }
9113
9114 return TARGET_XFER_EOF;
9115 }
9116
9117 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9118 first if the requested memory is unavailable in traceframe.
9119 Otherwise, fall back to remote_read_bytes_1. */
9120
9121 target_xfer_status
9122 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9123 gdb_byte *myaddr, ULONGEST len, int unit_size,
9124 ULONGEST *xfered_len)
9125 {
9126 if (len == 0)
9127 return TARGET_XFER_EOF;
9128
9129 if (get_traceframe_number () != -1)
9130 {
9131 std::vector<mem_range> available;
9132
9133 /* If we fail to get the set of available memory, then the
9134 target does not support querying traceframe info, and so we
9135 attempt reading from the traceframe anyway (assuming the
9136 target implements the old QTro packet then). */
9137 if (traceframe_available_memory (&available, memaddr, len))
9138 {
9139 if (available.empty () || available[0].start != memaddr)
9140 {
9141 enum target_xfer_status res;
9142
9143 /* Don't read into the traceframe's available
9144 memory. */
9145 if (!available.empty ())
9146 {
9147 LONGEST oldlen = len;
9148
9149 len = available[0].start - memaddr;
9150 gdb_assert (len <= oldlen);
9151 }
9152
9153 /* This goes through the topmost target again. */
9154 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9155 len, unit_size, xfered_len);
9156 if (res == TARGET_XFER_OK)
9157 return TARGET_XFER_OK;
9158 else
9159 {
9160 /* No use trying further, we know some memory starting
9161 at MEMADDR isn't available. */
9162 *xfered_len = len;
9163 return (*xfered_len != 0) ?
9164 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9165 }
9166 }
9167
9168 /* Don't try to read more than how much is available, in
9169 case the target implements the deprecated QTro packet to
9170 cater for older GDBs (the target's knowledge of read-only
9171 sections may be outdated by now). */
9172 len = available[0].length;
9173 }
9174 }
9175
9176 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9177 }
9178
9179 \f
9180
9181 /* Sends a packet with content determined by the printf format string
9182 FORMAT and the remaining arguments, then gets the reply. Returns
9183 whether the packet was a success, a failure, or unknown. */
9184
9185 packet_result
9186 remote_target::remote_send_printf (const char *format, ...)
9187 {
9188 struct remote_state *rs = get_remote_state ();
9189 int max_size = get_remote_packet_size ();
9190 va_list ap;
9191
9192 va_start (ap, format);
9193
9194 rs->buf[0] = '\0';
9195 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9196
9197 va_end (ap);
9198
9199 if (size >= max_size)
9200 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
9201
9202 if (putpkt (rs->buf) < 0)
9203 error (_("Communication problem with target."));
9204
9205 rs->buf[0] = '\0';
9206 getpkt (&rs->buf, 0);
9207
9208 return packet_check_result (rs->buf);
9209 }
9210
9211 /* Flash writing can take quite some time. We'll set
9212 effectively infinite timeout for flash operations.
9213 In future, we'll need to decide on a better approach. */
9214 static const int remote_flash_timeout = 1000;
9215
9216 void
9217 remote_target::flash_erase (ULONGEST address, LONGEST length)
9218 {
9219 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9220 enum packet_result ret;
9221 scoped_restore restore_timeout
9222 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9223
9224 ret = remote_send_printf ("vFlashErase:%s,%s",
9225 phex (address, addr_size),
9226 phex (length, 4));
9227 switch (ret)
9228 {
9229 case PACKET_UNKNOWN:
9230 error (_("Remote target does not support flash erase"));
9231 case PACKET_ERROR:
9232 error (_("Error erasing flash with vFlashErase packet"));
9233 default:
9234 break;
9235 }
9236 }
9237
9238 target_xfer_status
9239 remote_target::remote_flash_write (ULONGEST address,
9240 ULONGEST length, ULONGEST *xfered_len,
9241 const gdb_byte *data)
9242 {
9243 scoped_restore restore_timeout
9244 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9245 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9246 xfered_len,'X', 0);
9247 }
9248
9249 void
9250 remote_target::flash_done ()
9251 {
9252 int ret;
9253
9254 scoped_restore restore_timeout
9255 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9256
9257 ret = remote_send_printf ("vFlashDone");
9258
9259 switch (ret)
9260 {
9261 case PACKET_UNKNOWN:
9262 error (_("Remote target does not support vFlashDone"));
9263 case PACKET_ERROR:
9264 error (_("Error finishing flash operation"));
9265 default:
9266 break;
9267 }
9268 }
9269
9270 void
9271 remote_target::files_info ()
9272 {
9273 puts_filtered ("Debugging a target over a serial line.\n");
9274 }
9275 \f
9276 /* Stuff for dealing with the packets which are part of this protocol.
9277 See comment at top of file for details. */
9278
9279 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9280 error to higher layers. Called when a serial error is detected.
9281 The exception message is STRING, followed by a colon and a blank,
9282 the system error message for errno at function entry and final dot
9283 for output compatibility with throw_perror_with_name. */
9284
9285 static void
9286 unpush_and_perror (remote_target *target, const char *string)
9287 {
9288 int saved_errno = errno;
9289
9290 remote_unpush_target (target);
9291 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9292 safe_strerror (saved_errno));
9293 }
9294
9295 /* Read a single character from the remote end. The current quit
9296 handler is overridden to avoid quitting in the middle of packet
9297 sequence, as that would break communication with the remote server.
9298 See remote_serial_quit_handler for more detail. */
9299
9300 int
9301 remote_target::readchar (int timeout)
9302 {
9303 int ch;
9304 struct remote_state *rs = get_remote_state ();
9305
9306 {
9307 scoped_restore restore_quit_target
9308 = make_scoped_restore (&curr_quit_handler_target, this);
9309 scoped_restore restore_quit
9310 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9311
9312 rs->got_ctrlc_during_io = 0;
9313
9314 ch = serial_readchar (rs->remote_desc, timeout);
9315
9316 if (rs->got_ctrlc_during_io)
9317 set_quit_flag ();
9318 }
9319
9320 if (ch >= 0)
9321 return ch;
9322
9323 switch ((enum serial_rc) ch)
9324 {
9325 case SERIAL_EOF:
9326 remote_unpush_target (this);
9327 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9328 /* no return */
9329 case SERIAL_ERROR:
9330 unpush_and_perror (this, _("Remote communication error. "
9331 "Target disconnected."));
9332 /* no return */
9333 case SERIAL_TIMEOUT:
9334 break;
9335 }
9336 return ch;
9337 }
9338
9339 /* Wrapper for serial_write that closes the target and throws if
9340 writing fails. The current quit handler is overridden to avoid
9341 quitting in the middle of packet sequence, as that would break
9342 communication with the remote server. See
9343 remote_serial_quit_handler for more detail. */
9344
9345 void
9346 remote_target::remote_serial_write (const char *str, int len)
9347 {
9348 struct remote_state *rs = get_remote_state ();
9349
9350 scoped_restore restore_quit_target
9351 = make_scoped_restore (&curr_quit_handler_target, this);
9352 scoped_restore restore_quit
9353 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9354
9355 rs->got_ctrlc_during_io = 0;
9356
9357 if (serial_write (rs->remote_desc, str, len))
9358 {
9359 unpush_and_perror (this, _("Remote communication error. "
9360 "Target disconnected."));
9361 }
9362
9363 if (rs->got_ctrlc_during_io)
9364 set_quit_flag ();
9365 }
9366
9367 /* Return a string representing an escaped version of BUF, of len N.
9368 E.g. \n is converted to \\n, \t to \\t, etc. */
9369
9370 static std::string
9371 escape_buffer (const char *buf, int n)
9372 {
9373 string_file stb;
9374
9375 stb.putstrn (buf, n, '\\');
9376 return std::move (stb.string ());
9377 }
9378
9379 /* Display a null-terminated packet on stdout, for debugging, using C
9380 string notation. */
9381
9382 static void
9383 print_packet (const char *buf)
9384 {
9385 puts_filtered ("\"");
9386 fputstr_filtered (buf, '"', gdb_stdout);
9387 puts_filtered ("\"");
9388 }
9389
9390 int
9391 remote_target::putpkt (const char *buf)
9392 {
9393 return putpkt_binary (buf, strlen (buf));
9394 }
9395
9396 /* Wrapper around remote_target::putpkt to avoid exporting
9397 remote_target. */
9398
9399 int
9400 putpkt (remote_target *remote, const char *buf)
9401 {
9402 return remote->putpkt (buf);
9403 }
9404
9405 /* Send a packet to the remote machine, with error checking. The data
9406 of the packet is in BUF. The string in BUF can be at most
9407 get_remote_packet_size () - 5 to account for the $, # and checksum,
9408 and for a possible /0 if we are debugging (remote_debug) and want
9409 to print the sent packet as a string. */
9410
9411 int
9412 remote_target::putpkt_binary (const char *buf, int cnt)
9413 {
9414 struct remote_state *rs = get_remote_state ();
9415 int i;
9416 unsigned char csum = 0;
9417 gdb::def_vector<char> data (cnt + 6);
9418 char *buf2 = data.data ();
9419
9420 int ch;
9421 int tcount = 0;
9422 char *p;
9423
9424 /* Catch cases like trying to read memory or listing threads while
9425 we're waiting for a stop reply. The remote server wouldn't be
9426 ready to handle this request, so we'd hang and timeout. We don't
9427 have to worry about this in synchronous mode, because in that
9428 case it's not possible to issue a command while the target is
9429 running. This is not a problem in non-stop mode, because in that
9430 case, the stub is always ready to process serial input. */
9431 if (!target_is_non_stop_p ()
9432 && target_is_async_p ()
9433 && rs->waiting_for_stop_reply)
9434 {
9435 error (_("Cannot execute this command while the target is running.\n"
9436 "Use the \"interrupt\" command to stop the target\n"
9437 "and then try again."));
9438 }
9439
9440 /* We're sending out a new packet. Make sure we don't look at a
9441 stale cached response. */
9442 rs->cached_wait_status = 0;
9443
9444 /* Copy the packet into buffer BUF2, encapsulating it
9445 and giving it a checksum. */
9446
9447 p = buf2;
9448 *p++ = '$';
9449
9450 for (i = 0; i < cnt; i++)
9451 {
9452 csum += buf[i];
9453 *p++ = buf[i];
9454 }
9455 *p++ = '#';
9456 *p++ = tohex ((csum >> 4) & 0xf);
9457 *p++ = tohex (csum & 0xf);
9458
9459 /* Send it over and over until we get a positive ack. */
9460
9461 while (1)
9462 {
9463 if (remote_debug)
9464 {
9465 *p = '\0';
9466
9467 int len = (int) (p - buf2);
9468 int max_chars;
9469
9470 if (remote_packet_max_chars < 0)
9471 max_chars = len;
9472 else
9473 max_chars = remote_packet_max_chars;
9474
9475 std::string str
9476 = escape_buffer (buf2, std::min (len, max_chars));
9477
9478 if (len > max_chars)
9479 remote_debug_printf_nofunc
9480 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9481 len - max_chars);
9482 else
9483 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9484 }
9485 remote_serial_write (buf2, p - buf2);
9486
9487 /* If this is a no acks version of the remote protocol, send the
9488 packet and move on. */
9489 if (rs->noack_mode)
9490 break;
9491
9492 /* Read until either a timeout occurs (-2) or '+' is read.
9493 Handle any notification that arrives in the mean time. */
9494 while (1)
9495 {
9496 ch = readchar (remote_timeout);
9497
9498 switch (ch)
9499 {
9500 case '+':
9501 remote_debug_printf_nofunc ("Received Ack");
9502 return 1;
9503 case '-':
9504 remote_debug_printf_nofunc ("Received Nak");
9505 /* FALLTHROUGH */
9506 case SERIAL_TIMEOUT:
9507 tcount++;
9508 if (tcount > 3)
9509 return 0;
9510 break; /* Retransmit buffer. */
9511 case '$':
9512 {
9513 remote_debug_printf ("Packet instead of Ack, ignoring it");
9514 /* It's probably an old response sent because an ACK
9515 was lost. Gobble up the packet and ack it so it
9516 doesn't get retransmitted when we resend this
9517 packet. */
9518 skip_frame ();
9519 remote_serial_write ("+", 1);
9520 continue; /* Now, go look for +. */
9521 }
9522
9523 case '%':
9524 {
9525 int val;
9526
9527 /* If we got a notification, handle it, and go back to looking
9528 for an ack. */
9529 /* We've found the start of a notification. Now
9530 collect the data. */
9531 val = read_frame (&rs->buf);
9532 if (val >= 0)
9533 {
9534 remote_debug_printf_nofunc
9535 (" Notification received: %s",
9536 escape_buffer (rs->buf.data (), val).c_str ());
9537
9538 handle_notification (rs->notif_state, rs->buf.data ());
9539 /* We're in sync now, rewait for the ack. */
9540 tcount = 0;
9541 }
9542 else
9543 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9544 rs->buf.data ());
9545 continue;
9546 }
9547 /* fall-through */
9548 default:
9549 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9550 rs->buf.data ());
9551 continue;
9552 }
9553 break; /* Here to retransmit. */
9554 }
9555
9556 #if 0
9557 /* This is wrong. If doing a long backtrace, the user should be
9558 able to get out next time we call QUIT, without anything as
9559 violent as interrupt_query. If we want to provide a way out of
9560 here without getting to the next QUIT, it should be based on
9561 hitting ^C twice as in remote_wait. */
9562 if (quit_flag)
9563 {
9564 quit_flag = 0;
9565 interrupt_query ();
9566 }
9567 #endif
9568 }
9569
9570 return 0;
9571 }
9572
9573 /* Come here after finding the start of a frame when we expected an
9574 ack. Do our best to discard the rest of this packet. */
9575
9576 void
9577 remote_target::skip_frame ()
9578 {
9579 int c;
9580
9581 while (1)
9582 {
9583 c = readchar (remote_timeout);
9584 switch (c)
9585 {
9586 case SERIAL_TIMEOUT:
9587 /* Nothing we can do. */
9588 return;
9589 case '#':
9590 /* Discard the two bytes of checksum and stop. */
9591 c = readchar (remote_timeout);
9592 if (c >= 0)
9593 c = readchar (remote_timeout);
9594
9595 return;
9596 case '*': /* Run length encoding. */
9597 /* Discard the repeat count. */
9598 c = readchar (remote_timeout);
9599 if (c < 0)
9600 return;
9601 break;
9602 default:
9603 /* A regular character. */
9604 break;
9605 }
9606 }
9607 }
9608
9609 /* Come here after finding the start of the frame. Collect the rest
9610 into *BUF, verifying the checksum, length, and handling run-length
9611 compression. NUL terminate the buffer. If there is not enough room,
9612 expand *BUF.
9613
9614 Returns -1 on error, number of characters in buffer (ignoring the
9615 trailing NULL) on success. (could be extended to return one of the
9616 SERIAL status indications). */
9617
9618 long
9619 remote_target::read_frame (gdb::char_vector *buf_p)
9620 {
9621 unsigned char csum;
9622 long bc;
9623 int c;
9624 char *buf = buf_p->data ();
9625 struct remote_state *rs = get_remote_state ();
9626
9627 csum = 0;
9628 bc = 0;
9629
9630 while (1)
9631 {
9632 c = readchar (remote_timeout);
9633 switch (c)
9634 {
9635 case SERIAL_TIMEOUT:
9636 remote_debug_printf ("Timeout in mid-packet, retrying");
9637 return -1;
9638
9639 case '$':
9640 remote_debug_printf ("Saw new packet start in middle of old one");
9641 return -1; /* Start a new packet, count retries. */
9642
9643 case '#':
9644 {
9645 unsigned char pktcsum;
9646 int check_0 = 0;
9647 int check_1 = 0;
9648
9649 buf[bc] = '\0';
9650
9651 check_0 = readchar (remote_timeout);
9652 if (check_0 >= 0)
9653 check_1 = readchar (remote_timeout);
9654
9655 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9656 {
9657 remote_debug_printf ("Timeout in checksum, retrying");
9658 return -1;
9659 }
9660 else if (check_0 < 0 || check_1 < 0)
9661 {
9662 remote_debug_printf ("Communication error in checksum");
9663 return -1;
9664 }
9665
9666 /* Don't recompute the checksum; with no ack packets we
9667 don't have any way to indicate a packet retransmission
9668 is necessary. */
9669 if (rs->noack_mode)
9670 return bc;
9671
9672 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9673 if (csum == pktcsum)
9674 return bc;
9675
9676 remote_debug_printf
9677 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
9678 pktcsum, csum, escape_buffer (buf, bc).c_str ());
9679
9680 /* Number of characters in buffer ignoring trailing
9681 NULL. */
9682 return -1;
9683 }
9684 case '*': /* Run length encoding. */
9685 {
9686 int repeat;
9687
9688 csum += c;
9689 c = readchar (remote_timeout);
9690 csum += c;
9691 repeat = c - ' ' + 3; /* Compute repeat count. */
9692
9693 /* The character before ``*'' is repeated. */
9694
9695 if (repeat > 0 && repeat <= 255 && bc > 0)
9696 {
9697 if (bc + repeat - 1 >= buf_p->size () - 1)
9698 {
9699 /* Make some more room in the buffer. */
9700 buf_p->resize (buf_p->size () + repeat);
9701 buf = buf_p->data ();
9702 }
9703
9704 memset (&buf[bc], buf[bc - 1], repeat);
9705 bc += repeat;
9706 continue;
9707 }
9708
9709 buf[bc] = '\0';
9710 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9711 return -1;
9712 }
9713 default:
9714 if (bc >= buf_p->size () - 1)
9715 {
9716 /* Make some more room in the buffer. */
9717 buf_p->resize (buf_p->size () * 2);
9718 buf = buf_p->data ();
9719 }
9720
9721 buf[bc++] = c;
9722 csum += c;
9723 continue;
9724 }
9725 }
9726 }
9727
9728 /* Set this to the maximum number of seconds to wait instead of waiting forever
9729 in target_wait(). If this timer times out, then it generates an error and
9730 the command is aborted. This replaces most of the need for timeouts in the
9731 GDB test suite, and makes it possible to distinguish between a hung target
9732 and one with slow communications. */
9733
9734 static int watchdog = 0;
9735 static void
9736 show_watchdog (struct ui_file *file, int from_tty,
9737 struct cmd_list_element *c, const char *value)
9738 {
9739 fprintf_filtered (file, _("Watchdog timer is %s.\n"), value);
9740 }
9741
9742 /* Read a packet from the remote machine, with error checking, and
9743 store it in *BUF. Resize *BUF if necessary to hold the result. If
9744 FOREVER, wait forever rather than timing out; this is used (in
9745 synchronous mode) to wait for a target that is is executing user
9746 code to stop. */
9747 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9748 don't have to change all the calls to getpkt to deal with the
9749 return value, because at the moment I don't know what the right
9750 thing to do it for those. */
9751
9752 void
9753 remote_target::getpkt (gdb::char_vector *buf, int forever)
9754 {
9755 getpkt_sane (buf, forever);
9756 }
9757
9758
9759 /* Read a packet from the remote machine, with error checking, and
9760 store it in *BUF. Resize *BUF if necessary to hold the result. If
9761 FOREVER, wait forever rather than timing out; this is used (in
9762 synchronous mode) to wait for a target that is is executing user
9763 code to stop. If FOREVER == 0, this function is allowed to time
9764 out gracefully and return an indication of this to the caller.
9765 Otherwise return the number of bytes read. If EXPECTING_NOTIF,
9766 consider receiving a notification enough reason to return to the
9767 caller. *IS_NOTIF is an output boolean that indicates whether *BUF
9768 holds a notification or not (a regular packet). */
9769
9770 int
9771 remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
9772 int forever, int expecting_notif,
9773 int *is_notif)
9774 {
9775 struct remote_state *rs = get_remote_state ();
9776 int c;
9777 int tries;
9778 int timeout;
9779 int val = -1;
9780
9781 /* We're reading a new response. Make sure we don't look at a
9782 previously cached response. */
9783 rs->cached_wait_status = 0;
9784
9785 strcpy (buf->data (), "timeout");
9786
9787 if (forever)
9788 timeout = watchdog > 0 ? watchdog : -1;
9789 else if (expecting_notif)
9790 timeout = 0; /* There should already be a char in the buffer. If
9791 not, bail out. */
9792 else
9793 timeout = remote_timeout;
9794
9795 #define MAX_TRIES 3
9796
9797 /* Process any number of notifications, and then return when
9798 we get a packet. */
9799 for (;;)
9800 {
9801 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9802 times. */
9803 for (tries = 1; tries <= MAX_TRIES; tries++)
9804 {
9805 /* This can loop forever if the remote side sends us
9806 characters continuously, but if it pauses, we'll get
9807 SERIAL_TIMEOUT from readchar because of timeout. Then
9808 we'll count that as a retry.
9809
9810 Note that even when forever is set, we will only wait
9811 forever prior to the start of a packet. After that, we
9812 expect characters to arrive at a brisk pace. They should
9813 show up within remote_timeout intervals. */
9814 do
9815 c = readchar (timeout);
9816 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9817
9818 if (c == SERIAL_TIMEOUT)
9819 {
9820 if (expecting_notif)
9821 return -1; /* Don't complain, it's normal to not get
9822 anything in this case. */
9823
9824 if (forever) /* Watchdog went off? Kill the target. */
9825 {
9826 remote_unpush_target (this);
9827 throw_error (TARGET_CLOSE_ERROR,
9828 _("Watchdog timeout has expired. "
9829 "Target detached."));
9830 }
9831
9832 remote_debug_printf ("Timed out.");
9833 }
9834 else
9835 {
9836 /* We've found the start of a packet or notification.
9837 Now collect the data. */
9838 val = read_frame (buf);
9839 if (val >= 0)
9840 break;
9841 }
9842
9843 remote_serial_write ("-", 1);
9844 }
9845
9846 if (tries > MAX_TRIES)
9847 {
9848 /* We have tried hard enough, and just can't receive the
9849 packet/notification. Give up. */
9850 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9851
9852 /* Skip the ack char if we're in no-ack mode. */
9853 if (!rs->noack_mode)
9854 remote_serial_write ("+", 1);
9855 return -1;
9856 }
9857
9858 /* If we got an ordinary packet, return that to our caller. */
9859 if (c == '$')
9860 {
9861 if (remote_debug)
9862 {
9863 int max_chars;
9864
9865 if (remote_packet_max_chars < 0)
9866 max_chars = val;
9867 else
9868 max_chars = remote_packet_max_chars;
9869
9870 std::string str
9871 = escape_buffer (buf->data (),
9872 std::min (val, max_chars));
9873
9874 if (val > max_chars)
9875 remote_debug_printf_nofunc
9876 ("Packet received: %s [%d bytes omitted]", str.c_str (),
9877 val - max_chars);
9878 else
9879 remote_debug_printf_nofunc ("Packet received: %s",
9880 str.c_str ());
9881 }
9882
9883 /* Skip the ack char if we're in no-ack mode. */
9884 if (!rs->noack_mode)
9885 remote_serial_write ("+", 1);
9886 if (is_notif != NULL)
9887 *is_notif = 0;
9888 return val;
9889 }
9890
9891 /* If we got a notification, handle it, and go back to looking
9892 for a packet. */
9893 else
9894 {
9895 gdb_assert (c == '%');
9896
9897 remote_debug_printf_nofunc
9898 (" Notification received: %s",
9899 escape_buffer (buf->data (), val).c_str ());
9900
9901 if (is_notif != NULL)
9902 *is_notif = 1;
9903
9904 handle_notification (rs->notif_state, buf->data ());
9905
9906 /* Notifications require no acknowledgement. */
9907
9908 if (expecting_notif)
9909 return val;
9910 }
9911 }
9912 }
9913
9914 int
9915 remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
9916 {
9917 return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
9918 }
9919
9920 int
9921 remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
9922 int *is_notif)
9923 {
9924 return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
9925 }
9926
9927 /* Kill any new fork children of process PID that haven't been
9928 processed by follow_fork. */
9929
9930 void
9931 remote_target::kill_new_fork_children (int pid)
9932 {
9933 remote_state *rs = get_remote_state ();
9934 struct notif_client *notif = &notif_client_stop;
9935
9936 /* Kill the fork child threads of any threads in process PID
9937 that are stopped at a fork event. */
9938 for (thread_info *thread : all_non_exited_threads (this))
9939 {
9940 struct target_waitstatus *ws = &thread->pending_follow;
9941
9942 if (is_pending_fork_parent (ws, pid, thread->ptid))
9943 {
9944 int child_pid = ws->value.related_pid.pid ();
9945 int res;
9946
9947 res = remote_vkill (child_pid);
9948 if (res != 0)
9949 error (_("Can't kill fork child process %d"), child_pid);
9950 }
9951 }
9952
9953 /* Check for any pending fork events (not reported or processed yet)
9954 in process PID and kill those fork child threads as well. */
9955 remote_notif_get_pending_events (notif);
9956 for (auto &event : rs->stop_reply_queue)
9957 if (is_pending_fork_parent (&event->ws, pid, event->ptid))
9958 {
9959 int child_pid = event->ws.value.related_pid.pid ();
9960 int res;
9961
9962 res = remote_vkill (child_pid);
9963 if (res != 0)
9964 error (_("Can't kill fork child process %d"), child_pid);
9965 }
9966 }
9967
9968 \f
9969 /* Target hook to kill the current inferior. */
9970
9971 void
9972 remote_target::kill ()
9973 {
9974 int res = -1;
9975 int pid = inferior_ptid.pid ();
9976 struct remote_state *rs = get_remote_state ();
9977
9978 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9979 {
9980 /* If we're stopped while forking and we haven't followed yet,
9981 kill the child task. We need to do this before killing the
9982 parent task because if this is a vfork then the parent will
9983 be sleeping. */
9984 kill_new_fork_children (pid);
9985
9986 res = remote_vkill (pid);
9987 if (res == 0)
9988 {
9989 target_mourn_inferior (inferior_ptid);
9990 return;
9991 }
9992 }
9993
9994 /* If we are in 'target remote' mode and we are killing the only
9995 inferior, then we will tell gdbserver to exit and unpush the
9996 target. */
9997 if (res == -1 && !remote_multi_process_p (rs)
9998 && number_of_live_inferiors (this) == 1)
9999 {
10000 remote_kill_k ();
10001
10002 /* We've killed the remote end, we get to mourn it. If we are
10003 not in extended mode, mourning the inferior also unpushes
10004 remote_ops from the target stack, which closes the remote
10005 connection. */
10006 target_mourn_inferior (inferior_ptid);
10007
10008 return;
10009 }
10010
10011 error (_("Can't kill process"));
10012 }
10013
10014 /* Send a kill request to the target using the 'vKill' packet. */
10015
10016 int
10017 remote_target::remote_vkill (int pid)
10018 {
10019 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
10020 return -1;
10021
10022 remote_state *rs = get_remote_state ();
10023
10024 /* Tell the remote target to detach. */
10025 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10026 putpkt (rs->buf);
10027 getpkt (&rs->buf, 0);
10028
10029 switch (packet_ok (rs->buf,
10030 &remote_protocol_packets[PACKET_vKill]))
10031 {
10032 case PACKET_OK:
10033 return 0;
10034 case PACKET_ERROR:
10035 return 1;
10036 case PACKET_UNKNOWN:
10037 return -1;
10038 default:
10039 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
10040 }
10041 }
10042
10043 /* Send a kill request to the target using the 'k' packet. */
10044
10045 void
10046 remote_target::remote_kill_k ()
10047 {
10048 /* Catch errors so the user can quit from gdb even when we
10049 aren't on speaking terms with the remote system. */
10050 try
10051 {
10052 putpkt ("k");
10053 }
10054 catch (const gdb_exception_error &ex)
10055 {
10056 if (ex.error == TARGET_CLOSE_ERROR)
10057 {
10058 /* If we got an (EOF) error that caused the target
10059 to go away, then we're done, that's what we wanted.
10060 "k" is susceptible to cause a premature EOF, given
10061 that the remote server isn't actually required to
10062 reply to "k", and it can happen that it doesn't
10063 even get to reply ACK to the "k". */
10064 return;
10065 }
10066
10067 /* Otherwise, something went wrong. We didn't actually kill
10068 the target. Just propagate the exception, and let the
10069 user or higher layers decide what to do. */
10070 throw;
10071 }
10072 }
10073
10074 void
10075 remote_target::mourn_inferior ()
10076 {
10077 struct remote_state *rs = get_remote_state ();
10078
10079 /* We're no longer interested in notification events of an inferior
10080 that exited or was killed/detached. */
10081 discard_pending_stop_replies (current_inferior ());
10082
10083 /* In 'target remote' mode with one inferior, we close the connection. */
10084 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10085 {
10086 remote_unpush_target (this);
10087 return;
10088 }
10089
10090 /* In case we got here due to an error, but we're going to stay
10091 connected. */
10092 rs->waiting_for_stop_reply = 0;
10093
10094 /* If the current general thread belonged to the process we just
10095 detached from or has exited, the remote side current general
10096 thread becomes undefined. Considering a case like this:
10097
10098 - We just got here due to a detach.
10099 - The process that we're detaching from happens to immediately
10100 report a global breakpoint being hit in non-stop mode, in the
10101 same thread we had selected before.
10102 - GDB attaches to this process again.
10103 - This event happens to be the next event we handle.
10104
10105 GDB would consider that the current general thread didn't need to
10106 be set on the stub side (with Hg), since for all it knew,
10107 GENERAL_THREAD hadn't changed.
10108
10109 Notice that although in all-stop mode, the remote server always
10110 sets the current thread to the thread reporting the stop event,
10111 that doesn't happen in non-stop mode; in non-stop, the stub *must
10112 not* change the current thread when reporting a breakpoint hit,
10113 due to the decoupling of event reporting and event handling.
10114
10115 To keep things simple, we always invalidate our notion of the
10116 current thread. */
10117 record_currthread (rs, minus_one_ptid);
10118
10119 /* Call common code to mark the inferior as not running. */
10120 generic_mourn_inferior ();
10121 }
10122
10123 bool
10124 extended_remote_target::supports_disable_randomization ()
10125 {
10126 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
10127 }
10128
10129 void
10130 remote_target::extended_remote_disable_randomization (int val)
10131 {
10132 struct remote_state *rs = get_remote_state ();
10133 char *reply;
10134
10135 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10136 "QDisableRandomization:%x", val);
10137 putpkt (rs->buf);
10138 reply = remote_get_noisy_reply ();
10139 if (*reply == '\0')
10140 error (_("Target does not support QDisableRandomization."));
10141 if (strcmp (reply, "OK") != 0)
10142 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10143 }
10144
10145 int
10146 remote_target::extended_remote_run (const std::string &args)
10147 {
10148 struct remote_state *rs = get_remote_state ();
10149 int len;
10150 const char *remote_exec_file = get_remote_exec_file ();
10151
10152 /* If the user has disabled vRun support, or we have detected that
10153 support is not available, do not try it. */
10154 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
10155 return -1;
10156
10157 strcpy (rs->buf.data (), "vRun;");
10158 len = strlen (rs->buf.data ());
10159
10160 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10161 error (_("Remote file name too long for run packet"));
10162 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10163 strlen (remote_exec_file));
10164
10165 if (!args.empty ())
10166 {
10167 int i;
10168
10169 gdb_argv argv (args.c_str ());
10170 for (i = 0; argv[i] != NULL; i++)
10171 {
10172 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10173 error (_("Argument list too long for run packet"));
10174 rs->buf[len++] = ';';
10175 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10176 strlen (argv[i]));
10177 }
10178 }
10179
10180 rs->buf[len++] = '\0';
10181
10182 putpkt (rs->buf);
10183 getpkt (&rs->buf, 0);
10184
10185 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
10186 {
10187 case PACKET_OK:
10188 /* We have a wait response. All is well. */
10189 return 0;
10190 case PACKET_UNKNOWN:
10191 return -1;
10192 case PACKET_ERROR:
10193 if (remote_exec_file[0] == '\0')
10194 error (_("Running the default executable on the remote target failed; "
10195 "try \"set remote exec-file\"?"));
10196 else
10197 error (_("Running \"%s\" on the remote target failed"),
10198 remote_exec_file);
10199 default:
10200 gdb_assert_not_reached (_("bad switch"));
10201 }
10202 }
10203
10204 /* Helper function to send set/unset environment packets. ACTION is
10205 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10206 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10207 sent. */
10208
10209 void
10210 remote_target::send_environment_packet (const char *action,
10211 const char *packet,
10212 const char *value)
10213 {
10214 remote_state *rs = get_remote_state ();
10215
10216 /* Convert the environment variable to an hex string, which
10217 is the best format to be transmitted over the wire. */
10218 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10219 strlen (value));
10220
10221 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10222 "%s:%s", packet, encoded_value.c_str ());
10223
10224 putpkt (rs->buf);
10225 getpkt (&rs->buf, 0);
10226 if (strcmp (rs->buf.data (), "OK") != 0)
10227 warning (_("Unable to %s environment variable '%s' on remote."),
10228 action, value);
10229 }
10230
10231 /* Helper function to handle the QEnvironment* packets. */
10232
10233 void
10234 remote_target::extended_remote_environment_support ()
10235 {
10236 remote_state *rs = get_remote_state ();
10237
10238 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10239 {
10240 putpkt ("QEnvironmentReset");
10241 getpkt (&rs->buf, 0);
10242 if (strcmp (rs->buf.data (), "OK") != 0)
10243 warning (_("Unable to reset environment on remote."));
10244 }
10245
10246 gdb_environ *e = &current_inferior ()->environment;
10247
10248 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10249 for (const std::string &el : e->user_set_env ())
10250 send_environment_packet ("set", "QEnvironmentHexEncoded",
10251 el.c_str ());
10252
10253 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10254 for (const std::string &el : e->user_unset_env ())
10255 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10256 }
10257
10258 /* Helper function to set the current working directory for the
10259 inferior in the remote target. */
10260
10261 void
10262 remote_target::extended_remote_set_inferior_cwd ()
10263 {
10264 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10265 {
10266 const char *inferior_cwd = get_inferior_cwd ();
10267 remote_state *rs = get_remote_state ();
10268
10269 if (inferior_cwd != NULL)
10270 {
10271 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
10272 strlen (inferior_cwd));
10273
10274 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10275 "QSetWorkingDir:%s", hexpath.c_str ());
10276 }
10277 else
10278 {
10279 /* An empty inferior_cwd means that the user wants us to
10280 reset the remote server's inferior's cwd. */
10281 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10282 "QSetWorkingDir:");
10283 }
10284
10285 putpkt (rs->buf);
10286 getpkt (&rs->buf, 0);
10287 if (packet_ok (rs->buf,
10288 &remote_protocol_packets[PACKET_QSetWorkingDir])
10289 != PACKET_OK)
10290 error (_("\
10291 Remote replied unexpectedly while setting the inferior's working\n\
10292 directory: %s"),
10293 rs->buf.data ());
10294
10295 }
10296 }
10297
10298 /* In the extended protocol we want to be able to do things like
10299 "run" and have them basically work as expected. So we need
10300 a special create_inferior function. We support changing the
10301 executable file and the command line arguments, but not the
10302 environment. */
10303
10304 void
10305 extended_remote_target::create_inferior (const char *exec_file,
10306 const std::string &args,
10307 char **env, int from_tty)
10308 {
10309 int run_worked;
10310 char *stop_reply;
10311 struct remote_state *rs = get_remote_state ();
10312 const char *remote_exec_file = get_remote_exec_file ();
10313
10314 /* If running asynchronously, register the target file descriptor
10315 with the event loop. */
10316 if (target_can_async_p ())
10317 target_async (1);
10318
10319 /* Disable address space randomization if requested (and supported). */
10320 if (supports_disable_randomization ())
10321 extended_remote_disable_randomization (disable_randomization);
10322
10323 /* If startup-with-shell is on, we inform gdbserver to start the
10324 remote inferior using a shell. */
10325 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10326 {
10327 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10328 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10329 putpkt (rs->buf);
10330 getpkt (&rs->buf, 0);
10331 if (strcmp (rs->buf.data (), "OK") != 0)
10332 error (_("\
10333 Remote replied unexpectedly while setting startup-with-shell: %s"),
10334 rs->buf.data ());
10335 }
10336
10337 extended_remote_environment_support ();
10338
10339 extended_remote_set_inferior_cwd ();
10340
10341 /* Now restart the remote server. */
10342 run_worked = extended_remote_run (args) != -1;
10343 if (!run_worked)
10344 {
10345 /* vRun was not supported. Fail if we need it to do what the
10346 user requested. */
10347 if (remote_exec_file[0])
10348 error (_("Remote target does not support \"set remote exec-file\""));
10349 if (!args.empty ())
10350 error (_("Remote target does not support \"set args\" or run ARGS"));
10351
10352 /* Fall back to "R". */
10353 extended_remote_restart ();
10354 }
10355
10356 /* vRun's success return is a stop reply. */
10357 stop_reply = run_worked ? rs->buf.data () : NULL;
10358 add_current_inferior_and_thread (stop_reply);
10359
10360 /* Get updated offsets, if the stub uses qOffsets. */
10361 get_offsets ();
10362 }
10363 \f
10364
10365 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10366 the list of conditions (in agent expression bytecode format), if any, the
10367 target needs to evaluate. The output is placed into the packet buffer
10368 started from BUF and ended at BUF_END. */
10369
10370 static int
10371 remote_add_target_side_condition (struct gdbarch *gdbarch,
10372 struct bp_target_info *bp_tgt, char *buf,
10373 char *buf_end)
10374 {
10375 if (bp_tgt->conditions.empty ())
10376 return 0;
10377
10378 buf += strlen (buf);
10379 xsnprintf (buf, buf_end - buf, "%s", ";");
10380 buf++;
10381
10382 /* Send conditions to the target. */
10383 for (agent_expr *aexpr : bp_tgt->conditions)
10384 {
10385 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10386 buf += strlen (buf);
10387 for (int i = 0; i < aexpr->len; ++i)
10388 buf = pack_hex_byte (buf, aexpr->buf[i]);
10389 *buf = '\0';
10390 }
10391 return 0;
10392 }
10393
10394 static void
10395 remote_add_target_side_commands (struct gdbarch *gdbarch,
10396 struct bp_target_info *bp_tgt, char *buf)
10397 {
10398 if (bp_tgt->tcommands.empty ())
10399 return;
10400
10401 buf += strlen (buf);
10402
10403 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10404 buf += strlen (buf);
10405
10406 /* Concatenate all the agent expressions that are commands into the
10407 cmds parameter. */
10408 for (agent_expr *aexpr : bp_tgt->tcommands)
10409 {
10410 sprintf (buf, "X%x,", aexpr->len);
10411 buf += strlen (buf);
10412 for (int i = 0; i < aexpr->len; ++i)
10413 buf = pack_hex_byte (buf, aexpr->buf[i]);
10414 *buf = '\0';
10415 }
10416 }
10417
10418 /* Insert a breakpoint. On targets that have software breakpoint
10419 support, we ask the remote target to do the work; on targets
10420 which don't, we insert a traditional memory breakpoint. */
10421
10422 int
10423 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10424 struct bp_target_info *bp_tgt)
10425 {
10426 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10427 If it succeeds, then set the support to PACKET_ENABLE. If it
10428 fails, and the user has explicitly requested the Z support then
10429 report an error, otherwise, mark it disabled and go on. */
10430
10431 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10432 {
10433 CORE_ADDR addr = bp_tgt->reqstd_address;
10434 struct remote_state *rs;
10435 char *p, *endbuf;
10436
10437 /* Make sure the remote is pointing at the right process, if
10438 necessary. */
10439 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10440 set_general_process ();
10441
10442 rs = get_remote_state ();
10443 p = rs->buf.data ();
10444 endbuf = p + get_remote_packet_size ();
10445
10446 *(p++) = 'Z';
10447 *(p++) = '0';
10448 *(p++) = ',';
10449 addr = (ULONGEST) remote_address_masked (addr);
10450 p += hexnumstr (p, addr);
10451 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10452
10453 if (supports_evaluation_of_breakpoint_conditions ())
10454 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10455
10456 if (can_run_breakpoint_commands ())
10457 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10458
10459 putpkt (rs->buf);
10460 getpkt (&rs->buf, 0);
10461
10462 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10463 {
10464 case PACKET_ERROR:
10465 return -1;
10466 case PACKET_OK:
10467 return 0;
10468 case PACKET_UNKNOWN:
10469 break;
10470 }
10471 }
10472
10473 /* If this breakpoint has target-side commands but this stub doesn't
10474 support Z0 packets, throw error. */
10475 if (!bp_tgt->tcommands.empty ())
10476 throw_error (NOT_SUPPORTED_ERROR, _("\
10477 Target doesn't support breakpoints that have target side commands."));
10478
10479 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10480 }
10481
10482 int
10483 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10484 struct bp_target_info *bp_tgt,
10485 enum remove_bp_reason reason)
10486 {
10487 CORE_ADDR addr = bp_tgt->placed_address;
10488 struct remote_state *rs = get_remote_state ();
10489
10490 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10491 {
10492 char *p = rs->buf.data ();
10493 char *endbuf = p + get_remote_packet_size ();
10494
10495 /* Make sure the remote is pointing at the right process, if
10496 necessary. */
10497 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10498 set_general_process ();
10499
10500 *(p++) = 'z';
10501 *(p++) = '0';
10502 *(p++) = ',';
10503
10504 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10505 p += hexnumstr (p, addr);
10506 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10507
10508 putpkt (rs->buf);
10509 getpkt (&rs->buf, 0);
10510
10511 return (rs->buf[0] == 'E');
10512 }
10513
10514 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10515 }
10516
10517 static enum Z_packet_type
10518 watchpoint_to_Z_packet (int type)
10519 {
10520 switch (type)
10521 {
10522 case hw_write:
10523 return Z_PACKET_WRITE_WP;
10524 break;
10525 case hw_read:
10526 return Z_PACKET_READ_WP;
10527 break;
10528 case hw_access:
10529 return Z_PACKET_ACCESS_WP;
10530 break;
10531 default:
10532 internal_error (__FILE__, __LINE__,
10533 _("hw_bp_to_z: bad watchpoint type %d"), type);
10534 }
10535 }
10536
10537 int
10538 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10539 enum target_hw_bp_type type, struct expression *cond)
10540 {
10541 struct remote_state *rs = get_remote_state ();
10542 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10543 char *p;
10544 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10545
10546 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10547 return 1;
10548
10549 /* Make sure the remote is pointing at the right process, if
10550 necessary. */
10551 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10552 set_general_process ();
10553
10554 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10555 p = strchr (rs->buf.data (), '\0');
10556 addr = remote_address_masked (addr);
10557 p += hexnumstr (p, (ULONGEST) addr);
10558 xsnprintf (p, endbuf - p, ",%x", len);
10559
10560 putpkt (rs->buf);
10561 getpkt (&rs->buf, 0);
10562
10563 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10564 {
10565 case PACKET_ERROR:
10566 return -1;
10567 case PACKET_UNKNOWN:
10568 return 1;
10569 case PACKET_OK:
10570 return 0;
10571 }
10572 internal_error (__FILE__, __LINE__,
10573 _("remote_insert_watchpoint: reached end of function"));
10574 }
10575
10576 bool
10577 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10578 CORE_ADDR start, int length)
10579 {
10580 CORE_ADDR diff = remote_address_masked (addr - start);
10581
10582 return diff < length;
10583 }
10584
10585
10586 int
10587 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10588 enum target_hw_bp_type type, struct expression *cond)
10589 {
10590 struct remote_state *rs = get_remote_state ();
10591 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10592 char *p;
10593 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10594
10595 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10596 return -1;
10597
10598 /* Make sure the remote is pointing at the right process, if
10599 necessary. */
10600 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10601 set_general_process ();
10602
10603 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10604 p = strchr (rs->buf.data (), '\0');
10605 addr = remote_address_masked (addr);
10606 p += hexnumstr (p, (ULONGEST) addr);
10607 xsnprintf (p, endbuf - p, ",%x", len);
10608 putpkt (rs->buf);
10609 getpkt (&rs->buf, 0);
10610
10611 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10612 {
10613 case PACKET_ERROR:
10614 case PACKET_UNKNOWN:
10615 return -1;
10616 case PACKET_OK:
10617 return 0;
10618 }
10619 internal_error (__FILE__, __LINE__,
10620 _("remote_remove_watchpoint: reached end of function"));
10621 }
10622
10623
10624 static int remote_hw_watchpoint_limit = -1;
10625 static int remote_hw_watchpoint_length_limit = -1;
10626 static int remote_hw_breakpoint_limit = -1;
10627
10628 int
10629 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10630 {
10631 if (remote_hw_watchpoint_length_limit == 0)
10632 return 0;
10633 else if (remote_hw_watchpoint_length_limit < 0)
10634 return 1;
10635 else if (len <= remote_hw_watchpoint_length_limit)
10636 return 1;
10637 else
10638 return 0;
10639 }
10640
10641 int
10642 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10643 {
10644 if (type == bp_hardware_breakpoint)
10645 {
10646 if (remote_hw_breakpoint_limit == 0)
10647 return 0;
10648 else if (remote_hw_breakpoint_limit < 0)
10649 return 1;
10650 else if (cnt <= remote_hw_breakpoint_limit)
10651 return 1;
10652 }
10653 else
10654 {
10655 if (remote_hw_watchpoint_limit == 0)
10656 return 0;
10657 else if (remote_hw_watchpoint_limit < 0)
10658 return 1;
10659 else if (ot)
10660 return -1;
10661 else if (cnt <= remote_hw_watchpoint_limit)
10662 return 1;
10663 }
10664 return -1;
10665 }
10666
10667 /* The to_stopped_by_sw_breakpoint method of target remote. */
10668
10669 bool
10670 remote_target::stopped_by_sw_breakpoint ()
10671 {
10672 struct thread_info *thread = inferior_thread ();
10673
10674 return (thread->priv != NULL
10675 && (get_remote_thread_info (thread)->stop_reason
10676 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10677 }
10678
10679 /* The to_supports_stopped_by_sw_breakpoint method of target
10680 remote. */
10681
10682 bool
10683 remote_target::supports_stopped_by_sw_breakpoint ()
10684 {
10685 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10686 }
10687
10688 /* The to_stopped_by_hw_breakpoint method of target remote. */
10689
10690 bool
10691 remote_target::stopped_by_hw_breakpoint ()
10692 {
10693 struct thread_info *thread = inferior_thread ();
10694
10695 return (thread->priv != NULL
10696 && (get_remote_thread_info (thread)->stop_reason
10697 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10698 }
10699
10700 /* The to_supports_stopped_by_hw_breakpoint method of target
10701 remote. */
10702
10703 bool
10704 remote_target::supports_stopped_by_hw_breakpoint ()
10705 {
10706 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10707 }
10708
10709 bool
10710 remote_target::stopped_by_watchpoint ()
10711 {
10712 struct thread_info *thread = inferior_thread ();
10713
10714 return (thread->priv != NULL
10715 && (get_remote_thread_info (thread)->stop_reason
10716 == TARGET_STOPPED_BY_WATCHPOINT));
10717 }
10718
10719 bool
10720 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10721 {
10722 struct thread_info *thread = inferior_thread ();
10723
10724 if (thread->priv != NULL
10725 && (get_remote_thread_info (thread)->stop_reason
10726 == TARGET_STOPPED_BY_WATCHPOINT))
10727 {
10728 *addr_p = get_remote_thread_info (thread)->watch_data_address;
10729 return true;
10730 }
10731
10732 return false;
10733 }
10734
10735
10736 int
10737 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10738 struct bp_target_info *bp_tgt)
10739 {
10740 CORE_ADDR addr = bp_tgt->reqstd_address;
10741 struct remote_state *rs;
10742 char *p, *endbuf;
10743 char *message;
10744
10745 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10746 return -1;
10747
10748 /* Make sure the remote is pointing at the right process, if
10749 necessary. */
10750 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10751 set_general_process ();
10752
10753 rs = get_remote_state ();
10754 p = rs->buf.data ();
10755 endbuf = p + get_remote_packet_size ();
10756
10757 *(p++) = 'Z';
10758 *(p++) = '1';
10759 *(p++) = ',';
10760
10761 addr = remote_address_masked (addr);
10762 p += hexnumstr (p, (ULONGEST) addr);
10763 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10764
10765 if (supports_evaluation_of_breakpoint_conditions ())
10766 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10767
10768 if (can_run_breakpoint_commands ())
10769 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10770
10771 putpkt (rs->buf);
10772 getpkt (&rs->buf, 0);
10773
10774 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10775 {
10776 case PACKET_ERROR:
10777 if (rs->buf[1] == '.')
10778 {
10779 message = strchr (&rs->buf[2], '.');
10780 if (message)
10781 error (_("Remote failure reply: %s"), message + 1);
10782 }
10783 return -1;
10784 case PACKET_UNKNOWN:
10785 return -1;
10786 case PACKET_OK:
10787 return 0;
10788 }
10789 internal_error (__FILE__, __LINE__,
10790 _("remote_insert_hw_breakpoint: reached end of function"));
10791 }
10792
10793
10794 int
10795 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10796 struct bp_target_info *bp_tgt)
10797 {
10798 CORE_ADDR addr;
10799 struct remote_state *rs = get_remote_state ();
10800 char *p = rs->buf.data ();
10801 char *endbuf = p + get_remote_packet_size ();
10802
10803 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10804 return -1;
10805
10806 /* Make sure the remote is pointing at the right process, if
10807 necessary. */
10808 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10809 set_general_process ();
10810
10811 *(p++) = 'z';
10812 *(p++) = '1';
10813 *(p++) = ',';
10814
10815 addr = remote_address_masked (bp_tgt->placed_address);
10816 p += hexnumstr (p, (ULONGEST) addr);
10817 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10818
10819 putpkt (rs->buf);
10820 getpkt (&rs->buf, 0);
10821
10822 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10823 {
10824 case PACKET_ERROR:
10825 case PACKET_UNKNOWN:
10826 return -1;
10827 case PACKET_OK:
10828 return 0;
10829 }
10830 internal_error (__FILE__, __LINE__,
10831 _("remote_remove_hw_breakpoint: reached end of function"));
10832 }
10833
10834 /* Verify memory using the "qCRC:" request. */
10835
10836 int
10837 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10838 {
10839 struct remote_state *rs = get_remote_state ();
10840 unsigned long host_crc, target_crc;
10841 char *tmp;
10842
10843 /* It doesn't make sense to use qCRC if the remote target is
10844 connected but not running. */
10845 if (target_has_execution ()
10846 && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10847 {
10848 enum packet_result result;
10849
10850 /* Make sure the remote is pointing at the right process. */
10851 set_general_process ();
10852
10853 /* FIXME: assumes lma can fit into long. */
10854 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
10855 (long) lma, (long) size);
10856 putpkt (rs->buf);
10857
10858 /* Be clever; compute the host_crc before waiting for target
10859 reply. */
10860 host_crc = xcrc32 (data, size, 0xffffffff);
10861
10862 getpkt (&rs->buf, 0);
10863
10864 result = packet_ok (rs->buf,
10865 &remote_protocol_packets[PACKET_qCRC]);
10866 if (result == PACKET_ERROR)
10867 return -1;
10868 else if (result == PACKET_OK)
10869 {
10870 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10871 target_crc = target_crc * 16 + fromhex (*tmp);
10872
10873 return (host_crc == target_crc);
10874 }
10875 }
10876
10877 return simple_verify_memory (this, data, lma, size);
10878 }
10879
10880 /* compare-sections command
10881
10882 With no arguments, compares each loadable section in the exec bfd
10883 with the same memory range on the target, and reports mismatches.
10884 Useful for verifying the image on the target against the exec file. */
10885
10886 static void
10887 compare_sections_command (const char *args, int from_tty)
10888 {
10889 asection *s;
10890 const char *sectname;
10891 bfd_size_type size;
10892 bfd_vma lma;
10893 int matched = 0;
10894 int mismatched = 0;
10895 int res;
10896 int read_only = 0;
10897
10898 if (!current_program_space->exec_bfd ())
10899 error (_("command cannot be used without an exec file"));
10900
10901 if (args != NULL && strcmp (args, "-r") == 0)
10902 {
10903 read_only = 1;
10904 args = NULL;
10905 }
10906
10907 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
10908 {
10909 if (!(s->flags & SEC_LOAD))
10910 continue; /* Skip non-loadable section. */
10911
10912 if (read_only && (s->flags & SEC_READONLY) == 0)
10913 continue; /* Skip writeable sections */
10914
10915 size = bfd_section_size (s);
10916 if (size == 0)
10917 continue; /* Skip zero-length section. */
10918
10919 sectname = bfd_section_name (s);
10920 if (args && strcmp (args, sectname) != 0)
10921 continue; /* Not the section selected by user. */
10922
10923 matched = 1; /* Do this section. */
10924 lma = s->lma;
10925
10926 gdb::byte_vector sectdata (size);
10927 bfd_get_section_contents (current_program_space->exec_bfd (), s,
10928 sectdata.data (), 0, size);
10929
10930 res = target_verify_memory (sectdata.data (), lma, size);
10931
10932 if (res == -1)
10933 error (_("target memory fault, section %s, range %s -- %s"), sectname,
10934 paddress (target_gdbarch (), lma),
10935 paddress (target_gdbarch (), lma + size));
10936
10937 printf_filtered ("Section %s, range %s -- %s: ", sectname,
10938 paddress (target_gdbarch (), lma),
10939 paddress (target_gdbarch (), lma + size));
10940 if (res)
10941 printf_filtered ("matched.\n");
10942 else
10943 {
10944 printf_filtered ("MIS-MATCHED!\n");
10945 mismatched++;
10946 }
10947 }
10948 if (mismatched > 0)
10949 warning (_("One or more sections of the target image does not match\n\
10950 the loaded file\n"));
10951 if (args && !matched)
10952 printf_filtered (_("No loaded section named '%s'.\n"), args);
10953 }
10954
10955 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10956 into remote target. The number of bytes written to the remote
10957 target is returned, or -1 for error. */
10958
10959 target_xfer_status
10960 remote_target::remote_write_qxfer (const char *object_name,
10961 const char *annex, const gdb_byte *writebuf,
10962 ULONGEST offset, LONGEST len,
10963 ULONGEST *xfered_len,
10964 struct packet_config *packet)
10965 {
10966 int i, buf_len;
10967 ULONGEST n;
10968 struct remote_state *rs = get_remote_state ();
10969 int max_size = get_memory_write_packet_size ();
10970
10971 if (packet_config_support (packet) == PACKET_DISABLE)
10972 return TARGET_XFER_E_IO;
10973
10974 /* Insert header. */
10975 i = snprintf (rs->buf.data (), max_size,
10976 "qXfer:%s:write:%s:%s:",
10977 object_name, annex ? annex : "",
10978 phex_nz (offset, sizeof offset));
10979 max_size -= (i + 1);
10980
10981 /* Escape as much data as fits into rs->buf. */
10982 buf_len = remote_escape_output
10983 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
10984
10985 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
10986 || getpkt_sane (&rs->buf, 0) < 0
10987 || packet_ok (rs->buf, packet) != PACKET_OK)
10988 return TARGET_XFER_E_IO;
10989
10990 unpack_varlen_hex (rs->buf.data (), &n);
10991
10992 *xfered_len = n;
10993 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10994 }
10995
10996 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10997 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10998 number of bytes read is returned, or 0 for EOF, or -1 for error.
10999 The number of bytes read may be less than LEN without indicating an
11000 EOF. PACKET is checked and updated to indicate whether the remote
11001 target supports this object. */
11002
11003 target_xfer_status
11004 remote_target::remote_read_qxfer (const char *object_name,
11005 const char *annex,
11006 gdb_byte *readbuf, ULONGEST offset,
11007 LONGEST len,
11008 ULONGEST *xfered_len,
11009 struct packet_config *packet)
11010 {
11011 struct remote_state *rs = get_remote_state ();
11012 LONGEST i, n, packet_len;
11013
11014 if (packet_config_support (packet) == PACKET_DISABLE)
11015 return TARGET_XFER_E_IO;
11016
11017 /* Check whether we've cached an end-of-object packet that matches
11018 this request. */
11019 if (rs->finished_object)
11020 {
11021 if (strcmp (object_name, rs->finished_object) == 0
11022 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11023 && offset == rs->finished_offset)
11024 return TARGET_XFER_EOF;
11025
11026
11027 /* Otherwise, we're now reading something different. Discard
11028 the cache. */
11029 xfree (rs->finished_object);
11030 xfree (rs->finished_annex);
11031 rs->finished_object = NULL;
11032 rs->finished_annex = NULL;
11033 }
11034
11035 /* Request only enough to fit in a single packet. The actual data
11036 may not, since we don't know how much of it will need to be escaped;
11037 the target is free to respond with slightly less data. We subtract
11038 five to account for the response type and the protocol frame. */
11039 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11040 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11041 "qXfer:%s:read:%s:%s,%s",
11042 object_name, annex ? annex : "",
11043 phex_nz (offset, sizeof offset),
11044 phex_nz (n, sizeof n));
11045 i = putpkt (rs->buf);
11046 if (i < 0)
11047 return TARGET_XFER_E_IO;
11048
11049 rs->buf[0] = '\0';
11050 packet_len = getpkt_sane (&rs->buf, 0);
11051 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
11052 return TARGET_XFER_E_IO;
11053
11054 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11055 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11056
11057 /* 'm' means there is (or at least might be) more data after this
11058 batch. That does not make sense unless there's at least one byte
11059 of data in this reply. */
11060 if (rs->buf[0] == 'm' && packet_len == 1)
11061 error (_("Remote qXfer reply contained no data."));
11062
11063 /* Got some data. */
11064 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11065 packet_len - 1, readbuf, n);
11066
11067 /* 'l' is an EOF marker, possibly including a final block of data,
11068 or possibly empty. If we have the final block of a non-empty
11069 object, record this fact to bypass a subsequent partial read. */
11070 if (rs->buf[0] == 'l' && offset + i > 0)
11071 {
11072 rs->finished_object = xstrdup (object_name);
11073 rs->finished_annex = xstrdup (annex ? annex : "");
11074 rs->finished_offset = offset + i;
11075 }
11076
11077 if (i == 0)
11078 return TARGET_XFER_EOF;
11079 else
11080 {
11081 *xfered_len = i;
11082 return TARGET_XFER_OK;
11083 }
11084 }
11085
11086 enum target_xfer_status
11087 remote_target::xfer_partial (enum target_object object,
11088 const char *annex, gdb_byte *readbuf,
11089 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11090 ULONGEST *xfered_len)
11091 {
11092 struct remote_state *rs;
11093 int i;
11094 char *p2;
11095 char query_type;
11096 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
11097
11098 set_remote_traceframe ();
11099 set_general_thread (inferior_ptid);
11100
11101 rs = get_remote_state ();
11102
11103 /* Handle memory using the standard memory routines. */
11104 if (object == TARGET_OBJECT_MEMORY)
11105 {
11106 /* If the remote target is connected but not running, we should
11107 pass this request down to a lower stratum (e.g. the executable
11108 file). */
11109 if (!target_has_execution ())
11110 return TARGET_XFER_EOF;
11111
11112 if (writebuf != NULL)
11113 return remote_write_bytes (offset, writebuf, len, unit_size,
11114 xfered_len);
11115 else
11116 return remote_read_bytes (offset, readbuf, len, unit_size,
11117 xfered_len);
11118 }
11119
11120 /* Handle extra signal info using qxfer packets. */
11121 if (object == TARGET_OBJECT_SIGNAL_INFO)
11122 {
11123 if (readbuf)
11124 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11125 xfered_len, &remote_protocol_packets
11126 [PACKET_qXfer_siginfo_read]);
11127 else
11128 return remote_write_qxfer ("siginfo", annex,
11129 writebuf, offset, len, xfered_len,
11130 &remote_protocol_packets
11131 [PACKET_qXfer_siginfo_write]);
11132 }
11133
11134 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11135 {
11136 if (readbuf)
11137 return remote_read_qxfer ("statictrace", annex,
11138 readbuf, offset, len, xfered_len,
11139 &remote_protocol_packets
11140 [PACKET_qXfer_statictrace_read]);
11141 else
11142 return TARGET_XFER_E_IO;
11143 }
11144
11145 /* Only handle flash writes. */
11146 if (writebuf != NULL)
11147 {
11148 switch (object)
11149 {
11150 case TARGET_OBJECT_FLASH:
11151 return remote_flash_write (offset, len, xfered_len,
11152 writebuf);
11153
11154 default:
11155 return TARGET_XFER_E_IO;
11156 }
11157 }
11158
11159 /* Map pre-existing objects onto letters. DO NOT do this for new
11160 objects!!! Instead specify new query packets. */
11161 switch (object)
11162 {
11163 case TARGET_OBJECT_AVR:
11164 query_type = 'R';
11165 break;
11166
11167 case TARGET_OBJECT_AUXV:
11168 gdb_assert (annex == NULL);
11169 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
11170 xfered_len,
11171 &remote_protocol_packets[PACKET_qXfer_auxv]);
11172
11173 case TARGET_OBJECT_AVAILABLE_FEATURES:
11174 return remote_read_qxfer
11175 ("features", annex, readbuf, offset, len, xfered_len,
11176 &remote_protocol_packets[PACKET_qXfer_features]);
11177
11178 case TARGET_OBJECT_LIBRARIES:
11179 return remote_read_qxfer
11180 ("libraries", annex, readbuf, offset, len, xfered_len,
11181 &remote_protocol_packets[PACKET_qXfer_libraries]);
11182
11183 case TARGET_OBJECT_LIBRARIES_SVR4:
11184 return remote_read_qxfer
11185 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11186 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
11187
11188 case TARGET_OBJECT_MEMORY_MAP:
11189 gdb_assert (annex == NULL);
11190 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
11191 xfered_len,
11192 &remote_protocol_packets[PACKET_qXfer_memory_map]);
11193
11194 case TARGET_OBJECT_OSDATA:
11195 /* Should only get here if we're connected. */
11196 gdb_assert (rs->remote_desc);
11197 return remote_read_qxfer
11198 ("osdata", annex, readbuf, offset, len, xfered_len,
11199 &remote_protocol_packets[PACKET_qXfer_osdata]);
11200
11201 case TARGET_OBJECT_THREADS:
11202 gdb_assert (annex == NULL);
11203 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
11204 xfered_len,
11205 &remote_protocol_packets[PACKET_qXfer_threads]);
11206
11207 case TARGET_OBJECT_TRACEFRAME_INFO:
11208 gdb_assert (annex == NULL);
11209 return remote_read_qxfer
11210 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11211 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
11212
11213 case TARGET_OBJECT_FDPIC:
11214 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
11215 xfered_len,
11216 &remote_protocol_packets[PACKET_qXfer_fdpic]);
11217
11218 case TARGET_OBJECT_OPENVMS_UIB:
11219 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
11220 xfered_len,
11221 &remote_protocol_packets[PACKET_qXfer_uib]);
11222
11223 case TARGET_OBJECT_BTRACE:
11224 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
11225 xfered_len,
11226 &remote_protocol_packets[PACKET_qXfer_btrace]);
11227
11228 case TARGET_OBJECT_BTRACE_CONF:
11229 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
11230 len, xfered_len,
11231 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11232
11233 case TARGET_OBJECT_EXEC_FILE:
11234 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
11235 len, xfered_len,
11236 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11237
11238 default:
11239 return TARGET_XFER_E_IO;
11240 }
11241
11242 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11243 large enough let the caller deal with it. */
11244 if (len < get_remote_packet_size ())
11245 return TARGET_XFER_E_IO;
11246 len = get_remote_packet_size ();
11247
11248 /* Except for querying the minimum buffer size, target must be open. */
11249 if (!rs->remote_desc)
11250 error (_("remote query is only available after target open"));
11251
11252 gdb_assert (annex != NULL);
11253 gdb_assert (readbuf != NULL);
11254
11255 p2 = rs->buf.data ();
11256 *p2++ = 'q';
11257 *p2++ = query_type;
11258
11259 /* We used one buffer char for the remote protocol q command and
11260 another for the query type. As the remote protocol encapsulation
11261 uses 4 chars plus one extra in case we are debugging
11262 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11263 string. */
11264 i = 0;
11265 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11266 {
11267 /* Bad caller may have sent forbidden characters. */
11268 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11269 *p2++ = annex[i];
11270 i++;
11271 }
11272 *p2 = '\0';
11273 gdb_assert (annex[i] == '\0');
11274
11275 i = putpkt (rs->buf);
11276 if (i < 0)
11277 return TARGET_XFER_E_IO;
11278
11279 getpkt (&rs->buf, 0);
11280 strcpy ((char *) readbuf, rs->buf.data ());
11281
11282 *xfered_len = strlen ((char *) readbuf);
11283 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11284 }
11285
11286 /* Implementation of to_get_memory_xfer_limit. */
11287
11288 ULONGEST
11289 remote_target::get_memory_xfer_limit ()
11290 {
11291 return get_memory_write_packet_size ();
11292 }
11293
11294 int
11295 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11296 const gdb_byte *pattern, ULONGEST pattern_len,
11297 CORE_ADDR *found_addrp)
11298 {
11299 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11300 struct remote_state *rs = get_remote_state ();
11301 int max_size = get_memory_write_packet_size ();
11302 struct packet_config *packet =
11303 &remote_protocol_packets[PACKET_qSearch_memory];
11304 /* Number of packet bytes used to encode the pattern;
11305 this could be more than PATTERN_LEN due to escape characters. */
11306 int escaped_pattern_len;
11307 /* Amount of pattern that was encodable in the packet. */
11308 int used_pattern_len;
11309 int i;
11310 int found;
11311 ULONGEST found_addr;
11312
11313 auto read_memory = [=] (CORE_ADDR addr, gdb_byte *result, size_t len)
11314 {
11315 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11316 == len);
11317 };
11318
11319 /* Don't go to the target if we don't have to. This is done before
11320 checking packet_config_support to avoid the possibility that a
11321 success for this edge case means the facility works in
11322 general. */
11323 if (pattern_len > search_space_len)
11324 return 0;
11325 if (pattern_len == 0)
11326 {
11327 *found_addrp = start_addr;
11328 return 1;
11329 }
11330
11331 /* If we already know the packet isn't supported, fall back to the simple
11332 way of searching memory. */
11333
11334 if (packet_config_support (packet) == PACKET_DISABLE)
11335 {
11336 /* Target doesn't provided special support, fall back and use the
11337 standard support (copy memory and do the search here). */
11338 return simple_search_memory (read_memory, start_addr, search_space_len,
11339 pattern, pattern_len, found_addrp);
11340 }
11341
11342 /* Make sure the remote is pointing at the right process. */
11343 set_general_process ();
11344
11345 /* Insert header. */
11346 i = snprintf (rs->buf.data (), max_size,
11347 "qSearch:memory:%s;%s;",
11348 phex_nz (start_addr, addr_size),
11349 phex_nz (search_space_len, sizeof (search_space_len)));
11350 max_size -= (i + 1);
11351
11352 /* Escape as much data as fits into rs->buf. */
11353 escaped_pattern_len =
11354 remote_escape_output (pattern, pattern_len, 1,
11355 (gdb_byte *) rs->buf.data () + i,
11356 &used_pattern_len, max_size);
11357
11358 /* Bail if the pattern is too large. */
11359 if (used_pattern_len != pattern_len)
11360 error (_("Pattern is too large to transmit to remote target."));
11361
11362 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11363 || getpkt_sane (&rs->buf, 0) < 0
11364 || packet_ok (rs->buf, packet) != PACKET_OK)
11365 {
11366 /* The request may not have worked because the command is not
11367 supported. If so, fall back to the simple way. */
11368 if (packet_config_support (packet) == PACKET_DISABLE)
11369 {
11370 return simple_search_memory (read_memory, start_addr, search_space_len,
11371 pattern, pattern_len, found_addrp);
11372 }
11373 return -1;
11374 }
11375
11376 if (rs->buf[0] == '0')
11377 found = 0;
11378 else if (rs->buf[0] == '1')
11379 {
11380 found = 1;
11381 if (rs->buf[1] != ',')
11382 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11383 unpack_varlen_hex (&rs->buf[2], &found_addr);
11384 *found_addrp = found_addr;
11385 }
11386 else
11387 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11388
11389 return found;
11390 }
11391
11392 void
11393 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11394 {
11395 struct remote_state *rs = get_remote_state ();
11396 char *p = rs->buf.data ();
11397
11398 if (!rs->remote_desc)
11399 error (_("remote rcmd is only available after target open"));
11400
11401 /* Send a NULL command across as an empty command. */
11402 if (command == NULL)
11403 command = "";
11404
11405 /* The query prefix. */
11406 strcpy (rs->buf.data (), "qRcmd,");
11407 p = strchr (rs->buf.data (), '\0');
11408
11409 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11410 > get_remote_packet_size ())
11411 error (_("\"monitor\" command ``%s'' is too long."), command);
11412
11413 /* Encode the actual command. */
11414 bin2hex ((const gdb_byte *) command, p, strlen (command));
11415
11416 if (putpkt (rs->buf) < 0)
11417 error (_("Communication problem with target."));
11418
11419 /* get/display the response */
11420 while (1)
11421 {
11422 char *buf;
11423
11424 /* XXX - see also remote_get_noisy_reply(). */
11425 QUIT; /* Allow user to bail out with ^C. */
11426 rs->buf[0] = '\0';
11427 if (getpkt_sane (&rs->buf, 0) == -1)
11428 {
11429 /* Timeout. Continue to (try to) read responses.
11430 This is better than stopping with an error, assuming the stub
11431 is still executing the (long) monitor command.
11432 If needed, the user can interrupt gdb using C-c, obtaining
11433 an effect similar to stop on timeout. */
11434 continue;
11435 }
11436 buf = rs->buf.data ();
11437 if (buf[0] == '\0')
11438 error (_("Target does not support this command."));
11439 if (buf[0] == 'O' && buf[1] != 'K')
11440 {
11441 remote_console_output (buf + 1); /* 'O' message from stub. */
11442 continue;
11443 }
11444 if (strcmp (buf, "OK") == 0)
11445 break;
11446 if (strlen (buf) == 3 && buf[0] == 'E'
11447 && isdigit (buf[1]) && isdigit (buf[2]))
11448 {
11449 error (_("Protocol error with Rcmd"));
11450 }
11451 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11452 {
11453 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11454
11455 fputc_unfiltered (c, outbuf);
11456 }
11457 break;
11458 }
11459 }
11460
11461 std::vector<mem_region>
11462 remote_target::memory_map ()
11463 {
11464 std::vector<mem_region> result;
11465 gdb::optional<gdb::char_vector> text
11466 = target_read_stralloc (current_top_target (), TARGET_OBJECT_MEMORY_MAP, NULL);
11467
11468 if (text)
11469 result = parse_memory_map (text->data ());
11470
11471 return result;
11472 }
11473
11474 static void
11475 packet_command (const char *args, int from_tty)
11476 {
11477 remote_target *remote = get_current_remote_target ();
11478
11479 if (remote == nullptr)
11480 error (_("command can only be used with remote target"));
11481
11482 remote->packet_command (args, from_tty);
11483 }
11484
11485 void
11486 remote_target::packet_command (const char *args, int from_tty)
11487 {
11488 if (!args)
11489 error (_("remote-packet command requires packet text as argument"));
11490
11491 puts_filtered ("sending: ");
11492 print_packet (args);
11493 puts_filtered ("\n");
11494 putpkt (args);
11495
11496 remote_state *rs = get_remote_state ();
11497
11498 getpkt (&rs->buf, 0);
11499 puts_filtered ("received: ");
11500 print_packet (rs->buf.data ());
11501 puts_filtered ("\n");
11502 }
11503
11504 #if 0
11505 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11506
11507 static void display_thread_info (struct gdb_ext_thread_info *info);
11508
11509 static void threadset_test_cmd (char *cmd, int tty);
11510
11511 static void threadalive_test (char *cmd, int tty);
11512
11513 static void threadlist_test_cmd (char *cmd, int tty);
11514
11515 int get_and_display_threadinfo (threadref *ref);
11516
11517 static void threadinfo_test_cmd (char *cmd, int tty);
11518
11519 static int thread_display_step (threadref *ref, void *context);
11520
11521 static void threadlist_update_test_cmd (char *cmd, int tty);
11522
11523 static void init_remote_threadtests (void);
11524
11525 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11526
11527 static void
11528 threadset_test_cmd (const char *cmd, int tty)
11529 {
11530 int sample_thread = SAMPLE_THREAD;
11531
11532 printf_filtered (_("Remote threadset test\n"));
11533 set_general_thread (sample_thread);
11534 }
11535
11536
11537 static void
11538 threadalive_test (const char *cmd, int tty)
11539 {
11540 int sample_thread = SAMPLE_THREAD;
11541 int pid = inferior_ptid.pid ();
11542 ptid_t ptid = ptid_t (pid, sample_thread, 0);
11543
11544 if (remote_thread_alive (ptid))
11545 printf_filtered ("PASS: Thread alive test\n");
11546 else
11547 printf_filtered ("FAIL: Thread alive test\n");
11548 }
11549
11550 void output_threadid (char *title, threadref *ref);
11551
11552 void
11553 output_threadid (char *title, threadref *ref)
11554 {
11555 char hexid[20];
11556
11557 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
11558 hexid[16] = 0;
11559 printf_filtered ("%s %s\n", title, (&hexid[0]));
11560 }
11561
11562 static void
11563 threadlist_test_cmd (const char *cmd, int tty)
11564 {
11565 int startflag = 1;
11566 threadref nextthread;
11567 int done, result_count;
11568 threadref threadlist[3];
11569
11570 printf_filtered ("Remote Threadlist test\n");
11571 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11572 &result_count, &threadlist[0]))
11573 printf_filtered ("FAIL: threadlist test\n");
11574 else
11575 {
11576 threadref *scan = threadlist;
11577 threadref *limit = scan + result_count;
11578
11579 while (scan < limit)
11580 output_threadid (" thread ", scan++);
11581 }
11582 }
11583
11584 void
11585 display_thread_info (struct gdb_ext_thread_info *info)
11586 {
11587 output_threadid ("Threadid: ", &info->threadid);
11588 printf_filtered ("Name: %s\n ", info->shortname);
11589 printf_filtered ("State: %s\n", info->display);
11590 printf_filtered ("other: %s\n\n", info->more_display);
11591 }
11592
11593 int
11594 get_and_display_threadinfo (threadref *ref)
11595 {
11596 int result;
11597 int set;
11598 struct gdb_ext_thread_info threadinfo;
11599
11600 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11601 | TAG_MOREDISPLAY | TAG_DISPLAY;
11602 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11603 display_thread_info (&threadinfo);
11604 return result;
11605 }
11606
11607 static void
11608 threadinfo_test_cmd (const char *cmd, int tty)
11609 {
11610 int athread = SAMPLE_THREAD;
11611 threadref thread;
11612 int set;
11613
11614 int_to_threadref (&thread, athread);
11615 printf_filtered ("Remote Threadinfo test\n");
11616 if (!get_and_display_threadinfo (&thread))
11617 printf_filtered ("FAIL cannot get thread info\n");
11618 }
11619
11620 static int
11621 thread_display_step (threadref *ref, void *context)
11622 {
11623 /* output_threadid(" threadstep ",ref); *//* simple test */
11624 return get_and_display_threadinfo (ref);
11625 }
11626
11627 static void
11628 threadlist_update_test_cmd (const char *cmd, int tty)
11629 {
11630 printf_filtered ("Remote Threadlist update test\n");
11631 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11632 }
11633
11634 static void
11635 init_remote_threadtests (void)
11636 {
11637 add_com ("tlist", class_obscure, threadlist_test_cmd,
11638 _("Fetch and print the remote list of "
11639 "thread identifiers, one pkt only."));
11640 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11641 _("Fetch and display info about one thread."));
11642 add_com ("tset", class_obscure, threadset_test_cmd,
11643 _("Test setting to a different thread."));
11644 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11645 _("Iterate through updating all remote thread info."));
11646 add_com ("talive", class_obscure, threadalive_test,
11647 _("Remote thread alive test."));
11648 }
11649
11650 #endif /* 0 */
11651
11652 /* Convert a thread ID to a string. */
11653
11654 std::string
11655 remote_target::pid_to_str (ptid_t ptid)
11656 {
11657 struct remote_state *rs = get_remote_state ();
11658
11659 if (ptid == null_ptid)
11660 return normal_pid_to_str (ptid);
11661 else if (ptid.is_pid ())
11662 {
11663 /* Printing an inferior target id. */
11664
11665 /* When multi-process extensions are off, there's no way in the
11666 remote protocol to know the remote process id, if there's any
11667 at all. There's one exception --- when we're connected with
11668 target extended-remote, and we manually attached to a process
11669 with "attach PID". We don't record anywhere a flag that
11670 allows us to distinguish that case from the case of
11671 connecting with extended-remote and the stub already being
11672 attached to a process, and reporting yes to qAttached, hence
11673 no smart special casing here. */
11674 if (!remote_multi_process_p (rs))
11675 return "Remote target";
11676
11677 return normal_pid_to_str (ptid);
11678 }
11679 else
11680 {
11681 if (magic_null_ptid == ptid)
11682 return "Thread <main>";
11683 else if (remote_multi_process_p (rs))
11684 if (ptid.lwp () == 0)
11685 return normal_pid_to_str (ptid);
11686 else
11687 return string_printf ("Thread %d.%ld",
11688 ptid.pid (), ptid.lwp ());
11689 else
11690 return string_printf ("Thread %ld", ptid.lwp ());
11691 }
11692 }
11693
11694 /* Get the address of the thread local variable in OBJFILE which is
11695 stored at OFFSET within the thread local storage for thread PTID. */
11696
11697 CORE_ADDR
11698 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11699 CORE_ADDR offset)
11700 {
11701 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11702 {
11703 struct remote_state *rs = get_remote_state ();
11704 char *p = rs->buf.data ();
11705 char *endp = p + get_remote_packet_size ();
11706 enum packet_result result;
11707
11708 strcpy (p, "qGetTLSAddr:");
11709 p += strlen (p);
11710 p = write_ptid (p, endp, ptid);
11711 *p++ = ',';
11712 p += hexnumstr (p, offset);
11713 *p++ = ',';
11714 p += hexnumstr (p, lm);
11715 *p++ = '\0';
11716
11717 putpkt (rs->buf);
11718 getpkt (&rs->buf, 0);
11719 result = packet_ok (rs->buf,
11720 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11721 if (result == PACKET_OK)
11722 {
11723 ULONGEST addr;
11724
11725 unpack_varlen_hex (rs->buf.data (), &addr);
11726 return addr;
11727 }
11728 else if (result == PACKET_UNKNOWN)
11729 throw_error (TLS_GENERIC_ERROR,
11730 _("Remote target doesn't support qGetTLSAddr packet"));
11731 else
11732 throw_error (TLS_GENERIC_ERROR,
11733 _("Remote target failed to process qGetTLSAddr request"));
11734 }
11735 else
11736 throw_error (TLS_GENERIC_ERROR,
11737 _("TLS not supported or disabled on this target"));
11738 /* Not reached. */
11739 return 0;
11740 }
11741
11742 /* Provide thread local base, i.e. Thread Information Block address.
11743 Returns 1 if ptid is found and thread_local_base is non zero. */
11744
11745 bool
11746 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11747 {
11748 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11749 {
11750 struct remote_state *rs = get_remote_state ();
11751 char *p = rs->buf.data ();
11752 char *endp = p + get_remote_packet_size ();
11753 enum packet_result result;
11754
11755 strcpy (p, "qGetTIBAddr:");
11756 p += strlen (p);
11757 p = write_ptid (p, endp, ptid);
11758 *p++ = '\0';
11759
11760 putpkt (rs->buf);
11761 getpkt (&rs->buf, 0);
11762 result = packet_ok (rs->buf,
11763 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11764 if (result == PACKET_OK)
11765 {
11766 ULONGEST val;
11767 unpack_varlen_hex (rs->buf.data (), &val);
11768 if (addr)
11769 *addr = (CORE_ADDR) val;
11770 return true;
11771 }
11772 else if (result == PACKET_UNKNOWN)
11773 error (_("Remote target doesn't support qGetTIBAddr packet"));
11774 else
11775 error (_("Remote target failed to process qGetTIBAddr request"));
11776 }
11777 else
11778 error (_("qGetTIBAddr not supported or disabled on this target"));
11779 /* Not reached. */
11780 return false;
11781 }
11782
11783 /* Support for inferring a target description based on the current
11784 architecture and the size of a 'g' packet. While the 'g' packet
11785 can have any size (since optional registers can be left off the
11786 end), some sizes are easily recognizable given knowledge of the
11787 approximate architecture. */
11788
11789 struct remote_g_packet_guess
11790 {
11791 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
11792 : bytes (bytes_),
11793 tdesc (tdesc_)
11794 {
11795 }
11796
11797 int bytes;
11798 const struct target_desc *tdesc;
11799 };
11800
11801 struct remote_g_packet_data : public allocate_on_obstack
11802 {
11803 std::vector<remote_g_packet_guess> guesses;
11804 };
11805
11806 static struct gdbarch_data *remote_g_packet_data_handle;
11807
11808 static void *
11809 remote_g_packet_data_init (struct obstack *obstack)
11810 {
11811 return new (obstack) remote_g_packet_data;
11812 }
11813
11814 void
11815 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11816 const struct target_desc *tdesc)
11817 {
11818 struct remote_g_packet_data *data
11819 = ((struct remote_g_packet_data *)
11820 gdbarch_data (gdbarch, remote_g_packet_data_handle));
11821
11822 gdb_assert (tdesc != NULL);
11823
11824 for (const remote_g_packet_guess &guess : data->guesses)
11825 if (guess.bytes == bytes)
11826 internal_error (__FILE__, __LINE__,
11827 _("Duplicate g packet description added for size %d"),
11828 bytes);
11829
11830 data->guesses.emplace_back (bytes, tdesc);
11831 }
11832
11833 /* Return true if remote_read_description would do anything on this target
11834 and architecture, false otherwise. */
11835
11836 static bool
11837 remote_read_description_p (struct target_ops *target)
11838 {
11839 struct remote_g_packet_data *data
11840 = ((struct remote_g_packet_data *)
11841 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11842
11843 return !data->guesses.empty ();
11844 }
11845
11846 const struct target_desc *
11847 remote_target::read_description ()
11848 {
11849 struct remote_g_packet_data *data
11850 = ((struct remote_g_packet_data *)
11851 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11852
11853 /* Do not try this during initial connection, when we do not know
11854 whether there is a running but stopped thread. */
11855 if (!target_has_execution () || inferior_ptid == null_ptid)
11856 return beneath ()->read_description ();
11857
11858 if (!data->guesses.empty ())
11859 {
11860 int bytes = send_g_packet ();
11861
11862 for (const remote_g_packet_guess &guess : data->guesses)
11863 if (guess.bytes == bytes)
11864 return guess.tdesc;
11865
11866 /* We discard the g packet. A minor optimization would be to
11867 hold on to it, and fill the register cache once we have selected
11868 an architecture, but it's too tricky to do safely. */
11869 }
11870
11871 return beneath ()->read_description ();
11872 }
11873
11874 /* Remote file transfer support. This is host-initiated I/O, not
11875 target-initiated; for target-initiated, see remote-fileio.c. */
11876
11877 /* If *LEFT is at least the length of STRING, copy STRING to
11878 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11879 decrease *LEFT. Otherwise raise an error. */
11880
11881 static void
11882 remote_buffer_add_string (char **buffer, int *left, const char *string)
11883 {
11884 int len = strlen (string);
11885
11886 if (len > *left)
11887 error (_("Packet too long for target."));
11888
11889 memcpy (*buffer, string, len);
11890 *buffer += len;
11891 *left -= len;
11892
11893 /* NUL-terminate the buffer as a convenience, if there is
11894 room. */
11895 if (*left)
11896 **buffer = '\0';
11897 }
11898
11899 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11900 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11901 decrease *LEFT. Otherwise raise an error. */
11902
11903 static void
11904 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11905 int len)
11906 {
11907 if (2 * len > *left)
11908 error (_("Packet too long for target."));
11909
11910 bin2hex (bytes, *buffer, len);
11911 *buffer += 2 * len;
11912 *left -= 2 * len;
11913
11914 /* NUL-terminate the buffer as a convenience, if there is
11915 room. */
11916 if (*left)
11917 **buffer = '\0';
11918 }
11919
11920 /* If *LEFT is large enough, convert VALUE to hex and add it to
11921 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11922 decrease *LEFT. Otherwise raise an error. */
11923
11924 static void
11925 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11926 {
11927 int len = hexnumlen (value);
11928
11929 if (len > *left)
11930 error (_("Packet too long for target."));
11931
11932 hexnumstr (*buffer, value);
11933 *buffer += len;
11934 *left -= len;
11935
11936 /* NUL-terminate the buffer as a convenience, if there is
11937 room. */
11938 if (*left)
11939 **buffer = '\0';
11940 }
11941
11942 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11943 value, *REMOTE_ERRNO to the remote error number or zero if none
11944 was included, and *ATTACHMENT to point to the start of the annex
11945 if any. The length of the packet isn't needed here; there may
11946 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11947
11948 Return 0 if the packet could be parsed, -1 if it could not. If
11949 -1 is returned, the other variables may not be initialized. */
11950
11951 static int
11952 remote_hostio_parse_result (const char *buffer, int *retcode,
11953 int *remote_errno, const char **attachment)
11954 {
11955 char *p, *p2;
11956
11957 *remote_errno = 0;
11958 *attachment = NULL;
11959
11960 if (buffer[0] != 'F')
11961 return -1;
11962
11963 errno = 0;
11964 *retcode = strtol (&buffer[1], &p, 16);
11965 if (errno != 0 || p == &buffer[1])
11966 return -1;
11967
11968 /* Check for ",errno". */
11969 if (*p == ',')
11970 {
11971 errno = 0;
11972 *remote_errno = strtol (p + 1, &p2, 16);
11973 if (errno != 0 || p + 1 == p2)
11974 return -1;
11975 p = p2;
11976 }
11977
11978 /* Check for ";attachment". If there is no attachment, the
11979 packet should end here. */
11980 if (*p == ';')
11981 {
11982 *attachment = p + 1;
11983 return 0;
11984 }
11985 else if (*p == '\0')
11986 return 0;
11987 else
11988 return -1;
11989 }
11990
11991 /* Send a prepared I/O packet to the target and read its response.
11992 The prepared packet is in the global RS->BUF before this function
11993 is called, and the answer is there when we return.
11994
11995 COMMAND_BYTES is the length of the request to send, which may include
11996 binary data. WHICH_PACKET is the packet configuration to check
11997 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11998 is set to the error number and -1 is returned. Otherwise the value
11999 returned by the function is returned.
12000
12001 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12002 attachment is expected; an error will be reported if there's a
12003 mismatch. If one is found, *ATTACHMENT will be set to point into
12004 the packet buffer and *ATTACHMENT_LEN will be set to the
12005 attachment's length. */
12006
12007 int
12008 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12009 int *remote_errno, const char **attachment,
12010 int *attachment_len)
12011 {
12012 struct remote_state *rs = get_remote_state ();
12013 int ret, bytes_read;
12014 const char *attachment_tmp;
12015
12016 if (packet_support (which_packet) == PACKET_DISABLE)
12017 {
12018 *remote_errno = FILEIO_ENOSYS;
12019 return -1;
12020 }
12021
12022 putpkt_binary (rs->buf.data (), command_bytes);
12023 bytes_read = getpkt_sane (&rs->buf, 0);
12024
12025 /* If it timed out, something is wrong. Don't try to parse the
12026 buffer. */
12027 if (bytes_read < 0)
12028 {
12029 *remote_errno = FILEIO_EINVAL;
12030 return -1;
12031 }
12032
12033 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
12034 {
12035 case PACKET_ERROR:
12036 *remote_errno = FILEIO_EINVAL;
12037 return -1;
12038 case PACKET_UNKNOWN:
12039 *remote_errno = FILEIO_ENOSYS;
12040 return -1;
12041 case PACKET_OK:
12042 break;
12043 }
12044
12045 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12046 &attachment_tmp))
12047 {
12048 *remote_errno = FILEIO_EINVAL;
12049 return -1;
12050 }
12051
12052 /* Make sure we saw an attachment if and only if we expected one. */
12053 if ((attachment_tmp == NULL && attachment != NULL)
12054 || (attachment_tmp != NULL && attachment == NULL))
12055 {
12056 *remote_errno = FILEIO_EINVAL;
12057 return -1;
12058 }
12059
12060 /* If an attachment was found, it must point into the packet buffer;
12061 work out how many bytes there were. */
12062 if (attachment_tmp != NULL)
12063 {
12064 *attachment = attachment_tmp;
12065 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12066 }
12067
12068 return ret;
12069 }
12070
12071 /* See declaration.h. */
12072
12073 void
12074 readahead_cache::invalidate ()
12075 {
12076 this->fd = -1;
12077 }
12078
12079 /* See declaration.h. */
12080
12081 void
12082 readahead_cache::invalidate_fd (int fd)
12083 {
12084 if (this->fd == fd)
12085 this->fd = -1;
12086 }
12087
12088 /* Set the filesystem remote_hostio functions that take FILENAME
12089 arguments will use. Return 0 on success, or -1 if an error
12090 occurs (and set *REMOTE_ERRNO). */
12091
12092 int
12093 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12094 int *remote_errno)
12095 {
12096 struct remote_state *rs = get_remote_state ();
12097 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12098 char *p = rs->buf.data ();
12099 int left = get_remote_packet_size () - 1;
12100 char arg[9];
12101 int ret;
12102
12103 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12104 return 0;
12105
12106 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12107 return 0;
12108
12109 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12110
12111 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12112 remote_buffer_add_string (&p, &left, arg);
12113
12114 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12115 remote_errno, NULL, NULL);
12116
12117 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12118 return 0;
12119
12120 if (ret == 0)
12121 rs->fs_pid = required_pid;
12122
12123 return ret;
12124 }
12125
12126 /* Implementation of to_fileio_open. */
12127
12128 int
12129 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12130 int flags, int mode, int warn_if_slow,
12131 int *remote_errno)
12132 {
12133 struct remote_state *rs = get_remote_state ();
12134 char *p = rs->buf.data ();
12135 int left = get_remote_packet_size () - 1;
12136
12137 if (warn_if_slow)
12138 {
12139 static int warning_issued = 0;
12140
12141 printf_unfiltered (_("Reading %s from remote target...\n"),
12142 filename);
12143
12144 if (!warning_issued)
12145 {
12146 warning (_("File transfers from remote targets can be slow."
12147 " Use \"set sysroot\" to access files locally"
12148 " instead."));
12149 warning_issued = 1;
12150 }
12151 }
12152
12153 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12154 return -1;
12155
12156 remote_buffer_add_string (&p, &left, "vFile:open:");
12157
12158 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12159 strlen (filename));
12160 remote_buffer_add_string (&p, &left, ",");
12161
12162 remote_buffer_add_int (&p, &left, flags);
12163 remote_buffer_add_string (&p, &left, ",");
12164
12165 remote_buffer_add_int (&p, &left, mode);
12166
12167 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12168 remote_errno, NULL, NULL);
12169 }
12170
12171 int
12172 remote_target::fileio_open (struct inferior *inf, const char *filename,
12173 int flags, int mode, int warn_if_slow,
12174 int *remote_errno)
12175 {
12176 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12177 remote_errno);
12178 }
12179
12180 /* Implementation of to_fileio_pwrite. */
12181
12182 int
12183 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12184 ULONGEST offset, int *remote_errno)
12185 {
12186 struct remote_state *rs = get_remote_state ();
12187 char *p = rs->buf.data ();
12188 int left = get_remote_packet_size ();
12189 int out_len;
12190
12191 rs->readahead_cache.invalidate_fd (fd);
12192
12193 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12194
12195 remote_buffer_add_int (&p, &left, fd);
12196 remote_buffer_add_string (&p, &left, ",");
12197
12198 remote_buffer_add_int (&p, &left, offset);
12199 remote_buffer_add_string (&p, &left, ",");
12200
12201 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12202 (get_remote_packet_size ()
12203 - (p - rs->buf.data ())));
12204
12205 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12206 remote_errno, NULL, NULL);
12207 }
12208
12209 int
12210 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12211 ULONGEST offset, int *remote_errno)
12212 {
12213 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12214 }
12215
12216 /* Helper for the implementation of to_fileio_pread. Read the file
12217 from the remote side with vFile:pread. */
12218
12219 int
12220 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12221 ULONGEST offset, int *remote_errno)
12222 {
12223 struct remote_state *rs = get_remote_state ();
12224 char *p = rs->buf.data ();
12225 const char *attachment;
12226 int left = get_remote_packet_size ();
12227 int ret, attachment_len;
12228 int read_len;
12229
12230 remote_buffer_add_string (&p, &left, "vFile:pread:");
12231
12232 remote_buffer_add_int (&p, &left, fd);
12233 remote_buffer_add_string (&p, &left, ",");
12234
12235 remote_buffer_add_int (&p, &left, len);
12236 remote_buffer_add_string (&p, &left, ",");
12237
12238 remote_buffer_add_int (&p, &left, offset);
12239
12240 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12241 remote_errno, &attachment,
12242 &attachment_len);
12243
12244 if (ret < 0)
12245 return ret;
12246
12247 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12248 read_buf, len);
12249 if (read_len != ret)
12250 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12251
12252 return ret;
12253 }
12254
12255 /* See declaration.h. */
12256
12257 int
12258 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12259 ULONGEST offset)
12260 {
12261 if (this->fd == fd
12262 && this->offset <= offset
12263 && offset < this->offset + this->bufsize)
12264 {
12265 ULONGEST max = this->offset + this->bufsize;
12266
12267 if (offset + len > max)
12268 len = max - offset;
12269
12270 memcpy (read_buf, this->buf + offset - this->offset, len);
12271 return len;
12272 }
12273
12274 return 0;
12275 }
12276
12277 /* Implementation of to_fileio_pread. */
12278
12279 int
12280 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12281 ULONGEST offset, int *remote_errno)
12282 {
12283 int ret;
12284 struct remote_state *rs = get_remote_state ();
12285 readahead_cache *cache = &rs->readahead_cache;
12286
12287 ret = cache->pread (fd, read_buf, len, offset);
12288 if (ret > 0)
12289 {
12290 cache->hit_count++;
12291
12292 remote_debug_printf ("readahead cache hit %s",
12293 pulongest (cache->hit_count));
12294 return ret;
12295 }
12296
12297 cache->miss_count++;
12298
12299 remote_debug_printf ("readahead cache miss %s",
12300 pulongest (cache->miss_count));
12301
12302 cache->fd = fd;
12303 cache->offset = offset;
12304 cache->bufsize = get_remote_packet_size ();
12305 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12306
12307 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12308 cache->offset, remote_errno);
12309 if (ret <= 0)
12310 {
12311 cache->invalidate_fd (fd);
12312 return ret;
12313 }
12314
12315 cache->bufsize = ret;
12316 return cache->pread (fd, read_buf, len, offset);
12317 }
12318
12319 int
12320 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12321 ULONGEST offset, int *remote_errno)
12322 {
12323 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12324 }
12325
12326 /* Implementation of to_fileio_close. */
12327
12328 int
12329 remote_target::remote_hostio_close (int fd, int *remote_errno)
12330 {
12331 struct remote_state *rs = get_remote_state ();
12332 char *p = rs->buf.data ();
12333 int left = get_remote_packet_size () - 1;
12334
12335 rs->readahead_cache.invalidate_fd (fd);
12336
12337 remote_buffer_add_string (&p, &left, "vFile:close:");
12338
12339 remote_buffer_add_int (&p, &left, fd);
12340
12341 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12342 remote_errno, NULL, NULL);
12343 }
12344
12345 int
12346 remote_target::fileio_close (int fd, int *remote_errno)
12347 {
12348 return remote_hostio_close (fd, remote_errno);
12349 }
12350
12351 /* Implementation of to_fileio_unlink. */
12352
12353 int
12354 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12355 int *remote_errno)
12356 {
12357 struct remote_state *rs = get_remote_state ();
12358 char *p = rs->buf.data ();
12359 int left = get_remote_packet_size () - 1;
12360
12361 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12362 return -1;
12363
12364 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12365
12366 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12367 strlen (filename));
12368
12369 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12370 remote_errno, NULL, NULL);
12371 }
12372
12373 int
12374 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12375 int *remote_errno)
12376 {
12377 return remote_hostio_unlink (inf, filename, remote_errno);
12378 }
12379
12380 /* Implementation of to_fileio_readlink. */
12381
12382 gdb::optional<std::string>
12383 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12384 int *remote_errno)
12385 {
12386 struct remote_state *rs = get_remote_state ();
12387 char *p = rs->buf.data ();
12388 const char *attachment;
12389 int left = get_remote_packet_size ();
12390 int len, attachment_len;
12391 int read_len;
12392
12393 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12394 return {};
12395
12396 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12397
12398 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12399 strlen (filename));
12400
12401 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12402 remote_errno, &attachment,
12403 &attachment_len);
12404
12405 if (len < 0)
12406 return {};
12407
12408 std::string ret (len, '\0');
12409
12410 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12411 (gdb_byte *) &ret[0], len);
12412 if (read_len != len)
12413 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12414
12415 return ret;
12416 }
12417
12418 /* Implementation of to_fileio_fstat. */
12419
12420 int
12421 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12422 {
12423 struct remote_state *rs = get_remote_state ();
12424 char *p = rs->buf.data ();
12425 int left = get_remote_packet_size ();
12426 int attachment_len, ret;
12427 const char *attachment;
12428 struct fio_stat fst;
12429 int read_len;
12430
12431 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12432
12433 remote_buffer_add_int (&p, &left, fd);
12434
12435 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12436 remote_errno, &attachment,
12437 &attachment_len);
12438 if (ret < 0)
12439 {
12440 if (*remote_errno != FILEIO_ENOSYS)
12441 return ret;
12442
12443 /* Strictly we should return -1, ENOSYS here, but when
12444 "set sysroot remote:" was implemented in August 2008
12445 BFD's need for a stat function was sidestepped with
12446 this hack. This was not remedied until March 2015
12447 so we retain the previous behavior to avoid breaking
12448 compatibility.
12449
12450 Note that the memset is a March 2015 addition; older
12451 GDBs set st_size *and nothing else* so the structure
12452 would have garbage in all other fields. This might
12453 break something but retaining the previous behavior
12454 here would be just too wrong. */
12455
12456 memset (st, 0, sizeof (struct stat));
12457 st->st_size = INT_MAX;
12458 return 0;
12459 }
12460
12461 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12462 (gdb_byte *) &fst, sizeof (fst));
12463
12464 if (read_len != ret)
12465 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12466
12467 if (read_len != sizeof (fst))
12468 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12469 read_len, (int) sizeof (fst));
12470
12471 remote_fileio_to_host_stat (&fst, st);
12472
12473 return 0;
12474 }
12475
12476 /* Implementation of to_filesystem_is_local. */
12477
12478 bool
12479 remote_target::filesystem_is_local ()
12480 {
12481 /* Valgrind GDB presents itself as a remote target but works
12482 on the local filesystem: it does not implement remote get
12483 and users are not expected to set a sysroot. To handle
12484 this case we treat the remote filesystem as local if the
12485 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12486 does not support vFile:open. */
12487 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
12488 {
12489 enum packet_support ps = packet_support (PACKET_vFile_open);
12490
12491 if (ps == PACKET_SUPPORT_UNKNOWN)
12492 {
12493 int fd, remote_errno;
12494
12495 /* Try opening a file to probe support. The supplied
12496 filename is irrelevant, we only care about whether
12497 the stub recognizes the packet or not. */
12498 fd = remote_hostio_open (NULL, "just probing",
12499 FILEIO_O_RDONLY, 0700, 0,
12500 &remote_errno);
12501
12502 if (fd >= 0)
12503 remote_hostio_close (fd, &remote_errno);
12504
12505 ps = packet_support (PACKET_vFile_open);
12506 }
12507
12508 if (ps == PACKET_DISABLE)
12509 {
12510 static int warning_issued = 0;
12511
12512 if (!warning_issued)
12513 {
12514 warning (_("remote target does not support file"
12515 " transfer, attempting to access files"
12516 " from local filesystem."));
12517 warning_issued = 1;
12518 }
12519
12520 return true;
12521 }
12522 }
12523
12524 return false;
12525 }
12526
12527 static int
12528 remote_fileio_errno_to_host (int errnum)
12529 {
12530 switch (errnum)
12531 {
12532 case FILEIO_EPERM:
12533 return EPERM;
12534 case FILEIO_ENOENT:
12535 return ENOENT;
12536 case FILEIO_EINTR:
12537 return EINTR;
12538 case FILEIO_EIO:
12539 return EIO;
12540 case FILEIO_EBADF:
12541 return EBADF;
12542 case FILEIO_EACCES:
12543 return EACCES;
12544 case FILEIO_EFAULT:
12545 return EFAULT;
12546 case FILEIO_EBUSY:
12547 return EBUSY;
12548 case FILEIO_EEXIST:
12549 return EEXIST;
12550 case FILEIO_ENODEV:
12551 return ENODEV;
12552 case FILEIO_ENOTDIR:
12553 return ENOTDIR;
12554 case FILEIO_EISDIR:
12555 return EISDIR;
12556 case FILEIO_EINVAL:
12557 return EINVAL;
12558 case FILEIO_ENFILE:
12559 return ENFILE;
12560 case FILEIO_EMFILE:
12561 return EMFILE;
12562 case FILEIO_EFBIG:
12563 return EFBIG;
12564 case FILEIO_ENOSPC:
12565 return ENOSPC;
12566 case FILEIO_ESPIPE:
12567 return ESPIPE;
12568 case FILEIO_EROFS:
12569 return EROFS;
12570 case FILEIO_ENOSYS:
12571 return ENOSYS;
12572 case FILEIO_ENAMETOOLONG:
12573 return ENAMETOOLONG;
12574 }
12575 return -1;
12576 }
12577
12578 static char *
12579 remote_hostio_error (int errnum)
12580 {
12581 int host_error = remote_fileio_errno_to_host (errnum);
12582
12583 if (host_error == -1)
12584 error (_("Unknown remote I/O error %d"), errnum);
12585 else
12586 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12587 }
12588
12589 /* A RAII wrapper around a remote file descriptor. */
12590
12591 class scoped_remote_fd
12592 {
12593 public:
12594 scoped_remote_fd (remote_target *remote, int fd)
12595 : m_remote (remote), m_fd (fd)
12596 {
12597 }
12598
12599 ~scoped_remote_fd ()
12600 {
12601 if (m_fd != -1)
12602 {
12603 try
12604 {
12605 int remote_errno;
12606 m_remote->remote_hostio_close (m_fd, &remote_errno);
12607 }
12608 catch (...)
12609 {
12610 /* Swallow exception before it escapes the dtor. If
12611 something goes wrong, likely the connection is gone,
12612 and there's nothing else that can be done. */
12613 }
12614 }
12615 }
12616
12617 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12618
12619 /* Release ownership of the file descriptor, and return it. */
12620 ATTRIBUTE_UNUSED_RESULT int release () noexcept
12621 {
12622 int fd = m_fd;
12623 m_fd = -1;
12624 return fd;
12625 }
12626
12627 /* Return the owned file descriptor. */
12628 int get () const noexcept
12629 {
12630 return m_fd;
12631 }
12632
12633 private:
12634 /* The remote target. */
12635 remote_target *m_remote;
12636
12637 /* The owned remote I/O file descriptor. */
12638 int m_fd;
12639 };
12640
12641 void
12642 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12643 {
12644 remote_target *remote = get_current_remote_target ();
12645
12646 if (remote == nullptr)
12647 error (_("command can only be used with remote target"));
12648
12649 remote->remote_file_put (local_file, remote_file, from_tty);
12650 }
12651
12652 void
12653 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12654 int from_tty)
12655 {
12656 int retcode, remote_errno, bytes, io_size;
12657 int bytes_in_buffer;
12658 int saw_eof;
12659 ULONGEST offset;
12660
12661 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12662 if (file == NULL)
12663 perror_with_name (local_file);
12664
12665 scoped_remote_fd fd
12666 (this, remote_hostio_open (NULL,
12667 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12668 | FILEIO_O_TRUNC),
12669 0700, 0, &remote_errno));
12670 if (fd.get () == -1)
12671 remote_hostio_error (remote_errno);
12672
12673 /* Send up to this many bytes at once. They won't all fit in the
12674 remote packet limit, so we'll transfer slightly fewer. */
12675 io_size = get_remote_packet_size ();
12676 gdb::byte_vector buffer (io_size);
12677
12678 bytes_in_buffer = 0;
12679 saw_eof = 0;
12680 offset = 0;
12681 while (bytes_in_buffer || !saw_eof)
12682 {
12683 if (!saw_eof)
12684 {
12685 bytes = fread (buffer.data () + bytes_in_buffer, 1,
12686 io_size - bytes_in_buffer,
12687 file.get ());
12688 if (bytes == 0)
12689 {
12690 if (ferror (file.get ()))
12691 error (_("Error reading %s."), local_file);
12692 else
12693 {
12694 /* EOF. Unless there is something still in the
12695 buffer from the last iteration, we are done. */
12696 saw_eof = 1;
12697 if (bytes_in_buffer == 0)
12698 break;
12699 }
12700 }
12701 }
12702 else
12703 bytes = 0;
12704
12705 bytes += bytes_in_buffer;
12706 bytes_in_buffer = 0;
12707
12708 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12709 offset, &remote_errno);
12710
12711 if (retcode < 0)
12712 remote_hostio_error (remote_errno);
12713 else if (retcode == 0)
12714 error (_("Remote write of %d bytes returned 0!"), bytes);
12715 else if (retcode < bytes)
12716 {
12717 /* Short write. Save the rest of the read data for the next
12718 write. */
12719 bytes_in_buffer = bytes - retcode;
12720 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
12721 }
12722
12723 offset += retcode;
12724 }
12725
12726 if (remote_hostio_close (fd.release (), &remote_errno))
12727 remote_hostio_error (remote_errno);
12728
12729 if (from_tty)
12730 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12731 }
12732
12733 void
12734 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12735 {
12736 remote_target *remote = get_current_remote_target ();
12737
12738 if (remote == nullptr)
12739 error (_("command can only be used with remote target"));
12740
12741 remote->remote_file_get (remote_file, local_file, from_tty);
12742 }
12743
12744 void
12745 remote_target::remote_file_get (const char *remote_file, const char *local_file,
12746 int from_tty)
12747 {
12748 int remote_errno, bytes, io_size;
12749 ULONGEST offset;
12750
12751 scoped_remote_fd fd
12752 (this, remote_hostio_open (NULL,
12753 remote_file, FILEIO_O_RDONLY, 0, 0,
12754 &remote_errno));
12755 if (fd.get () == -1)
12756 remote_hostio_error (remote_errno);
12757
12758 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12759 if (file == NULL)
12760 perror_with_name (local_file);
12761
12762 /* Send up to this many bytes at once. They won't all fit in the
12763 remote packet limit, so we'll transfer slightly fewer. */
12764 io_size = get_remote_packet_size ();
12765 gdb::byte_vector buffer (io_size);
12766
12767 offset = 0;
12768 while (1)
12769 {
12770 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
12771 &remote_errno);
12772 if (bytes == 0)
12773 /* Success, but no bytes, means end-of-file. */
12774 break;
12775 if (bytes == -1)
12776 remote_hostio_error (remote_errno);
12777
12778 offset += bytes;
12779
12780 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
12781 if (bytes == 0)
12782 perror_with_name (local_file);
12783 }
12784
12785 if (remote_hostio_close (fd.release (), &remote_errno))
12786 remote_hostio_error (remote_errno);
12787
12788 if (from_tty)
12789 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12790 }
12791
12792 void
12793 remote_file_delete (const char *remote_file, int from_tty)
12794 {
12795 remote_target *remote = get_current_remote_target ();
12796
12797 if (remote == nullptr)
12798 error (_("command can only be used with remote target"));
12799
12800 remote->remote_file_delete (remote_file, from_tty);
12801 }
12802
12803 void
12804 remote_target::remote_file_delete (const char *remote_file, int from_tty)
12805 {
12806 int retcode, remote_errno;
12807
12808 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
12809 if (retcode == -1)
12810 remote_hostio_error (remote_errno);
12811
12812 if (from_tty)
12813 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12814 }
12815
12816 static void
12817 remote_put_command (const char *args, int from_tty)
12818 {
12819 if (args == NULL)
12820 error_no_arg (_("file to put"));
12821
12822 gdb_argv argv (args);
12823 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12824 error (_("Invalid parameters to remote put"));
12825
12826 remote_file_put (argv[0], argv[1], from_tty);
12827 }
12828
12829 static void
12830 remote_get_command (const char *args, int from_tty)
12831 {
12832 if (args == NULL)
12833 error_no_arg (_("file to get"));
12834
12835 gdb_argv argv (args);
12836 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12837 error (_("Invalid parameters to remote get"));
12838
12839 remote_file_get (argv[0], argv[1], from_tty);
12840 }
12841
12842 static void
12843 remote_delete_command (const char *args, int from_tty)
12844 {
12845 if (args == NULL)
12846 error_no_arg (_("file to delete"));
12847
12848 gdb_argv argv (args);
12849 if (argv[0] == NULL || argv[1] != NULL)
12850 error (_("Invalid parameters to remote delete"));
12851
12852 remote_file_delete (argv[0], from_tty);
12853 }
12854
12855 bool
12856 remote_target::can_execute_reverse ()
12857 {
12858 if (packet_support (PACKET_bs) == PACKET_ENABLE
12859 || packet_support (PACKET_bc) == PACKET_ENABLE)
12860 return true;
12861 else
12862 return false;
12863 }
12864
12865 bool
12866 remote_target::supports_non_stop ()
12867 {
12868 return true;
12869 }
12870
12871 bool
12872 remote_target::supports_disable_randomization ()
12873 {
12874 /* Only supported in extended mode. */
12875 return false;
12876 }
12877
12878 bool
12879 remote_target::supports_multi_process ()
12880 {
12881 struct remote_state *rs = get_remote_state ();
12882
12883 return remote_multi_process_p (rs);
12884 }
12885
12886 static int
12887 remote_supports_cond_tracepoints ()
12888 {
12889 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12890 }
12891
12892 bool
12893 remote_target::supports_evaluation_of_breakpoint_conditions ()
12894 {
12895 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12896 }
12897
12898 static int
12899 remote_supports_fast_tracepoints ()
12900 {
12901 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12902 }
12903
12904 static int
12905 remote_supports_static_tracepoints ()
12906 {
12907 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12908 }
12909
12910 static int
12911 remote_supports_install_in_trace ()
12912 {
12913 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12914 }
12915
12916 bool
12917 remote_target::supports_enable_disable_tracepoint ()
12918 {
12919 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12920 == PACKET_ENABLE);
12921 }
12922
12923 bool
12924 remote_target::supports_string_tracing ()
12925 {
12926 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12927 }
12928
12929 bool
12930 remote_target::can_run_breakpoint_commands ()
12931 {
12932 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12933 }
12934
12935 void
12936 remote_target::trace_init ()
12937 {
12938 struct remote_state *rs = get_remote_state ();
12939
12940 putpkt ("QTinit");
12941 remote_get_noisy_reply ();
12942 if (strcmp (rs->buf.data (), "OK") != 0)
12943 error (_("Target does not support this command."));
12944 }
12945
12946 /* Recursive routine to walk through command list including loops, and
12947 download packets for each command. */
12948
12949 void
12950 remote_target::remote_download_command_source (int num, ULONGEST addr,
12951 struct command_line *cmds)
12952 {
12953 struct remote_state *rs = get_remote_state ();
12954 struct command_line *cmd;
12955
12956 for (cmd = cmds; cmd; cmd = cmd->next)
12957 {
12958 QUIT; /* Allow user to bail out with ^C. */
12959 strcpy (rs->buf.data (), "QTDPsrc:");
12960 encode_source_string (num, addr, "cmd", cmd->line,
12961 rs->buf.data () + strlen (rs->buf.data ()),
12962 rs->buf.size () - strlen (rs->buf.data ()));
12963 putpkt (rs->buf);
12964 remote_get_noisy_reply ();
12965 if (strcmp (rs->buf.data (), "OK"))
12966 warning (_("Target does not support source download."));
12967
12968 if (cmd->control_type == while_control
12969 || cmd->control_type == while_stepping_control)
12970 {
12971 remote_download_command_source (num, addr, cmd->body_list_0.get ());
12972
12973 QUIT; /* Allow user to bail out with ^C. */
12974 strcpy (rs->buf.data (), "QTDPsrc:");
12975 encode_source_string (num, addr, "cmd", "end",
12976 rs->buf.data () + strlen (rs->buf.data ()),
12977 rs->buf.size () - strlen (rs->buf.data ()));
12978 putpkt (rs->buf);
12979 remote_get_noisy_reply ();
12980 if (strcmp (rs->buf.data (), "OK"))
12981 warning (_("Target does not support source download."));
12982 }
12983 }
12984 }
12985
12986 void
12987 remote_target::download_tracepoint (struct bp_location *loc)
12988 {
12989 CORE_ADDR tpaddr;
12990 char addrbuf[40];
12991 std::vector<std::string> tdp_actions;
12992 std::vector<std::string> stepping_actions;
12993 char *pkt;
12994 struct breakpoint *b = loc->owner;
12995 struct tracepoint *t = (struct tracepoint *) b;
12996 struct remote_state *rs = get_remote_state ();
12997 int ret;
12998 const char *err_msg = _("Tracepoint packet too large for target.");
12999 size_t size_left;
13000
13001 /* We use a buffer other than rs->buf because we'll build strings
13002 across multiple statements, and other statements in between could
13003 modify rs->buf. */
13004 gdb::char_vector buf (get_remote_packet_size ());
13005
13006 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13007
13008 tpaddr = loc->address;
13009 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13010 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13011 b->number, addrbuf, /* address */
13012 (b->enable_state == bp_enabled ? 'E' : 'D'),
13013 t->step_count, t->pass_count);
13014
13015 if (ret < 0 || ret >= buf.size ())
13016 error ("%s", err_msg);
13017
13018 /* Fast tracepoints are mostly handled by the target, but we can
13019 tell the target how big of an instruction block should be moved
13020 around. */
13021 if (b->type == bp_fast_tracepoint)
13022 {
13023 /* Only test for support at download time; we may not know
13024 target capabilities at definition time. */
13025 if (remote_supports_fast_tracepoints ())
13026 {
13027 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13028 NULL))
13029 {
13030 size_left = buf.size () - strlen (buf.data ());
13031 ret = snprintf (buf.data () + strlen (buf.data ()),
13032 size_left, ":F%x",
13033 gdb_insn_length (loc->gdbarch, tpaddr));
13034
13035 if (ret < 0 || ret >= size_left)
13036 error ("%s", err_msg);
13037 }
13038 else
13039 /* If it passed validation at definition but fails now,
13040 something is very wrong. */
13041 internal_error (__FILE__, __LINE__,
13042 _("Fast tracepoint not "
13043 "valid during download"));
13044 }
13045 else
13046 /* Fast tracepoints are functionally identical to regular
13047 tracepoints, so don't take lack of support as a reason to
13048 give up on the trace run. */
13049 warning (_("Target does not support fast tracepoints, "
13050 "downloading %d as regular tracepoint"), b->number);
13051 }
13052 else if (b->type == bp_static_tracepoint)
13053 {
13054 /* Only test for support at download time; we may not know
13055 target capabilities at definition time. */
13056 if (remote_supports_static_tracepoints ())
13057 {
13058 struct static_tracepoint_marker marker;
13059
13060 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13061 {
13062 size_left = buf.size () - strlen (buf.data ());
13063 ret = snprintf (buf.data () + strlen (buf.data ()),
13064 size_left, ":S");
13065
13066 if (ret < 0 || ret >= size_left)
13067 error ("%s", err_msg);
13068 }
13069 else
13070 error (_("Static tracepoint not valid during download"));
13071 }
13072 else
13073 /* Fast tracepoints are functionally identical to regular
13074 tracepoints, so don't take lack of support as a reason
13075 to give up on the trace run. */
13076 error (_("Target does not support static tracepoints"));
13077 }
13078 /* If the tracepoint has a conditional, make it into an agent
13079 expression and append to the definition. */
13080 if (loc->cond)
13081 {
13082 /* Only test support at download time, we may not know target
13083 capabilities at definition time. */
13084 if (remote_supports_cond_tracepoints ())
13085 {
13086 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13087 loc->cond.get ());
13088
13089 size_left = buf.size () - strlen (buf.data ());
13090
13091 ret = snprintf (buf.data () + strlen (buf.data ()),
13092 size_left, ":X%x,", aexpr->len);
13093
13094 if (ret < 0 || ret >= size_left)
13095 error ("%s", err_msg);
13096
13097 size_left = buf.size () - strlen (buf.data ());
13098
13099 /* Two bytes to encode each aexpr byte, plus the terminating
13100 null byte. */
13101 if (aexpr->len * 2 + 1 > size_left)
13102 error ("%s", err_msg);
13103
13104 pkt = buf.data () + strlen (buf.data ());
13105
13106 for (int ndx = 0; ndx < aexpr->len; ++ndx)
13107 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13108 *pkt = '\0';
13109 }
13110 else
13111 warning (_("Target does not support conditional tracepoints, "
13112 "ignoring tp %d cond"), b->number);
13113 }
13114
13115 if (b->commands || *default_collect)
13116 {
13117 size_left = buf.size () - strlen (buf.data ());
13118
13119 ret = snprintf (buf.data () + strlen (buf.data ()),
13120 size_left, "-");
13121
13122 if (ret < 0 || ret >= size_left)
13123 error ("%s", err_msg);
13124 }
13125
13126 putpkt (buf.data ());
13127 remote_get_noisy_reply ();
13128 if (strcmp (rs->buf.data (), "OK"))
13129 error (_("Target does not support tracepoints."));
13130
13131 /* do_single_steps (t); */
13132 for (auto action_it = tdp_actions.begin ();
13133 action_it != tdp_actions.end (); action_it++)
13134 {
13135 QUIT; /* Allow user to bail out with ^C. */
13136
13137 bool has_more = ((action_it + 1) != tdp_actions.end ()
13138 || !stepping_actions.empty ());
13139
13140 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13141 b->number, addrbuf, /* address */
13142 action_it->c_str (),
13143 has_more ? '-' : 0);
13144
13145 if (ret < 0 || ret >= buf.size ())
13146 error ("%s", err_msg);
13147
13148 putpkt (buf.data ());
13149 remote_get_noisy_reply ();
13150 if (strcmp (rs->buf.data (), "OK"))
13151 error (_("Error on target while setting tracepoints."));
13152 }
13153
13154 for (auto action_it = stepping_actions.begin ();
13155 action_it != stepping_actions.end (); action_it++)
13156 {
13157 QUIT; /* Allow user to bail out with ^C. */
13158
13159 bool is_first = action_it == stepping_actions.begin ();
13160 bool has_more = (action_it + 1) != stepping_actions.end ();
13161
13162 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13163 b->number, addrbuf, /* address */
13164 is_first ? "S" : "",
13165 action_it->c_str (),
13166 has_more ? "-" : "");
13167
13168 if (ret < 0 || ret >= buf.size ())
13169 error ("%s", err_msg);
13170
13171 putpkt (buf.data ());
13172 remote_get_noisy_reply ();
13173 if (strcmp (rs->buf.data (), "OK"))
13174 error (_("Error on target while setting tracepoints."));
13175 }
13176
13177 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13178 {
13179 if (b->location != NULL)
13180 {
13181 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13182
13183 if (ret < 0 || ret >= buf.size ())
13184 error ("%s", err_msg);
13185
13186 encode_source_string (b->number, loc->address, "at",
13187 event_location_to_string (b->location.get ()),
13188 buf.data () + strlen (buf.data ()),
13189 buf.size () - strlen (buf.data ()));
13190 putpkt (buf.data ());
13191 remote_get_noisy_reply ();
13192 if (strcmp (rs->buf.data (), "OK"))
13193 warning (_("Target does not support source download."));
13194 }
13195 if (b->cond_string)
13196 {
13197 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13198
13199 if (ret < 0 || ret >= buf.size ())
13200 error ("%s", err_msg);
13201
13202 encode_source_string (b->number, loc->address,
13203 "cond", b->cond_string,
13204 buf.data () + strlen (buf.data ()),
13205 buf.size () - strlen (buf.data ()));
13206 putpkt (buf.data ());
13207 remote_get_noisy_reply ();
13208 if (strcmp (rs->buf.data (), "OK"))
13209 warning (_("Target does not support source download."));
13210 }
13211 remote_download_command_source (b->number, loc->address,
13212 breakpoint_commands (b));
13213 }
13214 }
13215
13216 bool
13217 remote_target::can_download_tracepoint ()
13218 {
13219 struct remote_state *rs = get_remote_state ();
13220 struct trace_status *ts;
13221 int status;
13222
13223 /* Don't try to install tracepoints until we've relocated our
13224 symbols, and fetched and merged the target's tracepoint list with
13225 ours. */
13226 if (rs->starting_up)
13227 return false;
13228
13229 ts = current_trace_status ();
13230 status = get_trace_status (ts);
13231
13232 if (status == -1 || !ts->running_known || !ts->running)
13233 return false;
13234
13235 /* If we are in a tracing experiment, but remote stub doesn't support
13236 installing tracepoint in trace, we have to return. */
13237 if (!remote_supports_install_in_trace ())
13238 return false;
13239
13240 return true;
13241 }
13242
13243
13244 void
13245 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13246 {
13247 struct remote_state *rs = get_remote_state ();
13248 char *p;
13249
13250 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13251 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13252 tsv.builtin);
13253 p = rs->buf.data () + strlen (rs->buf.data ());
13254 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13255 >= get_remote_packet_size ())
13256 error (_("Trace state variable name too long for tsv definition packet"));
13257 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13258 *p++ = '\0';
13259 putpkt (rs->buf);
13260 remote_get_noisy_reply ();
13261 if (rs->buf[0] == '\0')
13262 error (_("Target does not support this command."));
13263 if (strcmp (rs->buf.data (), "OK") != 0)
13264 error (_("Error on target while downloading trace state variable."));
13265 }
13266
13267 void
13268 remote_target::enable_tracepoint (struct bp_location *location)
13269 {
13270 struct remote_state *rs = get_remote_state ();
13271
13272 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13273 location->owner->number,
13274 phex (location->address, sizeof (CORE_ADDR)));
13275 putpkt (rs->buf);
13276 remote_get_noisy_reply ();
13277 if (rs->buf[0] == '\0')
13278 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13279 if (strcmp (rs->buf.data (), "OK") != 0)
13280 error (_("Error on target while enabling tracepoint."));
13281 }
13282
13283 void
13284 remote_target::disable_tracepoint (struct bp_location *location)
13285 {
13286 struct remote_state *rs = get_remote_state ();
13287
13288 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13289 location->owner->number,
13290 phex (location->address, sizeof (CORE_ADDR)));
13291 putpkt (rs->buf);
13292 remote_get_noisy_reply ();
13293 if (rs->buf[0] == '\0')
13294 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13295 if (strcmp (rs->buf.data (), "OK") != 0)
13296 error (_("Error on target while disabling tracepoint."));
13297 }
13298
13299 void
13300 remote_target::trace_set_readonly_regions ()
13301 {
13302 asection *s;
13303 bfd_size_type size;
13304 bfd_vma vma;
13305 int anysecs = 0;
13306 int offset = 0;
13307
13308 if (!current_program_space->exec_bfd ())
13309 return; /* No information to give. */
13310
13311 struct remote_state *rs = get_remote_state ();
13312
13313 strcpy (rs->buf.data (), "QTro");
13314 offset = strlen (rs->buf.data ());
13315 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
13316 {
13317 char tmp1[40], tmp2[40];
13318 int sec_length;
13319
13320 if ((s->flags & SEC_LOAD) == 0 ||
13321 /* (s->flags & SEC_CODE) == 0 || */
13322 (s->flags & SEC_READONLY) == 0)
13323 continue;
13324
13325 anysecs = 1;
13326 vma = bfd_section_vma (s);
13327 size = bfd_section_size (s);
13328 sprintf_vma (tmp1, vma);
13329 sprintf_vma (tmp2, vma + size);
13330 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13331 if (offset + sec_length + 1 > rs->buf.size ())
13332 {
13333 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
13334 warning (_("\
13335 Too many sections for read-only sections definition packet."));
13336 break;
13337 }
13338 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13339 tmp1, tmp2);
13340 offset += sec_length;
13341 }
13342 if (anysecs)
13343 {
13344 putpkt (rs->buf);
13345 getpkt (&rs->buf, 0);
13346 }
13347 }
13348
13349 void
13350 remote_target::trace_start ()
13351 {
13352 struct remote_state *rs = get_remote_state ();
13353
13354 putpkt ("QTStart");
13355 remote_get_noisy_reply ();
13356 if (rs->buf[0] == '\0')
13357 error (_("Target does not support this command."));
13358 if (strcmp (rs->buf.data (), "OK") != 0)
13359 error (_("Bogus reply from target: %s"), rs->buf.data ());
13360 }
13361
13362 int
13363 remote_target::get_trace_status (struct trace_status *ts)
13364 {
13365 /* Initialize it just to avoid a GCC false warning. */
13366 char *p = NULL;
13367 enum packet_result result;
13368 struct remote_state *rs = get_remote_state ();
13369
13370 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13371 return -1;
13372
13373 /* FIXME we need to get register block size some other way. */
13374 trace_regblock_size
13375 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13376
13377 putpkt ("qTStatus");
13378
13379 try
13380 {
13381 p = remote_get_noisy_reply ();
13382 }
13383 catch (const gdb_exception_error &ex)
13384 {
13385 if (ex.error != TARGET_CLOSE_ERROR)
13386 {
13387 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13388 return -1;
13389 }
13390 throw;
13391 }
13392
13393 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13394
13395 /* If the remote target doesn't do tracing, flag it. */
13396 if (result == PACKET_UNKNOWN)
13397 return -1;
13398
13399 /* We're working with a live target. */
13400 ts->filename = NULL;
13401
13402 if (*p++ != 'T')
13403 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13404
13405 /* Function 'parse_trace_status' sets default value of each field of
13406 'ts' at first, so we don't have to do it here. */
13407 parse_trace_status (p, ts);
13408
13409 return ts->running;
13410 }
13411
13412 void
13413 remote_target::get_tracepoint_status (struct breakpoint *bp,
13414 struct uploaded_tp *utp)
13415 {
13416 struct remote_state *rs = get_remote_state ();
13417 char *reply;
13418 struct bp_location *loc;
13419 struct tracepoint *tp = (struct tracepoint *) bp;
13420 size_t size = get_remote_packet_size ();
13421
13422 if (tp)
13423 {
13424 tp->hit_count = 0;
13425 tp->traceframe_usage = 0;
13426 for (loc = tp->loc; loc; loc = loc->next)
13427 {
13428 /* If the tracepoint was never downloaded, don't go asking for
13429 any status. */
13430 if (tp->number_on_target == 0)
13431 continue;
13432 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13433 phex_nz (loc->address, 0));
13434 putpkt (rs->buf);
13435 reply = remote_get_noisy_reply ();
13436 if (reply && *reply)
13437 {
13438 if (*reply == 'V')
13439 parse_tracepoint_status (reply + 1, bp, utp);
13440 }
13441 }
13442 }
13443 else if (utp)
13444 {
13445 utp->hit_count = 0;
13446 utp->traceframe_usage = 0;
13447 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13448 phex_nz (utp->addr, 0));
13449 putpkt (rs->buf);
13450 reply = remote_get_noisy_reply ();
13451 if (reply && *reply)
13452 {
13453 if (*reply == 'V')
13454 parse_tracepoint_status (reply + 1, bp, utp);
13455 }
13456 }
13457 }
13458
13459 void
13460 remote_target::trace_stop ()
13461 {
13462 struct remote_state *rs = get_remote_state ();
13463
13464 putpkt ("QTStop");
13465 remote_get_noisy_reply ();
13466 if (rs->buf[0] == '\0')
13467 error (_("Target does not support this command."));
13468 if (strcmp (rs->buf.data (), "OK") != 0)
13469 error (_("Bogus reply from target: %s"), rs->buf.data ());
13470 }
13471
13472 int
13473 remote_target::trace_find (enum trace_find_type type, int num,
13474 CORE_ADDR addr1, CORE_ADDR addr2,
13475 int *tpp)
13476 {
13477 struct remote_state *rs = get_remote_state ();
13478 char *endbuf = rs->buf.data () + get_remote_packet_size ();
13479 char *p, *reply;
13480 int target_frameno = -1, target_tracept = -1;
13481
13482 /* Lookups other than by absolute frame number depend on the current
13483 trace selected, so make sure it is correct on the remote end
13484 first. */
13485 if (type != tfind_number)
13486 set_remote_traceframe ();
13487
13488 p = rs->buf.data ();
13489 strcpy (p, "QTFrame:");
13490 p = strchr (p, '\0');
13491 switch (type)
13492 {
13493 case tfind_number:
13494 xsnprintf (p, endbuf - p, "%x", num);
13495 break;
13496 case tfind_pc:
13497 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13498 break;
13499 case tfind_tp:
13500 xsnprintf (p, endbuf - p, "tdp:%x", num);
13501 break;
13502 case tfind_range:
13503 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13504 phex_nz (addr2, 0));
13505 break;
13506 case tfind_outside:
13507 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13508 phex_nz (addr2, 0));
13509 break;
13510 default:
13511 error (_("Unknown trace find type %d"), type);
13512 }
13513
13514 putpkt (rs->buf);
13515 reply = remote_get_noisy_reply ();
13516 if (*reply == '\0')
13517 error (_("Target does not support this command."));
13518
13519 while (reply && *reply)
13520 switch (*reply)
13521 {
13522 case 'F':
13523 p = ++reply;
13524 target_frameno = (int) strtol (p, &reply, 16);
13525 if (reply == p)
13526 error (_("Unable to parse trace frame number"));
13527 /* Don't update our remote traceframe number cache on failure
13528 to select a remote traceframe. */
13529 if (target_frameno == -1)
13530 return -1;
13531 break;
13532 case 'T':
13533 p = ++reply;
13534 target_tracept = (int) strtol (p, &reply, 16);
13535 if (reply == p)
13536 error (_("Unable to parse tracepoint number"));
13537 break;
13538 case 'O': /* "OK"? */
13539 if (reply[1] == 'K' && reply[2] == '\0')
13540 reply += 2;
13541 else
13542 error (_("Bogus reply from target: %s"), reply);
13543 break;
13544 default:
13545 error (_("Bogus reply from target: %s"), reply);
13546 }
13547 if (tpp)
13548 *tpp = target_tracept;
13549
13550 rs->remote_traceframe_number = target_frameno;
13551 return target_frameno;
13552 }
13553
13554 bool
13555 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13556 {
13557 struct remote_state *rs = get_remote_state ();
13558 char *reply;
13559 ULONGEST uval;
13560
13561 set_remote_traceframe ();
13562
13563 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
13564 putpkt (rs->buf);
13565 reply = remote_get_noisy_reply ();
13566 if (reply && *reply)
13567 {
13568 if (*reply == 'V')
13569 {
13570 unpack_varlen_hex (reply + 1, &uval);
13571 *val = (LONGEST) uval;
13572 return true;
13573 }
13574 }
13575 return false;
13576 }
13577
13578 int
13579 remote_target::save_trace_data (const char *filename)
13580 {
13581 struct remote_state *rs = get_remote_state ();
13582 char *p, *reply;
13583
13584 p = rs->buf.data ();
13585 strcpy (p, "QTSave:");
13586 p += strlen (p);
13587 if ((p - rs->buf.data ()) + strlen (filename) * 2
13588 >= get_remote_packet_size ())
13589 error (_("Remote file name too long for trace save packet"));
13590 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13591 *p++ = '\0';
13592 putpkt (rs->buf);
13593 reply = remote_get_noisy_reply ();
13594 if (*reply == '\0')
13595 error (_("Target does not support this command."));
13596 if (strcmp (reply, "OK") != 0)
13597 error (_("Bogus reply from target: %s"), reply);
13598 return 0;
13599 }
13600
13601 /* This is basically a memory transfer, but needs to be its own packet
13602 because we don't know how the target actually organizes its trace
13603 memory, plus we want to be able to ask for as much as possible, but
13604 not be unhappy if we don't get as much as we ask for. */
13605
13606 LONGEST
13607 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13608 {
13609 struct remote_state *rs = get_remote_state ();
13610 char *reply;
13611 char *p;
13612 int rslt;
13613
13614 p = rs->buf.data ();
13615 strcpy (p, "qTBuffer:");
13616 p += strlen (p);
13617 p += hexnumstr (p, offset);
13618 *p++ = ',';
13619 p += hexnumstr (p, len);
13620 *p++ = '\0';
13621
13622 putpkt (rs->buf);
13623 reply = remote_get_noisy_reply ();
13624 if (reply && *reply)
13625 {
13626 /* 'l' by itself means we're at the end of the buffer and
13627 there is nothing more to get. */
13628 if (*reply == 'l')
13629 return 0;
13630
13631 /* Convert the reply into binary. Limit the number of bytes to
13632 convert according to our passed-in buffer size, rather than
13633 what was returned in the packet; if the target is
13634 unexpectedly generous and gives us a bigger reply than we
13635 asked for, we don't want to crash. */
13636 rslt = hex2bin (reply, buf, len);
13637 return rslt;
13638 }
13639
13640 /* Something went wrong, flag as an error. */
13641 return -1;
13642 }
13643
13644 void
13645 remote_target::set_disconnected_tracing (int val)
13646 {
13647 struct remote_state *rs = get_remote_state ();
13648
13649 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13650 {
13651 char *reply;
13652
13653 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13654 "QTDisconnected:%x", val);
13655 putpkt (rs->buf);
13656 reply = remote_get_noisy_reply ();
13657 if (*reply == '\0')
13658 error (_("Target does not support this command."));
13659 if (strcmp (reply, "OK") != 0)
13660 error (_("Bogus reply from target: %s"), reply);
13661 }
13662 else if (val)
13663 warning (_("Target does not support disconnected tracing."));
13664 }
13665
13666 int
13667 remote_target::core_of_thread (ptid_t ptid)
13668 {
13669 thread_info *info = find_thread_ptid (this, ptid);
13670
13671 if (info != NULL && info->priv != NULL)
13672 return get_remote_thread_info (info)->core;
13673
13674 return -1;
13675 }
13676
13677 void
13678 remote_target::set_circular_trace_buffer (int val)
13679 {
13680 struct remote_state *rs = get_remote_state ();
13681 char *reply;
13682
13683 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13684 "QTBuffer:circular:%x", val);
13685 putpkt (rs->buf);
13686 reply = remote_get_noisy_reply ();
13687 if (*reply == '\0')
13688 error (_("Target does not support this command."));
13689 if (strcmp (reply, "OK") != 0)
13690 error (_("Bogus reply from target: %s"), reply);
13691 }
13692
13693 traceframe_info_up
13694 remote_target::traceframe_info ()
13695 {
13696 gdb::optional<gdb::char_vector> text
13697 = target_read_stralloc (current_top_target (), TARGET_OBJECT_TRACEFRAME_INFO,
13698 NULL);
13699 if (text)
13700 return parse_traceframe_info (text->data ());
13701
13702 return NULL;
13703 }
13704
13705 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13706 instruction on which a fast tracepoint may be placed. Returns -1
13707 if the packet is not supported, and 0 if the minimum instruction
13708 length is unknown. */
13709
13710 int
13711 remote_target::get_min_fast_tracepoint_insn_len ()
13712 {
13713 struct remote_state *rs = get_remote_state ();
13714 char *reply;
13715
13716 /* If we're not debugging a process yet, the IPA can't be
13717 loaded. */
13718 if (!target_has_execution ())
13719 return 0;
13720
13721 /* Make sure the remote is pointing at the right process. */
13722 set_general_process ();
13723
13724 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
13725 putpkt (rs->buf);
13726 reply = remote_get_noisy_reply ();
13727 if (*reply == '\0')
13728 return -1;
13729 else
13730 {
13731 ULONGEST min_insn_len;
13732
13733 unpack_varlen_hex (reply, &min_insn_len);
13734
13735 return (int) min_insn_len;
13736 }
13737 }
13738
13739 void
13740 remote_target::set_trace_buffer_size (LONGEST val)
13741 {
13742 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13743 {
13744 struct remote_state *rs = get_remote_state ();
13745 char *buf = rs->buf.data ();
13746 char *endbuf = buf + get_remote_packet_size ();
13747 enum packet_result result;
13748
13749 gdb_assert (val >= 0 || val == -1);
13750 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13751 /* Send -1 as literal "-1" to avoid host size dependency. */
13752 if (val < 0)
13753 {
13754 *buf++ = '-';
13755 buf += hexnumstr (buf, (ULONGEST) -val);
13756 }
13757 else
13758 buf += hexnumstr (buf, (ULONGEST) val);
13759
13760 putpkt (rs->buf);
13761 remote_get_noisy_reply ();
13762 result = packet_ok (rs->buf,
13763 &remote_protocol_packets[PACKET_QTBuffer_size]);
13764
13765 if (result != PACKET_OK)
13766 warning (_("Bogus reply from target: %s"), rs->buf.data ());
13767 }
13768 }
13769
13770 bool
13771 remote_target::set_trace_notes (const char *user, const char *notes,
13772 const char *stop_notes)
13773 {
13774 struct remote_state *rs = get_remote_state ();
13775 char *reply;
13776 char *buf = rs->buf.data ();
13777 char *endbuf = buf + get_remote_packet_size ();
13778 int nbytes;
13779
13780 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13781 if (user)
13782 {
13783 buf += xsnprintf (buf, endbuf - buf, "user:");
13784 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13785 buf += 2 * nbytes;
13786 *buf++ = ';';
13787 }
13788 if (notes)
13789 {
13790 buf += xsnprintf (buf, endbuf - buf, "notes:");
13791 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13792 buf += 2 * nbytes;
13793 *buf++ = ';';
13794 }
13795 if (stop_notes)
13796 {
13797 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13798 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13799 buf += 2 * nbytes;
13800 *buf++ = ';';
13801 }
13802 /* Ensure the buffer is terminated. */
13803 *buf = '\0';
13804
13805 putpkt (rs->buf);
13806 reply = remote_get_noisy_reply ();
13807 if (*reply == '\0')
13808 return false;
13809
13810 if (strcmp (reply, "OK") != 0)
13811 error (_("Bogus reply from target: %s"), reply);
13812
13813 return true;
13814 }
13815
13816 bool
13817 remote_target::use_agent (bool use)
13818 {
13819 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13820 {
13821 struct remote_state *rs = get_remote_state ();
13822
13823 /* If the stub supports QAgent. */
13824 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
13825 putpkt (rs->buf);
13826 getpkt (&rs->buf, 0);
13827
13828 if (strcmp (rs->buf.data (), "OK") == 0)
13829 {
13830 ::use_agent = use;
13831 return true;
13832 }
13833 }
13834
13835 return false;
13836 }
13837
13838 bool
13839 remote_target::can_use_agent ()
13840 {
13841 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13842 }
13843
13844 struct btrace_target_info
13845 {
13846 /* The ptid of the traced thread. */
13847 ptid_t ptid;
13848
13849 /* The obtained branch trace configuration. */
13850 struct btrace_config conf;
13851 };
13852
13853 /* Reset our idea of our target's btrace configuration. */
13854
13855 static void
13856 remote_btrace_reset (remote_state *rs)
13857 {
13858 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13859 }
13860
13861 /* Synchronize the configuration with the target. */
13862
13863 void
13864 remote_target::btrace_sync_conf (const btrace_config *conf)
13865 {
13866 struct packet_config *packet;
13867 struct remote_state *rs;
13868 char *buf, *pos, *endbuf;
13869
13870 rs = get_remote_state ();
13871 buf = rs->buf.data ();
13872 endbuf = buf + get_remote_packet_size ();
13873
13874 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13875 if (packet_config_support (packet) == PACKET_ENABLE
13876 && conf->bts.size != rs->btrace_config.bts.size)
13877 {
13878 pos = buf;
13879 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13880 conf->bts.size);
13881
13882 putpkt (buf);
13883 getpkt (&rs->buf, 0);
13884
13885 if (packet_ok (buf, packet) == PACKET_ERROR)
13886 {
13887 if (buf[0] == 'E' && buf[1] == '.')
13888 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13889 else
13890 error (_("Failed to configure the BTS buffer size."));
13891 }
13892
13893 rs->btrace_config.bts.size = conf->bts.size;
13894 }
13895
13896 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13897 if (packet_config_support (packet) == PACKET_ENABLE
13898 && conf->pt.size != rs->btrace_config.pt.size)
13899 {
13900 pos = buf;
13901 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13902 conf->pt.size);
13903
13904 putpkt (buf);
13905 getpkt (&rs->buf, 0);
13906
13907 if (packet_ok (buf, packet) == PACKET_ERROR)
13908 {
13909 if (buf[0] == 'E' && buf[1] == '.')
13910 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13911 else
13912 error (_("Failed to configure the trace buffer size."));
13913 }
13914
13915 rs->btrace_config.pt.size = conf->pt.size;
13916 }
13917 }
13918
13919 /* Read the current thread's btrace configuration from the target and
13920 store it into CONF. */
13921
13922 static void
13923 btrace_read_config (struct btrace_config *conf)
13924 {
13925 gdb::optional<gdb::char_vector> xml
13926 = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE_CONF, "");
13927 if (xml)
13928 parse_xml_btrace_conf (conf, xml->data ());
13929 }
13930
13931 /* Maybe reopen target btrace. */
13932
13933 void
13934 remote_target::remote_btrace_maybe_reopen ()
13935 {
13936 struct remote_state *rs = get_remote_state ();
13937 int btrace_target_pushed = 0;
13938 #if !defined (HAVE_LIBIPT)
13939 int warned = 0;
13940 #endif
13941
13942 /* Don't bother walking the entirety of the remote thread list when
13943 we know the feature isn't supported by the remote. */
13944 if (packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
13945 return;
13946
13947 scoped_restore_current_thread restore_thread;
13948
13949 for (thread_info *tp : all_non_exited_threads (this))
13950 {
13951 set_general_thread (tp->ptid);
13952
13953 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13954 btrace_read_config (&rs->btrace_config);
13955
13956 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13957 continue;
13958
13959 #if !defined (HAVE_LIBIPT)
13960 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13961 {
13962 if (!warned)
13963 {
13964 warned = 1;
13965 warning (_("Target is recording using Intel Processor Trace "
13966 "but support was disabled at compile time."));
13967 }
13968
13969 continue;
13970 }
13971 #endif /* !defined (HAVE_LIBIPT) */
13972
13973 /* Push target, once, but before anything else happens. This way our
13974 changes to the threads will be cleaned up by unpushing the target
13975 in case btrace_read_config () throws. */
13976 if (!btrace_target_pushed)
13977 {
13978 btrace_target_pushed = 1;
13979 record_btrace_push_target ();
13980 printf_filtered (_("Target is recording using %s.\n"),
13981 btrace_format_string (rs->btrace_config.format));
13982 }
13983
13984 tp->btrace.target = XCNEW (struct btrace_target_info);
13985 tp->btrace.target->ptid = tp->ptid;
13986 tp->btrace.target->conf = rs->btrace_config;
13987 }
13988 }
13989
13990 /* Enable branch tracing. */
13991
13992 struct btrace_target_info *
13993 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
13994 {
13995 struct btrace_target_info *tinfo = NULL;
13996 struct packet_config *packet = NULL;
13997 struct remote_state *rs = get_remote_state ();
13998 char *buf = rs->buf.data ();
13999 char *endbuf = buf + get_remote_packet_size ();
14000
14001 switch (conf->format)
14002 {
14003 case BTRACE_FORMAT_BTS:
14004 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
14005 break;
14006
14007 case BTRACE_FORMAT_PT:
14008 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
14009 break;
14010 }
14011
14012 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14013 error (_("Target does not support branch tracing."));
14014
14015 btrace_sync_conf (conf);
14016
14017 set_general_thread (ptid);
14018
14019 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14020 putpkt (rs->buf);
14021 getpkt (&rs->buf, 0);
14022
14023 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14024 {
14025 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14026 error (_("Could not enable branch tracing for %s: %s"),
14027 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14028 else
14029 error (_("Could not enable branch tracing for %s."),
14030 target_pid_to_str (ptid).c_str ());
14031 }
14032
14033 tinfo = XCNEW (struct btrace_target_info);
14034 tinfo->ptid = ptid;
14035
14036 /* If we fail to read the configuration, we lose some information, but the
14037 tracing itself is not impacted. */
14038 try
14039 {
14040 btrace_read_config (&tinfo->conf);
14041 }
14042 catch (const gdb_exception_error &err)
14043 {
14044 if (err.message != NULL)
14045 warning ("%s", err.what ());
14046 }
14047
14048 return tinfo;
14049 }
14050
14051 /* Disable branch tracing. */
14052
14053 void
14054 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14055 {
14056 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
14057 struct remote_state *rs = get_remote_state ();
14058 char *buf = rs->buf.data ();
14059 char *endbuf = buf + get_remote_packet_size ();
14060
14061 if (packet_config_support (packet) != PACKET_ENABLE)
14062 error (_("Target does not support branch tracing."));
14063
14064 set_general_thread (tinfo->ptid);
14065
14066 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14067 putpkt (rs->buf);
14068 getpkt (&rs->buf, 0);
14069
14070 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14071 {
14072 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14073 error (_("Could not disable branch tracing for %s: %s"),
14074 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14075 else
14076 error (_("Could not disable branch tracing for %s."),
14077 target_pid_to_str (tinfo->ptid).c_str ());
14078 }
14079
14080 xfree (tinfo);
14081 }
14082
14083 /* Teardown branch tracing. */
14084
14085 void
14086 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14087 {
14088 /* We must not talk to the target during teardown. */
14089 xfree (tinfo);
14090 }
14091
14092 /* Read the branch trace. */
14093
14094 enum btrace_error
14095 remote_target::read_btrace (struct btrace_data *btrace,
14096 struct btrace_target_info *tinfo,
14097 enum btrace_read_type type)
14098 {
14099 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
14100 const char *annex;
14101
14102 if (packet_config_support (packet) != PACKET_ENABLE)
14103 error (_("Target does not support branch tracing."));
14104
14105 #if !defined(HAVE_LIBEXPAT)
14106 error (_("Cannot process branch tracing result. XML parsing not supported."));
14107 #endif
14108
14109 switch (type)
14110 {
14111 case BTRACE_READ_ALL:
14112 annex = "all";
14113 break;
14114 case BTRACE_READ_NEW:
14115 annex = "new";
14116 break;
14117 case BTRACE_READ_DELTA:
14118 annex = "delta";
14119 break;
14120 default:
14121 internal_error (__FILE__, __LINE__,
14122 _("Bad branch tracing read type: %u."),
14123 (unsigned int) type);
14124 }
14125
14126 gdb::optional<gdb::char_vector> xml
14127 = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE, annex);
14128 if (!xml)
14129 return BTRACE_ERR_UNKNOWN;
14130
14131 parse_xml_btrace (btrace, xml->data ());
14132
14133 return BTRACE_ERR_NONE;
14134 }
14135
14136 const struct btrace_config *
14137 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14138 {
14139 return &tinfo->conf;
14140 }
14141
14142 bool
14143 remote_target::augmented_libraries_svr4_read ()
14144 {
14145 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
14146 == PACKET_ENABLE);
14147 }
14148
14149 /* Implementation of to_load. */
14150
14151 void
14152 remote_target::load (const char *name, int from_tty)
14153 {
14154 generic_load (name, from_tty);
14155 }
14156
14157 /* Accepts an integer PID; returns a string representing a file that
14158 can be opened on the remote side to get the symbols for the child
14159 process. Returns NULL if the operation is not supported. */
14160
14161 char *
14162 remote_target::pid_to_exec_file (int pid)
14163 {
14164 static gdb::optional<gdb::char_vector> filename;
14165 char *annex = NULL;
14166
14167 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14168 return NULL;
14169
14170 inferior *inf = find_inferior_pid (this, pid);
14171 if (inf == NULL)
14172 internal_error (__FILE__, __LINE__,
14173 _("not currently attached to process %d"), pid);
14174
14175 if (!inf->fake_pid_p)
14176 {
14177 const int annex_size = 9;
14178
14179 annex = (char *) alloca (annex_size);
14180 xsnprintf (annex, annex_size, "%x", pid);
14181 }
14182
14183 filename = target_read_stralloc (current_top_target (),
14184 TARGET_OBJECT_EXEC_FILE, annex);
14185
14186 return filename ? filename->data () : nullptr;
14187 }
14188
14189 /* Implement the to_can_do_single_step target_ops method. */
14190
14191 int
14192 remote_target::can_do_single_step ()
14193 {
14194 /* We can only tell whether target supports single step or not by
14195 supported s and S vCont actions if the stub supports vContSupported
14196 feature. If the stub doesn't support vContSupported feature,
14197 we have conservatively to think target doesn't supports single
14198 step. */
14199 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14200 {
14201 struct remote_state *rs = get_remote_state ();
14202
14203 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14204 remote_vcont_probe ();
14205
14206 return rs->supports_vCont.s && rs->supports_vCont.S;
14207 }
14208 else
14209 return 0;
14210 }
14211
14212 /* Implementation of the to_execution_direction method for the remote
14213 target. */
14214
14215 enum exec_direction_kind
14216 remote_target::execution_direction ()
14217 {
14218 struct remote_state *rs = get_remote_state ();
14219
14220 return rs->last_resume_exec_dir;
14221 }
14222
14223 /* Return pointer to the thread_info struct which corresponds to
14224 THREAD_HANDLE (having length HANDLE_LEN). */
14225
14226 thread_info *
14227 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14228 int handle_len,
14229 inferior *inf)
14230 {
14231 for (thread_info *tp : all_non_exited_threads (this))
14232 {
14233 remote_thread_info *priv = get_remote_thread_info (tp);
14234
14235 if (tp->inf == inf && priv != NULL)
14236 {
14237 if (handle_len != priv->thread_handle.size ())
14238 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14239 handle_len, priv->thread_handle.size ());
14240 if (memcmp (thread_handle, priv->thread_handle.data (),
14241 handle_len) == 0)
14242 return tp;
14243 }
14244 }
14245
14246 return NULL;
14247 }
14248
14249 gdb::byte_vector
14250 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14251 {
14252 remote_thread_info *priv = get_remote_thread_info (tp);
14253 return priv->thread_handle;
14254 }
14255
14256 bool
14257 remote_target::can_async_p ()
14258 {
14259 struct remote_state *rs = get_remote_state ();
14260
14261 /* We don't go async if the user has explicitly prevented it with the
14262 "maint set target-async" command. */
14263 if (!target_async_permitted)
14264 return false;
14265
14266 /* We're async whenever the serial device is. */
14267 return serial_can_async_p (rs->remote_desc);
14268 }
14269
14270 bool
14271 remote_target::is_async_p ()
14272 {
14273 struct remote_state *rs = get_remote_state ();
14274
14275 if (!target_async_permitted)
14276 /* We only enable async when the user specifically asks for it. */
14277 return false;
14278
14279 /* We're async whenever the serial device is. */
14280 return serial_is_async_p (rs->remote_desc);
14281 }
14282
14283 /* Pass the SERIAL event on and up to the client. One day this code
14284 will be able to delay notifying the client of an event until the
14285 point where an entire packet has been received. */
14286
14287 static serial_event_ftype remote_async_serial_handler;
14288
14289 static void
14290 remote_async_serial_handler (struct serial *scb, void *context)
14291 {
14292 /* Don't propogate error information up to the client. Instead let
14293 the client find out about the error by querying the target. */
14294 inferior_event_handler (INF_REG_EVENT);
14295 }
14296
14297 static void
14298 remote_async_inferior_event_handler (gdb_client_data data)
14299 {
14300 inferior_event_handler (INF_REG_EVENT);
14301 }
14302
14303 int
14304 remote_target::async_wait_fd ()
14305 {
14306 struct remote_state *rs = get_remote_state ();
14307 return rs->remote_desc->fd;
14308 }
14309
14310 void
14311 remote_target::async (int enable)
14312 {
14313 struct remote_state *rs = get_remote_state ();
14314
14315 if (enable)
14316 {
14317 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14318
14319 /* If there are pending events in the stop reply queue tell the
14320 event loop to process them. */
14321 if (!rs->stop_reply_queue.empty ())
14322 mark_async_event_handler (rs->remote_async_inferior_event_token);
14323 /* For simplicity, below we clear the pending events token
14324 without remembering whether it is marked, so here we always
14325 mark it. If there's actually no pending notification to
14326 process, this ends up being a no-op (other than a spurious
14327 event-loop wakeup). */
14328 if (target_is_non_stop_p ())
14329 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14330 }
14331 else
14332 {
14333 serial_async (rs->remote_desc, NULL, NULL);
14334 /* If the core is disabling async, it doesn't want to be
14335 disturbed with target events. Clear all async event sources
14336 too. */
14337 clear_async_event_handler (rs->remote_async_inferior_event_token);
14338 if (target_is_non_stop_p ())
14339 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14340 }
14341 }
14342
14343 /* Implementation of the to_thread_events method. */
14344
14345 void
14346 remote_target::thread_events (int enable)
14347 {
14348 struct remote_state *rs = get_remote_state ();
14349 size_t size = get_remote_packet_size ();
14350
14351 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14352 return;
14353
14354 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
14355 putpkt (rs->buf);
14356 getpkt (&rs->buf, 0);
14357
14358 switch (packet_ok (rs->buf,
14359 &remote_protocol_packets[PACKET_QThreadEvents]))
14360 {
14361 case PACKET_OK:
14362 if (strcmp (rs->buf.data (), "OK") != 0)
14363 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
14364 break;
14365 case PACKET_ERROR:
14366 warning (_("Remote failure reply: %s"), rs->buf.data ());
14367 break;
14368 case PACKET_UNKNOWN:
14369 break;
14370 }
14371 }
14372
14373 static void
14374 show_remote_cmd (const char *args, int from_tty)
14375 {
14376 /* We can't just use cmd_show_list here, because we want to skip
14377 the redundant "show remote Z-packet" and the legacy aliases. */
14378 struct cmd_list_element *list = remote_show_cmdlist;
14379 struct ui_out *uiout = current_uiout;
14380
14381 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14382 for (; list != NULL; list = list->next)
14383 if (strcmp (list->name, "Z-packet") == 0)
14384 continue;
14385 else if (list->type == not_set_cmd)
14386 /* Alias commands are exactly like the original, except they
14387 don't have the normal type. */
14388 continue;
14389 else
14390 {
14391 ui_out_emit_tuple option_emitter (uiout, "option");
14392
14393 uiout->field_string ("name", list->name);
14394 uiout->text (": ");
14395 if (list->type == show_cmd)
14396 do_show_command (NULL, from_tty, list);
14397 else
14398 cmd_func (list, NULL, from_tty);
14399 }
14400 }
14401
14402
14403 /* Function to be called whenever a new objfile (shlib) is detected. */
14404 static void
14405 remote_new_objfile (struct objfile *objfile)
14406 {
14407 remote_target *remote = get_current_remote_target ();
14408
14409 if (remote != NULL) /* Have a remote connection. */
14410 remote->remote_check_symbols ();
14411 }
14412
14413 /* Pull all the tracepoints defined on the target and create local
14414 data structures representing them. We don't want to create real
14415 tracepoints yet, we don't want to mess up the user's existing
14416 collection. */
14417
14418 int
14419 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14420 {
14421 struct remote_state *rs = get_remote_state ();
14422 char *p;
14423
14424 /* Ask for a first packet of tracepoint definition. */
14425 putpkt ("qTfP");
14426 getpkt (&rs->buf, 0);
14427 p = rs->buf.data ();
14428 while (*p && *p != 'l')
14429 {
14430 parse_tracepoint_definition (p, utpp);
14431 /* Ask for another packet of tracepoint definition. */
14432 putpkt ("qTsP");
14433 getpkt (&rs->buf, 0);
14434 p = rs->buf.data ();
14435 }
14436 return 0;
14437 }
14438
14439 int
14440 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14441 {
14442 struct remote_state *rs = get_remote_state ();
14443 char *p;
14444
14445 /* Ask for a first packet of variable definition. */
14446 putpkt ("qTfV");
14447 getpkt (&rs->buf, 0);
14448 p = rs->buf.data ();
14449 while (*p && *p != 'l')
14450 {
14451 parse_tsv_definition (p, utsvp);
14452 /* Ask for another packet of variable definition. */
14453 putpkt ("qTsV");
14454 getpkt (&rs->buf, 0);
14455 p = rs->buf.data ();
14456 }
14457 return 0;
14458 }
14459
14460 /* The "set/show range-stepping" show hook. */
14461
14462 static void
14463 show_range_stepping (struct ui_file *file, int from_tty,
14464 struct cmd_list_element *c,
14465 const char *value)
14466 {
14467 fprintf_filtered (file,
14468 _("Debugger's willingness to use range stepping "
14469 "is %s.\n"), value);
14470 }
14471
14472 /* Return true if the vCont;r action is supported by the remote
14473 stub. */
14474
14475 bool
14476 remote_target::vcont_r_supported ()
14477 {
14478 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14479 remote_vcont_probe ();
14480
14481 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14482 && get_remote_state ()->supports_vCont.r);
14483 }
14484
14485 /* The "set/show range-stepping" set hook. */
14486
14487 static void
14488 set_range_stepping (const char *ignore_args, int from_tty,
14489 struct cmd_list_element *c)
14490 {
14491 /* When enabling, check whether range stepping is actually supported
14492 by the target, and warn if not. */
14493 if (use_range_stepping)
14494 {
14495 remote_target *remote = get_current_remote_target ();
14496 if (remote == NULL
14497 || !remote->vcont_r_supported ())
14498 warning (_("Range stepping is not supported by the current target"));
14499 }
14500 }
14501
14502 static void
14503 show_remote_debug (struct ui_file *file, int from_tty,
14504 struct cmd_list_element *c, const char *value)
14505 {
14506 fprintf_filtered (file, _("Debugging of remote protocol is %s.\n"),
14507 value);
14508 }
14509
14510 static void
14511 show_remote_timeout (struct ui_file *file, int from_tty,
14512 struct cmd_list_element *c, const char *value)
14513 {
14514 fprintf_filtered (file,
14515 _("Timeout limit to wait for target to respond is %s.\n"),
14516 value);
14517 }
14518
14519 /* Implement the "supports_memory_tagging" target_ops method. */
14520
14521 bool
14522 remote_target::supports_memory_tagging ()
14523 {
14524 return remote_memory_tagging_p ();
14525 }
14526
14527 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
14528
14529 static void
14530 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14531 size_t len, int type)
14532 {
14533 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14534
14535 std::string request = string_printf ("qMemTags:%s,%s:%s",
14536 phex_nz (address, addr_size),
14537 phex_nz (len, sizeof (len)),
14538 phex_nz (type, sizeof (type)));
14539
14540 strcpy (packet.data (), request.c_str ());
14541 }
14542
14543 /* Parse the qMemTags packet reply into TAGS.
14544
14545 Return true if successful, false otherwise. */
14546
14547 static bool
14548 parse_fetch_memtags_reply (const gdb::char_vector &reply,
14549 gdb::byte_vector &tags)
14550 {
14551 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
14552 return false;
14553
14554 /* Copy the tag data. */
14555 tags = hex2bin (reply.data () + 1);
14556
14557 return true;
14558 }
14559
14560 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
14561
14562 static void
14563 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14564 size_t len, int type,
14565 const gdb::byte_vector &tags)
14566 {
14567 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14568
14569 /* Put together the main packet, address and length. */
14570 std::string request = string_printf ("QMemTags:%s,%s:%s:",
14571 phex_nz (address, addr_size),
14572 phex_nz (len, sizeof (len)),
14573 phex_nz (type, sizeof (type)));
14574 request += bin2hex (tags.data (), tags.size ());
14575
14576 /* Check if we have exceeded the maximum packet size. */
14577 if (packet.size () < request.length ())
14578 error (_("Contents too big for packet QMemTags."));
14579
14580 strcpy (packet.data (), request.c_str ());
14581 }
14582
14583 /* Implement the "fetch_memtags" target_ops method. */
14584
14585 bool
14586 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
14587 gdb::byte_vector &tags, int type)
14588 {
14589 /* Make sure the qMemTags packet is supported. */
14590 if (!remote_memory_tagging_p ())
14591 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
14592
14593 struct remote_state *rs = get_remote_state ();
14594
14595 create_fetch_memtags_request (rs->buf, address, len, type);
14596
14597 putpkt (rs->buf);
14598 getpkt (&rs->buf, 0);
14599
14600 return parse_fetch_memtags_reply (rs->buf, tags);
14601 }
14602
14603 /* Implement the "store_memtags" target_ops method. */
14604
14605 bool
14606 remote_target::store_memtags (CORE_ADDR address, size_t len,
14607 const gdb::byte_vector &tags, int type)
14608 {
14609 /* Make sure the QMemTags packet is supported. */
14610 if (!remote_memory_tagging_p ())
14611 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
14612
14613 struct remote_state *rs = get_remote_state ();
14614
14615 create_store_memtags_request (rs->buf, address, len, type, tags);
14616
14617 putpkt (rs->buf);
14618 getpkt (&rs->buf, 0);
14619
14620 /* Verify if the request was successful. */
14621 return packet_check_result (rs->buf.data ()) == PACKET_OK;
14622 }
14623
14624 #if GDB_SELF_TEST
14625
14626 namespace selftests {
14627
14628 static void
14629 test_memory_tagging_functions ()
14630 {
14631 remote_target remote;
14632
14633 struct packet_config *config
14634 = &remote_protocol_packets[PACKET_memory_tagging_feature];
14635
14636 scoped_restore restore_memtag_support_
14637 = make_scoped_restore (&config->support);
14638
14639 /* Test memory tagging packet support. */
14640 config->support = PACKET_SUPPORT_UNKNOWN;
14641 SELF_CHECK (remote.supports_memory_tagging () == false);
14642 config->support = PACKET_DISABLE;
14643 SELF_CHECK (remote.supports_memory_tagging () == false);
14644 config->support = PACKET_ENABLE;
14645 SELF_CHECK (remote.supports_memory_tagging () == true);
14646
14647 /* Setup testing. */
14648 gdb::char_vector packet;
14649 gdb::byte_vector tags, bv;
14650 std::string expected, reply;
14651 packet.resize (32000);
14652
14653 /* Test creating a qMemTags request. */
14654
14655 expected = "qMemTags:0,0:0";
14656 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
14657 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14658
14659 expected = "qMemTags:deadbeef,10:1";
14660 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
14661 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14662
14663 /* Test parsing a qMemTags reply. */
14664
14665 /* Error reply, tags vector unmodified. */
14666 reply = "E00";
14667 strcpy (packet.data (), reply.c_str ());
14668 tags.resize (0);
14669 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
14670 SELF_CHECK (tags.size () == 0);
14671
14672 /* Valid reply, tags vector updated. */
14673 tags.resize (0);
14674 bv.resize (0);
14675
14676 for (int i = 0; i < 5; i++)
14677 bv.push_back (i);
14678
14679 reply = "m" + bin2hex (bv.data (), bv.size ());
14680 strcpy (packet.data (), reply.c_str ());
14681
14682 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
14683 SELF_CHECK (tags.size () == 5);
14684
14685 for (int i = 0; i < 5; i++)
14686 SELF_CHECK (tags[i] == i);
14687
14688 /* Test creating a QMemTags request. */
14689
14690 /* Empty tag data. */
14691 tags.resize (0);
14692 expected = "QMemTags:0,0:0:";
14693 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
14694 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14695 expected.length ()) == 0);
14696
14697 /* Non-empty tag data. */
14698 tags.resize (0);
14699 for (int i = 0; i < 5; i++)
14700 tags.push_back (i);
14701 expected = "QMemTags:deadbeef,ff:1:0001020304";
14702 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
14703 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14704 expected.length ()) == 0);
14705 }
14706
14707 } // namespace selftests
14708 #endif /* GDB_SELF_TEST */
14709
14710 void _initialize_remote ();
14711 void
14712 _initialize_remote ()
14713 {
14714 struct cmd_list_element *cmd;
14715 const char *cmd_name;
14716
14717 /* architecture specific data */
14718 remote_g_packet_data_handle =
14719 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14720
14721 add_target (remote_target_info, remote_target::open);
14722 add_target (extended_remote_target_info, extended_remote_target::open);
14723
14724 /* Hook into new objfile notification. */
14725 gdb::observers::new_objfile.attach (remote_new_objfile);
14726
14727 #if 0
14728 init_remote_threadtests ();
14729 #endif
14730
14731 /* set/show remote ... */
14732
14733 add_basic_prefix_cmd ("remote", class_maintenance, _("\
14734 Remote protocol specific variables.\n\
14735 Configure various remote-protocol specific variables such as\n\
14736 the packets being used."),
14737 &remote_set_cmdlist, "set remote ",
14738 0 /* allow-unknown */, &setlist);
14739 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14740 Remote protocol specific variables.\n\
14741 Configure various remote-protocol specific variables such as\n\
14742 the packets being used."),
14743 &remote_show_cmdlist, "show remote ",
14744 0 /* allow-unknown */, &showlist);
14745
14746 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14747 Compare section data on target to the exec file.\n\
14748 Argument is a single section name (default: all loaded sections).\n\
14749 To compare only read-only loaded sections, specify the -r option."),
14750 &cmdlist);
14751
14752 add_cmd ("packet", class_maintenance, packet_command, _("\
14753 Send an arbitrary packet to a remote target.\n\
14754 maintenance packet TEXT\n\
14755 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14756 this command sends the string TEXT to the inferior, and displays the\n\
14757 response packet. GDB supplies the initial `$' character, and the\n\
14758 terminating `#' character and checksum."),
14759 &maintenancelist);
14760
14761 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14762 Set whether to send break if interrupted."), _("\
14763 Show whether to send break if interrupted."), _("\
14764 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14765 set_remotebreak, show_remotebreak,
14766 &setlist, &showlist);
14767 cmd_name = "remotebreak";
14768 cmd = lookup_cmd (&cmd_name, setlist, "", NULL, -1, 1);
14769 deprecate_cmd (cmd, "set remote interrupt-sequence");
14770 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14771 cmd = lookup_cmd (&cmd_name, showlist, "", NULL, -1, 1);
14772 deprecate_cmd (cmd, "show remote interrupt-sequence");
14773
14774 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14775 interrupt_sequence_modes, &interrupt_sequence_mode,
14776 _("\
14777 Set interrupt sequence to remote target."), _("\
14778 Show interrupt sequence to remote target."), _("\
14779 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14780 NULL, show_interrupt_sequence,
14781 &remote_set_cmdlist,
14782 &remote_show_cmdlist);
14783
14784 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14785 &interrupt_on_connect, _("\
14786 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
14787 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
14788 If set, interrupt sequence is sent to remote target."),
14789 NULL, NULL,
14790 &remote_set_cmdlist, &remote_show_cmdlist);
14791
14792 /* Install commands for configuring memory read/write packets. */
14793
14794 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14795 Set the maximum number of bytes per memory write packet (deprecated)."),
14796 &setlist);
14797 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14798 Show the maximum number of bytes per memory write packet (deprecated)."),
14799 &showlist);
14800 add_cmd ("memory-write-packet-size", no_class,
14801 set_memory_write_packet_size, _("\
14802 Set the maximum number of bytes per memory-write packet.\n\
14803 Specify the number of bytes in a packet or 0 (zero) for the\n\
14804 default packet size. The actual limit is further reduced\n\
14805 dependent on the target. Specify ``fixed'' to disable the\n\
14806 further restriction and ``limit'' to enable that restriction."),
14807 &remote_set_cmdlist);
14808 add_cmd ("memory-read-packet-size", no_class,
14809 set_memory_read_packet_size, _("\
14810 Set the maximum number of bytes per memory-read packet.\n\
14811 Specify the number of bytes in a packet or 0 (zero) for the\n\
14812 default packet size. The actual limit is further reduced\n\
14813 dependent on the target. Specify ``fixed'' to disable the\n\
14814 further restriction and ``limit'' to enable that restriction."),
14815 &remote_set_cmdlist);
14816 add_cmd ("memory-write-packet-size", no_class,
14817 show_memory_write_packet_size,
14818 _("Show the maximum number of bytes per memory-write packet."),
14819 &remote_show_cmdlist);
14820 add_cmd ("memory-read-packet-size", no_class,
14821 show_memory_read_packet_size,
14822 _("Show the maximum number of bytes per memory-read packet."),
14823 &remote_show_cmdlist);
14824
14825 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
14826 &remote_hw_watchpoint_limit, _("\
14827 Set the maximum number of target hardware watchpoints."), _("\
14828 Show the maximum number of target hardware watchpoints."), _("\
14829 Specify \"unlimited\" for unlimited hardware watchpoints."),
14830 NULL, show_hardware_watchpoint_limit,
14831 &remote_set_cmdlist,
14832 &remote_show_cmdlist);
14833 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
14834 no_class,
14835 &remote_hw_watchpoint_length_limit, _("\
14836 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14837 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14838 Specify \"unlimited\" to allow watchpoints of unlimited size."),
14839 NULL, show_hardware_watchpoint_length_limit,
14840 &remote_set_cmdlist, &remote_show_cmdlist);
14841 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
14842 &remote_hw_breakpoint_limit, _("\
14843 Set the maximum number of target hardware breakpoints."), _("\
14844 Show the maximum number of target hardware breakpoints."), _("\
14845 Specify \"unlimited\" for unlimited hardware breakpoints."),
14846 NULL, show_hardware_breakpoint_limit,
14847 &remote_set_cmdlist, &remote_show_cmdlist);
14848
14849 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14850 &remote_address_size, _("\
14851 Set the maximum size of the address (in bits) in a memory packet."), _("\
14852 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14853 NULL,
14854 NULL, /* FIXME: i18n: */
14855 &setlist, &showlist);
14856
14857 init_all_packet_configs ();
14858
14859 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14860 "X", "binary-download", 1);
14861
14862 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14863 "vCont", "verbose-resume", 0);
14864
14865 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14866 "QPassSignals", "pass-signals", 0);
14867
14868 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14869 "QCatchSyscalls", "catch-syscalls", 0);
14870
14871 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14872 "QProgramSignals", "program-signals", 0);
14873
14874 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14875 "QSetWorkingDir", "set-working-dir", 0);
14876
14877 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14878 "QStartupWithShell", "startup-with-shell", 0);
14879
14880 add_packet_config_cmd (&remote_protocol_packets
14881 [PACKET_QEnvironmentHexEncoded],
14882 "QEnvironmentHexEncoded", "environment-hex-encoded",
14883 0);
14884
14885 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14886 "QEnvironmentReset", "environment-reset",
14887 0);
14888
14889 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14890 "QEnvironmentUnset", "environment-unset",
14891 0);
14892
14893 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14894 "qSymbol", "symbol-lookup", 0);
14895
14896 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14897 "P", "set-register", 1);
14898
14899 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14900 "p", "fetch-register", 1);
14901
14902 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14903 "Z0", "software-breakpoint", 0);
14904
14905 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14906 "Z1", "hardware-breakpoint", 0);
14907
14908 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14909 "Z2", "write-watchpoint", 0);
14910
14911 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14912 "Z3", "read-watchpoint", 0);
14913
14914 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14915 "Z4", "access-watchpoint", 0);
14916
14917 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14918 "qXfer:auxv:read", "read-aux-vector", 0);
14919
14920 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14921 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14922
14923 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14924 "qXfer:features:read", "target-features", 0);
14925
14926 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14927 "qXfer:libraries:read", "library-info", 0);
14928
14929 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14930 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14931
14932 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14933 "qXfer:memory-map:read", "memory-map", 0);
14934
14935 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14936 "qXfer:osdata:read", "osdata", 0);
14937
14938 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14939 "qXfer:threads:read", "threads", 0);
14940
14941 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14942 "qXfer:siginfo:read", "read-siginfo-object", 0);
14943
14944 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14945 "qXfer:siginfo:write", "write-siginfo-object", 0);
14946
14947 add_packet_config_cmd
14948 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14949 "qXfer:traceframe-info:read", "traceframe-info", 0);
14950
14951 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14952 "qXfer:uib:read", "unwind-info-block", 0);
14953
14954 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14955 "qGetTLSAddr", "get-thread-local-storage-address",
14956 0);
14957
14958 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14959 "qGetTIBAddr", "get-thread-information-block-address",
14960 0);
14961
14962 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14963 "bc", "reverse-continue", 0);
14964
14965 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14966 "bs", "reverse-step", 0);
14967
14968 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14969 "qSupported", "supported-packets", 0);
14970
14971 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14972 "qSearch:memory", "search-memory", 0);
14973
14974 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14975 "qTStatus", "trace-status", 0);
14976
14977 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14978 "vFile:setfs", "hostio-setfs", 0);
14979
14980 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14981 "vFile:open", "hostio-open", 0);
14982
14983 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14984 "vFile:pread", "hostio-pread", 0);
14985
14986 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14987 "vFile:pwrite", "hostio-pwrite", 0);
14988
14989 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14990 "vFile:close", "hostio-close", 0);
14991
14992 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14993 "vFile:unlink", "hostio-unlink", 0);
14994
14995 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14996 "vFile:readlink", "hostio-readlink", 0);
14997
14998 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14999 "vFile:fstat", "hostio-fstat", 0);
15000
15001 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
15002 "vAttach", "attach", 0);
15003
15004 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
15005 "vRun", "run", 0);
15006
15007 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
15008 "QStartNoAckMode", "noack", 0);
15009
15010 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
15011 "vKill", "kill", 0);
15012
15013 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
15014 "qAttached", "query-attached", 0);
15015
15016 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
15017 "ConditionalTracepoints",
15018 "conditional-tracepoints", 0);
15019
15020 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
15021 "ConditionalBreakpoints",
15022 "conditional-breakpoints", 0);
15023
15024 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
15025 "BreakpointCommands",
15026 "breakpoint-commands", 0);
15027
15028 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
15029 "FastTracepoints", "fast-tracepoints", 0);
15030
15031 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
15032 "TracepointSource", "TracepointSource", 0);
15033
15034 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
15035 "QAllow", "allow", 0);
15036
15037 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
15038 "StaticTracepoints", "static-tracepoints", 0);
15039
15040 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
15041 "InstallInTrace", "install-in-trace", 0);
15042
15043 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
15044 "qXfer:statictrace:read", "read-sdata-object", 0);
15045
15046 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
15047 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
15048
15049 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
15050 "QDisableRandomization", "disable-randomization", 0);
15051
15052 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
15053 "QAgent", "agent", 0);
15054
15055 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
15056 "QTBuffer:size", "trace-buffer-size", 0);
15057
15058 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
15059 "Qbtrace:off", "disable-btrace", 0);
15060
15061 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
15062 "Qbtrace:bts", "enable-btrace-bts", 0);
15063
15064 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
15065 "Qbtrace:pt", "enable-btrace-pt", 0);
15066
15067 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
15068 "qXfer:btrace", "read-btrace", 0);
15069
15070 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
15071 "qXfer:btrace-conf", "read-btrace-conf", 0);
15072
15073 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
15074 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
15075
15076 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
15077 "multiprocess-feature", "multiprocess-feature", 0);
15078
15079 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
15080 "swbreak-feature", "swbreak-feature", 0);
15081
15082 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
15083 "hwbreak-feature", "hwbreak-feature", 0);
15084
15085 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
15086 "fork-event-feature", "fork-event-feature", 0);
15087
15088 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
15089 "vfork-event-feature", "vfork-event-feature", 0);
15090
15091 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
15092 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
15093
15094 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
15095 "vContSupported", "verbose-resume-supported", 0);
15096
15097 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
15098 "exec-event-feature", "exec-event-feature", 0);
15099
15100 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
15101 "vCtrlC", "ctrl-c", 0);
15102
15103 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
15104 "QThreadEvents", "thread-events", 0);
15105
15106 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
15107 "N stop reply", "no-resumed-stop-reply", 0);
15108
15109 add_packet_config_cmd (&remote_protocol_packets[PACKET_memory_tagging_feature],
15110 "memory-tagging-feature", "memory-tagging-feature", 0);
15111
15112 /* Assert that we've registered "set remote foo-packet" commands
15113 for all packet configs. */
15114 {
15115 int i;
15116
15117 for (i = 0; i < PACKET_MAX; i++)
15118 {
15119 /* Ideally all configs would have a command associated. Some
15120 still don't though. */
15121 int excepted;
15122
15123 switch (i)
15124 {
15125 case PACKET_QNonStop:
15126 case PACKET_EnableDisableTracepoints_feature:
15127 case PACKET_tracenz_feature:
15128 case PACKET_DisconnectedTracing_feature:
15129 case PACKET_augmented_libraries_svr4_read_feature:
15130 case PACKET_qCRC:
15131 /* Additions to this list need to be well justified:
15132 pre-existing packets are OK; new packets are not. */
15133 excepted = 1;
15134 break;
15135 default:
15136 excepted = 0;
15137 break;
15138 }
15139
15140 /* This catches both forgetting to add a config command, and
15141 forgetting to remove a packet from the exception list. */
15142 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
15143 }
15144 }
15145
15146 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15147 Z sub-packet has its own set and show commands, but users may
15148 have sets to this variable in their .gdbinit files (or in their
15149 documentation). */
15150 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
15151 &remote_Z_packet_detect, _("\
15152 Set use of remote protocol `Z' packets."), _("\
15153 Show use of remote protocol `Z' packets."), _("\
15154 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
15155 packets."),
15156 set_remote_protocol_Z_packet_cmd,
15157 show_remote_protocol_Z_packet_cmd,
15158 /* FIXME: i18n: Use of remote protocol
15159 `Z' packets is %s. */
15160 &remote_set_cmdlist, &remote_show_cmdlist);
15161
15162 add_basic_prefix_cmd ("remote", class_files, _("\
15163 Manipulate files on the remote system.\n\
15164 Transfer files to and from the remote target system."),
15165 &remote_cmdlist, "remote ",
15166 0 /* allow-unknown */, &cmdlist);
15167
15168 add_cmd ("put", class_files, remote_put_command,
15169 _("Copy a local file to the remote system."),
15170 &remote_cmdlist);
15171
15172 add_cmd ("get", class_files, remote_get_command,
15173 _("Copy a remote file to the local system."),
15174 &remote_cmdlist);
15175
15176 add_cmd ("delete", class_files, remote_delete_command,
15177 _("Delete a remote file."),
15178 &remote_cmdlist);
15179
15180 add_setshow_string_noescape_cmd ("exec-file", class_files,
15181 &remote_exec_file_var, _("\
15182 Set the remote pathname for \"run\"."), _("\
15183 Show the remote pathname for \"run\"."), NULL,
15184 set_remote_exec_file,
15185 show_remote_exec_file,
15186 &remote_set_cmdlist,
15187 &remote_show_cmdlist);
15188
15189 add_setshow_boolean_cmd ("range-stepping", class_run,
15190 &use_range_stepping, _("\
15191 Enable or disable range stepping."), _("\
15192 Show whether target-assisted range stepping is enabled."), _("\
15193 If on, and the target supports it, when stepping a source line, GDB\n\
15194 tells the target to step the corresponding range of addresses itself instead\n\
15195 of issuing multiple single-steps. This speeds up source level\n\
15196 stepping. If off, GDB always issues single-steps, even if range\n\
15197 stepping is supported by the target. The default is on."),
15198 set_range_stepping,
15199 show_range_stepping,
15200 &setlist,
15201 &showlist);
15202
15203 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15204 Set watchdog timer."), _("\
15205 Show watchdog timer."), _("\
15206 When non-zero, this timeout is used instead of waiting forever for a target\n\
15207 to finish a low-level step or continue operation. If the specified amount\n\
15208 of time passes without a response from the target, an error occurs."),
15209 NULL,
15210 show_watchdog,
15211 &setlist, &showlist);
15212
15213 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15214 &remote_packet_max_chars, _("\
15215 Set the maximum number of characters to display for each remote packet."), _("\
15216 Show the maximum number of characters to display for each remote packet."), _("\
15217 Specify \"unlimited\" to display all the characters."),
15218 NULL, show_remote_packet_max_chars,
15219 &setdebuglist, &showdebuglist);
15220
15221 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15222 _("Set debugging of remote protocol."),
15223 _("Show debugging of remote protocol."),
15224 _("\
15225 When enabled, each packet sent or received with the remote target\n\
15226 is displayed."),
15227 NULL,
15228 show_remote_debug,
15229 &setdebuglist, &showdebuglist);
15230
15231 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15232 &remote_timeout, _("\
15233 Set timeout limit to wait for target to respond."), _("\
15234 Show timeout limit to wait for target to respond."), _("\
15235 This value is used to set the time limit for gdb to wait for a response\n\
15236 from the target."),
15237 NULL,
15238 show_remote_timeout,
15239 &setlist, &showlist);
15240
15241 /* Eventually initialize fileio. See fileio.c */
15242 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
15243
15244 #if GDB_SELF_TEST
15245 selftests::register_test ("remote_memory_tagging",
15246 selftests::test_memory_tagging_functions);
15247 #endif
15248 }