gdb: use ptid_t::to_string instead of target_pid_to_str in debug statements
[binutils-gdb.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3 Copyright (C) 1988-2022 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20 /* See the GDB User Guide for details of the GDB remote protocol. */
21
22 #include "defs.h"
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "bfd.h"
28 #include "symfile.h"
29 #include "target.h"
30 #include "process-stratum-target.h"
31 #include "gdbcmd.h"
32 #include "objfiles.h"
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
35 #include "remote.h"
36 #include "remote-notif.h"
37 #include "regcache.h"
38 #include "value.h"
39 #include "observable.h"
40 #include "solib.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
44 #include "gdb_bfd.h"
45 #include "gdbsupport/filestuff.h"
46 #include "gdbsupport/rsp-low.h"
47 #include "disasm.h"
48 #include "location.h"
49
50 #include "gdbsupport/gdb_sys_time.h"
51
52 #include "gdbsupport/event-loop.h"
53 #include "event-top.h"
54 #include "inf-loop.h"
55
56 #include <signal.h>
57 #include "serial.h"
58
59 #include "gdbcore.h"
60
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
63 #include <sys/stat.h>
64 #include "xml-support.h"
65
66 #include "memory-map.h"
67
68 #include "tracepoint.h"
69 #include "ax.h"
70 #include "ax-gdb.h"
71 #include "gdbsupport/agent.h"
72 #include "btrace.h"
73 #include "record-btrace.h"
74 #include <algorithm>
75 #include "gdbsupport/scoped_restore.h"
76 #include "gdbsupport/environ.h"
77 #include "gdbsupport/byte-vector.h"
78 #include "gdbsupport/search.h"
79 #include <algorithm>
80 #include <unordered_map>
81 #include "async-event.h"
82 #include "gdbsupport/selftest.h"
83
84 /* The remote target. */
85
86 static const char remote_doc[] = N_("\
87 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
88 Specify the serial device it is connected to\n\
89 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
90
91 /* See remote.h */
92
93 bool remote_debug = false;
94
95 #define OPAQUETHREADBYTES 8
96
97 /* a 64 bit opaque identifier */
98 typedef unsigned char threadref[OPAQUETHREADBYTES];
99
100 struct gdb_ext_thread_info;
101 struct threads_listing_context;
102 typedef int (*rmt_thread_action) (threadref *ref, void *context);
103 struct protocol_feature;
104 struct packet_reg;
105
106 struct stop_reply;
107 typedef std::unique_ptr<stop_reply> stop_reply_up;
108
109 /* Generic configuration support for packets the stub optionally
110 supports. Allows the user to specify the use of the packet as well
111 as allowing GDB to auto-detect support in the remote stub. */
112
113 enum packet_support
114 {
115 PACKET_SUPPORT_UNKNOWN = 0,
116 PACKET_ENABLE,
117 PACKET_DISABLE
118 };
119
120 /* Analyze a packet's return value and update the packet config
121 accordingly. */
122
123 enum packet_result
124 {
125 PACKET_ERROR,
126 PACKET_OK,
127 PACKET_UNKNOWN
128 };
129
130 struct threads_listing_context;
131
132 /* Stub vCont actions support.
133
134 Each field is a boolean flag indicating whether the stub reports
135 support for the corresponding action. */
136
137 struct vCont_action_support
138 {
139 /* vCont;t */
140 bool t = false;
141
142 /* vCont;r */
143 bool r = false;
144
145 /* vCont;s */
146 bool s = false;
147
148 /* vCont;S */
149 bool S = false;
150 };
151
152 /* About this many threadids fit in a packet. */
153
154 #define MAXTHREADLISTRESULTS 32
155
156 /* Data for the vFile:pread readahead cache. */
157
158 struct readahead_cache
159 {
160 /* Invalidate the readahead cache. */
161 void invalidate ();
162
163 /* Invalidate the readahead cache if it is holding data for FD. */
164 void invalidate_fd (int fd);
165
166 /* Serve pread from the readahead cache. Returns number of bytes
167 read, or 0 if the request can't be served from the cache. */
168 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
169
170 /* The file descriptor for the file that is being cached. -1 if the
171 cache is invalid. */
172 int fd = -1;
173
174 /* The offset into the file that the cache buffer corresponds
175 to. */
176 ULONGEST offset = 0;
177
178 /* The buffer holding the cache contents. */
179 gdb_byte *buf = nullptr;
180 /* The buffer's size. We try to read as much as fits into a packet
181 at a time. */
182 size_t bufsize = 0;
183
184 /* Cache hit and miss counters. */
185 ULONGEST hit_count = 0;
186 ULONGEST miss_count = 0;
187 };
188
189 /* Description of the remote protocol for a given architecture. */
190
191 struct packet_reg
192 {
193 long offset; /* Offset into G packet. */
194 long regnum; /* GDB's internal register number. */
195 LONGEST pnum; /* Remote protocol register number. */
196 int in_g_packet; /* Always part of G packet. */
197 /* long size in bytes; == register_size (target_gdbarch (), regnum);
198 at present. */
199 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
200 at present. */
201 };
202
203 struct remote_arch_state
204 {
205 explicit remote_arch_state (struct gdbarch *gdbarch);
206
207 /* Description of the remote protocol registers. */
208 long sizeof_g_packet;
209
210 /* Description of the remote protocol registers indexed by REGNUM
211 (making an array gdbarch_num_regs in size). */
212 std::unique_ptr<packet_reg[]> regs;
213
214 /* This is the size (in chars) of the first response to the ``g''
215 packet. It is used as a heuristic when determining the maximum
216 size of memory-read and memory-write packets. A target will
217 typically only reserve a buffer large enough to hold the ``g''
218 packet. The size does not include packet overhead (headers and
219 trailers). */
220 long actual_register_packet_size;
221
222 /* This is the maximum size (in chars) of a non read/write packet.
223 It is also used as a cap on the size of read/write packets. */
224 long remote_packet_size;
225 };
226
227 /* Description of the remote protocol state for the currently
228 connected target. This is per-target state, and independent of the
229 selected architecture. */
230
231 class remote_state
232 {
233 public:
234
235 remote_state ();
236 ~remote_state ();
237
238 /* Get the remote arch state for GDBARCH. */
239 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
240
241 public: /* data */
242
243 /* A buffer to use for incoming packets, and its current size. The
244 buffer is grown dynamically for larger incoming packets.
245 Outgoing packets may also be constructed in this buffer.
246 The size of the buffer is always at least REMOTE_PACKET_SIZE;
247 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
248 packets. */
249 gdb::char_vector buf;
250
251 /* True if we're going through initial connection setup (finding out
252 about the remote side's threads, relocating symbols, etc.). */
253 bool starting_up = false;
254
255 /* If we negotiated packet size explicitly (and thus can bypass
256 heuristics for the largest packet size that will not overflow
257 a buffer in the stub), this will be set to that packet size.
258 Otherwise zero, meaning to use the guessed size. */
259 long explicit_packet_size = 0;
260
261 /* True, if in no ack mode. That is, neither GDB nor the stub will
262 expect acks from each other. The connection is assumed to be
263 reliable. */
264 bool noack_mode = false;
265
266 /* True if we're connected in extended remote mode. */
267 bool extended = false;
268
269 /* True if we resumed the target and we're waiting for the target to
270 stop. In the mean time, we can't start another command/query.
271 The remote server wouldn't be ready to process it, so we'd
272 timeout waiting for a reply that would never come and eventually
273 we'd close the connection. This can happen in asynchronous mode
274 because we allow GDB commands while the target is running. */
275 bool waiting_for_stop_reply = false;
276
277 /* The status of the stub support for the various vCont actions. */
278 vCont_action_support supports_vCont;
279 /* Whether vCont support was probed already. This is a workaround
280 until packet_support is per-connection. */
281 bool supports_vCont_probed;
282
283 /* True if the user has pressed Ctrl-C, but the target hasn't
284 responded to that. */
285 bool ctrlc_pending_p = false;
286
287 /* True if we saw a Ctrl-C while reading or writing from/to the
288 remote descriptor. At that point it is not safe to send a remote
289 interrupt packet, so we instead remember we saw the Ctrl-C and
290 process it once we're done with sending/receiving the current
291 packet, which should be shortly. If however that takes too long,
292 and the user presses Ctrl-C again, we offer to disconnect. */
293 bool got_ctrlc_during_io = false;
294
295 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
296 remote_open knows that we don't have a file open when the program
297 starts. */
298 struct serial *remote_desc = nullptr;
299
300 /* These are the threads which we last sent to the remote system. The
301 TID member will be -1 for all or -2 for not sent yet. */
302 ptid_t general_thread = null_ptid;
303 ptid_t continue_thread = null_ptid;
304
305 /* This is the traceframe which we last selected on the remote system.
306 It will be -1 if no traceframe is selected. */
307 int remote_traceframe_number = -1;
308
309 char *last_pass_packet = nullptr;
310
311 /* The last QProgramSignals packet sent to the target. We bypass
312 sending a new program signals list down to the target if the new
313 packet is exactly the same as the last we sent. IOW, we only let
314 the target know about program signals list changes. */
315 char *last_program_signals_packet = nullptr;
316
317 gdb_signal last_sent_signal = GDB_SIGNAL_0;
318
319 bool last_sent_step = false;
320
321 /* The execution direction of the last resume we got. */
322 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
323
324 char *finished_object = nullptr;
325 char *finished_annex = nullptr;
326 ULONGEST finished_offset = 0;
327
328 /* Should we try the 'ThreadInfo' query packet?
329
330 This variable (NOT available to the user: auto-detect only!)
331 determines whether GDB will use the new, simpler "ThreadInfo"
332 query or the older, more complex syntax for thread queries.
333 This is an auto-detect variable (set to true at each connect,
334 and set to false when the target fails to recognize it). */
335 bool use_threadinfo_query = false;
336 bool use_threadextra_query = false;
337
338 threadref echo_nextthread {};
339 threadref nextthread {};
340 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
341
342 /* The state of remote notification. */
343 struct remote_notif_state *notif_state = nullptr;
344
345 /* The branch trace configuration. */
346 struct btrace_config btrace_config {};
347
348 /* The argument to the last "vFile:setfs:" packet we sent, used
349 to avoid sending repeated unnecessary "vFile:setfs:" packets.
350 Initialized to -1 to indicate that no "vFile:setfs:" packet
351 has yet been sent. */
352 int fs_pid = -1;
353
354 /* A readahead cache for vFile:pread. Often, reading a binary
355 involves a sequence of small reads. E.g., when parsing an ELF
356 file. A readahead cache helps mostly the case of remote
357 debugging on a connection with higher latency, due to the
358 request/reply nature of the RSP. We only cache data for a single
359 file descriptor at a time. */
360 struct readahead_cache readahead_cache;
361
362 /* The list of already fetched and acknowledged stop events. This
363 queue is used for notification Stop, and other notifications
364 don't need queue for their events, because the notification
365 events of Stop can't be consumed immediately, so that events
366 should be queued first, and be consumed by remote_wait_{ns,as}
367 one per time. Other notifications can consume their events
368 immediately, so queue is not needed for them. */
369 std::vector<stop_reply_up> stop_reply_queue;
370
371 /* Asynchronous signal handle registered as event loop source for
372 when we have pending events ready to be passed to the core. */
373 struct async_event_handler *remote_async_inferior_event_token = nullptr;
374
375 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
376 ``forever'' still use the normal timeout mechanism. This is
377 currently used by the ASYNC code to guarentee that target reads
378 during the initial connect always time-out. Once getpkt has been
379 modified to return a timeout indication and, in turn
380 remote_wait()/wait_for_inferior() have gained a timeout parameter
381 this can go away. */
382 int wait_forever_enabled_p = 1;
383
384 private:
385 /* Mapping of remote protocol data for each gdbarch. Usually there
386 is only one entry here, though we may see more with stubs that
387 support multi-process. */
388 std::unordered_map<struct gdbarch *, remote_arch_state>
389 m_arch_states;
390 };
391
392 static const target_info remote_target_info = {
393 "remote",
394 N_("Remote target using gdb-specific protocol"),
395 remote_doc
396 };
397
398 class remote_target : public process_stratum_target
399 {
400 public:
401 remote_target () = default;
402 ~remote_target () override;
403
404 const target_info &info () const override
405 { return remote_target_info; }
406
407 const char *connection_string () override;
408
409 thread_control_capabilities get_thread_control_capabilities () override
410 { return tc_schedlock; }
411
412 /* Open a remote connection. */
413 static void open (const char *, int);
414
415 void close () override;
416
417 void detach (inferior *, int) override;
418 void disconnect (const char *, int) override;
419
420 void commit_resumed () override;
421 void resume (ptid_t, int, enum gdb_signal) override;
422 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
423 bool has_pending_events () override;
424
425 void fetch_registers (struct regcache *, int) override;
426 void store_registers (struct regcache *, int) override;
427 void prepare_to_store (struct regcache *) override;
428
429 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
430
431 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
432 enum remove_bp_reason) override;
433
434
435 bool stopped_by_sw_breakpoint () override;
436 bool supports_stopped_by_sw_breakpoint () override;
437
438 bool stopped_by_hw_breakpoint () override;
439
440 bool supports_stopped_by_hw_breakpoint () override;
441
442 bool stopped_by_watchpoint () override;
443
444 bool stopped_data_address (CORE_ADDR *) override;
445
446 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
447
448 int can_use_hw_breakpoint (enum bptype, int, int) override;
449
450 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
451
452 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
453
454 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
455
456 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
457 struct expression *) override;
458
459 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
460 struct expression *) override;
461
462 void kill () override;
463
464 void load (const char *, int) override;
465
466 void mourn_inferior () override;
467
468 void pass_signals (gdb::array_view<const unsigned char>) override;
469
470 int set_syscall_catchpoint (int, bool, int,
471 gdb::array_view<const int>) override;
472
473 void program_signals (gdb::array_view<const unsigned char>) override;
474
475 bool thread_alive (ptid_t ptid) override;
476
477 const char *thread_name (struct thread_info *) override;
478
479 void update_thread_list () override;
480
481 std::string pid_to_str (ptid_t) override;
482
483 const char *extra_thread_info (struct thread_info *) override;
484
485 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
486
487 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
488 int handle_len,
489 inferior *inf) override;
490
491 gdb::byte_vector thread_info_to_thread_handle (struct thread_info *tp)
492 override;
493
494 void stop (ptid_t) override;
495
496 void interrupt () override;
497
498 void pass_ctrlc () override;
499
500 enum target_xfer_status xfer_partial (enum target_object object,
501 const char *annex,
502 gdb_byte *readbuf,
503 const gdb_byte *writebuf,
504 ULONGEST offset, ULONGEST len,
505 ULONGEST *xfered_len) override;
506
507 ULONGEST get_memory_xfer_limit () override;
508
509 void rcmd (const char *command, struct ui_file *output) override;
510
511 char *pid_to_exec_file (int pid) override;
512
513 void log_command (const char *cmd) override
514 {
515 serial_log_command (this, cmd);
516 }
517
518 CORE_ADDR get_thread_local_address (ptid_t ptid,
519 CORE_ADDR load_module_addr,
520 CORE_ADDR offset) override;
521
522 bool can_execute_reverse () override;
523
524 std::vector<mem_region> memory_map () override;
525
526 void flash_erase (ULONGEST address, LONGEST length) override;
527
528 void flash_done () override;
529
530 const struct target_desc *read_description () override;
531
532 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
533 const gdb_byte *pattern, ULONGEST pattern_len,
534 CORE_ADDR *found_addrp) override;
535
536 bool can_async_p () override;
537
538 bool is_async_p () override;
539
540 void async (int) override;
541
542 int async_wait_fd () override;
543
544 void thread_events (int) override;
545
546 int can_do_single_step () override;
547
548 void terminal_inferior () override;
549
550 void terminal_ours () override;
551
552 bool supports_non_stop () override;
553
554 bool supports_multi_process () override;
555
556 bool supports_disable_randomization () override;
557
558 bool filesystem_is_local () override;
559
560
561 int fileio_open (struct inferior *inf, const char *filename,
562 int flags, int mode, int warn_if_slow,
563 int *target_errno) override;
564
565 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
566 ULONGEST offset, int *target_errno) override;
567
568 int fileio_pread (int fd, gdb_byte *read_buf, int len,
569 ULONGEST offset, int *target_errno) override;
570
571 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
572
573 int fileio_close (int fd, int *target_errno) override;
574
575 int fileio_unlink (struct inferior *inf,
576 const char *filename,
577 int *target_errno) override;
578
579 gdb::optional<std::string>
580 fileio_readlink (struct inferior *inf,
581 const char *filename,
582 int *target_errno) override;
583
584 bool supports_enable_disable_tracepoint () override;
585
586 bool supports_string_tracing () override;
587
588 bool supports_evaluation_of_breakpoint_conditions () override;
589
590 bool can_run_breakpoint_commands () override;
591
592 void trace_init () override;
593
594 void download_tracepoint (struct bp_location *location) override;
595
596 bool can_download_tracepoint () override;
597
598 void download_trace_state_variable (const trace_state_variable &tsv) override;
599
600 void enable_tracepoint (struct bp_location *location) override;
601
602 void disable_tracepoint (struct bp_location *location) override;
603
604 void trace_set_readonly_regions () override;
605
606 void trace_start () override;
607
608 int get_trace_status (struct trace_status *ts) override;
609
610 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
611 override;
612
613 void trace_stop () override;
614
615 int trace_find (enum trace_find_type type, int num,
616 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
617
618 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
619
620 int save_trace_data (const char *filename) override;
621
622 int upload_tracepoints (struct uploaded_tp **utpp) override;
623
624 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
625
626 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
627
628 int get_min_fast_tracepoint_insn_len () override;
629
630 void set_disconnected_tracing (int val) override;
631
632 void set_circular_trace_buffer (int val) override;
633
634 void set_trace_buffer_size (LONGEST val) override;
635
636 bool set_trace_notes (const char *user, const char *notes,
637 const char *stopnotes) override;
638
639 int core_of_thread (ptid_t ptid) override;
640
641 int verify_memory (const gdb_byte *data,
642 CORE_ADDR memaddr, ULONGEST size) override;
643
644
645 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
646
647 void set_permissions () override;
648
649 bool static_tracepoint_marker_at (CORE_ADDR,
650 struct static_tracepoint_marker *marker)
651 override;
652
653 std::vector<static_tracepoint_marker>
654 static_tracepoint_markers_by_strid (const char *id) override;
655
656 traceframe_info_up traceframe_info () override;
657
658 bool use_agent (bool use) override;
659 bool can_use_agent () override;
660
661 struct btrace_target_info *enable_btrace (ptid_t ptid,
662 const struct btrace_config *conf) override;
663
664 void disable_btrace (struct btrace_target_info *tinfo) override;
665
666 void teardown_btrace (struct btrace_target_info *tinfo) override;
667
668 enum btrace_error read_btrace (struct btrace_data *data,
669 struct btrace_target_info *btinfo,
670 enum btrace_read_type type) override;
671
672 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
673 bool augmented_libraries_svr4_read () override;
674 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
675 void follow_exec (inferior *, ptid_t, const char *) override;
676 int insert_fork_catchpoint (int) override;
677 int remove_fork_catchpoint (int) override;
678 int insert_vfork_catchpoint (int) override;
679 int remove_vfork_catchpoint (int) override;
680 int insert_exec_catchpoint (int) override;
681 int remove_exec_catchpoint (int) override;
682 enum exec_direction_kind execution_direction () override;
683
684 bool supports_memory_tagging () override;
685
686 bool fetch_memtags (CORE_ADDR address, size_t len,
687 gdb::byte_vector &tags, int type) override;
688
689 bool store_memtags (CORE_ADDR address, size_t len,
690 const gdb::byte_vector &tags, int type) override;
691
692 public: /* Remote specific methods. */
693
694 void remote_download_command_source (int num, ULONGEST addr,
695 struct command_line *cmds);
696
697 void remote_file_put (const char *local_file, const char *remote_file,
698 int from_tty);
699 void remote_file_get (const char *remote_file, const char *local_file,
700 int from_tty);
701 void remote_file_delete (const char *remote_file, int from_tty);
702
703 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
704 ULONGEST offset, int *remote_errno);
705 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
706 ULONGEST offset, int *remote_errno);
707 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
708 ULONGEST offset, int *remote_errno);
709
710 int remote_hostio_send_command (int command_bytes, int which_packet,
711 int *remote_errno, const char **attachment,
712 int *attachment_len);
713 int remote_hostio_set_filesystem (struct inferior *inf,
714 int *remote_errno);
715 /* We should get rid of this and use fileio_open directly. */
716 int remote_hostio_open (struct inferior *inf, const char *filename,
717 int flags, int mode, int warn_if_slow,
718 int *remote_errno);
719 int remote_hostio_close (int fd, int *remote_errno);
720
721 int remote_hostio_unlink (inferior *inf, const char *filename,
722 int *remote_errno);
723
724 struct remote_state *get_remote_state ();
725
726 long get_remote_packet_size (void);
727 long get_memory_packet_size (struct memory_packet_config *config);
728
729 long get_memory_write_packet_size ();
730 long get_memory_read_packet_size ();
731
732 char *append_pending_thread_resumptions (char *p, char *endp,
733 ptid_t ptid);
734 static void open_1 (const char *name, int from_tty, int extended_p);
735 void start_remote (int from_tty, int extended_p);
736 void remote_detach_1 (struct inferior *inf, int from_tty);
737
738 char *append_resumption (char *p, char *endp,
739 ptid_t ptid, int step, gdb_signal siggnal);
740 int remote_resume_with_vcont (ptid_t ptid, int step,
741 gdb_signal siggnal);
742
743 thread_info *add_current_inferior_and_thread (const char *wait_status);
744
745 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
746 target_wait_flags options);
747 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
748 target_wait_flags options);
749
750 ptid_t process_stop_reply (struct stop_reply *stop_reply,
751 target_waitstatus *status);
752
753 ptid_t select_thread_for_ambiguous_stop_reply
754 (const struct target_waitstatus &status);
755
756 void remote_notice_new_inferior (ptid_t currthread, bool executing);
757
758 void print_one_stopped_thread (thread_info *thread);
759 void process_initial_stop_replies (int from_tty);
760
761 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
762 bool silent_p);
763
764 void btrace_sync_conf (const btrace_config *conf);
765
766 void remote_btrace_maybe_reopen ();
767
768 void remove_new_fork_children (threads_listing_context *context);
769 void kill_new_fork_children (inferior *inf);
770 void discard_pending_stop_replies (struct inferior *inf);
771 int stop_reply_queue_length ();
772
773 void check_pending_events_prevent_wildcard_vcont
774 (bool *may_global_wildcard_vcont);
775
776 void discard_pending_stop_replies_in_queue ();
777 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
778 struct stop_reply *queued_stop_reply (ptid_t ptid);
779 int peek_stop_reply (ptid_t ptid);
780 void remote_parse_stop_reply (const char *buf, stop_reply *event);
781
782 void remote_stop_ns (ptid_t ptid);
783 void remote_interrupt_as ();
784 void remote_interrupt_ns ();
785
786 char *remote_get_noisy_reply ();
787 int remote_query_attached (int pid);
788 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
789 int try_open_exec);
790
791 ptid_t remote_current_thread (ptid_t oldpid);
792 ptid_t get_current_thread (const char *wait_status);
793
794 void set_thread (ptid_t ptid, int gen);
795 void set_general_thread (ptid_t ptid);
796 void set_continue_thread (ptid_t ptid);
797 void set_general_process ();
798
799 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
800
801 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
802 gdb_ext_thread_info *info);
803 int remote_get_threadinfo (threadref *threadid, int fieldset,
804 gdb_ext_thread_info *info);
805
806 int parse_threadlist_response (const char *pkt, int result_limit,
807 threadref *original_echo,
808 threadref *resultlist,
809 int *doneflag);
810 int remote_get_threadlist (int startflag, threadref *nextthread,
811 int result_limit, int *done, int *result_count,
812 threadref *threadlist);
813
814 int remote_threadlist_iterator (rmt_thread_action stepfunction,
815 void *context, int looplimit);
816
817 int remote_get_threads_with_ql (threads_listing_context *context);
818 int remote_get_threads_with_qxfer (threads_listing_context *context);
819 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
820
821 void extended_remote_restart ();
822
823 void get_offsets ();
824
825 void remote_check_symbols ();
826
827 void remote_supported_packet (const struct protocol_feature *feature,
828 enum packet_support support,
829 const char *argument);
830
831 void remote_query_supported ();
832
833 void remote_packet_size (const protocol_feature *feature,
834 packet_support support, const char *value);
835
836 void remote_serial_quit_handler ();
837
838 void remote_detach_pid (int pid);
839
840 void remote_vcont_probe ();
841
842 void remote_resume_with_hc (ptid_t ptid, int step,
843 gdb_signal siggnal);
844
845 void send_interrupt_sequence ();
846 void interrupt_query ();
847
848 void remote_notif_get_pending_events (notif_client *nc);
849
850 int fetch_register_using_p (struct regcache *regcache,
851 packet_reg *reg);
852 int send_g_packet ();
853 void process_g_packet (struct regcache *regcache);
854 void fetch_registers_using_g (struct regcache *regcache);
855 int store_register_using_P (const struct regcache *regcache,
856 packet_reg *reg);
857 void store_registers_using_G (const struct regcache *regcache);
858
859 void set_remote_traceframe ();
860
861 void check_binary_download (CORE_ADDR addr);
862
863 target_xfer_status remote_write_bytes_aux (const char *header,
864 CORE_ADDR memaddr,
865 const gdb_byte *myaddr,
866 ULONGEST len_units,
867 int unit_size,
868 ULONGEST *xfered_len_units,
869 char packet_format,
870 int use_length);
871
872 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
873 const gdb_byte *myaddr, ULONGEST len,
874 int unit_size, ULONGEST *xfered_len);
875
876 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
877 ULONGEST len_units,
878 int unit_size, ULONGEST *xfered_len_units);
879
880 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
881 ULONGEST memaddr,
882 ULONGEST len,
883 int unit_size,
884 ULONGEST *xfered_len);
885
886 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
887 gdb_byte *myaddr, ULONGEST len,
888 int unit_size,
889 ULONGEST *xfered_len);
890
891 packet_result remote_send_printf (const char *format, ...)
892 ATTRIBUTE_PRINTF (2, 3);
893
894 target_xfer_status remote_flash_write (ULONGEST address,
895 ULONGEST length, ULONGEST *xfered_len,
896 const gdb_byte *data);
897
898 int readchar (int timeout);
899
900 void remote_serial_write (const char *str, int len);
901
902 int putpkt (const char *buf);
903 int putpkt_binary (const char *buf, int cnt);
904
905 int putpkt (const gdb::char_vector &buf)
906 {
907 return putpkt (buf.data ());
908 }
909
910 void skip_frame ();
911 long read_frame (gdb::char_vector *buf_p);
912 void getpkt (gdb::char_vector *buf, int forever);
913 int getpkt_or_notif_sane_1 (gdb::char_vector *buf, int forever,
914 int expecting_notif, int *is_notif);
915 int getpkt_sane (gdb::char_vector *buf, int forever);
916 int getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
917 int *is_notif);
918 int remote_vkill (int pid);
919 void remote_kill_k ();
920
921 void extended_remote_disable_randomization (int val);
922 int extended_remote_run (const std::string &args);
923
924 void send_environment_packet (const char *action,
925 const char *packet,
926 const char *value);
927
928 void extended_remote_environment_support ();
929 void extended_remote_set_inferior_cwd ();
930
931 target_xfer_status remote_write_qxfer (const char *object_name,
932 const char *annex,
933 const gdb_byte *writebuf,
934 ULONGEST offset, LONGEST len,
935 ULONGEST *xfered_len,
936 struct packet_config *packet);
937
938 target_xfer_status remote_read_qxfer (const char *object_name,
939 const char *annex,
940 gdb_byte *readbuf, ULONGEST offset,
941 LONGEST len,
942 ULONGEST *xfered_len,
943 struct packet_config *packet);
944
945 void push_stop_reply (struct stop_reply *new_event);
946
947 bool vcont_r_supported ();
948
949 private:
950
951 bool start_remote_1 (int from_tty, int extended_p);
952
953 /* The remote state. Don't reference this directly. Use the
954 get_remote_state method instead. */
955 remote_state m_remote_state;
956 };
957
958 static const target_info extended_remote_target_info = {
959 "extended-remote",
960 N_("Extended remote target using gdb-specific protocol"),
961 remote_doc
962 };
963
964 /* Set up the extended remote target by extending the standard remote
965 target and adding to it. */
966
967 class extended_remote_target final : public remote_target
968 {
969 public:
970 const target_info &info () const override
971 { return extended_remote_target_info; }
972
973 /* Open an extended-remote connection. */
974 static void open (const char *, int);
975
976 bool can_create_inferior () override { return true; }
977 void create_inferior (const char *, const std::string &,
978 char **, int) override;
979
980 void detach (inferior *, int) override;
981
982 bool can_attach () override { return true; }
983 void attach (const char *, int) override;
984
985 void post_attach (int) override;
986 bool supports_disable_randomization () override;
987 };
988
989 struct stop_reply : public notif_event
990 {
991 ~stop_reply ();
992
993 /* The identifier of the thread about this event */
994 ptid_t ptid;
995
996 /* The remote state this event is associated with. When the remote
997 connection, represented by a remote_state object, is closed,
998 all the associated stop_reply events should be released. */
999 struct remote_state *rs;
1000
1001 struct target_waitstatus ws;
1002
1003 /* The architecture associated with the expedited registers. */
1004 gdbarch *arch;
1005
1006 /* Expedited registers. This makes remote debugging a bit more
1007 efficient for those targets that provide critical registers as
1008 part of their normal status mechanism (as another roundtrip to
1009 fetch them is avoided). */
1010 std::vector<cached_reg_t> regcache;
1011
1012 enum target_stop_reason stop_reason;
1013
1014 CORE_ADDR watch_data_address;
1015
1016 int core;
1017 };
1018
1019 /* See remote.h. */
1020
1021 bool
1022 is_remote_target (process_stratum_target *target)
1023 {
1024 remote_target *rt = dynamic_cast<remote_target *> (target);
1025 return rt != nullptr;
1026 }
1027
1028 /* Per-program-space data key. */
1029 static const struct program_space_key<char, gdb::xfree_deleter<char>>
1030 remote_pspace_data;
1031
1032 /* The variable registered as the control variable used by the
1033 remote exec-file commands. While the remote exec-file setting is
1034 per-program-space, the set/show machinery uses this as the
1035 location of the remote exec-file value. */
1036 static std::string remote_exec_file_var;
1037
1038 /* The size to align memory write packets, when practical. The protocol
1039 does not guarantee any alignment, and gdb will generate short
1040 writes and unaligned writes, but even as a best-effort attempt this
1041 can improve bulk transfers. For instance, if a write is misaligned
1042 relative to the target's data bus, the stub may need to make an extra
1043 round trip fetching data from the target. This doesn't make a
1044 huge difference, but it's easy to do, so we try to be helpful.
1045
1046 The alignment chosen is arbitrary; usually data bus width is
1047 important here, not the possibly larger cache line size. */
1048 enum { REMOTE_ALIGN_WRITES = 16 };
1049
1050 /* Prototypes for local functions. */
1051
1052 static int hexnumlen (ULONGEST num);
1053
1054 static int stubhex (int ch);
1055
1056 static int hexnumstr (char *, ULONGEST);
1057
1058 static int hexnumnstr (char *, ULONGEST, int);
1059
1060 static CORE_ADDR remote_address_masked (CORE_ADDR);
1061
1062 static int stub_unpack_int (const char *buff, int fieldlength);
1063
1064 struct packet_config;
1065
1066 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1067 int from_tty,
1068 struct cmd_list_element *c,
1069 const char *value);
1070
1071 static ptid_t read_ptid (const char *buf, const char **obuf);
1072
1073 static void remote_async_inferior_event_handler (gdb_client_data);
1074
1075 static bool remote_read_description_p (struct target_ops *target);
1076
1077 static void remote_console_output (const char *msg);
1078
1079 static void remote_btrace_reset (remote_state *rs);
1080
1081 static void remote_unpush_and_throw (remote_target *target);
1082
1083 /* For "remote". */
1084
1085 static struct cmd_list_element *remote_cmdlist;
1086
1087 /* For "set remote" and "show remote". */
1088
1089 static struct cmd_list_element *remote_set_cmdlist;
1090 static struct cmd_list_element *remote_show_cmdlist;
1091
1092 /* Controls whether GDB is willing to use range stepping. */
1093
1094 static bool use_range_stepping = true;
1095
1096 /* From the remote target's point of view, each thread is in one of these three
1097 states. */
1098 enum class resume_state
1099 {
1100 /* Not resumed - we haven't been asked to resume this thread. */
1101 NOT_RESUMED,
1102
1103 /* We have been asked to resume this thread, but haven't sent a vCont action
1104 for it yet. We'll need to consider it next time commit_resume is
1105 called. */
1106 RESUMED_PENDING_VCONT,
1107
1108 /* We have been asked to resume this thread, and we have sent a vCont action
1109 for it. */
1110 RESUMED,
1111 };
1112
1113 /* Information about a thread's pending vCont-resume. Used when a thread is in
1114 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1115 stores this information which is then picked up by
1116 remote_target::commit_resume to know which is the proper action for this
1117 thread to include in the vCont packet. */
1118 struct resumed_pending_vcont_info
1119 {
1120 /* True if the last resume call for this thread was a step request, false
1121 if a continue request. */
1122 bool step;
1123
1124 /* The signal specified in the last resume call for this thread. */
1125 gdb_signal sig;
1126 };
1127
1128 /* Private data that we'll store in (struct thread_info)->priv. */
1129 struct remote_thread_info : public private_thread_info
1130 {
1131 std::string extra;
1132 std::string name;
1133 int core = -1;
1134
1135 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1136 sequence of bytes. */
1137 gdb::byte_vector thread_handle;
1138
1139 /* Whether the target stopped for a breakpoint/watchpoint. */
1140 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1141
1142 /* This is set to the data address of the access causing the target
1143 to stop for a watchpoint. */
1144 CORE_ADDR watch_data_address = 0;
1145
1146 /* Get the thread's resume state. */
1147 enum resume_state get_resume_state () const
1148 {
1149 return m_resume_state;
1150 }
1151
1152 /* Put the thread in the NOT_RESUMED state. */
1153 void set_not_resumed ()
1154 {
1155 m_resume_state = resume_state::NOT_RESUMED;
1156 }
1157
1158 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1159 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1160 {
1161 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1162 m_resumed_pending_vcont_info.step = step;
1163 m_resumed_pending_vcont_info.sig = sig;
1164 }
1165
1166 /* Get the information this thread's pending vCont-resumption.
1167
1168 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1169 state. */
1170 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1171 {
1172 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1173
1174 return m_resumed_pending_vcont_info;
1175 }
1176
1177 /* Put the thread in the VCONT_RESUMED state. */
1178 void set_resumed ()
1179 {
1180 m_resume_state = resume_state::RESUMED;
1181 }
1182
1183 private:
1184 /* Resume state for this thread. This is used to implement vCont action
1185 coalescing (only when the target operates in non-stop mode).
1186
1187 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1188 which notes that this thread must be considered in the next commit_resume
1189 call.
1190
1191 remote_target::commit_resume sends a vCont packet with actions for the
1192 threads in the RESUMED_PENDING_VCONT state and moves them to the
1193 VCONT_RESUMED state.
1194
1195 When reporting a stop to the core for a thread, that thread is moved back
1196 to the NOT_RESUMED state. */
1197 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1198
1199 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1200 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1201 };
1202
1203 remote_state::remote_state ()
1204 : buf (400)
1205 {
1206 }
1207
1208 remote_state::~remote_state ()
1209 {
1210 xfree (this->last_pass_packet);
1211 xfree (this->last_program_signals_packet);
1212 xfree (this->finished_object);
1213 xfree (this->finished_annex);
1214 }
1215
1216 /* Utility: generate error from an incoming stub packet. */
1217 static void
1218 trace_error (char *buf)
1219 {
1220 if (*buf++ != 'E')
1221 return; /* not an error msg */
1222 switch (*buf)
1223 {
1224 case '1': /* malformed packet error */
1225 if (*++buf == '0') /* general case: */
1226 error (_("remote.c: error in outgoing packet."));
1227 else
1228 error (_("remote.c: error in outgoing packet at field #%ld."),
1229 strtol (buf, NULL, 16));
1230 default:
1231 error (_("Target returns error code '%s'."), buf);
1232 }
1233 }
1234
1235 /* Utility: wait for reply from stub, while accepting "O" packets. */
1236
1237 char *
1238 remote_target::remote_get_noisy_reply ()
1239 {
1240 struct remote_state *rs = get_remote_state ();
1241
1242 do /* Loop on reply from remote stub. */
1243 {
1244 char *buf;
1245
1246 QUIT; /* Allow user to bail out with ^C. */
1247 getpkt (&rs->buf, 0);
1248 buf = rs->buf.data ();
1249 if (buf[0] == 'E')
1250 trace_error (buf);
1251 else if (startswith (buf, "qRelocInsn:"))
1252 {
1253 ULONGEST ul;
1254 CORE_ADDR from, to, org_to;
1255 const char *p, *pp;
1256 int adjusted_size = 0;
1257 int relocated = 0;
1258
1259 p = buf + strlen ("qRelocInsn:");
1260 pp = unpack_varlen_hex (p, &ul);
1261 if (*pp != ';')
1262 error (_("invalid qRelocInsn packet: %s"), buf);
1263 from = ul;
1264
1265 p = pp + 1;
1266 unpack_varlen_hex (p, &ul);
1267 to = ul;
1268
1269 org_to = to;
1270
1271 try
1272 {
1273 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
1274 relocated = 1;
1275 }
1276 catch (const gdb_exception &ex)
1277 {
1278 if (ex.error == MEMORY_ERROR)
1279 {
1280 /* Propagate memory errors silently back to the
1281 target. The stub may have limited the range of
1282 addresses we can write to, for example. */
1283 }
1284 else
1285 {
1286 /* Something unexpectedly bad happened. Be verbose
1287 so we can tell what, and propagate the error back
1288 to the stub, so it doesn't get stuck waiting for
1289 a response. */
1290 exception_fprintf (gdb_stderr, ex,
1291 _("warning: relocating instruction: "));
1292 }
1293 putpkt ("E01");
1294 }
1295
1296 if (relocated)
1297 {
1298 adjusted_size = to - org_to;
1299
1300 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1301 putpkt (buf);
1302 }
1303 }
1304 else if (buf[0] == 'O' && buf[1] != 'K')
1305 remote_console_output (buf + 1); /* 'O' message from stub */
1306 else
1307 return buf; /* Here's the actual reply. */
1308 }
1309 while (1);
1310 }
1311
1312 struct remote_arch_state *
1313 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1314 {
1315 remote_arch_state *rsa;
1316
1317 auto it = this->m_arch_states.find (gdbarch);
1318 if (it == this->m_arch_states.end ())
1319 {
1320 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1321 std::forward_as_tuple (gdbarch),
1322 std::forward_as_tuple (gdbarch));
1323 rsa = &p.first->second;
1324
1325 /* Make sure that the packet buffer is plenty big enough for
1326 this architecture. */
1327 if (this->buf.size () < rsa->remote_packet_size)
1328 this->buf.resize (2 * rsa->remote_packet_size);
1329 }
1330 else
1331 rsa = &it->second;
1332
1333 return rsa;
1334 }
1335
1336 /* Fetch the global remote target state. */
1337
1338 remote_state *
1339 remote_target::get_remote_state ()
1340 {
1341 /* Make sure that the remote architecture state has been
1342 initialized, because doing so might reallocate rs->buf. Any
1343 function which calls getpkt also needs to be mindful of changes
1344 to rs->buf, but this call limits the number of places which run
1345 into trouble. */
1346 m_remote_state.get_remote_arch_state (target_gdbarch ());
1347
1348 return &m_remote_state;
1349 }
1350
1351 /* Fetch the remote exec-file from the current program space. */
1352
1353 static const char *
1354 get_remote_exec_file (void)
1355 {
1356 char *remote_exec_file;
1357
1358 remote_exec_file = remote_pspace_data.get (current_program_space);
1359 if (remote_exec_file == NULL)
1360 return "";
1361
1362 return remote_exec_file;
1363 }
1364
1365 /* Set the remote exec file for PSPACE. */
1366
1367 static void
1368 set_pspace_remote_exec_file (struct program_space *pspace,
1369 const char *remote_exec_file)
1370 {
1371 char *old_file = remote_pspace_data.get (pspace);
1372
1373 xfree (old_file);
1374 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1375 }
1376
1377 /* The "set/show remote exec-file" set command hook. */
1378
1379 static void
1380 set_remote_exec_file (const char *ignored, int from_tty,
1381 struct cmd_list_element *c)
1382 {
1383 set_pspace_remote_exec_file (current_program_space,
1384 remote_exec_file_var.c_str ());
1385 }
1386
1387 /* The "set/show remote exec-file" show command hook. */
1388
1389 static void
1390 show_remote_exec_file (struct ui_file *file, int from_tty,
1391 struct cmd_list_element *cmd, const char *value)
1392 {
1393 fprintf_filtered (file, "%s\n", get_remote_exec_file ());
1394 }
1395
1396 static int
1397 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1398 {
1399 int regnum, num_remote_regs, offset;
1400 struct packet_reg **remote_regs;
1401
1402 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1403 {
1404 struct packet_reg *r = &regs[regnum];
1405
1406 if (register_size (gdbarch, regnum) == 0)
1407 /* Do not try to fetch zero-sized (placeholder) registers. */
1408 r->pnum = -1;
1409 else
1410 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1411
1412 r->regnum = regnum;
1413 }
1414
1415 /* Define the g/G packet format as the contents of each register
1416 with a remote protocol number, in order of ascending protocol
1417 number. */
1418
1419 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1420 for (num_remote_regs = 0, regnum = 0;
1421 regnum < gdbarch_num_regs (gdbarch);
1422 regnum++)
1423 if (regs[regnum].pnum != -1)
1424 remote_regs[num_remote_regs++] = &regs[regnum];
1425
1426 std::sort (remote_regs, remote_regs + num_remote_regs,
1427 [] (const packet_reg *a, const packet_reg *b)
1428 { return a->pnum < b->pnum; });
1429
1430 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1431 {
1432 remote_regs[regnum]->in_g_packet = 1;
1433 remote_regs[regnum]->offset = offset;
1434 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1435 }
1436
1437 return offset;
1438 }
1439
1440 /* Given the architecture described by GDBARCH, return the remote
1441 protocol register's number and the register's offset in the g/G
1442 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1443 If the target does not have a mapping for REGNUM, return false,
1444 otherwise, return true. */
1445
1446 int
1447 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1448 int *pnum, int *poffset)
1449 {
1450 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1451
1452 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1453
1454 map_regcache_remote_table (gdbarch, regs.data ());
1455
1456 *pnum = regs[regnum].pnum;
1457 *poffset = regs[regnum].offset;
1458
1459 return *pnum != -1;
1460 }
1461
1462 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1463 {
1464 /* Use the architecture to build a regnum<->pnum table, which will be
1465 1:1 unless a feature set specifies otherwise. */
1466 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1467
1468 /* Record the maximum possible size of the g packet - it may turn out
1469 to be smaller. */
1470 this->sizeof_g_packet
1471 = map_regcache_remote_table (gdbarch, this->regs.get ());
1472
1473 /* Default maximum number of characters in a packet body. Many
1474 remote stubs have a hardwired buffer size of 400 bytes
1475 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1476 as the maximum packet-size to ensure that the packet and an extra
1477 NUL character can always fit in the buffer. This stops GDB
1478 trashing stubs that try to squeeze an extra NUL into what is
1479 already a full buffer (As of 1999-12-04 that was most stubs). */
1480 this->remote_packet_size = 400 - 1;
1481
1482 /* This one is filled in when a ``g'' packet is received. */
1483 this->actual_register_packet_size = 0;
1484
1485 /* Should rsa->sizeof_g_packet needs more space than the
1486 default, adjust the size accordingly. Remember that each byte is
1487 encoded as two characters. 32 is the overhead for the packet
1488 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1489 (``$NN:G...#NN'') is a better guess, the below has been padded a
1490 little. */
1491 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1492 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1493 }
1494
1495 /* Get a pointer to the current remote target. If not connected to a
1496 remote target, return NULL. */
1497
1498 static remote_target *
1499 get_current_remote_target ()
1500 {
1501 target_ops *proc_target = current_inferior ()->process_target ();
1502 return dynamic_cast<remote_target *> (proc_target);
1503 }
1504
1505 /* Return the current allowed size of a remote packet. This is
1506 inferred from the current architecture, and should be used to
1507 limit the length of outgoing packets. */
1508 long
1509 remote_target::get_remote_packet_size ()
1510 {
1511 struct remote_state *rs = get_remote_state ();
1512 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1513
1514 if (rs->explicit_packet_size)
1515 return rs->explicit_packet_size;
1516
1517 return rsa->remote_packet_size;
1518 }
1519
1520 static struct packet_reg *
1521 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1522 long regnum)
1523 {
1524 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1525 return NULL;
1526 else
1527 {
1528 struct packet_reg *r = &rsa->regs[regnum];
1529
1530 gdb_assert (r->regnum == regnum);
1531 return r;
1532 }
1533 }
1534
1535 static struct packet_reg *
1536 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1537 LONGEST pnum)
1538 {
1539 int i;
1540
1541 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1542 {
1543 struct packet_reg *r = &rsa->regs[i];
1544
1545 if (r->pnum == pnum)
1546 return r;
1547 }
1548 return NULL;
1549 }
1550
1551 /* Allow the user to specify what sequence to send to the remote
1552 when he requests a program interruption: Although ^C is usually
1553 what remote systems expect (this is the default, here), it is
1554 sometimes preferable to send a break. On other systems such
1555 as the Linux kernel, a break followed by g, which is Magic SysRq g
1556 is required in order to interrupt the execution. */
1557 const char interrupt_sequence_control_c[] = "Ctrl-C";
1558 const char interrupt_sequence_break[] = "BREAK";
1559 const char interrupt_sequence_break_g[] = "BREAK-g";
1560 static const char *const interrupt_sequence_modes[] =
1561 {
1562 interrupt_sequence_control_c,
1563 interrupt_sequence_break,
1564 interrupt_sequence_break_g,
1565 NULL
1566 };
1567 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1568
1569 static void
1570 show_interrupt_sequence (struct ui_file *file, int from_tty,
1571 struct cmd_list_element *c,
1572 const char *value)
1573 {
1574 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1575 fprintf_filtered (file,
1576 _("Send the ASCII ETX character (Ctrl-c) "
1577 "to the remote target to interrupt the "
1578 "execution of the program.\n"));
1579 else if (interrupt_sequence_mode == interrupt_sequence_break)
1580 fprintf_filtered (file,
1581 _("send a break signal to the remote target "
1582 "to interrupt the execution of the program.\n"));
1583 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1584 fprintf_filtered (file,
1585 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1586 "the remote target to interrupt the execution "
1587 "of Linux kernel.\n"));
1588 else
1589 internal_error (__FILE__, __LINE__,
1590 _("Invalid value for interrupt_sequence_mode: %s."),
1591 interrupt_sequence_mode);
1592 }
1593
1594 /* This boolean variable specifies whether interrupt_sequence is sent
1595 to the remote target when gdb connects to it.
1596 This is mostly needed when you debug the Linux kernel: The Linux kernel
1597 expects BREAK g which is Magic SysRq g for connecting gdb. */
1598 static bool interrupt_on_connect = false;
1599
1600 /* This variable is used to implement the "set/show remotebreak" commands.
1601 Since these commands are now deprecated in favor of "set/show remote
1602 interrupt-sequence", it no longer has any effect on the code. */
1603 static bool remote_break;
1604
1605 static void
1606 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1607 {
1608 if (remote_break)
1609 interrupt_sequence_mode = interrupt_sequence_break;
1610 else
1611 interrupt_sequence_mode = interrupt_sequence_control_c;
1612 }
1613
1614 static void
1615 show_remotebreak (struct ui_file *file, int from_tty,
1616 struct cmd_list_element *c,
1617 const char *value)
1618 {
1619 }
1620
1621 /* This variable sets the number of bits in an address that are to be
1622 sent in a memory ("M" or "m") packet. Normally, after stripping
1623 leading zeros, the entire address would be sent. This variable
1624 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1625 initial implementation of remote.c restricted the address sent in
1626 memory packets to ``host::sizeof long'' bytes - (typically 32
1627 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1628 address was never sent. Since fixing this bug may cause a break in
1629 some remote targets this variable is principally provided to
1630 facilitate backward compatibility. */
1631
1632 static unsigned int remote_address_size;
1633
1634 \f
1635 /* User configurable variables for the number of characters in a
1636 memory read/write packet. MIN (rsa->remote_packet_size,
1637 rsa->sizeof_g_packet) is the default. Some targets need smaller
1638 values (fifo overruns, et.al.) and some users need larger values
1639 (speed up transfers). The variables ``preferred_*'' (the user
1640 request), ``current_*'' (what was actually set) and ``forced_*''
1641 (Positive - a soft limit, negative - a hard limit). */
1642
1643 struct memory_packet_config
1644 {
1645 const char *name;
1646 long size;
1647 int fixed_p;
1648 };
1649
1650 /* The default max memory-write-packet-size, when the setting is
1651 "fixed". The 16k is historical. (It came from older GDB's using
1652 alloca for buffers and the knowledge (folklore?) that some hosts
1653 don't cope very well with large alloca calls.) */
1654 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1655
1656 /* The minimum remote packet size for memory transfers. Ensures we
1657 can write at least one byte. */
1658 #define MIN_MEMORY_PACKET_SIZE 20
1659
1660 /* Get the memory packet size, assuming it is fixed. */
1661
1662 static long
1663 get_fixed_memory_packet_size (struct memory_packet_config *config)
1664 {
1665 gdb_assert (config->fixed_p);
1666
1667 if (config->size <= 0)
1668 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1669 else
1670 return config->size;
1671 }
1672
1673 /* Compute the current size of a read/write packet. Since this makes
1674 use of ``actual_register_packet_size'' the computation is dynamic. */
1675
1676 long
1677 remote_target::get_memory_packet_size (struct memory_packet_config *config)
1678 {
1679 struct remote_state *rs = get_remote_state ();
1680 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1681
1682 long what_they_get;
1683 if (config->fixed_p)
1684 what_they_get = get_fixed_memory_packet_size (config);
1685 else
1686 {
1687 what_they_get = get_remote_packet_size ();
1688 /* Limit the packet to the size specified by the user. */
1689 if (config->size > 0
1690 && what_they_get > config->size)
1691 what_they_get = config->size;
1692
1693 /* Limit it to the size of the targets ``g'' response unless we have
1694 permission from the stub to use a larger packet size. */
1695 if (rs->explicit_packet_size == 0
1696 && rsa->actual_register_packet_size > 0
1697 && what_they_get > rsa->actual_register_packet_size)
1698 what_they_get = rsa->actual_register_packet_size;
1699 }
1700 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1701 what_they_get = MIN_MEMORY_PACKET_SIZE;
1702
1703 /* Make sure there is room in the global buffer for this packet
1704 (including its trailing NUL byte). */
1705 if (rs->buf.size () < what_they_get + 1)
1706 rs->buf.resize (2 * what_they_get);
1707
1708 return what_they_get;
1709 }
1710
1711 /* Update the size of a read/write packet. If they user wants
1712 something really big then do a sanity check. */
1713
1714 static void
1715 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1716 {
1717 int fixed_p = config->fixed_p;
1718 long size = config->size;
1719
1720 if (args == NULL)
1721 error (_("Argument required (integer, `fixed' or `limited')."));
1722 else if (strcmp (args, "hard") == 0
1723 || strcmp (args, "fixed") == 0)
1724 fixed_p = 1;
1725 else if (strcmp (args, "soft") == 0
1726 || strcmp (args, "limit") == 0)
1727 fixed_p = 0;
1728 else
1729 {
1730 char *end;
1731
1732 size = strtoul (args, &end, 0);
1733 if (args == end)
1734 error (_("Invalid %s (bad syntax)."), config->name);
1735
1736 /* Instead of explicitly capping the size of a packet to or
1737 disallowing it, the user is allowed to set the size to
1738 something arbitrarily large. */
1739 }
1740
1741 /* Extra checks? */
1742 if (fixed_p && !config->fixed_p)
1743 {
1744 /* So that the query shows the correct value. */
1745 long query_size = (size <= 0
1746 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1747 : size);
1748
1749 if (! query (_("The target may not be able to correctly handle a %s\n"
1750 "of %ld bytes. Change the packet size? "),
1751 config->name, query_size))
1752 error (_("Packet size not changed."));
1753 }
1754 /* Update the config. */
1755 config->fixed_p = fixed_p;
1756 config->size = size;
1757 }
1758
1759 static void
1760 show_memory_packet_size (struct memory_packet_config *config)
1761 {
1762 if (config->size == 0)
1763 printf_filtered (_("The %s is 0 (default). "), config->name);
1764 else
1765 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1766 if (config->fixed_p)
1767 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1768 get_fixed_memory_packet_size (config));
1769 else
1770 {
1771 remote_target *remote = get_current_remote_target ();
1772
1773 if (remote != NULL)
1774 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1775 remote->get_memory_packet_size (config));
1776 else
1777 puts_filtered ("The actual limit will be further reduced "
1778 "dependent on the target.\n");
1779 }
1780 }
1781
1782 /* FIXME: needs to be per-remote-target. */
1783 static struct memory_packet_config memory_write_packet_config =
1784 {
1785 "memory-write-packet-size",
1786 };
1787
1788 static void
1789 set_memory_write_packet_size (const char *args, int from_tty)
1790 {
1791 set_memory_packet_size (args, &memory_write_packet_config);
1792 }
1793
1794 static void
1795 show_memory_write_packet_size (const char *args, int from_tty)
1796 {
1797 show_memory_packet_size (&memory_write_packet_config);
1798 }
1799
1800 /* Show the number of hardware watchpoints that can be used. */
1801
1802 static void
1803 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
1804 struct cmd_list_element *c,
1805 const char *value)
1806 {
1807 fprintf_filtered (file, _("The maximum number of target hardware "
1808 "watchpoints is %s.\n"), value);
1809 }
1810
1811 /* Show the length limit (in bytes) for hardware watchpoints. */
1812
1813 static void
1814 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
1815 struct cmd_list_element *c,
1816 const char *value)
1817 {
1818 fprintf_filtered (file, _("The maximum length (in bytes) of a target "
1819 "hardware watchpoint is %s.\n"), value);
1820 }
1821
1822 /* Show the number of hardware breakpoints that can be used. */
1823
1824 static void
1825 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
1826 struct cmd_list_element *c,
1827 const char *value)
1828 {
1829 fprintf_filtered (file, _("The maximum number of target hardware "
1830 "breakpoints is %s.\n"), value);
1831 }
1832
1833 /* Controls the maximum number of characters to display in the debug output
1834 for each remote packet. The remaining characters are omitted. */
1835
1836 static int remote_packet_max_chars = 512;
1837
1838 /* Show the maximum number of characters to display for each remote packet
1839 when remote debugging is enabled. */
1840
1841 static void
1842 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
1843 struct cmd_list_element *c,
1844 const char *value)
1845 {
1846 fprintf_filtered (file, _("Number of remote packet characters to "
1847 "display is %s.\n"), value);
1848 }
1849
1850 long
1851 remote_target::get_memory_write_packet_size ()
1852 {
1853 return get_memory_packet_size (&memory_write_packet_config);
1854 }
1855
1856 /* FIXME: needs to be per-remote-target. */
1857 static struct memory_packet_config memory_read_packet_config =
1858 {
1859 "memory-read-packet-size",
1860 };
1861
1862 static void
1863 set_memory_read_packet_size (const char *args, int from_tty)
1864 {
1865 set_memory_packet_size (args, &memory_read_packet_config);
1866 }
1867
1868 static void
1869 show_memory_read_packet_size (const char *args, int from_tty)
1870 {
1871 show_memory_packet_size (&memory_read_packet_config);
1872 }
1873
1874 long
1875 remote_target::get_memory_read_packet_size ()
1876 {
1877 long size = get_memory_packet_size (&memory_read_packet_config);
1878
1879 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1880 extra buffer size argument before the memory read size can be
1881 increased beyond this. */
1882 if (size > get_remote_packet_size ())
1883 size = get_remote_packet_size ();
1884 return size;
1885 }
1886
1887 \f
1888
1889 struct packet_config
1890 {
1891 const char *name;
1892 const char *title;
1893
1894 /* If auto, GDB auto-detects support for this packet or feature,
1895 either through qSupported, or by trying the packet and looking
1896 at the response. If true, GDB assumes the target supports this
1897 packet. If false, the packet is disabled. Configs that don't
1898 have an associated command always have this set to auto. */
1899 enum auto_boolean detect;
1900
1901 /* The "show remote foo-packet" command created for this packet. */
1902 cmd_list_element *show_cmd;
1903
1904 /* Does the target support this packet? */
1905 enum packet_support support;
1906 };
1907
1908 static enum packet_support packet_config_support (struct packet_config *config);
1909 static enum packet_support packet_support (int packet);
1910
1911 static void
1912 show_packet_config_cmd (ui_file *file, struct packet_config *config)
1913 {
1914 const char *support = "internal-error";
1915
1916 switch (packet_config_support (config))
1917 {
1918 case PACKET_ENABLE:
1919 support = "enabled";
1920 break;
1921 case PACKET_DISABLE:
1922 support = "disabled";
1923 break;
1924 case PACKET_SUPPORT_UNKNOWN:
1925 support = "unknown";
1926 break;
1927 }
1928 switch (config->detect)
1929 {
1930 case AUTO_BOOLEAN_AUTO:
1931 fprintf_filtered (file,
1932 _("Support for the `%s' packet "
1933 "is auto-detected, currently %s.\n"),
1934 config->name, support);
1935 break;
1936 case AUTO_BOOLEAN_TRUE:
1937 case AUTO_BOOLEAN_FALSE:
1938 fprintf_filtered (file,
1939 _("Support for the `%s' packet is currently %s.\n"),
1940 config->name, support);
1941 break;
1942 }
1943 }
1944
1945 static void
1946 add_packet_config_cmd (struct packet_config *config, const char *name,
1947 const char *title, int legacy)
1948 {
1949 config->name = name;
1950 config->title = title;
1951 gdb::unique_xmalloc_ptr<char> set_doc
1952 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
1953 name, title);
1954 gdb::unique_xmalloc_ptr<char> show_doc
1955 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
1956 name, title);
1957 /* set/show TITLE-packet {auto,on,off} */
1958 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
1959 set_show_commands cmds
1960 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
1961 &config->detect, set_doc.get (),
1962 show_doc.get (), NULL, /* help_doc */
1963 NULL,
1964 show_remote_protocol_packet_cmd,
1965 &remote_set_cmdlist, &remote_show_cmdlist);
1966 config->show_cmd = cmds.show;
1967
1968 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1969 if (legacy)
1970 {
1971 /* It's not clear who should take ownership of this string, so, for
1972 now, make it static, and give copies to each of the add_alias_cmd
1973 calls below. */
1974 static gdb::unique_xmalloc_ptr<char> legacy_name
1975 = xstrprintf ("%s-packet", name);
1976 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
1977 &remote_set_cmdlist);
1978 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
1979 &remote_show_cmdlist);
1980 }
1981 }
1982
1983 static enum packet_result
1984 packet_check_result (const char *buf)
1985 {
1986 if (buf[0] != '\0')
1987 {
1988 /* The stub recognized the packet request. Check that the
1989 operation succeeded. */
1990 if (buf[0] == 'E'
1991 && isxdigit (buf[1]) && isxdigit (buf[2])
1992 && buf[3] == '\0')
1993 /* "Enn" - definitely an error. */
1994 return PACKET_ERROR;
1995
1996 /* Always treat "E." as an error. This will be used for
1997 more verbose error messages, such as E.memtypes. */
1998 if (buf[0] == 'E' && buf[1] == '.')
1999 return PACKET_ERROR;
2000
2001 /* The packet may or may not be OK. Just assume it is. */
2002 return PACKET_OK;
2003 }
2004 else
2005 /* The stub does not support the packet. */
2006 return PACKET_UNKNOWN;
2007 }
2008
2009 static enum packet_result
2010 packet_check_result (const gdb::char_vector &buf)
2011 {
2012 return packet_check_result (buf.data ());
2013 }
2014
2015 static enum packet_result
2016 packet_ok (const char *buf, struct packet_config *config)
2017 {
2018 enum packet_result result;
2019
2020 if (config->detect != AUTO_BOOLEAN_TRUE
2021 && config->support == PACKET_DISABLE)
2022 internal_error (__FILE__, __LINE__,
2023 _("packet_ok: attempt to use a disabled packet"));
2024
2025 result = packet_check_result (buf);
2026 switch (result)
2027 {
2028 case PACKET_OK:
2029 case PACKET_ERROR:
2030 /* The stub recognized the packet request. */
2031 if (config->support == PACKET_SUPPORT_UNKNOWN)
2032 {
2033 remote_debug_printf ("Packet %s (%s) is supported",
2034 config->name, config->title);
2035 config->support = PACKET_ENABLE;
2036 }
2037 break;
2038 case PACKET_UNKNOWN:
2039 /* The stub does not support the packet. */
2040 if (config->detect == AUTO_BOOLEAN_AUTO
2041 && config->support == PACKET_ENABLE)
2042 {
2043 /* If the stub previously indicated that the packet was
2044 supported then there is a protocol error. */
2045 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2046 config->name, config->title);
2047 }
2048 else if (config->detect == AUTO_BOOLEAN_TRUE)
2049 {
2050 /* The user set it wrong. */
2051 error (_("Enabled packet %s (%s) not recognized by stub"),
2052 config->name, config->title);
2053 }
2054
2055 remote_debug_printf ("Packet %s (%s) is NOT supported",
2056 config->name, config->title);
2057 config->support = PACKET_DISABLE;
2058 break;
2059 }
2060
2061 return result;
2062 }
2063
2064 static enum packet_result
2065 packet_ok (const gdb::char_vector &buf, struct packet_config *config)
2066 {
2067 return packet_ok (buf.data (), config);
2068 }
2069
2070 enum {
2071 PACKET_vCont = 0,
2072 PACKET_X,
2073 PACKET_qSymbol,
2074 PACKET_P,
2075 PACKET_p,
2076 PACKET_Z0,
2077 PACKET_Z1,
2078 PACKET_Z2,
2079 PACKET_Z3,
2080 PACKET_Z4,
2081 PACKET_vFile_setfs,
2082 PACKET_vFile_open,
2083 PACKET_vFile_pread,
2084 PACKET_vFile_pwrite,
2085 PACKET_vFile_close,
2086 PACKET_vFile_unlink,
2087 PACKET_vFile_readlink,
2088 PACKET_vFile_fstat,
2089 PACKET_qXfer_auxv,
2090 PACKET_qXfer_features,
2091 PACKET_qXfer_exec_file,
2092 PACKET_qXfer_libraries,
2093 PACKET_qXfer_libraries_svr4,
2094 PACKET_qXfer_memory_map,
2095 PACKET_qXfer_osdata,
2096 PACKET_qXfer_threads,
2097 PACKET_qXfer_statictrace_read,
2098 PACKET_qXfer_traceframe_info,
2099 PACKET_qXfer_uib,
2100 PACKET_qGetTIBAddr,
2101 PACKET_qGetTLSAddr,
2102 PACKET_qSupported,
2103 PACKET_qTStatus,
2104 PACKET_QPassSignals,
2105 PACKET_QCatchSyscalls,
2106 PACKET_QProgramSignals,
2107 PACKET_QSetWorkingDir,
2108 PACKET_QStartupWithShell,
2109 PACKET_QEnvironmentHexEncoded,
2110 PACKET_QEnvironmentReset,
2111 PACKET_QEnvironmentUnset,
2112 PACKET_qCRC,
2113 PACKET_qSearch_memory,
2114 PACKET_vAttach,
2115 PACKET_vRun,
2116 PACKET_QStartNoAckMode,
2117 PACKET_vKill,
2118 PACKET_qXfer_siginfo_read,
2119 PACKET_qXfer_siginfo_write,
2120 PACKET_qAttached,
2121
2122 /* Support for conditional tracepoints. */
2123 PACKET_ConditionalTracepoints,
2124
2125 /* Support for target-side breakpoint conditions. */
2126 PACKET_ConditionalBreakpoints,
2127
2128 /* Support for target-side breakpoint commands. */
2129 PACKET_BreakpointCommands,
2130
2131 /* Support for fast tracepoints. */
2132 PACKET_FastTracepoints,
2133
2134 /* Support for static tracepoints. */
2135 PACKET_StaticTracepoints,
2136
2137 /* Support for installing tracepoints while a trace experiment is
2138 running. */
2139 PACKET_InstallInTrace,
2140
2141 PACKET_bc,
2142 PACKET_bs,
2143 PACKET_TracepointSource,
2144 PACKET_QAllow,
2145 PACKET_qXfer_fdpic,
2146 PACKET_QDisableRandomization,
2147 PACKET_QAgent,
2148 PACKET_QTBuffer_size,
2149 PACKET_Qbtrace_off,
2150 PACKET_Qbtrace_bts,
2151 PACKET_Qbtrace_pt,
2152 PACKET_qXfer_btrace,
2153
2154 /* Support for the QNonStop packet. */
2155 PACKET_QNonStop,
2156
2157 /* Support for the QThreadEvents packet. */
2158 PACKET_QThreadEvents,
2159
2160 /* Support for multi-process extensions. */
2161 PACKET_multiprocess_feature,
2162
2163 /* Support for enabling and disabling tracepoints while a trace
2164 experiment is running. */
2165 PACKET_EnableDisableTracepoints_feature,
2166
2167 /* Support for collecting strings using the tracenz bytecode. */
2168 PACKET_tracenz_feature,
2169
2170 /* Support for continuing to run a trace experiment while GDB is
2171 disconnected. */
2172 PACKET_DisconnectedTracing_feature,
2173
2174 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2175 PACKET_augmented_libraries_svr4_read_feature,
2176
2177 /* Support for the qXfer:btrace-conf:read packet. */
2178 PACKET_qXfer_btrace_conf,
2179
2180 /* Support for the Qbtrace-conf:bts:size packet. */
2181 PACKET_Qbtrace_conf_bts_size,
2182
2183 /* Support for swbreak+ feature. */
2184 PACKET_swbreak_feature,
2185
2186 /* Support for hwbreak+ feature. */
2187 PACKET_hwbreak_feature,
2188
2189 /* Support for fork events. */
2190 PACKET_fork_event_feature,
2191
2192 /* Support for vfork events. */
2193 PACKET_vfork_event_feature,
2194
2195 /* Support for the Qbtrace-conf:pt:size packet. */
2196 PACKET_Qbtrace_conf_pt_size,
2197
2198 /* Support for exec events. */
2199 PACKET_exec_event_feature,
2200
2201 /* Support for query supported vCont actions. */
2202 PACKET_vContSupported,
2203
2204 /* Support remote CTRL-C. */
2205 PACKET_vCtrlC,
2206
2207 /* Support TARGET_WAITKIND_NO_RESUMED. */
2208 PACKET_no_resumed,
2209
2210 /* Support for memory tagging, allocation tag fetch/store
2211 packets and the tag violation stop replies. */
2212 PACKET_memory_tagging_feature,
2213
2214 PACKET_MAX
2215 };
2216
2217 /* FIXME: needs to be per-remote-target. Ignoring this for now,
2218 assuming all remote targets are the same server (thus all support
2219 the same packets). */
2220 static struct packet_config remote_protocol_packets[PACKET_MAX];
2221
2222 /* Returns the packet's corresponding "set remote foo-packet" command
2223 state. See struct packet_config for more details. */
2224
2225 static enum auto_boolean
2226 packet_set_cmd_state (int packet)
2227 {
2228 return remote_protocol_packets[packet].detect;
2229 }
2230
2231 /* Returns whether a given packet or feature is supported. This takes
2232 into account the state of the corresponding "set remote foo-packet"
2233 command, which may be used to bypass auto-detection. */
2234
2235 static enum packet_support
2236 packet_config_support (struct packet_config *config)
2237 {
2238 switch (config->detect)
2239 {
2240 case AUTO_BOOLEAN_TRUE:
2241 return PACKET_ENABLE;
2242 case AUTO_BOOLEAN_FALSE:
2243 return PACKET_DISABLE;
2244 case AUTO_BOOLEAN_AUTO:
2245 return config->support;
2246 default:
2247 gdb_assert_not_reached ("bad switch");
2248 }
2249 }
2250
2251 /* Same as packet_config_support, but takes the packet's enum value as
2252 argument. */
2253
2254 static enum packet_support
2255 packet_support (int packet)
2256 {
2257 struct packet_config *config = &remote_protocol_packets[packet];
2258
2259 return packet_config_support (config);
2260 }
2261
2262 static void
2263 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2264 struct cmd_list_element *c,
2265 const char *value)
2266 {
2267 struct packet_config *packet;
2268 gdb_assert (c->var.has_value ());
2269
2270 for (packet = remote_protocol_packets;
2271 packet < &remote_protocol_packets[PACKET_MAX];
2272 packet++)
2273 {
2274 if (c == packet->show_cmd)
2275 {
2276 show_packet_config_cmd (file, packet);
2277 return;
2278 }
2279 }
2280 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
2281 c->name);
2282 }
2283
2284 /* Should we try one of the 'Z' requests? */
2285
2286 enum Z_packet_type
2287 {
2288 Z_PACKET_SOFTWARE_BP,
2289 Z_PACKET_HARDWARE_BP,
2290 Z_PACKET_WRITE_WP,
2291 Z_PACKET_READ_WP,
2292 Z_PACKET_ACCESS_WP,
2293 NR_Z_PACKET_TYPES
2294 };
2295
2296 /* For compatibility with older distributions. Provide a ``set remote
2297 Z-packet ...'' command that updates all the Z packet types. */
2298
2299 static enum auto_boolean remote_Z_packet_detect;
2300
2301 static void
2302 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2303 struct cmd_list_element *c)
2304 {
2305 int i;
2306
2307 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2308 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2309 }
2310
2311 static void
2312 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2313 struct cmd_list_element *c,
2314 const char *value)
2315 {
2316 int i;
2317
2318 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2319 {
2320 show_packet_config_cmd (file, &remote_protocol_packets[PACKET_Z0 + i]);
2321 }
2322 }
2323
2324 /* Returns true if the multi-process extensions are in effect. */
2325
2326 static int
2327 remote_multi_process_p (struct remote_state *rs)
2328 {
2329 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2330 }
2331
2332 /* Returns true if fork events are supported. */
2333
2334 static int
2335 remote_fork_event_p (struct remote_state *rs)
2336 {
2337 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2338 }
2339
2340 /* Returns true if vfork events are supported. */
2341
2342 static int
2343 remote_vfork_event_p (struct remote_state *rs)
2344 {
2345 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2346 }
2347
2348 /* Returns true if exec events are supported. */
2349
2350 static int
2351 remote_exec_event_p (struct remote_state *rs)
2352 {
2353 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2354 }
2355
2356 /* Returns true if memory tagging is supported, false otherwise. */
2357
2358 static bool
2359 remote_memory_tagging_p ()
2360 {
2361 return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE;
2362 }
2363
2364 /* Insert fork catchpoint target routine. If fork events are enabled
2365 then return success, nothing more to do. */
2366
2367 int
2368 remote_target::insert_fork_catchpoint (int pid)
2369 {
2370 struct remote_state *rs = get_remote_state ();
2371
2372 return !remote_fork_event_p (rs);
2373 }
2374
2375 /* Remove fork catchpoint target routine. Nothing to do, just
2376 return success. */
2377
2378 int
2379 remote_target::remove_fork_catchpoint (int pid)
2380 {
2381 return 0;
2382 }
2383
2384 /* Insert vfork catchpoint target routine. If vfork events are enabled
2385 then return success, nothing more to do. */
2386
2387 int
2388 remote_target::insert_vfork_catchpoint (int pid)
2389 {
2390 struct remote_state *rs = get_remote_state ();
2391
2392 return !remote_vfork_event_p (rs);
2393 }
2394
2395 /* Remove vfork catchpoint target routine. Nothing to do, just
2396 return success. */
2397
2398 int
2399 remote_target::remove_vfork_catchpoint (int pid)
2400 {
2401 return 0;
2402 }
2403
2404 /* Insert exec catchpoint target routine. If exec events are
2405 enabled, just return success. */
2406
2407 int
2408 remote_target::insert_exec_catchpoint (int pid)
2409 {
2410 struct remote_state *rs = get_remote_state ();
2411
2412 return !remote_exec_event_p (rs);
2413 }
2414
2415 /* Remove exec catchpoint target routine. Nothing to do, just
2416 return success. */
2417
2418 int
2419 remote_target::remove_exec_catchpoint (int pid)
2420 {
2421 return 0;
2422 }
2423
2424 \f
2425
2426 /* Take advantage of the fact that the TID field is not used, to tag
2427 special ptids with it set to != 0. */
2428 static const ptid_t magic_null_ptid (42000, -1, 1);
2429 static const ptid_t not_sent_ptid (42000, -2, 1);
2430 static const ptid_t any_thread_ptid (42000, 0, 1);
2431
2432 /* Find out if the stub attached to PID (and hence GDB should offer to
2433 detach instead of killing it when bailing out). */
2434
2435 int
2436 remote_target::remote_query_attached (int pid)
2437 {
2438 struct remote_state *rs = get_remote_state ();
2439 size_t size = get_remote_packet_size ();
2440
2441 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2442 return 0;
2443
2444 if (remote_multi_process_p (rs))
2445 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2446 else
2447 xsnprintf (rs->buf.data (), size, "qAttached");
2448
2449 putpkt (rs->buf);
2450 getpkt (&rs->buf, 0);
2451
2452 switch (packet_ok (rs->buf,
2453 &remote_protocol_packets[PACKET_qAttached]))
2454 {
2455 case PACKET_OK:
2456 if (strcmp (rs->buf.data (), "1") == 0)
2457 return 1;
2458 break;
2459 case PACKET_ERROR:
2460 warning (_("Remote failure reply: %s"), rs->buf.data ());
2461 break;
2462 case PACKET_UNKNOWN:
2463 break;
2464 }
2465
2466 return 0;
2467 }
2468
2469 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2470 has been invented by GDB, instead of reported by the target. Since
2471 we can be connected to a remote system before before knowing about
2472 any inferior, mark the target with execution when we find the first
2473 inferior. If ATTACHED is 1, then we had just attached to this
2474 inferior. If it is 0, then we just created this inferior. If it
2475 is -1, then try querying the remote stub to find out if it had
2476 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2477 attempt to open this inferior's executable as the main executable
2478 if no main executable is open already. */
2479
2480 inferior *
2481 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2482 int try_open_exec)
2483 {
2484 struct inferior *inf;
2485
2486 /* Check whether this process we're learning about is to be
2487 considered attached, or if is to be considered to have been
2488 spawned by the stub. */
2489 if (attached == -1)
2490 attached = remote_query_attached (pid);
2491
2492 if (gdbarch_has_global_solist (target_gdbarch ()))
2493 {
2494 /* If the target shares code across all inferiors, then every
2495 attach adds a new inferior. */
2496 inf = add_inferior (pid);
2497
2498 /* ... and every inferior is bound to the same program space.
2499 However, each inferior may still have its own address
2500 space. */
2501 inf->aspace = maybe_new_address_space ();
2502 inf->pspace = current_program_space;
2503 }
2504 else
2505 {
2506 /* In the traditional debugging scenario, there's a 1-1 match
2507 between program/address spaces. We simply bind the inferior
2508 to the program space's address space. */
2509 inf = current_inferior ();
2510
2511 /* However, if the current inferior is already bound to a
2512 process, find some other empty inferior. */
2513 if (inf->pid != 0)
2514 {
2515 inf = nullptr;
2516 for (inferior *it : all_inferiors ())
2517 if (it->pid == 0)
2518 {
2519 inf = it;
2520 break;
2521 }
2522 }
2523 if (inf == nullptr)
2524 {
2525 /* Since all inferiors were already bound to a process, add
2526 a new inferior. */
2527 inf = add_inferior_with_spaces ();
2528 }
2529 switch_to_inferior_no_thread (inf);
2530 inf->push_target (this);
2531 inferior_appeared (inf, pid);
2532 }
2533
2534 inf->attach_flag = attached;
2535 inf->fake_pid_p = fake_pid_p;
2536
2537 /* If no main executable is currently open then attempt to
2538 open the file that was executed to create this inferior. */
2539 if (try_open_exec && get_exec_file (0) == NULL)
2540 exec_file_locate_attach (pid, 0, 1);
2541
2542 /* Check for exec file mismatch, and let the user solve it. */
2543 validate_exec_file (1);
2544
2545 return inf;
2546 }
2547
2548 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2549 static remote_thread_info *get_remote_thread_info (remote_target *target,
2550 ptid_t ptid);
2551
2552 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2553 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2554 remote_state::starting_up flag) is true then the new thread is added
2555 silently, otherwise the new thread will be announced to the user. */
2556
2557 thread_info *
2558 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2559 bool silent_p)
2560 {
2561 struct remote_state *rs = get_remote_state ();
2562 struct thread_info *thread;
2563
2564 /* GDB historically didn't pull threads in the initial connection
2565 setup. If the remote target doesn't even have a concept of
2566 threads (e.g., a bare-metal target), even if internally we
2567 consider that a single-threaded target, mentioning a new thread
2568 might be confusing to the user. Be silent then, preserving the
2569 age old behavior. */
2570 if (rs->starting_up || silent_p)
2571 thread = add_thread_silent (this, ptid);
2572 else
2573 thread = add_thread (this, ptid);
2574
2575 /* We start by assuming threads are resumed. That state then gets updated
2576 when we process a matching stop reply. */
2577 get_remote_thread_info (thread)->set_resumed ();
2578
2579 set_executing (this, ptid, executing);
2580 set_running (this, ptid, running);
2581
2582 return thread;
2583 }
2584
2585 /* Come here when we learn about a thread id from the remote target.
2586 It may be the first time we hear about such thread, so take the
2587 opportunity to add it to GDB's thread list. In case this is the
2588 first time we're noticing its corresponding inferior, add it to
2589 GDB's inferior list as well. EXECUTING indicates whether the
2590 thread is (internally) executing or stopped. */
2591
2592 void
2593 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2594 {
2595 /* In non-stop mode, we assume new found threads are (externally)
2596 running until proven otherwise with a stop reply. In all-stop,
2597 we can only get here if all threads are stopped. */
2598 bool running = target_is_non_stop_p ();
2599
2600 /* If this is a new thread, add it to GDB's thread list.
2601 If we leave it up to WFI to do this, bad things will happen. */
2602
2603 thread_info *tp = find_thread_ptid (this, currthread);
2604 if (tp != NULL && tp->state == THREAD_EXITED)
2605 {
2606 /* We're seeing an event on a thread id we knew had exited.
2607 This has to be a new thread reusing the old id. Add it. */
2608 remote_add_thread (currthread, running, executing, false);
2609 return;
2610 }
2611
2612 if (!in_thread_list (this, currthread))
2613 {
2614 struct inferior *inf = NULL;
2615 int pid = currthread.pid ();
2616
2617 if (inferior_ptid.is_pid ()
2618 && pid == inferior_ptid.pid ())
2619 {
2620 /* inferior_ptid has no thread member yet. This can happen
2621 with the vAttach -> remote_wait,"TAAthread:" path if the
2622 stub doesn't support qC. This is the first stop reported
2623 after an attach, so this is the main thread. Update the
2624 ptid in the thread list. */
2625 if (in_thread_list (this, ptid_t (pid)))
2626 thread_change_ptid (this, inferior_ptid, currthread);
2627 else
2628 {
2629 thread_info *thr
2630 = remote_add_thread (currthread, running, executing, false);
2631 switch_to_thread (thr);
2632 }
2633 return;
2634 }
2635
2636 if (magic_null_ptid == inferior_ptid)
2637 {
2638 /* inferior_ptid is not set yet. This can happen with the
2639 vRun -> remote_wait,"TAAthread:" path if the stub
2640 doesn't support qC. This is the first stop reported
2641 after an attach, so this is the main thread. Update the
2642 ptid in the thread list. */
2643 thread_change_ptid (this, inferior_ptid, currthread);
2644 return;
2645 }
2646
2647 /* When connecting to a target remote, or to a target
2648 extended-remote which already was debugging an inferior, we
2649 may not know about it yet. Add it before adding its child
2650 thread, so notifications are emitted in a sensible order. */
2651 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2652 {
2653 struct remote_state *rs = get_remote_state ();
2654 bool fake_pid_p = !remote_multi_process_p (rs);
2655
2656 inf = remote_add_inferior (fake_pid_p,
2657 currthread.pid (), -1, 1);
2658 }
2659
2660 /* This is really a new thread. Add it. */
2661 thread_info *new_thr
2662 = remote_add_thread (currthread, running, executing, false);
2663
2664 /* If we found a new inferior, let the common code do whatever
2665 it needs to with it (e.g., read shared libraries, insert
2666 breakpoints), unless we're just setting up an all-stop
2667 connection. */
2668 if (inf != NULL)
2669 {
2670 struct remote_state *rs = get_remote_state ();
2671
2672 if (!rs->starting_up)
2673 notice_new_inferior (new_thr, executing, 0);
2674 }
2675 }
2676 }
2677
2678 /* Return THREAD's private thread data, creating it if necessary. */
2679
2680 static remote_thread_info *
2681 get_remote_thread_info (thread_info *thread)
2682 {
2683 gdb_assert (thread != NULL);
2684
2685 if (thread->priv == NULL)
2686 thread->priv.reset (new remote_thread_info);
2687
2688 return static_cast<remote_thread_info *> (thread->priv.get ());
2689 }
2690
2691 /* Return PTID's private thread data, creating it if necessary. */
2692
2693 static remote_thread_info *
2694 get_remote_thread_info (remote_target *target, ptid_t ptid)
2695 {
2696 thread_info *thr = find_thread_ptid (target, ptid);
2697 return get_remote_thread_info (thr);
2698 }
2699
2700 /* Call this function as a result of
2701 1) A halt indication (T packet) containing a thread id
2702 2) A direct query of currthread
2703 3) Successful execution of set thread */
2704
2705 static void
2706 record_currthread (struct remote_state *rs, ptid_t currthread)
2707 {
2708 rs->general_thread = currthread;
2709 }
2710
2711 /* If 'QPassSignals' is supported, tell the remote stub what signals
2712 it can simply pass through to the inferior without reporting. */
2713
2714 void
2715 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2716 {
2717 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2718 {
2719 char *pass_packet, *p;
2720 int count = 0;
2721 struct remote_state *rs = get_remote_state ();
2722
2723 gdb_assert (pass_signals.size () < 256);
2724 for (size_t i = 0; i < pass_signals.size (); i++)
2725 {
2726 if (pass_signals[i])
2727 count++;
2728 }
2729 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2730 strcpy (pass_packet, "QPassSignals:");
2731 p = pass_packet + strlen (pass_packet);
2732 for (size_t i = 0; i < pass_signals.size (); i++)
2733 {
2734 if (pass_signals[i])
2735 {
2736 if (i >= 16)
2737 *p++ = tohex (i >> 4);
2738 *p++ = tohex (i & 15);
2739 if (count)
2740 *p++ = ';';
2741 else
2742 break;
2743 count--;
2744 }
2745 }
2746 *p = 0;
2747 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2748 {
2749 putpkt (pass_packet);
2750 getpkt (&rs->buf, 0);
2751 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2752 xfree (rs->last_pass_packet);
2753 rs->last_pass_packet = pass_packet;
2754 }
2755 else
2756 xfree (pass_packet);
2757 }
2758 }
2759
2760 /* If 'QCatchSyscalls' is supported, tell the remote stub
2761 to report syscalls to GDB. */
2762
2763 int
2764 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2765 gdb::array_view<const int> syscall_counts)
2766 {
2767 const char *catch_packet;
2768 enum packet_result result;
2769 int n_sysno = 0;
2770
2771 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2772 {
2773 /* Not supported. */
2774 return 1;
2775 }
2776
2777 if (needed && any_count == 0)
2778 {
2779 /* Count how many syscalls are to be caught. */
2780 for (size_t i = 0; i < syscall_counts.size (); i++)
2781 {
2782 if (syscall_counts[i] != 0)
2783 n_sysno++;
2784 }
2785 }
2786
2787 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
2788 pid, needed, any_count, n_sysno);
2789
2790 std::string built_packet;
2791 if (needed)
2792 {
2793 /* Prepare a packet with the sysno list, assuming max 8+1
2794 characters for a sysno. If the resulting packet size is too
2795 big, fallback on the non-selective packet. */
2796 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2797 built_packet.reserve (maxpktsz);
2798 built_packet = "QCatchSyscalls:1";
2799 if (any_count == 0)
2800 {
2801 /* Add in each syscall to be caught. */
2802 for (size_t i = 0; i < syscall_counts.size (); i++)
2803 {
2804 if (syscall_counts[i] != 0)
2805 string_appendf (built_packet, ";%zx", i);
2806 }
2807 }
2808 if (built_packet.size () > get_remote_packet_size ())
2809 {
2810 /* catch_packet too big. Fallback to less efficient
2811 non selective mode, with GDB doing the filtering. */
2812 catch_packet = "QCatchSyscalls:1";
2813 }
2814 else
2815 catch_packet = built_packet.c_str ();
2816 }
2817 else
2818 catch_packet = "QCatchSyscalls:0";
2819
2820 struct remote_state *rs = get_remote_state ();
2821
2822 putpkt (catch_packet);
2823 getpkt (&rs->buf, 0);
2824 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2825 if (result == PACKET_OK)
2826 return 0;
2827 else
2828 return -1;
2829 }
2830
2831 /* If 'QProgramSignals' is supported, tell the remote stub what
2832 signals it should pass through to the inferior when detaching. */
2833
2834 void
2835 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
2836 {
2837 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2838 {
2839 char *packet, *p;
2840 int count = 0;
2841 struct remote_state *rs = get_remote_state ();
2842
2843 gdb_assert (signals.size () < 256);
2844 for (size_t i = 0; i < signals.size (); i++)
2845 {
2846 if (signals[i])
2847 count++;
2848 }
2849 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2850 strcpy (packet, "QProgramSignals:");
2851 p = packet + strlen (packet);
2852 for (size_t i = 0; i < signals.size (); i++)
2853 {
2854 if (signal_pass_state (i))
2855 {
2856 if (i >= 16)
2857 *p++ = tohex (i >> 4);
2858 *p++ = tohex (i & 15);
2859 if (count)
2860 *p++ = ';';
2861 else
2862 break;
2863 count--;
2864 }
2865 }
2866 *p = 0;
2867 if (!rs->last_program_signals_packet
2868 || strcmp (rs->last_program_signals_packet, packet) != 0)
2869 {
2870 putpkt (packet);
2871 getpkt (&rs->buf, 0);
2872 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2873 xfree (rs->last_program_signals_packet);
2874 rs->last_program_signals_packet = packet;
2875 }
2876 else
2877 xfree (packet);
2878 }
2879 }
2880
2881 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2882 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2883 thread. If GEN is set, set the general thread, if not, then set
2884 the step/continue thread. */
2885 void
2886 remote_target::set_thread (ptid_t ptid, int gen)
2887 {
2888 struct remote_state *rs = get_remote_state ();
2889 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2890 char *buf = rs->buf.data ();
2891 char *endbuf = buf + get_remote_packet_size ();
2892
2893 if (state == ptid)
2894 return;
2895
2896 *buf++ = 'H';
2897 *buf++ = gen ? 'g' : 'c';
2898 if (ptid == magic_null_ptid)
2899 xsnprintf (buf, endbuf - buf, "0");
2900 else if (ptid == any_thread_ptid)
2901 xsnprintf (buf, endbuf - buf, "0");
2902 else if (ptid == minus_one_ptid)
2903 xsnprintf (buf, endbuf - buf, "-1");
2904 else
2905 write_ptid (buf, endbuf, ptid);
2906 putpkt (rs->buf);
2907 getpkt (&rs->buf, 0);
2908 if (gen)
2909 rs->general_thread = ptid;
2910 else
2911 rs->continue_thread = ptid;
2912 }
2913
2914 void
2915 remote_target::set_general_thread (ptid_t ptid)
2916 {
2917 set_thread (ptid, 1);
2918 }
2919
2920 void
2921 remote_target::set_continue_thread (ptid_t ptid)
2922 {
2923 set_thread (ptid, 0);
2924 }
2925
2926 /* Change the remote current process. Which thread within the process
2927 ends up selected isn't important, as long as it is the same process
2928 as what INFERIOR_PTID points to.
2929
2930 This comes from that fact that there is no explicit notion of
2931 "selected process" in the protocol. The selected process for
2932 general operations is the process the selected general thread
2933 belongs to. */
2934
2935 void
2936 remote_target::set_general_process ()
2937 {
2938 struct remote_state *rs = get_remote_state ();
2939
2940 /* If the remote can't handle multiple processes, don't bother. */
2941 if (!remote_multi_process_p (rs))
2942 return;
2943
2944 /* We only need to change the remote current thread if it's pointing
2945 at some other process. */
2946 if (rs->general_thread.pid () != inferior_ptid.pid ())
2947 set_general_thread (inferior_ptid);
2948 }
2949
2950 \f
2951 /* Return nonzero if this is the main thread that we made up ourselves
2952 to model non-threaded targets as single-threaded. */
2953
2954 static int
2955 remote_thread_always_alive (ptid_t ptid)
2956 {
2957 if (ptid == magic_null_ptid)
2958 /* The main thread is always alive. */
2959 return 1;
2960
2961 if (ptid.pid () != 0 && ptid.lwp () == 0)
2962 /* The main thread is always alive. This can happen after a
2963 vAttach, if the remote side doesn't support
2964 multi-threading. */
2965 return 1;
2966
2967 return 0;
2968 }
2969
2970 /* Return nonzero if the thread PTID is still alive on the remote
2971 system. */
2972
2973 bool
2974 remote_target::thread_alive (ptid_t ptid)
2975 {
2976 struct remote_state *rs = get_remote_state ();
2977 char *p, *endp;
2978
2979 /* Check if this is a thread that we made up ourselves to model
2980 non-threaded targets as single-threaded. */
2981 if (remote_thread_always_alive (ptid))
2982 return 1;
2983
2984 p = rs->buf.data ();
2985 endp = p + get_remote_packet_size ();
2986
2987 *p++ = 'T';
2988 write_ptid (p, endp, ptid);
2989
2990 putpkt (rs->buf);
2991 getpkt (&rs->buf, 0);
2992 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2993 }
2994
2995 /* Return a pointer to a thread name if we know it and NULL otherwise.
2996 The thread_info object owns the memory for the name. */
2997
2998 const char *
2999 remote_target::thread_name (struct thread_info *info)
3000 {
3001 if (info->priv != NULL)
3002 {
3003 const std::string &name = get_remote_thread_info (info)->name;
3004 return !name.empty () ? name.c_str () : NULL;
3005 }
3006
3007 return NULL;
3008 }
3009
3010 /* About these extended threadlist and threadinfo packets. They are
3011 variable length packets but, the fields within them are often fixed
3012 length. They are redundant enough to send over UDP as is the
3013 remote protocol in general. There is a matching unit test module
3014 in libstub. */
3015
3016 /* WARNING: This threadref data structure comes from the remote O.S.,
3017 libstub protocol encoding, and remote.c. It is not particularly
3018 changable. */
3019
3020 /* Right now, the internal structure is int. We want it to be bigger.
3021 Plan to fix this. */
3022
3023 typedef int gdb_threadref; /* Internal GDB thread reference. */
3024
3025 /* gdb_ext_thread_info is an internal GDB data structure which is
3026 equivalent to the reply of the remote threadinfo packet. */
3027
3028 struct gdb_ext_thread_info
3029 {
3030 threadref threadid; /* External form of thread reference. */
3031 int active; /* Has state interesting to GDB?
3032 regs, stack. */
3033 char display[256]; /* Brief state display, name,
3034 blocked/suspended. */
3035 char shortname[32]; /* To be used to name threads. */
3036 char more_display[256]; /* Long info, statistics, queue depth,
3037 whatever. */
3038 };
3039
3040 /* The volume of remote transfers can be limited by submitting
3041 a mask containing bits specifying the desired information.
3042 Use a union of these values as the 'selection' parameter to
3043 get_thread_info. FIXME: Make these TAG names more thread specific. */
3044
3045 #define TAG_THREADID 1
3046 #define TAG_EXISTS 2
3047 #define TAG_DISPLAY 4
3048 #define TAG_THREADNAME 8
3049 #define TAG_MOREDISPLAY 16
3050
3051 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3052
3053 static const char *unpack_nibble (const char *buf, int *val);
3054
3055 static const char *unpack_byte (const char *buf, int *value);
3056
3057 static char *pack_int (char *buf, int value);
3058
3059 static const char *unpack_int (const char *buf, int *value);
3060
3061 static const char *unpack_string (const char *src, char *dest, int length);
3062
3063 static char *pack_threadid (char *pkt, threadref *id);
3064
3065 static const char *unpack_threadid (const char *inbuf, threadref *id);
3066
3067 void int_to_threadref (threadref *id, int value);
3068
3069 static int threadref_to_int (threadref *ref);
3070
3071 static void copy_threadref (threadref *dest, threadref *src);
3072
3073 static int threadmatch (threadref *dest, threadref *src);
3074
3075 static char *pack_threadinfo_request (char *pkt, int mode,
3076 threadref *id);
3077
3078 static char *pack_threadlist_request (char *pkt, int startflag,
3079 int threadcount,
3080 threadref *nextthread);
3081
3082 static int remote_newthread_step (threadref *ref, void *context);
3083
3084
3085 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3086 buffer we're allowed to write to. Returns
3087 BUF+CHARACTERS_WRITTEN. */
3088
3089 char *
3090 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3091 {
3092 int pid, tid;
3093 struct remote_state *rs = get_remote_state ();
3094
3095 if (remote_multi_process_p (rs))
3096 {
3097 pid = ptid.pid ();
3098 if (pid < 0)
3099 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3100 else
3101 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3102 }
3103 tid = ptid.lwp ();
3104 if (tid < 0)
3105 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3106 else
3107 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3108
3109 return buf;
3110 }
3111
3112 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3113 last parsed char. Returns null_ptid if no thread id is found, and
3114 throws an error if the thread id has an invalid format. */
3115
3116 static ptid_t
3117 read_ptid (const char *buf, const char **obuf)
3118 {
3119 const char *p = buf;
3120 const char *pp;
3121 ULONGEST pid = 0, tid = 0;
3122
3123 if (*p == 'p')
3124 {
3125 /* Multi-process ptid. */
3126 pp = unpack_varlen_hex (p + 1, &pid);
3127 if (*pp != '.')
3128 error (_("invalid remote ptid: %s"), p);
3129
3130 p = pp;
3131 pp = unpack_varlen_hex (p + 1, &tid);
3132 if (obuf)
3133 *obuf = pp;
3134 return ptid_t (pid, tid);
3135 }
3136
3137 /* No multi-process. Just a tid. */
3138 pp = unpack_varlen_hex (p, &tid);
3139
3140 /* Return null_ptid when no thread id is found. */
3141 if (p == pp)
3142 {
3143 if (obuf)
3144 *obuf = pp;
3145 return null_ptid;
3146 }
3147
3148 /* Since the stub is not sending a process id, then default to
3149 what's in inferior_ptid, unless it's null at this point. If so,
3150 then since there's no way to know the pid of the reported
3151 threads, use the magic number. */
3152 if (inferior_ptid == null_ptid)
3153 pid = magic_null_ptid.pid ();
3154 else
3155 pid = inferior_ptid.pid ();
3156
3157 if (obuf)
3158 *obuf = pp;
3159 return ptid_t (pid, tid);
3160 }
3161
3162 static int
3163 stubhex (int ch)
3164 {
3165 if (ch >= 'a' && ch <= 'f')
3166 return ch - 'a' + 10;
3167 if (ch >= '0' && ch <= '9')
3168 return ch - '0';
3169 if (ch >= 'A' && ch <= 'F')
3170 return ch - 'A' + 10;
3171 return -1;
3172 }
3173
3174 static int
3175 stub_unpack_int (const char *buff, int fieldlength)
3176 {
3177 int nibble;
3178 int retval = 0;
3179
3180 while (fieldlength)
3181 {
3182 nibble = stubhex (*buff++);
3183 retval |= nibble;
3184 fieldlength--;
3185 if (fieldlength)
3186 retval = retval << 4;
3187 }
3188 return retval;
3189 }
3190
3191 static const char *
3192 unpack_nibble (const char *buf, int *val)
3193 {
3194 *val = fromhex (*buf++);
3195 return buf;
3196 }
3197
3198 static const char *
3199 unpack_byte (const char *buf, int *value)
3200 {
3201 *value = stub_unpack_int (buf, 2);
3202 return buf + 2;
3203 }
3204
3205 static char *
3206 pack_int (char *buf, int value)
3207 {
3208 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3209 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3210 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3211 buf = pack_hex_byte (buf, (value & 0xff));
3212 return buf;
3213 }
3214
3215 static const char *
3216 unpack_int (const char *buf, int *value)
3217 {
3218 *value = stub_unpack_int (buf, 8);
3219 return buf + 8;
3220 }
3221
3222 #if 0 /* Currently unused, uncomment when needed. */
3223 static char *pack_string (char *pkt, char *string);
3224
3225 static char *
3226 pack_string (char *pkt, char *string)
3227 {
3228 char ch;
3229 int len;
3230
3231 len = strlen (string);
3232 if (len > 200)
3233 len = 200; /* Bigger than most GDB packets, junk??? */
3234 pkt = pack_hex_byte (pkt, len);
3235 while (len-- > 0)
3236 {
3237 ch = *string++;
3238 if ((ch == '\0') || (ch == '#'))
3239 ch = '*'; /* Protect encapsulation. */
3240 *pkt++ = ch;
3241 }
3242 return pkt;
3243 }
3244 #endif /* 0 (unused) */
3245
3246 static const char *
3247 unpack_string (const char *src, char *dest, int length)
3248 {
3249 while (length--)
3250 *dest++ = *src++;
3251 *dest = '\0';
3252 return src;
3253 }
3254
3255 static char *
3256 pack_threadid (char *pkt, threadref *id)
3257 {
3258 char *limit;
3259 unsigned char *altid;
3260
3261 altid = (unsigned char *) id;
3262 limit = pkt + BUF_THREAD_ID_SIZE;
3263 while (pkt < limit)
3264 pkt = pack_hex_byte (pkt, *altid++);
3265 return pkt;
3266 }
3267
3268
3269 static const char *
3270 unpack_threadid (const char *inbuf, threadref *id)
3271 {
3272 char *altref;
3273 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3274 int x, y;
3275
3276 altref = (char *) id;
3277
3278 while (inbuf < limit)
3279 {
3280 x = stubhex (*inbuf++);
3281 y = stubhex (*inbuf++);
3282 *altref++ = (x << 4) | y;
3283 }
3284 return inbuf;
3285 }
3286
3287 /* Externally, threadrefs are 64 bits but internally, they are still
3288 ints. This is due to a mismatch of specifications. We would like
3289 to use 64bit thread references internally. This is an adapter
3290 function. */
3291
3292 void
3293 int_to_threadref (threadref *id, int value)
3294 {
3295 unsigned char *scan;
3296
3297 scan = (unsigned char *) id;
3298 {
3299 int i = 4;
3300 while (i--)
3301 *scan++ = 0;
3302 }
3303 *scan++ = (value >> 24) & 0xff;
3304 *scan++ = (value >> 16) & 0xff;
3305 *scan++ = (value >> 8) & 0xff;
3306 *scan++ = (value & 0xff);
3307 }
3308
3309 static int
3310 threadref_to_int (threadref *ref)
3311 {
3312 int i, value = 0;
3313 unsigned char *scan;
3314
3315 scan = *ref;
3316 scan += 4;
3317 i = 4;
3318 while (i-- > 0)
3319 value = (value << 8) | ((*scan++) & 0xff);
3320 return value;
3321 }
3322
3323 static void
3324 copy_threadref (threadref *dest, threadref *src)
3325 {
3326 int i;
3327 unsigned char *csrc, *cdest;
3328
3329 csrc = (unsigned char *) src;
3330 cdest = (unsigned char *) dest;
3331 i = 8;
3332 while (i--)
3333 *cdest++ = *csrc++;
3334 }
3335
3336 static int
3337 threadmatch (threadref *dest, threadref *src)
3338 {
3339 /* Things are broken right now, so just assume we got a match. */
3340 #if 0
3341 unsigned char *srcp, *destp;
3342 int i, result;
3343 srcp = (char *) src;
3344 destp = (char *) dest;
3345
3346 result = 1;
3347 while (i-- > 0)
3348 result &= (*srcp++ == *destp++) ? 1 : 0;
3349 return result;
3350 #endif
3351 return 1;
3352 }
3353
3354 /*
3355 threadid:1, # always request threadid
3356 context_exists:2,
3357 display:4,
3358 unique_name:8,
3359 more_display:16
3360 */
3361
3362 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3363
3364 static char *
3365 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3366 {
3367 *pkt++ = 'q'; /* Info Query */
3368 *pkt++ = 'P'; /* process or thread info */
3369 pkt = pack_int (pkt, mode); /* mode */
3370 pkt = pack_threadid (pkt, id); /* threadid */
3371 *pkt = '\0'; /* terminate */
3372 return pkt;
3373 }
3374
3375 /* These values tag the fields in a thread info response packet. */
3376 /* Tagging the fields allows us to request specific fields and to
3377 add more fields as time goes by. */
3378
3379 #define TAG_THREADID 1 /* Echo the thread identifier. */
3380 #define TAG_EXISTS 2 /* Is this process defined enough to
3381 fetch registers and its stack? */
3382 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3383 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3384 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3385 the process. */
3386
3387 int
3388 remote_target::remote_unpack_thread_info_response (const char *pkt,
3389 threadref *expectedref,
3390 gdb_ext_thread_info *info)
3391 {
3392 struct remote_state *rs = get_remote_state ();
3393 int mask, length;
3394 int tag;
3395 threadref ref;
3396 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3397 int retval = 1;
3398
3399 /* info->threadid = 0; FIXME: implement zero_threadref. */
3400 info->active = 0;
3401 info->display[0] = '\0';
3402 info->shortname[0] = '\0';
3403 info->more_display[0] = '\0';
3404
3405 /* Assume the characters indicating the packet type have been
3406 stripped. */
3407 pkt = unpack_int (pkt, &mask); /* arg mask */
3408 pkt = unpack_threadid (pkt, &ref);
3409
3410 if (mask == 0)
3411 warning (_("Incomplete response to threadinfo request."));
3412 if (!threadmatch (&ref, expectedref))
3413 { /* This is an answer to a different request. */
3414 warning (_("ERROR RMT Thread info mismatch."));
3415 return 0;
3416 }
3417 copy_threadref (&info->threadid, &ref);
3418
3419 /* Loop on tagged fields , try to bail if something goes wrong. */
3420
3421 /* Packets are terminated with nulls. */
3422 while ((pkt < limit) && mask && *pkt)
3423 {
3424 pkt = unpack_int (pkt, &tag); /* tag */
3425 pkt = unpack_byte (pkt, &length); /* length */
3426 if (!(tag & mask)) /* Tags out of synch with mask. */
3427 {
3428 warning (_("ERROR RMT: threadinfo tag mismatch."));
3429 retval = 0;
3430 break;
3431 }
3432 if (tag == TAG_THREADID)
3433 {
3434 if (length != 16)
3435 {
3436 warning (_("ERROR RMT: length of threadid is not 16."));
3437 retval = 0;
3438 break;
3439 }
3440 pkt = unpack_threadid (pkt, &ref);
3441 mask = mask & ~TAG_THREADID;
3442 continue;
3443 }
3444 if (tag == TAG_EXISTS)
3445 {
3446 info->active = stub_unpack_int (pkt, length);
3447 pkt += length;
3448 mask = mask & ~(TAG_EXISTS);
3449 if (length > 8)
3450 {
3451 warning (_("ERROR RMT: 'exists' length too long."));
3452 retval = 0;
3453 break;
3454 }
3455 continue;
3456 }
3457 if (tag == TAG_THREADNAME)
3458 {
3459 pkt = unpack_string (pkt, &info->shortname[0], length);
3460 mask = mask & ~TAG_THREADNAME;
3461 continue;
3462 }
3463 if (tag == TAG_DISPLAY)
3464 {
3465 pkt = unpack_string (pkt, &info->display[0], length);
3466 mask = mask & ~TAG_DISPLAY;
3467 continue;
3468 }
3469 if (tag == TAG_MOREDISPLAY)
3470 {
3471 pkt = unpack_string (pkt, &info->more_display[0], length);
3472 mask = mask & ~TAG_MOREDISPLAY;
3473 continue;
3474 }
3475 warning (_("ERROR RMT: unknown thread info tag."));
3476 break; /* Not a tag we know about. */
3477 }
3478 return retval;
3479 }
3480
3481 int
3482 remote_target::remote_get_threadinfo (threadref *threadid,
3483 int fieldset,
3484 gdb_ext_thread_info *info)
3485 {
3486 struct remote_state *rs = get_remote_state ();
3487 int result;
3488
3489 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3490 putpkt (rs->buf);
3491 getpkt (&rs->buf, 0);
3492
3493 if (rs->buf[0] == '\0')
3494 return 0;
3495
3496 result = remote_unpack_thread_info_response (&rs->buf[2],
3497 threadid, info);
3498 return result;
3499 }
3500
3501 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3502
3503 static char *
3504 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3505 threadref *nextthread)
3506 {
3507 *pkt++ = 'q'; /* info query packet */
3508 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3509 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3510 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3511 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3512 *pkt = '\0';
3513 return pkt;
3514 }
3515
3516 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3517
3518 int
3519 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3520 threadref *original_echo,
3521 threadref *resultlist,
3522 int *doneflag)
3523 {
3524 struct remote_state *rs = get_remote_state ();
3525 int count, resultcount, done;
3526
3527 resultcount = 0;
3528 /* Assume the 'q' and 'M chars have been stripped. */
3529 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3530 /* done parse past here */
3531 pkt = unpack_byte (pkt, &count); /* count field */
3532 pkt = unpack_nibble (pkt, &done);
3533 /* The first threadid is the argument threadid. */
3534 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3535 while ((count-- > 0) && (pkt < limit))
3536 {
3537 pkt = unpack_threadid (pkt, resultlist++);
3538 if (resultcount++ >= result_limit)
3539 break;
3540 }
3541 if (doneflag)
3542 *doneflag = done;
3543 return resultcount;
3544 }
3545
3546 /* Fetch the next batch of threads from the remote. Returns -1 if the
3547 qL packet is not supported, 0 on error and 1 on success. */
3548
3549 int
3550 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3551 int result_limit, int *done, int *result_count,
3552 threadref *threadlist)
3553 {
3554 struct remote_state *rs = get_remote_state ();
3555 int result = 1;
3556
3557 /* Truncate result limit to be smaller than the packet size. */
3558 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3559 >= get_remote_packet_size ())
3560 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3561
3562 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3563 nextthread);
3564 putpkt (rs->buf);
3565 getpkt (&rs->buf, 0);
3566 if (rs->buf[0] == '\0')
3567 {
3568 /* Packet not supported. */
3569 return -1;
3570 }
3571
3572 *result_count =
3573 parse_threadlist_response (&rs->buf[2], result_limit,
3574 &rs->echo_nextthread, threadlist, done);
3575
3576 if (!threadmatch (&rs->echo_nextthread, nextthread))
3577 {
3578 /* FIXME: This is a good reason to drop the packet. */
3579 /* Possibly, there is a duplicate response. */
3580 /* Possibilities :
3581 retransmit immediatly - race conditions
3582 retransmit after timeout - yes
3583 exit
3584 wait for packet, then exit
3585 */
3586 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3587 return 0; /* I choose simply exiting. */
3588 }
3589 if (*result_count <= 0)
3590 {
3591 if (*done != 1)
3592 {
3593 warning (_("RMT ERROR : failed to get remote thread list."));
3594 result = 0;
3595 }
3596 return result; /* break; */
3597 }
3598 if (*result_count > result_limit)
3599 {
3600 *result_count = 0;
3601 warning (_("RMT ERROR: threadlist response longer than requested."));
3602 return 0;
3603 }
3604 return result;
3605 }
3606
3607 /* Fetch the list of remote threads, with the qL packet, and call
3608 STEPFUNCTION for each thread found. Stops iterating and returns 1
3609 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3610 STEPFUNCTION returns false. If the packet is not supported,
3611 returns -1. */
3612
3613 int
3614 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3615 void *context, int looplimit)
3616 {
3617 struct remote_state *rs = get_remote_state ();
3618 int done, i, result_count;
3619 int startflag = 1;
3620 int result = 1;
3621 int loopcount = 0;
3622
3623 done = 0;
3624 while (!done)
3625 {
3626 if (loopcount++ > looplimit)
3627 {
3628 result = 0;
3629 warning (_("Remote fetch threadlist -infinite loop-."));
3630 break;
3631 }
3632 result = remote_get_threadlist (startflag, &rs->nextthread,
3633 MAXTHREADLISTRESULTS,
3634 &done, &result_count,
3635 rs->resultthreadlist);
3636 if (result <= 0)
3637 break;
3638 /* Clear for later iterations. */
3639 startflag = 0;
3640 /* Setup to resume next batch of thread references, set nextthread. */
3641 if (result_count >= 1)
3642 copy_threadref (&rs->nextthread,
3643 &rs->resultthreadlist[result_count - 1]);
3644 i = 0;
3645 while (result_count--)
3646 {
3647 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3648 {
3649 result = 0;
3650 break;
3651 }
3652 }
3653 }
3654 return result;
3655 }
3656
3657 /* A thread found on the remote target. */
3658
3659 struct thread_item
3660 {
3661 explicit thread_item (ptid_t ptid_)
3662 : ptid (ptid_)
3663 {}
3664
3665 thread_item (thread_item &&other) = default;
3666 thread_item &operator= (thread_item &&other) = default;
3667
3668 DISABLE_COPY_AND_ASSIGN (thread_item);
3669
3670 /* The thread's PTID. */
3671 ptid_t ptid;
3672
3673 /* The thread's extra info. */
3674 std::string extra;
3675
3676 /* The thread's name. */
3677 std::string name;
3678
3679 /* The core the thread was running on. -1 if not known. */
3680 int core = -1;
3681
3682 /* The thread handle associated with the thread. */
3683 gdb::byte_vector thread_handle;
3684 };
3685
3686 /* Context passed around to the various methods listing remote
3687 threads. As new threads are found, they're added to the ITEMS
3688 vector. */
3689
3690 struct threads_listing_context
3691 {
3692 /* Return true if this object contains an entry for a thread with ptid
3693 PTID. */
3694
3695 bool contains_thread (ptid_t ptid) const
3696 {
3697 auto match_ptid = [&] (const thread_item &item)
3698 {
3699 return item.ptid == ptid;
3700 };
3701
3702 auto it = std::find_if (this->items.begin (),
3703 this->items.end (),
3704 match_ptid);
3705
3706 return it != this->items.end ();
3707 }
3708
3709 /* Remove the thread with ptid PTID. */
3710
3711 void remove_thread (ptid_t ptid)
3712 {
3713 auto match_ptid = [&] (const thread_item &item)
3714 {
3715 return item.ptid == ptid;
3716 };
3717
3718 auto it = std::remove_if (this->items.begin (),
3719 this->items.end (),
3720 match_ptid);
3721
3722 if (it != this->items.end ())
3723 this->items.erase (it);
3724 }
3725
3726 /* The threads found on the remote target. */
3727 std::vector<thread_item> items;
3728 };
3729
3730 static int
3731 remote_newthread_step (threadref *ref, void *data)
3732 {
3733 struct threads_listing_context *context
3734 = (struct threads_listing_context *) data;
3735 int pid = inferior_ptid.pid ();
3736 int lwp = threadref_to_int (ref);
3737 ptid_t ptid (pid, lwp);
3738
3739 context->items.emplace_back (ptid);
3740
3741 return 1; /* continue iterator */
3742 }
3743
3744 #define CRAZY_MAX_THREADS 1000
3745
3746 ptid_t
3747 remote_target::remote_current_thread (ptid_t oldpid)
3748 {
3749 struct remote_state *rs = get_remote_state ();
3750
3751 putpkt ("qC");
3752 getpkt (&rs->buf, 0);
3753 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3754 {
3755 const char *obuf;
3756 ptid_t result;
3757
3758 result = read_ptid (&rs->buf[2], &obuf);
3759 if (*obuf != '\0')
3760 remote_debug_printf ("warning: garbage in qC reply");
3761
3762 return result;
3763 }
3764 else
3765 return oldpid;
3766 }
3767
3768 /* List remote threads using the deprecated qL packet. */
3769
3770 int
3771 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3772 {
3773 if (remote_threadlist_iterator (remote_newthread_step, context,
3774 CRAZY_MAX_THREADS) >= 0)
3775 return 1;
3776
3777 return 0;
3778 }
3779
3780 #if defined(HAVE_LIBEXPAT)
3781
3782 static void
3783 start_thread (struct gdb_xml_parser *parser,
3784 const struct gdb_xml_element *element,
3785 void *user_data,
3786 std::vector<gdb_xml_value> &attributes)
3787 {
3788 struct threads_listing_context *data
3789 = (struct threads_listing_context *) user_data;
3790 struct gdb_xml_value *attr;
3791
3792 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3793 ptid_t ptid = read_ptid (id, NULL);
3794
3795 data->items.emplace_back (ptid);
3796 thread_item &item = data->items.back ();
3797
3798 attr = xml_find_attribute (attributes, "core");
3799 if (attr != NULL)
3800 item.core = *(ULONGEST *) attr->value.get ();
3801
3802 attr = xml_find_attribute (attributes, "name");
3803 if (attr != NULL)
3804 item.name = (const char *) attr->value.get ();
3805
3806 attr = xml_find_attribute (attributes, "handle");
3807 if (attr != NULL)
3808 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3809 }
3810
3811 static void
3812 end_thread (struct gdb_xml_parser *parser,
3813 const struct gdb_xml_element *element,
3814 void *user_data, const char *body_text)
3815 {
3816 struct threads_listing_context *data
3817 = (struct threads_listing_context *) user_data;
3818
3819 if (body_text != NULL && *body_text != '\0')
3820 data->items.back ().extra = body_text;
3821 }
3822
3823 const struct gdb_xml_attribute thread_attributes[] = {
3824 { "id", GDB_XML_AF_NONE, NULL, NULL },
3825 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3826 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3827 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3828 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3829 };
3830
3831 const struct gdb_xml_element thread_children[] = {
3832 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3833 };
3834
3835 const struct gdb_xml_element threads_children[] = {
3836 { "thread", thread_attributes, thread_children,
3837 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3838 start_thread, end_thread },
3839 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3840 };
3841
3842 const struct gdb_xml_element threads_elements[] = {
3843 { "threads", NULL, threads_children,
3844 GDB_XML_EF_NONE, NULL, NULL },
3845 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3846 };
3847
3848 #endif
3849
3850 /* List remote threads using qXfer:threads:read. */
3851
3852 int
3853 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
3854 {
3855 #if defined(HAVE_LIBEXPAT)
3856 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3857 {
3858 gdb::optional<gdb::char_vector> xml
3859 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
3860
3861 if (xml && (*xml)[0] != '\0')
3862 {
3863 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3864 threads_elements, xml->data (), context);
3865 }
3866
3867 return 1;
3868 }
3869 #endif
3870
3871 return 0;
3872 }
3873
3874 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3875
3876 int
3877 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
3878 {
3879 struct remote_state *rs = get_remote_state ();
3880
3881 if (rs->use_threadinfo_query)
3882 {
3883 const char *bufp;
3884
3885 putpkt ("qfThreadInfo");
3886 getpkt (&rs->buf, 0);
3887 bufp = rs->buf.data ();
3888 if (bufp[0] != '\0') /* q packet recognized */
3889 {
3890 while (*bufp++ == 'm') /* reply contains one or more TID */
3891 {
3892 do
3893 {
3894 ptid_t ptid = read_ptid (bufp, &bufp);
3895 context->items.emplace_back (ptid);
3896 }
3897 while (*bufp++ == ','); /* comma-separated list */
3898 putpkt ("qsThreadInfo");
3899 getpkt (&rs->buf, 0);
3900 bufp = rs->buf.data ();
3901 }
3902 return 1;
3903 }
3904 else
3905 {
3906 /* Packet not recognized. */
3907 rs->use_threadinfo_query = 0;
3908 }
3909 }
3910
3911 return 0;
3912 }
3913
3914 /* Return true if INF only has one non-exited thread. */
3915
3916 static bool
3917 has_single_non_exited_thread (inferior *inf)
3918 {
3919 int count = 0;
3920 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
3921 if (++count > 1)
3922 break;
3923 return count == 1;
3924 }
3925
3926 /* Implement the to_update_thread_list function for the remote
3927 targets. */
3928
3929 void
3930 remote_target::update_thread_list ()
3931 {
3932 struct threads_listing_context context;
3933 int got_list = 0;
3934
3935 /* We have a few different mechanisms to fetch the thread list. Try
3936 them all, starting with the most preferred one first, falling
3937 back to older methods. */
3938 if (remote_get_threads_with_qxfer (&context)
3939 || remote_get_threads_with_qthreadinfo (&context)
3940 || remote_get_threads_with_ql (&context))
3941 {
3942 got_list = 1;
3943
3944 if (context.items.empty ()
3945 && remote_thread_always_alive (inferior_ptid))
3946 {
3947 /* Some targets don't really support threads, but still
3948 reply an (empty) thread list in response to the thread
3949 listing packets, instead of replying "packet not
3950 supported". Exit early so we don't delete the main
3951 thread. */
3952 return;
3953 }
3954
3955 /* CONTEXT now holds the current thread list on the remote
3956 target end. Delete GDB-side threads no longer found on the
3957 target. */
3958 for (thread_info *tp : all_threads_safe ())
3959 {
3960 if (tp->inf->process_target () != this)
3961 continue;
3962
3963 if (!context.contains_thread (tp->ptid))
3964 {
3965 /* Do not remove the thread if it is the last thread in
3966 the inferior. This situation happens when we have a
3967 pending exit process status to process. Otherwise we
3968 may end up with a seemingly live inferior (i.e. pid
3969 != 0) that has no threads. */
3970 if (has_single_non_exited_thread (tp->inf))
3971 continue;
3972
3973 /* Not found. */
3974 delete_thread (tp);
3975 }
3976 }
3977
3978 /* Remove any unreported fork child threads from CONTEXT so
3979 that we don't interfere with follow fork, which is where
3980 creation of such threads is handled. */
3981 remove_new_fork_children (&context);
3982
3983 /* And now add threads we don't know about yet to our list. */
3984 for (thread_item &item : context.items)
3985 {
3986 if (item.ptid != null_ptid)
3987 {
3988 /* In non-stop mode, we assume new found threads are
3989 executing until proven otherwise with a stop reply.
3990 In all-stop, we can only get here if all threads are
3991 stopped. */
3992 bool executing = target_is_non_stop_p ();
3993
3994 remote_notice_new_inferior (item.ptid, executing);
3995
3996 thread_info *tp = find_thread_ptid (this, item.ptid);
3997 remote_thread_info *info = get_remote_thread_info (tp);
3998 info->core = item.core;
3999 info->extra = std::move (item.extra);
4000 info->name = std::move (item.name);
4001 info->thread_handle = std::move (item.thread_handle);
4002 }
4003 }
4004 }
4005
4006 if (!got_list)
4007 {
4008 /* If no thread listing method is supported, then query whether
4009 each known thread is alive, one by one, with the T packet.
4010 If the target doesn't support threads at all, then this is a
4011 no-op. See remote_thread_alive. */
4012 prune_threads ();
4013 }
4014 }
4015
4016 /*
4017 * Collect a descriptive string about the given thread.
4018 * The target may say anything it wants to about the thread
4019 * (typically info about its blocked / runnable state, name, etc.).
4020 * This string will appear in the info threads display.
4021 *
4022 * Optional: targets are not required to implement this function.
4023 */
4024
4025 const char *
4026 remote_target::extra_thread_info (thread_info *tp)
4027 {
4028 struct remote_state *rs = get_remote_state ();
4029 int set;
4030 threadref id;
4031 struct gdb_ext_thread_info threadinfo;
4032
4033 if (rs->remote_desc == 0) /* paranoia */
4034 internal_error (__FILE__, __LINE__,
4035 _("remote_threads_extra_info"));
4036
4037 if (tp->ptid == magic_null_ptid
4038 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4039 /* This is the main thread which was added by GDB. The remote
4040 server doesn't know about it. */
4041 return NULL;
4042
4043 std::string &extra = get_remote_thread_info (tp)->extra;
4044
4045 /* If already have cached info, use it. */
4046 if (!extra.empty ())
4047 return extra.c_str ();
4048
4049 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4050 {
4051 /* If we're using qXfer:threads:read, then the extra info is
4052 included in the XML. So if we didn't have anything cached,
4053 it's because there's really no extra info. */
4054 return NULL;
4055 }
4056
4057 if (rs->use_threadextra_query)
4058 {
4059 char *b = rs->buf.data ();
4060 char *endb = b + get_remote_packet_size ();
4061
4062 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4063 b += strlen (b);
4064 write_ptid (b, endb, tp->ptid);
4065
4066 putpkt (rs->buf);
4067 getpkt (&rs->buf, 0);
4068 if (rs->buf[0] != 0)
4069 {
4070 extra.resize (strlen (rs->buf.data ()) / 2);
4071 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4072 return extra.c_str ();
4073 }
4074 }
4075
4076 /* If the above query fails, fall back to the old method. */
4077 rs->use_threadextra_query = 0;
4078 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4079 | TAG_MOREDISPLAY | TAG_DISPLAY;
4080 int_to_threadref (&id, tp->ptid.lwp ());
4081 if (remote_get_threadinfo (&id, set, &threadinfo))
4082 if (threadinfo.active)
4083 {
4084 if (*threadinfo.shortname)
4085 string_appendf (extra, " Name: %s", threadinfo.shortname);
4086 if (*threadinfo.display)
4087 {
4088 if (!extra.empty ())
4089 extra += ',';
4090 string_appendf (extra, " State: %s", threadinfo.display);
4091 }
4092 if (*threadinfo.more_display)
4093 {
4094 if (!extra.empty ())
4095 extra += ',';
4096 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4097 }
4098 return extra.c_str ();
4099 }
4100 return NULL;
4101 }
4102 \f
4103
4104 bool
4105 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4106 struct static_tracepoint_marker *marker)
4107 {
4108 struct remote_state *rs = get_remote_state ();
4109 char *p = rs->buf.data ();
4110
4111 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4112 p += strlen (p);
4113 p += hexnumstr (p, addr);
4114 putpkt (rs->buf);
4115 getpkt (&rs->buf, 0);
4116 p = rs->buf.data ();
4117
4118 if (*p == 'E')
4119 error (_("Remote failure reply: %s"), p);
4120
4121 if (*p++ == 'm')
4122 {
4123 parse_static_tracepoint_marker_definition (p, NULL, marker);
4124 return true;
4125 }
4126
4127 return false;
4128 }
4129
4130 std::vector<static_tracepoint_marker>
4131 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4132 {
4133 struct remote_state *rs = get_remote_state ();
4134 std::vector<static_tracepoint_marker> markers;
4135 const char *p;
4136 static_tracepoint_marker marker;
4137
4138 /* Ask for a first packet of static tracepoint marker
4139 definition. */
4140 putpkt ("qTfSTM");
4141 getpkt (&rs->buf, 0);
4142 p = rs->buf.data ();
4143 if (*p == 'E')
4144 error (_("Remote failure reply: %s"), p);
4145
4146 while (*p++ == 'm')
4147 {
4148 do
4149 {
4150 parse_static_tracepoint_marker_definition (p, &p, &marker);
4151
4152 if (strid == NULL || marker.str_id == strid)
4153 markers.push_back (std::move (marker));
4154 }
4155 while (*p++ == ','); /* comma-separated list */
4156 /* Ask for another packet of static tracepoint definition. */
4157 putpkt ("qTsSTM");
4158 getpkt (&rs->buf, 0);
4159 p = rs->buf.data ();
4160 }
4161
4162 return markers;
4163 }
4164
4165 \f
4166 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4167
4168 ptid_t
4169 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4170 {
4171 return ptid_t (inferior_ptid.pid (), lwp);
4172 }
4173 \f
4174
4175 /* Restart the remote side; this is an extended protocol operation. */
4176
4177 void
4178 remote_target::extended_remote_restart ()
4179 {
4180 struct remote_state *rs = get_remote_state ();
4181
4182 /* Send the restart command; for reasons I don't understand the
4183 remote side really expects a number after the "R". */
4184 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4185 putpkt (rs->buf);
4186
4187 remote_fileio_reset ();
4188 }
4189 \f
4190 /* Clean up connection to a remote debugger. */
4191
4192 void
4193 remote_target::close ()
4194 {
4195 /* Make sure we leave stdin registered in the event loop. */
4196 terminal_ours ();
4197
4198 trace_reset_local_state ();
4199
4200 delete this;
4201 }
4202
4203 remote_target::~remote_target ()
4204 {
4205 struct remote_state *rs = get_remote_state ();
4206
4207 /* Check for NULL because we may get here with a partially
4208 constructed target/connection. */
4209 if (rs->remote_desc == nullptr)
4210 return;
4211
4212 serial_close (rs->remote_desc);
4213
4214 /* We are destroying the remote target, so we should discard
4215 everything of this target. */
4216 discard_pending_stop_replies_in_queue ();
4217
4218 if (rs->remote_async_inferior_event_token)
4219 delete_async_event_handler (&rs->remote_async_inferior_event_token);
4220
4221 delete rs->notif_state;
4222 }
4223
4224 /* Query the remote side for the text, data and bss offsets. */
4225
4226 void
4227 remote_target::get_offsets ()
4228 {
4229 struct remote_state *rs = get_remote_state ();
4230 char *buf;
4231 char *ptr;
4232 int lose, num_segments = 0, do_sections, do_segments;
4233 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4234
4235 if (current_program_space->symfile_object_file == NULL)
4236 return;
4237
4238 putpkt ("qOffsets");
4239 getpkt (&rs->buf, 0);
4240 buf = rs->buf.data ();
4241
4242 if (buf[0] == '\000')
4243 return; /* Return silently. Stub doesn't support
4244 this command. */
4245 if (buf[0] == 'E')
4246 {
4247 warning (_("Remote failure reply: %s"), buf);
4248 return;
4249 }
4250
4251 /* Pick up each field in turn. This used to be done with scanf, but
4252 scanf will make trouble if CORE_ADDR size doesn't match
4253 conversion directives correctly. The following code will work
4254 with any size of CORE_ADDR. */
4255 text_addr = data_addr = bss_addr = 0;
4256 ptr = buf;
4257 lose = 0;
4258
4259 if (startswith (ptr, "Text="))
4260 {
4261 ptr += 5;
4262 /* Don't use strtol, could lose on big values. */
4263 while (*ptr && *ptr != ';')
4264 text_addr = (text_addr << 4) + fromhex (*ptr++);
4265
4266 if (startswith (ptr, ";Data="))
4267 {
4268 ptr += 6;
4269 while (*ptr && *ptr != ';')
4270 data_addr = (data_addr << 4) + fromhex (*ptr++);
4271 }
4272 else
4273 lose = 1;
4274
4275 if (!lose && startswith (ptr, ";Bss="))
4276 {
4277 ptr += 5;
4278 while (*ptr && *ptr != ';')
4279 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4280
4281 if (bss_addr != data_addr)
4282 warning (_("Target reported unsupported offsets: %s"), buf);
4283 }
4284 else
4285 lose = 1;
4286 }
4287 else if (startswith (ptr, "TextSeg="))
4288 {
4289 ptr += 8;
4290 /* Don't use strtol, could lose on big values. */
4291 while (*ptr && *ptr != ';')
4292 text_addr = (text_addr << 4) + fromhex (*ptr++);
4293 num_segments = 1;
4294
4295 if (startswith (ptr, ";DataSeg="))
4296 {
4297 ptr += 9;
4298 while (*ptr && *ptr != ';')
4299 data_addr = (data_addr << 4) + fromhex (*ptr++);
4300 num_segments++;
4301 }
4302 }
4303 else
4304 lose = 1;
4305
4306 if (lose)
4307 error (_("Malformed response to offset query, %s"), buf);
4308 else if (*ptr != '\0')
4309 warning (_("Target reported unsupported offsets: %s"), buf);
4310
4311 objfile *objf = current_program_space->symfile_object_file;
4312 section_offsets offs = objf->section_offsets;
4313
4314 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd);
4315 do_segments = (data != NULL);
4316 do_sections = num_segments == 0;
4317
4318 if (num_segments > 0)
4319 {
4320 segments[0] = text_addr;
4321 segments[1] = data_addr;
4322 }
4323 /* If we have two segments, we can still try to relocate everything
4324 by assuming that the .text and .data offsets apply to the whole
4325 text and data segments. Convert the offsets given in the packet
4326 to base addresses for symfile_map_offsets_to_segments. */
4327 else if (data != nullptr && data->segments.size () == 2)
4328 {
4329 segments[0] = data->segments[0].base + text_addr;
4330 segments[1] = data->segments[1].base + data_addr;
4331 num_segments = 2;
4332 }
4333 /* If the object file has only one segment, assume that it is text
4334 rather than data; main programs with no writable data are rare,
4335 but programs with no code are useless. Of course the code might
4336 have ended up in the data segment... to detect that we would need
4337 the permissions here. */
4338 else if (data && data->segments.size () == 1)
4339 {
4340 segments[0] = data->segments[0].base + text_addr;
4341 num_segments = 1;
4342 }
4343 /* There's no way to relocate by segment. */
4344 else
4345 do_segments = 0;
4346
4347 if (do_segments)
4348 {
4349 int ret = symfile_map_offsets_to_segments (objf->obfd,
4350 data.get (), offs,
4351 num_segments, segments);
4352
4353 if (ret == 0 && !do_sections)
4354 error (_("Can not handle qOffsets TextSeg "
4355 "response with this symbol file"));
4356
4357 if (ret > 0)
4358 do_sections = 0;
4359 }
4360
4361 if (do_sections)
4362 {
4363 offs[SECT_OFF_TEXT (objf)] = text_addr;
4364
4365 /* This is a temporary kludge to force data and bss to use the
4366 same offsets because that's what nlmconv does now. The real
4367 solution requires changes to the stub and remote.c that I
4368 don't have time to do right now. */
4369
4370 offs[SECT_OFF_DATA (objf)] = data_addr;
4371 offs[SECT_OFF_BSS (objf)] = data_addr;
4372 }
4373
4374 objfile_relocate (objf, offs);
4375 }
4376
4377 /* Send interrupt_sequence to remote target. */
4378
4379 void
4380 remote_target::send_interrupt_sequence ()
4381 {
4382 struct remote_state *rs = get_remote_state ();
4383
4384 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4385 remote_serial_write ("\x03", 1);
4386 else if (interrupt_sequence_mode == interrupt_sequence_break)
4387 serial_send_break (rs->remote_desc);
4388 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4389 {
4390 serial_send_break (rs->remote_desc);
4391 remote_serial_write ("g", 1);
4392 }
4393 else
4394 internal_error (__FILE__, __LINE__,
4395 _("Invalid value for interrupt_sequence_mode: %s."),
4396 interrupt_sequence_mode);
4397 }
4398
4399
4400 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4401 and extract the PTID. Returns NULL_PTID if not found. */
4402
4403 static ptid_t
4404 stop_reply_extract_thread (const char *stop_reply)
4405 {
4406 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4407 {
4408 const char *p;
4409
4410 /* Txx r:val ; r:val (...) */
4411 p = &stop_reply[3];
4412
4413 /* Look for "register" named "thread". */
4414 while (*p != '\0')
4415 {
4416 const char *p1;
4417
4418 p1 = strchr (p, ':');
4419 if (p1 == NULL)
4420 return null_ptid;
4421
4422 if (strncmp (p, "thread", p1 - p) == 0)
4423 return read_ptid (++p1, &p);
4424
4425 p1 = strchr (p, ';');
4426 if (p1 == NULL)
4427 return null_ptid;
4428 p1++;
4429
4430 p = p1;
4431 }
4432 }
4433
4434 return null_ptid;
4435 }
4436
4437 /* Determine the remote side's current thread. If we have a stop
4438 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4439 "thread" register we can extract the current thread from. If not,
4440 ask the remote which is the current thread with qC. The former
4441 method avoids a roundtrip. */
4442
4443 ptid_t
4444 remote_target::get_current_thread (const char *wait_status)
4445 {
4446 ptid_t ptid = null_ptid;
4447
4448 /* Note we don't use remote_parse_stop_reply as that makes use of
4449 the target architecture, which we haven't yet fully determined at
4450 this point. */
4451 if (wait_status != NULL)
4452 ptid = stop_reply_extract_thread (wait_status);
4453 if (ptid == null_ptid)
4454 ptid = remote_current_thread (inferior_ptid);
4455
4456 return ptid;
4457 }
4458
4459 /* Query the remote target for which is the current thread/process,
4460 add it to our tables, and update INFERIOR_PTID. The caller is
4461 responsible for setting the state such that the remote end is ready
4462 to return the current thread.
4463
4464 This function is called after handling the '?' or 'vRun' packets,
4465 whose response is a stop reply from which we can also try
4466 extracting the thread. If the target doesn't support the explicit
4467 qC query, we infer the current thread from that stop reply, passed
4468 in in WAIT_STATUS, which may be NULL.
4469
4470 The function returns pointer to the main thread of the inferior. */
4471
4472 thread_info *
4473 remote_target::add_current_inferior_and_thread (const char *wait_status)
4474 {
4475 struct remote_state *rs = get_remote_state ();
4476 bool fake_pid_p = false;
4477
4478 switch_to_no_thread ();
4479
4480 /* Now, if we have thread information, update the current thread's
4481 ptid. */
4482 ptid_t curr_ptid = get_current_thread (wait_status);
4483
4484 if (curr_ptid != null_ptid)
4485 {
4486 if (!remote_multi_process_p (rs))
4487 fake_pid_p = true;
4488 }
4489 else
4490 {
4491 /* Without this, some commands which require an active target
4492 (such as kill) won't work. This variable serves (at least)
4493 double duty as both the pid of the target process (if it has
4494 such), and as a flag indicating that a target is active. */
4495 curr_ptid = magic_null_ptid;
4496 fake_pid_p = true;
4497 }
4498
4499 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4500
4501 /* Add the main thread and switch to it. Don't try reading
4502 registers yet, since we haven't fetched the target description
4503 yet. */
4504 thread_info *tp = add_thread_silent (this, curr_ptid);
4505 switch_to_thread_no_regs (tp);
4506
4507 return tp;
4508 }
4509
4510 /* Print info about a thread that was found already stopped on
4511 connection. */
4512
4513 void
4514 remote_target::print_one_stopped_thread (thread_info *thread)
4515 {
4516 target_waitstatus ws;
4517
4518 /* If there is a pending waitstatus, use it. If there isn't it's because
4519 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4520 and process_initial_stop_replies decided it wasn't interesting to save
4521 and report to the core. */
4522 if (thread->has_pending_waitstatus ())
4523 {
4524 ws = thread->pending_waitstatus ();
4525 thread->clear_pending_waitstatus ();
4526 }
4527 else
4528 {
4529 ws.set_stopped (GDB_SIGNAL_0);
4530 }
4531
4532 switch_to_thread (thread);
4533 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4534 set_current_sal_from_frame (get_current_frame ());
4535
4536 /* For "info program". */
4537 set_last_target_status (this, thread->ptid, ws);
4538
4539 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4540 {
4541 enum gdb_signal sig = ws.sig ();
4542
4543 if (signal_print_state (sig))
4544 gdb::observers::signal_received.notify (sig);
4545 }
4546 gdb::observers::normal_stop.notify (NULL, 1);
4547 }
4548
4549 /* Process all initial stop replies the remote side sent in response
4550 to the ? packet. These indicate threads that were already stopped
4551 on initial connection. We mark these threads as stopped and print
4552 their current frame before giving the user the prompt. */
4553
4554 void
4555 remote_target::process_initial_stop_replies (int from_tty)
4556 {
4557 int pending_stop_replies = stop_reply_queue_length ();
4558 struct thread_info *selected = NULL;
4559 struct thread_info *lowest_stopped = NULL;
4560 struct thread_info *first = NULL;
4561
4562 /* This is only used when the target is non-stop. */
4563 gdb_assert (target_is_non_stop_p ());
4564
4565 /* Consume the initial pending events. */
4566 while (pending_stop_replies-- > 0)
4567 {
4568 ptid_t waiton_ptid = minus_one_ptid;
4569 ptid_t event_ptid;
4570 struct target_waitstatus ws;
4571 int ignore_event = 0;
4572
4573 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4574 if (remote_debug)
4575 print_target_wait_results (waiton_ptid, event_ptid, ws);
4576
4577 switch (ws.kind ())
4578 {
4579 case TARGET_WAITKIND_IGNORE:
4580 case TARGET_WAITKIND_NO_RESUMED:
4581 case TARGET_WAITKIND_SIGNALLED:
4582 case TARGET_WAITKIND_EXITED:
4583 /* We shouldn't see these, but if we do, just ignore. */
4584 remote_debug_printf ("event ignored");
4585 ignore_event = 1;
4586 break;
4587
4588 default:
4589 break;
4590 }
4591
4592 if (ignore_event)
4593 continue;
4594
4595 thread_info *evthread = find_thread_ptid (this, event_ptid);
4596
4597 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4598 {
4599 enum gdb_signal sig = ws.sig ();
4600
4601 /* Stubs traditionally report SIGTRAP as initial signal,
4602 instead of signal 0. Suppress it. */
4603 if (sig == GDB_SIGNAL_TRAP)
4604 sig = GDB_SIGNAL_0;
4605 evthread->set_stop_signal (sig);
4606 ws.set_stopped (sig);
4607 }
4608
4609 if (ws.kind () != TARGET_WAITKIND_STOPPED
4610 || ws.sig () != GDB_SIGNAL_0)
4611 evthread->set_pending_waitstatus (ws);
4612
4613 set_executing (this, event_ptid, false);
4614 set_running (this, event_ptid, false);
4615 get_remote_thread_info (evthread)->set_not_resumed ();
4616 }
4617
4618 /* "Notice" the new inferiors before anything related to
4619 registers/memory. */
4620 for (inferior *inf : all_non_exited_inferiors (this))
4621 {
4622 inf->needs_setup = 1;
4623
4624 if (non_stop)
4625 {
4626 thread_info *thread = any_live_thread_of_inferior (inf);
4627 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4628 from_tty);
4629 }
4630 }
4631
4632 /* If all-stop on top of non-stop, pause all threads. Note this
4633 records the threads' stop pc, so must be done after "noticing"
4634 the inferiors. */
4635 if (!non_stop)
4636 {
4637 {
4638 /* At this point, the remote target is not async. It needs to be for
4639 the poll in stop_all_threads to consider events from it, so enable
4640 it temporarily. */
4641 gdb_assert (!this->is_async_p ());
4642 SCOPE_EXIT { target_async (0); };
4643 target_async (1);
4644 stop_all_threads ();
4645 }
4646
4647 /* If all threads of an inferior were already stopped, we
4648 haven't setup the inferior yet. */
4649 for (inferior *inf : all_non_exited_inferiors (this))
4650 {
4651 if (inf->needs_setup)
4652 {
4653 thread_info *thread = any_live_thread_of_inferior (inf);
4654 switch_to_thread_no_regs (thread);
4655 setup_inferior (0);
4656 }
4657 }
4658 }
4659
4660 /* Now go over all threads that are stopped, and print their current
4661 frame. If all-stop, then if there's a signalled thread, pick
4662 that as current. */
4663 for (thread_info *thread : all_non_exited_threads (this))
4664 {
4665 if (first == NULL)
4666 first = thread;
4667
4668 if (!non_stop)
4669 thread->set_running (false);
4670 else if (thread->state != THREAD_STOPPED)
4671 continue;
4672
4673 if (selected == nullptr && thread->has_pending_waitstatus ())
4674 selected = thread;
4675
4676 if (lowest_stopped == NULL
4677 || thread->inf->num < lowest_stopped->inf->num
4678 || thread->per_inf_num < lowest_stopped->per_inf_num)
4679 lowest_stopped = thread;
4680
4681 if (non_stop)
4682 print_one_stopped_thread (thread);
4683 }
4684
4685 /* In all-stop, we only print the status of one thread, and leave
4686 others with their status pending. */
4687 if (!non_stop)
4688 {
4689 thread_info *thread = selected;
4690 if (thread == NULL)
4691 thread = lowest_stopped;
4692 if (thread == NULL)
4693 thread = first;
4694
4695 print_one_stopped_thread (thread);
4696 }
4697 }
4698
4699 /* Mark a remote_target as marking (by setting the starting_up flag within
4700 its remote_state) for the lifetime of this object. The reference count
4701 on the remote target is temporarily incremented, to prevent the target
4702 being deleted under our feet. */
4703
4704 struct scoped_mark_target_starting
4705 {
4706 /* Constructor, TARGET is the target to be marked as starting, its
4707 reference count will be incremented. */
4708 scoped_mark_target_starting (remote_target *target)
4709 : m_remote_target (target)
4710 {
4711 m_remote_target->incref ();
4712 remote_state *rs = m_remote_target->get_remote_state ();
4713 rs->starting_up = true;
4714 }
4715
4716 /* Destructor, mark the target being worked on as no longer starting, and
4717 decrement the reference count. */
4718 ~scoped_mark_target_starting ()
4719 {
4720 remote_state *rs = m_remote_target->get_remote_state ();
4721 rs->starting_up = false;
4722 decref_target (m_remote_target);
4723 }
4724
4725 private:
4726
4727 /* The target on which we are operating. */
4728 remote_target *m_remote_target;
4729 };
4730
4731 /* Helper for remote_target::start_remote, start the remote connection and
4732 sync state. Return true if everything goes OK, otherwise, return false.
4733 This function exists so that the scoped_restore created within it will
4734 expire before we return to remote_target::start_remote. */
4735
4736 bool
4737 remote_target::start_remote_1 (int from_tty, int extended_p)
4738 {
4739 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4740
4741 struct remote_state *rs = get_remote_state ();
4742 struct packet_config *noack_config;
4743
4744 /* Signal other parts that we're going through the initial setup,
4745 and so things may not be stable yet. E.g., we don't try to
4746 install tracepoints until we've relocated symbols. Also, a
4747 Ctrl-C before we're connected and synced up can't interrupt the
4748 target. Instead, it offers to drop the (potentially wedged)
4749 connection. */
4750 scoped_mark_target_starting target_is_starting (this);
4751
4752 QUIT;
4753
4754 if (interrupt_on_connect)
4755 send_interrupt_sequence ();
4756
4757 /* Ack any packet which the remote side has already sent. */
4758 remote_serial_write ("+", 1);
4759
4760 /* The first packet we send to the target is the optional "supported
4761 packets" request. If the target can answer this, it will tell us
4762 which later probes to skip. */
4763 remote_query_supported ();
4764
4765 /* If the stub wants to get a QAllow, compose one and send it. */
4766 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4767 set_permissions ();
4768
4769 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4770 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4771 as a reply to known packet. For packet "vFile:setfs:" it is an
4772 invalid reply and GDB would return error in
4773 remote_hostio_set_filesystem, making remote files access impossible.
4774 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4775 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4776 {
4777 const char v_mustreplyempty[] = "vMustReplyEmpty";
4778
4779 putpkt (v_mustreplyempty);
4780 getpkt (&rs->buf, 0);
4781 if (strcmp (rs->buf.data (), "OK") == 0)
4782 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4783 else if (strcmp (rs->buf.data (), "") != 0)
4784 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4785 rs->buf.data ());
4786 }
4787
4788 /* Next, we possibly activate noack mode.
4789
4790 If the QStartNoAckMode packet configuration is set to AUTO,
4791 enable noack mode if the stub reported a wish for it with
4792 qSupported.
4793
4794 If set to TRUE, then enable noack mode even if the stub didn't
4795 report it in qSupported. If the stub doesn't reply OK, the
4796 session ends with an error.
4797
4798 If FALSE, then don't activate noack mode, regardless of what the
4799 stub claimed should be the default with qSupported. */
4800
4801 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4802 if (packet_config_support (noack_config) != PACKET_DISABLE)
4803 {
4804 putpkt ("QStartNoAckMode");
4805 getpkt (&rs->buf, 0);
4806 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4807 rs->noack_mode = 1;
4808 }
4809
4810 if (extended_p)
4811 {
4812 /* Tell the remote that we are using the extended protocol. */
4813 putpkt ("!");
4814 getpkt (&rs->buf, 0);
4815 }
4816
4817 /* Let the target know which signals it is allowed to pass down to
4818 the program. */
4819 update_signals_program_target ();
4820
4821 /* Next, if the target can specify a description, read it. We do
4822 this before anything involving memory or registers. */
4823 target_find_description ();
4824
4825 /* Next, now that we know something about the target, update the
4826 address spaces in the program spaces. */
4827 update_address_spaces ();
4828
4829 /* On OSs where the list of libraries is global to all
4830 processes, we fetch them early. */
4831 if (gdbarch_has_global_solist (target_gdbarch ()))
4832 solib_add (NULL, from_tty, auto_solib_add);
4833
4834 if (target_is_non_stop_p ())
4835 {
4836 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4837 error (_("Non-stop mode requested, but remote "
4838 "does not support non-stop"));
4839
4840 putpkt ("QNonStop:1");
4841 getpkt (&rs->buf, 0);
4842
4843 if (strcmp (rs->buf.data (), "OK") != 0)
4844 error (_("Remote refused setting non-stop mode with: %s"),
4845 rs->buf.data ());
4846
4847 /* Find about threads and processes the stub is already
4848 controlling. We default to adding them in the running state.
4849 The '?' query below will then tell us about which threads are
4850 stopped. */
4851 this->update_thread_list ();
4852 }
4853 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4854 {
4855 /* Don't assume that the stub can operate in all-stop mode.
4856 Request it explicitly. */
4857 putpkt ("QNonStop:0");
4858 getpkt (&rs->buf, 0);
4859
4860 if (strcmp (rs->buf.data (), "OK") != 0)
4861 error (_("Remote refused setting all-stop mode with: %s"),
4862 rs->buf.data ());
4863 }
4864
4865 /* Upload TSVs regardless of whether the target is running or not. The
4866 remote stub, such as GDBserver, may have some predefined or builtin
4867 TSVs, even if the target is not running. */
4868 if (get_trace_status (current_trace_status ()) != -1)
4869 {
4870 struct uploaded_tsv *uploaded_tsvs = NULL;
4871
4872 upload_trace_state_variables (&uploaded_tsvs);
4873 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4874 }
4875
4876 /* Check whether the target is running now. */
4877 putpkt ("?");
4878 getpkt (&rs->buf, 0);
4879
4880 if (!target_is_non_stop_p ())
4881 {
4882 char *wait_status = NULL;
4883
4884 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4885 {
4886 if (!extended_p)
4887 error (_("The target is not running (try extended-remote?)"));
4888 return false;
4889 }
4890 else
4891 {
4892 /* Save the reply for later. */
4893 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
4894 strcpy (wait_status, rs->buf.data ());
4895 }
4896
4897 /* Fetch thread list. */
4898 target_update_thread_list ();
4899
4900 /* Let the stub know that we want it to return the thread. */
4901 set_continue_thread (minus_one_ptid);
4902
4903 if (thread_count (this) == 0)
4904 {
4905 /* Target has no concept of threads at all. GDB treats
4906 non-threaded target as single-threaded; add a main
4907 thread. */
4908 thread_info *tp = add_current_inferior_and_thread (wait_status);
4909 get_remote_thread_info (tp)->set_resumed ();
4910 }
4911 else
4912 {
4913 /* We have thread information; select the thread the target
4914 says should be current. If we're reconnecting to a
4915 multi-threaded program, this will ideally be the thread
4916 that last reported an event before GDB disconnected. */
4917 ptid_t curr_thread = get_current_thread (wait_status);
4918 if (curr_thread == null_ptid)
4919 {
4920 /* Odd... The target was able to list threads, but not
4921 tell us which thread was current (no "thread"
4922 register in T stop reply?). Just pick the first
4923 thread in the thread list then. */
4924
4925 remote_debug_printf ("warning: couldn't determine remote "
4926 "current thread; picking first in list.");
4927
4928 for (thread_info *tp : all_non_exited_threads (this,
4929 minus_one_ptid))
4930 {
4931 switch_to_thread (tp);
4932 break;
4933 }
4934 }
4935 else
4936 switch_to_thread (find_thread_ptid (this, curr_thread));
4937 }
4938
4939 /* init_wait_for_inferior should be called before get_offsets in order
4940 to manage `inserted' flag in bp loc in a correct state.
4941 breakpoint_init_inferior, called from init_wait_for_inferior, set
4942 `inserted' flag to 0, while before breakpoint_re_set, called from
4943 start_remote, set `inserted' flag to 1. In the initialization of
4944 inferior, breakpoint_init_inferior should be called first, and then
4945 breakpoint_re_set can be called. If this order is broken, state of
4946 `inserted' flag is wrong, and cause some problems on breakpoint
4947 manipulation. */
4948 init_wait_for_inferior ();
4949
4950 get_offsets (); /* Get text, data & bss offsets. */
4951
4952 /* If we could not find a description using qXfer, and we know
4953 how to do it some other way, try again. This is not
4954 supported for non-stop; it could be, but it is tricky if
4955 there are no stopped threads when we connect. */
4956 if (remote_read_description_p (this)
4957 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4958 {
4959 target_clear_description ();
4960 target_find_description ();
4961 }
4962
4963 /* Use the previously fetched status. */
4964 gdb_assert (wait_status != NULL);
4965 struct notif_event *reply
4966 = remote_notif_parse (this, &notif_client_stop, wait_status);
4967 push_stop_reply ((struct stop_reply *) reply);
4968
4969 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
4970 }
4971 else
4972 {
4973 /* Clear WFI global state. Do this before finding about new
4974 threads and inferiors, and setting the current inferior.
4975 Otherwise we would clear the proceed status of the current
4976 inferior when we want its stop_soon state to be preserved
4977 (see notice_new_inferior). */
4978 init_wait_for_inferior ();
4979
4980 /* In non-stop, we will either get an "OK", meaning that there
4981 are no stopped threads at this time; or, a regular stop
4982 reply. In the latter case, there may be more than one thread
4983 stopped --- we pull them all out using the vStopped
4984 mechanism. */
4985 if (strcmp (rs->buf.data (), "OK") != 0)
4986 {
4987 struct notif_client *notif = &notif_client_stop;
4988
4989 /* remote_notif_get_pending_replies acks this one, and gets
4990 the rest out. */
4991 rs->notif_state->pending_event[notif_client_stop.id]
4992 = remote_notif_parse (this, notif, rs->buf.data ());
4993 remote_notif_get_pending_events (notif);
4994 }
4995
4996 if (thread_count (this) == 0)
4997 {
4998 if (!extended_p)
4999 error (_("The target is not running (try extended-remote?)"));
5000 return false;
5001 }
5002
5003 /* Report all signals during attach/startup. */
5004 pass_signals ({});
5005
5006 /* If there are already stopped threads, mark them stopped and
5007 report their stops before giving the prompt to the user. */
5008 process_initial_stop_replies (from_tty);
5009
5010 if (target_can_async_p ())
5011 target_async (1);
5012 }
5013
5014 /* If we connected to a live target, do some additional setup. */
5015 if (target_has_execution ())
5016 {
5017 /* No use without a symbol-file. */
5018 if (current_program_space->symfile_object_file)
5019 remote_check_symbols ();
5020 }
5021
5022 /* Possibly the target has been engaged in a trace run started
5023 previously; find out where things are at. */
5024 if (get_trace_status (current_trace_status ()) != -1)
5025 {
5026 struct uploaded_tp *uploaded_tps = NULL;
5027
5028 if (current_trace_status ()->running)
5029 printf_filtered (_("Trace is already running on the target.\n"));
5030
5031 upload_tracepoints (&uploaded_tps);
5032
5033 merge_uploaded_tracepoints (&uploaded_tps);
5034 }
5035
5036 /* Possibly the target has been engaged in a btrace record started
5037 previously; find out where things are at. */
5038 remote_btrace_maybe_reopen ();
5039
5040 return true;
5041 }
5042
5043 /* Start the remote connection and sync state. */
5044
5045 void
5046 remote_target::start_remote (int from_tty, int extended_p)
5047 {
5048 if (start_remote_1 (from_tty, extended_p)
5049 && breakpoints_should_be_inserted_now ())
5050 insert_breakpoints ();
5051 }
5052
5053 const char *
5054 remote_target::connection_string ()
5055 {
5056 remote_state *rs = get_remote_state ();
5057
5058 if (rs->remote_desc->name != NULL)
5059 return rs->remote_desc->name;
5060 else
5061 return NULL;
5062 }
5063
5064 /* Open a connection to a remote debugger.
5065 NAME is the filename used for communication. */
5066
5067 void
5068 remote_target::open (const char *name, int from_tty)
5069 {
5070 open_1 (name, from_tty, 0);
5071 }
5072
5073 /* Open a connection to a remote debugger using the extended
5074 remote gdb protocol. NAME is the filename used for communication. */
5075
5076 void
5077 extended_remote_target::open (const char *name, int from_tty)
5078 {
5079 open_1 (name, from_tty, 1 /*extended_p */);
5080 }
5081
5082 /* Reset all packets back to "unknown support". Called when opening a
5083 new connection to a remote target. */
5084
5085 static void
5086 reset_all_packet_configs_support (void)
5087 {
5088 int i;
5089
5090 for (i = 0; i < PACKET_MAX; i++)
5091 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5092 }
5093
5094 /* Initialize all packet configs. */
5095
5096 static void
5097 init_all_packet_configs (void)
5098 {
5099 int i;
5100
5101 for (i = 0; i < PACKET_MAX; i++)
5102 {
5103 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5104 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5105 }
5106 }
5107
5108 /* Symbol look-up. */
5109
5110 void
5111 remote_target::remote_check_symbols ()
5112 {
5113 char *tmp;
5114 int end;
5115
5116 /* The remote side has no concept of inferiors that aren't running
5117 yet, it only knows about running processes. If we're connected
5118 but our current inferior is not running, we should not invite the
5119 remote target to request symbol lookups related to its
5120 (unrelated) current process. */
5121 if (!target_has_execution ())
5122 return;
5123
5124 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5125 return;
5126
5127 /* Make sure the remote is pointing at the right process. Note
5128 there's no way to select "no process". */
5129 set_general_process ();
5130
5131 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5132 because we need both at the same time. */
5133 gdb::char_vector msg (get_remote_packet_size ());
5134 gdb::char_vector reply (get_remote_packet_size ());
5135
5136 /* Invite target to request symbol lookups. */
5137
5138 putpkt ("qSymbol::");
5139 getpkt (&reply, 0);
5140 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
5141
5142 while (startswith (reply.data (), "qSymbol:"))
5143 {
5144 struct bound_minimal_symbol sym;
5145
5146 tmp = &reply[8];
5147 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5148 strlen (tmp) / 2);
5149 msg[end] = '\0';
5150 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5151 if (sym.minsym == NULL)
5152 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5153 &reply[8]);
5154 else
5155 {
5156 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5157 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
5158
5159 /* If this is a function address, return the start of code
5160 instead of any data function descriptor. */
5161 sym_addr = gdbarch_convert_from_func_ptr_addr
5162 (target_gdbarch (), sym_addr, current_inferior ()->top_target ());
5163
5164 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5165 phex_nz (sym_addr, addr_size), &reply[8]);
5166 }
5167
5168 putpkt (msg.data ());
5169 getpkt (&reply, 0);
5170 }
5171 }
5172
5173 static struct serial *
5174 remote_serial_open (const char *name)
5175 {
5176 static int udp_warning = 0;
5177
5178 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5179 of in ser-tcp.c, because it is the remote protocol assuming that the
5180 serial connection is reliable and not the serial connection promising
5181 to be. */
5182 if (!udp_warning && startswith (name, "udp:"))
5183 {
5184 warning (_("The remote protocol may be unreliable over UDP.\n"
5185 "Some events may be lost, rendering further debugging "
5186 "impossible."));
5187 udp_warning = 1;
5188 }
5189
5190 return serial_open (name);
5191 }
5192
5193 /* Inform the target of our permission settings. The permission flags
5194 work without this, but if the target knows the settings, it can do
5195 a couple things. First, it can add its own check, to catch cases
5196 that somehow manage to get by the permissions checks in target
5197 methods. Second, if the target is wired to disallow particular
5198 settings (for instance, a system in the field that is not set up to
5199 be able to stop at a breakpoint), it can object to any unavailable
5200 permissions. */
5201
5202 void
5203 remote_target::set_permissions ()
5204 {
5205 struct remote_state *rs = get_remote_state ();
5206
5207 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5208 "WriteReg:%x;WriteMem:%x;"
5209 "InsertBreak:%x;InsertTrace:%x;"
5210 "InsertFastTrace:%x;Stop:%x",
5211 may_write_registers, may_write_memory,
5212 may_insert_breakpoints, may_insert_tracepoints,
5213 may_insert_fast_tracepoints, may_stop);
5214 putpkt (rs->buf);
5215 getpkt (&rs->buf, 0);
5216
5217 /* If the target didn't like the packet, warn the user. Do not try
5218 to undo the user's settings, that would just be maddening. */
5219 if (strcmp (rs->buf.data (), "OK") != 0)
5220 warning (_("Remote refused setting permissions with: %s"),
5221 rs->buf.data ());
5222 }
5223
5224 /* This type describes each known response to the qSupported
5225 packet. */
5226 struct protocol_feature
5227 {
5228 /* The name of this protocol feature. */
5229 const char *name;
5230
5231 /* The default for this protocol feature. */
5232 enum packet_support default_support;
5233
5234 /* The function to call when this feature is reported, or after
5235 qSupported processing if the feature is not supported.
5236 The first argument points to this structure. The second
5237 argument indicates whether the packet requested support be
5238 enabled, disabled, or probed (or the default, if this function
5239 is being called at the end of processing and this feature was
5240 not reported). The third argument may be NULL; if not NULL, it
5241 is a NUL-terminated string taken from the packet following
5242 this feature's name and an equals sign. */
5243 void (*func) (remote_target *remote, const struct protocol_feature *,
5244 enum packet_support, const char *);
5245
5246 /* The corresponding packet for this feature. Only used if
5247 FUNC is remote_supported_packet. */
5248 int packet;
5249 };
5250
5251 static void
5252 remote_supported_packet (remote_target *remote,
5253 const struct protocol_feature *feature,
5254 enum packet_support support,
5255 const char *argument)
5256 {
5257 if (argument)
5258 {
5259 warning (_("Remote qSupported response supplied an unexpected value for"
5260 " \"%s\"."), feature->name);
5261 return;
5262 }
5263
5264 remote_protocol_packets[feature->packet].support = support;
5265 }
5266
5267 void
5268 remote_target::remote_packet_size (const protocol_feature *feature,
5269 enum packet_support support, const char *value)
5270 {
5271 struct remote_state *rs = get_remote_state ();
5272
5273 int packet_size;
5274 char *value_end;
5275
5276 if (support != PACKET_ENABLE)
5277 return;
5278
5279 if (value == NULL || *value == '\0')
5280 {
5281 warning (_("Remote target reported \"%s\" without a size."),
5282 feature->name);
5283 return;
5284 }
5285
5286 errno = 0;
5287 packet_size = strtol (value, &value_end, 16);
5288 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5289 {
5290 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5291 feature->name, value);
5292 return;
5293 }
5294
5295 /* Record the new maximum packet size. */
5296 rs->explicit_packet_size = packet_size;
5297 }
5298
5299 static void
5300 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5301 enum packet_support support, const char *value)
5302 {
5303 remote->remote_packet_size (feature, support, value);
5304 }
5305
5306 static const struct protocol_feature remote_protocol_features[] = {
5307 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5308 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5309 PACKET_qXfer_auxv },
5310 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5311 PACKET_qXfer_exec_file },
5312 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5313 PACKET_qXfer_features },
5314 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5315 PACKET_qXfer_libraries },
5316 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5317 PACKET_qXfer_libraries_svr4 },
5318 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5319 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5320 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5321 PACKET_qXfer_memory_map },
5322 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5323 PACKET_qXfer_osdata },
5324 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5325 PACKET_qXfer_threads },
5326 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5327 PACKET_qXfer_traceframe_info },
5328 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5329 PACKET_QPassSignals },
5330 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5331 PACKET_QCatchSyscalls },
5332 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5333 PACKET_QProgramSignals },
5334 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5335 PACKET_QSetWorkingDir },
5336 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5337 PACKET_QStartupWithShell },
5338 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5339 PACKET_QEnvironmentHexEncoded },
5340 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5341 PACKET_QEnvironmentReset },
5342 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5343 PACKET_QEnvironmentUnset },
5344 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5345 PACKET_QStartNoAckMode },
5346 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5347 PACKET_multiprocess_feature },
5348 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5349 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5350 PACKET_qXfer_siginfo_read },
5351 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5352 PACKET_qXfer_siginfo_write },
5353 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5354 PACKET_ConditionalTracepoints },
5355 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5356 PACKET_ConditionalBreakpoints },
5357 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5358 PACKET_BreakpointCommands },
5359 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5360 PACKET_FastTracepoints },
5361 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5362 PACKET_StaticTracepoints },
5363 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5364 PACKET_InstallInTrace},
5365 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5366 PACKET_DisconnectedTracing_feature },
5367 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5368 PACKET_bc },
5369 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5370 PACKET_bs },
5371 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5372 PACKET_TracepointSource },
5373 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5374 PACKET_QAllow },
5375 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5376 PACKET_EnableDisableTracepoints_feature },
5377 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5378 PACKET_qXfer_fdpic },
5379 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5380 PACKET_qXfer_uib },
5381 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5382 PACKET_QDisableRandomization },
5383 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5384 { "QTBuffer:size", PACKET_DISABLE,
5385 remote_supported_packet, PACKET_QTBuffer_size},
5386 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5387 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5388 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5389 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5390 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5391 PACKET_qXfer_btrace },
5392 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5393 PACKET_qXfer_btrace_conf },
5394 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5395 PACKET_Qbtrace_conf_bts_size },
5396 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5397 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5398 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5399 PACKET_fork_event_feature },
5400 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5401 PACKET_vfork_event_feature },
5402 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5403 PACKET_exec_event_feature },
5404 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5405 PACKET_Qbtrace_conf_pt_size },
5406 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5407 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5408 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5409 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5410 PACKET_memory_tagging_feature },
5411 };
5412
5413 static char *remote_support_xml;
5414
5415 /* Register string appended to "xmlRegisters=" in qSupported query. */
5416
5417 void
5418 register_remote_support_xml (const char *xml)
5419 {
5420 #if defined(HAVE_LIBEXPAT)
5421 if (remote_support_xml == NULL)
5422 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5423 else
5424 {
5425 char *copy = xstrdup (remote_support_xml + 13);
5426 char *saveptr;
5427 char *p = strtok_r (copy, ",", &saveptr);
5428
5429 do
5430 {
5431 if (strcmp (p, xml) == 0)
5432 {
5433 /* already there */
5434 xfree (copy);
5435 return;
5436 }
5437 }
5438 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5439 xfree (copy);
5440
5441 remote_support_xml = reconcat (remote_support_xml,
5442 remote_support_xml, ",", xml,
5443 (char *) NULL);
5444 }
5445 #endif
5446 }
5447
5448 static void
5449 remote_query_supported_append (std::string *msg, const char *append)
5450 {
5451 if (!msg->empty ())
5452 msg->append (";");
5453 msg->append (append);
5454 }
5455
5456 void
5457 remote_target::remote_query_supported ()
5458 {
5459 struct remote_state *rs = get_remote_state ();
5460 char *next;
5461 int i;
5462 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5463
5464 /* The packet support flags are handled differently for this packet
5465 than for most others. We treat an error, a disabled packet, and
5466 an empty response identically: any features which must be reported
5467 to be used will be automatically disabled. An empty buffer
5468 accomplishes this, since that is also the representation for a list
5469 containing no features. */
5470
5471 rs->buf[0] = 0;
5472 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5473 {
5474 std::string q;
5475
5476 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5477 remote_query_supported_append (&q, "multiprocess+");
5478
5479 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5480 remote_query_supported_append (&q, "swbreak+");
5481 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5482 remote_query_supported_append (&q, "hwbreak+");
5483
5484 remote_query_supported_append (&q, "qRelocInsn+");
5485
5486 if (packet_set_cmd_state (PACKET_fork_event_feature)
5487 != AUTO_BOOLEAN_FALSE)
5488 remote_query_supported_append (&q, "fork-events+");
5489 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5490 != AUTO_BOOLEAN_FALSE)
5491 remote_query_supported_append (&q, "vfork-events+");
5492 if (packet_set_cmd_state (PACKET_exec_event_feature)
5493 != AUTO_BOOLEAN_FALSE)
5494 remote_query_supported_append (&q, "exec-events+");
5495
5496 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5497 remote_query_supported_append (&q, "vContSupported+");
5498
5499 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5500 remote_query_supported_append (&q, "QThreadEvents+");
5501
5502 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5503 remote_query_supported_append (&q, "no-resumed+");
5504
5505 if (packet_set_cmd_state (PACKET_memory_tagging_feature)
5506 != AUTO_BOOLEAN_FALSE)
5507 remote_query_supported_append (&q, "memory-tagging+");
5508
5509 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5510 the qSupported:xmlRegisters=i386 handling. */
5511 if (remote_support_xml != NULL
5512 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5513 remote_query_supported_append (&q, remote_support_xml);
5514
5515 q = "qSupported:" + q;
5516 putpkt (q.c_str ());
5517
5518 getpkt (&rs->buf, 0);
5519
5520 /* If an error occured, warn, but do not return - just reset the
5521 buffer to empty and go on to disable features. */
5522 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5523 == PACKET_ERROR)
5524 {
5525 warning (_("Remote failure reply: %s"), rs->buf.data ());
5526 rs->buf[0] = 0;
5527 }
5528 }
5529
5530 memset (seen, 0, sizeof (seen));
5531
5532 next = rs->buf.data ();
5533 while (*next)
5534 {
5535 enum packet_support is_supported;
5536 char *p, *end, *name_end, *value;
5537
5538 /* First separate out this item from the rest of the packet. If
5539 there's another item after this, we overwrite the separator
5540 (terminated strings are much easier to work with). */
5541 p = next;
5542 end = strchr (p, ';');
5543 if (end == NULL)
5544 {
5545 end = p + strlen (p);
5546 next = end;
5547 }
5548 else
5549 {
5550 *end = '\0';
5551 next = end + 1;
5552
5553 if (end == p)
5554 {
5555 warning (_("empty item in \"qSupported\" response"));
5556 continue;
5557 }
5558 }
5559
5560 name_end = strchr (p, '=');
5561 if (name_end)
5562 {
5563 /* This is a name=value entry. */
5564 is_supported = PACKET_ENABLE;
5565 value = name_end + 1;
5566 *name_end = '\0';
5567 }
5568 else
5569 {
5570 value = NULL;
5571 switch (end[-1])
5572 {
5573 case '+':
5574 is_supported = PACKET_ENABLE;
5575 break;
5576
5577 case '-':
5578 is_supported = PACKET_DISABLE;
5579 break;
5580
5581 case '?':
5582 is_supported = PACKET_SUPPORT_UNKNOWN;
5583 break;
5584
5585 default:
5586 warning (_("unrecognized item \"%s\" "
5587 "in \"qSupported\" response"), p);
5588 continue;
5589 }
5590 end[-1] = '\0';
5591 }
5592
5593 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5594 if (strcmp (remote_protocol_features[i].name, p) == 0)
5595 {
5596 const struct protocol_feature *feature;
5597
5598 seen[i] = 1;
5599 feature = &remote_protocol_features[i];
5600 feature->func (this, feature, is_supported, value);
5601 break;
5602 }
5603 }
5604
5605 /* If we increased the packet size, make sure to increase the global
5606 buffer size also. We delay this until after parsing the entire
5607 qSupported packet, because this is the same buffer we were
5608 parsing. */
5609 if (rs->buf.size () < rs->explicit_packet_size)
5610 rs->buf.resize (rs->explicit_packet_size);
5611
5612 /* Handle the defaults for unmentioned features. */
5613 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5614 if (!seen[i])
5615 {
5616 const struct protocol_feature *feature;
5617
5618 feature = &remote_protocol_features[i];
5619 feature->func (this, feature, feature->default_support, NULL);
5620 }
5621 }
5622
5623 /* Serial QUIT handler for the remote serial descriptor.
5624
5625 Defers handling a Ctrl-C until we're done with the current
5626 command/response packet sequence, unless:
5627
5628 - We're setting up the connection. Don't send a remote interrupt
5629 request, as we're not fully synced yet. Quit immediately
5630 instead.
5631
5632 - The target has been resumed in the foreground
5633 (target_terminal::is_ours is false) with a synchronous resume
5634 packet, and we're blocked waiting for the stop reply, thus a
5635 Ctrl-C should be immediately sent to the target.
5636
5637 - We get a second Ctrl-C while still within the same serial read or
5638 write. In that case the serial is seemingly wedged --- offer to
5639 quit/disconnect.
5640
5641 - We see a second Ctrl-C without target response, after having
5642 previously interrupted the target. In that case the target/stub
5643 is probably wedged --- offer to quit/disconnect.
5644 */
5645
5646 void
5647 remote_target::remote_serial_quit_handler ()
5648 {
5649 struct remote_state *rs = get_remote_state ();
5650
5651 if (check_quit_flag ())
5652 {
5653 /* If we're starting up, we're not fully synced yet. Quit
5654 immediately. */
5655 if (rs->starting_up)
5656 quit ();
5657 else if (rs->got_ctrlc_during_io)
5658 {
5659 if (query (_("The target is not responding to GDB commands.\n"
5660 "Stop debugging it? ")))
5661 remote_unpush_and_throw (this);
5662 }
5663 /* If ^C has already been sent once, offer to disconnect. */
5664 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5665 interrupt_query ();
5666 /* All-stop protocol, and blocked waiting for stop reply. Send
5667 an interrupt request. */
5668 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5669 target_interrupt ();
5670 else
5671 rs->got_ctrlc_during_io = 1;
5672 }
5673 }
5674
5675 /* The remote_target that is current while the quit handler is
5676 overridden with remote_serial_quit_handler. */
5677 static remote_target *curr_quit_handler_target;
5678
5679 static void
5680 remote_serial_quit_handler ()
5681 {
5682 curr_quit_handler_target->remote_serial_quit_handler ();
5683 }
5684
5685 /* Remove the remote target from the target stack of each inferior
5686 that is using it. Upper targets depend on it so remove them
5687 first. */
5688
5689 static void
5690 remote_unpush_target (remote_target *target)
5691 {
5692 /* We have to unpush the target from all inferiors, even those that
5693 aren't running. */
5694 scoped_restore_current_inferior restore_current_inferior;
5695
5696 for (inferior *inf : all_inferiors (target))
5697 {
5698 switch_to_inferior_no_thread (inf);
5699 pop_all_targets_at_and_above (process_stratum);
5700 generic_mourn_inferior ();
5701 }
5702
5703 /* Don't rely on target_close doing this when the target is popped
5704 from the last remote inferior above, because something may be
5705 holding a reference to the target higher up on the stack, meaning
5706 target_close won't be called yet. We lost the connection to the
5707 target, so clear these now, otherwise we may later throw
5708 TARGET_CLOSE_ERROR while trying to tell the remote target to
5709 close the file. */
5710 fileio_handles_invalidate_target (target);
5711 }
5712
5713 static void
5714 remote_unpush_and_throw (remote_target *target)
5715 {
5716 remote_unpush_target (target);
5717 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5718 }
5719
5720 void
5721 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5722 {
5723 remote_target *curr_remote = get_current_remote_target ();
5724
5725 if (name == 0)
5726 error (_("To open a remote debug connection, you need to specify what\n"
5727 "serial device is attached to the remote system\n"
5728 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5729
5730 /* If we're connected to a running target, target_preopen will kill it.
5731 Ask this question first, before target_preopen has a chance to kill
5732 anything. */
5733 if (curr_remote != NULL && !target_has_execution ())
5734 {
5735 if (from_tty
5736 && !query (_("Already connected to a remote target. Disconnect? ")))
5737 error (_("Still connected."));
5738 }
5739
5740 /* Here the possibly existing remote target gets unpushed. */
5741 target_preopen (from_tty);
5742
5743 remote_fileio_reset ();
5744 reopen_exec_file ();
5745 reread_symbols (from_tty);
5746
5747 remote_target *remote
5748 = (extended_p ? new extended_remote_target () : new remote_target ());
5749 target_ops_up target_holder (remote);
5750
5751 remote_state *rs = remote->get_remote_state ();
5752
5753 /* See FIXME above. */
5754 if (!target_async_permitted)
5755 rs->wait_forever_enabled_p = 1;
5756
5757 rs->remote_desc = remote_serial_open (name);
5758 if (!rs->remote_desc)
5759 perror_with_name (name);
5760
5761 if (baud_rate != -1)
5762 {
5763 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5764 {
5765 /* The requested speed could not be set. Error out to
5766 top level after closing remote_desc. Take care to
5767 set remote_desc to NULL to avoid closing remote_desc
5768 more than once. */
5769 serial_close (rs->remote_desc);
5770 rs->remote_desc = NULL;
5771 perror_with_name (name);
5772 }
5773 }
5774
5775 serial_setparity (rs->remote_desc, serial_parity);
5776 serial_raw (rs->remote_desc);
5777
5778 /* If there is something sitting in the buffer we might take it as a
5779 response to a command, which would be bad. */
5780 serial_flush_input (rs->remote_desc);
5781
5782 if (from_tty)
5783 {
5784 puts_filtered ("Remote debugging using ");
5785 puts_filtered (name);
5786 puts_filtered ("\n");
5787 }
5788
5789 /* Switch to using the remote target now. */
5790 current_inferior ()->push_target (std::move (target_holder));
5791
5792 /* Register extra event sources in the event loop. */
5793 rs->remote_async_inferior_event_token
5794 = create_async_event_handler (remote_async_inferior_event_handler, nullptr,
5795 "remote");
5796 rs->notif_state = remote_notif_state_allocate (remote);
5797
5798 /* Reset the target state; these things will be queried either by
5799 remote_query_supported or as they are needed. */
5800 reset_all_packet_configs_support ();
5801 rs->explicit_packet_size = 0;
5802 rs->noack_mode = 0;
5803 rs->extended = extended_p;
5804 rs->waiting_for_stop_reply = 0;
5805 rs->ctrlc_pending_p = 0;
5806 rs->got_ctrlc_during_io = 0;
5807
5808 rs->general_thread = not_sent_ptid;
5809 rs->continue_thread = not_sent_ptid;
5810 rs->remote_traceframe_number = -1;
5811
5812 rs->last_resume_exec_dir = EXEC_FORWARD;
5813
5814 /* Probe for ability to use "ThreadInfo" query, as required. */
5815 rs->use_threadinfo_query = 1;
5816 rs->use_threadextra_query = 1;
5817
5818 rs->readahead_cache.invalidate ();
5819
5820 if (target_async_permitted)
5821 {
5822 /* FIXME: cagney/1999-09-23: During the initial connection it is
5823 assumed that the target is already ready and able to respond to
5824 requests. Unfortunately remote_start_remote() eventually calls
5825 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5826 around this. Eventually a mechanism that allows
5827 wait_for_inferior() to expect/get timeouts will be
5828 implemented. */
5829 rs->wait_forever_enabled_p = 0;
5830 }
5831
5832 /* First delete any symbols previously loaded from shared libraries. */
5833 no_shared_libraries (NULL, 0);
5834
5835 /* Start the remote connection. If error() or QUIT, discard this
5836 target (we'd otherwise be in an inconsistent state) and then
5837 propogate the error on up the exception chain. This ensures that
5838 the caller doesn't stumble along blindly assuming that the
5839 function succeeded. The CLI doesn't have this problem but other
5840 UI's, such as MI do.
5841
5842 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5843 this function should return an error indication letting the
5844 caller restore the previous state. Unfortunately the command
5845 ``target remote'' is directly wired to this function making that
5846 impossible. On a positive note, the CLI side of this problem has
5847 been fixed - the function set_cmd_context() makes it possible for
5848 all the ``target ....'' commands to share a common callback
5849 function. See cli-dump.c. */
5850 {
5851
5852 try
5853 {
5854 remote->start_remote (from_tty, extended_p);
5855 }
5856 catch (const gdb_exception &ex)
5857 {
5858 /* Pop the partially set up target - unless something else did
5859 already before throwing the exception. */
5860 if (ex.error != TARGET_CLOSE_ERROR)
5861 remote_unpush_target (remote);
5862 throw;
5863 }
5864 }
5865
5866 remote_btrace_reset (rs);
5867
5868 if (target_async_permitted)
5869 rs->wait_forever_enabled_p = 1;
5870 }
5871
5872 /* Determine if WS represents a fork status. */
5873
5874 static bool
5875 is_fork_status (target_waitkind kind)
5876 {
5877 return (kind == TARGET_WAITKIND_FORKED
5878 || kind == TARGET_WAITKIND_VFORKED);
5879 }
5880
5881 /* Return THREAD's pending status if it is a pending fork parent, else
5882 return nullptr. */
5883
5884 static const target_waitstatus *
5885 thread_pending_fork_status (struct thread_info *thread)
5886 {
5887 const target_waitstatus &ws
5888 = (thread->has_pending_waitstatus ()
5889 ? thread->pending_waitstatus ()
5890 : thread->pending_follow);
5891
5892 if (!is_fork_status (ws.kind ()))
5893 return nullptr;
5894
5895 return &ws;
5896 }
5897
5898 /* Detach the specified process. */
5899
5900 void
5901 remote_target::remote_detach_pid (int pid)
5902 {
5903 struct remote_state *rs = get_remote_state ();
5904
5905 /* This should not be necessary, but the handling for D;PID in
5906 GDBserver versions prior to 8.2 incorrectly assumes that the
5907 selected process points to the same process we're detaching,
5908 leading to misbehavior (and possibly GDBserver crashing) when it
5909 does not. Since it's easy and cheap, work around it by forcing
5910 GDBserver to select GDB's current process. */
5911 set_general_process ();
5912
5913 if (remote_multi_process_p (rs))
5914 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
5915 else
5916 strcpy (rs->buf.data (), "D");
5917
5918 putpkt (rs->buf);
5919 getpkt (&rs->buf, 0);
5920
5921 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5922 ;
5923 else if (rs->buf[0] == '\0')
5924 error (_("Remote doesn't know how to detach"));
5925 else
5926 error (_("Can't detach process."));
5927 }
5928
5929 /* This detaches a program to which we previously attached, using
5930 inferior_ptid to identify the process. After this is done, GDB
5931 can be used to debug some other program. We better not have left
5932 any breakpoints in the target program or it'll die when it hits
5933 one. */
5934
5935 void
5936 remote_target::remote_detach_1 (inferior *inf, int from_tty)
5937 {
5938 int pid = inferior_ptid.pid ();
5939 struct remote_state *rs = get_remote_state ();
5940 int is_fork_parent;
5941
5942 if (!target_has_execution ())
5943 error (_("No process to detach from."));
5944
5945 target_announce_detach (from_tty);
5946
5947 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
5948 {
5949 /* If we're in breakpoints-always-inserted mode, or the inferior
5950 is running, we have to remove breakpoints before detaching.
5951 We don't do this in common code instead because not all
5952 targets support removing breakpoints while the target is
5953 running. The remote target / gdbserver does, though. */
5954 remove_breakpoints_inf (current_inferior ());
5955 }
5956
5957 /* Tell the remote target to detach. */
5958 remote_detach_pid (pid);
5959
5960 /* Exit only if this is the only active inferior. */
5961 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
5962 puts_filtered (_("Ending remote debugging.\n"));
5963
5964 /* See if any thread of the inferior we are detaching has a pending fork
5965 status. In that case, we must detach from the child resulting from
5966 that fork. */
5967 for (thread_info *thread : inf->non_exited_threads ())
5968 {
5969 const target_waitstatus *ws = thread_pending_fork_status (thread);
5970
5971 if (ws == nullptr)
5972 continue;
5973
5974 remote_detach_pid (ws->child_ptid ().pid ());
5975 }
5976
5977 /* Check also for any pending fork events in the stop reply queue. */
5978 remote_notif_get_pending_events (&notif_client_stop);
5979 for (stop_reply_up &reply : rs->stop_reply_queue)
5980 {
5981 if (reply->ptid.pid () != pid)
5982 continue;
5983
5984 if (!is_fork_status (reply->ws.kind ()))
5985 continue;
5986
5987 remote_detach_pid (reply->ws.child_ptid ().pid ());
5988 }
5989
5990 thread_info *tp = find_thread_ptid (this, inferior_ptid);
5991
5992 /* Check to see if we are detaching a fork parent. Note that if we
5993 are detaching a fork child, tp == NULL. */
5994 is_fork_parent = (tp != NULL
5995 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
5996
5997 /* If doing detach-on-fork, we don't mourn, because that will delete
5998 breakpoints that should be available for the followed inferior. */
5999 if (!is_fork_parent)
6000 {
6001 /* Save the pid as a string before mourning, since that will
6002 unpush the remote target, and we need the string after. */
6003 std::string infpid = target_pid_to_str (ptid_t (pid));
6004
6005 target_mourn_inferior (inferior_ptid);
6006 if (print_inferior_events)
6007 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
6008 inf->num, infpid.c_str ());
6009 }
6010 else
6011 {
6012 switch_to_no_thread ();
6013 detach_inferior (current_inferior ());
6014 }
6015 }
6016
6017 void
6018 remote_target::detach (inferior *inf, int from_tty)
6019 {
6020 remote_detach_1 (inf, from_tty);
6021 }
6022
6023 void
6024 extended_remote_target::detach (inferior *inf, int from_tty)
6025 {
6026 remote_detach_1 (inf, from_tty);
6027 }
6028
6029 /* Target follow-fork function for remote targets. On entry, and
6030 at return, the current inferior is the fork parent.
6031
6032 Note that although this is currently only used for extended-remote,
6033 it is named remote_follow_fork in anticipation of using it for the
6034 remote target as well. */
6035
6036 void
6037 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6038 target_waitkind fork_kind, bool follow_child,
6039 bool detach_fork)
6040 {
6041 process_stratum_target::follow_fork (child_inf, child_ptid,
6042 fork_kind, follow_child, detach_fork);
6043
6044 struct remote_state *rs = get_remote_state ();
6045
6046 if ((fork_kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
6047 || (fork_kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
6048 {
6049 /* When following the parent and detaching the child, we detach
6050 the child here. For the case of following the child and
6051 detaching the parent, the detach is done in the target-
6052 independent follow fork code in infrun.c. We can't use
6053 target_detach when detaching an unfollowed child because
6054 the client side doesn't know anything about the child. */
6055 if (detach_fork && !follow_child)
6056 {
6057 /* Detach the fork child. */
6058 remote_detach_pid (child_ptid.pid ());
6059 }
6060 }
6061 }
6062
6063 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6064 in the program space of the new inferior. */
6065
6066 void
6067 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6068 const char *execd_pathname)
6069 {
6070 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6071
6072 /* We know that this is a target file name, so if it has the "target:"
6073 prefix we strip it off before saving it in the program space. */
6074 if (is_target_filename (execd_pathname))
6075 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6076
6077 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6078 }
6079
6080 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6081
6082 void
6083 remote_target::disconnect (const char *args, int from_tty)
6084 {
6085 if (args)
6086 error (_("Argument given to \"disconnect\" when remotely debugging."));
6087
6088 /* Make sure we unpush even the extended remote targets. Calling
6089 target_mourn_inferior won't unpush, and
6090 remote_target::mourn_inferior won't unpush if there is more than
6091 one inferior left. */
6092 remote_unpush_target (this);
6093
6094 if (from_tty)
6095 puts_filtered ("Ending remote debugging.\n");
6096 }
6097
6098 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6099 be chatty about it. */
6100
6101 void
6102 extended_remote_target::attach (const char *args, int from_tty)
6103 {
6104 struct remote_state *rs = get_remote_state ();
6105 int pid;
6106 char *wait_status = NULL;
6107
6108 pid = parse_pid_to_attach (args);
6109
6110 /* Remote PID can be freely equal to getpid, do not check it here the same
6111 way as in other targets. */
6112
6113 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
6114 error (_("This target does not support attaching to a process"));
6115
6116 target_announce_attach (from_tty, pid);
6117
6118 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6119 putpkt (rs->buf);
6120 getpkt (&rs->buf, 0);
6121
6122 switch (packet_ok (rs->buf,
6123 &remote_protocol_packets[PACKET_vAttach]))
6124 {
6125 case PACKET_OK:
6126 if (!target_is_non_stop_p ())
6127 {
6128 /* Save the reply for later. */
6129 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6130 strcpy (wait_status, rs->buf.data ());
6131 }
6132 else if (strcmp (rs->buf.data (), "OK") != 0)
6133 error (_("Attaching to %s failed with: %s"),
6134 target_pid_to_str (ptid_t (pid)).c_str (),
6135 rs->buf.data ());
6136 break;
6137 case PACKET_UNKNOWN:
6138 error (_("This target does not support attaching to a process"));
6139 default:
6140 error (_("Attaching to %s failed"),
6141 target_pid_to_str (ptid_t (pid)).c_str ());
6142 }
6143
6144 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6145
6146 inferior_ptid = ptid_t (pid);
6147
6148 if (target_is_non_stop_p ())
6149 {
6150 /* Get list of threads. */
6151 update_thread_list ();
6152
6153 thread_info *thread = first_thread_of_inferior (current_inferior ());
6154 if (thread != nullptr)
6155 switch_to_thread (thread);
6156
6157 /* Invalidate our notion of the remote current thread. */
6158 record_currthread (rs, minus_one_ptid);
6159 }
6160 else
6161 {
6162 /* Now, if we have thread information, update the main thread's
6163 ptid. */
6164 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6165
6166 /* Add the main thread to the thread list. We add the thread
6167 silently in this case (the final true parameter). */
6168 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
6169
6170 switch_to_thread (thr);
6171 }
6172
6173 /* Next, if the target can specify a description, read it. We do
6174 this before anything involving memory or registers. */
6175 target_find_description ();
6176
6177 if (!target_is_non_stop_p ())
6178 {
6179 /* Use the previously fetched status. */
6180 gdb_assert (wait_status != NULL);
6181
6182 struct notif_event *reply
6183 = remote_notif_parse (this, &notif_client_stop, wait_status);
6184
6185 push_stop_reply ((struct stop_reply *) reply);
6186
6187 if (target_can_async_p ())
6188 target_async (1);
6189 }
6190 else
6191 {
6192 gdb_assert (wait_status == NULL);
6193
6194 gdb_assert (target_can_async_p ());
6195 target_async (1);
6196 }
6197 }
6198
6199 /* Implementation of the to_post_attach method. */
6200
6201 void
6202 extended_remote_target::post_attach (int pid)
6203 {
6204 /* Get text, data & bss offsets. */
6205 get_offsets ();
6206
6207 /* In certain cases GDB might not have had the chance to start
6208 symbol lookup up until now. This could happen if the debugged
6209 binary is not using shared libraries, the vsyscall page is not
6210 present (on Linux) and the binary itself hadn't changed since the
6211 debugging process was started. */
6212 if (current_program_space->symfile_object_file != NULL)
6213 remote_check_symbols();
6214 }
6215
6216 \f
6217 /* Check for the availability of vCont. This function should also check
6218 the response. */
6219
6220 void
6221 remote_target::remote_vcont_probe ()
6222 {
6223 remote_state *rs = get_remote_state ();
6224 char *buf;
6225
6226 strcpy (rs->buf.data (), "vCont?");
6227 putpkt (rs->buf);
6228 getpkt (&rs->buf, 0);
6229 buf = rs->buf.data ();
6230
6231 /* Make sure that the features we assume are supported. */
6232 if (startswith (buf, "vCont"))
6233 {
6234 char *p = &buf[5];
6235 int support_c, support_C;
6236
6237 rs->supports_vCont.s = 0;
6238 rs->supports_vCont.S = 0;
6239 support_c = 0;
6240 support_C = 0;
6241 rs->supports_vCont.t = 0;
6242 rs->supports_vCont.r = 0;
6243 while (p && *p == ';')
6244 {
6245 p++;
6246 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6247 rs->supports_vCont.s = 1;
6248 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6249 rs->supports_vCont.S = 1;
6250 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6251 support_c = 1;
6252 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6253 support_C = 1;
6254 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6255 rs->supports_vCont.t = 1;
6256 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6257 rs->supports_vCont.r = 1;
6258
6259 p = strchr (p, ';');
6260 }
6261
6262 /* If c, and C are not all supported, we can't use vCont. Clearing
6263 BUF will make packet_ok disable the packet. */
6264 if (!support_c || !support_C)
6265 buf[0] = 0;
6266 }
6267
6268 packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCont]);
6269 rs->supports_vCont_probed = true;
6270 }
6271
6272 /* Helper function for building "vCont" resumptions. Write a
6273 resumption to P. ENDP points to one-passed-the-end of the buffer
6274 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6275 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6276 resumed thread should be single-stepped and/or signalled. If PTID
6277 equals minus_one_ptid, then all threads are resumed; if PTID
6278 represents a process, then all threads of the process are resumed;
6279 the thread to be stepped and/or signalled is given in the global
6280 INFERIOR_PTID. */
6281
6282 char *
6283 remote_target::append_resumption (char *p, char *endp,
6284 ptid_t ptid, int step, gdb_signal siggnal)
6285 {
6286 struct remote_state *rs = get_remote_state ();
6287
6288 if (step && siggnal != GDB_SIGNAL_0)
6289 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6290 else if (step
6291 /* GDB is willing to range step. */
6292 && use_range_stepping
6293 /* Target supports range stepping. */
6294 && rs->supports_vCont.r
6295 /* We don't currently support range stepping multiple
6296 threads with a wildcard (though the protocol allows it,
6297 so stubs shouldn't make an active effort to forbid
6298 it). */
6299 && !(remote_multi_process_p (rs) && ptid.is_pid ()))
6300 {
6301 struct thread_info *tp;
6302
6303 if (ptid == minus_one_ptid)
6304 {
6305 /* If we don't know about the target thread's tid, then
6306 we're resuming magic_null_ptid (see caller). */
6307 tp = find_thread_ptid (this, magic_null_ptid);
6308 }
6309 else
6310 tp = find_thread_ptid (this, ptid);
6311 gdb_assert (tp != NULL);
6312
6313 if (tp->control.may_range_step)
6314 {
6315 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6316
6317 p += xsnprintf (p, endp - p, ";r%s,%s",
6318 phex_nz (tp->control.step_range_start,
6319 addr_size),
6320 phex_nz (tp->control.step_range_end,
6321 addr_size));
6322 }
6323 else
6324 p += xsnprintf (p, endp - p, ";s");
6325 }
6326 else if (step)
6327 p += xsnprintf (p, endp - p, ";s");
6328 else if (siggnal != GDB_SIGNAL_0)
6329 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6330 else
6331 p += xsnprintf (p, endp - p, ";c");
6332
6333 if (remote_multi_process_p (rs) && ptid.is_pid ())
6334 {
6335 ptid_t nptid;
6336
6337 /* All (-1) threads of process. */
6338 nptid = ptid_t (ptid.pid (), -1);
6339
6340 p += xsnprintf (p, endp - p, ":");
6341 p = write_ptid (p, endp, nptid);
6342 }
6343 else if (ptid != minus_one_ptid)
6344 {
6345 p += xsnprintf (p, endp - p, ":");
6346 p = write_ptid (p, endp, ptid);
6347 }
6348
6349 return p;
6350 }
6351
6352 /* Clear the thread's private info on resume. */
6353
6354 static void
6355 resume_clear_thread_private_info (struct thread_info *thread)
6356 {
6357 if (thread->priv != NULL)
6358 {
6359 remote_thread_info *priv = get_remote_thread_info (thread);
6360
6361 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6362 priv->watch_data_address = 0;
6363 }
6364 }
6365
6366 /* Append a vCont continue-with-signal action for threads that have a
6367 non-zero stop signal. */
6368
6369 char *
6370 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6371 ptid_t ptid)
6372 {
6373 for (thread_info *thread : all_non_exited_threads (this, ptid))
6374 if (inferior_ptid != thread->ptid
6375 && thread->stop_signal () != GDB_SIGNAL_0)
6376 {
6377 p = append_resumption (p, endp, thread->ptid,
6378 0, thread->stop_signal ());
6379 thread->set_stop_signal (GDB_SIGNAL_0);
6380 resume_clear_thread_private_info (thread);
6381 }
6382
6383 return p;
6384 }
6385
6386 /* Set the target running, using the packets that use Hc
6387 (c/s/C/S). */
6388
6389 void
6390 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6391 gdb_signal siggnal)
6392 {
6393 struct remote_state *rs = get_remote_state ();
6394 char *buf;
6395
6396 rs->last_sent_signal = siggnal;
6397 rs->last_sent_step = step;
6398
6399 /* The c/s/C/S resume packets use Hc, so set the continue
6400 thread. */
6401 if (ptid == minus_one_ptid)
6402 set_continue_thread (any_thread_ptid);
6403 else
6404 set_continue_thread (ptid);
6405
6406 for (thread_info *thread : all_non_exited_threads (this))
6407 resume_clear_thread_private_info (thread);
6408
6409 buf = rs->buf.data ();
6410 if (::execution_direction == EXEC_REVERSE)
6411 {
6412 /* We don't pass signals to the target in reverse exec mode. */
6413 if (info_verbose && siggnal != GDB_SIGNAL_0)
6414 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6415 siggnal);
6416
6417 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6418 error (_("Remote reverse-step not supported."));
6419 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6420 error (_("Remote reverse-continue not supported."));
6421
6422 strcpy (buf, step ? "bs" : "bc");
6423 }
6424 else if (siggnal != GDB_SIGNAL_0)
6425 {
6426 buf[0] = step ? 'S' : 'C';
6427 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6428 buf[2] = tohex (((int) siggnal) & 0xf);
6429 buf[3] = '\0';
6430 }
6431 else
6432 strcpy (buf, step ? "s" : "c");
6433
6434 putpkt (buf);
6435 }
6436
6437 /* Resume the remote inferior by using a "vCont" packet. The thread
6438 to be resumed is PTID; STEP and SIGGNAL indicate whether the
6439 resumed thread should be single-stepped and/or signalled. If PTID
6440 equals minus_one_ptid, then all threads are resumed; the thread to
6441 be stepped and/or signalled is given in the global INFERIOR_PTID.
6442 This function returns non-zero iff it resumes the inferior.
6443
6444 This function issues a strict subset of all possible vCont commands
6445 at the moment. */
6446
6447 int
6448 remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6449 enum gdb_signal siggnal)
6450 {
6451 struct remote_state *rs = get_remote_state ();
6452 char *p;
6453 char *endp;
6454
6455 /* No reverse execution actions defined for vCont. */
6456 if (::execution_direction == EXEC_REVERSE)
6457 return 0;
6458
6459 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6460 remote_vcont_probe ();
6461
6462 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6463 return 0;
6464
6465 p = rs->buf.data ();
6466 endp = p + get_remote_packet_size ();
6467
6468 /* If we could generate a wider range of packets, we'd have to worry
6469 about overflowing BUF. Should there be a generic
6470 "multi-part-packet" packet? */
6471
6472 p += xsnprintf (p, endp - p, "vCont");
6473
6474 if (ptid == magic_null_ptid)
6475 {
6476 /* MAGIC_NULL_PTID means that we don't have any active threads,
6477 so we don't have any TID numbers the inferior will
6478 understand. Make sure to only send forms that do not specify
6479 a TID. */
6480 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6481 }
6482 else if (ptid == minus_one_ptid || ptid.is_pid ())
6483 {
6484 /* Resume all threads (of all processes, or of a single
6485 process), with preference for INFERIOR_PTID. This assumes
6486 inferior_ptid belongs to the set of all threads we are about
6487 to resume. */
6488 if (step || siggnal != GDB_SIGNAL_0)
6489 {
6490 /* Step inferior_ptid, with or without signal. */
6491 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6492 }
6493
6494 /* Also pass down any pending signaled resumption for other
6495 threads not the current. */
6496 p = append_pending_thread_resumptions (p, endp, ptid);
6497
6498 /* And continue others without a signal. */
6499 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
6500 }
6501 else
6502 {
6503 /* Scheduler locking; resume only PTID. */
6504 append_resumption (p, endp, ptid, step, siggnal);
6505 }
6506
6507 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6508 putpkt (rs->buf);
6509
6510 if (target_is_non_stop_p ())
6511 {
6512 /* In non-stop, the stub replies to vCont with "OK". The stop
6513 reply will be reported asynchronously by means of a `%Stop'
6514 notification. */
6515 getpkt (&rs->buf, 0);
6516 if (strcmp (rs->buf.data (), "OK") != 0)
6517 error (_("Unexpected vCont reply in non-stop mode: %s"),
6518 rs->buf.data ());
6519 }
6520
6521 return 1;
6522 }
6523
6524 /* Tell the remote machine to resume. */
6525
6526 void
6527 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
6528 {
6529 struct remote_state *rs = get_remote_state ();
6530
6531 /* When connected in non-stop mode, the core resumes threads
6532 individually. Resuming remote threads directly in target_resume
6533 would thus result in sending one packet per thread. Instead, to
6534 minimize roundtrip latency, here we just store the resume
6535 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6536 resumption will be done in remote_target::commit_resume, where we'll be
6537 able to do vCont action coalescing. */
6538 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6539 {
6540 remote_thread_info *remote_thr;
6541
6542 if (minus_one_ptid == ptid || ptid.is_pid ())
6543 remote_thr = get_remote_thread_info (this, inferior_ptid);
6544 else
6545 remote_thr = get_remote_thread_info (this, ptid);
6546
6547 /* We don't expect the core to ask to resume an already resumed (from
6548 its point of view) thread. */
6549 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6550
6551 remote_thr->set_resumed_pending_vcont (step, siggnal);
6552 return;
6553 }
6554
6555 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6556 (explained in remote-notif.c:handle_notification) so
6557 remote_notif_process is not called. We need find a place where
6558 it is safe to start a 'vNotif' sequence. It is good to do it
6559 before resuming inferior, because inferior was stopped and no RSP
6560 traffic at that moment. */
6561 if (!target_is_non_stop_p ())
6562 remote_notif_process (rs->notif_state, &notif_client_stop);
6563
6564 rs->last_resume_exec_dir = ::execution_direction;
6565
6566 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6567 if (!remote_resume_with_vcont (ptid, step, siggnal))
6568 remote_resume_with_hc (ptid, step, siggnal);
6569
6570 /* Update resumed state tracked by the remote target. */
6571 for (thread_info *tp : all_non_exited_threads (this, ptid))
6572 get_remote_thread_info (tp)->set_resumed ();
6573
6574 /* We are about to start executing the inferior, let's register it
6575 with the event loop. NOTE: this is the one place where all the
6576 execution commands end up. We could alternatively do this in each
6577 of the execution commands in infcmd.c. */
6578 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6579 into infcmd.c in order to allow inferior function calls to work
6580 NOT asynchronously. */
6581 if (target_can_async_p ())
6582 target_async (1);
6583
6584 /* We've just told the target to resume. The remote server will
6585 wait for the inferior to stop, and then send a stop reply. In
6586 the mean time, we can't start another command/query ourselves
6587 because the stub wouldn't be ready to process it. This applies
6588 only to the base all-stop protocol, however. In non-stop (which
6589 only supports vCont), the stub replies with an "OK", and is
6590 immediate able to process further serial input. */
6591 if (!target_is_non_stop_p ())
6592 rs->waiting_for_stop_reply = 1;
6593 }
6594
6595 /* Private per-inferior info for target remote processes. */
6596
6597 struct remote_inferior : public private_inferior
6598 {
6599 /* Whether we can send a wildcard vCont for this process. */
6600 bool may_wildcard_vcont = true;
6601 };
6602
6603 /* Get the remote private inferior data associated to INF. */
6604
6605 static remote_inferior *
6606 get_remote_inferior (inferior *inf)
6607 {
6608 if (inf->priv == NULL)
6609 inf->priv.reset (new remote_inferior);
6610
6611 return static_cast<remote_inferior *> (inf->priv.get ());
6612 }
6613
6614 /* Class used to track the construction of a vCont packet in the
6615 outgoing packet buffer. This is used to send multiple vCont
6616 packets if we have more actions than would fit a single packet. */
6617
6618 class vcont_builder
6619 {
6620 public:
6621 explicit vcont_builder (remote_target *remote)
6622 : m_remote (remote)
6623 {
6624 restart ();
6625 }
6626
6627 void flush ();
6628 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6629
6630 private:
6631 void restart ();
6632
6633 /* The remote target. */
6634 remote_target *m_remote;
6635
6636 /* Pointer to the first action. P points here if no action has been
6637 appended yet. */
6638 char *m_first_action;
6639
6640 /* Where the next action will be appended. */
6641 char *m_p;
6642
6643 /* The end of the buffer. Must never write past this. */
6644 char *m_endp;
6645 };
6646
6647 /* Prepare the outgoing buffer for a new vCont packet. */
6648
6649 void
6650 vcont_builder::restart ()
6651 {
6652 struct remote_state *rs = m_remote->get_remote_state ();
6653
6654 m_p = rs->buf.data ();
6655 m_endp = m_p + m_remote->get_remote_packet_size ();
6656 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6657 m_first_action = m_p;
6658 }
6659
6660 /* If the vCont packet being built has any action, send it to the
6661 remote end. */
6662
6663 void
6664 vcont_builder::flush ()
6665 {
6666 struct remote_state *rs;
6667
6668 if (m_p == m_first_action)
6669 return;
6670
6671 rs = m_remote->get_remote_state ();
6672 m_remote->putpkt (rs->buf);
6673 m_remote->getpkt (&rs->buf, 0);
6674 if (strcmp (rs->buf.data (), "OK") != 0)
6675 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
6676 }
6677
6678 /* The largest action is range-stepping, with its two addresses. This
6679 is more than sufficient. If a new, bigger action is created, it'll
6680 quickly trigger a failed assertion in append_resumption (and we'll
6681 just bump this). */
6682 #define MAX_ACTION_SIZE 200
6683
6684 /* Append a new vCont action in the outgoing packet being built. If
6685 the action doesn't fit the packet along with previous actions, push
6686 what we've got so far to the remote end and start over a new vCont
6687 packet (with the new action). */
6688
6689 void
6690 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6691 {
6692 char buf[MAX_ACTION_SIZE + 1];
6693
6694 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6695 ptid, step, siggnal);
6696
6697 /* Check whether this new action would fit in the vCont packet along
6698 with previous actions. If not, send what we've got so far and
6699 start a new vCont packet. */
6700 size_t rsize = endp - buf;
6701 if (rsize > m_endp - m_p)
6702 {
6703 flush ();
6704 restart ();
6705
6706 /* Should now fit. */
6707 gdb_assert (rsize <= m_endp - m_p);
6708 }
6709
6710 memcpy (m_p, buf, rsize);
6711 m_p += rsize;
6712 *m_p = '\0';
6713 }
6714
6715 /* to_commit_resume implementation. */
6716
6717 void
6718 remote_target::commit_resumed ()
6719 {
6720 /* If connected in all-stop mode, we'd send the remote resume
6721 request directly from remote_resume. Likewise if
6722 reverse-debugging, as there are no defined vCont actions for
6723 reverse execution. */
6724 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6725 return;
6726
6727 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6728 instead of resuming all threads of each process individually.
6729 However, if any thread of a process must remain halted, we can't
6730 send wildcard resumes and must send one action per thread.
6731
6732 Care must be taken to not resume threads/processes the server
6733 side already told us are stopped, but the core doesn't know about
6734 yet, because the events are still in the vStopped notification
6735 queue. For example:
6736
6737 #1 => vCont s:p1.1;c
6738 #2 <= OK
6739 #3 <= %Stopped T05 p1.1
6740 #4 => vStopped
6741 #5 <= T05 p1.2
6742 #6 => vStopped
6743 #7 <= OK
6744 #8 (infrun handles the stop for p1.1 and continues stepping)
6745 #9 => vCont s:p1.1;c
6746
6747 The last vCont above would resume thread p1.2 by mistake, because
6748 the server has no idea that the event for p1.2 had not been
6749 handled yet.
6750
6751 The server side must similarly ignore resume actions for the
6752 thread that has a pending %Stopped notification (and any other
6753 threads with events pending), until GDB acks the notification
6754 with vStopped. Otherwise, e.g., the following case is
6755 mishandled:
6756
6757 #1 => g (or any other packet)
6758 #2 <= [registers]
6759 #3 <= %Stopped T05 p1.2
6760 #4 => vCont s:p1.1;c
6761 #5 <= OK
6762
6763 Above, the server must not resume thread p1.2. GDB can't know
6764 that p1.2 stopped until it acks the %Stopped notification, and
6765 since from GDB's perspective all threads should be running, it
6766 sends a "c" action.
6767
6768 Finally, special care must also be given to handling fork/vfork
6769 events. A (v)fork event actually tells us that two processes
6770 stopped -- the parent and the child. Until we follow the fork,
6771 we must not resume the child. Therefore, if we have a pending
6772 fork follow, we must not send a global wildcard resume action
6773 (vCont;c). We can still send process-wide wildcards though. */
6774
6775 /* Start by assuming a global wildcard (vCont;c) is possible. */
6776 bool may_global_wildcard_vcont = true;
6777
6778 /* And assume every process is individually wildcard-able too. */
6779 for (inferior *inf : all_non_exited_inferiors (this))
6780 {
6781 remote_inferior *priv = get_remote_inferior (inf);
6782
6783 priv->may_wildcard_vcont = true;
6784 }
6785
6786 /* Check for any pending events (not reported or processed yet) and
6787 disable process and global wildcard resumes appropriately. */
6788 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6789
6790 bool any_pending_vcont_resume = false;
6791
6792 for (thread_info *tp : all_non_exited_threads (this))
6793 {
6794 remote_thread_info *priv = get_remote_thread_info (tp);
6795
6796 /* If a thread of a process is not meant to be resumed, then we
6797 can't wildcard that process. */
6798 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
6799 {
6800 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6801
6802 /* And if we can't wildcard a process, we can't wildcard
6803 everything either. */
6804 may_global_wildcard_vcont = false;
6805 continue;
6806 }
6807
6808 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
6809 any_pending_vcont_resume = true;
6810
6811 /* If a thread is the parent of an unfollowed fork, then we
6812 can't do a global wildcard, as that would resume the fork
6813 child. */
6814 if (thread_pending_fork_status (tp) != nullptr)
6815 may_global_wildcard_vcont = false;
6816 }
6817
6818 /* We didn't have any resumed thread pending a vCont resume, so nothing to
6819 do. */
6820 if (!any_pending_vcont_resume)
6821 return;
6822
6823 /* Now let's build the vCont packet(s). Actions must be appended
6824 from narrower to wider scopes (thread -> process -> global). If
6825 we end up with too many actions for a single packet vcont_builder
6826 flushes the current vCont packet to the remote side and starts a
6827 new one. */
6828 struct vcont_builder vcont_builder (this);
6829
6830 /* Threads first. */
6831 for (thread_info *tp : all_non_exited_threads (this))
6832 {
6833 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6834
6835 /* If the thread was previously vCont-resumed, no need to send a specific
6836 action for it. If we didn't receive a resume request for it, don't
6837 send an action for it either. */
6838 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
6839 continue;
6840
6841 gdb_assert (!thread_is_in_step_over_chain (tp));
6842
6843 /* We should never be commit-resuming a thread that has a stop reply.
6844 Otherwise, we would end up reporting a stop event for a thread while
6845 it is running on the remote target. */
6846 remote_state *rs = get_remote_state ();
6847 for (const auto &stop_reply : rs->stop_reply_queue)
6848 gdb_assert (stop_reply->ptid != tp->ptid);
6849
6850 const resumed_pending_vcont_info &info
6851 = remote_thr->resumed_pending_vcont_info ();
6852
6853 /* Check if we need to send a specific action for this thread. If not,
6854 it will be included in a wildcard resume instead. */
6855 if (info.step || info.sig != GDB_SIGNAL_0
6856 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
6857 vcont_builder.push_action (tp->ptid, info.step, info.sig);
6858
6859 remote_thr->set_resumed ();
6860 }
6861
6862 /* Now check whether we can send any process-wide wildcard. This is
6863 to avoid sending a global wildcard in the case nothing is
6864 supposed to be resumed. */
6865 bool any_process_wildcard = false;
6866
6867 for (inferior *inf : all_non_exited_inferiors (this))
6868 {
6869 if (get_remote_inferior (inf)->may_wildcard_vcont)
6870 {
6871 any_process_wildcard = true;
6872 break;
6873 }
6874 }
6875
6876 if (any_process_wildcard)
6877 {
6878 /* If all processes are wildcard-able, then send a single "c"
6879 action, otherwise, send an "all (-1) threads of process"
6880 continue action for each running process, if any. */
6881 if (may_global_wildcard_vcont)
6882 {
6883 vcont_builder.push_action (minus_one_ptid,
6884 false, GDB_SIGNAL_0);
6885 }
6886 else
6887 {
6888 for (inferior *inf : all_non_exited_inferiors (this))
6889 {
6890 if (get_remote_inferior (inf)->may_wildcard_vcont)
6891 {
6892 vcont_builder.push_action (ptid_t (inf->pid),
6893 false, GDB_SIGNAL_0);
6894 }
6895 }
6896 }
6897 }
6898
6899 vcont_builder.flush ();
6900 }
6901
6902 /* Implementation of target_has_pending_events. */
6903
6904 bool
6905 remote_target::has_pending_events ()
6906 {
6907 if (target_can_async_p ())
6908 {
6909 remote_state *rs = get_remote_state ();
6910
6911 if (async_event_handler_marked (rs->remote_async_inferior_event_token))
6912 return true;
6913
6914 /* Note that BUFCNT can be negative, indicating sticky
6915 error. */
6916 if (rs->remote_desc->bufcnt != 0)
6917 return true;
6918 }
6919 return false;
6920 }
6921
6922 \f
6923
6924 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6925 thread, all threads of a remote process, or all threads of all
6926 processes. */
6927
6928 void
6929 remote_target::remote_stop_ns (ptid_t ptid)
6930 {
6931 struct remote_state *rs = get_remote_state ();
6932 char *p = rs->buf.data ();
6933 char *endp = p + get_remote_packet_size ();
6934
6935 /* If any thread that needs to stop was resumed but pending a vCont
6936 resume, generate a phony stop_reply. However, first check
6937 whether the thread wasn't resumed with a signal. Generating a
6938 phony stop in that case would result in losing the signal. */
6939 bool needs_commit = false;
6940 for (thread_info *tp : all_non_exited_threads (this, ptid))
6941 {
6942 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6943
6944 if (remote_thr->get_resume_state ()
6945 == resume_state::RESUMED_PENDING_VCONT)
6946 {
6947 const resumed_pending_vcont_info &info
6948 = remote_thr->resumed_pending_vcont_info ();
6949 if (info.sig != GDB_SIGNAL_0)
6950 {
6951 /* This signal must be forwarded to the inferior. We
6952 could commit-resume just this thread, but its simpler
6953 to just commit-resume everything. */
6954 needs_commit = true;
6955 break;
6956 }
6957 }
6958 }
6959
6960 if (needs_commit)
6961 commit_resumed ();
6962 else
6963 for (thread_info *tp : all_non_exited_threads (this, ptid))
6964 {
6965 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6966
6967 if (remote_thr->get_resume_state ()
6968 == resume_state::RESUMED_PENDING_VCONT)
6969 {
6970 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
6971 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
6972 tp->ptid.lwp (),
6973 pulongest (tp->ptid.tid ()));
6974
6975 /* Check that the thread wasn't resumed with a signal.
6976 Generating a phony stop would result in losing the
6977 signal. */
6978 const resumed_pending_vcont_info &info
6979 = remote_thr->resumed_pending_vcont_info ();
6980 gdb_assert (info.sig == GDB_SIGNAL_0);
6981
6982 stop_reply *sr = new stop_reply ();
6983 sr->ptid = tp->ptid;
6984 sr->rs = rs;
6985 sr->ws.set_stopped (GDB_SIGNAL_0);
6986 sr->arch = tp->inf->gdbarch;
6987 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6988 sr->watch_data_address = 0;
6989 sr->core = 0;
6990 this->push_stop_reply (sr);
6991
6992 /* Pretend that this thread was actually resumed on the
6993 remote target, then stopped. If we leave it in the
6994 RESUMED_PENDING_VCONT state and the commit_resumed
6995 method is called while the stop reply is still in the
6996 queue, we'll end up reporting a stop event to the core
6997 for that thread while it is running on the remote
6998 target... that would be bad. */
6999 remote_thr->set_resumed ();
7000 }
7001 }
7002
7003 /* FIXME: This supports_vCont_probed check is a workaround until
7004 packet_support is per-connection. */
7005 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN
7006 || !rs->supports_vCont_probed)
7007 remote_vcont_probe ();
7008
7009 if (!rs->supports_vCont.t)
7010 error (_("Remote server does not support stopping threads"));
7011
7012 if (ptid == minus_one_ptid
7013 || (!remote_multi_process_p (rs) && ptid.is_pid ()))
7014 p += xsnprintf (p, endp - p, "vCont;t");
7015 else
7016 {
7017 ptid_t nptid;
7018
7019 p += xsnprintf (p, endp - p, "vCont;t:");
7020
7021 if (ptid.is_pid ())
7022 /* All (-1) threads of process. */
7023 nptid = ptid_t (ptid.pid (), -1);
7024 else
7025 {
7026 /* Small optimization: if we already have a stop reply for
7027 this thread, no use in telling the stub we want this
7028 stopped. */
7029 if (peek_stop_reply (ptid))
7030 return;
7031
7032 nptid = ptid;
7033 }
7034
7035 write_ptid (p, endp, nptid);
7036 }
7037
7038 /* In non-stop, we get an immediate OK reply. The stop reply will
7039 come in asynchronously by notification. */
7040 putpkt (rs->buf);
7041 getpkt (&rs->buf, 0);
7042 if (strcmp (rs->buf.data (), "OK") != 0)
7043 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7044 rs->buf.data ());
7045 }
7046
7047 /* All-stop version of target_interrupt. Sends a break or a ^C to
7048 interrupt the remote target. It is undefined which thread of which
7049 process reports the interrupt. */
7050
7051 void
7052 remote_target::remote_interrupt_as ()
7053 {
7054 struct remote_state *rs = get_remote_state ();
7055
7056 rs->ctrlc_pending_p = 1;
7057
7058 /* If the inferior is stopped already, but the core didn't know
7059 about it yet, just ignore the request. The pending stop events
7060 will be collected in remote_wait. */
7061 if (stop_reply_queue_length () > 0)
7062 return;
7063
7064 /* Send interrupt_sequence to remote target. */
7065 send_interrupt_sequence ();
7066 }
7067
7068 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7069 the remote target. It is undefined which thread of which process
7070 reports the interrupt. Throws an error if the packet is not
7071 supported by the server. */
7072
7073 void
7074 remote_target::remote_interrupt_ns ()
7075 {
7076 struct remote_state *rs = get_remote_state ();
7077 char *p = rs->buf.data ();
7078 char *endp = p + get_remote_packet_size ();
7079
7080 xsnprintf (p, endp - p, "vCtrlC");
7081
7082 /* In non-stop, we get an immediate OK reply. The stop reply will
7083 come in asynchronously by notification. */
7084 putpkt (rs->buf);
7085 getpkt (&rs->buf, 0);
7086
7087 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
7088 {
7089 case PACKET_OK:
7090 break;
7091 case PACKET_UNKNOWN:
7092 error (_("No support for interrupting the remote target."));
7093 case PACKET_ERROR:
7094 error (_("Interrupting target failed: %s"), rs->buf.data ());
7095 }
7096 }
7097
7098 /* Implement the to_stop function for the remote targets. */
7099
7100 void
7101 remote_target::stop (ptid_t ptid)
7102 {
7103 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7104
7105 if (target_is_non_stop_p ())
7106 remote_stop_ns (ptid);
7107 else
7108 {
7109 /* We don't currently have a way to transparently pause the
7110 remote target in all-stop mode. Interrupt it instead. */
7111 remote_interrupt_as ();
7112 }
7113 }
7114
7115 /* Implement the to_interrupt function for the remote targets. */
7116
7117 void
7118 remote_target::interrupt ()
7119 {
7120 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7121
7122 if (target_is_non_stop_p ())
7123 remote_interrupt_ns ();
7124 else
7125 remote_interrupt_as ();
7126 }
7127
7128 /* Implement the to_pass_ctrlc function for the remote targets. */
7129
7130 void
7131 remote_target::pass_ctrlc ()
7132 {
7133 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7134
7135 struct remote_state *rs = get_remote_state ();
7136
7137 /* If we're starting up, we're not fully synced yet. Quit
7138 immediately. */
7139 if (rs->starting_up)
7140 quit ();
7141 /* If ^C has already been sent once, offer to disconnect. */
7142 else if (rs->ctrlc_pending_p)
7143 interrupt_query ();
7144 else
7145 target_interrupt ();
7146 }
7147
7148 /* Ask the user what to do when an interrupt is received. */
7149
7150 void
7151 remote_target::interrupt_query ()
7152 {
7153 struct remote_state *rs = get_remote_state ();
7154
7155 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7156 {
7157 if (query (_("The target is not responding to interrupt requests.\n"
7158 "Stop debugging it? ")))
7159 {
7160 remote_unpush_target (this);
7161 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7162 }
7163 }
7164 else
7165 {
7166 if (query (_("Interrupted while waiting for the program.\n"
7167 "Give up waiting? ")))
7168 quit ();
7169 }
7170 }
7171
7172 /* Enable/disable target terminal ownership. Most targets can use
7173 terminal groups to control terminal ownership. Remote targets are
7174 different in that explicit transfer of ownership to/from GDB/target
7175 is required. */
7176
7177 void
7178 remote_target::terminal_inferior ()
7179 {
7180 /* NOTE: At this point we could also register our selves as the
7181 recipient of all input. Any characters typed could then be
7182 passed on down to the target. */
7183 }
7184
7185 void
7186 remote_target::terminal_ours ()
7187 {
7188 }
7189
7190 static void
7191 remote_console_output (const char *msg)
7192 {
7193 const char *p;
7194
7195 for (p = msg; p[0] && p[1]; p += 2)
7196 {
7197 char tb[2];
7198 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7199
7200 tb[0] = c;
7201 tb[1] = 0;
7202 gdb_stdtarg->puts (tb);
7203 }
7204 gdb_stdtarg->flush ();
7205 }
7206
7207 /* Return the length of the stop reply queue. */
7208
7209 int
7210 remote_target::stop_reply_queue_length ()
7211 {
7212 remote_state *rs = get_remote_state ();
7213 return rs->stop_reply_queue.size ();
7214 }
7215
7216 static void
7217 remote_notif_stop_parse (remote_target *remote,
7218 struct notif_client *self, const char *buf,
7219 struct notif_event *event)
7220 {
7221 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7222 }
7223
7224 static void
7225 remote_notif_stop_ack (remote_target *remote,
7226 struct notif_client *self, const char *buf,
7227 struct notif_event *event)
7228 {
7229 struct stop_reply *stop_reply = (struct stop_reply *) event;
7230
7231 /* acknowledge */
7232 putpkt (remote, self->ack_command);
7233
7234 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7235 the notification. It was left in the queue because we need to
7236 acknowledge it and pull the rest of the notifications out. */
7237 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7238 remote->push_stop_reply (stop_reply);
7239 }
7240
7241 static int
7242 remote_notif_stop_can_get_pending_events (remote_target *remote,
7243 struct notif_client *self)
7244 {
7245 /* We can't get pending events in remote_notif_process for
7246 notification stop, and we have to do this in remote_wait_ns
7247 instead. If we fetch all queued events from stub, remote stub
7248 may exit and we have no chance to process them back in
7249 remote_wait_ns. */
7250 remote_state *rs = remote->get_remote_state ();
7251 mark_async_event_handler (rs->remote_async_inferior_event_token);
7252 return 0;
7253 }
7254
7255 stop_reply::~stop_reply ()
7256 {
7257 for (cached_reg_t &reg : regcache)
7258 xfree (reg.data);
7259 }
7260
7261 static notif_event_up
7262 remote_notif_stop_alloc_reply ()
7263 {
7264 return notif_event_up (new struct stop_reply ());
7265 }
7266
7267 /* A client of notification Stop. */
7268
7269 struct notif_client notif_client_stop =
7270 {
7271 "Stop",
7272 "vStopped",
7273 remote_notif_stop_parse,
7274 remote_notif_stop_ack,
7275 remote_notif_stop_can_get_pending_events,
7276 remote_notif_stop_alloc_reply,
7277 REMOTE_NOTIF_STOP,
7278 };
7279
7280 /* If CONTEXT contains any fork child threads that have not been
7281 reported yet, remove them from the CONTEXT list. If such a
7282 thread exists it is because we are stopped at a fork catchpoint
7283 and have not yet called follow_fork, which will set up the
7284 host-side data structures for the new process. */
7285
7286 void
7287 remote_target::remove_new_fork_children (threads_listing_context *context)
7288 {
7289 struct notif_client *notif = &notif_client_stop;
7290
7291 /* For any threads stopped at a fork event, remove the corresponding
7292 fork child threads from the CONTEXT list. */
7293 for (thread_info *thread : all_non_exited_threads (this))
7294 {
7295 const target_waitstatus *ws = thread_pending_fork_status (thread);
7296
7297 if (ws == nullptr)
7298 continue;
7299
7300 context->remove_thread (ws->child_ptid ());
7301 }
7302
7303 /* Check for any pending fork events (not reported or processed yet)
7304 in process PID and remove those fork child threads from the
7305 CONTEXT list as well. */
7306 remote_notif_get_pending_events (notif);
7307 for (auto &event : get_remote_state ()->stop_reply_queue)
7308 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7309 || event->ws.kind () == TARGET_WAITKIND_VFORKED
7310 || event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7311 context->remove_thread (event->ws.child_ptid ());
7312 }
7313
7314 /* Check whether any event pending in the vStopped queue would prevent a
7315 global or process wildcard vCont action. Set *may_global_wildcard to
7316 false if we can't do a global wildcard (vCont;c), and clear the event
7317 inferior's may_wildcard_vcont flag if we can't do a process-wide
7318 wildcard resume (vCont;c:pPID.-1). */
7319
7320 void
7321 remote_target::check_pending_events_prevent_wildcard_vcont
7322 (bool *may_global_wildcard)
7323 {
7324 struct notif_client *notif = &notif_client_stop;
7325
7326 remote_notif_get_pending_events (notif);
7327 for (auto &event : get_remote_state ()->stop_reply_queue)
7328 {
7329 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7330 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7331 continue;
7332
7333 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7334 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7335 *may_global_wildcard = false;
7336
7337 /* This may be the first time we heard about this process.
7338 Regardless, we must not do a global wildcard resume, otherwise
7339 we'd resume this process too. */
7340 *may_global_wildcard = false;
7341 if (event->ptid != null_ptid)
7342 {
7343 inferior *inf = find_inferior_ptid (this, event->ptid);
7344 if (inf != NULL)
7345 get_remote_inferior (inf)->may_wildcard_vcont = false;
7346 }
7347 }
7348 }
7349
7350 /* Discard all pending stop replies of inferior INF. */
7351
7352 void
7353 remote_target::discard_pending_stop_replies (struct inferior *inf)
7354 {
7355 struct stop_reply *reply;
7356 struct remote_state *rs = get_remote_state ();
7357 struct remote_notif_state *rns = rs->notif_state;
7358
7359 /* This function can be notified when an inferior exists. When the
7360 target is not remote, the notification state is NULL. */
7361 if (rs->remote_desc == NULL)
7362 return;
7363
7364 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7365
7366 /* Discard the in-flight notification. */
7367 if (reply != NULL && reply->ptid.pid () == inf->pid)
7368 {
7369 /* Leave the notification pending, since the server expects that
7370 we acknowledge it with vStopped. But clear its contents, so
7371 that later on when we acknowledge it, we also discard it. */
7372 remote_debug_printf
7373 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7374 reply->ptid.to_string().c_str(),
7375 reply->ws.to_string ().c_str ());
7376 reply->ws.set_ignore ();
7377 }
7378
7379 /* Discard the stop replies we have already pulled with
7380 vStopped. */
7381 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7382 rs->stop_reply_queue.end (),
7383 [=] (const stop_reply_up &event)
7384 {
7385 return event->ptid.pid () == inf->pid;
7386 });
7387 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7388 remote_debug_printf
7389 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7390 reply->ptid.to_string().c_str(),
7391 reply->ws.to_string ().c_str ());
7392 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7393 }
7394
7395 /* Discard the stop replies for RS in stop_reply_queue. */
7396
7397 void
7398 remote_target::discard_pending_stop_replies_in_queue ()
7399 {
7400 remote_state *rs = get_remote_state ();
7401
7402 /* Discard the stop replies we have already pulled with
7403 vStopped. */
7404 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7405 rs->stop_reply_queue.end (),
7406 [=] (const stop_reply_up &event)
7407 {
7408 return event->rs == rs;
7409 });
7410 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7411 }
7412
7413 /* Remove the first reply in 'stop_reply_queue' which matches
7414 PTID. */
7415
7416 struct stop_reply *
7417 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7418 {
7419 remote_state *rs = get_remote_state ();
7420
7421 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7422 rs->stop_reply_queue.end (),
7423 [=] (const stop_reply_up &event)
7424 {
7425 return event->ptid.matches (ptid);
7426 });
7427 struct stop_reply *result;
7428 if (iter == rs->stop_reply_queue.end ())
7429 result = nullptr;
7430 else
7431 {
7432 result = iter->release ();
7433 rs->stop_reply_queue.erase (iter);
7434 }
7435
7436 if (notif_debug)
7437 fprintf_unfiltered (gdb_stdlog,
7438 "notif: discard queued event: 'Stop' in %s\n",
7439 ptid.to_string ().c_str ());
7440
7441 return result;
7442 }
7443
7444 /* Look for a queued stop reply belonging to PTID. If one is found,
7445 remove it from the queue, and return it. Returns NULL if none is
7446 found. If there are still queued events left to process, tell the
7447 event loop to get back to target_wait soon. */
7448
7449 struct stop_reply *
7450 remote_target::queued_stop_reply (ptid_t ptid)
7451 {
7452 remote_state *rs = get_remote_state ();
7453 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7454
7455 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7456 {
7457 /* There's still at least an event left. */
7458 mark_async_event_handler (rs->remote_async_inferior_event_token);
7459 }
7460
7461 return r;
7462 }
7463
7464 /* Push a fully parsed stop reply in the stop reply queue. Since we
7465 know that we now have at least one queued event left to pass to the
7466 core side, tell the event loop to get back to target_wait soon. */
7467
7468 void
7469 remote_target::push_stop_reply (struct stop_reply *new_event)
7470 {
7471 remote_state *rs = get_remote_state ();
7472 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7473
7474 if (notif_debug)
7475 fprintf_unfiltered (gdb_stdlog,
7476 "notif: push 'Stop' %s to queue %d\n",
7477 new_event->ptid.to_string ().c_str (),
7478 int (rs->stop_reply_queue.size ()));
7479
7480 /* Mark the pending event queue only if async mode is currently enabled.
7481 If async mode is not currently enabled, then, if it later becomes
7482 enabled, and there are events in this queue, we will mark the event
7483 token at that point, see remote_target::async. */
7484 if (target_is_async_p ())
7485 mark_async_event_handler (rs->remote_async_inferior_event_token);
7486 }
7487
7488 /* Returns true if we have a stop reply for PTID. */
7489
7490 int
7491 remote_target::peek_stop_reply (ptid_t ptid)
7492 {
7493 remote_state *rs = get_remote_state ();
7494 for (auto &event : rs->stop_reply_queue)
7495 if (ptid == event->ptid
7496 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7497 return 1;
7498 return 0;
7499 }
7500
7501 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7502 starting with P and ending with PEND matches PREFIX. */
7503
7504 static int
7505 strprefix (const char *p, const char *pend, const char *prefix)
7506 {
7507 for ( ; p < pend; p++, prefix++)
7508 if (*p != *prefix)
7509 return 0;
7510 return *prefix == '\0';
7511 }
7512
7513 /* Parse the stop reply in BUF. Either the function succeeds, and the
7514 result is stored in EVENT, or throws an error. */
7515
7516 void
7517 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7518 {
7519 remote_arch_state *rsa = NULL;
7520 ULONGEST addr;
7521 const char *p;
7522 int skipregs = 0;
7523
7524 event->ptid = null_ptid;
7525 event->rs = get_remote_state ();
7526 event->ws.set_ignore ();
7527 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7528 event->regcache.clear ();
7529 event->core = -1;
7530
7531 switch (buf[0])
7532 {
7533 case 'T': /* Status with PC, SP, FP, ... */
7534 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7535 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7536 ss = signal number
7537 n... = register number
7538 r... = register contents
7539 */
7540
7541 p = &buf[3]; /* after Txx */
7542 while (*p)
7543 {
7544 const char *p1;
7545 int fieldsize;
7546
7547 p1 = strchr (p, ':');
7548 if (p1 == NULL)
7549 error (_("Malformed packet(a) (missing colon): %s\n\
7550 Packet: '%s'\n"),
7551 p, buf);
7552 if (p == p1)
7553 error (_("Malformed packet(a) (missing register number): %s\n\
7554 Packet: '%s'\n"),
7555 p, buf);
7556
7557 /* Some "registers" are actually extended stop information.
7558 Note if you're adding a new entry here: GDB 7.9 and
7559 earlier assume that all register "numbers" that start
7560 with an hex digit are real register numbers. Make sure
7561 the server only sends such a packet if it knows the
7562 client understands it. */
7563
7564 if (strprefix (p, p1, "thread"))
7565 event->ptid = read_ptid (++p1, &p);
7566 else if (strprefix (p, p1, "syscall_entry"))
7567 {
7568 ULONGEST sysno;
7569
7570 p = unpack_varlen_hex (++p1, &sysno);
7571 event->ws.set_syscall_entry ((int) sysno);
7572 }
7573 else if (strprefix (p, p1, "syscall_return"))
7574 {
7575 ULONGEST sysno;
7576
7577 p = unpack_varlen_hex (++p1, &sysno);
7578 event->ws.set_syscall_return ((int) sysno);
7579 }
7580 else if (strprefix (p, p1, "watch")
7581 || strprefix (p, p1, "rwatch")
7582 || strprefix (p, p1, "awatch"))
7583 {
7584 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7585 p = unpack_varlen_hex (++p1, &addr);
7586 event->watch_data_address = (CORE_ADDR) addr;
7587 }
7588 else if (strprefix (p, p1, "swbreak"))
7589 {
7590 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7591
7592 /* Make sure the stub doesn't forget to indicate support
7593 with qSupported. */
7594 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7595 error (_("Unexpected swbreak stop reason"));
7596
7597 /* The value part is documented as "must be empty",
7598 though we ignore it, in case we ever decide to make
7599 use of it in a backward compatible way. */
7600 p = strchrnul (p1 + 1, ';');
7601 }
7602 else if (strprefix (p, p1, "hwbreak"))
7603 {
7604 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7605
7606 /* Make sure the stub doesn't forget to indicate support
7607 with qSupported. */
7608 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7609 error (_("Unexpected hwbreak stop reason"));
7610
7611 /* See above. */
7612 p = strchrnul (p1 + 1, ';');
7613 }
7614 else if (strprefix (p, p1, "library"))
7615 {
7616 event->ws.set_loaded ();
7617 p = strchrnul (p1 + 1, ';');
7618 }
7619 else if (strprefix (p, p1, "replaylog"))
7620 {
7621 event->ws.set_no_history ();
7622 /* p1 will indicate "begin" or "end", but it makes
7623 no difference for now, so ignore it. */
7624 p = strchrnul (p1 + 1, ';');
7625 }
7626 else if (strprefix (p, p1, "core"))
7627 {
7628 ULONGEST c;
7629
7630 p = unpack_varlen_hex (++p1, &c);
7631 event->core = c;
7632 }
7633 else if (strprefix (p, p1, "fork"))
7634 event->ws.set_forked (read_ptid (++p1, &p));
7635 else if (strprefix (p, p1, "vfork"))
7636 event->ws.set_vforked (read_ptid (++p1, &p));
7637 else if (strprefix (p, p1, "vforkdone"))
7638 {
7639 event->ws.set_vfork_done ();
7640 p = strchrnul (p1 + 1, ';');
7641 }
7642 else if (strprefix (p, p1, "exec"))
7643 {
7644 ULONGEST ignored;
7645 int pathlen;
7646
7647 /* Determine the length of the execd pathname. */
7648 p = unpack_varlen_hex (++p1, &ignored);
7649 pathlen = (p - p1) / 2;
7650
7651 /* Save the pathname for event reporting and for
7652 the next run command. */
7653 gdb::unique_xmalloc_ptr<char> pathname
7654 ((char *) xmalloc (pathlen + 1));
7655 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
7656 pathname.get ()[pathlen] = '\0';
7657
7658 /* This is freed during event handling. */
7659 event->ws.set_execd (std::move (pathname));
7660
7661 /* Skip the registers included in this packet, since
7662 they may be for an architecture different from the
7663 one used by the original program. */
7664 skipregs = 1;
7665 }
7666 else if (strprefix (p, p1, "create"))
7667 {
7668 event->ws.set_thread_created ();
7669 p = strchrnul (p1 + 1, ';');
7670 }
7671 else
7672 {
7673 ULONGEST pnum;
7674 const char *p_temp;
7675
7676 if (skipregs)
7677 {
7678 p = strchrnul (p1 + 1, ';');
7679 p++;
7680 continue;
7681 }
7682
7683 /* Maybe a real ``P'' register number. */
7684 p_temp = unpack_varlen_hex (p, &pnum);
7685 /* If the first invalid character is the colon, we got a
7686 register number. Otherwise, it's an unknown stop
7687 reason. */
7688 if (p_temp == p1)
7689 {
7690 /* If we haven't parsed the event's thread yet, find
7691 it now, in order to find the architecture of the
7692 reported expedited registers. */
7693 if (event->ptid == null_ptid)
7694 {
7695 /* If there is no thread-id information then leave
7696 the event->ptid as null_ptid. Later in
7697 process_stop_reply we will pick a suitable
7698 thread. */
7699 const char *thr = strstr (p1 + 1, ";thread:");
7700 if (thr != NULL)
7701 event->ptid = read_ptid (thr + strlen (";thread:"),
7702 NULL);
7703 }
7704
7705 if (rsa == NULL)
7706 {
7707 inferior *inf
7708 = (event->ptid == null_ptid
7709 ? NULL
7710 : find_inferior_ptid (this, event->ptid));
7711 /* If this is the first time we learn anything
7712 about this process, skip the registers
7713 included in this packet, since we don't yet
7714 know which architecture to use to parse them.
7715 We'll determine the architecture later when
7716 we process the stop reply and retrieve the
7717 target description, via
7718 remote_notice_new_inferior ->
7719 post_create_inferior. */
7720 if (inf == NULL)
7721 {
7722 p = strchrnul (p1 + 1, ';');
7723 p++;
7724 continue;
7725 }
7726
7727 event->arch = inf->gdbarch;
7728 rsa = event->rs->get_remote_arch_state (event->arch);
7729 }
7730
7731 packet_reg *reg
7732 = packet_reg_from_pnum (event->arch, rsa, pnum);
7733 cached_reg_t cached_reg;
7734
7735 if (reg == NULL)
7736 error (_("Remote sent bad register number %s: %s\n\
7737 Packet: '%s'\n"),
7738 hex_string (pnum), p, buf);
7739
7740 cached_reg.num = reg->regnum;
7741 cached_reg.data = (gdb_byte *)
7742 xmalloc (register_size (event->arch, reg->regnum));
7743
7744 p = p1 + 1;
7745 fieldsize = hex2bin (p, cached_reg.data,
7746 register_size (event->arch, reg->regnum));
7747 p += 2 * fieldsize;
7748 if (fieldsize < register_size (event->arch, reg->regnum))
7749 warning (_("Remote reply is too short: %s"), buf);
7750
7751 event->regcache.push_back (cached_reg);
7752 }
7753 else
7754 {
7755 /* Not a number. Silently skip unknown optional
7756 info. */
7757 p = strchrnul (p1 + 1, ';');
7758 }
7759 }
7760
7761 if (*p != ';')
7762 error (_("Remote register badly formatted: %s\nhere: %s"),
7763 buf, p);
7764 ++p;
7765 }
7766
7767 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
7768 break;
7769
7770 /* fall through */
7771 case 'S': /* Old style status, just signal only. */
7772 {
7773 int sig;
7774
7775 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7776 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7777 event->ws.set_stopped ((enum gdb_signal) sig);
7778 else
7779 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
7780 }
7781 break;
7782 case 'w': /* Thread exited. */
7783 {
7784 ULONGEST value;
7785
7786 p = unpack_varlen_hex (&buf[1], &value);
7787 event->ws.set_thread_exited (value);
7788 if (*p != ';')
7789 error (_("stop reply packet badly formatted: %s"), buf);
7790 event->ptid = read_ptid (++p, NULL);
7791 break;
7792 }
7793 case 'W': /* Target exited. */
7794 case 'X':
7795 {
7796 ULONGEST value;
7797
7798 /* GDB used to accept only 2 hex chars here. Stubs should
7799 only send more if they detect GDB supports multi-process
7800 support. */
7801 p = unpack_varlen_hex (&buf[1], &value);
7802
7803 if (buf[0] == 'W')
7804 {
7805 /* The remote process exited. */
7806 event->ws.set_exited (value);
7807 }
7808 else
7809 {
7810 /* The remote process exited with a signal. */
7811 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7812 event->ws.set_signalled ((enum gdb_signal) value);
7813 else
7814 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
7815 }
7816
7817 /* If no process is specified, return null_ptid, and let the
7818 caller figure out the right process to use. */
7819 int pid = 0;
7820 if (*p == '\0')
7821 ;
7822 else if (*p == ';')
7823 {
7824 p++;
7825
7826 if (*p == '\0')
7827 ;
7828 else if (startswith (p, "process:"))
7829 {
7830 ULONGEST upid;
7831
7832 p += sizeof ("process:") - 1;
7833 unpack_varlen_hex (p, &upid);
7834 pid = upid;
7835 }
7836 else
7837 error (_("unknown stop reply packet: %s"), buf);
7838 }
7839 else
7840 error (_("unknown stop reply packet: %s"), buf);
7841 event->ptid = ptid_t (pid);
7842 }
7843 break;
7844 case 'N':
7845 event->ws.set_no_resumed ();
7846 event->ptid = minus_one_ptid;
7847 break;
7848 }
7849 }
7850
7851 /* When the stub wants to tell GDB about a new notification reply, it
7852 sends a notification (%Stop, for example). Those can come it at
7853 any time, hence, we have to make sure that any pending
7854 putpkt/getpkt sequence we're making is finished, before querying
7855 the stub for more events with the corresponding ack command
7856 (vStopped, for example). E.g., if we started a vStopped sequence
7857 immediately upon receiving the notification, something like this
7858 could happen:
7859
7860 1.1) --> Hg 1
7861 1.2) <-- OK
7862 1.3) --> g
7863 1.4) <-- %Stop
7864 1.5) --> vStopped
7865 1.6) <-- (registers reply to step #1.3)
7866
7867 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7868 query.
7869
7870 To solve this, whenever we parse a %Stop notification successfully,
7871 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7872 doing whatever we were doing:
7873
7874 2.1) --> Hg 1
7875 2.2) <-- OK
7876 2.3) --> g
7877 2.4) <-- %Stop
7878 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7879 2.5) <-- (registers reply to step #2.3)
7880
7881 Eventually after step #2.5, we return to the event loop, which
7882 notices there's an event on the
7883 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7884 associated callback --- the function below. At this point, we're
7885 always safe to start a vStopped sequence. :
7886
7887 2.6) --> vStopped
7888 2.7) <-- T05 thread:2
7889 2.8) --> vStopped
7890 2.9) --> OK
7891 */
7892
7893 void
7894 remote_target::remote_notif_get_pending_events (notif_client *nc)
7895 {
7896 struct remote_state *rs = get_remote_state ();
7897
7898 if (rs->notif_state->pending_event[nc->id] != NULL)
7899 {
7900 if (notif_debug)
7901 fprintf_unfiltered (gdb_stdlog,
7902 "notif: process: '%s' ack pending event\n",
7903 nc->name);
7904
7905 /* acknowledge */
7906 nc->ack (this, nc, rs->buf.data (),
7907 rs->notif_state->pending_event[nc->id]);
7908 rs->notif_state->pending_event[nc->id] = NULL;
7909
7910 while (1)
7911 {
7912 getpkt (&rs->buf, 0);
7913 if (strcmp (rs->buf.data (), "OK") == 0)
7914 break;
7915 else
7916 remote_notif_ack (this, nc, rs->buf.data ());
7917 }
7918 }
7919 else
7920 {
7921 if (notif_debug)
7922 fprintf_unfiltered (gdb_stdlog,
7923 "notif: process: '%s' no pending reply\n",
7924 nc->name);
7925 }
7926 }
7927
7928 /* Wrapper around remote_target::remote_notif_get_pending_events to
7929 avoid having to export the whole remote_target class. */
7930
7931 void
7932 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7933 {
7934 remote->remote_notif_get_pending_events (nc);
7935 }
7936
7937 /* Called from process_stop_reply when the stop packet we are responding
7938 to didn't include a process-id or thread-id. STATUS is the stop event
7939 we are responding to.
7940
7941 It is the task of this function to select a suitable thread (or process)
7942 and return its ptid, this is the thread (or process) we will assume the
7943 stop event came from.
7944
7945 In some cases there isn't really any choice about which thread (or
7946 process) is selected, a basic remote with a single process containing a
7947 single thread might choose not to send any process-id or thread-id in
7948 its stop packets, this function will select and return the one and only
7949 thread.
7950
7951 However, if a target supports multiple threads (or processes) and still
7952 doesn't include a thread-id (or process-id) in its stop packet then
7953 first, this is a badly behaving target, and second, we're going to have
7954 to select a thread (or process) at random and use that. This function
7955 will print a warning to the user if it detects that there is the
7956 possibility that GDB is guessing which thread (or process) to
7957 report.
7958
7959 Note that this is called before GDB fetches the updated thread list from the
7960 target. So it's possible for the stop reply to be ambiguous and for GDB to
7961 not realize it. For example, if there's initially one thread, the target
7962 spawns a second thread, and then sends a stop reply without an id that
7963 concerns the first thread. GDB will assume the stop reply is about the
7964 first thread - the only thread it knows about - without printing a warning.
7965 Anyway, if the remote meant for the stop reply to be about the second thread,
7966 then it would be really broken, because GDB doesn't know about that thread
7967 yet. */
7968
7969 ptid_t
7970 remote_target::select_thread_for_ambiguous_stop_reply
7971 (const target_waitstatus &status)
7972 {
7973 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7974
7975 /* Some stop events apply to all threads in an inferior, while others
7976 only apply to a single thread. */
7977 bool process_wide_stop
7978 = (status.kind () == TARGET_WAITKIND_EXITED
7979 || status.kind () == TARGET_WAITKIND_SIGNALLED);
7980
7981 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
7982
7983 thread_info *first_resumed_thread = nullptr;
7984 bool ambiguous = false;
7985
7986 /* Consider all non-exited threads of the target, find the first resumed
7987 one. */
7988 for (thread_info *thr : all_non_exited_threads (this))
7989 {
7990 remote_thread_info *remote_thr = get_remote_thread_info (thr);
7991
7992 if (remote_thr->get_resume_state () != resume_state::RESUMED)
7993 continue;
7994
7995 if (first_resumed_thread == nullptr)
7996 first_resumed_thread = thr;
7997 else if (!process_wide_stop
7998 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
7999 ambiguous = true;
8000 }
8001
8002 gdb_assert (first_resumed_thread != nullptr);
8003
8004 remote_debug_printf ("first resumed thread is %s",
8005 pid_to_str (first_resumed_thread->ptid).c_str ());
8006 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8007
8008 /* Warn if the remote target is sending ambiguous stop replies. */
8009 if (ambiguous)
8010 {
8011 static bool warned = false;
8012
8013 if (!warned)
8014 {
8015 /* If you are seeing this warning then the remote target has
8016 stopped without specifying a thread-id, but the target
8017 does have multiple threads (or inferiors), and so GDB is
8018 having to guess which thread stopped.
8019
8020 Examples of what might cause this are the target sending
8021 and 'S' stop packet, or a 'T' stop packet and not
8022 including a thread-id.
8023
8024 Additionally, the target might send a 'W' or 'X packet
8025 without including a process-id, when the target has
8026 multiple running inferiors. */
8027 if (process_wide_stop)
8028 warning (_("multi-inferior target stopped without "
8029 "sending a process-id, using first "
8030 "non-exited inferior"));
8031 else
8032 warning (_("multi-threaded target stopped without "
8033 "sending a thread-id, using first "
8034 "non-exited thread"));
8035 warned = true;
8036 }
8037 }
8038
8039 /* If this is a stop for all threads then don't use a particular threads
8040 ptid, instead create a new ptid where only the pid field is set. */
8041 if (process_wide_stop)
8042 return ptid_t (first_resumed_thread->ptid.pid ());
8043 else
8044 return first_resumed_thread->ptid;
8045 }
8046
8047 /* Called when it is decided that STOP_REPLY holds the info of the
8048 event that is to be returned to the core. This function always
8049 destroys STOP_REPLY. */
8050
8051 ptid_t
8052 remote_target::process_stop_reply (struct stop_reply *stop_reply,
8053 struct target_waitstatus *status)
8054 {
8055 *status = stop_reply->ws;
8056 ptid_t ptid = stop_reply->ptid;
8057
8058 /* If no thread/process was reported by the stub then select a suitable
8059 thread/process. */
8060 if (ptid == null_ptid)
8061 ptid = select_thread_for_ambiguous_stop_reply (*status);
8062 gdb_assert (ptid != null_ptid);
8063
8064 if (status->kind () != TARGET_WAITKIND_EXITED
8065 && status->kind () != TARGET_WAITKIND_SIGNALLED
8066 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8067 {
8068 /* Expedited registers. */
8069 if (!stop_reply->regcache.empty ())
8070 {
8071 struct regcache *regcache
8072 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
8073
8074 for (cached_reg_t &reg : stop_reply->regcache)
8075 {
8076 regcache->raw_supply (reg.num, reg.data);
8077 xfree (reg.data);
8078 }
8079
8080 stop_reply->regcache.clear ();
8081 }
8082
8083 remote_notice_new_inferior (ptid, false);
8084 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8085 remote_thr->core = stop_reply->core;
8086 remote_thr->stop_reason = stop_reply->stop_reason;
8087 remote_thr->watch_data_address = stop_reply->watch_data_address;
8088
8089 if (target_is_non_stop_p ())
8090 {
8091 /* If the target works in non-stop mode, a stop-reply indicates that
8092 only this thread stopped. */
8093 remote_thr->set_not_resumed ();
8094 }
8095 else
8096 {
8097 /* If the target works in all-stop mode, a stop-reply indicates that
8098 all the target's threads stopped. */
8099 for (thread_info *tp : all_non_exited_threads (this))
8100 get_remote_thread_info (tp)->set_not_resumed ();
8101 }
8102 }
8103
8104 delete stop_reply;
8105 return ptid;
8106 }
8107
8108 /* The non-stop mode version of target_wait. */
8109
8110 ptid_t
8111 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8112 target_wait_flags options)
8113 {
8114 struct remote_state *rs = get_remote_state ();
8115 struct stop_reply *stop_reply;
8116 int ret;
8117 int is_notif = 0;
8118
8119 /* If in non-stop mode, get out of getpkt even if a
8120 notification is received. */
8121
8122 ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
8123 while (1)
8124 {
8125 if (ret != -1 && !is_notif)
8126 switch (rs->buf[0])
8127 {
8128 case 'E': /* Error of some sort. */
8129 /* We're out of sync with the target now. Did it continue
8130 or not? We can't tell which thread it was in non-stop,
8131 so just ignore this. */
8132 warning (_("Remote failure reply: %s"), rs->buf.data ());
8133 break;
8134 case 'O': /* Console output. */
8135 remote_console_output (&rs->buf[1]);
8136 break;
8137 default:
8138 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8139 break;
8140 }
8141
8142 /* Acknowledge a pending stop reply that may have arrived in the
8143 mean time. */
8144 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8145 remote_notif_get_pending_events (&notif_client_stop);
8146
8147 /* If indeed we noticed a stop reply, we're done. */
8148 stop_reply = queued_stop_reply (ptid);
8149 if (stop_reply != NULL)
8150 return process_stop_reply (stop_reply, status);
8151
8152 /* Still no event. If we're just polling for an event, then
8153 return to the event loop. */
8154 if (options & TARGET_WNOHANG)
8155 {
8156 status->set_ignore ();
8157 return minus_one_ptid;
8158 }
8159
8160 /* Otherwise do a blocking wait. */
8161 ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
8162 }
8163 }
8164
8165 /* Return the first resumed thread. */
8166
8167 static ptid_t
8168 first_remote_resumed_thread (remote_target *target)
8169 {
8170 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8171 if (tp->resumed ())
8172 return tp->ptid;
8173 return null_ptid;
8174 }
8175
8176 /* Wait until the remote machine stops, then return, storing status in
8177 STATUS just as `wait' would. */
8178
8179 ptid_t
8180 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8181 target_wait_flags options)
8182 {
8183 struct remote_state *rs = get_remote_state ();
8184 ptid_t event_ptid = null_ptid;
8185 char *buf;
8186 struct stop_reply *stop_reply;
8187
8188 again:
8189
8190 status->set_ignore ();
8191
8192 stop_reply = queued_stop_reply (ptid);
8193 if (stop_reply != NULL)
8194 {
8195 /* None of the paths that push a stop reply onto the queue should
8196 have set the waiting_for_stop_reply flag. */
8197 gdb_assert (!rs->waiting_for_stop_reply);
8198 event_ptid = process_stop_reply (stop_reply, status);
8199 }
8200 else
8201 {
8202 int forever = ((options & TARGET_WNOHANG) == 0
8203 && rs->wait_forever_enabled_p);
8204
8205 if (!rs->waiting_for_stop_reply)
8206 {
8207 status->set_no_resumed ();
8208 return minus_one_ptid;
8209 }
8210
8211 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8212 _never_ wait for ever -> test on target_is_async_p().
8213 However, before we do that we need to ensure that the caller
8214 knows how to take the target into/out of async mode. */
8215 int is_notif;
8216 int ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
8217
8218 /* GDB gets a notification. Return to core as this event is
8219 not interesting. */
8220 if (ret != -1 && is_notif)
8221 return minus_one_ptid;
8222
8223 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8224 return minus_one_ptid;
8225
8226 buf = rs->buf.data ();
8227
8228 /* Assume that the target has acknowledged Ctrl-C unless we receive
8229 an 'F' or 'O' packet. */
8230 if (buf[0] != 'F' && buf[0] != 'O')
8231 rs->ctrlc_pending_p = 0;
8232
8233 switch (buf[0])
8234 {
8235 case 'E': /* Error of some sort. */
8236 /* We're out of sync with the target now. Did it continue or
8237 not? Not is more likely, so report a stop. */
8238 rs->waiting_for_stop_reply = 0;
8239
8240 warning (_("Remote failure reply: %s"), buf);
8241 status->set_stopped (GDB_SIGNAL_0);
8242 break;
8243 case 'F': /* File-I/O request. */
8244 /* GDB may access the inferior memory while handling the File-I/O
8245 request, but we don't want GDB accessing memory while waiting
8246 for a stop reply. See the comments in putpkt_binary. Set
8247 waiting_for_stop_reply to 0 temporarily. */
8248 rs->waiting_for_stop_reply = 0;
8249 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8250 rs->ctrlc_pending_p = 0;
8251 /* GDB handled the File-I/O request, and the target is running
8252 again. Keep waiting for events. */
8253 rs->waiting_for_stop_reply = 1;
8254 break;
8255 case 'N': case 'T': case 'S': case 'X': case 'W':
8256 {
8257 /* There is a stop reply to handle. */
8258 rs->waiting_for_stop_reply = 0;
8259
8260 stop_reply
8261 = (struct stop_reply *) remote_notif_parse (this,
8262 &notif_client_stop,
8263 rs->buf.data ());
8264
8265 event_ptid = process_stop_reply (stop_reply, status);
8266 break;
8267 }
8268 case 'O': /* Console output. */
8269 remote_console_output (buf + 1);
8270 break;
8271 case '\0':
8272 if (rs->last_sent_signal != GDB_SIGNAL_0)
8273 {
8274 /* Zero length reply means that we tried 'S' or 'C' and the
8275 remote system doesn't support it. */
8276 target_terminal::ours_for_output ();
8277 printf_filtered
8278 ("Can't send signals to this remote system. %s not sent.\n",
8279 gdb_signal_to_name (rs->last_sent_signal));
8280 rs->last_sent_signal = GDB_SIGNAL_0;
8281 target_terminal::inferior ();
8282
8283 strcpy (buf, rs->last_sent_step ? "s" : "c");
8284 putpkt (buf);
8285 break;
8286 }
8287 /* fallthrough */
8288 default:
8289 warning (_("Invalid remote reply: %s"), buf);
8290 break;
8291 }
8292 }
8293
8294 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8295 return minus_one_ptid;
8296 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8297 {
8298 /* Nothing interesting happened. If we're doing a non-blocking
8299 poll, we're done. Otherwise, go back to waiting. */
8300 if (options & TARGET_WNOHANG)
8301 return minus_one_ptid;
8302 else
8303 goto again;
8304 }
8305 else if (status->kind () != TARGET_WAITKIND_EXITED
8306 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8307 {
8308 if (event_ptid != null_ptid)
8309 record_currthread (rs, event_ptid);
8310 else
8311 event_ptid = first_remote_resumed_thread (this);
8312 }
8313 else
8314 {
8315 /* A process exit. Invalidate our notion of current thread. */
8316 record_currthread (rs, minus_one_ptid);
8317 /* It's possible that the packet did not include a pid. */
8318 if (event_ptid == null_ptid)
8319 event_ptid = first_remote_resumed_thread (this);
8320 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8321 if (event_ptid == null_ptid)
8322 event_ptid = magic_null_ptid;
8323 }
8324
8325 return event_ptid;
8326 }
8327
8328 /* Wait until the remote machine stops, then return, storing status in
8329 STATUS just as `wait' would. */
8330
8331 ptid_t
8332 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8333 target_wait_flags options)
8334 {
8335 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8336
8337 remote_state *rs = get_remote_state ();
8338
8339 /* Start by clearing the flag that asks for our wait method to be called,
8340 we'll mark it again at the end if needed. If the target is not in
8341 async mode then the async token should not be marked. */
8342 if (target_is_async_p ())
8343 clear_async_event_handler (rs->remote_async_inferior_event_token);
8344 else
8345 gdb_assert (!async_event_handler_marked
8346 (rs->remote_async_inferior_event_token));
8347
8348 ptid_t event_ptid;
8349
8350 if (target_is_non_stop_p ())
8351 event_ptid = wait_ns (ptid, status, options);
8352 else
8353 event_ptid = wait_as (ptid, status, options);
8354
8355 if (target_is_async_p ())
8356 {
8357 /* If there are events left in the queue, or unacknowledged
8358 notifications, then tell the event loop to call us again. */
8359 if (!rs->stop_reply_queue.empty ()
8360 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8361 mark_async_event_handler (rs->remote_async_inferior_event_token);
8362 }
8363
8364 return event_ptid;
8365 }
8366
8367 /* Fetch a single register using a 'p' packet. */
8368
8369 int
8370 remote_target::fetch_register_using_p (struct regcache *regcache,
8371 packet_reg *reg)
8372 {
8373 struct gdbarch *gdbarch = regcache->arch ();
8374 struct remote_state *rs = get_remote_state ();
8375 char *buf, *p;
8376 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8377 int i;
8378
8379 if (packet_support (PACKET_p) == PACKET_DISABLE)
8380 return 0;
8381
8382 if (reg->pnum == -1)
8383 return 0;
8384
8385 p = rs->buf.data ();
8386 *p++ = 'p';
8387 p += hexnumstr (p, reg->pnum);
8388 *p++ = '\0';
8389 putpkt (rs->buf);
8390 getpkt (&rs->buf, 0);
8391
8392 buf = rs->buf.data ();
8393
8394 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_p]))
8395 {
8396 case PACKET_OK:
8397 break;
8398 case PACKET_UNKNOWN:
8399 return 0;
8400 case PACKET_ERROR:
8401 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8402 gdbarch_register_name (regcache->arch (),
8403 reg->regnum),
8404 buf);
8405 }
8406
8407 /* If this register is unfetchable, tell the regcache. */
8408 if (buf[0] == 'x')
8409 {
8410 regcache->raw_supply (reg->regnum, NULL);
8411 return 1;
8412 }
8413
8414 /* Otherwise, parse and supply the value. */
8415 p = buf;
8416 i = 0;
8417 while (p[0] != 0)
8418 {
8419 if (p[1] == 0)
8420 error (_("fetch_register_using_p: early buf termination"));
8421
8422 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8423 p += 2;
8424 }
8425 regcache->raw_supply (reg->regnum, regp);
8426 return 1;
8427 }
8428
8429 /* Fetch the registers included in the target's 'g' packet. */
8430
8431 int
8432 remote_target::send_g_packet ()
8433 {
8434 struct remote_state *rs = get_remote_state ();
8435 int buf_len;
8436
8437 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8438 putpkt (rs->buf);
8439 getpkt (&rs->buf, 0);
8440 if (packet_check_result (rs->buf) == PACKET_ERROR)
8441 error (_("Could not read registers; remote failure reply '%s'"),
8442 rs->buf.data ());
8443
8444 /* We can get out of synch in various cases. If the first character
8445 in the buffer is not a hex character, assume that has happened
8446 and try to fetch another packet to read. */
8447 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8448 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8449 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8450 && rs->buf[0] != 'x') /* New: unavailable register value. */
8451 {
8452 remote_debug_printf ("Bad register packet; fetching a new packet");
8453 getpkt (&rs->buf, 0);
8454 }
8455
8456 buf_len = strlen (rs->buf.data ());
8457
8458 /* Sanity check the received packet. */
8459 if (buf_len % 2 != 0)
8460 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8461
8462 return buf_len / 2;
8463 }
8464
8465 void
8466 remote_target::process_g_packet (struct regcache *regcache)
8467 {
8468 struct gdbarch *gdbarch = regcache->arch ();
8469 struct remote_state *rs = get_remote_state ();
8470 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8471 int i, buf_len;
8472 char *p;
8473 char *regs;
8474
8475 buf_len = strlen (rs->buf.data ());
8476
8477 /* Further sanity checks, with knowledge of the architecture. */
8478 if (buf_len > 2 * rsa->sizeof_g_packet)
8479 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8480 "bytes): %s"),
8481 rsa->sizeof_g_packet, buf_len / 2,
8482 rs->buf.data ());
8483
8484 /* Save the size of the packet sent to us by the target. It is used
8485 as a heuristic when determining the max size of packets that the
8486 target can safely receive. */
8487 if (rsa->actual_register_packet_size == 0)
8488 rsa->actual_register_packet_size = buf_len;
8489
8490 /* If this is smaller than we guessed the 'g' packet would be,
8491 update our records. A 'g' reply that doesn't include a register's
8492 value implies either that the register is not available, or that
8493 the 'p' packet must be used. */
8494 if (buf_len < 2 * rsa->sizeof_g_packet)
8495 {
8496 long sizeof_g_packet = buf_len / 2;
8497
8498 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8499 {
8500 long offset = rsa->regs[i].offset;
8501 long reg_size = register_size (gdbarch, i);
8502
8503 if (rsa->regs[i].pnum == -1)
8504 continue;
8505
8506 if (offset >= sizeof_g_packet)
8507 rsa->regs[i].in_g_packet = 0;
8508 else if (offset + reg_size > sizeof_g_packet)
8509 error (_("Truncated register %d in remote 'g' packet"), i);
8510 else
8511 rsa->regs[i].in_g_packet = 1;
8512 }
8513
8514 /* Looks valid enough, we can assume this is the correct length
8515 for a 'g' packet. It's important not to adjust
8516 rsa->sizeof_g_packet if we have truncated registers otherwise
8517 this "if" won't be run the next time the method is called
8518 with a packet of the same size and one of the internal errors
8519 below will trigger instead. */
8520 rsa->sizeof_g_packet = sizeof_g_packet;
8521 }
8522
8523 regs = (char *) alloca (rsa->sizeof_g_packet);
8524
8525 /* Unimplemented registers read as all bits zero. */
8526 memset (regs, 0, rsa->sizeof_g_packet);
8527
8528 /* Reply describes registers byte by byte, each byte encoded as two
8529 hex characters. Suck them all up, then supply them to the
8530 register cacheing/storage mechanism. */
8531
8532 p = rs->buf.data ();
8533 for (i = 0; i < rsa->sizeof_g_packet; i++)
8534 {
8535 if (p[0] == 0 || p[1] == 0)
8536 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8537 internal_error (__FILE__, __LINE__,
8538 _("unexpected end of 'g' packet reply"));
8539
8540 if (p[0] == 'x' && p[1] == 'x')
8541 regs[i] = 0; /* 'x' */
8542 else
8543 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8544 p += 2;
8545 }
8546
8547 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8548 {
8549 struct packet_reg *r = &rsa->regs[i];
8550 long reg_size = register_size (gdbarch, i);
8551
8552 if (r->in_g_packet)
8553 {
8554 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8555 /* This shouldn't happen - we adjusted in_g_packet above. */
8556 internal_error (__FILE__, __LINE__,
8557 _("unexpected end of 'g' packet reply"));
8558 else if (rs->buf[r->offset * 2] == 'x')
8559 {
8560 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8561 /* The register isn't available, mark it as such (at
8562 the same time setting the value to zero). */
8563 regcache->raw_supply (r->regnum, NULL);
8564 }
8565 else
8566 regcache->raw_supply (r->regnum, regs + r->offset);
8567 }
8568 }
8569 }
8570
8571 void
8572 remote_target::fetch_registers_using_g (struct regcache *regcache)
8573 {
8574 send_g_packet ();
8575 process_g_packet (regcache);
8576 }
8577
8578 /* Make the remote selected traceframe match GDB's selected
8579 traceframe. */
8580
8581 void
8582 remote_target::set_remote_traceframe ()
8583 {
8584 int newnum;
8585 struct remote_state *rs = get_remote_state ();
8586
8587 if (rs->remote_traceframe_number == get_traceframe_number ())
8588 return;
8589
8590 /* Avoid recursion, remote_trace_find calls us again. */
8591 rs->remote_traceframe_number = get_traceframe_number ();
8592
8593 newnum = target_trace_find (tfind_number,
8594 get_traceframe_number (), 0, 0, NULL);
8595
8596 /* Should not happen. If it does, all bets are off. */
8597 if (newnum != get_traceframe_number ())
8598 warning (_("could not set remote traceframe"));
8599 }
8600
8601 void
8602 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8603 {
8604 struct gdbarch *gdbarch = regcache->arch ();
8605 struct remote_state *rs = get_remote_state ();
8606 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8607 int i;
8608
8609 set_remote_traceframe ();
8610 set_general_thread (regcache->ptid ());
8611
8612 if (regnum >= 0)
8613 {
8614 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8615
8616 gdb_assert (reg != NULL);
8617
8618 /* If this register might be in the 'g' packet, try that first -
8619 we are likely to read more than one register. If this is the
8620 first 'g' packet, we might be overly optimistic about its
8621 contents, so fall back to 'p'. */
8622 if (reg->in_g_packet)
8623 {
8624 fetch_registers_using_g (regcache);
8625 if (reg->in_g_packet)
8626 return;
8627 }
8628
8629 if (fetch_register_using_p (regcache, reg))
8630 return;
8631
8632 /* This register is not available. */
8633 regcache->raw_supply (reg->regnum, NULL);
8634
8635 return;
8636 }
8637
8638 fetch_registers_using_g (regcache);
8639
8640 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8641 if (!rsa->regs[i].in_g_packet)
8642 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8643 {
8644 /* This register is not available. */
8645 regcache->raw_supply (i, NULL);
8646 }
8647 }
8648
8649 /* Prepare to store registers. Since we may send them all (using a
8650 'G' request), we have to read out the ones we don't want to change
8651 first. */
8652
8653 void
8654 remote_target::prepare_to_store (struct regcache *regcache)
8655 {
8656 struct remote_state *rs = get_remote_state ();
8657 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8658 int i;
8659
8660 /* Make sure the entire registers array is valid. */
8661 switch (packet_support (PACKET_P))
8662 {
8663 case PACKET_DISABLE:
8664 case PACKET_SUPPORT_UNKNOWN:
8665 /* Make sure all the necessary registers are cached. */
8666 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8667 if (rsa->regs[i].in_g_packet)
8668 regcache->raw_update (rsa->regs[i].regnum);
8669 break;
8670 case PACKET_ENABLE:
8671 break;
8672 }
8673 }
8674
8675 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8676 packet was not recognized. */
8677
8678 int
8679 remote_target::store_register_using_P (const struct regcache *regcache,
8680 packet_reg *reg)
8681 {
8682 struct gdbarch *gdbarch = regcache->arch ();
8683 struct remote_state *rs = get_remote_state ();
8684 /* Try storing a single register. */
8685 char *buf = rs->buf.data ();
8686 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8687 char *p;
8688
8689 if (packet_support (PACKET_P) == PACKET_DISABLE)
8690 return 0;
8691
8692 if (reg->pnum == -1)
8693 return 0;
8694
8695 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8696 p = buf + strlen (buf);
8697 regcache->raw_collect (reg->regnum, regp);
8698 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8699 putpkt (rs->buf);
8700 getpkt (&rs->buf, 0);
8701
8702 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8703 {
8704 case PACKET_OK:
8705 return 1;
8706 case PACKET_ERROR:
8707 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8708 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
8709 case PACKET_UNKNOWN:
8710 return 0;
8711 default:
8712 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8713 }
8714 }
8715
8716 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8717 contents of the register cache buffer. FIXME: ignores errors. */
8718
8719 void
8720 remote_target::store_registers_using_G (const struct regcache *regcache)
8721 {
8722 struct remote_state *rs = get_remote_state ();
8723 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8724 gdb_byte *regs;
8725 char *p;
8726
8727 /* Extract all the registers in the regcache copying them into a
8728 local buffer. */
8729 {
8730 int i;
8731
8732 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8733 memset (regs, 0, rsa->sizeof_g_packet);
8734 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8735 {
8736 struct packet_reg *r = &rsa->regs[i];
8737
8738 if (r->in_g_packet)
8739 regcache->raw_collect (r->regnum, regs + r->offset);
8740 }
8741 }
8742
8743 /* Command describes registers byte by byte,
8744 each byte encoded as two hex characters. */
8745 p = rs->buf.data ();
8746 *p++ = 'G';
8747 bin2hex (regs, p, rsa->sizeof_g_packet);
8748 putpkt (rs->buf);
8749 getpkt (&rs->buf, 0);
8750 if (packet_check_result (rs->buf) == PACKET_ERROR)
8751 error (_("Could not write registers; remote failure reply '%s'"),
8752 rs->buf.data ());
8753 }
8754
8755 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8756 of the register cache buffer. FIXME: ignores errors. */
8757
8758 void
8759 remote_target::store_registers (struct regcache *regcache, int regnum)
8760 {
8761 struct gdbarch *gdbarch = regcache->arch ();
8762 struct remote_state *rs = get_remote_state ();
8763 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8764 int i;
8765
8766 set_remote_traceframe ();
8767 set_general_thread (regcache->ptid ());
8768
8769 if (regnum >= 0)
8770 {
8771 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8772
8773 gdb_assert (reg != NULL);
8774
8775 /* Always prefer to store registers using the 'P' packet if
8776 possible; we often change only a small number of registers.
8777 Sometimes we change a larger number; we'd need help from a
8778 higher layer to know to use 'G'. */
8779 if (store_register_using_P (regcache, reg))
8780 return;
8781
8782 /* For now, don't complain if we have no way to write the
8783 register. GDB loses track of unavailable registers too
8784 easily. Some day, this may be an error. We don't have
8785 any way to read the register, either... */
8786 if (!reg->in_g_packet)
8787 return;
8788
8789 store_registers_using_G (regcache);
8790 return;
8791 }
8792
8793 store_registers_using_G (regcache);
8794
8795 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8796 if (!rsa->regs[i].in_g_packet)
8797 if (!store_register_using_P (regcache, &rsa->regs[i]))
8798 /* See above for why we do not issue an error here. */
8799 continue;
8800 }
8801 \f
8802
8803 /* Return the number of hex digits in num. */
8804
8805 static int
8806 hexnumlen (ULONGEST num)
8807 {
8808 int i;
8809
8810 for (i = 0; num != 0; i++)
8811 num >>= 4;
8812
8813 return std::max (i, 1);
8814 }
8815
8816 /* Set BUF to the minimum number of hex digits representing NUM. */
8817
8818 static int
8819 hexnumstr (char *buf, ULONGEST num)
8820 {
8821 int len = hexnumlen (num);
8822
8823 return hexnumnstr (buf, num, len);
8824 }
8825
8826
8827 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
8828
8829 static int
8830 hexnumnstr (char *buf, ULONGEST num, int width)
8831 {
8832 int i;
8833
8834 buf[width] = '\0';
8835
8836 for (i = width - 1; i >= 0; i--)
8837 {
8838 buf[i] = "0123456789abcdef"[(num & 0xf)];
8839 num >>= 4;
8840 }
8841
8842 return width;
8843 }
8844
8845 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8846
8847 static CORE_ADDR
8848 remote_address_masked (CORE_ADDR addr)
8849 {
8850 unsigned int address_size = remote_address_size;
8851
8852 /* If "remoteaddresssize" was not set, default to target address size. */
8853 if (!address_size)
8854 address_size = gdbarch_addr_bit (target_gdbarch ());
8855
8856 if (address_size > 0
8857 && address_size < (sizeof (ULONGEST) * 8))
8858 {
8859 /* Only create a mask when that mask can safely be constructed
8860 in a ULONGEST variable. */
8861 ULONGEST mask = 1;
8862
8863 mask = (mask << address_size) - 1;
8864 addr &= mask;
8865 }
8866 return addr;
8867 }
8868
8869 /* Determine whether the remote target supports binary downloading.
8870 This is accomplished by sending a no-op memory write of zero length
8871 to the target at the specified address. It does not suffice to send
8872 the whole packet, since many stubs strip the eighth bit and
8873 subsequently compute a wrong checksum, which causes real havoc with
8874 remote_write_bytes.
8875
8876 NOTE: This can still lose if the serial line is not eight-bit
8877 clean. In cases like this, the user should clear "remote
8878 X-packet". */
8879
8880 void
8881 remote_target::check_binary_download (CORE_ADDR addr)
8882 {
8883 struct remote_state *rs = get_remote_state ();
8884
8885 switch (packet_support (PACKET_X))
8886 {
8887 case PACKET_DISABLE:
8888 break;
8889 case PACKET_ENABLE:
8890 break;
8891 case PACKET_SUPPORT_UNKNOWN:
8892 {
8893 char *p;
8894
8895 p = rs->buf.data ();
8896 *p++ = 'X';
8897 p += hexnumstr (p, (ULONGEST) addr);
8898 *p++ = ',';
8899 p += hexnumstr (p, (ULONGEST) 0);
8900 *p++ = ':';
8901 *p = '\0';
8902
8903 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
8904 getpkt (&rs->buf, 0);
8905
8906 if (rs->buf[0] == '\0')
8907 {
8908 remote_debug_printf ("binary downloading NOT supported by target");
8909 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8910 }
8911 else
8912 {
8913 remote_debug_printf ("binary downloading supported by target");
8914 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8915 }
8916 break;
8917 }
8918 }
8919 }
8920
8921 /* Helper function to resize the payload in order to try to get a good
8922 alignment. We try to write an amount of data such that the next write will
8923 start on an address aligned on REMOTE_ALIGN_WRITES. */
8924
8925 static int
8926 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8927 {
8928 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8929 }
8930
8931 /* Write memory data directly to the remote machine.
8932 This does not inform the data cache; the data cache uses this.
8933 HEADER is the starting part of the packet.
8934 MEMADDR is the address in the remote memory space.
8935 MYADDR is the address of the buffer in our space.
8936 LEN_UNITS is the number of addressable units to write.
8937 UNIT_SIZE is the length in bytes of an addressable unit.
8938 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8939 should send data as binary ('X'), or hex-encoded ('M').
8940
8941 The function creates packet of the form
8942 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8943
8944 where encoding of <DATA> is terminated by PACKET_FORMAT.
8945
8946 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8947 are omitted.
8948
8949 Return the transferred status, error or OK (an
8950 'enum target_xfer_status' value). Save the number of addressable units
8951 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8952
8953 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8954 exchange between gdb and the stub could look like (?? in place of the
8955 checksum):
8956
8957 -> $m1000,4#??
8958 <- aaaabbbbccccdddd
8959
8960 -> $M1000,3:eeeeffffeeee#??
8961 <- OK
8962
8963 -> $m1000,4#??
8964 <- eeeeffffeeeedddd */
8965
8966 target_xfer_status
8967 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8968 const gdb_byte *myaddr,
8969 ULONGEST len_units,
8970 int unit_size,
8971 ULONGEST *xfered_len_units,
8972 char packet_format, int use_length)
8973 {
8974 struct remote_state *rs = get_remote_state ();
8975 char *p;
8976 char *plen = NULL;
8977 int plenlen = 0;
8978 int todo_units;
8979 int units_written;
8980 int payload_capacity_bytes;
8981 int payload_length_bytes;
8982
8983 if (packet_format != 'X' && packet_format != 'M')
8984 internal_error (__FILE__, __LINE__,
8985 _("remote_write_bytes_aux: bad packet format"));
8986
8987 if (len_units == 0)
8988 return TARGET_XFER_EOF;
8989
8990 payload_capacity_bytes = get_memory_write_packet_size ();
8991
8992 /* The packet buffer will be large enough for the payload;
8993 get_memory_packet_size ensures this. */
8994 rs->buf[0] = '\0';
8995
8996 /* Compute the size of the actual payload by subtracting out the
8997 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8998
8999 payload_capacity_bytes -= strlen ("$,:#NN");
9000 if (!use_length)
9001 /* The comma won't be used. */
9002 payload_capacity_bytes += 1;
9003 payload_capacity_bytes -= strlen (header);
9004 payload_capacity_bytes -= hexnumlen (memaddr);
9005
9006 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9007
9008 strcat (rs->buf.data (), header);
9009 p = rs->buf.data () + strlen (header);
9010
9011 /* Compute a best guess of the number of bytes actually transfered. */
9012 if (packet_format == 'X')
9013 {
9014 /* Best guess at number of bytes that will fit. */
9015 todo_units = std::min (len_units,
9016 (ULONGEST) payload_capacity_bytes / unit_size);
9017 if (use_length)
9018 payload_capacity_bytes -= hexnumlen (todo_units);
9019 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9020 }
9021 else
9022 {
9023 /* Number of bytes that will fit. */
9024 todo_units
9025 = std::min (len_units,
9026 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9027 if (use_length)
9028 payload_capacity_bytes -= hexnumlen (todo_units);
9029 todo_units = std::min (todo_units,
9030 (payload_capacity_bytes / unit_size) / 2);
9031 }
9032
9033 if (todo_units <= 0)
9034 internal_error (__FILE__, __LINE__,
9035 _("minimum packet size too small to write data"));
9036
9037 /* If we already need another packet, then try to align the end
9038 of this packet to a useful boundary. */
9039 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9040 todo_units = align_for_efficient_write (todo_units, memaddr);
9041
9042 /* Append "<memaddr>". */
9043 memaddr = remote_address_masked (memaddr);
9044 p += hexnumstr (p, (ULONGEST) memaddr);
9045
9046 if (use_length)
9047 {
9048 /* Append ",". */
9049 *p++ = ',';
9050
9051 /* Append the length and retain its location and size. It may need to be
9052 adjusted once the packet body has been created. */
9053 plen = p;
9054 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9055 p += plenlen;
9056 }
9057
9058 /* Append ":". */
9059 *p++ = ':';
9060 *p = '\0';
9061
9062 /* Append the packet body. */
9063 if (packet_format == 'X')
9064 {
9065 /* Binary mode. Send target system values byte by byte, in
9066 increasing byte addresses. Only escape certain critical
9067 characters. */
9068 payload_length_bytes =
9069 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9070 &units_written, payload_capacity_bytes);
9071
9072 /* If not all TODO units fit, then we'll need another packet. Make
9073 a second try to keep the end of the packet aligned. Don't do
9074 this if the packet is tiny. */
9075 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9076 {
9077 int new_todo_units;
9078
9079 new_todo_units = align_for_efficient_write (units_written, memaddr);
9080
9081 if (new_todo_units != units_written)
9082 payload_length_bytes =
9083 remote_escape_output (myaddr, new_todo_units, unit_size,
9084 (gdb_byte *) p, &units_written,
9085 payload_capacity_bytes);
9086 }
9087
9088 p += payload_length_bytes;
9089 if (use_length && units_written < todo_units)
9090 {
9091 /* Escape chars have filled up the buffer prematurely,
9092 and we have actually sent fewer units than planned.
9093 Fix-up the length field of the packet. Use the same
9094 number of characters as before. */
9095 plen += hexnumnstr (plen, (ULONGEST) units_written,
9096 plenlen);
9097 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9098 }
9099 }
9100 else
9101 {
9102 /* Normal mode: Send target system values byte by byte, in
9103 increasing byte addresses. Each byte is encoded as a two hex
9104 value. */
9105 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9106 units_written = todo_units;
9107 }
9108
9109 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9110 getpkt (&rs->buf, 0);
9111
9112 if (rs->buf[0] == 'E')
9113 return TARGET_XFER_E_IO;
9114
9115 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9116 send fewer units than we'd planned. */
9117 *xfered_len_units = (ULONGEST) units_written;
9118 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9119 }
9120
9121 /* Write memory data directly to the remote machine.
9122 This does not inform the data cache; the data cache uses this.
9123 MEMADDR is the address in the remote memory space.
9124 MYADDR is the address of the buffer in our space.
9125 LEN is the number of bytes.
9126
9127 Return the transferred status, error or OK (an
9128 'enum target_xfer_status' value). Save the number of bytes
9129 transferred in *XFERED_LEN. Only transfer a single packet. */
9130
9131 target_xfer_status
9132 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9133 ULONGEST len, int unit_size,
9134 ULONGEST *xfered_len)
9135 {
9136 const char *packet_format = NULL;
9137
9138 /* Check whether the target supports binary download. */
9139 check_binary_download (memaddr);
9140
9141 switch (packet_support (PACKET_X))
9142 {
9143 case PACKET_ENABLE:
9144 packet_format = "X";
9145 break;
9146 case PACKET_DISABLE:
9147 packet_format = "M";
9148 break;
9149 case PACKET_SUPPORT_UNKNOWN:
9150 internal_error (__FILE__, __LINE__,
9151 _("remote_write_bytes: bad internal state"));
9152 default:
9153 internal_error (__FILE__, __LINE__, _("bad switch"));
9154 }
9155
9156 return remote_write_bytes_aux (packet_format,
9157 memaddr, myaddr, len, unit_size, xfered_len,
9158 packet_format[0], 1);
9159 }
9160
9161 /* Read memory data directly from the remote machine.
9162 This does not use the data cache; the data cache uses this.
9163 MEMADDR is the address in the remote memory space.
9164 MYADDR is the address of the buffer in our space.
9165 LEN_UNITS is the number of addressable memory units to read..
9166 UNIT_SIZE is the length in bytes of an addressable unit.
9167
9168 Return the transferred status, error or OK (an
9169 'enum target_xfer_status' value). Save the number of bytes
9170 transferred in *XFERED_LEN_UNITS.
9171
9172 See the comment of remote_write_bytes_aux for an example of
9173 memory read/write exchange between gdb and the stub. */
9174
9175 target_xfer_status
9176 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9177 ULONGEST len_units,
9178 int unit_size, ULONGEST *xfered_len_units)
9179 {
9180 struct remote_state *rs = get_remote_state ();
9181 int buf_size_bytes; /* Max size of packet output buffer. */
9182 char *p;
9183 int todo_units;
9184 int decoded_bytes;
9185
9186 buf_size_bytes = get_memory_read_packet_size ();
9187 /* The packet buffer will be large enough for the payload;
9188 get_memory_packet_size ensures this. */
9189
9190 /* Number of units that will fit. */
9191 todo_units = std::min (len_units,
9192 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9193
9194 /* Construct "m"<memaddr>","<len>". */
9195 memaddr = remote_address_masked (memaddr);
9196 p = rs->buf.data ();
9197 *p++ = 'm';
9198 p += hexnumstr (p, (ULONGEST) memaddr);
9199 *p++ = ',';
9200 p += hexnumstr (p, (ULONGEST) todo_units);
9201 *p = '\0';
9202 putpkt (rs->buf);
9203 getpkt (&rs->buf, 0);
9204 if (rs->buf[0] == 'E'
9205 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9206 && rs->buf[3] == '\0')
9207 return TARGET_XFER_E_IO;
9208 /* Reply describes memory byte by byte, each byte encoded as two hex
9209 characters. */
9210 p = rs->buf.data ();
9211 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9212 /* Return what we have. Let higher layers handle partial reads. */
9213 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9214 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9215 }
9216
9217 /* Using the set of read-only target sections of remote, read live
9218 read-only memory.
9219
9220 For interface/parameters/return description see target.h,
9221 to_xfer_partial. */
9222
9223 target_xfer_status
9224 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9225 ULONGEST memaddr,
9226 ULONGEST len,
9227 int unit_size,
9228 ULONGEST *xfered_len)
9229 {
9230 const struct target_section *secp;
9231
9232 secp = target_section_by_addr (this, memaddr);
9233 if (secp != NULL
9234 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9235 {
9236 ULONGEST memend = memaddr + len;
9237
9238 const target_section_table *table = target_get_section_table (this);
9239 for (const target_section &p : *table)
9240 {
9241 if (memaddr >= p.addr)
9242 {
9243 if (memend <= p.endaddr)
9244 {
9245 /* Entire transfer is within this section. */
9246 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9247 xfered_len);
9248 }
9249 else if (memaddr >= p.endaddr)
9250 {
9251 /* This section ends before the transfer starts. */
9252 continue;
9253 }
9254 else
9255 {
9256 /* This section overlaps the transfer. Just do half. */
9257 len = p.endaddr - memaddr;
9258 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9259 xfered_len);
9260 }
9261 }
9262 }
9263 }
9264
9265 return TARGET_XFER_EOF;
9266 }
9267
9268 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9269 first if the requested memory is unavailable in traceframe.
9270 Otherwise, fall back to remote_read_bytes_1. */
9271
9272 target_xfer_status
9273 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9274 gdb_byte *myaddr, ULONGEST len, int unit_size,
9275 ULONGEST *xfered_len)
9276 {
9277 if (len == 0)
9278 return TARGET_XFER_EOF;
9279
9280 if (get_traceframe_number () != -1)
9281 {
9282 std::vector<mem_range> available;
9283
9284 /* If we fail to get the set of available memory, then the
9285 target does not support querying traceframe info, and so we
9286 attempt reading from the traceframe anyway (assuming the
9287 target implements the old QTro packet then). */
9288 if (traceframe_available_memory (&available, memaddr, len))
9289 {
9290 if (available.empty () || available[0].start != memaddr)
9291 {
9292 enum target_xfer_status res;
9293
9294 /* Don't read into the traceframe's available
9295 memory. */
9296 if (!available.empty ())
9297 {
9298 LONGEST oldlen = len;
9299
9300 len = available[0].start - memaddr;
9301 gdb_assert (len <= oldlen);
9302 }
9303
9304 /* This goes through the topmost target again. */
9305 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9306 len, unit_size, xfered_len);
9307 if (res == TARGET_XFER_OK)
9308 return TARGET_XFER_OK;
9309 else
9310 {
9311 /* No use trying further, we know some memory starting
9312 at MEMADDR isn't available. */
9313 *xfered_len = len;
9314 return (*xfered_len != 0) ?
9315 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9316 }
9317 }
9318
9319 /* Don't try to read more than how much is available, in
9320 case the target implements the deprecated QTro packet to
9321 cater for older GDBs (the target's knowledge of read-only
9322 sections may be outdated by now). */
9323 len = available[0].length;
9324 }
9325 }
9326
9327 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9328 }
9329
9330 \f
9331
9332 /* Sends a packet with content determined by the printf format string
9333 FORMAT and the remaining arguments, then gets the reply. Returns
9334 whether the packet was a success, a failure, or unknown. */
9335
9336 packet_result
9337 remote_target::remote_send_printf (const char *format, ...)
9338 {
9339 struct remote_state *rs = get_remote_state ();
9340 int max_size = get_remote_packet_size ();
9341 va_list ap;
9342
9343 va_start (ap, format);
9344
9345 rs->buf[0] = '\0';
9346 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9347
9348 va_end (ap);
9349
9350 if (size >= max_size)
9351 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
9352
9353 if (putpkt (rs->buf) < 0)
9354 error (_("Communication problem with target."));
9355
9356 rs->buf[0] = '\0';
9357 getpkt (&rs->buf, 0);
9358
9359 return packet_check_result (rs->buf);
9360 }
9361
9362 /* Flash writing can take quite some time. We'll set
9363 effectively infinite timeout for flash operations.
9364 In future, we'll need to decide on a better approach. */
9365 static const int remote_flash_timeout = 1000;
9366
9367 void
9368 remote_target::flash_erase (ULONGEST address, LONGEST length)
9369 {
9370 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9371 enum packet_result ret;
9372 scoped_restore restore_timeout
9373 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9374
9375 ret = remote_send_printf ("vFlashErase:%s,%s",
9376 phex (address, addr_size),
9377 phex (length, 4));
9378 switch (ret)
9379 {
9380 case PACKET_UNKNOWN:
9381 error (_("Remote target does not support flash erase"));
9382 case PACKET_ERROR:
9383 error (_("Error erasing flash with vFlashErase packet"));
9384 default:
9385 break;
9386 }
9387 }
9388
9389 target_xfer_status
9390 remote_target::remote_flash_write (ULONGEST address,
9391 ULONGEST length, ULONGEST *xfered_len,
9392 const gdb_byte *data)
9393 {
9394 scoped_restore restore_timeout
9395 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9396 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9397 xfered_len,'X', 0);
9398 }
9399
9400 void
9401 remote_target::flash_done ()
9402 {
9403 int ret;
9404
9405 scoped_restore restore_timeout
9406 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9407
9408 ret = remote_send_printf ("vFlashDone");
9409
9410 switch (ret)
9411 {
9412 case PACKET_UNKNOWN:
9413 error (_("Remote target does not support vFlashDone"));
9414 case PACKET_ERROR:
9415 error (_("Error finishing flash operation"));
9416 default:
9417 break;
9418 }
9419 }
9420
9421 \f
9422 /* Stuff for dealing with the packets which are part of this protocol.
9423 See comment at top of file for details. */
9424
9425 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9426 error to higher layers. Called when a serial error is detected.
9427 The exception message is STRING, followed by a colon and a blank,
9428 the system error message for errno at function entry and final dot
9429 for output compatibility with throw_perror_with_name. */
9430
9431 static void
9432 unpush_and_perror (remote_target *target, const char *string)
9433 {
9434 int saved_errno = errno;
9435
9436 remote_unpush_target (target);
9437 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9438 safe_strerror (saved_errno));
9439 }
9440
9441 /* Read a single character from the remote end. The current quit
9442 handler is overridden to avoid quitting in the middle of packet
9443 sequence, as that would break communication with the remote server.
9444 See remote_serial_quit_handler for more detail. */
9445
9446 int
9447 remote_target::readchar (int timeout)
9448 {
9449 int ch;
9450 struct remote_state *rs = get_remote_state ();
9451
9452 {
9453 scoped_restore restore_quit_target
9454 = make_scoped_restore (&curr_quit_handler_target, this);
9455 scoped_restore restore_quit
9456 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9457
9458 rs->got_ctrlc_during_io = 0;
9459
9460 ch = serial_readchar (rs->remote_desc, timeout);
9461
9462 if (rs->got_ctrlc_during_io)
9463 set_quit_flag ();
9464 }
9465
9466 if (ch >= 0)
9467 return ch;
9468
9469 switch ((enum serial_rc) ch)
9470 {
9471 case SERIAL_EOF:
9472 remote_unpush_target (this);
9473 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9474 /* no return */
9475 case SERIAL_ERROR:
9476 unpush_and_perror (this, _("Remote communication error. "
9477 "Target disconnected."));
9478 /* no return */
9479 case SERIAL_TIMEOUT:
9480 break;
9481 }
9482 return ch;
9483 }
9484
9485 /* Wrapper for serial_write that closes the target and throws if
9486 writing fails. The current quit handler is overridden to avoid
9487 quitting in the middle of packet sequence, as that would break
9488 communication with the remote server. See
9489 remote_serial_quit_handler for more detail. */
9490
9491 void
9492 remote_target::remote_serial_write (const char *str, int len)
9493 {
9494 struct remote_state *rs = get_remote_state ();
9495
9496 scoped_restore restore_quit_target
9497 = make_scoped_restore (&curr_quit_handler_target, this);
9498 scoped_restore restore_quit
9499 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9500
9501 rs->got_ctrlc_during_io = 0;
9502
9503 if (serial_write (rs->remote_desc, str, len))
9504 {
9505 unpush_and_perror (this, _("Remote communication error. "
9506 "Target disconnected."));
9507 }
9508
9509 if (rs->got_ctrlc_during_io)
9510 set_quit_flag ();
9511 }
9512
9513 /* Return a string representing an escaped version of BUF, of len N.
9514 E.g. \n is converted to \\n, \t to \\t, etc. */
9515
9516 static std::string
9517 escape_buffer (const char *buf, int n)
9518 {
9519 string_file stb;
9520
9521 stb.putstrn (buf, n, '\\');
9522 return std::move (stb.string ());
9523 }
9524
9525 int
9526 remote_target::putpkt (const char *buf)
9527 {
9528 return putpkt_binary (buf, strlen (buf));
9529 }
9530
9531 /* Wrapper around remote_target::putpkt to avoid exporting
9532 remote_target. */
9533
9534 int
9535 putpkt (remote_target *remote, const char *buf)
9536 {
9537 return remote->putpkt (buf);
9538 }
9539
9540 /* Send a packet to the remote machine, with error checking. The data
9541 of the packet is in BUF. The string in BUF can be at most
9542 get_remote_packet_size () - 5 to account for the $, # and checksum,
9543 and for a possible /0 if we are debugging (remote_debug) and want
9544 to print the sent packet as a string. */
9545
9546 int
9547 remote_target::putpkt_binary (const char *buf, int cnt)
9548 {
9549 struct remote_state *rs = get_remote_state ();
9550 int i;
9551 unsigned char csum = 0;
9552 gdb::def_vector<char> data (cnt + 6);
9553 char *buf2 = data.data ();
9554
9555 int ch;
9556 int tcount = 0;
9557 char *p;
9558
9559 /* Catch cases like trying to read memory or listing threads while
9560 we're waiting for a stop reply. The remote server wouldn't be
9561 ready to handle this request, so we'd hang and timeout. We don't
9562 have to worry about this in synchronous mode, because in that
9563 case it's not possible to issue a command while the target is
9564 running. This is not a problem in non-stop mode, because in that
9565 case, the stub is always ready to process serial input. */
9566 if (!target_is_non_stop_p ()
9567 && target_is_async_p ()
9568 && rs->waiting_for_stop_reply)
9569 {
9570 error (_("Cannot execute this command while the target is running.\n"
9571 "Use the \"interrupt\" command to stop the target\n"
9572 "and then try again."));
9573 }
9574
9575 /* Copy the packet into buffer BUF2, encapsulating it
9576 and giving it a checksum. */
9577
9578 p = buf2;
9579 *p++ = '$';
9580
9581 for (i = 0; i < cnt; i++)
9582 {
9583 csum += buf[i];
9584 *p++ = buf[i];
9585 }
9586 *p++ = '#';
9587 *p++ = tohex ((csum >> 4) & 0xf);
9588 *p++ = tohex (csum & 0xf);
9589
9590 /* Send it over and over until we get a positive ack. */
9591
9592 while (1)
9593 {
9594 if (remote_debug)
9595 {
9596 *p = '\0';
9597
9598 int len = (int) (p - buf2);
9599 int max_chars;
9600
9601 if (remote_packet_max_chars < 0)
9602 max_chars = len;
9603 else
9604 max_chars = remote_packet_max_chars;
9605
9606 std::string str
9607 = escape_buffer (buf2, std::min (len, max_chars));
9608
9609 if (len > max_chars)
9610 remote_debug_printf_nofunc
9611 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9612 len - max_chars);
9613 else
9614 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9615 }
9616 remote_serial_write (buf2, p - buf2);
9617
9618 /* If this is a no acks version of the remote protocol, send the
9619 packet and move on. */
9620 if (rs->noack_mode)
9621 break;
9622
9623 /* Read until either a timeout occurs (-2) or '+' is read.
9624 Handle any notification that arrives in the mean time. */
9625 while (1)
9626 {
9627 ch = readchar (remote_timeout);
9628
9629 switch (ch)
9630 {
9631 case '+':
9632 remote_debug_printf_nofunc ("Received Ack");
9633 return 1;
9634 case '-':
9635 remote_debug_printf_nofunc ("Received Nak");
9636 /* FALLTHROUGH */
9637 case SERIAL_TIMEOUT:
9638 tcount++;
9639 if (tcount > 3)
9640 return 0;
9641 break; /* Retransmit buffer. */
9642 case '$':
9643 {
9644 remote_debug_printf ("Packet instead of Ack, ignoring it");
9645 /* It's probably an old response sent because an ACK
9646 was lost. Gobble up the packet and ack it so it
9647 doesn't get retransmitted when we resend this
9648 packet. */
9649 skip_frame ();
9650 remote_serial_write ("+", 1);
9651 continue; /* Now, go look for +. */
9652 }
9653
9654 case '%':
9655 {
9656 int val;
9657
9658 /* If we got a notification, handle it, and go back to looking
9659 for an ack. */
9660 /* We've found the start of a notification. Now
9661 collect the data. */
9662 val = read_frame (&rs->buf);
9663 if (val >= 0)
9664 {
9665 remote_debug_printf_nofunc
9666 (" Notification received: %s",
9667 escape_buffer (rs->buf.data (), val).c_str ());
9668
9669 handle_notification (rs->notif_state, rs->buf.data ());
9670 /* We're in sync now, rewait for the ack. */
9671 tcount = 0;
9672 }
9673 else
9674 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9675 rs->buf.data ());
9676 continue;
9677 }
9678 /* fall-through */
9679 default:
9680 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9681 rs->buf.data ());
9682 continue;
9683 }
9684 break; /* Here to retransmit. */
9685 }
9686
9687 #if 0
9688 /* This is wrong. If doing a long backtrace, the user should be
9689 able to get out next time we call QUIT, without anything as
9690 violent as interrupt_query. If we want to provide a way out of
9691 here without getting to the next QUIT, it should be based on
9692 hitting ^C twice as in remote_wait. */
9693 if (quit_flag)
9694 {
9695 quit_flag = 0;
9696 interrupt_query ();
9697 }
9698 #endif
9699 }
9700
9701 return 0;
9702 }
9703
9704 /* Come here after finding the start of a frame when we expected an
9705 ack. Do our best to discard the rest of this packet. */
9706
9707 void
9708 remote_target::skip_frame ()
9709 {
9710 int c;
9711
9712 while (1)
9713 {
9714 c = readchar (remote_timeout);
9715 switch (c)
9716 {
9717 case SERIAL_TIMEOUT:
9718 /* Nothing we can do. */
9719 return;
9720 case '#':
9721 /* Discard the two bytes of checksum and stop. */
9722 c = readchar (remote_timeout);
9723 if (c >= 0)
9724 c = readchar (remote_timeout);
9725
9726 return;
9727 case '*': /* Run length encoding. */
9728 /* Discard the repeat count. */
9729 c = readchar (remote_timeout);
9730 if (c < 0)
9731 return;
9732 break;
9733 default:
9734 /* A regular character. */
9735 break;
9736 }
9737 }
9738 }
9739
9740 /* Come here after finding the start of the frame. Collect the rest
9741 into *BUF, verifying the checksum, length, and handling run-length
9742 compression. NUL terminate the buffer. If there is not enough room,
9743 expand *BUF.
9744
9745 Returns -1 on error, number of characters in buffer (ignoring the
9746 trailing NULL) on success. (could be extended to return one of the
9747 SERIAL status indications). */
9748
9749 long
9750 remote_target::read_frame (gdb::char_vector *buf_p)
9751 {
9752 unsigned char csum;
9753 long bc;
9754 int c;
9755 char *buf = buf_p->data ();
9756 struct remote_state *rs = get_remote_state ();
9757
9758 csum = 0;
9759 bc = 0;
9760
9761 while (1)
9762 {
9763 c = readchar (remote_timeout);
9764 switch (c)
9765 {
9766 case SERIAL_TIMEOUT:
9767 remote_debug_printf ("Timeout in mid-packet, retrying");
9768 return -1;
9769
9770 case '$':
9771 remote_debug_printf ("Saw new packet start in middle of old one");
9772 return -1; /* Start a new packet, count retries. */
9773
9774 case '#':
9775 {
9776 unsigned char pktcsum;
9777 int check_0 = 0;
9778 int check_1 = 0;
9779
9780 buf[bc] = '\0';
9781
9782 check_0 = readchar (remote_timeout);
9783 if (check_0 >= 0)
9784 check_1 = readchar (remote_timeout);
9785
9786 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9787 {
9788 remote_debug_printf ("Timeout in checksum, retrying");
9789 return -1;
9790 }
9791 else if (check_0 < 0 || check_1 < 0)
9792 {
9793 remote_debug_printf ("Communication error in checksum");
9794 return -1;
9795 }
9796
9797 /* Don't recompute the checksum; with no ack packets we
9798 don't have any way to indicate a packet retransmission
9799 is necessary. */
9800 if (rs->noack_mode)
9801 return bc;
9802
9803 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9804 if (csum == pktcsum)
9805 return bc;
9806
9807 remote_debug_printf
9808 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
9809 pktcsum, csum, escape_buffer (buf, bc).c_str ());
9810
9811 /* Number of characters in buffer ignoring trailing
9812 NULL. */
9813 return -1;
9814 }
9815 case '*': /* Run length encoding. */
9816 {
9817 int repeat;
9818
9819 csum += c;
9820 c = readchar (remote_timeout);
9821 csum += c;
9822 repeat = c - ' ' + 3; /* Compute repeat count. */
9823
9824 /* The character before ``*'' is repeated. */
9825
9826 if (repeat > 0 && repeat <= 255 && bc > 0)
9827 {
9828 if (bc + repeat - 1 >= buf_p->size () - 1)
9829 {
9830 /* Make some more room in the buffer. */
9831 buf_p->resize (buf_p->size () + repeat);
9832 buf = buf_p->data ();
9833 }
9834
9835 memset (&buf[bc], buf[bc - 1], repeat);
9836 bc += repeat;
9837 continue;
9838 }
9839
9840 buf[bc] = '\0';
9841 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9842 return -1;
9843 }
9844 default:
9845 if (bc >= buf_p->size () - 1)
9846 {
9847 /* Make some more room in the buffer. */
9848 buf_p->resize (buf_p->size () * 2);
9849 buf = buf_p->data ();
9850 }
9851
9852 buf[bc++] = c;
9853 csum += c;
9854 continue;
9855 }
9856 }
9857 }
9858
9859 /* Set this to the maximum number of seconds to wait instead of waiting forever
9860 in target_wait(). If this timer times out, then it generates an error and
9861 the command is aborted. This replaces most of the need for timeouts in the
9862 GDB test suite, and makes it possible to distinguish between a hung target
9863 and one with slow communications. */
9864
9865 static int watchdog = 0;
9866 static void
9867 show_watchdog (struct ui_file *file, int from_tty,
9868 struct cmd_list_element *c, const char *value)
9869 {
9870 fprintf_filtered (file, _("Watchdog timer is %s.\n"), value);
9871 }
9872
9873 /* Read a packet from the remote machine, with error checking, and
9874 store it in *BUF. Resize *BUF if necessary to hold the result. If
9875 FOREVER, wait forever rather than timing out; this is used (in
9876 synchronous mode) to wait for a target that is is executing user
9877 code to stop. */
9878 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9879 don't have to change all the calls to getpkt to deal with the
9880 return value, because at the moment I don't know what the right
9881 thing to do it for those. */
9882
9883 void
9884 remote_target::getpkt (gdb::char_vector *buf, int forever)
9885 {
9886 getpkt_sane (buf, forever);
9887 }
9888
9889
9890 /* Read a packet from the remote machine, with error checking, and
9891 store it in *BUF. Resize *BUF if necessary to hold the result. If
9892 FOREVER, wait forever rather than timing out; this is used (in
9893 synchronous mode) to wait for a target that is is executing user
9894 code to stop. If FOREVER == 0, this function is allowed to time
9895 out gracefully and return an indication of this to the caller.
9896 Otherwise return the number of bytes read. If EXPECTING_NOTIF,
9897 consider receiving a notification enough reason to return to the
9898 caller. *IS_NOTIF is an output boolean that indicates whether *BUF
9899 holds a notification or not (a regular packet). */
9900
9901 int
9902 remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
9903 int forever, int expecting_notif,
9904 int *is_notif)
9905 {
9906 struct remote_state *rs = get_remote_state ();
9907 int c;
9908 int tries;
9909 int timeout;
9910 int val = -1;
9911
9912 strcpy (buf->data (), "timeout");
9913
9914 if (forever)
9915 timeout = watchdog > 0 ? watchdog : -1;
9916 else if (expecting_notif)
9917 timeout = 0; /* There should already be a char in the buffer. If
9918 not, bail out. */
9919 else
9920 timeout = remote_timeout;
9921
9922 #define MAX_TRIES 3
9923
9924 /* Process any number of notifications, and then return when
9925 we get a packet. */
9926 for (;;)
9927 {
9928 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9929 times. */
9930 for (tries = 1; tries <= MAX_TRIES; tries++)
9931 {
9932 /* This can loop forever if the remote side sends us
9933 characters continuously, but if it pauses, we'll get
9934 SERIAL_TIMEOUT from readchar because of timeout. Then
9935 we'll count that as a retry.
9936
9937 Note that even when forever is set, we will only wait
9938 forever prior to the start of a packet. After that, we
9939 expect characters to arrive at a brisk pace. They should
9940 show up within remote_timeout intervals. */
9941 do
9942 c = readchar (timeout);
9943 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9944
9945 if (c == SERIAL_TIMEOUT)
9946 {
9947 if (expecting_notif)
9948 return -1; /* Don't complain, it's normal to not get
9949 anything in this case. */
9950
9951 if (forever) /* Watchdog went off? Kill the target. */
9952 {
9953 remote_unpush_target (this);
9954 throw_error (TARGET_CLOSE_ERROR,
9955 _("Watchdog timeout has expired. "
9956 "Target detached."));
9957 }
9958
9959 remote_debug_printf ("Timed out.");
9960 }
9961 else
9962 {
9963 /* We've found the start of a packet or notification.
9964 Now collect the data. */
9965 val = read_frame (buf);
9966 if (val >= 0)
9967 break;
9968 }
9969
9970 remote_serial_write ("-", 1);
9971 }
9972
9973 if (tries > MAX_TRIES)
9974 {
9975 /* We have tried hard enough, and just can't receive the
9976 packet/notification. Give up. */
9977 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9978
9979 /* Skip the ack char if we're in no-ack mode. */
9980 if (!rs->noack_mode)
9981 remote_serial_write ("+", 1);
9982 return -1;
9983 }
9984
9985 /* If we got an ordinary packet, return that to our caller. */
9986 if (c == '$')
9987 {
9988 if (remote_debug)
9989 {
9990 int max_chars;
9991
9992 if (remote_packet_max_chars < 0)
9993 max_chars = val;
9994 else
9995 max_chars = remote_packet_max_chars;
9996
9997 std::string str
9998 = escape_buffer (buf->data (),
9999 std::min (val, max_chars));
10000
10001 if (val > max_chars)
10002 remote_debug_printf_nofunc
10003 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10004 val - max_chars);
10005 else
10006 remote_debug_printf_nofunc ("Packet received: %s",
10007 str.c_str ());
10008 }
10009
10010 /* Skip the ack char if we're in no-ack mode. */
10011 if (!rs->noack_mode)
10012 remote_serial_write ("+", 1);
10013 if (is_notif != NULL)
10014 *is_notif = 0;
10015 return val;
10016 }
10017
10018 /* If we got a notification, handle it, and go back to looking
10019 for a packet. */
10020 else
10021 {
10022 gdb_assert (c == '%');
10023
10024 remote_debug_printf_nofunc
10025 (" Notification received: %s",
10026 escape_buffer (buf->data (), val).c_str ());
10027
10028 if (is_notif != NULL)
10029 *is_notif = 1;
10030
10031 handle_notification (rs->notif_state, buf->data ());
10032
10033 /* Notifications require no acknowledgement. */
10034
10035 if (expecting_notif)
10036 return val;
10037 }
10038 }
10039 }
10040
10041 int
10042 remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
10043 {
10044 return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
10045 }
10046
10047 int
10048 remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
10049 int *is_notif)
10050 {
10051 return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
10052 }
10053
10054 /* Kill any new fork children of inferior INF that haven't been
10055 processed by follow_fork. */
10056
10057 void
10058 remote_target::kill_new_fork_children (inferior *inf)
10059 {
10060 remote_state *rs = get_remote_state ();
10061 struct notif_client *notif = &notif_client_stop;
10062
10063 /* Kill the fork child threads of any threads in inferior INF that are stopped
10064 at a fork event. */
10065 for (thread_info *thread : inf->non_exited_threads ())
10066 {
10067 const target_waitstatus *ws = thread_pending_fork_status (thread);
10068
10069 if (ws == nullptr)
10070 continue;
10071
10072 int child_pid = ws->child_ptid ().pid ();
10073 int res = remote_vkill (child_pid);
10074
10075 if (res != 0)
10076 error (_("Can't kill fork child process %d"), child_pid);
10077 }
10078
10079 /* Check for any pending fork events (not reported or processed yet)
10080 in inferior INF and kill those fork child threads as well. */
10081 remote_notif_get_pending_events (notif);
10082 for (auto &event : rs->stop_reply_queue)
10083 {
10084 if (event->ptid.pid () != inf->pid)
10085 continue;
10086
10087 if (!is_fork_status (event->ws.kind ()))
10088 continue;
10089
10090 int child_pid = event->ws.child_ptid ().pid ();
10091 int res = remote_vkill (child_pid);
10092
10093 if (res != 0)
10094 error (_("Can't kill fork child process %d"), child_pid);
10095 }
10096 }
10097
10098 \f
10099 /* Target hook to kill the current inferior. */
10100
10101 void
10102 remote_target::kill ()
10103 {
10104 int res = -1;
10105 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10106 struct remote_state *rs = get_remote_state ();
10107
10108 gdb_assert (inf != nullptr);
10109
10110 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
10111 {
10112 /* If we're stopped while forking and we haven't followed yet,
10113 kill the child task. We need to do this before killing the
10114 parent task because if this is a vfork then the parent will
10115 be sleeping. */
10116 kill_new_fork_children (inf);
10117
10118 res = remote_vkill (inf->pid);
10119 if (res == 0)
10120 {
10121 target_mourn_inferior (inferior_ptid);
10122 return;
10123 }
10124 }
10125
10126 /* If we are in 'target remote' mode and we are killing the only
10127 inferior, then we will tell gdbserver to exit and unpush the
10128 target. */
10129 if (res == -1 && !remote_multi_process_p (rs)
10130 && number_of_live_inferiors (this) == 1)
10131 {
10132 remote_kill_k ();
10133
10134 /* We've killed the remote end, we get to mourn it. If we are
10135 not in extended mode, mourning the inferior also unpushes
10136 remote_ops from the target stack, which closes the remote
10137 connection. */
10138 target_mourn_inferior (inferior_ptid);
10139
10140 return;
10141 }
10142
10143 error (_("Can't kill process"));
10144 }
10145
10146 /* Send a kill request to the target using the 'vKill' packet. */
10147
10148 int
10149 remote_target::remote_vkill (int pid)
10150 {
10151 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
10152 return -1;
10153
10154 remote_state *rs = get_remote_state ();
10155
10156 /* Tell the remote target to detach. */
10157 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10158 putpkt (rs->buf);
10159 getpkt (&rs->buf, 0);
10160
10161 switch (packet_ok (rs->buf,
10162 &remote_protocol_packets[PACKET_vKill]))
10163 {
10164 case PACKET_OK:
10165 return 0;
10166 case PACKET_ERROR:
10167 return 1;
10168 case PACKET_UNKNOWN:
10169 return -1;
10170 default:
10171 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
10172 }
10173 }
10174
10175 /* Send a kill request to the target using the 'k' packet. */
10176
10177 void
10178 remote_target::remote_kill_k ()
10179 {
10180 /* Catch errors so the user can quit from gdb even when we
10181 aren't on speaking terms with the remote system. */
10182 try
10183 {
10184 putpkt ("k");
10185 }
10186 catch (const gdb_exception_error &ex)
10187 {
10188 if (ex.error == TARGET_CLOSE_ERROR)
10189 {
10190 /* If we got an (EOF) error that caused the target
10191 to go away, then we're done, that's what we wanted.
10192 "k" is susceptible to cause a premature EOF, given
10193 that the remote server isn't actually required to
10194 reply to "k", and it can happen that it doesn't
10195 even get to reply ACK to the "k". */
10196 return;
10197 }
10198
10199 /* Otherwise, something went wrong. We didn't actually kill
10200 the target. Just propagate the exception, and let the
10201 user or higher layers decide what to do. */
10202 throw;
10203 }
10204 }
10205
10206 void
10207 remote_target::mourn_inferior ()
10208 {
10209 struct remote_state *rs = get_remote_state ();
10210
10211 /* We're no longer interested in notification events of an inferior
10212 that exited or was killed/detached. */
10213 discard_pending_stop_replies (current_inferior ());
10214
10215 /* In 'target remote' mode with one inferior, we close the connection. */
10216 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10217 {
10218 remote_unpush_target (this);
10219 return;
10220 }
10221
10222 /* In case we got here due to an error, but we're going to stay
10223 connected. */
10224 rs->waiting_for_stop_reply = 0;
10225
10226 /* If the current general thread belonged to the process we just
10227 detached from or has exited, the remote side current general
10228 thread becomes undefined. Considering a case like this:
10229
10230 - We just got here due to a detach.
10231 - The process that we're detaching from happens to immediately
10232 report a global breakpoint being hit in non-stop mode, in the
10233 same thread we had selected before.
10234 - GDB attaches to this process again.
10235 - This event happens to be the next event we handle.
10236
10237 GDB would consider that the current general thread didn't need to
10238 be set on the stub side (with Hg), since for all it knew,
10239 GENERAL_THREAD hadn't changed.
10240
10241 Notice that although in all-stop mode, the remote server always
10242 sets the current thread to the thread reporting the stop event,
10243 that doesn't happen in non-stop mode; in non-stop, the stub *must
10244 not* change the current thread when reporting a breakpoint hit,
10245 due to the decoupling of event reporting and event handling.
10246
10247 To keep things simple, we always invalidate our notion of the
10248 current thread. */
10249 record_currthread (rs, minus_one_ptid);
10250
10251 /* Call common code to mark the inferior as not running. */
10252 generic_mourn_inferior ();
10253 }
10254
10255 bool
10256 extended_remote_target::supports_disable_randomization ()
10257 {
10258 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
10259 }
10260
10261 void
10262 remote_target::extended_remote_disable_randomization (int val)
10263 {
10264 struct remote_state *rs = get_remote_state ();
10265 char *reply;
10266
10267 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10268 "QDisableRandomization:%x", val);
10269 putpkt (rs->buf);
10270 reply = remote_get_noisy_reply ();
10271 if (*reply == '\0')
10272 error (_("Target does not support QDisableRandomization."));
10273 if (strcmp (reply, "OK") != 0)
10274 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10275 }
10276
10277 int
10278 remote_target::extended_remote_run (const std::string &args)
10279 {
10280 struct remote_state *rs = get_remote_state ();
10281 int len;
10282 const char *remote_exec_file = get_remote_exec_file ();
10283
10284 /* If the user has disabled vRun support, or we have detected that
10285 support is not available, do not try it. */
10286 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
10287 return -1;
10288
10289 strcpy (rs->buf.data (), "vRun;");
10290 len = strlen (rs->buf.data ());
10291
10292 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10293 error (_("Remote file name too long for run packet"));
10294 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10295 strlen (remote_exec_file));
10296
10297 if (!args.empty ())
10298 {
10299 int i;
10300
10301 gdb_argv argv (args.c_str ());
10302 for (i = 0; argv[i] != NULL; i++)
10303 {
10304 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10305 error (_("Argument list too long for run packet"));
10306 rs->buf[len++] = ';';
10307 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10308 strlen (argv[i]));
10309 }
10310 }
10311
10312 rs->buf[len++] = '\0';
10313
10314 putpkt (rs->buf);
10315 getpkt (&rs->buf, 0);
10316
10317 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
10318 {
10319 case PACKET_OK:
10320 /* We have a wait response. All is well. */
10321 return 0;
10322 case PACKET_UNKNOWN:
10323 return -1;
10324 case PACKET_ERROR:
10325 if (remote_exec_file[0] == '\0')
10326 error (_("Running the default executable on the remote target failed; "
10327 "try \"set remote exec-file\"?"));
10328 else
10329 error (_("Running \"%s\" on the remote target failed"),
10330 remote_exec_file);
10331 default:
10332 gdb_assert_not_reached ("bad switch");
10333 }
10334 }
10335
10336 /* Helper function to send set/unset environment packets. ACTION is
10337 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10338 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10339 sent. */
10340
10341 void
10342 remote_target::send_environment_packet (const char *action,
10343 const char *packet,
10344 const char *value)
10345 {
10346 remote_state *rs = get_remote_state ();
10347
10348 /* Convert the environment variable to an hex string, which
10349 is the best format to be transmitted over the wire. */
10350 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10351 strlen (value));
10352
10353 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10354 "%s:%s", packet, encoded_value.c_str ());
10355
10356 putpkt (rs->buf);
10357 getpkt (&rs->buf, 0);
10358 if (strcmp (rs->buf.data (), "OK") != 0)
10359 warning (_("Unable to %s environment variable '%s' on remote."),
10360 action, value);
10361 }
10362
10363 /* Helper function to handle the QEnvironment* packets. */
10364
10365 void
10366 remote_target::extended_remote_environment_support ()
10367 {
10368 remote_state *rs = get_remote_state ();
10369
10370 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10371 {
10372 putpkt ("QEnvironmentReset");
10373 getpkt (&rs->buf, 0);
10374 if (strcmp (rs->buf.data (), "OK") != 0)
10375 warning (_("Unable to reset environment on remote."));
10376 }
10377
10378 gdb_environ *e = &current_inferior ()->environment;
10379
10380 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10381 for (const std::string &el : e->user_set_env ())
10382 send_environment_packet ("set", "QEnvironmentHexEncoded",
10383 el.c_str ());
10384
10385 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10386 for (const std::string &el : e->user_unset_env ())
10387 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10388 }
10389
10390 /* Helper function to set the current working directory for the
10391 inferior in the remote target. */
10392
10393 void
10394 remote_target::extended_remote_set_inferior_cwd ()
10395 {
10396 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10397 {
10398 const std::string &inferior_cwd = current_inferior ()->cwd ();
10399 remote_state *rs = get_remote_state ();
10400
10401 if (!inferior_cwd.empty ())
10402 {
10403 std::string hexpath
10404 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10405 inferior_cwd.size ());
10406
10407 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10408 "QSetWorkingDir:%s", hexpath.c_str ());
10409 }
10410 else
10411 {
10412 /* An empty inferior_cwd means that the user wants us to
10413 reset the remote server's inferior's cwd. */
10414 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10415 "QSetWorkingDir:");
10416 }
10417
10418 putpkt (rs->buf);
10419 getpkt (&rs->buf, 0);
10420 if (packet_ok (rs->buf,
10421 &remote_protocol_packets[PACKET_QSetWorkingDir])
10422 != PACKET_OK)
10423 error (_("\
10424 Remote replied unexpectedly while setting the inferior's working\n\
10425 directory: %s"),
10426 rs->buf.data ());
10427
10428 }
10429 }
10430
10431 /* In the extended protocol we want to be able to do things like
10432 "run" and have them basically work as expected. So we need
10433 a special create_inferior function. We support changing the
10434 executable file and the command line arguments, but not the
10435 environment. */
10436
10437 void
10438 extended_remote_target::create_inferior (const char *exec_file,
10439 const std::string &args,
10440 char **env, int from_tty)
10441 {
10442 int run_worked;
10443 char *stop_reply;
10444 struct remote_state *rs = get_remote_state ();
10445 const char *remote_exec_file = get_remote_exec_file ();
10446
10447 /* If running asynchronously, register the target file descriptor
10448 with the event loop. */
10449 if (target_can_async_p ())
10450 target_async (1);
10451
10452 /* Disable address space randomization if requested (and supported). */
10453 if (supports_disable_randomization ())
10454 extended_remote_disable_randomization (disable_randomization);
10455
10456 /* If startup-with-shell is on, we inform gdbserver to start the
10457 remote inferior using a shell. */
10458 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10459 {
10460 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10461 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10462 putpkt (rs->buf);
10463 getpkt (&rs->buf, 0);
10464 if (strcmp (rs->buf.data (), "OK") != 0)
10465 error (_("\
10466 Remote replied unexpectedly while setting startup-with-shell: %s"),
10467 rs->buf.data ());
10468 }
10469
10470 extended_remote_environment_support ();
10471
10472 extended_remote_set_inferior_cwd ();
10473
10474 /* Now restart the remote server. */
10475 run_worked = extended_remote_run (args) != -1;
10476 if (!run_worked)
10477 {
10478 /* vRun was not supported. Fail if we need it to do what the
10479 user requested. */
10480 if (remote_exec_file[0])
10481 error (_("Remote target does not support \"set remote exec-file\""));
10482 if (!args.empty ())
10483 error (_("Remote target does not support \"set args\" or run ARGS"));
10484
10485 /* Fall back to "R". */
10486 extended_remote_restart ();
10487 }
10488
10489 /* vRun's success return is a stop reply. */
10490 stop_reply = run_worked ? rs->buf.data () : NULL;
10491 add_current_inferior_and_thread (stop_reply);
10492
10493 /* Get updated offsets, if the stub uses qOffsets. */
10494 get_offsets ();
10495 }
10496 \f
10497
10498 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10499 the list of conditions (in agent expression bytecode format), if any, the
10500 target needs to evaluate. The output is placed into the packet buffer
10501 started from BUF and ended at BUF_END. */
10502
10503 static int
10504 remote_add_target_side_condition (struct gdbarch *gdbarch,
10505 struct bp_target_info *bp_tgt, char *buf,
10506 char *buf_end)
10507 {
10508 if (bp_tgt->conditions.empty ())
10509 return 0;
10510
10511 buf += strlen (buf);
10512 xsnprintf (buf, buf_end - buf, "%s", ";");
10513 buf++;
10514
10515 /* Send conditions to the target. */
10516 for (agent_expr *aexpr : bp_tgt->conditions)
10517 {
10518 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10519 buf += strlen (buf);
10520 for (int i = 0; i < aexpr->len; ++i)
10521 buf = pack_hex_byte (buf, aexpr->buf[i]);
10522 *buf = '\0';
10523 }
10524 return 0;
10525 }
10526
10527 static void
10528 remote_add_target_side_commands (struct gdbarch *gdbarch,
10529 struct bp_target_info *bp_tgt, char *buf)
10530 {
10531 if (bp_tgt->tcommands.empty ())
10532 return;
10533
10534 buf += strlen (buf);
10535
10536 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10537 buf += strlen (buf);
10538
10539 /* Concatenate all the agent expressions that are commands into the
10540 cmds parameter. */
10541 for (agent_expr *aexpr : bp_tgt->tcommands)
10542 {
10543 sprintf (buf, "X%x,", aexpr->len);
10544 buf += strlen (buf);
10545 for (int i = 0; i < aexpr->len; ++i)
10546 buf = pack_hex_byte (buf, aexpr->buf[i]);
10547 *buf = '\0';
10548 }
10549 }
10550
10551 /* Insert a breakpoint. On targets that have software breakpoint
10552 support, we ask the remote target to do the work; on targets
10553 which don't, we insert a traditional memory breakpoint. */
10554
10555 int
10556 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10557 struct bp_target_info *bp_tgt)
10558 {
10559 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10560 If it succeeds, then set the support to PACKET_ENABLE. If it
10561 fails, and the user has explicitly requested the Z support then
10562 report an error, otherwise, mark it disabled and go on. */
10563
10564 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10565 {
10566 CORE_ADDR addr = bp_tgt->reqstd_address;
10567 struct remote_state *rs;
10568 char *p, *endbuf;
10569
10570 /* Make sure the remote is pointing at the right process, if
10571 necessary. */
10572 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10573 set_general_process ();
10574
10575 rs = get_remote_state ();
10576 p = rs->buf.data ();
10577 endbuf = p + get_remote_packet_size ();
10578
10579 *(p++) = 'Z';
10580 *(p++) = '0';
10581 *(p++) = ',';
10582 addr = (ULONGEST) remote_address_masked (addr);
10583 p += hexnumstr (p, addr);
10584 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10585
10586 if (supports_evaluation_of_breakpoint_conditions ())
10587 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10588
10589 if (can_run_breakpoint_commands ())
10590 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10591
10592 putpkt (rs->buf);
10593 getpkt (&rs->buf, 0);
10594
10595 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10596 {
10597 case PACKET_ERROR:
10598 return -1;
10599 case PACKET_OK:
10600 return 0;
10601 case PACKET_UNKNOWN:
10602 break;
10603 }
10604 }
10605
10606 /* If this breakpoint has target-side commands but this stub doesn't
10607 support Z0 packets, throw error. */
10608 if (!bp_tgt->tcommands.empty ())
10609 throw_error (NOT_SUPPORTED_ERROR, _("\
10610 Target doesn't support breakpoints that have target side commands."));
10611
10612 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10613 }
10614
10615 int
10616 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10617 struct bp_target_info *bp_tgt,
10618 enum remove_bp_reason reason)
10619 {
10620 CORE_ADDR addr = bp_tgt->placed_address;
10621 struct remote_state *rs = get_remote_state ();
10622
10623 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10624 {
10625 char *p = rs->buf.data ();
10626 char *endbuf = p + get_remote_packet_size ();
10627
10628 /* Make sure the remote is pointing at the right process, if
10629 necessary. */
10630 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10631 set_general_process ();
10632
10633 *(p++) = 'z';
10634 *(p++) = '0';
10635 *(p++) = ',';
10636
10637 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10638 p += hexnumstr (p, addr);
10639 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10640
10641 putpkt (rs->buf);
10642 getpkt (&rs->buf, 0);
10643
10644 return (rs->buf[0] == 'E');
10645 }
10646
10647 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10648 }
10649
10650 static enum Z_packet_type
10651 watchpoint_to_Z_packet (int type)
10652 {
10653 switch (type)
10654 {
10655 case hw_write:
10656 return Z_PACKET_WRITE_WP;
10657 break;
10658 case hw_read:
10659 return Z_PACKET_READ_WP;
10660 break;
10661 case hw_access:
10662 return Z_PACKET_ACCESS_WP;
10663 break;
10664 default:
10665 internal_error (__FILE__, __LINE__,
10666 _("hw_bp_to_z: bad watchpoint type %d"), type);
10667 }
10668 }
10669
10670 int
10671 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10672 enum target_hw_bp_type type, struct expression *cond)
10673 {
10674 struct remote_state *rs = get_remote_state ();
10675 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10676 char *p;
10677 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10678
10679 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10680 return 1;
10681
10682 /* Make sure the remote is pointing at the right process, if
10683 necessary. */
10684 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10685 set_general_process ();
10686
10687 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10688 p = strchr (rs->buf.data (), '\0');
10689 addr = remote_address_masked (addr);
10690 p += hexnumstr (p, (ULONGEST) addr);
10691 xsnprintf (p, endbuf - p, ",%x", len);
10692
10693 putpkt (rs->buf);
10694 getpkt (&rs->buf, 0);
10695
10696 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10697 {
10698 case PACKET_ERROR:
10699 return -1;
10700 case PACKET_UNKNOWN:
10701 return 1;
10702 case PACKET_OK:
10703 return 0;
10704 }
10705 internal_error (__FILE__, __LINE__,
10706 _("remote_insert_watchpoint: reached end of function"));
10707 }
10708
10709 bool
10710 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10711 CORE_ADDR start, int length)
10712 {
10713 CORE_ADDR diff = remote_address_masked (addr - start);
10714
10715 return diff < length;
10716 }
10717
10718
10719 int
10720 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10721 enum target_hw_bp_type type, struct expression *cond)
10722 {
10723 struct remote_state *rs = get_remote_state ();
10724 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10725 char *p;
10726 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10727
10728 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10729 return -1;
10730
10731 /* Make sure the remote is pointing at the right process, if
10732 necessary. */
10733 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10734 set_general_process ();
10735
10736 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10737 p = strchr (rs->buf.data (), '\0');
10738 addr = remote_address_masked (addr);
10739 p += hexnumstr (p, (ULONGEST) addr);
10740 xsnprintf (p, endbuf - p, ",%x", len);
10741 putpkt (rs->buf);
10742 getpkt (&rs->buf, 0);
10743
10744 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10745 {
10746 case PACKET_ERROR:
10747 case PACKET_UNKNOWN:
10748 return -1;
10749 case PACKET_OK:
10750 return 0;
10751 }
10752 internal_error (__FILE__, __LINE__,
10753 _("remote_remove_watchpoint: reached end of function"));
10754 }
10755
10756
10757 static int remote_hw_watchpoint_limit = -1;
10758 static int remote_hw_watchpoint_length_limit = -1;
10759 static int remote_hw_breakpoint_limit = -1;
10760
10761 int
10762 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10763 {
10764 if (remote_hw_watchpoint_length_limit == 0)
10765 return 0;
10766 else if (remote_hw_watchpoint_length_limit < 0)
10767 return 1;
10768 else if (len <= remote_hw_watchpoint_length_limit)
10769 return 1;
10770 else
10771 return 0;
10772 }
10773
10774 int
10775 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10776 {
10777 if (type == bp_hardware_breakpoint)
10778 {
10779 if (remote_hw_breakpoint_limit == 0)
10780 return 0;
10781 else if (remote_hw_breakpoint_limit < 0)
10782 return 1;
10783 else if (cnt <= remote_hw_breakpoint_limit)
10784 return 1;
10785 }
10786 else
10787 {
10788 if (remote_hw_watchpoint_limit == 0)
10789 return 0;
10790 else if (remote_hw_watchpoint_limit < 0)
10791 return 1;
10792 else if (ot)
10793 return -1;
10794 else if (cnt <= remote_hw_watchpoint_limit)
10795 return 1;
10796 }
10797 return -1;
10798 }
10799
10800 /* The to_stopped_by_sw_breakpoint method of target remote. */
10801
10802 bool
10803 remote_target::stopped_by_sw_breakpoint ()
10804 {
10805 struct thread_info *thread = inferior_thread ();
10806
10807 return (thread->priv != NULL
10808 && (get_remote_thread_info (thread)->stop_reason
10809 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10810 }
10811
10812 /* The to_supports_stopped_by_sw_breakpoint method of target
10813 remote. */
10814
10815 bool
10816 remote_target::supports_stopped_by_sw_breakpoint ()
10817 {
10818 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10819 }
10820
10821 /* The to_stopped_by_hw_breakpoint method of target remote. */
10822
10823 bool
10824 remote_target::stopped_by_hw_breakpoint ()
10825 {
10826 struct thread_info *thread = inferior_thread ();
10827
10828 return (thread->priv != NULL
10829 && (get_remote_thread_info (thread)->stop_reason
10830 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10831 }
10832
10833 /* The to_supports_stopped_by_hw_breakpoint method of target
10834 remote. */
10835
10836 bool
10837 remote_target::supports_stopped_by_hw_breakpoint ()
10838 {
10839 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10840 }
10841
10842 bool
10843 remote_target::stopped_by_watchpoint ()
10844 {
10845 struct thread_info *thread = inferior_thread ();
10846
10847 return (thread->priv != NULL
10848 && (get_remote_thread_info (thread)->stop_reason
10849 == TARGET_STOPPED_BY_WATCHPOINT));
10850 }
10851
10852 bool
10853 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10854 {
10855 struct thread_info *thread = inferior_thread ();
10856
10857 if (thread->priv != NULL
10858 && (get_remote_thread_info (thread)->stop_reason
10859 == TARGET_STOPPED_BY_WATCHPOINT))
10860 {
10861 *addr_p = get_remote_thread_info (thread)->watch_data_address;
10862 return true;
10863 }
10864
10865 return false;
10866 }
10867
10868
10869 int
10870 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10871 struct bp_target_info *bp_tgt)
10872 {
10873 CORE_ADDR addr = bp_tgt->reqstd_address;
10874 struct remote_state *rs;
10875 char *p, *endbuf;
10876 char *message;
10877
10878 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10879 return -1;
10880
10881 /* Make sure the remote is pointing at the right process, if
10882 necessary. */
10883 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10884 set_general_process ();
10885
10886 rs = get_remote_state ();
10887 p = rs->buf.data ();
10888 endbuf = p + get_remote_packet_size ();
10889
10890 *(p++) = 'Z';
10891 *(p++) = '1';
10892 *(p++) = ',';
10893
10894 addr = remote_address_masked (addr);
10895 p += hexnumstr (p, (ULONGEST) addr);
10896 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10897
10898 if (supports_evaluation_of_breakpoint_conditions ())
10899 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10900
10901 if (can_run_breakpoint_commands ())
10902 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10903
10904 putpkt (rs->buf);
10905 getpkt (&rs->buf, 0);
10906
10907 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10908 {
10909 case PACKET_ERROR:
10910 if (rs->buf[1] == '.')
10911 {
10912 message = strchr (&rs->buf[2], '.');
10913 if (message)
10914 error (_("Remote failure reply: %s"), message + 1);
10915 }
10916 return -1;
10917 case PACKET_UNKNOWN:
10918 return -1;
10919 case PACKET_OK:
10920 return 0;
10921 }
10922 internal_error (__FILE__, __LINE__,
10923 _("remote_insert_hw_breakpoint: reached end of function"));
10924 }
10925
10926
10927 int
10928 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10929 struct bp_target_info *bp_tgt)
10930 {
10931 CORE_ADDR addr;
10932 struct remote_state *rs = get_remote_state ();
10933 char *p = rs->buf.data ();
10934 char *endbuf = p + get_remote_packet_size ();
10935
10936 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10937 return -1;
10938
10939 /* Make sure the remote is pointing at the right process, if
10940 necessary. */
10941 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10942 set_general_process ();
10943
10944 *(p++) = 'z';
10945 *(p++) = '1';
10946 *(p++) = ',';
10947
10948 addr = remote_address_masked (bp_tgt->placed_address);
10949 p += hexnumstr (p, (ULONGEST) addr);
10950 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10951
10952 putpkt (rs->buf);
10953 getpkt (&rs->buf, 0);
10954
10955 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10956 {
10957 case PACKET_ERROR:
10958 case PACKET_UNKNOWN:
10959 return -1;
10960 case PACKET_OK:
10961 return 0;
10962 }
10963 internal_error (__FILE__, __LINE__,
10964 _("remote_remove_hw_breakpoint: reached end of function"));
10965 }
10966
10967 /* Verify memory using the "qCRC:" request. */
10968
10969 int
10970 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10971 {
10972 struct remote_state *rs = get_remote_state ();
10973 unsigned long host_crc, target_crc;
10974 char *tmp;
10975
10976 /* It doesn't make sense to use qCRC if the remote target is
10977 connected but not running. */
10978 if (target_has_execution ()
10979 && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10980 {
10981 enum packet_result result;
10982
10983 /* Make sure the remote is pointing at the right process. */
10984 set_general_process ();
10985
10986 /* FIXME: assumes lma can fit into long. */
10987 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
10988 (long) lma, (long) size);
10989 putpkt (rs->buf);
10990
10991 /* Be clever; compute the host_crc before waiting for target
10992 reply. */
10993 host_crc = xcrc32 (data, size, 0xffffffff);
10994
10995 getpkt (&rs->buf, 0);
10996
10997 result = packet_ok (rs->buf,
10998 &remote_protocol_packets[PACKET_qCRC]);
10999 if (result == PACKET_ERROR)
11000 return -1;
11001 else if (result == PACKET_OK)
11002 {
11003 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11004 target_crc = target_crc * 16 + fromhex (*tmp);
11005
11006 return (host_crc == target_crc);
11007 }
11008 }
11009
11010 return simple_verify_memory (this, data, lma, size);
11011 }
11012
11013 /* compare-sections command
11014
11015 With no arguments, compares each loadable section in the exec bfd
11016 with the same memory range on the target, and reports mismatches.
11017 Useful for verifying the image on the target against the exec file. */
11018
11019 static void
11020 compare_sections_command (const char *args, int from_tty)
11021 {
11022 asection *s;
11023 const char *sectname;
11024 bfd_size_type size;
11025 bfd_vma lma;
11026 int matched = 0;
11027 int mismatched = 0;
11028 int res;
11029 int read_only = 0;
11030
11031 if (!current_program_space->exec_bfd ())
11032 error (_("command cannot be used without an exec file"));
11033
11034 if (args != NULL && strcmp (args, "-r") == 0)
11035 {
11036 read_only = 1;
11037 args = NULL;
11038 }
11039
11040 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11041 {
11042 if (!(s->flags & SEC_LOAD))
11043 continue; /* Skip non-loadable section. */
11044
11045 if (read_only && (s->flags & SEC_READONLY) == 0)
11046 continue; /* Skip writeable sections */
11047
11048 size = bfd_section_size (s);
11049 if (size == 0)
11050 continue; /* Skip zero-length section. */
11051
11052 sectname = bfd_section_name (s);
11053 if (args && strcmp (args, sectname) != 0)
11054 continue; /* Not the section selected by user. */
11055
11056 matched = 1; /* Do this section. */
11057 lma = s->lma;
11058
11059 gdb::byte_vector sectdata (size);
11060 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11061 sectdata.data (), 0, size);
11062
11063 res = target_verify_memory (sectdata.data (), lma, size);
11064
11065 if (res == -1)
11066 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11067 paddress (target_gdbarch (), lma),
11068 paddress (target_gdbarch (), lma + size));
11069
11070 printf_filtered ("Section %s, range %s -- %s: ", sectname,
11071 paddress (target_gdbarch (), lma),
11072 paddress (target_gdbarch (), lma + size));
11073 if (res)
11074 printf_filtered ("matched.\n");
11075 else
11076 {
11077 printf_filtered ("MIS-MATCHED!\n");
11078 mismatched++;
11079 }
11080 }
11081 if (mismatched > 0)
11082 warning (_("One or more sections of the target image does not match\n\
11083 the loaded file\n"));
11084 if (args && !matched)
11085 printf_filtered (_("No loaded section named '%s'.\n"), args);
11086 }
11087
11088 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11089 into remote target. The number of bytes written to the remote
11090 target is returned, or -1 for error. */
11091
11092 target_xfer_status
11093 remote_target::remote_write_qxfer (const char *object_name,
11094 const char *annex, const gdb_byte *writebuf,
11095 ULONGEST offset, LONGEST len,
11096 ULONGEST *xfered_len,
11097 struct packet_config *packet)
11098 {
11099 int i, buf_len;
11100 ULONGEST n;
11101 struct remote_state *rs = get_remote_state ();
11102 int max_size = get_memory_write_packet_size ();
11103
11104 if (packet_config_support (packet) == PACKET_DISABLE)
11105 return TARGET_XFER_E_IO;
11106
11107 /* Insert header. */
11108 i = snprintf (rs->buf.data (), max_size,
11109 "qXfer:%s:write:%s:%s:",
11110 object_name, annex ? annex : "",
11111 phex_nz (offset, sizeof offset));
11112 max_size -= (i + 1);
11113
11114 /* Escape as much data as fits into rs->buf. */
11115 buf_len = remote_escape_output
11116 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11117
11118 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11119 || getpkt_sane (&rs->buf, 0) < 0
11120 || packet_ok (rs->buf, packet) != PACKET_OK)
11121 return TARGET_XFER_E_IO;
11122
11123 unpack_varlen_hex (rs->buf.data (), &n);
11124
11125 *xfered_len = n;
11126 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11127 }
11128
11129 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11130 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11131 number of bytes read is returned, or 0 for EOF, or -1 for error.
11132 The number of bytes read may be less than LEN without indicating an
11133 EOF. PACKET is checked and updated to indicate whether the remote
11134 target supports this object. */
11135
11136 target_xfer_status
11137 remote_target::remote_read_qxfer (const char *object_name,
11138 const char *annex,
11139 gdb_byte *readbuf, ULONGEST offset,
11140 LONGEST len,
11141 ULONGEST *xfered_len,
11142 struct packet_config *packet)
11143 {
11144 struct remote_state *rs = get_remote_state ();
11145 LONGEST i, n, packet_len;
11146
11147 if (packet_config_support (packet) == PACKET_DISABLE)
11148 return TARGET_XFER_E_IO;
11149
11150 /* Check whether we've cached an end-of-object packet that matches
11151 this request. */
11152 if (rs->finished_object)
11153 {
11154 if (strcmp (object_name, rs->finished_object) == 0
11155 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11156 && offset == rs->finished_offset)
11157 return TARGET_XFER_EOF;
11158
11159
11160 /* Otherwise, we're now reading something different. Discard
11161 the cache. */
11162 xfree (rs->finished_object);
11163 xfree (rs->finished_annex);
11164 rs->finished_object = NULL;
11165 rs->finished_annex = NULL;
11166 }
11167
11168 /* Request only enough to fit in a single packet. The actual data
11169 may not, since we don't know how much of it will need to be escaped;
11170 the target is free to respond with slightly less data. We subtract
11171 five to account for the response type and the protocol frame. */
11172 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11173 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11174 "qXfer:%s:read:%s:%s,%s",
11175 object_name, annex ? annex : "",
11176 phex_nz (offset, sizeof offset),
11177 phex_nz (n, sizeof n));
11178 i = putpkt (rs->buf);
11179 if (i < 0)
11180 return TARGET_XFER_E_IO;
11181
11182 rs->buf[0] = '\0';
11183 packet_len = getpkt_sane (&rs->buf, 0);
11184 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
11185 return TARGET_XFER_E_IO;
11186
11187 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11188 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11189
11190 /* 'm' means there is (or at least might be) more data after this
11191 batch. That does not make sense unless there's at least one byte
11192 of data in this reply. */
11193 if (rs->buf[0] == 'm' && packet_len == 1)
11194 error (_("Remote qXfer reply contained no data."));
11195
11196 /* Got some data. */
11197 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11198 packet_len - 1, readbuf, n);
11199
11200 /* 'l' is an EOF marker, possibly including a final block of data,
11201 or possibly empty. If we have the final block of a non-empty
11202 object, record this fact to bypass a subsequent partial read. */
11203 if (rs->buf[0] == 'l' && offset + i > 0)
11204 {
11205 rs->finished_object = xstrdup (object_name);
11206 rs->finished_annex = xstrdup (annex ? annex : "");
11207 rs->finished_offset = offset + i;
11208 }
11209
11210 if (i == 0)
11211 return TARGET_XFER_EOF;
11212 else
11213 {
11214 *xfered_len = i;
11215 return TARGET_XFER_OK;
11216 }
11217 }
11218
11219 enum target_xfer_status
11220 remote_target::xfer_partial (enum target_object object,
11221 const char *annex, gdb_byte *readbuf,
11222 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11223 ULONGEST *xfered_len)
11224 {
11225 struct remote_state *rs;
11226 int i;
11227 char *p2;
11228 char query_type;
11229 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
11230
11231 set_remote_traceframe ();
11232 set_general_thread (inferior_ptid);
11233
11234 rs = get_remote_state ();
11235
11236 /* Handle memory using the standard memory routines. */
11237 if (object == TARGET_OBJECT_MEMORY)
11238 {
11239 /* If the remote target is connected but not running, we should
11240 pass this request down to a lower stratum (e.g. the executable
11241 file). */
11242 if (!target_has_execution ())
11243 return TARGET_XFER_EOF;
11244
11245 if (writebuf != NULL)
11246 return remote_write_bytes (offset, writebuf, len, unit_size,
11247 xfered_len);
11248 else
11249 return remote_read_bytes (offset, readbuf, len, unit_size,
11250 xfered_len);
11251 }
11252
11253 /* Handle extra signal info using qxfer packets. */
11254 if (object == TARGET_OBJECT_SIGNAL_INFO)
11255 {
11256 if (readbuf)
11257 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11258 xfered_len, &remote_protocol_packets
11259 [PACKET_qXfer_siginfo_read]);
11260 else
11261 return remote_write_qxfer ("siginfo", annex,
11262 writebuf, offset, len, xfered_len,
11263 &remote_protocol_packets
11264 [PACKET_qXfer_siginfo_write]);
11265 }
11266
11267 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11268 {
11269 if (readbuf)
11270 return remote_read_qxfer ("statictrace", annex,
11271 readbuf, offset, len, xfered_len,
11272 &remote_protocol_packets
11273 [PACKET_qXfer_statictrace_read]);
11274 else
11275 return TARGET_XFER_E_IO;
11276 }
11277
11278 /* Only handle flash writes. */
11279 if (writebuf != NULL)
11280 {
11281 switch (object)
11282 {
11283 case TARGET_OBJECT_FLASH:
11284 return remote_flash_write (offset, len, xfered_len,
11285 writebuf);
11286
11287 default:
11288 return TARGET_XFER_E_IO;
11289 }
11290 }
11291
11292 /* Map pre-existing objects onto letters. DO NOT do this for new
11293 objects!!! Instead specify new query packets. */
11294 switch (object)
11295 {
11296 case TARGET_OBJECT_AVR:
11297 query_type = 'R';
11298 break;
11299
11300 case TARGET_OBJECT_AUXV:
11301 gdb_assert (annex == NULL);
11302 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
11303 xfered_len,
11304 &remote_protocol_packets[PACKET_qXfer_auxv]);
11305
11306 case TARGET_OBJECT_AVAILABLE_FEATURES:
11307 return remote_read_qxfer
11308 ("features", annex, readbuf, offset, len, xfered_len,
11309 &remote_protocol_packets[PACKET_qXfer_features]);
11310
11311 case TARGET_OBJECT_LIBRARIES:
11312 return remote_read_qxfer
11313 ("libraries", annex, readbuf, offset, len, xfered_len,
11314 &remote_protocol_packets[PACKET_qXfer_libraries]);
11315
11316 case TARGET_OBJECT_LIBRARIES_SVR4:
11317 return remote_read_qxfer
11318 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11319 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
11320
11321 case TARGET_OBJECT_MEMORY_MAP:
11322 gdb_assert (annex == NULL);
11323 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
11324 xfered_len,
11325 &remote_protocol_packets[PACKET_qXfer_memory_map]);
11326
11327 case TARGET_OBJECT_OSDATA:
11328 /* Should only get here if we're connected. */
11329 gdb_assert (rs->remote_desc);
11330 return remote_read_qxfer
11331 ("osdata", annex, readbuf, offset, len, xfered_len,
11332 &remote_protocol_packets[PACKET_qXfer_osdata]);
11333
11334 case TARGET_OBJECT_THREADS:
11335 gdb_assert (annex == NULL);
11336 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
11337 xfered_len,
11338 &remote_protocol_packets[PACKET_qXfer_threads]);
11339
11340 case TARGET_OBJECT_TRACEFRAME_INFO:
11341 gdb_assert (annex == NULL);
11342 return remote_read_qxfer
11343 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11344 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
11345
11346 case TARGET_OBJECT_FDPIC:
11347 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
11348 xfered_len,
11349 &remote_protocol_packets[PACKET_qXfer_fdpic]);
11350
11351 case TARGET_OBJECT_OPENVMS_UIB:
11352 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
11353 xfered_len,
11354 &remote_protocol_packets[PACKET_qXfer_uib]);
11355
11356 case TARGET_OBJECT_BTRACE:
11357 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
11358 xfered_len,
11359 &remote_protocol_packets[PACKET_qXfer_btrace]);
11360
11361 case TARGET_OBJECT_BTRACE_CONF:
11362 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
11363 len, xfered_len,
11364 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11365
11366 case TARGET_OBJECT_EXEC_FILE:
11367 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
11368 len, xfered_len,
11369 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11370
11371 default:
11372 return TARGET_XFER_E_IO;
11373 }
11374
11375 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11376 large enough let the caller deal with it. */
11377 if (len < get_remote_packet_size ())
11378 return TARGET_XFER_E_IO;
11379 len = get_remote_packet_size ();
11380
11381 /* Except for querying the minimum buffer size, target must be open. */
11382 if (!rs->remote_desc)
11383 error (_("remote query is only available after target open"));
11384
11385 gdb_assert (annex != NULL);
11386 gdb_assert (readbuf != NULL);
11387
11388 p2 = rs->buf.data ();
11389 *p2++ = 'q';
11390 *p2++ = query_type;
11391
11392 /* We used one buffer char for the remote protocol q command and
11393 another for the query type. As the remote protocol encapsulation
11394 uses 4 chars plus one extra in case we are debugging
11395 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11396 string. */
11397 i = 0;
11398 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11399 {
11400 /* Bad caller may have sent forbidden characters. */
11401 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11402 *p2++ = annex[i];
11403 i++;
11404 }
11405 *p2 = '\0';
11406 gdb_assert (annex[i] == '\0');
11407
11408 i = putpkt (rs->buf);
11409 if (i < 0)
11410 return TARGET_XFER_E_IO;
11411
11412 getpkt (&rs->buf, 0);
11413 strcpy ((char *) readbuf, rs->buf.data ());
11414
11415 *xfered_len = strlen ((char *) readbuf);
11416 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11417 }
11418
11419 /* Implementation of to_get_memory_xfer_limit. */
11420
11421 ULONGEST
11422 remote_target::get_memory_xfer_limit ()
11423 {
11424 return get_memory_write_packet_size ();
11425 }
11426
11427 int
11428 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11429 const gdb_byte *pattern, ULONGEST pattern_len,
11430 CORE_ADDR *found_addrp)
11431 {
11432 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11433 struct remote_state *rs = get_remote_state ();
11434 int max_size = get_memory_write_packet_size ();
11435 struct packet_config *packet =
11436 &remote_protocol_packets[PACKET_qSearch_memory];
11437 /* Number of packet bytes used to encode the pattern;
11438 this could be more than PATTERN_LEN due to escape characters. */
11439 int escaped_pattern_len;
11440 /* Amount of pattern that was encodable in the packet. */
11441 int used_pattern_len;
11442 int i;
11443 int found;
11444 ULONGEST found_addr;
11445
11446 auto read_memory = [=] (CORE_ADDR addr, gdb_byte *result, size_t len)
11447 {
11448 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11449 == len);
11450 };
11451
11452 /* Don't go to the target if we don't have to. This is done before
11453 checking packet_config_support to avoid the possibility that a
11454 success for this edge case means the facility works in
11455 general. */
11456 if (pattern_len > search_space_len)
11457 return 0;
11458 if (pattern_len == 0)
11459 {
11460 *found_addrp = start_addr;
11461 return 1;
11462 }
11463
11464 /* If we already know the packet isn't supported, fall back to the simple
11465 way of searching memory. */
11466
11467 if (packet_config_support (packet) == PACKET_DISABLE)
11468 {
11469 /* Target doesn't provided special support, fall back and use the
11470 standard support (copy memory and do the search here). */
11471 return simple_search_memory (read_memory, start_addr, search_space_len,
11472 pattern, pattern_len, found_addrp);
11473 }
11474
11475 /* Make sure the remote is pointing at the right process. */
11476 set_general_process ();
11477
11478 /* Insert header. */
11479 i = snprintf (rs->buf.data (), max_size,
11480 "qSearch:memory:%s;%s;",
11481 phex_nz (start_addr, addr_size),
11482 phex_nz (search_space_len, sizeof (search_space_len)));
11483 max_size -= (i + 1);
11484
11485 /* Escape as much data as fits into rs->buf. */
11486 escaped_pattern_len =
11487 remote_escape_output (pattern, pattern_len, 1,
11488 (gdb_byte *) rs->buf.data () + i,
11489 &used_pattern_len, max_size);
11490
11491 /* Bail if the pattern is too large. */
11492 if (used_pattern_len != pattern_len)
11493 error (_("Pattern is too large to transmit to remote target."));
11494
11495 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11496 || getpkt_sane (&rs->buf, 0) < 0
11497 || packet_ok (rs->buf, packet) != PACKET_OK)
11498 {
11499 /* The request may not have worked because the command is not
11500 supported. If so, fall back to the simple way. */
11501 if (packet_config_support (packet) == PACKET_DISABLE)
11502 {
11503 return simple_search_memory (read_memory, start_addr, search_space_len,
11504 pattern, pattern_len, found_addrp);
11505 }
11506 return -1;
11507 }
11508
11509 if (rs->buf[0] == '0')
11510 found = 0;
11511 else if (rs->buf[0] == '1')
11512 {
11513 found = 1;
11514 if (rs->buf[1] != ',')
11515 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11516 unpack_varlen_hex (&rs->buf[2], &found_addr);
11517 *found_addrp = found_addr;
11518 }
11519 else
11520 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11521
11522 return found;
11523 }
11524
11525 void
11526 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11527 {
11528 struct remote_state *rs = get_remote_state ();
11529 char *p = rs->buf.data ();
11530
11531 if (!rs->remote_desc)
11532 error (_("remote rcmd is only available after target open"));
11533
11534 /* Send a NULL command across as an empty command. */
11535 if (command == NULL)
11536 command = "";
11537
11538 /* The query prefix. */
11539 strcpy (rs->buf.data (), "qRcmd,");
11540 p = strchr (rs->buf.data (), '\0');
11541
11542 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11543 > get_remote_packet_size ())
11544 error (_("\"monitor\" command ``%s'' is too long."), command);
11545
11546 /* Encode the actual command. */
11547 bin2hex ((const gdb_byte *) command, p, strlen (command));
11548
11549 if (putpkt (rs->buf) < 0)
11550 error (_("Communication problem with target."));
11551
11552 /* get/display the response */
11553 while (1)
11554 {
11555 char *buf;
11556
11557 /* XXX - see also remote_get_noisy_reply(). */
11558 QUIT; /* Allow user to bail out with ^C. */
11559 rs->buf[0] = '\0';
11560 if (getpkt_sane (&rs->buf, 0) == -1)
11561 {
11562 /* Timeout. Continue to (try to) read responses.
11563 This is better than stopping with an error, assuming the stub
11564 is still executing the (long) monitor command.
11565 If needed, the user can interrupt gdb using C-c, obtaining
11566 an effect similar to stop on timeout. */
11567 continue;
11568 }
11569 buf = rs->buf.data ();
11570 if (buf[0] == '\0')
11571 error (_("Target does not support this command."));
11572 if (buf[0] == 'O' && buf[1] != 'K')
11573 {
11574 remote_console_output (buf + 1); /* 'O' message from stub. */
11575 continue;
11576 }
11577 if (strcmp (buf, "OK") == 0)
11578 break;
11579 if (strlen (buf) == 3 && buf[0] == 'E'
11580 && isdigit (buf[1]) && isdigit (buf[2]))
11581 {
11582 error (_("Protocol error with Rcmd"));
11583 }
11584 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11585 {
11586 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11587
11588 fputc_unfiltered (c, outbuf);
11589 }
11590 break;
11591 }
11592 }
11593
11594 std::vector<mem_region>
11595 remote_target::memory_map ()
11596 {
11597 std::vector<mem_region> result;
11598 gdb::optional<gdb::char_vector> text
11599 = target_read_stralloc (current_inferior ()->top_target (),
11600 TARGET_OBJECT_MEMORY_MAP, NULL);
11601
11602 if (text)
11603 result = parse_memory_map (text->data ());
11604
11605 return result;
11606 }
11607
11608 /* Set of callbacks used to implement the 'maint packet' command. */
11609
11610 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
11611 {
11612 /* Called before the packet is sent. BUF is the packet content before
11613 the protocol specific prefix, suffix, and escaping is added. */
11614
11615 void sending (gdb::array_view<const char> &buf) override
11616 {
11617 puts_filtered ("sending: ");
11618 print_packet (buf);
11619 puts_filtered ("\n");
11620 }
11621
11622 /* Called with BUF, the reply from the remote target. */
11623
11624 void received (gdb::array_view<const char> &buf) override
11625 {
11626 puts_filtered ("received: \"");
11627 print_packet (buf);
11628 puts_filtered ("\"\n");
11629 }
11630
11631 private:
11632
11633 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11634 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11635
11636 static void
11637 print_packet (gdb::array_view<const char> &buf)
11638 {
11639 string_file stb;
11640
11641 for (int i = 0; i < buf.size (); ++i)
11642 {
11643 gdb_byte c = buf[i];
11644 if (isprint (c))
11645 fputc_unfiltered (c, &stb);
11646 else
11647 fprintf_unfiltered (&stb, "\\x%02x", (unsigned char) c);
11648 }
11649
11650 puts_filtered (stb.string ().c_str ());
11651 }
11652 };
11653
11654 /* See remote.h. */
11655
11656 void
11657 send_remote_packet (gdb::array_view<const char> &buf,
11658 send_remote_packet_callbacks *callbacks)
11659 {
11660 if (buf.size () == 0 || buf.data ()[0] == '\0')
11661 error (_("a remote packet must not be empty"));
11662
11663 remote_target *remote = get_current_remote_target ();
11664 if (remote == nullptr)
11665 error (_("packets can only be sent to a remote target"));
11666
11667 callbacks->sending (buf);
11668
11669 remote->putpkt_binary (buf.data (), buf.size ());
11670 remote_state *rs = remote->get_remote_state ();
11671 int bytes = remote->getpkt_sane (&rs->buf, 0);
11672
11673 if (bytes < 0)
11674 error (_("error while fetching packet from remote target"));
11675
11676 gdb::array_view<const char> view (&rs->buf[0], bytes);
11677 callbacks->received (view);
11678 }
11679
11680 /* Entry point for the 'maint packet' command. */
11681
11682 static void
11683 cli_packet_command (const char *args, int from_tty)
11684 {
11685 cli_packet_command_callbacks cb;
11686 gdb::array_view<const char> view
11687 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11688 send_remote_packet (view, &cb);
11689 }
11690
11691 #if 0
11692 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11693
11694 static void display_thread_info (struct gdb_ext_thread_info *info);
11695
11696 static void threadset_test_cmd (char *cmd, int tty);
11697
11698 static void threadalive_test (char *cmd, int tty);
11699
11700 static void threadlist_test_cmd (char *cmd, int tty);
11701
11702 int get_and_display_threadinfo (threadref *ref);
11703
11704 static void threadinfo_test_cmd (char *cmd, int tty);
11705
11706 static int thread_display_step (threadref *ref, void *context);
11707
11708 static void threadlist_update_test_cmd (char *cmd, int tty);
11709
11710 static void init_remote_threadtests (void);
11711
11712 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11713
11714 static void
11715 threadset_test_cmd (const char *cmd, int tty)
11716 {
11717 int sample_thread = SAMPLE_THREAD;
11718
11719 printf_filtered (_("Remote threadset test\n"));
11720 set_general_thread (sample_thread);
11721 }
11722
11723
11724 static void
11725 threadalive_test (const char *cmd, int tty)
11726 {
11727 int sample_thread = SAMPLE_THREAD;
11728 int pid = inferior_ptid.pid ();
11729 ptid_t ptid = ptid_t (pid, sample_thread, 0);
11730
11731 if (remote_thread_alive (ptid))
11732 printf_filtered ("PASS: Thread alive test\n");
11733 else
11734 printf_filtered ("FAIL: Thread alive test\n");
11735 }
11736
11737 void output_threadid (char *title, threadref *ref);
11738
11739 void
11740 output_threadid (char *title, threadref *ref)
11741 {
11742 char hexid[20];
11743
11744 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
11745 hexid[16] = 0;
11746 printf_filtered ("%s %s\n", title, (&hexid[0]));
11747 }
11748
11749 static void
11750 threadlist_test_cmd (const char *cmd, int tty)
11751 {
11752 int startflag = 1;
11753 threadref nextthread;
11754 int done, result_count;
11755 threadref threadlist[3];
11756
11757 printf_filtered ("Remote Threadlist test\n");
11758 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11759 &result_count, &threadlist[0]))
11760 printf_filtered ("FAIL: threadlist test\n");
11761 else
11762 {
11763 threadref *scan = threadlist;
11764 threadref *limit = scan + result_count;
11765
11766 while (scan < limit)
11767 output_threadid (" thread ", scan++);
11768 }
11769 }
11770
11771 void
11772 display_thread_info (struct gdb_ext_thread_info *info)
11773 {
11774 output_threadid ("Threadid: ", &info->threadid);
11775 printf_filtered ("Name: %s\n ", info->shortname);
11776 printf_filtered ("State: %s\n", info->display);
11777 printf_filtered ("other: %s\n\n", info->more_display);
11778 }
11779
11780 int
11781 get_and_display_threadinfo (threadref *ref)
11782 {
11783 int result;
11784 int set;
11785 struct gdb_ext_thread_info threadinfo;
11786
11787 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11788 | TAG_MOREDISPLAY | TAG_DISPLAY;
11789 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11790 display_thread_info (&threadinfo);
11791 return result;
11792 }
11793
11794 static void
11795 threadinfo_test_cmd (const char *cmd, int tty)
11796 {
11797 int athread = SAMPLE_THREAD;
11798 threadref thread;
11799 int set;
11800
11801 int_to_threadref (&thread, athread);
11802 printf_filtered ("Remote Threadinfo test\n");
11803 if (!get_and_display_threadinfo (&thread))
11804 printf_filtered ("FAIL cannot get thread info\n");
11805 }
11806
11807 static int
11808 thread_display_step (threadref *ref, void *context)
11809 {
11810 /* output_threadid(" threadstep ",ref); *//* simple test */
11811 return get_and_display_threadinfo (ref);
11812 }
11813
11814 static void
11815 threadlist_update_test_cmd (const char *cmd, int tty)
11816 {
11817 printf_filtered ("Remote Threadlist update test\n");
11818 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11819 }
11820
11821 static void
11822 init_remote_threadtests (void)
11823 {
11824 add_com ("tlist", class_obscure, threadlist_test_cmd,
11825 _("Fetch and print the remote list of "
11826 "thread identifiers, one pkt only."));
11827 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11828 _("Fetch and display info about one thread."));
11829 add_com ("tset", class_obscure, threadset_test_cmd,
11830 _("Test setting to a different thread."));
11831 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11832 _("Iterate through updating all remote thread info."));
11833 add_com ("talive", class_obscure, threadalive_test,
11834 _("Remote thread alive test."));
11835 }
11836
11837 #endif /* 0 */
11838
11839 /* Convert a thread ID to a string. */
11840
11841 std::string
11842 remote_target::pid_to_str (ptid_t ptid)
11843 {
11844 struct remote_state *rs = get_remote_state ();
11845
11846 if (ptid == null_ptid)
11847 return normal_pid_to_str (ptid);
11848 else if (ptid.is_pid ())
11849 {
11850 /* Printing an inferior target id. */
11851
11852 /* When multi-process extensions are off, there's no way in the
11853 remote protocol to know the remote process id, if there's any
11854 at all. There's one exception --- when we're connected with
11855 target extended-remote, and we manually attached to a process
11856 with "attach PID". We don't record anywhere a flag that
11857 allows us to distinguish that case from the case of
11858 connecting with extended-remote and the stub already being
11859 attached to a process, and reporting yes to qAttached, hence
11860 no smart special casing here. */
11861 if (!remote_multi_process_p (rs))
11862 return "Remote target";
11863
11864 return normal_pid_to_str (ptid);
11865 }
11866 else
11867 {
11868 if (magic_null_ptid == ptid)
11869 return "Thread <main>";
11870 else if (remote_multi_process_p (rs))
11871 if (ptid.lwp () == 0)
11872 return normal_pid_to_str (ptid);
11873 else
11874 return string_printf ("Thread %d.%ld",
11875 ptid.pid (), ptid.lwp ());
11876 else
11877 return string_printf ("Thread %ld", ptid.lwp ());
11878 }
11879 }
11880
11881 /* Get the address of the thread local variable in OBJFILE which is
11882 stored at OFFSET within the thread local storage for thread PTID. */
11883
11884 CORE_ADDR
11885 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11886 CORE_ADDR offset)
11887 {
11888 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11889 {
11890 struct remote_state *rs = get_remote_state ();
11891 char *p = rs->buf.data ();
11892 char *endp = p + get_remote_packet_size ();
11893 enum packet_result result;
11894
11895 strcpy (p, "qGetTLSAddr:");
11896 p += strlen (p);
11897 p = write_ptid (p, endp, ptid);
11898 *p++ = ',';
11899 p += hexnumstr (p, offset);
11900 *p++ = ',';
11901 p += hexnumstr (p, lm);
11902 *p++ = '\0';
11903
11904 putpkt (rs->buf);
11905 getpkt (&rs->buf, 0);
11906 result = packet_ok (rs->buf,
11907 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11908 if (result == PACKET_OK)
11909 {
11910 ULONGEST addr;
11911
11912 unpack_varlen_hex (rs->buf.data (), &addr);
11913 return addr;
11914 }
11915 else if (result == PACKET_UNKNOWN)
11916 throw_error (TLS_GENERIC_ERROR,
11917 _("Remote target doesn't support qGetTLSAddr packet"));
11918 else
11919 throw_error (TLS_GENERIC_ERROR,
11920 _("Remote target failed to process qGetTLSAddr request"));
11921 }
11922 else
11923 throw_error (TLS_GENERIC_ERROR,
11924 _("TLS not supported or disabled on this target"));
11925 /* Not reached. */
11926 return 0;
11927 }
11928
11929 /* Provide thread local base, i.e. Thread Information Block address.
11930 Returns 1 if ptid is found and thread_local_base is non zero. */
11931
11932 bool
11933 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11934 {
11935 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11936 {
11937 struct remote_state *rs = get_remote_state ();
11938 char *p = rs->buf.data ();
11939 char *endp = p + get_remote_packet_size ();
11940 enum packet_result result;
11941
11942 strcpy (p, "qGetTIBAddr:");
11943 p += strlen (p);
11944 p = write_ptid (p, endp, ptid);
11945 *p++ = '\0';
11946
11947 putpkt (rs->buf);
11948 getpkt (&rs->buf, 0);
11949 result = packet_ok (rs->buf,
11950 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11951 if (result == PACKET_OK)
11952 {
11953 ULONGEST val;
11954 unpack_varlen_hex (rs->buf.data (), &val);
11955 if (addr)
11956 *addr = (CORE_ADDR) val;
11957 return true;
11958 }
11959 else if (result == PACKET_UNKNOWN)
11960 error (_("Remote target doesn't support qGetTIBAddr packet"));
11961 else
11962 error (_("Remote target failed to process qGetTIBAddr request"));
11963 }
11964 else
11965 error (_("qGetTIBAddr not supported or disabled on this target"));
11966 /* Not reached. */
11967 return false;
11968 }
11969
11970 /* Support for inferring a target description based on the current
11971 architecture and the size of a 'g' packet. While the 'g' packet
11972 can have any size (since optional registers can be left off the
11973 end), some sizes are easily recognizable given knowledge of the
11974 approximate architecture. */
11975
11976 struct remote_g_packet_guess
11977 {
11978 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
11979 : bytes (bytes_),
11980 tdesc (tdesc_)
11981 {
11982 }
11983
11984 int bytes;
11985 const struct target_desc *tdesc;
11986 };
11987
11988 struct remote_g_packet_data : public allocate_on_obstack
11989 {
11990 std::vector<remote_g_packet_guess> guesses;
11991 };
11992
11993 static struct gdbarch_data *remote_g_packet_data_handle;
11994
11995 static void *
11996 remote_g_packet_data_init (struct obstack *obstack)
11997 {
11998 return new (obstack) remote_g_packet_data;
11999 }
12000
12001 void
12002 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12003 const struct target_desc *tdesc)
12004 {
12005 struct remote_g_packet_data *data
12006 = ((struct remote_g_packet_data *)
12007 gdbarch_data (gdbarch, remote_g_packet_data_handle));
12008
12009 gdb_assert (tdesc != NULL);
12010
12011 for (const remote_g_packet_guess &guess : data->guesses)
12012 if (guess.bytes == bytes)
12013 internal_error (__FILE__, __LINE__,
12014 _("Duplicate g packet description added for size %d"),
12015 bytes);
12016
12017 data->guesses.emplace_back (bytes, tdesc);
12018 }
12019
12020 /* Return true if remote_read_description would do anything on this target
12021 and architecture, false otherwise. */
12022
12023 static bool
12024 remote_read_description_p (struct target_ops *target)
12025 {
12026 struct remote_g_packet_data *data
12027 = ((struct remote_g_packet_data *)
12028 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
12029
12030 return !data->guesses.empty ();
12031 }
12032
12033 const struct target_desc *
12034 remote_target::read_description ()
12035 {
12036 struct remote_g_packet_data *data
12037 = ((struct remote_g_packet_data *)
12038 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
12039
12040 /* Do not try this during initial connection, when we do not know
12041 whether there is a running but stopped thread. */
12042 if (!target_has_execution () || inferior_ptid == null_ptid)
12043 return beneath ()->read_description ();
12044
12045 if (!data->guesses.empty ())
12046 {
12047 int bytes = send_g_packet ();
12048
12049 for (const remote_g_packet_guess &guess : data->guesses)
12050 if (guess.bytes == bytes)
12051 return guess.tdesc;
12052
12053 /* We discard the g packet. A minor optimization would be to
12054 hold on to it, and fill the register cache once we have selected
12055 an architecture, but it's too tricky to do safely. */
12056 }
12057
12058 return beneath ()->read_description ();
12059 }
12060
12061 /* Remote file transfer support. This is host-initiated I/O, not
12062 target-initiated; for target-initiated, see remote-fileio.c. */
12063
12064 /* If *LEFT is at least the length of STRING, copy STRING to
12065 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12066 decrease *LEFT. Otherwise raise an error. */
12067
12068 static void
12069 remote_buffer_add_string (char **buffer, int *left, const char *string)
12070 {
12071 int len = strlen (string);
12072
12073 if (len > *left)
12074 error (_("Packet too long for target."));
12075
12076 memcpy (*buffer, string, len);
12077 *buffer += len;
12078 *left -= len;
12079
12080 /* NUL-terminate the buffer as a convenience, if there is
12081 room. */
12082 if (*left)
12083 **buffer = '\0';
12084 }
12085
12086 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12087 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12088 decrease *LEFT. Otherwise raise an error. */
12089
12090 static void
12091 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12092 int len)
12093 {
12094 if (2 * len > *left)
12095 error (_("Packet too long for target."));
12096
12097 bin2hex (bytes, *buffer, len);
12098 *buffer += 2 * len;
12099 *left -= 2 * len;
12100
12101 /* NUL-terminate the buffer as a convenience, if there is
12102 room. */
12103 if (*left)
12104 **buffer = '\0';
12105 }
12106
12107 /* If *LEFT is large enough, convert VALUE to hex and add it to
12108 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12109 decrease *LEFT. Otherwise raise an error. */
12110
12111 static void
12112 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12113 {
12114 int len = hexnumlen (value);
12115
12116 if (len > *left)
12117 error (_("Packet too long for target."));
12118
12119 hexnumstr (*buffer, value);
12120 *buffer += len;
12121 *left -= len;
12122
12123 /* NUL-terminate the buffer as a convenience, if there is
12124 room. */
12125 if (*left)
12126 **buffer = '\0';
12127 }
12128
12129 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12130 value, *REMOTE_ERRNO to the remote error number or zero if none
12131 was included, and *ATTACHMENT to point to the start of the annex
12132 if any. The length of the packet isn't needed here; there may
12133 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12134
12135 Return 0 if the packet could be parsed, -1 if it could not. If
12136 -1 is returned, the other variables may not be initialized. */
12137
12138 static int
12139 remote_hostio_parse_result (const char *buffer, int *retcode,
12140 int *remote_errno, const char **attachment)
12141 {
12142 char *p, *p2;
12143
12144 *remote_errno = 0;
12145 *attachment = NULL;
12146
12147 if (buffer[0] != 'F')
12148 return -1;
12149
12150 errno = 0;
12151 *retcode = strtol (&buffer[1], &p, 16);
12152 if (errno != 0 || p == &buffer[1])
12153 return -1;
12154
12155 /* Check for ",errno". */
12156 if (*p == ',')
12157 {
12158 errno = 0;
12159 *remote_errno = strtol (p + 1, &p2, 16);
12160 if (errno != 0 || p + 1 == p2)
12161 return -1;
12162 p = p2;
12163 }
12164
12165 /* Check for ";attachment". If there is no attachment, the
12166 packet should end here. */
12167 if (*p == ';')
12168 {
12169 *attachment = p + 1;
12170 return 0;
12171 }
12172 else if (*p == '\0')
12173 return 0;
12174 else
12175 return -1;
12176 }
12177
12178 /* Send a prepared I/O packet to the target and read its response.
12179 The prepared packet is in the global RS->BUF before this function
12180 is called, and the answer is there when we return.
12181
12182 COMMAND_BYTES is the length of the request to send, which may include
12183 binary data. WHICH_PACKET is the packet configuration to check
12184 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12185 is set to the error number and -1 is returned. Otherwise the value
12186 returned by the function is returned.
12187
12188 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12189 attachment is expected; an error will be reported if there's a
12190 mismatch. If one is found, *ATTACHMENT will be set to point into
12191 the packet buffer and *ATTACHMENT_LEN will be set to the
12192 attachment's length. */
12193
12194 int
12195 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12196 int *remote_errno, const char **attachment,
12197 int *attachment_len)
12198 {
12199 struct remote_state *rs = get_remote_state ();
12200 int ret, bytes_read;
12201 const char *attachment_tmp;
12202
12203 if (packet_support (which_packet) == PACKET_DISABLE)
12204 {
12205 *remote_errno = FILEIO_ENOSYS;
12206 return -1;
12207 }
12208
12209 putpkt_binary (rs->buf.data (), command_bytes);
12210 bytes_read = getpkt_sane (&rs->buf, 0);
12211
12212 /* If it timed out, something is wrong. Don't try to parse the
12213 buffer. */
12214 if (bytes_read < 0)
12215 {
12216 *remote_errno = FILEIO_EINVAL;
12217 return -1;
12218 }
12219
12220 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
12221 {
12222 case PACKET_ERROR:
12223 *remote_errno = FILEIO_EINVAL;
12224 return -1;
12225 case PACKET_UNKNOWN:
12226 *remote_errno = FILEIO_ENOSYS;
12227 return -1;
12228 case PACKET_OK:
12229 break;
12230 }
12231
12232 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12233 &attachment_tmp))
12234 {
12235 *remote_errno = FILEIO_EINVAL;
12236 return -1;
12237 }
12238
12239 /* Make sure we saw an attachment if and only if we expected one. */
12240 if ((attachment_tmp == NULL && attachment != NULL)
12241 || (attachment_tmp != NULL && attachment == NULL))
12242 {
12243 *remote_errno = FILEIO_EINVAL;
12244 return -1;
12245 }
12246
12247 /* If an attachment was found, it must point into the packet buffer;
12248 work out how many bytes there were. */
12249 if (attachment_tmp != NULL)
12250 {
12251 *attachment = attachment_tmp;
12252 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12253 }
12254
12255 return ret;
12256 }
12257
12258 /* See declaration.h. */
12259
12260 void
12261 readahead_cache::invalidate ()
12262 {
12263 this->fd = -1;
12264 }
12265
12266 /* See declaration.h. */
12267
12268 void
12269 readahead_cache::invalidate_fd (int fd)
12270 {
12271 if (this->fd == fd)
12272 this->fd = -1;
12273 }
12274
12275 /* Set the filesystem remote_hostio functions that take FILENAME
12276 arguments will use. Return 0 on success, or -1 if an error
12277 occurs (and set *REMOTE_ERRNO). */
12278
12279 int
12280 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12281 int *remote_errno)
12282 {
12283 struct remote_state *rs = get_remote_state ();
12284 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12285 char *p = rs->buf.data ();
12286 int left = get_remote_packet_size () - 1;
12287 char arg[9];
12288 int ret;
12289
12290 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12291 return 0;
12292
12293 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12294 return 0;
12295
12296 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12297
12298 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12299 remote_buffer_add_string (&p, &left, arg);
12300
12301 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12302 remote_errno, NULL, NULL);
12303
12304 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12305 return 0;
12306
12307 if (ret == 0)
12308 rs->fs_pid = required_pid;
12309
12310 return ret;
12311 }
12312
12313 /* Implementation of to_fileio_open. */
12314
12315 int
12316 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12317 int flags, int mode, int warn_if_slow,
12318 int *remote_errno)
12319 {
12320 struct remote_state *rs = get_remote_state ();
12321 char *p = rs->buf.data ();
12322 int left = get_remote_packet_size () - 1;
12323
12324 if (warn_if_slow)
12325 {
12326 static int warning_issued = 0;
12327
12328 printf_unfiltered (_("Reading %s from remote target...\n"),
12329 filename);
12330
12331 if (!warning_issued)
12332 {
12333 warning (_("File transfers from remote targets can be slow."
12334 " Use \"set sysroot\" to access files locally"
12335 " instead."));
12336 warning_issued = 1;
12337 }
12338 }
12339
12340 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12341 return -1;
12342
12343 remote_buffer_add_string (&p, &left, "vFile:open:");
12344
12345 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12346 strlen (filename));
12347 remote_buffer_add_string (&p, &left, ",");
12348
12349 remote_buffer_add_int (&p, &left, flags);
12350 remote_buffer_add_string (&p, &left, ",");
12351
12352 remote_buffer_add_int (&p, &left, mode);
12353
12354 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12355 remote_errno, NULL, NULL);
12356 }
12357
12358 int
12359 remote_target::fileio_open (struct inferior *inf, const char *filename,
12360 int flags, int mode, int warn_if_slow,
12361 int *remote_errno)
12362 {
12363 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12364 remote_errno);
12365 }
12366
12367 /* Implementation of to_fileio_pwrite. */
12368
12369 int
12370 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12371 ULONGEST offset, int *remote_errno)
12372 {
12373 struct remote_state *rs = get_remote_state ();
12374 char *p = rs->buf.data ();
12375 int left = get_remote_packet_size ();
12376 int out_len;
12377
12378 rs->readahead_cache.invalidate_fd (fd);
12379
12380 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12381
12382 remote_buffer_add_int (&p, &left, fd);
12383 remote_buffer_add_string (&p, &left, ",");
12384
12385 remote_buffer_add_int (&p, &left, offset);
12386 remote_buffer_add_string (&p, &left, ",");
12387
12388 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12389 (get_remote_packet_size ()
12390 - (p - rs->buf.data ())));
12391
12392 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12393 remote_errno, NULL, NULL);
12394 }
12395
12396 int
12397 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12398 ULONGEST offset, int *remote_errno)
12399 {
12400 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12401 }
12402
12403 /* Helper for the implementation of to_fileio_pread. Read the file
12404 from the remote side with vFile:pread. */
12405
12406 int
12407 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12408 ULONGEST offset, int *remote_errno)
12409 {
12410 struct remote_state *rs = get_remote_state ();
12411 char *p = rs->buf.data ();
12412 const char *attachment;
12413 int left = get_remote_packet_size ();
12414 int ret, attachment_len;
12415 int read_len;
12416
12417 remote_buffer_add_string (&p, &left, "vFile:pread:");
12418
12419 remote_buffer_add_int (&p, &left, fd);
12420 remote_buffer_add_string (&p, &left, ",");
12421
12422 remote_buffer_add_int (&p, &left, len);
12423 remote_buffer_add_string (&p, &left, ",");
12424
12425 remote_buffer_add_int (&p, &left, offset);
12426
12427 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12428 remote_errno, &attachment,
12429 &attachment_len);
12430
12431 if (ret < 0)
12432 return ret;
12433
12434 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12435 read_buf, len);
12436 if (read_len != ret)
12437 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12438
12439 return ret;
12440 }
12441
12442 /* See declaration.h. */
12443
12444 int
12445 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12446 ULONGEST offset)
12447 {
12448 if (this->fd == fd
12449 && this->offset <= offset
12450 && offset < this->offset + this->bufsize)
12451 {
12452 ULONGEST max = this->offset + this->bufsize;
12453
12454 if (offset + len > max)
12455 len = max - offset;
12456
12457 memcpy (read_buf, this->buf + offset - this->offset, len);
12458 return len;
12459 }
12460
12461 return 0;
12462 }
12463
12464 /* Implementation of to_fileio_pread. */
12465
12466 int
12467 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12468 ULONGEST offset, int *remote_errno)
12469 {
12470 int ret;
12471 struct remote_state *rs = get_remote_state ();
12472 readahead_cache *cache = &rs->readahead_cache;
12473
12474 ret = cache->pread (fd, read_buf, len, offset);
12475 if (ret > 0)
12476 {
12477 cache->hit_count++;
12478
12479 remote_debug_printf ("readahead cache hit %s",
12480 pulongest (cache->hit_count));
12481 return ret;
12482 }
12483
12484 cache->miss_count++;
12485
12486 remote_debug_printf ("readahead cache miss %s",
12487 pulongest (cache->miss_count));
12488
12489 cache->fd = fd;
12490 cache->offset = offset;
12491 cache->bufsize = get_remote_packet_size ();
12492 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12493
12494 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12495 cache->offset, remote_errno);
12496 if (ret <= 0)
12497 {
12498 cache->invalidate_fd (fd);
12499 return ret;
12500 }
12501
12502 cache->bufsize = ret;
12503 return cache->pread (fd, read_buf, len, offset);
12504 }
12505
12506 int
12507 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12508 ULONGEST offset, int *remote_errno)
12509 {
12510 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12511 }
12512
12513 /* Implementation of to_fileio_close. */
12514
12515 int
12516 remote_target::remote_hostio_close (int fd, int *remote_errno)
12517 {
12518 struct remote_state *rs = get_remote_state ();
12519 char *p = rs->buf.data ();
12520 int left = get_remote_packet_size () - 1;
12521
12522 rs->readahead_cache.invalidate_fd (fd);
12523
12524 remote_buffer_add_string (&p, &left, "vFile:close:");
12525
12526 remote_buffer_add_int (&p, &left, fd);
12527
12528 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12529 remote_errno, NULL, NULL);
12530 }
12531
12532 int
12533 remote_target::fileio_close (int fd, int *remote_errno)
12534 {
12535 return remote_hostio_close (fd, remote_errno);
12536 }
12537
12538 /* Implementation of to_fileio_unlink. */
12539
12540 int
12541 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12542 int *remote_errno)
12543 {
12544 struct remote_state *rs = get_remote_state ();
12545 char *p = rs->buf.data ();
12546 int left = get_remote_packet_size () - 1;
12547
12548 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12549 return -1;
12550
12551 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12552
12553 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12554 strlen (filename));
12555
12556 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12557 remote_errno, NULL, NULL);
12558 }
12559
12560 int
12561 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12562 int *remote_errno)
12563 {
12564 return remote_hostio_unlink (inf, filename, remote_errno);
12565 }
12566
12567 /* Implementation of to_fileio_readlink. */
12568
12569 gdb::optional<std::string>
12570 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12571 int *remote_errno)
12572 {
12573 struct remote_state *rs = get_remote_state ();
12574 char *p = rs->buf.data ();
12575 const char *attachment;
12576 int left = get_remote_packet_size ();
12577 int len, attachment_len;
12578 int read_len;
12579
12580 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12581 return {};
12582
12583 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12584
12585 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12586 strlen (filename));
12587
12588 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12589 remote_errno, &attachment,
12590 &attachment_len);
12591
12592 if (len < 0)
12593 return {};
12594
12595 std::string ret (len, '\0');
12596
12597 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12598 (gdb_byte *) &ret[0], len);
12599 if (read_len != len)
12600 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12601
12602 return ret;
12603 }
12604
12605 /* Implementation of to_fileio_fstat. */
12606
12607 int
12608 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12609 {
12610 struct remote_state *rs = get_remote_state ();
12611 char *p = rs->buf.data ();
12612 int left = get_remote_packet_size ();
12613 int attachment_len, ret;
12614 const char *attachment;
12615 struct fio_stat fst;
12616 int read_len;
12617
12618 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12619
12620 remote_buffer_add_int (&p, &left, fd);
12621
12622 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12623 remote_errno, &attachment,
12624 &attachment_len);
12625 if (ret < 0)
12626 {
12627 if (*remote_errno != FILEIO_ENOSYS)
12628 return ret;
12629
12630 /* Strictly we should return -1, ENOSYS here, but when
12631 "set sysroot remote:" was implemented in August 2008
12632 BFD's need for a stat function was sidestepped with
12633 this hack. This was not remedied until March 2015
12634 so we retain the previous behavior to avoid breaking
12635 compatibility.
12636
12637 Note that the memset is a March 2015 addition; older
12638 GDBs set st_size *and nothing else* so the structure
12639 would have garbage in all other fields. This might
12640 break something but retaining the previous behavior
12641 here would be just too wrong. */
12642
12643 memset (st, 0, sizeof (struct stat));
12644 st->st_size = INT_MAX;
12645 return 0;
12646 }
12647
12648 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12649 (gdb_byte *) &fst, sizeof (fst));
12650
12651 if (read_len != ret)
12652 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12653
12654 if (read_len != sizeof (fst))
12655 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12656 read_len, (int) sizeof (fst));
12657
12658 remote_fileio_to_host_stat (&fst, st);
12659
12660 return 0;
12661 }
12662
12663 /* Implementation of to_filesystem_is_local. */
12664
12665 bool
12666 remote_target::filesystem_is_local ()
12667 {
12668 /* Valgrind GDB presents itself as a remote target but works
12669 on the local filesystem: it does not implement remote get
12670 and users are not expected to set a sysroot. To handle
12671 this case we treat the remote filesystem as local if the
12672 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12673 does not support vFile:open. */
12674 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
12675 {
12676 enum packet_support ps = packet_support (PACKET_vFile_open);
12677
12678 if (ps == PACKET_SUPPORT_UNKNOWN)
12679 {
12680 int fd, remote_errno;
12681
12682 /* Try opening a file to probe support. The supplied
12683 filename is irrelevant, we only care about whether
12684 the stub recognizes the packet or not. */
12685 fd = remote_hostio_open (NULL, "just probing",
12686 FILEIO_O_RDONLY, 0700, 0,
12687 &remote_errno);
12688
12689 if (fd >= 0)
12690 remote_hostio_close (fd, &remote_errno);
12691
12692 ps = packet_support (PACKET_vFile_open);
12693 }
12694
12695 if (ps == PACKET_DISABLE)
12696 {
12697 static int warning_issued = 0;
12698
12699 if (!warning_issued)
12700 {
12701 warning (_("remote target does not support file"
12702 " transfer, attempting to access files"
12703 " from local filesystem."));
12704 warning_issued = 1;
12705 }
12706
12707 return true;
12708 }
12709 }
12710
12711 return false;
12712 }
12713
12714 static int
12715 remote_fileio_errno_to_host (int errnum)
12716 {
12717 switch (errnum)
12718 {
12719 case FILEIO_EPERM:
12720 return EPERM;
12721 case FILEIO_ENOENT:
12722 return ENOENT;
12723 case FILEIO_EINTR:
12724 return EINTR;
12725 case FILEIO_EIO:
12726 return EIO;
12727 case FILEIO_EBADF:
12728 return EBADF;
12729 case FILEIO_EACCES:
12730 return EACCES;
12731 case FILEIO_EFAULT:
12732 return EFAULT;
12733 case FILEIO_EBUSY:
12734 return EBUSY;
12735 case FILEIO_EEXIST:
12736 return EEXIST;
12737 case FILEIO_ENODEV:
12738 return ENODEV;
12739 case FILEIO_ENOTDIR:
12740 return ENOTDIR;
12741 case FILEIO_EISDIR:
12742 return EISDIR;
12743 case FILEIO_EINVAL:
12744 return EINVAL;
12745 case FILEIO_ENFILE:
12746 return ENFILE;
12747 case FILEIO_EMFILE:
12748 return EMFILE;
12749 case FILEIO_EFBIG:
12750 return EFBIG;
12751 case FILEIO_ENOSPC:
12752 return ENOSPC;
12753 case FILEIO_ESPIPE:
12754 return ESPIPE;
12755 case FILEIO_EROFS:
12756 return EROFS;
12757 case FILEIO_ENOSYS:
12758 return ENOSYS;
12759 case FILEIO_ENAMETOOLONG:
12760 return ENAMETOOLONG;
12761 }
12762 return -1;
12763 }
12764
12765 static char *
12766 remote_hostio_error (int errnum)
12767 {
12768 int host_error = remote_fileio_errno_to_host (errnum);
12769
12770 if (host_error == -1)
12771 error (_("Unknown remote I/O error %d"), errnum);
12772 else
12773 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12774 }
12775
12776 /* A RAII wrapper around a remote file descriptor. */
12777
12778 class scoped_remote_fd
12779 {
12780 public:
12781 scoped_remote_fd (remote_target *remote, int fd)
12782 : m_remote (remote), m_fd (fd)
12783 {
12784 }
12785
12786 ~scoped_remote_fd ()
12787 {
12788 if (m_fd != -1)
12789 {
12790 try
12791 {
12792 int remote_errno;
12793 m_remote->remote_hostio_close (m_fd, &remote_errno);
12794 }
12795 catch (...)
12796 {
12797 /* Swallow exception before it escapes the dtor. If
12798 something goes wrong, likely the connection is gone,
12799 and there's nothing else that can be done. */
12800 }
12801 }
12802 }
12803
12804 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12805
12806 /* Release ownership of the file descriptor, and return it. */
12807 ATTRIBUTE_UNUSED_RESULT int release () noexcept
12808 {
12809 int fd = m_fd;
12810 m_fd = -1;
12811 return fd;
12812 }
12813
12814 /* Return the owned file descriptor. */
12815 int get () const noexcept
12816 {
12817 return m_fd;
12818 }
12819
12820 private:
12821 /* The remote target. */
12822 remote_target *m_remote;
12823
12824 /* The owned remote I/O file descriptor. */
12825 int m_fd;
12826 };
12827
12828 void
12829 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12830 {
12831 remote_target *remote = get_current_remote_target ();
12832
12833 if (remote == nullptr)
12834 error (_("command can only be used with remote target"));
12835
12836 remote->remote_file_put (local_file, remote_file, from_tty);
12837 }
12838
12839 void
12840 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12841 int from_tty)
12842 {
12843 int retcode, remote_errno, bytes, io_size;
12844 int bytes_in_buffer;
12845 int saw_eof;
12846 ULONGEST offset;
12847
12848 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12849 if (file == NULL)
12850 perror_with_name (local_file);
12851
12852 scoped_remote_fd fd
12853 (this, remote_hostio_open (NULL,
12854 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12855 | FILEIO_O_TRUNC),
12856 0700, 0, &remote_errno));
12857 if (fd.get () == -1)
12858 remote_hostio_error (remote_errno);
12859
12860 /* Send up to this many bytes at once. They won't all fit in the
12861 remote packet limit, so we'll transfer slightly fewer. */
12862 io_size = get_remote_packet_size ();
12863 gdb::byte_vector buffer (io_size);
12864
12865 bytes_in_buffer = 0;
12866 saw_eof = 0;
12867 offset = 0;
12868 while (bytes_in_buffer || !saw_eof)
12869 {
12870 if (!saw_eof)
12871 {
12872 bytes = fread (buffer.data () + bytes_in_buffer, 1,
12873 io_size - bytes_in_buffer,
12874 file.get ());
12875 if (bytes == 0)
12876 {
12877 if (ferror (file.get ()))
12878 error (_("Error reading %s."), local_file);
12879 else
12880 {
12881 /* EOF. Unless there is something still in the
12882 buffer from the last iteration, we are done. */
12883 saw_eof = 1;
12884 if (bytes_in_buffer == 0)
12885 break;
12886 }
12887 }
12888 }
12889 else
12890 bytes = 0;
12891
12892 bytes += bytes_in_buffer;
12893 bytes_in_buffer = 0;
12894
12895 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12896 offset, &remote_errno);
12897
12898 if (retcode < 0)
12899 remote_hostio_error (remote_errno);
12900 else if (retcode == 0)
12901 error (_("Remote write of %d bytes returned 0!"), bytes);
12902 else if (retcode < bytes)
12903 {
12904 /* Short write. Save the rest of the read data for the next
12905 write. */
12906 bytes_in_buffer = bytes - retcode;
12907 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
12908 }
12909
12910 offset += retcode;
12911 }
12912
12913 if (remote_hostio_close (fd.release (), &remote_errno))
12914 remote_hostio_error (remote_errno);
12915
12916 if (from_tty)
12917 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12918 }
12919
12920 void
12921 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12922 {
12923 remote_target *remote = get_current_remote_target ();
12924
12925 if (remote == nullptr)
12926 error (_("command can only be used with remote target"));
12927
12928 remote->remote_file_get (remote_file, local_file, from_tty);
12929 }
12930
12931 void
12932 remote_target::remote_file_get (const char *remote_file, const char *local_file,
12933 int from_tty)
12934 {
12935 int remote_errno, bytes, io_size;
12936 ULONGEST offset;
12937
12938 scoped_remote_fd fd
12939 (this, remote_hostio_open (NULL,
12940 remote_file, FILEIO_O_RDONLY, 0, 0,
12941 &remote_errno));
12942 if (fd.get () == -1)
12943 remote_hostio_error (remote_errno);
12944
12945 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12946 if (file == NULL)
12947 perror_with_name (local_file);
12948
12949 /* Send up to this many bytes at once. They won't all fit in the
12950 remote packet limit, so we'll transfer slightly fewer. */
12951 io_size = get_remote_packet_size ();
12952 gdb::byte_vector buffer (io_size);
12953
12954 offset = 0;
12955 while (1)
12956 {
12957 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
12958 &remote_errno);
12959 if (bytes == 0)
12960 /* Success, but no bytes, means end-of-file. */
12961 break;
12962 if (bytes == -1)
12963 remote_hostio_error (remote_errno);
12964
12965 offset += bytes;
12966
12967 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
12968 if (bytes == 0)
12969 perror_with_name (local_file);
12970 }
12971
12972 if (remote_hostio_close (fd.release (), &remote_errno))
12973 remote_hostio_error (remote_errno);
12974
12975 if (from_tty)
12976 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12977 }
12978
12979 void
12980 remote_file_delete (const char *remote_file, int from_tty)
12981 {
12982 remote_target *remote = get_current_remote_target ();
12983
12984 if (remote == nullptr)
12985 error (_("command can only be used with remote target"));
12986
12987 remote->remote_file_delete (remote_file, from_tty);
12988 }
12989
12990 void
12991 remote_target::remote_file_delete (const char *remote_file, int from_tty)
12992 {
12993 int retcode, remote_errno;
12994
12995 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
12996 if (retcode == -1)
12997 remote_hostio_error (remote_errno);
12998
12999 if (from_tty)
13000 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
13001 }
13002
13003 static void
13004 remote_put_command (const char *args, int from_tty)
13005 {
13006 if (args == NULL)
13007 error_no_arg (_("file to put"));
13008
13009 gdb_argv argv (args);
13010 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13011 error (_("Invalid parameters to remote put"));
13012
13013 remote_file_put (argv[0], argv[1], from_tty);
13014 }
13015
13016 static void
13017 remote_get_command (const char *args, int from_tty)
13018 {
13019 if (args == NULL)
13020 error_no_arg (_("file to get"));
13021
13022 gdb_argv argv (args);
13023 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13024 error (_("Invalid parameters to remote get"));
13025
13026 remote_file_get (argv[0], argv[1], from_tty);
13027 }
13028
13029 static void
13030 remote_delete_command (const char *args, int from_tty)
13031 {
13032 if (args == NULL)
13033 error_no_arg (_("file to delete"));
13034
13035 gdb_argv argv (args);
13036 if (argv[0] == NULL || argv[1] != NULL)
13037 error (_("Invalid parameters to remote delete"));
13038
13039 remote_file_delete (argv[0], from_tty);
13040 }
13041
13042 bool
13043 remote_target::can_execute_reverse ()
13044 {
13045 if (packet_support (PACKET_bs) == PACKET_ENABLE
13046 || packet_support (PACKET_bc) == PACKET_ENABLE)
13047 return true;
13048 else
13049 return false;
13050 }
13051
13052 bool
13053 remote_target::supports_non_stop ()
13054 {
13055 return true;
13056 }
13057
13058 bool
13059 remote_target::supports_disable_randomization ()
13060 {
13061 /* Only supported in extended mode. */
13062 return false;
13063 }
13064
13065 bool
13066 remote_target::supports_multi_process ()
13067 {
13068 struct remote_state *rs = get_remote_state ();
13069
13070 return remote_multi_process_p (rs);
13071 }
13072
13073 static int
13074 remote_supports_cond_tracepoints ()
13075 {
13076 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
13077 }
13078
13079 bool
13080 remote_target::supports_evaluation_of_breakpoint_conditions ()
13081 {
13082 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
13083 }
13084
13085 static int
13086 remote_supports_fast_tracepoints ()
13087 {
13088 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13089 }
13090
13091 static int
13092 remote_supports_static_tracepoints ()
13093 {
13094 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13095 }
13096
13097 static int
13098 remote_supports_install_in_trace ()
13099 {
13100 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13101 }
13102
13103 bool
13104 remote_target::supports_enable_disable_tracepoint ()
13105 {
13106 return (packet_support (PACKET_EnableDisableTracepoints_feature)
13107 == PACKET_ENABLE);
13108 }
13109
13110 bool
13111 remote_target::supports_string_tracing ()
13112 {
13113 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13114 }
13115
13116 bool
13117 remote_target::can_run_breakpoint_commands ()
13118 {
13119 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13120 }
13121
13122 void
13123 remote_target::trace_init ()
13124 {
13125 struct remote_state *rs = get_remote_state ();
13126
13127 putpkt ("QTinit");
13128 remote_get_noisy_reply ();
13129 if (strcmp (rs->buf.data (), "OK") != 0)
13130 error (_("Target does not support this command."));
13131 }
13132
13133 /* Recursive routine to walk through command list including loops, and
13134 download packets for each command. */
13135
13136 void
13137 remote_target::remote_download_command_source (int num, ULONGEST addr,
13138 struct command_line *cmds)
13139 {
13140 struct remote_state *rs = get_remote_state ();
13141 struct command_line *cmd;
13142
13143 for (cmd = cmds; cmd; cmd = cmd->next)
13144 {
13145 QUIT; /* Allow user to bail out with ^C. */
13146 strcpy (rs->buf.data (), "QTDPsrc:");
13147 encode_source_string (num, addr, "cmd", cmd->line,
13148 rs->buf.data () + strlen (rs->buf.data ()),
13149 rs->buf.size () - strlen (rs->buf.data ()));
13150 putpkt (rs->buf);
13151 remote_get_noisy_reply ();
13152 if (strcmp (rs->buf.data (), "OK"))
13153 warning (_("Target does not support source download."));
13154
13155 if (cmd->control_type == while_control
13156 || cmd->control_type == while_stepping_control)
13157 {
13158 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13159
13160 QUIT; /* Allow user to bail out with ^C. */
13161 strcpy (rs->buf.data (), "QTDPsrc:");
13162 encode_source_string (num, addr, "cmd", "end",
13163 rs->buf.data () + strlen (rs->buf.data ()),
13164 rs->buf.size () - strlen (rs->buf.data ()));
13165 putpkt (rs->buf);
13166 remote_get_noisy_reply ();
13167 if (strcmp (rs->buf.data (), "OK"))
13168 warning (_("Target does not support source download."));
13169 }
13170 }
13171 }
13172
13173 void
13174 remote_target::download_tracepoint (struct bp_location *loc)
13175 {
13176 CORE_ADDR tpaddr;
13177 char addrbuf[40];
13178 std::vector<std::string> tdp_actions;
13179 std::vector<std::string> stepping_actions;
13180 char *pkt;
13181 struct breakpoint *b = loc->owner;
13182 struct tracepoint *t = (struct tracepoint *) b;
13183 struct remote_state *rs = get_remote_state ();
13184 int ret;
13185 const char *err_msg = _("Tracepoint packet too large for target.");
13186 size_t size_left;
13187
13188 /* We use a buffer other than rs->buf because we'll build strings
13189 across multiple statements, and other statements in between could
13190 modify rs->buf. */
13191 gdb::char_vector buf (get_remote_packet_size ());
13192
13193 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13194
13195 tpaddr = loc->address;
13196 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13197 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13198 b->number, addrbuf, /* address */
13199 (b->enable_state == bp_enabled ? 'E' : 'D'),
13200 t->step_count, t->pass_count);
13201
13202 if (ret < 0 || ret >= buf.size ())
13203 error ("%s", err_msg);
13204
13205 /* Fast tracepoints are mostly handled by the target, but we can
13206 tell the target how big of an instruction block should be moved
13207 around. */
13208 if (b->type == bp_fast_tracepoint)
13209 {
13210 /* Only test for support at download time; we may not know
13211 target capabilities at definition time. */
13212 if (remote_supports_fast_tracepoints ())
13213 {
13214 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13215 NULL))
13216 {
13217 size_left = buf.size () - strlen (buf.data ());
13218 ret = snprintf (buf.data () + strlen (buf.data ()),
13219 size_left, ":F%x",
13220 gdb_insn_length (loc->gdbarch, tpaddr));
13221
13222 if (ret < 0 || ret >= size_left)
13223 error ("%s", err_msg);
13224 }
13225 else
13226 /* If it passed validation at definition but fails now,
13227 something is very wrong. */
13228 internal_error (__FILE__, __LINE__,
13229 _("Fast tracepoint not "
13230 "valid during download"));
13231 }
13232 else
13233 /* Fast tracepoints are functionally identical to regular
13234 tracepoints, so don't take lack of support as a reason to
13235 give up on the trace run. */
13236 warning (_("Target does not support fast tracepoints, "
13237 "downloading %d as regular tracepoint"), b->number);
13238 }
13239 else if (b->type == bp_static_tracepoint)
13240 {
13241 /* Only test for support at download time; we may not know
13242 target capabilities at definition time. */
13243 if (remote_supports_static_tracepoints ())
13244 {
13245 struct static_tracepoint_marker marker;
13246
13247 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13248 {
13249 size_left = buf.size () - strlen (buf.data ());
13250 ret = snprintf (buf.data () + strlen (buf.data ()),
13251 size_left, ":S");
13252
13253 if (ret < 0 || ret >= size_left)
13254 error ("%s", err_msg);
13255 }
13256 else
13257 error (_("Static tracepoint not valid during download"));
13258 }
13259 else
13260 /* Fast tracepoints are functionally identical to regular
13261 tracepoints, so don't take lack of support as a reason
13262 to give up on the trace run. */
13263 error (_("Target does not support static tracepoints"));
13264 }
13265 /* If the tracepoint has a conditional, make it into an agent
13266 expression and append to the definition. */
13267 if (loc->cond)
13268 {
13269 /* Only test support at download time, we may not know target
13270 capabilities at definition time. */
13271 if (remote_supports_cond_tracepoints ())
13272 {
13273 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13274 loc->cond.get ());
13275
13276 size_left = buf.size () - strlen (buf.data ());
13277
13278 ret = snprintf (buf.data () + strlen (buf.data ()),
13279 size_left, ":X%x,", aexpr->len);
13280
13281 if (ret < 0 || ret >= size_left)
13282 error ("%s", err_msg);
13283
13284 size_left = buf.size () - strlen (buf.data ());
13285
13286 /* Two bytes to encode each aexpr byte, plus the terminating
13287 null byte. */
13288 if (aexpr->len * 2 + 1 > size_left)
13289 error ("%s", err_msg);
13290
13291 pkt = buf.data () + strlen (buf.data ());
13292
13293 for (int ndx = 0; ndx < aexpr->len; ++ndx)
13294 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13295 *pkt = '\0';
13296 }
13297 else
13298 warning (_("Target does not support conditional tracepoints, "
13299 "ignoring tp %d cond"), b->number);
13300 }
13301
13302 if (b->commands || !default_collect.empty ())
13303 {
13304 size_left = buf.size () - strlen (buf.data ());
13305
13306 ret = snprintf (buf.data () + strlen (buf.data ()),
13307 size_left, "-");
13308
13309 if (ret < 0 || ret >= size_left)
13310 error ("%s", err_msg);
13311 }
13312
13313 putpkt (buf.data ());
13314 remote_get_noisy_reply ();
13315 if (strcmp (rs->buf.data (), "OK"))
13316 error (_("Target does not support tracepoints."));
13317
13318 /* do_single_steps (t); */
13319 for (auto action_it = tdp_actions.begin ();
13320 action_it != tdp_actions.end (); action_it++)
13321 {
13322 QUIT; /* Allow user to bail out with ^C. */
13323
13324 bool has_more = ((action_it + 1) != tdp_actions.end ()
13325 || !stepping_actions.empty ());
13326
13327 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13328 b->number, addrbuf, /* address */
13329 action_it->c_str (),
13330 has_more ? '-' : 0);
13331
13332 if (ret < 0 || ret >= buf.size ())
13333 error ("%s", err_msg);
13334
13335 putpkt (buf.data ());
13336 remote_get_noisy_reply ();
13337 if (strcmp (rs->buf.data (), "OK"))
13338 error (_("Error on target while setting tracepoints."));
13339 }
13340
13341 for (auto action_it = stepping_actions.begin ();
13342 action_it != stepping_actions.end (); action_it++)
13343 {
13344 QUIT; /* Allow user to bail out with ^C. */
13345
13346 bool is_first = action_it == stepping_actions.begin ();
13347 bool has_more = (action_it + 1) != stepping_actions.end ();
13348
13349 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13350 b->number, addrbuf, /* address */
13351 is_first ? "S" : "",
13352 action_it->c_str (),
13353 has_more ? "-" : "");
13354
13355 if (ret < 0 || ret >= buf.size ())
13356 error ("%s", err_msg);
13357
13358 putpkt (buf.data ());
13359 remote_get_noisy_reply ();
13360 if (strcmp (rs->buf.data (), "OK"))
13361 error (_("Error on target while setting tracepoints."));
13362 }
13363
13364 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13365 {
13366 if (b->location != NULL)
13367 {
13368 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13369
13370 if (ret < 0 || ret >= buf.size ())
13371 error ("%s", err_msg);
13372
13373 encode_source_string (b->number, loc->address, "at",
13374 event_location_to_string (b->location.get ()),
13375 buf.data () + strlen (buf.data ()),
13376 buf.size () - strlen (buf.data ()));
13377 putpkt (buf.data ());
13378 remote_get_noisy_reply ();
13379 if (strcmp (rs->buf.data (), "OK"))
13380 warning (_("Target does not support source download."));
13381 }
13382 if (b->cond_string)
13383 {
13384 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13385
13386 if (ret < 0 || ret >= buf.size ())
13387 error ("%s", err_msg);
13388
13389 encode_source_string (b->number, loc->address,
13390 "cond", b->cond_string.get (),
13391 buf.data () + strlen (buf.data ()),
13392 buf.size () - strlen (buf.data ()));
13393 putpkt (buf.data ());
13394 remote_get_noisy_reply ();
13395 if (strcmp (rs->buf.data (), "OK"))
13396 warning (_("Target does not support source download."));
13397 }
13398 remote_download_command_source (b->number, loc->address,
13399 breakpoint_commands (b));
13400 }
13401 }
13402
13403 bool
13404 remote_target::can_download_tracepoint ()
13405 {
13406 struct remote_state *rs = get_remote_state ();
13407 struct trace_status *ts;
13408 int status;
13409
13410 /* Don't try to install tracepoints until we've relocated our
13411 symbols, and fetched and merged the target's tracepoint list with
13412 ours. */
13413 if (rs->starting_up)
13414 return false;
13415
13416 ts = current_trace_status ();
13417 status = get_trace_status (ts);
13418
13419 if (status == -1 || !ts->running_known || !ts->running)
13420 return false;
13421
13422 /* If we are in a tracing experiment, but remote stub doesn't support
13423 installing tracepoint in trace, we have to return. */
13424 if (!remote_supports_install_in_trace ())
13425 return false;
13426
13427 return true;
13428 }
13429
13430
13431 void
13432 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13433 {
13434 struct remote_state *rs = get_remote_state ();
13435 char *p;
13436
13437 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13438 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13439 tsv.builtin);
13440 p = rs->buf.data () + strlen (rs->buf.data ());
13441 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13442 >= get_remote_packet_size ())
13443 error (_("Trace state variable name too long for tsv definition packet"));
13444 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13445 *p++ = '\0';
13446 putpkt (rs->buf);
13447 remote_get_noisy_reply ();
13448 if (rs->buf[0] == '\0')
13449 error (_("Target does not support this command."));
13450 if (strcmp (rs->buf.data (), "OK") != 0)
13451 error (_("Error on target while downloading trace state variable."));
13452 }
13453
13454 void
13455 remote_target::enable_tracepoint (struct bp_location *location)
13456 {
13457 struct remote_state *rs = get_remote_state ();
13458
13459 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13460 location->owner->number,
13461 phex (location->address, sizeof (CORE_ADDR)));
13462 putpkt (rs->buf);
13463 remote_get_noisy_reply ();
13464 if (rs->buf[0] == '\0')
13465 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13466 if (strcmp (rs->buf.data (), "OK") != 0)
13467 error (_("Error on target while enabling tracepoint."));
13468 }
13469
13470 void
13471 remote_target::disable_tracepoint (struct bp_location *location)
13472 {
13473 struct remote_state *rs = get_remote_state ();
13474
13475 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13476 location->owner->number,
13477 phex (location->address, sizeof (CORE_ADDR)));
13478 putpkt (rs->buf);
13479 remote_get_noisy_reply ();
13480 if (rs->buf[0] == '\0')
13481 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13482 if (strcmp (rs->buf.data (), "OK") != 0)
13483 error (_("Error on target while disabling tracepoint."));
13484 }
13485
13486 void
13487 remote_target::trace_set_readonly_regions ()
13488 {
13489 asection *s;
13490 bfd_size_type size;
13491 bfd_vma vma;
13492 int anysecs = 0;
13493 int offset = 0;
13494
13495 if (!current_program_space->exec_bfd ())
13496 return; /* No information to give. */
13497
13498 struct remote_state *rs = get_remote_state ();
13499
13500 strcpy (rs->buf.data (), "QTro");
13501 offset = strlen (rs->buf.data ());
13502 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
13503 {
13504 char tmp1[40], tmp2[40];
13505 int sec_length;
13506
13507 if ((s->flags & SEC_LOAD) == 0 ||
13508 /* (s->flags & SEC_CODE) == 0 || */
13509 (s->flags & SEC_READONLY) == 0)
13510 continue;
13511
13512 anysecs = 1;
13513 vma = bfd_section_vma (s);
13514 size = bfd_section_size (s);
13515 sprintf_vma (tmp1, vma);
13516 sprintf_vma (tmp2, vma + size);
13517 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13518 if (offset + sec_length + 1 > rs->buf.size ())
13519 {
13520 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
13521 warning (_("\
13522 Too many sections for read-only sections definition packet."));
13523 break;
13524 }
13525 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13526 tmp1, tmp2);
13527 offset += sec_length;
13528 }
13529 if (anysecs)
13530 {
13531 putpkt (rs->buf);
13532 getpkt (&rs->buf, 0);
13533 }
13534 }
13535
13536 void
13537 remote_target::trace_start ()
13538 {
13539 struct remote_state *rs = get_remote_state ();
13540
13541 putpkt ("QTStart");
13542 remote_get_noisy_reply ();
13543 if (rs->buf[0] == '\0')
13544 error (_("Target does not support this command."));
13545 if (strcmp (rs->buf.data (), "OK") != 0)
13546 error (_("Bogus reply from target: %s"), rs->buf.data ());
13547 }
13548
13549 int
13550 remote_target::get_trace_status (struct trace_status *ts)
13551 {
13552 /* Initialize it just to avoid a GCC false warning. */
13553 char *p = NULL;
13554 enum packet_result result;
13555 struct remote_state *rs = get_remote_state ();
13556
13557 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13558 return -1;
13559
13560 /* FIXME we need to get register block size some other way. */
13561 trace_regblock_size
13562 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13563
13564 putpkt ("qTStatus");
13565
13566 try
13567 {
13568 p = remote_get_noisy_reply ();
13569 }
13570 catch (const gdb_exception_error &ex)
13571 {
13572 if (ex.error != TARGET_CLOSE_ERROR)
13573 {
13574 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13575 return -1;
13576 }
13577 throw;
13578 }
13579
13580 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13581
13582 /* If the remote target doesn't do tracing, flag it. */
13583 if (result == PACKET_UNKNOWN)
13584 return -1;
13585
13586 /* We're working with a live target. */
13587 ts->filename = NULL;
13588
13589 if (*p++ != 'T')
13590 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13591
13592 /* Function 'parse_trace_status' sets default value of each field of
13593 'ts' at first, so we don't have to do it here. */
13594 parse_trace_status (p, ts);
13595
13596 return ts->running;
13597 }
13598
13599 void
13600 remote_target::get_tracepoint_status (struct breakpoint *bp,
13601 struct uploaded_tp *utp)
13602 {
13603 struct remote_state *rs = get_remote_state ();
13604 char *reply;
13605 struct tracepoint *tp = (struct tracepoint *) bp;
13606 size_t size = get_remote_packet_size ();
13607
13608 if (tp)
13609 {
13610 tp->hit_count = 0;
13611 tp->traceframe_usage = 0;
13612 for (bp_location *loc : tp->locations ())
13613 {
13614 /* If the tracepoint was never downloaded, don't go asking for
13615 any status. */
13616 if (tp->number_on_target == 0)
13617 continue;
13618 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13619 phex_nz (loc->address, 0));
13620 putpkt (rs->buf);
13621 reply = remote_get_noisy_reply ();
13622 if (reply && *reply)
13623 {
13624 if (*reply == 'V')
13625 parse_tracepoint_status (reply + 1, bp, utp);
13626 }
13627 }
13628 }
13629 else if (utp)
13630 {
13631 utp->hit_count = 0;
13632 utp->traceframe_usage = 0;
13633 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13634 phex_nz (utp->addr, 0));
13635 putpkt (rs->buf);
13636 reply = remote_get_noisy_reply ();
13637 if (reply && *reply)
13638 {
13639 if (*reply == 'V')
13640 parse_tracepoint_status (reply + 1, bp, utp);
13641 }
13642 }
13643 }
13644
13645 void
13646 remote_target::trace_stop ()
13647 {
13648 struct remote_state *rs = get_remote_state ();
13649
13650 putpkt ("QTStop");
13651 remote_get_noisy_reply ();
13652 if (rs->buf[0] == '\0')
13653 error (_("Target does not support this command."));
13654 if (strcmp (rs->buf.data (), "OK") != 0)
13655 error (_("Bogus reply from target: %s"), rs->buf.data ());
13656 }
13657
13658 int
13659 remote_target::trace_find (enum trace_find_type type, int num,
13660 CORE_ADDR addr1, CORE_ADDR addr2,
13661 int *tpp)
13662 {
13663 struct remote_state *rs = get_remote_state ();
13664 char *endbuf = rs->buf.data () + get_remote_packet_size ();
13665 char *p, *reply;
13666 int target_frameno = -1, target_tracept = -1;
13667
13668 /* Lookups other than by absolute frame number depend on the current
13669 trace selected, so make sure it is correct on the remote end
13670 first. */
13671 if (type != tfind_number)
13672 set_remote_traceframe ();
13673
13674 p = rs->buf.data ();
13675 strcpy (p, "QTFrame:");
13676 p = strchr (p, '\0');
13677 switch (type)
13678 {
13679 case tfind_number:
13680 xsnprintf (p, endbuf - p, "%x", num);
13681 break;
13682 case tfind_pc:
13683 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13684 break;
13685 case tfind_tp:
13686 xsnprintf (p, endbuf - p, "tdp:%x", num);
13687 break;
13688 case tfind_range:
13689 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13690 phex_nz (addr2, 0));
13691 break;
13692 case tfind_outside:
13693 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13694 phex_nz (addr2, 0));
13695 break;
13696 default:
13697 error (_("Unknown trace find type %d"), type);
13698 }
13699
13700 putpkt (rs->buf);
13701 reply = remote_get_noisy_reply ();
13702 if (*reply == '\0')
13703 error (_("Target does not support this command."));
13704
13705 while (reply && *reply)
13706 switch (*reply)
13707 {
13708 case 'F':
13709 p = ++reply;
13710 target_frameno = (int) strtol (p, &reply, 16);
13711 if (reply == p)
13712 error (_("Unable to parse trace frame number"));
13713 /* Don't update our remote traceframe number cache on failure
13714 to select a remote traceframe. */
13715 if (target_frameno == -1)
13716 return -1;
13717 break;
13718 case 'T':
13719 p = ++reply;
13720 target_tracept = (int) strtol (p, &reply, 16);
13721 if (reply == p)
13722 error (_("Unable to parse tracepoint number"));
13723 break;
13724 case 'O': /* "OK"? */
13725 if (reply[1] == 'K' && reply[2] == '\0')
13726 reply += 2;
13727 else
13728 error (_("Bogus reply from target: %s"), reply);
13729 break;
13730 default:
13731 error (_("Bogus reply from target: %s"), reply);
13732 }
13733 if (tpp)
13734 *tpp = target_tracept;
13735
13736 rs->remote_traceframe_number = target_frameno;
13737 return target_frameno;
13738 }
13739
13740 bool
13741 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13742 {
13743 struct remote_state *rs = get_remote_state ();
13744 char *reply;
13745 ULONGEST uval;
13746
13747 set_remote_traceframe ();
13748
13749 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
13750 putpkt (rs->buf);
13751 reply = remote_get_noisy_reply ();
13752 if (reply && *reply)
13753 {
13754 if (*reply == 'V')
13755 {
13756 unpack_varlen_hex (reply + 1, &uval);
13757 *val = (LONGEST) uval;
13758 return true;
13759 }
13760 }
13761 return false;
13762 }
13763
13764 int
13765 remote_target::save_trace_data (const char *filename)
13766 {
13767 struct remote_state *rs = get_remote_state ();
13768 char *p, *reply;
13769
13770 p = rs->buf.data ();
13771 strcpy (p, "QTSave:");
13772 p += strlen (p);
13773 if ((p - rs->buf.data ()) + strlen (filename) * 2
13774 >= get_remote_packet_size ())
13775 error (_("Remote file name too long for trace save packet"));
13776 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13777 *p++ = '\0';
13778 putpkt (rs->buf);
13779 reply = remote_get_noisy_reply ();
13780 if (*reply == '\0')
13781 error (_("Target does not support this command."));
13782 if (strcmp (reply, "OK") != 0)
13783 error (_("Bogus reply from target: %s"), reply);
13784 return 0;
13785 }
13786
13787 /* This is basically a memory transfer, but needs to be its own packet
13788 because we don't know how the target actually organizes its trace
13789 memory, plus we want to be able to ask for as much as possible, but
13790 not be unhappy if we don't get as much as we ask for. */
13791
13792 LONGEST
13793 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13794 {
13795 struct remote_state *rs = get_remote_state ();
13796 char *reply;
13797 char *p;
13798 int rslt;
13799
13800 p = rs->buf.data ();
13801 strcpy (p, "qTBuffer:");
13802 p += strlen (p);
13803 p += hexnumstr (p, offset);
13804 *p++ = ',';
13805 p += hexnumstr (p, len);
13806 *p++ = '\0';
13807
13808 putpkt (rs->buf);
13809 reply = remote_get_noisy_reply ();
13810 if (reply && *reply)
13811 {
13812 /* 'l' by itself means we're at the end of the buffer and
13813 there is nothing more to get. */
13814 if (*reply == 'l')
13815 return 0;
13816
13817 /* Convert the reply into binary. Limit the number of bytes to
13818 convert according to our passed-in buffer size, rather than
13819 what was returned in the packet; if the target is
13820 unexpectedly generous and gives us a bigger reply than we
13821 asked for, we don't want to crash. */
13822 rslt = hex2bin (reply, buf, len);
13823 return rslt;
13824 }
13825
13826 /* Something went wrong, flag as an error. */
13827 return -1;
13828 }
13829
13830 void
13831 remote_target::set_disconnected_tracing (int val)
13832 {
13833 struct remote_state *rs = get_remote_state ();
13834
13835 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13836 {
13837 char *reply;
13838
13839 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13840 "QTDisconnected:%x", val);
13841 putpkt (rs->buf);
13842 reply = remote_get_noisy_reply ();
13843 if (*reply == '\0')
13844 error (_("Target does not support this command."));
13845 if (strcmp (reply, "OK") != 0)
13846 error (_("Bogus reply from target: %s"), reply);
13847 }
13848 else if (val)
13849 warning (_("Target does not support disconnected tracing."));
13850 }
13851
13852 int
13853 remote_target::core_of_thread (ptid_t ptid)
13854 {
13855 thread_info *info = find_thread_ptid (this, ptid);
13856
13857 if (info != NULL && info->priv != NULL)
13858 return get_remote_thread_info (info)->core;
13859
13860 return -1;
13861 }
13862
13863 void
13864 remote_target::set_circular_trace_buffer (int val)
13865 {
13866 struct remote_state *rs = get_remote_state ();
13867 char *reply;
13868
13869 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13870 "QTBuffer:circular:%x", val);
13871 putpkt (rs->buf);
13872 reply = remote_get_noisy_reply ();
13873 if (*reply == '\0')
13874 error (_("Target does not support this command."));
13875 if (strcmp (reply, "OK") != 0)
13876 error (_("Bogus reply from target: %s"), reply);
13877 }
13878
13879 traceframe_info_up
13880 remote_target::traceframe_info ()
13881 {
13882 gdb::optional<gdb::char_vector> text
13883 = target_read_stralloc (current_inferior ()->top_target (),
13884 TARGET_OBJECT_TRACEFRAME_INFO,
13885 NULL);
13886 if (text)
13887 return parse_traceframe_info (text->data ());
13888
13889 return NULL;
13890 }
13891
13892 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13893 instruction on which a fast tracepoint may be placed. Returns -1
13894 if the packet is not supported, and 0 if the minimum instruction
13895 length is unknown. */
13896
13897 int
13898 remote_target::get_min_fast_tracepoint_insn_len ()
13899 {
13900 struct remote_state *rs = get_remote_state ();
13901 char *reply;
13902
13903 /* If we're not debugging a process yet, the IPA can't be
13904 loaded. */
13905 if (!target_has_execution ())
13906 return 0;
13907
13908 /* Make sure the remote is pointing at the right process. */
13909 set_general_process ();
13910
13911 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
13912 putpkt (rs->buf);
13913 reply = remote_get_noisy_reply ();
13914 if (*reply == '\0')
13915 return -1;
13916 else
13917 {
13918 ULONGEST min_insn_len;
13919
13920 unpack_varlen_hex (reply, &min_insn_len);
13921
13922 return (int) min_insn_len;
13923 }
13924 }
13925
13926 void
13927 remote_target::set_trace_buffer_size (LONGEST val)
13928 {
13929 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13930 {
13931 struct remote_state *rs = get_remote_state ();
13932 char *buf = rs->buf.data ();
13933 char *endbuf = buf + get_remote_packet_size ();
13934 enum packet_result result;
13935
13936 gdb_assert (val >= 0 || val == -1);
13937 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13938 /* Send -1 as literal "-1" to avoid host size dependency. */
13939 if (val < 0)
13940 {
13941 *buf++ = '-';
13942 buf += hexnumstr (buf, (ULONGEST) -val);
13943 }
13944 else
13945 buf += hexnumstr (buf, (ULONGEST) val);
13946
13947 putpkt (rs->buf);
13948 remote_get_noisy_reply ();
13949 result = packet_ok (rs->buf,
13950 &remote_protocol_packets[PACKET_QTBuffer_size]);
13951
13952 if (result != PACKET_OK)
13953 warning (_("Bogus reply from target: %s"), rs->buf.data ());
13954 }
13955 }
13956
13957 bool
13958 remote_target::set_trace_notes (const char *user, const char *notes,
13959 const char *stop_notes)
13960 {
13961 struct remote_state *rs = get_remote_state ();
13962 char *reply;
13963 char *buf = rs->buf.data ();
13964 char *endbuf = buf + get_remote_packet_size ();
13965 int nbytes;
13966
13967 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13968 if (user)
13969 {
13970 buf += xsnprintf (buf, endbuf - buf, "user:");
13971 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13972 buf += 2 * nbytes;
13973 *buf++ = ';';
13974 }
13975 if (notes)
13976 {
13977 buf += xsnprintf (buf, endbuf - buf, "notes:");
13978 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13979 buf += 2 * nbytes;
13980 *buf++ = ';';
13981 }
13982 if (stop_notes)
13983 {
13984 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13985 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13986 buf += 2 * nbytes;
13987 *buf++ = ';';
13988 }
13989 /* Ensure the buffer is terminated. */
13990 *buf = '\0';
13991
13992 putpkt (rs->buf);
13993 reply = remote_get_noisy_reply ();
13994 if (*reply == '\0')
13995 return false;
13996
13997 if (strcmp (reply, "OK") != 0)
13998 error (_("Bogus reply from target: %s"), reply);
13999
14000 return true;
14001 }
14002
14003 bool
14004 remote_target::use_agent (bool use)
14005 {
14006 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
14007 {
14008 struct remote_state *rs = get_remote_state ();
14009
14010 /* If the stub supports QAgent. */
14011 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
14012 putpkt (rs->buf);
14013 getpkt (&rs->buf, 0);
14014
14015 if (strcmp (rs->buf.data (), "OK") == 0)
14016 {
14017 ::use_agent = use;
14018 return true;
14019 }
14020 }
14021
14022 return false;
14023 }
14024
14025 bool
14026 remote_target::can_use_agent ()
14027 {
14028 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
14029 }
14030
14031 struct btrace_target_info
14032 {
14033 /* The ptid of the traced thread. */
14034 ptid_t ptid;
14035
14036 /* The obtained branch trace configuration. */
14037 struct btrace_config conf;
14038 };
14039
14040 /* Reset our idea of our target's btrace configuration. */
14041
14042 static void
14043 remote_btrace_reset (remote_state *rs)
14044 {
14045 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14046 }
14047
14048 /* Synchronize the configuration with the target. */
14049
14050 void
14051 remote_target::btrace_sync_conf (const btrace_config *conf)
14052 {
14053 struct packet_config *packet;
14054 struct remote_state *rs;
14055 char *buf, *pos, *endbuf;
14056
14057 rs = get_remote_state ();
14058 buf = rs->buf.data ();
14059 endbuf = buf + get_remote_packet_size ();
14060
14061 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
14062 if (packet_config_support (packet) == PACKET_ENABLE
14063 && conf->bts.size != rs->btrace_config.bts.size)
14064 {
14065 pos = buf;
14066 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
14067 conf->bts.size);
14068
14069 putpkt (buf);
14070 getpkt (&rs->buf, 0);
14071
14072 if (packet_ok (buf, packet) == PACKET_ERROR)
14073 {
14074 if (buf[0] == 'E' && buf[1] == '.')
14075 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14076 else
14077 error (_("Failed to configure the BTS buffer size."));
14078 }
14079
14080 rs->btrace_config.bts.size = conf->bts.size;
14081 }
14082
14083 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
14084 if (packet_config_support (packet) == PACKET_ENABLE
14085 && conf->pt.size != rs->btrace_config.pt.size)
14086 {
14087 pos = buf;
14088 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
14089 conf->pt.size);
14090
14091 putpkt (buf);
14092 getpkt (&rs->buf, 0);
14093
14094 if (packet_ok (buf, packet) == PACKET_ERROR)
14095 {
14096 if (buf[0] == 'E' && buf[1] == '.')
14097 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14098 else
14099 error (_("Failed to configure the trace buffer size."));
14100 }
14101
14102 rs->btrace_config.pt.size = conf->pt.size;
14103 }
14104 }
14105
14106 /* Read the current thread's btrace configuration from the target and
14107 store it into CONF. */
14108
14109 static void
14110 btrace_read_config (struct btrace_config *conf)
14111 {
14112 gdb::optional<gdb::char_vector> xml
14113 = target_read_stralloc (current_inferior ()->top_target (),
14114 TARGET_OBJECT_BTRACE_CONF, "");
14115 if (xml)
14116 parse_xml_btrace_conf (conf, xml->data ());
14117 }
14118
14119 /* Maybe reopen target btrace. */
14120
14121 void
14122 remote_target::remote_btrace_maybe_reopen ()
14123 {
14124 struct remote_state *rs = get_remote_state ();
14125 int btrace_target_pushed = 0;
14126 #if !defined (HAVE_LIBIPT)
14127 int warned = 0;
14128 #endif
14129
14130 /* Don't bother walking the entirety of the remote thread list when
14131 we know the feature isn't supported by the remote. */
14132 if (packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14133 return;
14134
14135 scoped_restore_current_thread restore_thread;
14136
14137 for (thread_info *tp : all_non_exited_threads (this))
14138 {
14139 set_general_thread (tp->ptid);
14140
14141 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14142 btrace_read_config (&rs->btrace_config);
14143
14144 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14145 continue;
14146
14147 #if !defined (HAVE_LIBIPT)
14148 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14149 {
14150 if (!warned)
14151 {
14152 warned = 1;
14153 warning (_("Target is recording using Intel Processor Trace "
14154 "but support was disabled at compile time."));
14155 }
14156
14157 continue;
14158 }
14159 #endif /* !defined (HAVE_LIBIPT) */
14160
14161 /* Push target, once, but before anything else happens. This way our
14162 changes to the threads will be cleaned up by unpushing the target
14163 in case btrace_read_config () throws. */
14164 if (!btrace_target_pushed)
14165 {
14166 btrace_target_pushed = 1;
14167 record_btrace_push_target ();
14168 printf_filtered (_("Target is recording using %s.\n"),
14169 btrace_format_string (rs->btrace_config.format));
14170 }
14171
14172 tp->btrace.target = XCNEW (struct btrace_target_info);
14173 tp->btrace.target->ptid = tp->ptid;
14174 tp->btrace.target->conf = rs->btrace_config;
14175 }
14176 }
14177
14178 /* Enable branch tracing. */
14179
14180 struct btrace_target_info *
14181 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
14182 {
14183 struct btrace_target_info *tinfo = NULL;
14184 struct packet_config *packet = NULL;
14185 struct remote_state *rs = get_remote_state ();
14186 char *buf = rs->buf.data ();
14187 char *endbuf = buf + get_remote_packet_size ();
14188
14189 switch (conf->format)
14190 {
14191 case BTRACE_FORMAT_BTS:
14192 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
14193 break;
14194
14195 case BTRACE_FORMAT_PT:
14196 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
14197 break;
14198 }
14199
14200 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14201 error (_("Target does not support branch tracing."));
14202
14203 btrace_sync_conf (conf);
14204
14205 set_general_thread (ptid);
14206
14207 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14208 putpkt (rs->buf);
14209 getpkt (&rs->buf, 0);
14210
14211 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14212 {
14213 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14214 error (_("Could not enable branch tracing for %s: %s"),
14215 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14216 else
14217 error (_("Could not enable branch tracing for %s."),
14218 target_pid_to_str (ptid).c_str ());
14219 }
14220
14221 tinfo = XCNEW (struct btrace_target_info);
14222 tinfo->ptid = ptid;
14223
14224 /* If we fail to read the configuration, we lose some information, but the
14225 tracing itself is not impacted. */
14226 try
14227 {
14228 btrace_read_config (&tinfo->conf);
14229 }
14230 catch (const gdb_exception_error &err)
14231 {
14232 if (err.message != NULL)
14233 warning ("%s", err.what ());
14234 }
14235
14236 return tinfo;
14237 }
14238
14239 /* Disable branch tracing. */
14240
14241 void
14242 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14243 {
14244 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
14245 struct remote_state *rs = get_remote_state ();
14246 char *buf = rs->buf.data ();
14247 char *endbuf = buf + get_remote_packet_size ();
14248
14249 if (packet_config_support (packet) != PACKET_ENABLE)
14250 error (_("Target does not support branch tracing."));
14251
14252 set_general_thread (tinfo->ptid);
14253
14254 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14255 putpkt (rs->buf);
14256 getpkt (&rs->buf, 0);
14257
14258 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14259 {
14260 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14261 error (_("Could not disable branch tracing for %s: %s"),
14262 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14263 else
14264 error (_("Could not disable branch tracing for %s."),
14265 target_pid_to_str (tinfo->ptid).c_str ());
14266 }
14267
14268 xfree (tinfo);
14269 }
14270
14271 /* Teardown branch tracing. */
14272
14273 void
14274 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14275 {
14276 /* We must not talk to the target during teardown. */
14277 xfree (tinfo);
14278 }
14279
14280 /* Read the branch trace. */
14281
14282 enum btrace_error
14283 remote_target::read_btrace (struct btrace_data *btrace,
14284 struct btrace_target_info *tinfo,
14285 enum btrace_read_type type)
14286 {
14287 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
14288 const char *annex;
14289
14290 if (packet_config_support (packet) != PACKET_ENABLE)
14291 error (_("Target does not support branch tracing."));
14292
14293 #if !defined(HAVE_LIBEXPAT)
14294 error (_("Cannot process branch tracing result. XML parsing not supported."));
14295 #endif
14296
14297 switch (type)
14298 {
14299 case BTRACE_READ_ALL:
14300 annex = "all";
14301 break;
14302 case BTRACE_READ_NEW:
14303 annex = "new";
14304 break;
14305 case BTRACE_READ_DELTA:
14306 annex = "delta";
14307 break;
14308 default:
14309 internal_error (__FILE__, __LINE__,
14310 _("Bad branch tracing read type: %u."),
14311 (unsigned int) type);
14312 }
14313
14314 gdb::optional<gdb::char_vector> xml
14315 = target_read_stralloc (current_inferior ()->top_target (),
14316 TARGET_OBJECT_BTRACE, annex);
14317 if (!xml)
14318 return BTRACE_ERR_UNKNOWN;
14319
14320 parse_xml_btrace (btrace, xml->data ());
14321
14322 return BTRACE_ERR_NONE;
14323 }
14324
14325 const struct btrace_config *
14326 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14327 {
14328 return &tinfo->conf;
14329 }
14330
14331 bool
14332 remote_target::augmented_libraries_svr4_read ()
14333 {
14334 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
14335 == PACKET_ENABLE);
14336 }
14337
14338 /* Implementation of to_load. */
14339
14340 void
14341 remote_target::load (const char *name, int from_tty)
14342 {
14343 generic_load (name, from_tty);
14344 }
14345
14346 /* Accepts an integer PID; returns a string representing a file that
14347 can be opened on the remote side to get the symbols for the child
14348 process. Returns NULL if the operation is not supported. */
14349
14350 char *
14351 remote_target::pid_to_exec_file (int pid)
14352 {
14353 static gdb::optional<gdb::char_vector> filename;
14354 char *annex = NULL;
14355
14356 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14357 return NULL;
14358
14359 inferior *inf = find_inferior_pid (this, pid);
14360 if (inf == NULL)
14361 internal_error (__FILE__, __LINE__,
14362 _("not currently attached to process %d"), pid);
14363
14364 if (!inf->fake_pid_p)
14365 {
14366 const int annex_size = 9;
14367
14368 annex = (char *) alloca (annex_size);
14369 xsnprintf (annex, annex_size, "%x", pid);
14370 }
14371
14372 filename = target_read_stralloc (current_inferior ()->top_target (),
14373 TARGET_OBJECT_EXEC_FILE, annex);
14374
14375 return filename ? filename->data () : nullptr;
14376 }
14377
14378 /* Implement the to_can_do_single_step target_ops method. */
14379
14380 int
14381 remote_target::can_do_single_step ()
14382 {
14383 /* We can only tell whether target supports single step or not by
14384 supported s and S vCont actions if the stub supports vContSupported
14385 feature. If the stub doesn't support vContSupported feature,
14386 we have conservatively to think target doesn't supports single
14387 step. */
14388 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14389 {
14390 struct remote_state *rs = get_remote_state ();
14391
14392 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14393 remote_vcont_probe ();
14394
14395 return rs->supports_vCont.s && rs->supports_vCont.S;
14396 }
14397 else
14398 return 0;
14399 }
14400
14401 /* Implementation of the to_execution_direction method for the remote
14402 target. */
14403
14404 enum exec_direction_kind
14405 remote_target::execution_direction ()
14406 {
14407 struct remote_state *rs = get_remote_state ();
14408
14409 return rs->last_resume_exec_dir;
14410 }
14411
14412 /* Return pointer to the thread_info struct which corresponds to
14413 THREAD_HANDLE (having length HANDLE_LEN). */
14414
14415 thread_info *
14416 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14417 int handle_len,
14418 inferior *inf)
14419 {
14420 for (thread_info *tp : all_non_exited_threads (this))
14421 {
14422 remote_thread_info *priv = get_remote_thread_info (tp);
14423
14424 if (tp->inf == inf && priv != NULL)
14425 {
14426 if (handle_len != priv->thread_handle.size ())
14427 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14428 handle_len, priv->thread_handle.size ());
14429 if (memcmp (thread_handle, priv->thread_handle.data (),
14430 handle_len) == 0)
14431 return tp;
14432 }
14433 }
14434
14435 return NULL;
14436 }
14437
14438 gdb::byte_vector
14439 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14440 {
14441 remote_thread_info *priv = get_remote_thread_info (tp);
14442 return priv->thread_handle;
14443 }
14444
14445 bool
14446 remote_target::can_async_p ()
14447 {
14448 /* This flag should be checked in the common target.c code. */
14449 gdb_assert (target_async_permitted);
14450
14451 /* We're async whenever the serial device can. */
14452 struct remote_state *rs = get_remote_state ();
14453 return serial_can_async_p (rs->remote_desc);
14454 }
14455
14456 bool
14457 remote_target::is_async_p ()
14458 {
14459 /* We're async whenever the serial device is. */
14460 struct remote_state *rs = get_remote_state ();
14461 return serial_is_async_p (rs->remote_desc);
14462 }
14463
14464 /* Pass the SERIAL event on and up to the client. One day this code
14465 will be able to delay notifying the client of an event until the
14466 point where an entire packet has been received. */
14467
14468 static serial_event_ftype remote_async_serial_handler;
14469
14470 static void
14471 remote_async_serial_handler (struct serial *scb, void *context)
14472 {
14473 /* Don't propogate error information up to the client. Instead let
14474 the client find out about the error by querying the target. */
14475 inferior_event_handler (INF_REG_EVENT);
14476 }
14477
14478 static void
14479 remote_async_inferior_event_handler (gdb_client_data data)
14480 {
14481 inferior_event_handler (INF_REG_EVENT);
14482 }
14483
14484 int
14485 remote_target::async_wait_fd ()
14486 {
14487 struct remote_state *rs = get_remote_state ();
14488 return rs->remote_desc->fd;
14489 }
14490
14491 void
14492 remote_target::async (int enable)
14493 {
14494 struct remote_state *rs = get_remote_state ();
14495
14496 if (enable)
14497 {
14498 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14499
14500 /* If there are pending events in the stop reply queue tell the
14501 event loop to process them. */
14502 if (!rs->stop_reply_queue.empty ())
14503 mark_async_event_handler (rs->remote_async_inferior_event_token);
14504 /* For simplicity, below we clear the pending events token
14505 without remembering whether it is marked, so here we always
14506 mark it. If there's actually no pending notification to
14507 process, this ends up being a no-op (other than a spurious
14508 event-loop wakeup). */
14509 if (target_is_non_stop_p ())
14510 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14511 }
14512 else
14513 {
14514 serial_async (rs->remote_desc, NULL, NULL);
14515 /* If the core is disabling async, it doesn't want to be
14516 disturbed with target events. Clear all async event sources
14517 too. */
14518 clear_async_event_handler (rs->remote_async_inferior_event_token);
14519 if (target_is_non_stop_p ())
14520 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14521 }
14522 }
14523
14524 /* Implementation of the to_thread_events method. */
14525
14526 void
14527 remote_target::thread_events (int enable)
14528 {
14529 struct remote_state *rs = get_remote_state ();
14530 size_t size = get_remote_packet_size ();
14531
14532 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14533 return;
14534
14535 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
14536 putpkt (rs->buf);
14537 getpkt (&rs->buf, 0);
14538
14539 switch (packet_ok (rs->buf,
14540 &remote_protocol_packets[PACKET_QThreadEvents]))
14541 {
14542 case PACKET_OK:
14543 if (strcmp (rs->buf.data (), "OK") != 0)
14544 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
14545 break;
14546 case PACKET_ERROR:
14547 warning (_("Remote failure reply: %s"), rs->buf.data ());
14548 break;
14549 case PACKET_UNKNOWN:
14550 break;
14551 }
14552 }
14553
14554 static void
14555 show_remote_cmd (const char *args, int from_tty)
14556 {
14557 /* We can't just use cmd_show_list here, because we want to skip
14558 the redundant "show remote Z-packet" and the legacy aliases. */
14559 struct cmd_list_element *list = remote_show_cmdlist;
14560 struct ui_out *uiout = current_uiout;
14561
14562 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14563 for (; list != NULL; list = list->next)
14564 if (strcmp (list->name, "Z-packet") == 0)
14565 continue;
14566 else if (list->type == not_set_cmd)
14567 /* Alias commands are exactly like the original, except they
14568 don't have the normal type. */
14569 continue;
14570 else
14571 {
14572 ui_out_emit_tuple option_emitter (uiout, "option");
14573
14574 uiout->field_string ("name", list->name);
14575 uiout->text (": ");
14576 if (list->type == show_cmd)
14577 do_show_command (NULL, from_tty, list);
14578 else
14579 cmd_func (list, NULL, from_tty);
14580 }
14581 }
14582
14583
14584 /* Function to be called whenever a new objfile (shlib) is detected. */
14585 static void
14586 remote_new_objfile (struct objfile *objfile)
14587 {
14588 remote_target *remote = get_current_remote_target ();
14589
14590 /* First, check whether the current inferior's process target is a remote
14591 target. */
14592 if (remote == nullptr)
14593 return;
14594
14595 /* When we are attaching or handling a fork child and the shared library
14596 subsystem reads the list of loaded libraries, we receive new objfile
14597 events in between each found library. The libraries are read in an
14598 undefined order, so if we gave the remote side a chance to look up
14599 symbols between each objfile, we might give it an inconsistent picture
14600 of the inferior. It could appear that a library A appears loaded but
14601 a library B does not, even though library A requires library B. That
14602 would present a state that couldn't normally exist in the inferior.
14603
14604 So, skip these events, we'll give the remote a chance to look up symbols
14605 once all the loaded libraries and their symbols are known to GDB. */
14606 if (current_inferior ()->in_initial_library_scan)
14607 return;
14608
14609 remote->remote_check_symbols ();
14610 }
14611
14612 /* Pull all the tracepoints defined on the target and create local
14613 data structures representing them. We don't want to create real
14614 tracepoints yet, we don't want to mess up the user's existing
14615 collection. */
14616
14617 int
14618 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14619 {
14620 struct remote_state *rs = get_remote_state ();
14621 char *p;
14622
14623 /* Ask for a first packet of tracepoint definition. */
14624 putpkt ("qTfP");
14625 getpkt (&rs->buf, 0);
14626 p = rs->buf.data ();
14627 while (*p && *p != 'l')
14628 {
14629 parse_tracepoint_definition (p, utpp);
14630 /* Ask for another packet of tracepoint definition. */
14631 putpkt ("qTsP");
14632 getpkt (&rs->buf, 0);
14633 p = rs->buf.data ();
14634 }
14635 return 0;
14636 }
14637
14638 int
14639 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14640 {
14641 struct remote_state *rs = get_remote_state ();
14642 char *p;
14643
14644 /* Ask for a first packet of variable definition. */
14645 putpkt ("qTfV");
14646 getpkt (&rs->buf, 0);
14647 p = rs->buf.data ();
14648 while (*p && *p != 'l')
14649 {
14650 parse_tsv_definition (p, utsvp);
14651 /* Ask for another packet of variable definition. */
14652 putpkt ("qTsV");
14653 getpkt (&rs->buf, 0);
14654 p = rs->buf.data ();
14655 }
14656 return 0;
14657 }
14658
14659 /* The "set/show range-stepping" show hook. */
14660
14661 static void
14662 show_range_stepping (struct ui_file *file, int from_tty,
14663 struct cmd_list_element *c,
14664 const char *value)
14665 {
14666 fprintf_filtered (file,
14667 _("Debugger's willingness to use range stepping "
14668 "is %s.\n"), value);
14669 }
14670
14671 /* Return true if the vCont;r action is supported by the remote
14672 stub. */
14673
14674 bool
14675 remote_target::vcont_r_supported ()
14676 {
14677 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14678 remote_vcont_probe ();
14679
14680 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14681 && get_remote_state ()->supports_vCont.r);
14682 }
14683
14684 /* The "set/show range-stepping" set hook. */
14685
14686 static void
14687 set_range_stepping (const char *ignore_args, int from_tty,
14688 struct cmd_list_element *c)
14689 {
14690 /* When enabling, check whether range stepping is actually supported
14691 by the target, and warn if not. */
14692 if (use_range_stepping)
14693 {
14694 remote_target *remote = get_current_remote_target ();
14695 if (remote == NULL
14696 || !remote->vcont_r_supported ())
14697 warning (_("Range stepping is not supported by the current target"));
14698 }
14699 }
14700
14701 static void
14702 show_remote_debug (struct ui_file *file, int from_tty,
14703 struct cmd_list_element *c, const char *value)
14704 {
14705 fprintf_filtered (file, _("Debugging of remote protocol is %s.\n"),
14706 value);
14707 }
14708
14709 static void
14710 show_remote_timeout (struct ui_file *file, int from_tty,
14711 struct cmd_list_element *c, const char *value)
14712 {
14713 fprintf_filtered (file,
14714 _("Timeout limit to wait for target to respond is %s.\n"),
14715 value);
14716 }
14717
14718 /* Implement the "supports_memory_tagging" target_ops method. */
14719
14720 bool
14721 remote_target::supports_memory_tagging ()
14722 {
14723 return remote_memory_tagging_p ();
14724 }
14725
14726 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
14727
14728 static void
14729 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14730 size_t len, int type)
14731 {
14732 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14733
14734 std::string request = string_printf ("qMemTags:%s,%s:%s",
14735 phex_nz (address, addr_size),
14736 phex_nz (len, sizeof (len)),
14737 phex_nz (type, sizeof (type)));
14738
14739 strcpy (packet.data (), request.c_str ());
14740 }
14741
14742 /* Parse the qMemTags packet reply into TAGS.
14743
14744 Return true if successful, false otherwise. */
14745
14746 static bool
14747 parse_fetch_memtags_reply (const gdb::char_vector &reply,
14748 gdb::byte_vector &tags)
14749 {
14750 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
14751 return false;
14752
14753 /* Copy the tag data. */
14754 tags = hex2bin (reply.data () + 1);
14755
14756 return true;
14757 }
14758
14759 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
14760
14761 static void
14762 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14763 size_t len, int type,
14764 const gdb::byte_vector &tags)
14765 {
14766 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14767
14768 /* Put together the main packet, address and length. */
14769 std::string request = string_printf ("QMemTags:%s,%s:%s:",
14770 phex_nz (address, addr_size),
14771 phex_nz (len, sizeof (len)),
14772 phex_nz (type, sizeof (type)));
14773 request += bin2hex (tags.data (), tags.size ());
14774
14775 /* Check if we have exceeded the maximum packet size. */
14776 if (packet.size () < request.length ())
14777 error (_("Contents too big for packet QMemTags."));
14778
14779 strcpy (packet.data (), request.c_str ());
14780 }
14781
14782 /* Implement the "fetch_memtags" target_ops method. */
14783
14784 bool
14785 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
14786 gdb::byte_vector &tags, int type)
14787 {
14788 /* Make sure the qMemTags packet is supported. */
14789 if (!remote_memory_tagging_p ())
14790 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
14791
14792 struct remote_state *rs = get_remote_state ();
14793
14794 create_fetch_memtags_request (rs->buf, address, len, type);
14795
14796 putpkt (rs->buf);
14797 getpkt (&rs->buf, 0);
14798
14799 return parse_fetch_memtags_reply (rs->buf, tags);
14800 }
14801
14802 /* Implement the "store_memtags" target_ops method. */
14803
14804 bool
14805 remote_target::store_memtags (CORE_ADDR address, size_t len,
14806 const gdb::byte_vector &tags, int type)
14807 {
14808 /* Make sure the QMemTags packet is supported. */
14809 if (!remote_memory_tagging_p ())
14810 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
14811
14812 struct remote_state *rs = get_remote_state ();
14813
14814 create_store_memtags_request (rs->buf, address, len, type, tags);
14815
14816 putpkt (rs->buf);
14817 getpkt (&rs->buf, 0);
14818
14819 /* Verify if the request was successful. */
14820 return packet_check_result (rs->buf.data ()) == PACKET_OK;
14821 }
14822
14823 /* Return true if remote target T is non-stop. */
14824
14825 bool
14826 remote_target_is_non_stop_p (remote_target *t)
14827 {
14828 scoped_restore_current_thread restore_thread;
14829 switch_to_target_no_thread (t);
14830
14831 return target_is_non_stop_p ();
14832 }
14833
14834 #if GDB_SELF_TEST
14835
14836 namespace selftests {
14837
14838 static void
14839 test_memory_tagging_functions ()
14840 {
14841 remote_target remote;
14842
14843 struct packet_config *config
14844 = &remote_protocol_packets[PACKET_memory_tagging_feature];
14845
14846 scoped_restore restore_memtag_support_
14847 = make_scoped_restore (&config->support);
14848
14849 /* Test memory tagging packet support. */
14850 config->support = PACKET_SUPPORT_UNKNOWN;
14851 SELF_CHECK (remote.supports_memory_tagging () == false);
14852 config->support = PACKET_DISABLE;
14853 SELF_CHECK (remote.supports_memory_tagging () == false);
14854 config->support = PACKET_ENABLE;
14855 SELF_CHECK (remote.supports_memory_tagging () == true);
14856
14857 /* Setup testing. */
14858 gdb::char_vector packet;
14859 gdb::byte_vector tags, bv;
14860 std::string expected, reply;
14861 packet.resize (32000);
14862
14863 /* Test creating a qMemTags request. */
14864
14865 expected = "qMemTags:0,0:0";
14866 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
14867 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14868
14869 expected = "qMemTags:deadbeef,10:1";
14870 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
14871 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14872
14873 /* Test parsing a qMemTags reply. */
14874
14875 /* Error reply, tags vector unmodified. */
14876 reply = "E00";
14877 strcpy (packet.data (), reply.c_str ());
14878 tags.resize (0);
14879 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
14880 SELF_CHECK (tags.size () == 0);
14881
14882 /* Valid reply, tags vector updated. */
14883 tags.resize (0);
14884 bv.resize (0);
14885
14886 for (int i = 0; i < 5; i++)
14887 bv.push_back (i);
14888
14889 reply = "m" + bin2hex (bv.data (), bv.size ());
14890 strcpy (packet.data (), reply.c_str ());
14891
14892 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
14893 SELF_CHECK (tags.size () == 5);
14894
14895 for (int i = 0; i < 5; i++)
14896 SELF_CHECK (tags[i] == i);
14897
14898 /* Test creating a QMemTags request. */
14899
14900 /* Empty tag data. */
14901 tags.resize (0);
14902 expected = "QMemTags:0,0:0:";
14903 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
14904 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14905 expected.length ()) == 0);
14906
14907 /* Non-empty tag data. */
14908 tags.resize (0);
14909 for (int i = 0; i < 5; i++)
14910 tags.push_back (i);
14911 expected = "QMemTags:deadbeef,ff:1:0001020304";
14912 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
14913 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14914 expected.length ()) == 0);
14915 }
14916
14917 } // namespace selftests
14918 #endif /* GDB_SELF_TEST */
14919
14920 void _initialize_remote ();
14921 void
14922 _initialize_remote ()
14923 {
14924 /* architecture specific data */
14925 remote_g_packet_data_handle =
14926 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14927
14928 add_target (remote_target_info, remote_target::open);
14929 add_target (extended_remote_target_info, extended_remote_target::open);
14930
14931 /* Hook into new objfile notification. */
14932 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
14933
14934 #if 0
14935 init_remote_threadtests ();
14936 #endif
14937
14938 /* set/show remote ... */
14939
14940 add_basic_prefix_cmd ("remote", class_maintenance, _("\
14941 Remote protocol specific variables.\n\
14942 Configure various remote-protocol specific variables such as\n\
14943 the packets being used."),
14944 &remote_set_cmdlist,
14945 0 /* allow-unknown */, &setlist);
14946 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14947 Remote protocol specific variables.\n\
14948 Configure various remote-protocol specific variables such as\n\
14949 the packets being used."),
14950 &remote_show_cmdlist,
14951 0 /* allow-unknown */, &showlist);
14952
14953 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14954 Compare section data on target to the exec file.\n\
14955 Argument is a single section name (default: all loaded sections).\n\
14956 To compare only read-only loaded sections, specify the -r option."),
14957 &cmdlist);
14958
14959 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
14960 Send an arbitrary packet to a remote target.\n\
14961 maintenance packet TEXT\n\
14962 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14963 this command sends the string TEXT to the inferior, and displays the\n\
14964 response packet. GDB supplies the initial `$' character, and the\n\
14965 terminating `#' character and checksum."),
14966 &maintenancelist);
14967
14968 set_show_commands remotebreak_cmds
14969 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14970 Set whether to send break if interrupted."), _("\
14971 Show whether to send break if interrupted."), _("\
14972 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14973 set_remotebreak, show_remotebreak,
14974 &setlist, &showlist);
14975 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
14976 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
14977
14978 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14979 interrupt_sequence_modes, &interrupt_sequence_mode,
14980 _("\
14981 Set interrupt sequence to remote target."), _("\
14982 Show interrupt sequence to remote target."), _("\
14983 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14984 NULL, show_interrupt_sequence,
14985 &remote_set_cmdlist,
14986 &remote_show_cmdlist);
14987
14988 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14989 &interrupt_on_connect, _("\
14990 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
14991 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
14992 If set, interrupt sequence is sent to remote target."),
14993 NULL, NULL,
14994 &remote_set_cmdlist, &remote_show_cmdlist);
14995
14996 /* Install commands for configuring memory read/write packets. */
14997
14998 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14999 Set the maximum number of bytes per memory write packet (deprecated)."),
15000 &setlist);
15001 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
15002 Show the maximum number of bytes per memory write packet (deprecated)."),
15003 &showlist);
15004 add_cmd ("memory-write-packet-size", no_class,
15005 set_memory_write_packet_size, _("\
15006 Set the maximum number of bytes per memory-write packet.\n\
15007 Specify the number of bytes in a packet or 0 (zero) for the\n\
15008 default packet size. The actual limit is further reduced\n\
15009 dependent on the target. Specify ``fixed'' to disable the\n\
15010 further restriction and ``limit'' to enable that restriction."),
15011 &remote_set_cmdlist);
15012 add_cmd ("memory-read-packet-size", no_class,
15013 set_memory_read_packet_size, _("\
15014 Set the maximum number of bytes per memory-read packet.\n\
15015 Specify the number of bytes in a packet or 0 (zero) for the\n\
15016 default packet size. The actual limit is further reduced\n\
15017 dependent on the target. Specify ``fixed'' to disable the\n\
15018 further restriction and ``limit'' to enable that restriction."),
15019 &remote_set_cmdlist);
15020 add_cmd ("memory-write-packet-size", no_class,
15021 show_memory_write_packet_size,
15022 _("Show the maximum number of bytes per memory-write packet."),
15023 &remote_show_cmdlist);
15024 add_cmd ("memory-read-packet-size", no_class,
15025 show_memory_read_packet_size,
15026 _("Show the maximum number of bytes per memory-read packet."),
15027 &remote_show_cmdlist);
15028
15029 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
15030 &remote_hw_watchpoint_limit, _("\
15031 Set the maximum number of target hardware watchpoints."), _("\
15032 Show the maximum number of target hardware watchpoints."), _("\
15033 Specify \"unlimited\" for unlimited hardware watchpoints."),
15034 NULL, show_hardware_watchpoint_limit,
15035 &remote_set_cmdlist,
15036 &remote_show_cmdlist);
15037 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15038 no_class,
15039 &remote_hw_watchpoint_length_limit, _("\
15040 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15041 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15042 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15043 NULL, show_hardware_watchpoint_length_limit,
15044 &remote_set_cmdlist, &remote_show_cmdlist);
15045 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
15046 &remote_hw_breakpoint_limit, _("\
15047 Set the maximum number of target hardware breakpoints."), _("\
15048 Show the maximum number of target hardware breakpoints."), _("\
15049 Specify \"unlimited\" for unlimited hardware breakpoints."),
15050 NULL, show_hardware_breakpoint_limit,
15051 &remote_set_cmdlist, &remote_show_cmdlist);
15052
15053 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15054 &remote_address_size, _("\
15055 Set the maximum size of the address (in bits) in a memory packet."), _("\
15056 Show the maximum size of the address (in bits) in a memory packet."), NULL,
15057 NULL,
15058 NULL, /* FIXME: i18n: */
15059 &setlist, &showlist);
15060
15061 init_all_packet_configs ();
15062
15063 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
15064 "X", "binary-download", 1);
15065
15066 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
15067 "vCont", "verbose-resume", 0);
15068
15069 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
15070 "QPassSignals", "pass-signals", 0);
15071
15072 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
15073 "QCatchSyscalls", "catch-syscalls", 0);
15074
15075 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
15076 "QProgramSignals", "program-signals", 0);
15077
15078 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
15079 "QSetWorkingDir", "set-working-dir", 0);
15080
15081 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
15082 "QStartupWithShell", "startup-with-shell", 0);
15083
15084 add_packet_config_cmd (&remote_protocol_packets
15085 [PACKET_QEnvironmentHexEncoded],
15086 "QEnvironmentHexEncoded", "environment-hex-encoded",
15087 0);
15088
15089 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
15090 "QEnvironmentReset", "environment-reset",
15091 0);
15092
15093 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
15094 "QEnvironmentUnset", "environment-unset",
15095 0);
15096
15097 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
15098 "qSymbol", "symbol-lookup", 0);
15099
15100 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
15101 "P", "set-register", 1);
15102
15103 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
15104 "p", "fetch-register", 1);
15105
15106 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
15107 "Z0", "software-breakpoint", 0);
15108
15109 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
15110 "Z1", "hardware-breakpoint", 0);
15111
15112 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
15113 "Z2", "write-watchpoint", 0);
15114
15115 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
15116 "Z3", "read-watchpoint", 0);
15117
15118 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
15119 "Z4", "access-watchpoint", 0);
15120
15121 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
15122 "qXfer:auxv:read", "read-aux-vector", 0);
15123
15124 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
15125 "qXfer:exec-file:read", "pid-to-exec-file", 0);
15126
15127 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
15128 "qXfer:features:read", "target-features", 0);
15129
15130 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
15131 "qXfer:libraries:read", "library-info", 0);
15132
15133 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
15134 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15135
15136 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
15137 "qXfer:memory-map:read", "memory-map", 0);
15138
15139 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
15140 "qXfer:osdata:read", "osdata", 0);
15141
15142 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
15143 "qXfer:threads:read", "threads", 0);
15144
15145 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
15146 "qXfer:siginfo:read", "read-siginfo-object", 0);
15147
15148 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
15149 "qXfer:siginfo:write", "write-siginfo-object", 0);
15150
15151 add_packet_config_cmd
15152 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
15153 "qXfer:traceframe-info:read", "traceframe-info", 0);
15154
15155 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
15156 "qXfer:uib:read", "unwind-info-block", 0);
15157
15158 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
15159 "qGetTLSAddr", "get-thread-local-storage-address",
15160 0);
15161
15162 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
15163 "qGetTIBAddr", "get-thread-information-block-address",
15164 0);
15165
15166 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
15167 "bc", "reverse-continue", 0);
15168
15169 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
15170 "bs", "reverse-step", 0);
15171
15172 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
15173 "qSupported", "supported-packets", 0);
15174
15175 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
15176 "qSearch:memory", "search-memory", 0);
15177
15178 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
15179 "qTStatus", "trace-status", 0);
15180
15181 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
15182 "vFile:setfs", "hostio-setfs", 0);
15183
15184 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
15185 "vFile:open", "hostio-open", 0);
15186
15187 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
15188 "vFile:pread", "hostio-pread", 0);
15189
15190 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
15191 "vFile:pwrite", "hostio-pwrite", 0);
15192
15193 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
15194 "vFile:close", "hostio-close", 0);
15195
15196 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
15197 "vFile:unlink", "hostio-unlink", 0);
15198
15199 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
15200 "vFile:readlink", "hostio-readlink", 0);
15201
15202 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
15203 "vFile:fstat", "hostio-fstat", 0);
15204
15205 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
15206 "vAttach", "attach", 0);
15207
15208 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
15209 "vRun", "run", 0);
15210
15211 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
15212 "QStartNoAckMode", "noack", 0);
15213
15214 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
15215 "vKill", "kill", 0);
15216
15217 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
15218 "qAttached", "query-attached", 0);
15219
15220 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
15221 "ConditionalTracepoints",
15222 "conditional-tracepoints", 0);
15223
15224 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
15225 "ConditionalBreakpoints",
15226 "conditional-breakpoints", 0);
15227
15228 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
15229 "BreakpointCommands",
15230 "breakpoint-commands", 0);
15231
15232 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
15233 "FastTracepoints", "fast-tracepoints", 0);
15234
15235 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
15236 "TracepointSource", "TracepointSource", 0);
15237
15238 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
15239 "QAllow", "allow", 0);
15240
15241 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
15242 "StaticTracepoints", "static-tracepoints", 0);
15243
15244 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
15245 "InstallInTrace", "install-in-trace", 0);
15246
15247 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
15248 "qXfer:statictrace:read", "read-sdata-object", 0);
15249
15250 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
15251 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
15252
15253 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
15254 "QDisableRandomization", "disable-randomization", 0);
15255
15256 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
15257 "QAgent", "agent", 0);
15258
15259 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
15260 "QTBuffer:size", "trace-buffer-size", 0);
15261
15262 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
15263 "Qbtrace:off", "disable-btrace", 0);
15264
15265 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
15266 "Qbtrace:bts", "enable-btrace-bts", 0);
15267
15268 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
15269 "Qbtrace:pt", "enable-btrace-pt", 0);
15270
15271 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
15272 "qXfer:btrace", "read-btrace", 0);
15273
15274 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
15275 "qXfer:btrace-conf", "read-btrace-conf", 0);
15276
15277 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
15278 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
15279
15280 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
15281 "multiprocess-feature", "multiprocess-feature", 0);
15282
15283 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
15284 "swbreak-feature", "swbreak-feature", 0);
15285
15286 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
15287 "hwbreak-feature", "hwbreak-feature", 0);
15288
15289 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
15290 "fork-event-feature", "fork-event-feature", 0);
15291
15292 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
15293 "vfork-event-feature", "vfork-event-feature", 0);
15294
15295 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
15296 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
15297
15298 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
15299 "vContSupported", "verbose-resume-supported", 0);
15300
15301 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
15302 "exec-event-feature", "exec-event-feature", 0);
15303
15304 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
15305 "vCtrlC", "ctrl-c", 0);
15306
15307 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
15308 "QThreadEvents", "thread-events", 0);
15309
15310 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
15311 "N stop reply", "no-resumed-stop-reply", 0);
15312
15313 add_packet_config_cmd (&remote_protocol_packets[PACKET_memory_tagging_feature],
15314 "memory-tagging-feature", "memory-tagging-feature", 0);
15315
15316 /* Assert that we've registered "set remote foo-packet" commands
15317 for all packet configs. */
15318 {
15319 int i;
15320
15321 for (i = 0; i < PACKET_MAX; i++)
15322 {
15323 /* Ideally all configs would have a command associated. Some
15324 still don't though. */
15325 int excepted;
15326
15327 switch (i)
15328 {
15329 case PACKET_QNonStop:
15330 case PACKET_EnableDisableTracepoints_feature:
15331 case PACKET_tracenz_feature:
15332 case PACKET_DisconnectedTracing_feature:
15333 case PACKET_augmented_libraries_svr4_read_feature:
15334 case PACKET_qCRC:
15335 /* Additions to this list need to be well justified:
15336 pre-existing packets are OK; new packets are not. */
15337 excepted = 1;
15338 break;
15339 default:
15340 excepted = 0;
15341 break;
15342 }
15343
15344 /* This catches both forgetting to add a config command, and
15345 forgetting to remove a packet from the exception list. */
15346 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
15347 }
15348 }
15349
15350 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15351 Z sub-packet has its own set and show commands, but users may
15352 have sets to this variable in their .gdbinit files (or in their
15353 documentation). */
15354 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
15355 &remote_Z_packet_detect, _("\
15356 Set use of remote protocol `Z' packets."), _("\
15357 Show use of remote protocol `Z' packets."), _("\
15358 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
15359 packets."),
15360 set_remote_protocol_Z_packet_cmd,
15361 show_remote_protocol_Z_packet_cmd,
15362 /* FIXME: i18n: Use of remote protocol
15363 `Z' packets is %s. */
15364 &remote_set_cmdlist, &remote_show_cmdlist);
15365
15366 add_basic_prefix_cmd ("remote", class_files, _("\
15367 Manipulate files on the remote system.\n\
15368 Transfer files to and from the remote target system."),
15369 &remote_cmdlist,
15370 0 /* allow-unknown */, &cmdlist);
15371
15372 add_cmd ("put", class_files, remote_put_command,
15373 _("Copy a local file to the remote system."),
15374 &remote_cmdlist);
15375
15376 add_cmd ("get", class_files, remote_get_command,
15377 _("Copy a remote file to the local system."),
15378 &remote_cmdlist);
15379
15380 add_cmd ("delete", class_files, remote_delete_command,
15381 _("Delete a remote file."),
15382 &remote_cmdlist);
15383
15384 add_setshow_string_noescape_cmd ("exec-file", class_files,
15385 &remote_exec_file_var, _("\
15386 Set the remote pathname for \"run\"."), _("\
15387 Show the remote pathname for \"run\"."), NULL,
15388 set_remote_exec_file,
15389 show_remote_exec_file,
15390 &remote_set_cmdlist,
15391 &remote_show_cmdlist);
15392
15393 add_setshow_boolean_cmd ("range-stepping", class_run,
15394 &use_range_stepping, _("\
15395 Enable or disable range stepping."), _("\
15396 Show whether target-assisted range stepping is enabled."), _("\
15397 If on, and the target supports it, when stepping a source line, GDB\n\
15398 tells the target to step the corresponding range of addresses itself instead\n\
15399 of issuing multiple single-steps. This speeds up source level\n\
15400 stepping. If off, GDB always issues single-steps, even if range\n\
15401 stepping is supported by the target. The default is on."),
15402 set_range_stepping,
15403 show_range_stepping,
15404 &setlist,
15405 &showlist);
15406
15407 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15408 Set watchdog timer."), _("\
15409 Show watchdog timer."), _("\
15410 When non-zero, this timeout is used instead of waiting forever for a target\n\
15411 to finish a low-level step or continue operation. If the specified amount\n\
15412 of time passes without a response from the target, an error occurs."),
15413 NULL,
15414 show_watchdog,
15415 &setlist, &showlist);
15416
15417 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15418 &remote_packet_max_chars, _("\
15419 Set the maximum number of characters to display for each remote packet."), _("\
15420 Show the maximum number of characters to display for each remote packet."), _("\
15421 Specify \"unlimited\" to display all the characters."),
15422 NULL, show_remote_packet_max_chars,
15423 &setdebuglist, &showdebuglist);
15424
15425 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15426 _("Set debugging of remote protocol."),
15427 _("Show debugging of remote protocol."),
15428 _("\
15429 When enabled, each packet sent or received with the remote target\n\
15430 is displayed."),
15431 NULL,
15432 show_remote_debug,
15433 &setdebuglist, &showdebuglist);
15434
15435 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15436 &remote_timeout, _("\
15437 Set timeout limit to wait for target to respond."), _("\
15438 Show timeout limit to wait for target to respond."), _("\
15439 This value is used to set the time limit for gdb to wait for a response\n\
15440 from the target."),
15441 NULL,
15442 show_remote_timeout,
15443 &setlist, &showlist);
15444
15445 /* Eventually initialize fileio. See fileio.c */
15446 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
15447
15448 #if GDB_SELF_TEST
15449 selftests::register_test ("remote_memory_tagging",
15450 selftests::test_memory_tagging_functions);
15451 #endif
15452 }