]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/remote.c
Automatic Copyright Year update after running gdb/copyright.py
[thirdparty/binutils-gdb.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3 Copyright (C) 1988-2022 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20 /* See the GDB User Guide for details of the GDB remote protocol. */
21
22 #include "defs.h"
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "bfd.h"
28 #include "symfile.h"
29 #include "target.h"
30 #include "process-stratum-target.h"
31 #include "gdbcmd.h"
32 #include "objfiles.h"
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
35 #include "remote.h"
36 #include "remote-notif.h"
37 #include "regcache.h"
38 #include "value.h"
39 #include "observable.h"
40 #include "solib.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
44 #include "gdb_bfd.h"
45 #include "gdbsupport/filestuff.h"
46 #include "gdbsupport/rsp-low.h"
47 #include "disasm.h"
48 #include "location.h"
49
50 #include "gdbsupport/gdb_sys_time.h"
51
52 #include "gdbsupport/event-loop.h"
53 #include "event-top.h"
54 #include "inf-loop.h"
55
56 #include <signal.h>
57 #include "serial.h"
58
59 #include "gdbcore.h"
60
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
63 #include <sys/stat.h>
64 #include "xml-support.h"
65
66 #include "memory-map.h"
67
68 #include "tracepoint.h"
69 #include "ax.h"
70 #include "ax-gdb.h"
71 #include "gdbsupport/agent.h"
72 #include "btrace.h"
73 #include "record-btrace.h"
74 #include <algorithm>
75 #include "gdbsupport/scoped_restore.h"
76 #include "gdbsupport/environ.h"
77 #include "gdbsupport/byte-vector.h"
78 #include "gdbsupport/search.h"
79 #include <algorithm>
80 #include <unordered_map>
81 #include "async-event.h"
82 #include "gdbsupport/selftest.h"
83
84 /* The remote target. */
85
86 static const char remote_doc[] = N_("\
87 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
88 Specify the serial device it is connected to\n\
89 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
90
91 /* See remote.h */
92
93 bool remote_debug = false;
94
95 #define OPAQUETHREADBYTES 8
96
97 /* a 64 bit opaque identifier */
98 typedef unsigned char threadref[OPAQUETHREADBYTES];
99
100 struct gdb_ext_thread_info;
101 struct threads_listing_context;
102 typedef int (*rmt_thread_action) (threadref *ref, void *context);
103 struct protocol_feature;
104 struct packet_reg;
105
106 struct stop_reply;
107 typedef std::unique_ptr<stop_reply> stop_reply_up;
108
109 /* Generic configuration support for packets the stub optionally
110 supports. Allows the user to specify the use of the packet as well
111 as allowing GDB to auto-detect support in the remote stub. */
112
113 enum packet_support
114 {
115 PACKET_SUPPORT_UNKNOWN = 0,
116 PACKET_ENABLE,
117 PACKET_DISABLE
118 };
119
120 /* Analyze a packet's return value and update the packet config
121 accordingly. */
122
123 enum packet_result
124 {
125 PACKET_ERROR,
126 PACKET_OK,
127 PACKET_UNKNOWN
128 };
129
130 struct threads_listing_context;
131
132 /* Stub vCont actions support.
133
134 Each field is a boolean flag indicating whether the stub reports
135 support for the corresponding action. */
136
137 struct vCont_action_support
138 {
139 /* vCont;t */
140 bool t = false;
141
142 /* vCont;r */
143 bool r = false;
144
145 /* vCont;s */
146 bool s = false;
147
148 /* vCont;S */
149 bool S = false;
150 };
151
152 /* About this many threadids fit in a packet. */
153
154 #define MAXTHREADLISTRESULTS 32
155
156 /* Data for the vFile:pread readahead cache. */
157
158 struct readahead_cache
159 {
160 /* Invalidate the readahead cache. */
161 void invalidate ();
162
163 /* Invalidate the readahead cache if it is holding data for FD. */
164 void invalidate_fd (int fd);
165
166 /* Serve pread from the readahead cache. Returns number of bytes
167 read, or 0 if the request can't be served from the cache. */
168 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
169
170 /* The file descriptor for the file that is being cached. -1 if the
171 cache is invalid. */
172 int fd = -1;
173
174 /* The offset into the file that the cache buffer corresponds
175 to. */
176 ULONGEST offset = 0;
177
178 /* The buffer holding the cache contents. */
179 gdb_byte *buf = nullptr;
180 /* The buffer's size. We try to read as much as fits into a packet
181 at a time. */
182 size_t bufsize = 0;
183
184 /* Cache hit and miss counters. */
185 ULONGEST hit_count = 0;
186 ULONGEST miss_count = 0;
187 };
188
189 /* Description of the remote protocol for a given architecture. */
190
191 struct packet_reg
192 {
193 long offset; /* Offset into G packet. */
194 long regnum; /* GDB's internal register number. */
195 LONGEST pnum; /* Remote protocol register number. */
196 int in_g_packet; /* Always part of G packet. */
197 /* long size in bytes; == register_size (target_gdbarch (), regnum);
198 at present. */
199 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
200 at present. */
201 };
202
203 struct remote_arch_state
204 {
205 explicit remote_arch_state (struct gdbarch *gdbarch);
206
207 /* Description of the remote protocol registers. */
208 long sizeof_g_packet;
209
210 /* Description of the remote protocol registers indexed by REGNUM
211 (making an array gdbarch_num_regs in size). */
212 std::unique_ptr<packet_reg[]> regs;
213
214 /* This is the size (in chars) of the first response to the ``g''
215 packet. It is used as a heuristic when determining the maximum
216 size of memory-read and memory-write packets. A target will
217 typically only reserve a buffer large enough to hold the ``g''
218 packet. The size does not include packet overhead (headers and
219 trailers). */
220 long actual_register_packet_size;
221
222 /* This is the maximum size (in chars) of a non read/write packet.
223 It is also used as a cap on the size of read/write packets. */
224 long remote_packet_size;
225 };
226
227 /* Description of the remote protocol state for the currently
228 connected target. This is per-target state, and independent of the
229 selected architecture. */
230
231 class remote_state
232 {
233 public:
234
235 remote_state ();
236 ~remote_state ();
237
238 /* Get the remote arch state for GDBARCH. */
239 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
240
241 public: /* data */
242
243 /* A buffer to use for incoming packets, and its current size. The
244 buffer is grown dynamically for larger incoming packets.
245 Outgoing packets may also be constructed in this buffer.
246 The size of the buffer is always at least REMOTE_PACKET_SIZE;
247 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
248 packets. */
249 gdb::char_vector buf;
250
251 /* True if we're going through initial connection setup (finding out
252 about the remote side's threads, relocating symbols, etc.). */
253 bool starting_up = false;
254
255 /* If we negotiated packet size explicitly (and thus can bypass
256 heuristics for the largest packet size that will not overflow
257 a buffer in the stub), this will be set to that packet size.
258 Otherwise zero, meaning to use the guessed size. */
259 long explicit_packet_size = 0;
260
261 /* True, if in no ack mode. That is, neither GDB nor the stub will
262 expect acks from each other. The connection is assumed to be
263 reliable. */
264 bool noack_mode = false;
265
266 /* True if we're connected in extended remote mode. */
267 bool extended = false;
268
269 /* True if we resumed the target and we're waiting for the target to
270 stop. In the mean time, we can't start another command/query.
271 The remote server wouldn't be ready to process it, so we'd
272 timeout waiting for a reply that would never come and eventually
273 we'd close the connection. This can happen in asynchronous mode
274 because we allow GDB commands while the target is running. */
275 bool waiting_for_stop_reply = false;
276
277 /* The status of the stub support for the various vCont actions. */
278 vCont_action_support supports_vCont;
279 /* Whether vCont support was probed already. This is a workaround
280 until packet_support is per-connection. */
281 bool supports_vCont_probed;
282
283 /* True if the user has pressed Ctrl-C, but the target hasn't
284 responded to that. */
285 bool ctrlc_pending_p = false;
286
287 /* True if we saw a Ctrl-C while reading or writing from/to the
288 remote descriptor. At that point it is not safe to send a remote
289 interrupt packet, so we instead remember we saw the Ctrl-C and
290 process it once we're done with sending/receiving the current
291 packet, which should be shortly. If however that takes too long,
292 and the user presses Ctrl-C again, we offer to disconnect. */
293 bool got_ctrlc_during_io = false;
294
295 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
296 remote_open knows that we don't have a file open when the program
297 starts. */
298 struct serial *remote_desc = nullptr;
299
300 /* These are the threads which we last sent to the remote system. The
301 TID member will be -1 for all or -2 for not sent yet. */
302 ptid_t general_thread = null_ptid;
303 ptid_t continue_thread = null_ptid;
304
305 /* This is the traceframe which we last selected on the remote system.
306 It will be -1 if no traceframe is selected. */
307 int remote_traceframe_number = -1;
308
309 char *last_pass_packet = nullptr;
310
311 /* The last QProgramSignals packet sent to the target. We bypass
312 sending a new program signals list down to the target if the new
313 packet is exactly the same as the last we sent. IOW, we only let
314 the target know about program signals list changes. */
315 char *last_program_signals_packet = nullptr;
316
317 gdb_signal last_sent_signal = GDB_SIGNAL_0;
318
319 bool last_sent_step = false;
320
321 /* The execution direction of the last resume we got. */
322 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
323
324 char *finished_object = nullptr;
325 char *finished_annex = nullptr;
326 ULONGEST finished_offset = 0;
327
328 /* Should we try the 'ThreadInfo' query packet?
329
330 This variable (NOT available to the user: auto-detect only!)
331 determines whether GDB will use the new, simpler "ThreadInfo"
332 query or the older, more complex syntax for thread queries.
333 This is an auto-detect variable (set to true at each connect,
334 and set to false when the target fails to recognize it). */
335 bool use_threadinfo_query = false;
336 bool use_threadextra_query = false;
337
338 threadref echo_nextthread {};
339 threadref nextthread {};
340 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
341
342 /* The state of remote notification. */
343 struct remote_notif_state *notif_state = nullptr;
344
345 /* The branch trace configuration. */
346 struct btrace_config btrace_config {};
347
348 /* The argument to the last "vFile:setfs:" packet we sent, used
349 to avoid sending repeated unnecessary "vFile:setfs:" packets.
350 Initialized to -1 to indicate that no "vFile:setfs:" packet
351 has yet been sent. */
352 int fs_pid = -1;
353
354 /* A readahead cache for vFile:pread. Often, reading a binary
355 involves a sequence of small reads. E.g., when parsing an ELF
356 file. A readahead cache helps mostly the case of remote
357 debugging on a connection with higher latency, due to the
358 request/reply nature of the RSP. We only cache data for a single
359 file descriptor at a time. */
360 struct readahead_cache readahead_cache;
361
362 /* The list of already fetched and acknowledged stop events. This
363 queue is used for notification Stop, and other notifications
364 don't need queue for their events, because the notification
365 events of Stop can't be consumed immediately, so that events
366 should be queued first, and be consumed by remote_wait_{ns,as}
367 one per time. Other notifications can consume their events
368 immediately, so queue is not needed for them. */
369 std::vector<stop_reply_up> stop_reply_queue;
370
371 /* Asynchronous signal handle registered as event loop source for
372 when we have pending events ready to be passed to the core. */
373 struct async_event_handler *remote_async_inferior_event_token = nullptr;
374
375 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
376 ``forever'' still use the normal timeout mechanism. This is
377 currently used by the ASYNC code to guarentee that target reads
378 during the initial connect always time-out. Once getpkt has been
379 modified to return a timeout indication and, in turn
380 remote_wait()/wait_for_inferior() have gained a timeout parameter
381 this can go away. */
382 int wait_forever_enabled_p = 1;
383
384 private:
385 /* Mapping of remote protocol data for each gdbarch. Usually there
386 is only one entry here, though we may see more with stubs that
387 support multi-process. */
388 std::unordered_map<struct gdbarch *, remote_arch_state>
389 m_arch_states;
390 };
391
392 static const target_info remote_target_info = {
393 "remote",
394 N_("Remote serial target in 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 void files_info () override;
430
431 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
432
433 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
434 enum remove_bp_reason) override;
435
436
437 bool stopped_by_sw_breakpoint () override;
438 bool supports_stopped_by_sw_breakpoint () override;
439
440 bool stopped_by_hw_breakpoint () override;
441
442 bool supports_stopped_by_hw_breakpoint () override;
443
444 bool stopped_by_watchpoint () override;
445
446 bool stopped_data_address (CORE_ADDR *) override;
447
448 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
449
450 int can_use_hw_breakpoint (enum bptype, int, int) override;
451
452 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
453
454 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
455
456 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
457
458 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
459 struct expression *) override;
460
461 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
462 struct expression *) override;
463
464 void kill () override;
465
466 void load (const char *, int) override;
467
468 void mourn_inferior () override;
469
470 void pass_signals (gdb::array_view<const unsigned char>) override;
471
472 int set_syscall_catchpoint (int, bool, int,
473 gdb::array_view<const int>) override;
474
475 void program_signals (gdb::array_view<const unsigned char>) override;
476
477 bool thread_alive (ptid_t ptid) override;
478
479 const char *thread_name (struct thread_info *) override;
480
481 void update_thread_list () override;
482
483 std::string pid_to_str (ptid_t) override;
484
485 const char *extra_thread_info (struct thread_info *) override;
486
487 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
488
489 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
490 int handle_len,
491 inferior *inf) override;
492
493 gdb::byte_vector thread_info_to_thread_handle (struct thread_info *tp)
494 override;
495
496 void stop (ptid_t) override;
497
498 void interrupt () override;
499
500 void pass_ctrlc () override;
501
502 enum target_xfer_status xfer_partial (enum target_object object,
503 const char *annex,
504 gdb_byte *readbuf,
505 const gdb_byte *writebuf,
506 ULONGEST offset, ULONGEST len,
507 ULONGEST *xfered_len) override;
508
509 ULONGEST get_memory_xfer_limit () override;
510
511 void rcmd (const char *command, struct ui_file *output) override;
512
513 char *pid_to_exec_file (int pid) override;
514
515 void log_command (const char *cmd) override
516 {
517 serial_log_command (this, cmd);
518 }
519
520 CORE_ADDR get_thread_local_address (ptid_t ptid,
521 CORE_ADDR load_module_addr,
522 CORE_ADDR offset) override;
523
524 bool can_execute_reverse () override;
525
526 std::vector<mem_region> memory_map () override;
527
528 void flash_erase (ULONGEST address, LONGEST length) override;
529
530 void flash_done () override;
531
532 const struct target_desc *read_description () override;
533
534 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
535 const gdb_byte *pattern, ULONGEST pattern_len,
536 CORE_ADDR *found_addrp) override;
537
538 bool can_async_p () override;
539
540 bool is_async_p () override;
541
542 void async (int) override;
543
544 int async_wait_fd () override;
545
546 void thread_events (int) override;
547
548 int can_do_single_step () override;
549
550 void terminal_inferior () override;
551
552 void terminal_ours () override;
553
554 bool supports_non_stop () override;
555
556 bool supports_multi_process () override;
557
558 bool supports_disable_randomization () override;
559
560 bool filesystem_is_local () override;
561
562
563 int fileio_open (struct inferior *inf, const char *filename,
564 int flags, int mode, int warn_if_slow,
565 int *target_errno) override;
566
567 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
568 ULONGEST offset, int *target_errno) override;
569
570 int fileio_pread (int fd, gdb_byte *read_buf, int len,
571 ULONGEST offset, int *target_errno) override;
572
573 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
574
575 int fileio_close (int fd, int *target_errno) override;
576
577 int fileio_unlink (struct inferior *inf,
578 const char *filename,
579 int *target_errno) override;
580
581 gdb::optional<std::string>
582 fileio_readlink (struct inferior *inf,
583 const char *filename,
584 int *target_errno) override;
585
586 bool supports_enable_disable_tracepoint () override;
587
588 bool supports_string_tracing () override;
589
590 bool supports_evaluation_of_breakpoint_conditions () override;
591
592 bool can_run_breakpoint_commands () override;
593
594 void trace_init () override;
595
596 void download_tracepoint (struct bp_location *location) override;
597
598 bool can_download_tracepoint () override;
599
600 void download_trace_state_variable (const trace_state_variable &tsv) override;
601
602 void enable_tracepoint (struct bp_location *location) override;
603
604 void disable_tracepoint (struct bp_location *location) override;
605
606 void trace_set_readonly_regions () override;
607
608 void trace_start () override;
609
610 int get_trace_status (struct trace_status *ts) override;
611
612 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
613 override;
614
615 void trace_stop () override;
616
617 int trace_find (enum trace_find_type type, int num,
618 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
619
620 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
621
622 int save_trace_data (const char *filename) override;
623
624 int upload_tracepoints (struct uploaded_tp **utpp) override;
625
626 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
627
628 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
629
630 int get_min_fast_tracepoint_insn_len () override;
631
632 void set_disconnected_tracing (int val) override;
633
634 void set_circular_trace_buffer (int val) override;
635
636 void set_trace_buffer_size (LONGEST val) override;
637
638 bool set_trace_notes (const char *user, const char *notes,
639 const char *stopnotes) override;
640
641 int core_of_thread (ptid_t ptid) override;
642
643 int verify_memory (const gdb_byte *data,
644 CORE_ADDR memaddr, ULONGEST size) override;
645
646
647 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
648
649 void set_permissions () override;
650
651 bool static_tracepoint_marker_at (CORE_ADDR,
652 struct static_tracepoint_marker *marker)
653 override;
654
655 std::vector<static_tracepoint_marker>
656 static_tracepoint_markers_by_strid (const char *id) override;
657
658 traceframe_info_up traceframe_info () override;
659
660 bool use_agent (bool use) override;
661 bool can_use_agent () override;
662
663 struct btrace_target_info *enable_btrace (ptid_t ptid,
664 const struct btrace_config *conf) override;
665
666 void disable_btrace (struct btrace_target_info *tinfo) override;
667
668 void teardown_btrace (struct btrace_target_info *tinfo) override;
669
670 enum btrace_error read_btrace (struct btrace_data *data,
671 struct btrace_target_info *btinfo,
672 enum btrace_read_type type) override;
673
674 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
675 bool augmented_libraries_svr4_read () override;
676 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
677 void follow_exec (inferior *, ptid_t, const char *) override;
678 int insert_fork_catchpoint (int) override;
679 int remove_fork_catchpoint (int) override;
680 int insert_vfork_catchpoint (int) override;
681 int remove_vfork_catchpoint (int) override;
682 int insert_exec_catchpoint (int) override;
683 int remove_exec_catchpoint (int) override;
684 enum exec_direction_kind execution_direction () override;
685
686 bool supports_memory_tagging () override;
687
688 bool fetch_memtags (CORE_ADDR address, size_t len,
689 gdb::byte_vector &tags, int type) override;
690
691 bool store_memtags (CORE_ADDR address, size_t len,
692 const gdb::byte_vector &tags, int type) override;
693
694 public: /* Remote specific methods. */
695
696 void remote_download_command_source (int num, ULONGEST addr,
697 struct command_line *cmds);
698
699 void remote_file_put (const char *local_file, const char *remote_file,
700 int from_tty);
701 void remote_file_get (const char *remote_file, const char *local_file,
702 int from_tty);
703 void remote_file_delete (const char *remote_file, int from_tty);
704
705 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
706 ULONGEST offset, int *remote_errno);
707 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
708 ULONGEST offset, int *remote_errno);
709 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
710 ULONGEST offset, int *remote_errno);
711
712 int remote_hostio_send_command (int command_bytes, int which_packet,
713 int *remote_errno, const char **attachment,
714 int *attachment_len);
715 int remote_hostio_set_filesystem (struct inferior *inf,
716 int *remote_errno);
717 /* We should get rid of this and use fileio_open directly. */
718 int remote_hostio_open (struct inferior *inf, const char *filename,
719 int flags, int mode, int warn_if_slow,
720 int *remote_errno);
721 int remote_hostio_close (int fd, int *remote_errno);
722
723 int remote_hostio_unlink (inferior *inf, const char *filename,
724 int *remote_errno);
725
726 struct remote_state *get_remote_state ();
727
728 long get_remote_packet_size (void);
729 long get_memory_packet_size (struct memory_packet_config *config);
730
731 long get_memory_write_packet_size ();
732 long get_memory_read_packet_size ();
733
734 char *append_pending_thread_resumptions (char *p, char *endp,
735 ptid_t ptid);
736 static void open_1 (const char *name, int from_tty, int extended_p);
737 void start_remote (int from_tty, int extended_p);
738 void remote_detach_1 (struct inferior *inf, int from_tty);
739
740 char *append_resumption (char *p, char *endp,
741 ptid_t ptid, int step, gdb_signal siggnal);
742 int remote_resume_with_vcont (ptid_t ptid, int step,
743 gdb_signal siggnal);
744
745 thread_info *add_current_inferior_and_thread (const char *wait_status);
746
747 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
748 target_wait_flags options);
749 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
750 target_wait_flags options);
751
752 ptid_t process_stop_reply (struct stop_reply *stop_reply,
753 target_waitstatus *status);
754
755 ptid_t select_thread_for_ambiguous_stop_reply
756 (const struct target_waitstatus &status);
757
758 void remote_notice_new_inferior (ptid_t currthread, bool executing);
759
760 void print_one_stopped_thread (thread_info *thread);
761 void process_initial_stop_replies (int from_tty);
762
763 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
764 bool silent_p);
765
766 void btrace_sync_conf (const btrace_config *conf);
767
768 void remote_btrace_maybe_reopen ();
769
770 void remove_new_fork_children (threads_listing_context *context);
771 void kill_new_fork_children (inferior *inf);
772 void discard_pending_stop_replies (struct inferior *inf);
773 int stop_reply_queue_length ();
774
775 void check_pending_events_prevent_wildcard_vcont
776 (bool *may_global_wildcard_vcont);
777
778 void discard_pending_stop_replies_in_queue ();
779 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
780 struct stop_reply *queued_stop_reply (ptid_t ptid);
781 int peek_stop_reply (ptid_t ptid);
782 void remote_parse_stop_reply (const char *buf, stop_reply *event);
783
784 void remote_stop_ns (ptid_t ptid);
785 void remote_interrupt_as ();
786 void remote_interrupt_ns ();
787
788 char *remote_get_noisy_reply ();
789 int remote_query_attached (int pid);
790 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
791 int try_open_exec);
792
793 ptid_t remote_current_thread (ptid_t oldpid);
794 ptid_t get_current_thread (const char *wait_status);
795
796 void set_thread (ptid_t ptid, int gen);
797 void set_general_thread (ptid_t ptid);
798 void set_continue_thread (ptid_t ptid);
799 void set_general_process ();
800
801 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
802
803 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
804 gdb_ext_thread_info *info);
805 int remote_get_threadinfo (threadref *threadid, int fieldset,
806 gdb_ext_thread_info *info);
807
808 int parse_threadlist_response (const char *pkt, int result_limit,
809 threadref *original_echo,
810 threadref *resultlist,
811 int *doneflag);
812 int remote_get_threadlist (int startflag, threadref *nextthread,
813 int result_limit, int *done, int *result_count,
814 threadref *threadlist);
815
816 int remote_threadlist_iterator (rmt_thread_action stepfunction,
817 void *context, int looplimit);
818
819 int remote_get_threads_with_ql (threads_listing_context *context);
820 int remote_get_threads_with_qxfer (threads_listing_context *context);
821 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
822
823 void extended_remote_restart ();
824
825 void get_offsets ();
826
827 void remote_check_symbols ();
828
829 void remote_supported_packet (const struct protocol_feature *feature,
830 enum packet_support support,
831 const char *argument);
832
833 void remote_query_supported ();
834
835 void remote_packet_size (const protocol_feature *feature,
836 packet_support support, const char *value);
837
838 void remote_serial_quit_handler ();
839
840 void remote_detach_pid (int pid);
841
842 void remote_vcont_probe ();
843
844 void remote_resume_with_hc (ptid_t ptid, int step,
845 gdb_signal siggnal);
846
847 void send_interrupt_sequence ();
848 void interrupt_query ();
849
850 void remote_notif_get_pending_events (notif_client *nc);
851
852 int fetch_register_using_p (struct regcache *regcache,
853 packet_reg *reg);
854 int send_g_packet ();
855 void process_g_packet (struct regcache *regcache);
856 void fetch_registers_using_g (struct regcache *regcache);
857 int store_register_using_P (const struct regcache *regcache,
858 packet_reg *reg);
859 void store_registers_using_G (const struct regcache *regcache);
860
861 void set_remote_traceframe ();
862
863 void check_binary_download (CORE_ADDR addr);
864
865 target_xfer_status remote_write_bytes_aux (const char *header,
866 CORE_ADDR memaddr,
867 const gdb_byte *myaddr,
868 ULONGEST len_units,
869 int unit_size,
870 ULONGEST *xfered_len_units,
871 char packet_format,
872 int use_length);
873
874 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
875 const gdb_byte *myaddr, ULONGEST len,
876 int unit_size, ULONGEST *xfered_len);
877
878 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
879 ULONGEST len_units,
880 int unit_size, ULONGEST *xfered_len_units);
881
882 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
883 ULONGEST memaddr,
884 ULONGEST len,
885 int unit_size,
886 ULONGEST *xfered_len);
887
888 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
889 gdb_byte *myaddr, ULONGEST len,
890 int unit_size,
891 ULONGEST *xfered_len);
892
893 packet_result remote_send_printf (const char *format, ...)
894 ATTRIBUTE_PRINTF (2, 3);
895
896 target_xfer_status remote_flash_write (ULONGEST address,
897 ULONGEST length, ULONGEST *xfered_len,
898 const gdb_byte *data);
899
900 int readchar (int timeout);
901
902 void remote_serial_write (const char *str, int len);
903
904 int putpkt (const char *buf);
905 int putpkt_binary (const char *buf, int cnt);
906
907 int putpkt (const gdb::char_vector &buf)
908 {
909 return putpkt (buf.data ());
910 }
911
912 void skip_frame ();
913 long read_frame (gdb::char_vector *buf_p);
914 void getpkt (gdb::char_vector *buf, int forever);
915 int getpkt_or_notif_sane_1 (gdb::char_vector *buf, int forever,
916 int expecting_notif, int *is_notif);
917 int getpkt_sane (gdb::char_vector *buf, int forever);
918 int getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
919 int *is_notif);
920 int remote_vkill (int pid);
921 void remote_kill_k ();
922
923 void extended_remote_disable_randomization (int val);
924 int extended_remote_run (const std::string &args);
925
926 void send_environment_packet (const char *action,
927 const char *packet,
928 const char *value);
929
930 void extended_remote_environment_support ();
931 void extended_remote_set_inferior_cwd ();
932
933 target_xfer_status remote_write_qxfer (const char *object_name,
934 const char *annex,
935 const gdb_byte *writebuf,
936 ULONGEST offset, LONGEST len,
937 ULONGEST *xfered_len,
938 struct packet_config *packet);
939
940 target_xfer_status remote_read_qxfer (const char *object_name,
941 const char *annex,
942 gdb_byte *readbuf, ULONGEST offset,
943 LONGEST len,
944 ULONGEST *xfered_len,
945 struct packet_config *packet);
946
947 void push_stop_reply (struct stop_reply *new_event);
948
949 bool vcont_r_supported ();
950
951 private:
952
953 bool start_remote_1 (int from_tty, int extended_p);
954
955 /* The remote state. Don't reference this directly. Use the
956 get_remote_state method instead. */
957 remote_state m_remote_state;
958 };
959
960 static const target_info extended_remote_target_info = {
961 "extended-remote",
962 N_("Extended remote serial target in gdb-specific protocol"),
963 remote_doc
964 };
965
966 /* Set up the extended remote target by extending the standard remote
967 target and adding to it. */
968
969 class extended_remote_target final : public remote_target
970 {
971 public:
972 const target_info &info () const override
973 { return extended_remote_target_info; }
974
975 /* Open an extended-remote connection. */
976 static void open (const char *, int);
977
978 bool can_create_inferior () override { return true; }
979 void create_inferior (const char *, const std::string &,
980 char **, int) override;
981
982 void detach (inferior *, int) override;
983
984 bool can_attach () override { return true; }
985 void attach (const char *, int) override;
986
987 void post_attach (int) override;
988 bool supports_disable_randomization () override;
989 };
990
991 struct stop_reply : public notif_event
992 {
993 ~stop_reply ();
994
995 /* The identifier of the thread about this event */
996 ptid_t ptid;
997
998 /* The remote state this event is associated with. When the remote
999 connection, represented by a remote_state object, is closed,
1000 all the associated stop_reply events should be released. */
1001 struct remote_state *rs;
1002
1003 struct target_waitstatus ws;
1004
1005 /* The architecture associated with the expedited registers. */
1006 gdbarch *arch;
1007
1008 /* Expedited registers. This makes remote debugging a bit more
1009 efficient for those targets that provide critical registers as
1010 part of their normal status mechanism (as another roundtrip to
1011 fetch them is avoided). */
1012 std::vector<cached_reg_t> regcache;
1013
1014 enum target_stop_reason stop_reason;
1015
1016 CORE_ADDR watch_data_address;
1017
1018 int core;
1019 };
1020
1021 /* See remote.h. */
1022
1023 bool
1024 is_remote_target (process_stratum_target *target)
1025 {
1026 remote_target *rt = dynamic_cast<remote_target *> (target);
1027 return rt != nullptr;
1028 }
1029
1030 /* Per-program-space data key. */
1031 static const struct program_space_key<char, gdb::xfree_deleter<char>>
1032 remote_pspace_data;
1033
1034 /* The variable registered as the control variable used by the
1035 remote exec-file commands. While the remote exec-file setting is
1036 per-program-space, the set/show machinery uses this as the
1037 location of the remote exec-file value. */
1038 static std::string remote_exec_file_var;
1039
1040 /* The size to align memory write packets, when practical. The protocol
1041 does not guarantee any alignment, and gdb will generate short
1042 writes and unaligned writes, but even as a best-effort attempt this
1043 can improve bulk transfers. For instance, if a write is misaligned
1044 relative to the target's data bus, the stub may need to make an extra
1045 round trip fetching data from the target. This doesn't make a
1046 huge difference, but it's easy to do, so we try to be helpful.
1047
1048 The alignment chosen is arbitrary; usually data bus width is
1049 important here, not the possibly larger cache line size. */
1050 enum { REMOTE_ALIGN_WRITES = 16 };
1051
1052 /* Prototypes for local functions. */
1053
1054 static int hexnumlen (ULONGEST num);
1055
1056 static int stubhex (int ch);
1057
1058 static int hexnumstr (char *, ULONGEST);
1059
1060 static int hexnumnstr (char *, ULONGEST, int);
1061
1062 static CORE_ADDR remote_address_masked (CORE_ADDR);
1063
1064 static int stub_unpack_int (const char *buff, int fieldlength);
1065
1066 struct packet_config;
1067
1068 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1069 int from_tty,
1070 struct cmd_list_element *c,
1071 const char *value);
1072
1073 static ptid_t read_ptid (const char *buf, const char **obuf);
1074
1075 static void remote_async_inferior_event_handler (gdb_client_data);
1076
1077 static bool remote_read_description_p (struct target_ops *target);
1078
1079 static void remote_console_output (const char *msg);
1080
1081 static void remote_btrace_reset (remote_state *rs);
1082
1083 static void remote_unpush_and_throw (remote_target *target);
1084
1085 /* For "remote". */
1086
1087 static struct cmd_list_element *remote_cmdlist;
1088
1089 /* For "set remote" and "show remote". */
1090
1091 static struct cmd_list_element *remote_set_cmdlist;
1092 static struct cmd_list_element *remote_show_cmdlist;
1093
1094 /* Controls whether GDB is willing to use range stepping. */
1095
1096 static bool use_range_stepping = true;
1097
1098 /* From the remote target's point of view, each thread is in one of these three
1099 states. */
1100 enum class resume_state
1101 {
1102 /* Not resumed - we haven't been asked to resume this thread. */
1103 NOT_RESUMED,
1104
1105 /* We have been asked to resume this thread, but haven't sent a vCont action
1106 for it yet. We'll need to consider it next time commit_resume is
1107 called. */
1108 RESUMED_PENDING_VCONT,
1109
1110 /* We have been asked to resume this thread, and we have sent a vCont action
1111 for it. */
1112 RESUMED,
1113 };
1114
1115 /* Information about a thread's pending vCont-resume. Used when a thread is in
1116 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1117 stores this information which is then picked up by
1118 remote_target::commit_resume to know which is the proper action for this
1119 thread to include in the vCont packet. */
1120 struct resumed_pending_vcont_info
1121 {
1122 /* True if the last resume call for this thread was a step request, false
1123 if a continue request. */
1124 bool step;
1125
1126 /* The signal specified in the last resume call for this thread. */
1127 gdb_signal sig;
1128 };
1129
1130 /* Private data that we'll store in (struct thread_info)->priv. */
1131 struct remote_thread_info : public private_thread_info
1132 {
1133 std::string extra;
1134 std::string name;
1135 int core = -1;
1136
1137 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1138 sequence of bytes. */
1139 gdb::byte_vector thread_handle;
1140
1141 /* Whether the target stopped for a breakpoint/watchpoint. */
1142 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1143
1144 /* This is set to the data address of the access causing the target
1145 to stop for a watchpoint. */
1146 CORE_ADDR watch_data_address = 0;
1147
1148 /* Get the thread's resume state. */
1149 enum resume_state get_resume_state () const
1150 {
1151 return m_resume_state;
1152 }
1153
1154 /* Put the thread in the NOT_RESUMED state. */
1155 void set_not_resumed ()
1156 {
1157 m_resume_state = resume_state::NOT_RESUMED;
1158 }
1159
1160 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1161 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1162 {
1163 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1164 m_resumed_pending_vcont_info.step = step;
1165 m_resumed_pending_vcont_info.sig = sig;
1166 }
1167
1168 /* Get the information this thread's pending vCont-resumption.
1169
1170 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1171 state. */
1172 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1173 {
1174 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1175
1176 return m_resumed_pending_vcont_info;
1177 }
1178
1179 /* Put the thread in the VCONT_RESUMED state. */
1180 void set_resumed ()
1181 {
1182 m_resume_state = resume_state::RESUMED;
1183 }
1184
1185 private:
1186 /* Resume state for this thread. This is used to implement vCont action
1187 coalescing (only when the target operates in non-stop mode).
1188
1189 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1190 which notes that this thread must be considered in the next commit_resume
1191 call.
1192
1193 remote_target::commit_resume sends a vCont packet with actions for the
1194 threads in the RESUMED_PENDING_VCONT state and moves them to the
1195 VCONT_RESUMED state.
1196
1197 When reporting a stop to the core for a thread, that thread is moved back
1198 to the NOT_RESUMED state. */
1199 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1200
1201 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1202 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1203 };
1204
1205 remote_state::remote_state ()
1206 : buf (400)
1207 {
1208 }
1209
1210 remote_state::~remote_state ()
1211 {
1212 xfree (this->last_pass_packet);
1213 xfree (this->last_program_signals_packet);
1214 xfree (this->finished_object);
1215 xfree (this->finished_annex);
1216 }
1217
1218 /* Utility: generate error from an incoming stub packet. */
1219 static void
1220 trace_error (char *buf)
1221 {
1222 if (*buf++ != 'E')
1223 return; /* not an error msg */
1224 switch (*buf)
1225 {
1226 case '1': /* malformed packet error */
1227 if (*++buf == '0') /* general case: */
1228 error (_("remote.c: error in outgoing packet."));
1229 else
1230 error (_("remote.c: error in outgoing packet at field #%ld."),
1231 strtol (buf, NULL, 16));
1232 default:
1233 error (_("Target returns error code '%s'."), buf);
1234 }
1235 }
1236
1237 /* Utility: wait for reply from stub, while accepting "O" packets. */
1238
1239 char *
1240 remote_target::remote_get_noisy_reply ()
1241 {
1242 struct remote_state *rs = get_remote_state ();
1243
1244 do /* Loop on reply from remote stub. */
1245 {
1246 char *buf;
1247
1248 QUIT; /* Allow user to bail out with ^C. */
1249 getpkt (&rs->buf, 0);
1250 buf = rs->buf.data ();
1251 if (buf[0] == 'E')
1252 trace_error (buf);
1253 else if (startswith (buf, "qRelocInsn:"))
1254 {
1255 ULONGEST ul;
1256 CORE_ADDR from, to, org_to;
1257 const char *p, *pp;
1258 int adjusted_size = 0;
1259 int relocated = 0;
1260
1261 p = buf + strlen ("qRelocInsn:");
1262 pp = unpack_varlen_hex (p, &ul);
1263 if (*pp != ';')
1264 error (_("invalid qRelocInsn packet: %s"), buf);
1265 from = ul;
1266
1267 p = pp + 1;
1268 unpack_varlen_hex (p, &ul);
1269 to = ul;
1270
1271 org_to = to;
1272
1273 try
1274 {
1275 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
1276 relocated = 1;
1277 }
1278 catch (const gdb_exception &ex)
1279 {
1280 if (ex.error == MEMORY_ERROR)
1281 {
1282 /* Propagate memory errors silently back to the
1283 target. The stub may have limited the range of
1284 addresses we can write to, for example. */
1285 }
1286 else
1287 {
1288 /* Something unexpectedly bad happened. Be verbose
1289 so we can tell what, and propagate the error back
1290 to the stub, so it doesn't get stuck waiting for
1291 a response. */
1292 exception_fprintf (gdb_stderr, ex,
1293 _("warning: relocating instruction: "));
1294 }
1295 putpkt ("E01");
1296 }
1297
1298 if (relocated)
1299 {
1300 adjusted_size = to - org_to;
1301
1302 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1303 putpkt (buf);
1304 }
1305 }
1306 else if (buf[0] == 'O' && buf[1] != 'K')
1307 remote_console_output (buf + 1); /* 'O' message from stub */
1308 else
1309 return buf; /* Here's the actual reply. */
1310 }
1311 while (1);
1312 }
1313
1314 struct remote_arch_state *
1315 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1316 {
1317 remote_arch_state *rsa;
1318
1319 auto it = this->m_arch_states.find (gdbarch);
1320 if (it == this->m_arch_states.end ())
1321 {
1322 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1323 std::forward_as_tuple (gdbarch),
1324 std::forward_as_tuple (gdbarch));
1325 rsa = &p.first->second;
1326
1327 /* Make sure that the packet buffer is plenty big enough for
1328 this architecture. */
1329 if (this->buf.size () < rsa->remote_packet_size)
1330 this->buf.resize (2 * rsa->remote_packet_size);
1331 }
1332 else
1333 rsa = &it->second;
1334
1335 return rsa;
1336 }
1337
1338 /* Fetch the global remote target state. */
1339
1340 remote_state *
1341 remote_target::get_remote_state ()
1342 {
1343 /* Make sure that the remote architecture state has been
1344 initialized, because doing so might reallocate rs->buf. Any
1345 function which calls getpkt also needs to be mindful of changes
1346 to rs->buf, but this call limits the number of places which run
1347 into trouble. */
1348 m_remote_state.get_remote_arch_state (target_gdbarch ());
1349
1350 return &m_remote_state;
1351 }
1352
1353 /* Fetch the remote exec-file from the current program space. */
1354
1355 static const char *
1356 get_remote_exec_file (void)
1357 {
1358 char *remote_exec_file;
1359
1360 remote_exec_file = remote_pspace_data.get (current_program_space);
1361 if (remote_exec_file == NULL)
1362 return "";
1363
1364 return remote_exec_file;
1365 }
1366
1367 /* Set the remote exec file for PSPACE. */
1368
1369 static void
1370 set_pspace_remote_exec_file (struct program_space *pspace,
1371 const char *remote_exec_file)
1372 {
1373 char *old_file = remote_pspace_data.get (pspace);
1374
1375 xfree (old_file);
1376 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1377 }
1378
1379 /* The "set/show remote exec-file" set command hook. */
1380
1381 static void
1382 set_remote_exec_file (const char *ignored, int from_tty,
1383 struct cmd_list_element *c)
1384 {
1385 set_pspace_remote_exec_file (current_program_space,
1386 remote_exec_file_var.c_str ());
1387 }
1388
1389 /* The "set/show remote exec-file" show command hook. */
1390
1391 static void
1392 show_remote_exec_file (struct ui_file *file, int from_tty,
1393 struct cmd_list_element *cmd, const char *value)
1394 {
1395 fprintf_filtered (file, "%s\n", get_remote_exec_file ());
1396 }
1397
1398 static int
1399 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1400 {
1401 int regnum, num_remote_regs, offset;
1402 struct packet_reg **remote_regs;
1403
1404 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1405 {
1406 struct packet_reg *r = &regs[regnum];
1407
1408 if (register_size (gdbarch, regnum) == 0)
1409 /* Do not try to fetch zero-sized (placeholder) registers. */
1410 r->pnum = -1;
1411 else
1412 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1413
1414 r->regnum = regnum;
1415 }
1416
1417 /* Define the g/G packet format as the contents of each register
1418 with a remote protocol number, in order of ascending protocol
1419 number. */
1420
1421 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1422 for (num_remote_regs = 0, regnum = 0;
1423 regnum < gdbarch_num_regs (gdbarch);
1424 regnum++)
1425 if (regs[regnum].pnum != -1)
1426 remote_regs[num_remote_regs++] = &regs[regnum];
1427
1428 std::sort (remote_regs, remote_regs + num_remote_regs,
1429 [] (const packet_reg *a, const packet_reg *b)
1430 { return a->pnum < b->pnum; });
1431
1432 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1433 {
1434 remote_regs[regnum]->in_g_packet = 1;
1435 remote_regs[regnum]->offset = offset;
1436 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1437 }
1438
1439 return offset;
1440 }
1441
1442 /* Given the architecture described by GDBARCH, return the remote
1443 protocol register's number and the register's offset in the g/G
1444 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1445 If the target does not have a mapping for REGNUM, return false,
1446 otherwise, return true. */
1447
1448 int
1449 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1450 int *pnum, int *poffset)
1451 {
1452 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1453
1454 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1455
1456 map_regcache_remote_table (gdbarch, regs.data ());
1457
1458 *pnum = regs[regnum].pnum;
1459 *poffset = regs[regnum].offset;
1460
1461 return *pnum != -1;
1462 }
1463
1464 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1465 {
1466 /* Use the architecture to build a regnum<->pnum table, which will be
1467 1:1 unless a feature set specifies otherwise. */
1468 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1469
1470 /* Record the maximum possible size of the g packet - it may turn out
1471 to be smaller. */
1472 this->sizeof_g_packet
1473 = map_regcache_remote_table (gdbarch, this->regs.get ());
1474
1475 /* Default maximum number of characters in a packet body. Many
1476 remote stubs have a hardwired buffer size of 400 bytes
1477 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1478 as the maximum packet-size to ensure that the packet and an extra
1479 NUL character can always fit in the buffer. This stops GDB
1480 trashing stubs that try to squeeze an extra NUL into what is
1481 already a full buffer (As of 1999-12-04 that was most stubs). */
1482 this->remote_packet_size = 400 - 1;
1483
1484 /* This one is filled in when a ``g'' packet is received. */
1485 this->actual_register_packet_size = 0;
1486
1487 /* Should rsa->sizeof_g_packet needs more space than the
1488 default, adjust the size accordingly. Remember that each byte is
1489 encoded as two characters. 32 is the overhead for the packet
1490 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1491 (``$NN:G...#NN'') is a better guess, the below has been padded a
1492 little. */
1493 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1494 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1495 }
1496
1497 /* Get a pointer to the current remote target. If not connected to a
1498 remote target, return NULL. */
1499
1500 static remote_target *
1501 get_current_remote_target ()
1502 {
1503 target_ops *proc_target = current_inferior ()->process_target ();
1504 return dynamic_cast<remote_target *> (proc_target);
1505 }
1506
1507 /* Return the current allowed size of a remote packet. This is
1508 inferred from the current architecture, and should be used to
1509 limit the length of outgoing packets. */
1510 long
1511 remote_target::get_remote_packet_size ()
1512 {
1513 struct remote_state *rs = get_remote_state ();
1514 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1515
1516 if (rs->explicit_packet_size)
1517 return rs->explicit_packet_size;
1518
1519 return rsa->remote_packet_size;
1520 }
1521
1522 static struct packet_reg *
1523 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1524 long regnum)
1525 {
1526 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1527 return NULL;
1528 else
1529 {
1530 struct packet_reg *r = &rsa->regs[regnum];
1531
1532 gdb_assert (r->regnum == regnum);
1533 return r;
1534 }
1535 }
1536
1537 static struct packet_reg *
1538 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1539 LONGEST pnum)
1540 {
1541 int i;
1542
1543 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1544 {
1545 struct packet_reg *r = &rsa->regs[i];
1546
1547 if (r->pnum == pnum)
1548 return r;
1549 }
1550 return NULL;
1551 }
1552
1553 /* Allow the user to specify what sequence to send to the remote
1554 when he requests a program interruption: Although ^C is usually
1555 what remote systems expect (this is the default, here), it is
1556 sometimes preferable to send a break. On other systems such
1557 as the Linux kernel, a break followed by g, which is Magic SysRq g
1558 is required in order to interrupt the execution. */
1559 const char interrupt_sequence_control_c[] = "Ctrl-C";
1560 const char interrupt_sequence_break[] = "BREAK";
1561 const char interrupt_sequence_break_g[] = "BREAK-g";
1562 static const char *const interrupt_sequence_modes[] =
1563 {
1564 interrupt_sequence_control_c,
1565 interrupt_sequence_break,
1566 interrupt_sequence_break_g,
1567 NULL
1568 };
1569 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1570
1571 static void
1572 show_interrupt_sequence (struct ui_file *file, int from_tty,
1573 struct cmd_list_element *c,
1574 const char *value)
1575 {
1576 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1577 fprintf_filtered (file,
1578 _("Send the ASCII ETX character (Ctrl-c) "
1579 "to the remote target to interrupt the "
1580 "execution of the program.\n"));
1581 else if (interrupt_sequence_mode == interrupt_sequence_break)
1582 fprintf_filtered (file,
1583 _("send a break signal to the remote target "
1584 "to interrupt the execution of the program.\n"));
1585 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1586 fprintf_filtered (file,
1587 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1588 "the remote target to interrupt the execution "
1589 "of Linux kernel.\n"));
1590 else
1591 internal_error (__FILE__, __LINE__,
1592 _("Invalid value for interrupt_sequence_mode: %s."),
1593 interrupt_sequence_mode);
1594 }
1595
1596 /* This boolean variable specifies whether interrupt_sequence is sent
1597 to the remote target when gdb connects to it.
1598 This is mostly needed when you debug the Linux kernel: The Linux kernel
1599 expects BREAK g which is Magic SysRq g for connecting gdb. */
1600 static bool interrupt_on_connect = false;
1601
1602 /* This variable is used to implement the "set/show remotebreak" commands.
1603 Since these commands are now deprecated in favor of "set/show remote
1604 interrupt-sequence", it no longer has any effect on the code. */
1605 static bool remote_break;
1606
1607 static void
1608 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1609 {
1610 if (remote_break)
1611 interrupt_sequence_mode = interrupt_sequence_break;
1612 else
1613 interrupt_sequence_mode = interrupt_sequence_control_c;
1614 }
1615
1616 static void
1617 show_remotebreak (struct ui_file *file, int from_tty,
1618 struct cmd_list_element *c,
1619 const char *value)
1620 {
1621 }
1622
1623 /* This variable sets the number of bits in an address that are to be
1624 sent in a memory ("M" or "m") packet. Normally, after stripping
1625 leading zeros, the entire address would be sent. This variable
1626 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1627 initial implementation of remote.c restricted the address sent in
1628 memory packets to ``host::sizeof long'' bytes - (typically 32
1629 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1630 address was never sent. Since fixing this bug may cause a break in
1631 some remote targets this variable is principally provided to
1632 facilitate backward compatibility. */
1633
1634 static unsigned int remote_address_size;
1635
1636 \f
1637 /* User configurable variables for the number of characters in a
1638 memory read/write packet. MIN (rsa->remote_packet_size,
1639 rsa->sizeof_g_packet) is the default. Some targets need smaller
1640 values (fifo overruns, et.al.) and some users need larger values
1641 (speed up transfers). The variables ``preferred_*'' (the user
1642 request), ``current_*'' (what was actually set) and ``forced_*''
1643 (Positive - a soft limit, negative - a hard limit). */
1644
1645 struct memory_packet_config
1646 {
1647 const char *name;
1648 long size;
1649 int fixed_p;
1650 };
1651
1652 /* The default max memory-write-packet-size, when the setting is
1653 "fixed". The 16k is historical. (It came from older GDB's using
1654 alloca for buffers and the knowledge (folklore?) that some hosts
1655 don't cope very well with large alloca calls.) */
1656 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1657
1658 /* The minimum remote packet size for memory transfers. Ensures we
1659 can write at least one byte. */
1660 #define MIN_MEMORY_PACKET_SIZE 20
1661
1662 /* Get the memory packet size, assuming it is fixed. */
1663
1664 static long
1665 get_fixed_memory_packet_size (struct memory_packet_config *config)
1666 {
1667 gdb_assert (config->fixed_p);
1668
1669 if (config->size <= 0)
1670 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1671 else
1672 return config->size;
1673 }
1674
1675 /* Compute the current size of a read/write packet. Since this makes
1676 use of ``actual_register_packet_size'' the computation is dynamic. */
1677
1678 long
1679 remote_target::get_memory_packet_size (struct memory_packet_config *config)
1680 {
1681 struct remote_state *rs = get_remote_state ();
1682 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1683
1684 long what_they_get;
1685 if (config->fixed_p)
1686 what_they_get = get_fixed_memory_packet_size (config);
1687 else
1688 {
1689 what_they_get = get_remote_packet_size ();
1690 /* Limit the packet to the size specified by the user. */
1691 if (config->size > 0
1692 && what_they_get > config->size)
1693 what_they_get = config->size;
1694
1695 /* Limit it to the size of the targets ``g'' response unless we have
1696 permission from the stub to use a larger packet size. */
1697 if (rs->explicit_packet_size == 0
1698 && rsa->actual_register_packet_size > 0
1699 && what_they_get > rsa->actual_register_packet_size)
1700 what_they_get = rsa->actual_register_packet_size;
1701 }
1702 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1703 what_they_get = MIN_MEMORY_PACKET_SIZE;
1704
1705 /* Make sure there is room in the global buffer for this packet
1706 (including its trailing NUL byte). */
1707 if (rs->buf.size () < what_they_get + 1)
1708 rs->buf.resize (2 * what_they_get);
1709
1710 return what_they_get;
1711 }
1712
1713 /* Update the size of a read/write packet. If they user wants
1714 something really big then do a sanity check. */
1715
1716 static void
1717 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1718 {
1719 int fixed_p = config->fixed_p;
1720 long size = config->size;
1721
1722 if (args == NULL)
1723 error (_("Argument required (integer, `fixed' or `limited')."));
1724 else if (strcmp (args, "hard") == 0
1725 || strcmp (args, "fixed") == 0)
1726 fixed_p = 1;
1727 else if (strcmp (args, "soft") == 0
1728 || strcmp (args, "limit") == 0)
1729 fixed_p = 0;
1730 else
1731 {
1732 char *end;
1733
1734 size = strtoul (args, &end, 0);
1735 if (args == end)
1736 error (_("Invalid %s (bad syntax)."), config->name);
1737
1738 /* Instead of explicitly capping the size of a packet to or
1739 disallowing it, the user is allowed to set the size to
1740 something arbitrarily large. */
1741 }
1742
1743 /* Extra checks? */
1744 if (fixed_p && !config->fixed_p)
1745 {
1746 /* So that the query shows the correct value. */
1747 long query_size = (size <= 0
1748 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1749 : size);
1750
1751 if (! query (_("The target may not be able to correctly handle a %s\n"
1752 "of %ld bytes. Change the packet size? "),
1753 config->name, query_size))
1754 error (_("Packet size not changed."));
1755 }
1756 /* Update the config. */
1757 config->fixed_p = fixed_p;
1758 config->size = size;
1759 }
1760
1761 static void
1762 show_memory_packet_size (struct memory_packet_config *config)
1763 {
1764 if (config->size == 0)
1765 printf_filtered (_("The %s is 0 (default). "), config->name);
1766 else
1767 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1768 if (config->fixed_p)
1769 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1770 get_fixed_memory_packet_size (config));
1771 else
1772 {
1773 remote_target *remote = get_current_remote_target ();
1774
1775 if (remote != NULL)
1776 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1777 remote->get_memory_packet_size (config));
1778 else
1779 puts_filtered ("The actual limit will be further reduced "
1780 "dependent on the target.\n");
1781 }
1782 }
1783
1784 /* FIXME: needs to be per-remote-target. */
1785 static struct memory_packet_config memory_write_packet_config =
1786 {
1787 "memory-write-packet-size",
1788 };
1789
1790 static void
1791 set_memory_write_packet_size (const char *args, int from_tty)
1792 {
1793 set_memory_packet_size (args, &memory_write_packet_config);
1794 }
1795
1796 static void
1797 show_memory_write_packet_size (const char *args, int from_tty)
1798 {
1799 show_memory_packet_size (&memory_write_packet_config);
1800 }
1801
1802 /* Show the number of hardware watchpoints that can be used. */
1803
1804 static void
1805 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
1806 struct cmd_list_element *c,
1807 const char *value)
1808 {
1809 fprintf_filtered (file, _("The maximum number of target hardware "
1810 "watchpoints is %s.\n"), value);
1811 }
1812
1813 /* Show the length limit (in bytes) for hardware watchpoints. */
1814
1815 static void
1816 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
1817 struct cmd_list_element *c,
1818 const char *value)
1819 {
1820 fprintf_filtered (file, _("The maximum length (in bytes) of a target "
1821 "hardware watchpoint is %s.\n"), value);
1822 }
1823
1824 /* Show the number of hardware breakpoints that can be used. */
1825
1826 static void
1827 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
1828 struct cmd_list_element *c,
1829 const char *value)
1830 {
1831 fprintf_filtered (file, _("The maximum number of target hardware "
1832 "breakpoints is %s.\n"), value);
1833 }
1834
1835 /* Controls the maximum number of characters to display in the debug output
1836 for each remote packet. The remaining characters are omitted. */
1837
1838 static int remote_packet_max_chars = 512;
1839
1840 /* Show the maximum number of characters to display for each remote packet
1841 when remote debugging is enabled. */
1842
1843 static void
1844 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
1845 struct cmd_list_element *c,
1846 const char *value)
1847 {
1848 fprintf_filtered (file, _("Number of remote packet characters to "
1849 "display is %s.\n"), value);
1850 }
1851
1852 long
1853 remote_target::get_memory_write_packet_size ()
1854 {
1855 return get_memory_packet_size (&memory_write_packet_config);
1856 }
1857
1858 /* FIXME: needs to be per-remote-target. */
1859 static struct memory_packet_config memory_read_packet_config =
1860 {
1861 "memory-read-packet-size",
1862 };
1863
1864 static void
1865 set_memory_read_packet_size (const char *args, int from_tty)
1866 {
1867 set_memory_packet_size (args, &memory_read_packet_config);
1868 }
1869
1870 static void
1871 show_memory_read_packet_size (const char *args, int from_tty)
1872 {
1873 show_memory_packet_size (&memory_read_packet_config);
1874 }
1875
1876 long
1877 remote_target::get_memory_read_packet_size ()
1878 {
1879 long size = get_memory_packet_size (&memory_read_packet_config);
1880
1881 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1882 extra buffer size argument before the memory read size can be
1883 increased beyond this. */
1884 if (size > get_remote_packet_size ())
1885 size = get_remote_packet_size ();
1886 return size;
1887 }
1888
1889 \f
1890
1891 struct packet_config
1892 {
1893 const char *name;
1894 const char *title;
1895
1896 /* If auto, GDB auto-detects support for this packet or feature,
1897 either through qSupported, or by trying the packet and looking
1898 at the response. If true, GDB assumes the target supports this
1899 packet. If false, the packet is disabled. Configs that don't
1900 have an associated command always have this set to auto. */
1901 enum auto_boolean detect;
1902
1903 /* The "show remote foo-packet" command created for this packet. */
1904 cmd_list_element *show_cmd;
1905
1906 /* Does the target support this packet? */
1907 enum packet_support support;
1908 };
1909
1910 static enum packet_support packet_config_support (struct packet_config *config);
1911 static enum packet_support packet_support (int packet);
1912
1913 static void
1914 show_packet_config_cmd (ui_file *file, struct packet_config *config)
1915 {
1916 const char *support = "internal-error";
1917
1918 switch (packet_config_support (config))
1919 {
1920 case PACKET_ENABLE:
1921 support = "enabled";
1922 break;
1923 case PACKET_DISABLE:
1924 support = "disabled";
1925 break;
1926 case PACKET_SUPPORT_UNKNOWN:
1927 support = "unknown";
1928 break;
1929 }
1930 switch (config->detect)
1931 {
1932 case AUTO_BOOLEAN_AUTO:
1933 fprintf_filtered (file,
1934 _("Support for the `%s' packet "
1935 "is auto-detected, currently %s.\n"),
1936 config->name, support);
1937 break;
1938 case AUTO_BOOLEAN_TRUE:
1939 case AUTO_BOOLEAN_FALSE:
1940 fprintf_filtered (file,
1941 _("Support for the `%s' packet is currently %s.\n"),
1942 config->name, support);
1943 break;
1944 }
1945 }
1946
1947 static void
1948 add_packet_config_cmd (struct packet_config *config, const char *name,
1949 const char *title, int legacy)
1950 {
1951 config->name = name;
1952 config->title = title;
1953 gdb::unique_xmalloc_ptr<char> set_doc
1954 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
1955 name, title);
1956 gdb::unique_xmalloc_ptr<char> show_doc
1957 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
1958 name, title);
1959 /* set/show TITLE-packet {auto,on,off} */
1960 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
1961 set_show_commands cmds
1962 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
1963 &config->detect, set_doc.get (),
1964 show_doc.get (), NULL, /* help_doc */
1965 NULL,
1966 show_remote_protocol_packet_cmd,
1967 &remote_set_cmdlist, &remote_show_cmdlist);
1968 config->show_cmd = cmds.show;
1969
1970 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1971 if (legacy)
1972 {
1973 /* It's not clear who should take ownership of this string, so, for
1974 now, make it static, and give copies to each of the add_alias_cmd
1975 calls below. */
1976 static gdb::unique_xmalloc_ptr<char> legacy_name
1977 = xstrprintf ("%s-packet", name);
1978 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
1979 &remote_set_cmdlist);
1980 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
1981 &remote_show_cmdlist);
1982 }
1983 }
1984
1985 static enum packet_result
1986 packet_check_result (const char *buf)
1987 {
1988 if (buf[0] != '\0')
1989 {
1990 /* The stub recognized the packet request. Check that the
1991 operation succeeded. */
1992 if (buf[0] == 'E'
1993 && isxdigit (buf[1]) && isxdigit (buf[2])
1994 && buf[3] == '\0')
1995 /* "Enn" - definitely an error. */
1996 return PACKET_ERROR;
1997
1998 /* Always treat "E." as an error. This will be used for
1999 more verbose error messages, such as E.memtypes. */
2000 if (buf[0] == 'E' && buf[1] == '.')
2001 return PACKET_ERROR;
2002
2003 /* The packet may or may not be OK. Just assume it is. */
2004 return PACKET_OK;
2005 }
2006 else
2007 /* The stub does not support the packet. */
2008 return PACKET_UNKNOWN;
2009 }
2010
2011 static enum packet_result
2012 packet_check_result (const gdb::char_vector &buf)
2013 {
2014 return packet_check_result (buf.data ());
2015 }
2016
2017 static enum packet_result
2018 packet_ok (const char *buf, struct packet_config *config)
2019 {
2020 enum packet_result result;
2021
2022 if (config->detect != AUTO_BOOLEAN_TRUE
2023 && config->support == PACKET_DISABLE)
2024 internal_error (__FILE__, __LINE__,
2025 _("packet_ok: attempt to use a disabled packet"));
2026
2027 result = packet_check_result (buf);
2028 switch (result)
2029 {
2030 case PACKET_OK:
2031 case PACKET_ERROR:
2032 /* The stub recognized the packet request. */
2033 if (config->support == PACKET_SUPPORT_UNKNOWN)
2034 {
2035 remote_debug_printf ("Packet %s (%s) is supported",
2036 config->name, config->title);
2037 config->support = PACKET_ENABLE;
2038 }
2039 break;
2040 case PACKET_UNKNOWN:
2041 /* The stub does not support the packet. */
2042 if (config->detect == AUTO_BOOLEAN_AUTO
2043 && config->support == PACKET_ENABLE)
2044 {
2045 /* If the stub previously indicated that the packet was
2046 supported then there is a protocol error. */
2047 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2048 config->name, config->title);
2049 }
2050 else if (config->detect == AUTO_BOOLEAN_TRUE)
2051 {
2052 /* The user set it wrong. */
2053 error (_("Enabled packet %s (%s) not recognized by stub"),
2054 config->name, config->title);
2055 }
2056
2057 remote_debug_printf ("Packet %s (%s) is NOT supported",
2058 config->name, config->title);
2059 config->support = PACKET_DISABLE;
2060 break;
2061 }
2062
2063 return result;
2064 }
2065
2066 static enum packet_result
2067 packet_ok (const gdb::char_vector &buf, struct packet_config *config)
2068 {
2069 return packet_ok (buf.data (), config);
2070 }
2071
2072 enum {
2073 PACKET_vCont = 0,
2074 PACKET_X,
2075 PACKET_qSymbol,
2076 PACKET_P,
2077 PACKET_p,
2078 PACKET_Z0,
2079 PACKET_Z1,
2080 PACKET_Z2,
2081 PACKET_Z3,
2082 PACKET_Z4,
2083 PACKET_vFile_setfs,
2084 PACKET_vFile_open,
2085 PACKET_vFile_pread,
2086 PACKET_vFile_pwrite,
2087 PACKET_vFile_close,
2088 PACKET_vFile_unlink,
2089 PACKET_vFile_readlink,
2090 PACKET_vFile_fstat,
2091 PACKET_qXfer_auxv,
2092 PACKET_qXfer_features,
2093 PACKET_qXfer_exec_file,
2094 PACKET_qXfer_libraries,
2095 PACKET_qXfer_libraries_svr4,
2096 PACKET_qXfer_memory_map,
2097 PACKET_qXfer_osdata,
2098 PACKET_qXfer_threads,
2099 PACKET_qXfer_statictrace_read,
2100 PACKET_qXfer_traceframe_info,
2101 PACKET_qXfer_uib,
2102 PACKET_qGetTIBAddr,
2103 PACKET_qGetTLSAddr,
2104 PACKET_qSupported,
2105 PACKET_qTStatus,
2106 PACKET_QPassSignals,
2107 PACKET_QCatchSyscalls,
2108 PACKET_QProgramSignals,
2109 PACKET_QSetWorkingDir,
2110 PACKET_QStartupWithShell,
2111 PACKET_QEnvironmentHexEncoded,
2112 PACKET_QEnvironmentReset,
2113 PACKET_QEnvironmentUnset,
2114 PACKET_qCRC,
2115 PACKET_qSearch_memory,
2116 PACKET_vAttach,
2117 PACKET_vRun,
2118 PACKET_QStartNoAckMode,
2119 PACKET_vKill,
2120 PACKET_qXfer_siginfo_read,
2121 PACKET_qXfer_siginfo_write,
2122 PACKET_qAttached,
2123
2124 /* Support for conditional tracepoints. */
2125 PACKET_ConditionalTracepoints,
2126
2127 /* Support for target-side breakpoint conditions. */
2128 PACKET_ConditionalBreakpoints,
2129
2130 /* Support for target-side breakpoint commands. */
2131 PACKET_BreakpointCommands,
2132
2133 /* Support for fast tracepoints. */
2134 PACKET_FastTracepoints,
2135
2136 /* Support for static tracepoints. */
2137 PACKET_StaticTracepoints,
2138
2139 /* Support for installing tracepoints while a trace experiment is
2140 running. */
2141 PACKET_InstallInTrace,
2142
2143 PACKET_bc,
2144 PACKET_bs,
2145 PACKET_TracepointSource,
2146 PACKET_QAllow,
2147 PACKET_qXfer_fdpic,
2148 PACKET_QDisableRandomization,
2149 PACKET_QAgent,
2150 PACKET_QTBuffer_size,
2151 PACKET_Qbtrace_off,
2152 PACKET_Qbtrace_bts,
2153 PACKET_Qbtrace_pt,
2154 PACKET_qXfer_btrace,
2155
2156 /* Support for the QNonStop packet. */
2157 PACKET_QNonStop,
2158
2159 /* Support for the QThreadEvents packet. */
2160 PACKET_QThreadEvents,
2161
2162 /* Support for multi-process extensions. */
2163 PACKET_multiprocess_feature,
2164
2165 /* Support for enabling and disabling tracepoints while a trace
2166 experiment is running. */
2167 PACKET_EnableDisableTracepoints_feature,
2168
2169 /* Support for collecting strings using the tracenz bytecode. */
2170 PACKET_tracenz_feature,
2171
2172 /* Support for continuing to run a trace experiment while GDB is
2173 disconnected. */
2174 PACKET_DisconnectedTracing_feature,
2175
2176 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2177 PACKET_augmented_libraries_svr4_read_feature,
2178
2179 /* Support for the qXfer:btrace-conf:read packet. */
2180 PACKET_qXfer_btrace_conf,
2181
2182 /* Support for the Qbtrace-conf:bts:size packet. */
2183 PACKET_Qbtrace_conf_bts_size,
2184
2185 /* Support for swbreak+ feature. */
2186 PACKET_swbreak_feature,
2187
2188 /* Support for hwbreak+ feature. */
2189 PACKET_hwbreak_feature,
2190
2191 /* Support for fork events. */
2192 PACKET_fork_event_feature,
2193
2194 /* Support for vfork events. */
2195 PACKET_vfork_event_feature,
2196
2197 /* Support for the Qbtrace-conf:pt:size packet. */
2198 PACKET_Qbtrace_conf_pt_size,
2199
2200 /* Support for exec events. */
2201 PACKET_exec_event_feature,
2202
2203 /* Support for query supported vCont actions. */
2204 PACKET_vContSupported,
2205
2206 /* Support remote CTRL-C. */
2207 PACKET_vCtrlC,
2208
2209 /* Support TARGET_WAITKIND_NO_RESUMED. */
2210 PACKET_no_resumed,
2211
2212 /* Support for memory tagging, allocation tag fetch/store
2213 packets and the tag violation stop replies. */
2214 PACKET_memory_tagging_feature,
2215
2216 PACKET_MAX
2217 };
2218
2219 /* FIXME: needs to be per-remote-target. Ignoring this for now,
2220 assuming all remote targets are the same server (thus all support
2221 the same packets). */
2222 static struct packet_config remote_protocol_packets[PACKET_MAX];
2223
2224 /* Returns the packet's corresponding "set remote foo-packet" command
2225 state. See struct packet_config for more details. */
2226
2227 static enum auto_boolean
2228 packet_set_cmd_state (int packet)
2229 {
2230 return remote_protocol_packets[packet].detect;
2231 }
2232
2233 /* Returns whether a given packet or feature is supported. This takes
2234 into account the state of the corresponding "set remote foo-packet"
2235 command, which may be used to bypass auto-detection. */
2236
2237 static enum packet_support
2238 packet_config_support (struct packet_config *config)
2239 {
2240 switch (config->detect)
2241 {
2242 case AUTO_BOOLEAN_TRUE:
2243 return PACKET_ENABLE;
2244 case AUTO_BOOLEAN_FALSE:
2245 return PACKET_DISABLE;
2246 case AUTO_BOOLEAN_AUTO:
2247 return config->support;
2248 default:
2249 gdb_assert_not_reached ("bad switch");
2250 }
2251 }
2252
2253 /* Same as packet_config_support, but takes the packet's enum value as
2254 argument. */
2255
2256 static enum packet_support
2257 packet_support (int packet)
2258 {
2259 struct packet_config *config = &remote_protocol_packets[packet];
2260
2261 return packet_config_support (config);
2262 }
2263
2264 static void
2265 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2266 struct cmd_list_element *c,
2267 const char *value)
2268 {
2269 struct packet_config *packet;
2270 gdb_assert (c->var.has_value ());
2271
2272 for (packet = remote_protocol_packets;
2273 packet < &remote_protocol_packets[PACKET_MAX];
2274 packet++)
2275 {
2276 if (c == packet->show_cmd)
2277 {
2278 show_packet_config_cmd (file, packet);
2279 return;
2280 }
2281 }
2282 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
2283 c->name);
2284 }
2285
2286 /* Should we try one of the 'Z' requests? */
2287
2288 enum Z_packet_type
2289 {
2290 Z_PACKET_SOFTWARE_BP,
2291 Z_PACKET_HARDWARE_BP,
2292 Z_PACKET_WRITE_WP,
2293 Z_PACKET_READ_WP,
2294 Z_PACKET_ACCESS_WP,
2295 NR_Z_PACKET_TYPES
2296 };
2297
2298 /* For compatibility with older distributions. Provide a ``set remote
2299 Z-packet ...'' command that updates all the Z packet types. */
2300
2301 static enum auto_boolean remote_Z_packet_detect;
2302
2303 static void
2304 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2305 struct cmd_list_element *c)
2306 {
2307 int i;
2308
2309 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2310 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2311 }
2312
2313 static void
2314 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2315 struct cmd_list_element *c,
2316 const char *value)
2317 {
2318 int i;
2319
2320 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2321 {
2322 show_packet_config_cmd (file, &remote_protocol_packets[PACKET_Z0 + i]);
2323 }
2324 }
2325
2326 /* Returns true if the multi-process extensions are in effect. */
2327
2328 static int
2329 remote_multi_process_p (struct remote_state *rs)
2330 {
2331 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2332 }
2333
2334 /* Returns true if fork events are supported. */
2335
2336 static int
2337 remote_fork_event_p (struct remote_state *rs)
2338 {
2339 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2340 }
2341
2342 /* Returns true if vfork events are supported. */
2343
2344 static int
2345 remote_vfork_event_p (struct remote_state *rs)
2346 {
2347 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2348 }
2349
2350 /* Returns true if exec events are supported. */
2351
2352 static int
2353 remote_exec_event_p (struct remote_state *rs)
2354 {
2355 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2356 }
2357
2358 /* Returns true if memory tagging is supported, false otherwise. */
2359
2360 static bool
2361 remote_memory_tagging_p ()
2362 {
2363 return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE;
2364 }
2365
2366 /* Insert fork catchpoint target routine. If fork events are enabled
2367 then return success, nothing more to do. */
2368
2369 int
2370 remote_target::insert_fork_catchpoint (int pid)
2371 {
2372 struct remote_state *rs = get_remote_state ();
2373
2374 return !remote_fork_event_p (rs);
2375 }
2376
2377 /* Remove fork catchpoint target routine. Nothing to do, just
2378 return success. */
2379
2380 int
2381 remote_target::remove_fork_catchpoint (int pid)
2382 {
2383 return 0;
2384 }
2385
2386 /* Insert vfork catchpoint target routine. If vfork events are enabled
2387 then return success, nothing more to do. */
2388
2389 int
2390 remote_target::insert_vfork_catchpoint (int pid)
2391 {
2392 struct remote_state *rs = get_remote_state ();
2393
2394 return !remote_vfork_event_p (rs);
2395 }
2396
2397 /* Remove vfork catchpoint target routine. Nothing to do, just
2398 return success. */
2399
2400 int
2401 remote_target::remove_vfork_catchpoint (int pid)
2402 {
2403 return 0;
2404 }
2405
2406 /* Insert exec catchpoint target routine. If exec events are
2407 enabled, just return success. */
2408
2409 int
2410 remote_target::insert_exec_catchpoint (int pid)
2411 {
2412 struct remote_state *rs = get_remote_state ();
2413
2414 return !remote_exec_event_p (rs);
2415 }
2416
2417 /* Remove exec catchpoint target routine. Nothing to do, just
2418 return success. */
2419
2420 int
2421 remote_target::remove_exec_catchpoint (int pid)
2422 {
2423 return 0;
2424 }
2425
2426 \f
2427
2428 /* Take advantage of the fact that the TID field is not used, to tag
2429 special ptids with it set to != 0. */
2430 static const ptid_t magic_null_ptid (42000, -1, 1);
2431 static const ptid_t not_sent_ptid (42000, -2, 1);
2432 static const ptid_t any_thread_ptid (42000, 0, 1);
2433
2434 /* Find out if the stub attached to PID (and hence GDB should offer to
2435 detach instead of killing it when bailing out). */
2436
2437 int
2438 remote_target::remote_query_attached (int pid)
2439 {
2440 struct remote_state *rs = get_remote_state ();
2441 size_t size = get_remote_packet_size ();
2442
2443 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2444 return 0;
2445
2446 if (remote_multi_process_p (rs))
2447 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2448 else
2449 xsnprintf (rs->buf.data (), size, "qAttached");
2450
2451 putpkt (rs->buf);
2452 getpkt (&rs->buf, 0);
2453
2454 switch (packet_ok (rs->buf,
2455 &remote_protocol_packets[PACKET_qAttached]))
2456 {
2457 case PACKET_OK:
2458 if (strcmp (rs->buf.data (), "1") == 0)
2459 return 1;
2460 break;
2461 case PACKET_ERROR:
2462 warning (_("Remote failure reply: %s"), rs->buf.data ());
2463 break;
2464 case PACKET_UNKNOWN:
2465 break;
2466 }
2467
2468 return 0;
2469 }
2470
2471 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2472 has been invented by GDB, instead of reported by the target. Since
2473 we can be connected to a remote system before before knowing about
2474 any inferior, mark the target with execution when we find the first
2475 inferior. If ATTACHED is 1, then we had just attached to this
2476 inferior. If it is 0, then we just created this inferior. If it
2477 is -1, then try querying the remote stub to find out if it had
2478 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2479 attempt to open this inferior's executable as the main executable
2480 if no main executable is open already. */
2481
2482 inferior *
2483 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2484 int try_open_exec)
2485 {
2486 struct inferior *inf;
2487
2488 /* Check whether this process we're learning about is to be
2489 considered attached, or if is to be considered to have been
2490 spawned by the stub. */
2491 if (attached == -1)
2492 attached = remote_query_attached (pid);
2493
2494 if (gdbarch_has_global_solist (target_gdbarch ()))
2495 {
2496 /* If the target shares code across all inferiors, then every
2497 attach adds a new inferior. */
2498 inf = add_inferior (pid);
2499
2500 /* ... and every inferior is bound to the same program space.
2501 However, each inferior may still have its own address
2502 space. */
2503 inf->aspace = maybe_new_address_space ();
2504 inf->pspace = current_program_space;
2505 }
2506 else
2507 {
2508 /* In the traditional debugging scenario, there's a 1-1 match
2509 between program/address spaces. We simply bind the inferior
2510 to the program space's address space. */
2511 inf = current_inferior ();
2512
2513 /* However, if the current inferior is already bound to a
2514 process, find some other empty inferior. */
2515 if (inf->pid != 0)
2516 {
2517 inf = nullptr;
2518 for (inferior *it : all_inferiors ())
2519 if (it->pid == 0)
2520 {
2521 inf = it;
2522 break;
2523 }
2524 }
2525 if (inf == nullptr)
2526 {
2527 /* Since all inferiors were already bound to a process, add
2528 a new inferior. */
2529 inf = add_inferior_with_spaces ();
2530 }
2531 switch_to_inferior_no_thread (inf);
2532 inf->push_target (this);
2533 inferior_appeared (inf, pid);
2534 }
2535
2536 inf->attach_flag = attached;
2537 inf->fake_pid_p = fake_pid_p;
2538
2539 /* If no main executable is currently open then attempt to
2540 open the file that was executed to create this inferior. */
2541 if (try_open_exec && get_exec_file (0) == NULL)
2542 exec_file_locate_attach (pid, 0, 1);
2543
2544 /* Check for exec file mismatch, and let the user solve it. */
2545 validate_exec_file (1);
2546
2547 return inf;
2548 }
2549
2550 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2551 static remote_thread_info *get_remote_thread_info (remote_target *target,
2552 ptid_t ptid);
2553
2554 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2555 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2556 remote_state::starting_up flag) is true then the new thread is added
2557 silently, otherwise the new thread will be announced to the user. */
2558
2559 thread_info *
2560 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2561 bool silent_p)
2562 {
2563 struct remote_state *rs = get_remote_state ();
2564 struct thread_info *thread;
2565
2566 /* GDB historically didn't pull threads in the initial connection
2567 setup. If the remote target doesn't even have a concept of
2568 threads (e.g., a bare-metal target), even if internally we
2569 consider that a single-threaded target, mentioning a new thread
2570 might be confusing to the user. Be silent then, preserving the
2571 age old behavior. */
2572 if (rs->starting_up || silent_p)
2573 thread = add_thread_silent (this, ptid);
2574 else
2575 thread = add_thread (this, ptid);
2576
2577 /* We start by assuming threads are resumed. That state then gets updated
2578 when we process a matching stop reply. */
2579 get_remote_thread_info (thread)->set_resumed ();
2580
2581 set_executing (this, ptid, executing);
2582 set_running (this, ptid, running);
2583
2584 return thread;
2585 }
2586
2587 /* Come here when we learn about a thread id from the remote target.
2588 It may be the first time we hear about such thread, so take the
2589 opportunity to add it to GDB's thread list. In case this is the
2590 first time we're noticing its corresponding inferior, add it to
2591 GDB's inferior list as well. EXECUTING indicates whether the
2592 thread is (internally) executing or stopped. */
2593
2594 void
2595 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2596 {
2597 /* In non-stop mode, we assume new found threads are (externally)
2598 running until proven otherwise with a stop reply. In all-stop,
2599 we can only get here if all threads are stopped. */
2600 bool running = target_is_non_stop_p ();
2601
2602 /* If this is a new thread, add it to GDB's thread list.
2603 If we leave it up to WFI to do this, bad things will happen. */
2604
2605 thread_info *tp = find_thread_ptid (this, currthread);
2606 if (tp != NULL && tp->state == THREAD_EXITED)
2607 {
2608 /* We're seeing an event on a thread id we knew had exited.
2609 This has to be a new thread reusing the old id. Add it. */
2610 remote_add_thread (currthread, running, executing, false);
2611 return;
2612 }
2613
2614 if (!in_thread_list (this, currthread))
2615 {
2616 struct inferior *inf = NULL;
2617 int pid = currthread.pid ();
2618
2619 if (inferior_ptid.is_pid ()
2620 && pid == inferior_ptid.pid ())
2621 {
2622 /* inferior_ptid has no thread member yet. This can happen
2623 with the vAttach -> remote_wait,"TAAthread:" path if the
2624 stub doesn't support qC. This is the first stop reported
2625 after an attach, so this is the main thread. Update the
2626 ptid in the thread list. */
2627 if (in_thread_list (this, ptid_t (pid)))
2628 thread_change_ptid (this, inferior_ptid, currthread);
2629 else
2630 {
2631 thread_info *thr
2632 = remote_add_thread (currthread, running, executing, false);
2633 switch_to_thread (thr);
2634 }
2635 return;
2636 }
2637
2638 if (magic_null_ptid == inferior_ptid)
2639 {
2640 /* inferior_ptid is not set yet. This can happen with the
2641 vRun -> remote_wait,"TAAthread:" path if the stub
2642 doesn't support qC. This is the first stop reported
2643 after an attach, so this is the main thread. Update the
2644 ptid in the thread list. */
2645 thread_change_ptid (this, inferior_ptid, currthread);
2646 return;
2647 }
2648
2649 /* When connecting to a target remote, or to a target
2650 extended-remote which already was debugging an inferior, we
2651 may not know about it yet. Add it before adding its child
2652 thread, so notifications are emitted in a sensible order. */
2653 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2654 {
2655 struct remote_state *rs = get_remote_state ();
2656 bool fake_pid_p = !remote_multi_process_p (rs);
2657
2658 inf = remote_add_inferior (fake_pid_p,
2659 currthread.pid (), -1, 1);
2660 }
2661
2662 /* This is really a new thread. Add it. */
2663 thread_info *new_thr
2664 = remote_add_thread (currthread, running, executing, false);
2665
2666 /* If we found a new inferior, let the common code do whatever
2667 it needs to with it (e.g., read shared libraries, insert
2668 breakpoints), unless we're just setting up an all-stop
2669 connection. */
2670 if (inf != NULL)
2671 {
2672 struct remote_state *rs = get_remote_state ();
2673
2674 if (!rs->starting_up)
2675 notice_new_inferior (new_thr, executing, 0);
2676 }
2677 }
2678 }
2679
2680 /* Return THREAD's private thread data, creating it if necessary. */
2681
2682 static remote_thread_info *
2683 get_remote_thread_info (thread_info *thread)
2684 {
2685 gdb_assert (thread != NULL);
2686
2687 if (thread->priv == NULL)
2688 thread->priv.reset (new remote_thread_info);
2689
2690 return static_cast<remote_thread_info *> (thread->priv.get ());
2691 }
2692
2693 /* Return PTID's private thread data, creating it if necessary. */
2694
2695 static remote_thread_info *
2696 get_remote_thread_info (remote_target *target, ptid_t ptid)
2697 {
2698 thread_info *thr = find_thread_ptid (target, ptid);
2699 return get_remote_thread_info (thr);
2700 }
2701
2702 /* Call this function as a result of
2703 1) A halt indication (T packet) containing a thread id
2704 2) A direct query of currthread
2705 3) Successful execution of set thread */
2706
2707 static void
2708 record_currthread (struct remote_state *rs, ptid_t currthread)
2709 {
2710 rs->general_thread = currthread;
2711 }
2712
2713 /* If 'QPassSignals' is supported, tell the remote stub what signals
2714 it can simply pass through to the inferior without reporting. */
2715
2716 void
2717 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2718 {
2719 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2720 {
2721 char *pass_packet, *p;
2722 int count = 0;
2723 struct remote_state *rs = get_remote_state ();
2724
2725 gdb_assert (pass_signals.size () < 256);
2726 for (size_t i = 0; i < pass_signals.size (); i++)
2727 {
2728 if (pass_signals[i])
2729 count++;
2730 }
2731 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2732 strcpy (pass_packet, "QPassSignals:");
2733 p = pass_packet + strlen (pass_packet);
2734 for (size_t i = 0; i < pass_signals.size (); i++)
2735 {
2736 if (pass_signals[i])
2737 {
2738 if (i >= 16)
2739 *p++ = tohex (i >> 4);
2740 *p++ = tohex (i & 15);
2741 if (count)
2742 *p++ = ';';
2743 else
2744 break;
2745 count--;
2746 }
2747 }
2748 *p = 0;
2749 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2750 {
2751 putpkt (pass_packet);
2752 getpkt (&rs->buf, 0);
2753 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2754 xfree (rs->last_pass_packet);
2755 rs->last_pass_packet = pass_packet;
2756 }
2757 else
2758 xfree (pass_packet);
2759 }
2760 }
2761
2762 /* If 'QCatchSyscalls' is supported, tell the remote stub
2763 to report syscalls to GDB. */
2764
2765 int
2766 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2767 gdb::array_view<const int> syscall_counts)
2768 {
2769 const char *catch_packet;
2770 enum packet_result result;
2771 int n_sysno = 0;
2772
2773 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2774 {
2775 /* Not supported. */
2776 return 1;
2777 }
2778
2779 if (needed && any_count == 0)
2780 {
2781 /* Count how many syscalls are to be caught. */
2782 for (size_t i = 0; i < syscall_counts.size (); i++)
2783 {
2784 if (syscall_counts[i] != 0)
2785 n_sysno++;
2786 }
2787 }
2788
2789 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
2790 pid, needed, any_count, n_sysno);
2791
2792 std::string built_packet;
2793 if (needed)
2794 {
2795 /* Prepare a packet with the sysno list, assuming max 8+1
2796 characters for a sysno. If the resulting packet size is too
2797 big, fallback on the non-selective packet. */
2798 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2799 built_packet.reserve (maxpktsz);
2800 built_packet = "QCatchSyscalls:1";
2801 if (any_count == 0)
2802 {
2803 /* Add in each syscall to be caught. */
2804 for (size_t i = 0; i < syscall_counts.size (); i++)
2805 {
2806 if (syscall_counts[i] != 0)
2807 string_appendf (built_packet, ";%zx", i);
2808 }
2809 }
2810 if (built_packet.size () > get_remote_packet_size ())
2811 {
2812 /* catch_packet too big. Fallback to less efficient
2813 non selective mode, with GDB doing the filtering. */
2814 catch_packet = "QCatchSyscalls:1";
2815 }
2816 else
2817 catch_packet = built_packet.c_str ();
2818 }
2819 else
2820 catch_packet = "QCatchSyscalls:0";
2821
2822 struct remote_state *rs = get_remote_state ();
2823
2824 putpkt (catch_packet);
2825 getpkt (&rs->buf, 0);
2826 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2827 if (result == PACKET_OK)
2828 return 0;
2829 else
2830 return -1;
2831 }
2832
2833 /* If 'QProgramSignals' is supported, tell the remote stub what
2834 signals it should pass through to the inferior when detaching. */
2835
2836 void
2837 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
2838 {
2839 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2840 {
2841 char *packet, *p;
2842 int count = 0;
2843 struct remote_state *rs = get_remote_state ();
2844
2845 gdb_assert (signals.size () < 256);
2846 for (size_t i = 0; i < signals.size (); i++)
2847 {
2848 if (signals[i])
2849 count++;
2850 }
2851 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2852 strcpy (packet, "QProgramSignals:");
2853 p = packet + strlen (packet);
2854 for (size_t i = 0; i < signals.size (); i++)
2855 {
2856 if (signal_pass_state (i))
2857 {
2858 if (i >= 16)
2859 *p++ = tohex (i >> 4);
2860 *p++ = tohex (i & 15);
2861 if (count)
2862 *p++ = ';';
2863 else
2864 break;
2865 count--;
2866 }
2867 }
2868 *p = 0;
2869 if (!rs->last_program_signals_packet
2870 || strcmp (rs->last_program_signals_packet, packet) != 0)
2871 {
2872 putpkt (packet);
2873 getpkt (&rs->buf, 0);
2874 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2875 xfree (rs->last_program_signals_packet);
2876 rs->last_program_signals_packet = packet;
2877 }
2878 else
2879 xfree (packet);
2880 }
2881 }
2882
2883 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2884 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2885 thread. If GEN is set, set the general thread, if not, then set
2886 the step/continue thread. */
2887 void
2888 remote_target::set_thread (ptid_t ptid, int gen)
2889 {
2890 struct remote_state *rs = get_remote_state ();
2891 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2892 char *buf = rs->buf.data ();
2893 char *endbuf = buf + get_remote_packet_size ();
2894
2895 if (state == ptid)
2896 return;
2897
2898 *buf++ = 'H';
2899 *buf++ = gen ? 'g' : 'c';
2900 if (ptid == magic_null_ptid)
2901 xsnprintf (buf, endbuf - buf, "0");
2902 else if (ptid == any_thread_ptid)
2903 xsnprintf (buf, endbuf - buf, "0");
2904 else if (ptid == minus_one_ptid)
2905 xsnprintf (buf, endbuf - buf, "-1");
2906 else
2907 write_ptid (buf, endbuf, ptid);
2908 putpkt (rs->buf);
2909 getpkt (&rs->buf, 0);
2910 if (gen)
2911 rs->general_thread = ptid;
2912 else
2913 rs->continue_thread = ptid;
2914 }
2915
2916 void
2917 remote_target::set_general_thread (ptid_t ptid)
2918 {
2919 set_thread (ptid, 1);
2920 }
2921
2922 void
2923 remote_target::set_continue_thread (ptid_t ptid)
2924 {
2925 set_thread (ptid, 0);
2926 }
2927
2928 /* Change the remote current process. Which thread within the process
2929 ends up selected isn't important, as long as it is the same process
2930 as what INFERIOR_PTID points to.
2931
2932 This comes from that fact that there is no explicit notion of
2933 "selected process" in the protocol. The selected process for
2934 general operations is the process the selected general thread
2935 belongs to. */
2936
2937 void
2938 remote_target::set_general_process ()
2939 {
2940 struct remote_state *rs = get_remote_state ();
2941
2942 /* If the remote can't handle multiple processes, don't bother. */
2943 if (!remote_multi_process_p (rs))
2944 return;
2945
2946 /* We only need to change the remote current thread if it's pointing
2947 at some other process. */
2948 if (rs->general_thread.pid () != inferior_ptid.pid ())
2949 set_general_thread (inferior_ptid);
2950 }
2951
2952 \f
2953 /* Return nonzero if this is the main thread that we made up ourselves
2954 to model non-threaded targets as single-threaded. */
2955
2956 static int
2957 remote_thread_always_alive (ptid_t ptid)
2958 {
2959 if (ptid == magic_null_ptid)
2960 /* The main thread is always alive. */
2961 return 1;
2962
2963 if (ptid.pid () != 0 && ptid.lwp () == 0)
2964 /* The main thread is always alive. This can happen after a
2965 vAttach, if the remote side doesn't support
2966 multi-threading. */
2967 return 1;
2968
2969 return 0;
2970 }
2971
2972 /* Return nonzero if the thread PTID is still alive on the remote
2973 system. */
2974
2975 bool
2976 remote_target::thread_alive (ptid_t ptid)
2977 {
2978 struct remote_state *rs = get_remote_state ();
2979 char *p, *endp;
2980
2981 /* Check if this is a thread that we made up ourselves to model
2982 non-threaded targets as single-threaded. */
2983 if (remote_thread_always_alive (ptid))
2984 return 1;
2985
2986 p = rs->buf.data ();
2987 endp = p + get_remote_packet_size ();
2988
2989 *p++ = 'T';
2990 write_ptid (p, endp, ptid);
2991
2992 putpkt (rs->buf);
2993 getpkt (&rs->buf, 0);
2994 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2995 }
2996
2997 /* Return a pointer to a thread name if we know it and NULL otherwise.
2998 The thread_info object owns the memory for the name. */
2999
3000 const char *
3001 remote_target::thread_name (struct thread_info *info)
3002 {
3003 if (info->priv != NULL)
3004 {
3005 const std::string &name = get_remote_thread_info (info)->name;
3006 return !name.empty () ? name.c_str () : NULL;
3007 }
3008
3009 return NULL;
3010 }
3011
3012 /* About these extended threadlist and threadinfo packets. They are
3013 variable length packets but, the fields within them are often fixed
3014 length. They are redundant enough to send over UDP as is the
3015 remote protocol in general. There is a matching unit test module
3016 in libstub. */
3017
3018 /* WARNING: This threadref data structure comes from the remote O.S.,
3019 libstub protocol encoding, and remote.c. It is not particularly
3020 changable. */
3021
3022 /* Right now, the internal structure is int. We want it to be bigger.
3023 Plan to fix this. */
3024
3025 typedef int gdb_threadref; /* Internal GDB thread reference. */
3026
3027 /* gdb_ext_thread_info is an internal GDB data structure which is
3028 equivalent to the reply of the remote threadinfo packet. */
3029
3030 struct gdb_ext_thread_info
3031 {
3032 threadref threadid; /* External form of thread reference. */
3033 int active; /* Has state interesting to GDB?
3034 regs, stack. */
3035 char display[256]; /* Brief state display, name,
3036 blocked/suspended. */
3037 char shortname[32]; /* To be used to name threads. */
3038 char more_display[256]; /* Long info, statistics, queue depth,
3039 whatever. */
3040 };
3041
3042 /* The volume of remote transfers can be limited by submitting
3043 a mask containing bits specifying the desired information.
3044 Use a union of these values as the 'selection' parameter to
3045 get_thread_info. FIXME: Make these TAG names more thread specific. */
3046
3047 #define TAG_THREADID 1
3048 #define TAG_EXISTS 2
3049 #define TAG_DISPLAY 4
3050 #define TAG_THREADNAME 8
3051 #define TAG_MOREDISPLAY 16
3052
3053 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3054
3055 static const char *unpack_nibble (const char *buf, int *val);
3056
3057 static const char *unpack_byte (const char *buf, int *value);
3058
3059 static char *pack_int (char *buf, int value);
3060
3061 static const char *unpack_int (const char *buf, int *value);
3062
3063 static const char *unpack_string (const char *src, char *dest, int length);
3064
3065 static char *pack_threadid (char *pkt, threadref *id);
3066
3067 static const char *unpack_threadid (const char *inbuf, threadref *id);
3068
3069 void int_to_threadref (threadref *id, int value);
3070
3071 static int threadref_to_int (threadref *ref);
3072
3073 static void copy_threadref (threadref *dest, threadref *src);
3074
3075 static int threadmatch (threadref *dest, threadref *src);
3076
3077 static char *pack_threadinfo_request (char *pkt, int mode,
3078 threadref *id);
3079
3080 static char *pack_threadlist_request (char *pkt, int startflag,
3081 int threadcount,
3082 threadref *nextthread);
3083
3084 static int remote_newthread_step (threadref *ref, void *context);
3085
3086
3087 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3088 buffer we're allowed to write to. Returns
3089 BUF+CHARACTERS_WRITTEN. */
3090
3091 char *
3092 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3093 {
3094 int pid, tid;
3095 struct remote_state *rs = get_remote_state ();
3096
3097 if (remote_multi_process_p (rs))
3098 {
3099 pid = ptid.pid ();
3100 if (pid < 0)
3101 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3102 else
3103 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3104 }
3105 tid = ptid.lwp ();
3106 if (tid < 0)
3107 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3108 else
3109 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3110
3111 return buf;
3112 }
3113
3114 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3115 last parsed char. Returns null_ptid if no thread id is found, and
3116 throws an error if the thread id has an invalid format. */
3117
3118 static ptid_t
3119 read_ptid (const char *buf, const char **obuf)
3120 {
3121 const char *p = buf;
3122 const char *pp;
3123 ULONGEST pid = 0, tid = 0;
3124
3125 if (*p == 'p')
3126 {
3127 /* Multi-process ptid. */
3128 pp = unpack_varlen_hex (p + 1, &pid);
3129 if (*pp != '.')
3130 error (_("invalid remote ptid: %s"), p);
3131
3132 p = pp;
3133 pp = unpack_varlen_hex (p + 1, &tid);
3134 if (obuf)
3135 *obuf = pp;
3136 return ptid_t (pid, tid);
3137 }
3138
3139 /* No multi-process. Just a tid. */
3140 pp = unpack_varlen_hex (p, &tid);
3141
3142 /* Return null_ptid when no thread id is found. */
3143 if (p == pp)
3144 {
3145 if (obuf)
3146 *obuf = pp;
3147 return null_ptid;
3148 }
3149
3150 /* Since the stub is not sending a process id, then default to
3151 what's in inferior_ptid, unless it's null at this point. If so,
3152 then since there's no way to know the pid of the reported
3153 threads, use the magic number. */
3154 if (inferior_ptid == null_ptid)
3155 pid = magic_null_ptid.pid ();
3156 else
3157 pid = inferior_ptid.pid ();
3158
3159 if (obuf)
3160 *obuf = pp;
3161 return ptid_t (pid, tid);
3162 }
3163
3164 static int
3165 stubhex (int ch)
3166 {
3167 if (ch >= 'a' && ch <= 'f')
3168 return ch - 'a' + 10;
3169 if (ch >= '0' && ch <= '9')
3170 return ch - '0';
3171 if (ch >= 'A' && ch <= 'F')
3172 return ch - 'A' + 10;
3173 return -1;
3174 }
3175
3176 static int
3177 stub_unpack_int (const char *buff, int fieldlength)
3178 {
3179 int nibble;
3180 int retval = 0;
3181
3182 while (fieldlength)
3183 {
3184 nibble = stubhex (*buff++);
3185 retval |= nibble;
3186 fieldlength--;
3187 if (fieldlength)
3188 retval = retval << 4;
3189 }
3190 return retval;
3191 }
3192
3193 static const char *
3194 unpack_nibble (const char *buf, int *val)
3195 {
3196 *val = fromhex (*buf++);
3197 return buf;
3198 }
3199
3200 static const char *
3201 unpack_byte (const char *buf, int *value)
3202 {
3203 *value = stub_unpack_int (buf, 2);
3204 return buf + 2;
3205 }
3206
3207 static char *
3208 pack_int (char *buf, int value)
3209 {
3210 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3211 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3212 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3213 buf = pack_hex_byte (buf, (value & 0xff));
3214 return buf;
3215 }
3216
3217 static const char *
3218 unpack_int (const char *buf, int *value)
3219 {
3220 *value = stub_unpack_int (buf, 8);
3221 return buf + 8;
3222 }
3223
3224 #if 0 /* Currently unused, uncomment when needed. */
3225 static char *pack_string (char *pkt, char *string);
3226
3227 static char *
3228 pack_string (char *pkt, char *string)
3229 {
3230 char ch;
3231 int len;
3232
3233 len = strlen (string);
3234 if (len > 200)
3235 len = 200; /* Bigger than most GDB packets, junk??? */
3236 pkt = pack_hex_byte (pkt, len);
3237 while (len-- > 0)
3238 {
3239 ch = *string++;
3240 if ((ch == '\0') || (ch == '#'))
3241 ch = '*'; /* Protect encapsulation. */
3242 *pkt++ = ch;
3243 }
3244 return pkt;
3245 }
3246 #endif /* 0 (unused) */
3247
3248 static const char *
3249 unpack_string (const char *src, char *dest, int length)
3250 {
3251 while (length--)
3252 *dest++ = *src++;
3253 *dest = '\0';
3254 return src;
3255 }
3256
3257 static char *
3258 pack_threadid (char *pkt, threadref *id)
3259 {
3260 char *limit;
3261 unsigned char *altid;
3262
3263 altid = (unsigned char *) id;
3264 limit = pkt + BUF_THREAD_ID_SIZE;
3265 while (pkt < limit)
3266 pkt = pack_hex_byte (pkt, *altid++);
3267 return pkt;
3268 }
3269
3270
3271 static const char *
3272 unpack_threadid (const char *inbuf, threadref *id)
3273 {
3274 char *altref;
3275 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3276 int x, y;
3277
3278 altref = (char *) id;
3279
3280 while (inbuf < limit)
3281 {
3282 x = stubhex (*inbuf++);
3283 y = stubhex (*inbuf++);
3284 *altref++ = (x << 4) | y;
3285 }
3286 return inbuf;
3287 }
3288
3289 /* Externally, threadrefs are 64 bits but internally, they are still
3290 ints. This is due to a mismatch of specifications. We would like
3291 to use 64bit thread references internally. This is an adapter
3292 function. */
3293
3294 void
3295 int_to_threadref (threadref *id, int value)
3296 {
3297 unsigned char *scan;
3298
3299 scan = (unsigned char *) id;
3300 {
3301 int i = 4;
3302 while (i--)
3303 *scan++ = 0;
3304 }
3305 *scan++ = (value >> 24) & 0xff;
3306 *scan++ = (value >> 16) & 0xff;
3307 *scan++ = (value >> 8) & 0xff;
3308 *scan++ = (value & 0xff);
3309 }
3310
3311 static int
3312 threadref_to_int (threadref *ref)
3313 {
3314 int i, value = 0;
3315 unsigned char *scan;
3316
3317 scan = *ref;
3318 scan += 4;
3319 i = 4;
3320 while (i-- > 0)
3321 value = (value << 8) | ((*scan++) & 0xff);
3322 return value;
3323 }
3324
3325 static void
3326 copy_threadref (threadref *dest, threadref *src)
3327 {
3328 int i;
3329 unsigned char *csrc, *cdest;
3330
3331 csrc = (unsigned char *) src;
3332 cdest = (unsigned char *) dest;
3333 i = 8;
3334 while (i--)
3335 *cdest++ = *csrc++;
3336 }
3337
3338 static int
3339 threadmatch (threadref *dest, threadref *src)
3340 {
3341 /* Things are broken right now, so just assume we got a match. */
3342 #if 0
3343 unsigned char *srcp, *destp;
3344 int i, result;
3345 srcp = (char *) src;
3346 destp = (char *) dest;
3347
3348 result = 1;
3349 while (i-- > 0)
3350 result &= (*srcp++ == *destp++) ? 1 : 0;
3351 return result;
3352 #endif
3353 return 1;
3354 }
3355
3356 /*
3357 threadid:1, # always request threadid
3358 context_exists:2,
3359 display:4,
3360 unique_name:8,
3361 more_display:16
3362 */
3363
3364 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3365
3366 static char *
3367 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3368 {
3369 *pkt++ = 'q'; /* Info Query */
3370 *pkt++ = 'P'; /* process or thread info */
3371 pkt = pack_int (pkt, mode); /* mode */
3372 pkt = pack_threadid (pkt, id); /* threadid */
3373 *pkt = '\0'; /* terminate */
3374 return pkt;
3375 }
3376
3377 /* These values tag the fields in a thread info response packet. */
3378 /* Tagging the fields allows us to request specific fields and to
3379 add more fields as time goes by. */
3380
3381 #define TAG_THREADID 1 /* Echo the thread identifier. */
3382 #define TAG_EXISTS 2 /* Is this process defined enough to
3383 fetch registers and its stack? */
3384 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3385 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3386 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3387 the process. */
3388
3389 int
3390 remote_target::remote_unpack_thread_info_response (const char *pkt,
3391 threadref *expectedref,
3392 gdb_ext_thread_info *info)
3393 {
3394 struct remote_state *rs = get_remote_state ();
3395 int mask, length;
3396 int tag;
3397 threadref ref;
3398 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3399 int retval = 1;
3400
3401 /* info->threadid = 0; FIXME: implement zero_threadref. */
3402 info->active = 0;
3403 info->display[0] = '\0';
3404 info->shortname[0] = '\0';
3405 info->more_display[0] = '\0';
3406
3407 /* Assume the characters indicating the packet type have been
3408 stripped. */
3409 pkt = unpack_int (pkt, &mask); /* arg mask */
3410 pkt = unpack_threadid (pkt, &ref);
3411
3412 if (mask == 0)
3413 warning (_("Incomplete response to threadinfo request."));
3414 if (!threadmatch (&ref, expectedref))
3415 { /* This is an answer to a different request. */
3416 warning (_("ERROR RMT Thread info mismatch."));
3417 return 0;
3418 }
3419 copy_threadref (&info->threadid, &ref);
3420
3421 /* Loop on tagged fields , try to bail if something goes wrong. */
3422
3423 /* Packets are terminated with nulls. */
3424 while ((pkt < limit) && mask && *pkt)
3425 {
3426 pkt = unpack_int (pkt, &tag); /* tag */
3427 pkt = unpack_byte (pkt, &length); /* length */
3428 if (!(tag & mask)) /* Tags out of synch with mask. */
3429 {
3430 warning (_("ERROR RMT: threadinfo tag mismatch."));
3431 retval = 0;
3432 break;
3433 }
3434 if (tag == TAG_THREADID)
3435 {
3436 if (length != 16)
3437 {
3438 warning (_("ERROR RMT: length of threadid is not 16."));
3439 retval = 0;
3440 break;
3441 }
3442 pkt = unpack_threadid (pkt, &ref);
3443 mask = mask & ~TAG_THREADID;
3444 continue;
3445 }
3446 if (tag == TAG_EXISTS)
3447 {
3448 info->active = stub_unpack_int (pkt, length);
3449 pkt += length;
3450 mask = mask & ~(TAG_EXISTS);
3451 if (length > 8)
3452 {
3453 warning (_("ERROR RMT: 'exists' length too long."));
3454 retval = 0;
3455 break;
3456 }
3457 continue;
3458 }
3459 if (tag == TAG_THREADNAME)
3460 {
3461 pkt = unpack_string (pkt, &info->shortname[0], length);
3462 mask = mask & ~TAG_THREADNAME;
3463 continue;
3464 }
3465 if (tag == TAG_DISPLAY)
3466 {
3467 pkt = unpack_string (pkt, &info->display[0], length);
3468 mask = mask & ~TAG_DISPLAY;
3469 continue;
3470 }
3471 if (tag == TAG_MOREDISPLAY)
3472 {
3473 pkt = unpack_string (pkt, &info->more_display[0], length);
3474 mask = mask & ~TAG_MOREDISPLAY;
3475 continue;
3476 }
3477 warning (_("ERROR RMT: unknown thread info tag."));
3478 break; /* Not a tag we know about. */
3479 }
3480 return retval;
3481 }
3482
3483 int
3484 remote_target::remote_get_threadinfo (threadref *threadid,
3485 int fieldset,
3486 gdb_ext_thread_info *info)
3487 {
3488 struct remote_state *rs = get_remote_state ();
3489 int result;
3490
3491 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3492 putpkt (rs->buf);
3493 getpkt (&rs->buf, 0);
3494
3495 if (rs->buf[0] == '\0')
3496 return 0;
3497
3498 result = remote_unpack_thread_info_response (&rs->buf[2],
3499 threadid, info);
3500 return result;
3501 }
3502
3503 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3504
3505 static char *
3506 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3507 threadref *nextthread)
3508 {
3509 *pkt++ = 'q'; /* info query packet */
3510 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3511 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3512 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3513 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3514 *pkt = '\0';
3515 return pkt;
3516 }
3517
3518 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3519
3520 int
3521 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3522 threadref *original_echo,
3523 threadref *resultlist,
3524 int *doneflag)
3525 {
3526 struct remote_state *rs = get_remote_state ();
3527 int count, resultcount, done;
3528
3529 resultcount = 0;
3530 /* Assume the 'q' and 'M chars have been stripped. */
3531 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3532 /* done parse past here */
3533 pkt = unpack_byte (pkt, &count); /* count field */
3534 pkt = unpack_nibble (pkt, &done);
3535 /* The first threadid is the argument threadid. */
3536 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3537 while ((count-- > 0) && (pkt < limit))
3538 {
3539 pkt = unpack_threadid (pkt, resultlist++);
3540 if (resultcount++ >= result_limit)
3541 break;
3542 }
3543 if (doneflag)
3544 *doneflag = done;
3545 return resultcount;
3546 }
3547
3548 /* Fetch the next batch of threads from the remote. Returns -1 if the
3549 qL packet is not supported, 0 on error and 1 on success. */
3550
3551 int
3552 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3553 int result_limit, int *done, int *result_count,
3554 threadref *threadlist)
3555 {
3556 struct remote_state *rs = get_remote_state ();
3557 int result = 1;
3558
3559 /* Truncate result limit to be smaller than the packet size. */
3560 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3561 >= get_remote_packet_size ())
3562 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3563
3564 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3565 nextthread);
3566 putpkt (rs->buf);
3567 getpkt (&rs->buf, 0);
3568 if (rs->buf[0] == '\0')
3569 {
3570 /* Packet not supported. */
3571 return -1;
3572 }
3573
3574 *result_count =
3575 parse_threadlist_response (&rs->buf[2], result_limit,
3576 &rs->echo_nextthread, threadlist, done);
3577
3578 if (!threadmatch (&rs->echo_nextthread, nextthread))
3579 {
3580 /* FIXME: This is a good reason to drop the packet. */
3581 /* Possibly, there is a duplicate response. */
3582 /* Possibilities :
3583 retransmit immediatly - race conditions
3584 retransmit after timeout - yes
3585 exit
3586 wait for packet, then exit
3587 */
3588 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3589 return 0; /* I choose simply exiting. */
3590 }
3591 if (*result_count <= 0)
3592 {
3593 if (*done != 1)
3594 {
3595 warning (_("RMT ERROR : failed to get remote thread list."));
3596 result = 0;
3597 }
3598 return result; /* break; */
3599 }
3600 if (*result_count > result_limit)
3601 {
3602 *result_count = 0;
3603 warning (_("RMT ERROR: threadlist response longer than requested."));
3604 return 0;
3605 }
3606 return result;
3607 }
3608
3609 /* Fetch the list of remote threads, with the qL packet, and call
3610 STEPFUNCTION for each thread found. Stops iterating and returns 1
3611 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3612 STEPFUNCTION returns false. If the packet is not supported,
3613 returns -1. */
3614
3615 int
3616 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3617 void *context, int looplimit)
3618 {
3619 struct remote_state *rs = get_remote_state ();
3620 int done, i, result_count;
3621 int startflag = 1;
3622 int result = 1;
3623 int loopcount = 0;
3624
3625 done = 0;
3626 while (!done)
3627 {
3628 if (loopcount++ > looplimit)
3629 {
3630 result = 0;
3631 warning (_("Remote fetch threadlist -infinite loop-."));
3632 break;
3633 }
3634 result = remote_get_threadlist (startflag, &rs->nextthread,
3635 MAXTHREADLISTRESULTS,
3636 &done, &result_count,
3637 rs->resultthreadlist);
3638 if (result <= 0)
3639 break;
3640 /* Clear for later iterations. */
3641 startflag = 0;
3642 /* Setup to resume next batch of thread references, set nextthread. */
3643 if (result_count >= 1)
3644 copy_threadref (&rs->nextthread,
3645 &rs->resultthreadlist[result_count - 1]);
3646 i = 0;
3647 while (result_count--)
3648 {
3649 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3650 {
3651 result = 0;
3652 break;
3653 }
3654 }
3655 }
3656 return result;
3657 }
3658
3659 /* A thread found on the remote target. */
3660
3661 struct thread_item
3662 {
3663 explicit thread_item (ptid_t ptid_)
3664 : ptid (ptid_)
3665 {}
3666
3667 thread_item (thread_item &&other) = default;
3668 thread_item &operator= (thread_item &&other) = default;
3669
3670 DISABLE_COPY_AND_ASSIGN (thread_item);
3671
3672 /* The thread's PTID. */
3673 ptid_t ptid;
3674
3675 /* The thread's extra info. */
3676 std::string extra;
3677
3678 /* The thread's name. */
3679 std::string name;
3680
3681 /* The core the thread was running on. -1 if not known. */
3682 int core = -1;
3683
3684 /* The thread handle associated with the thread. */
3685 gdb::byte_vector thread_handle;
3686 };
3687
3688 /* Context passed around to the various methods listing remote
3689 threads. As new threads are found, they're added to the ITEMS
3690 vector. */
3691
3692 struct threads_listing_context
3693 {
3694 /* Return true if this object contains an entry for a thread with ptid
3695 PTID. */
3696
3697 bool contains_thread (ptid_t ptid) const
3698 {
3699 auto match_ptid = [&] (const thread_item &item)
3700 {
3701 return item.ptid == ptid;
3702 };
3703
3704 auto it = std::find_if (this->items.begin (),
3705 this->items.end (),
3706 match_ptid);
3707
3708 return it != this->items.end ();
3709 }
3710
3711 /* Remove the thread with ptid PTID. */
3712
3713 void remove_thread (ptid_t ptid)
3714 {
3715 auto match_ptid = [&] (const thread_item &item)
3716 {
3717 return item.ptid == ptid;
3718 };
3719
3720 auto it = std::remove_if (this->items.begin (),
3721 this->items.end (),
3722 match_ptid);
3723
3724 if (it != this->items.end ())
3725 this->items.erase (it);
3726 }
3727
3728 /* The threads found on the remote target. */
3729 std::vector<thread_item> items;
3730 };
3731
3732 static int
3733 remote_newthread_step (threadref *ref, void *data)
3734 {
3735 struct threads_listing_context *context
3736 = (struct threads_listing_context *) data;
3737 int pid = inferior_ptid.pid ();
3738 int lwp = threadref_to_int (ref);
3739 ptid_t ptid (pid, lwp);
3740
3741 context->items.emplace_back (ptid);
3742
3743 return 1; /* continue iterator */
3744 }
3745
3746 #define CRAZY_MAX_THREADS 1000
3747
3748 ptid_t
3749 remote_target::remote_current_thread (ptid_t oldpid)
3750 {
3751 struct remote_state *rs = get_remote_state ();
3752
3753 putpkt ("qC");
3754 getpkt (&rs->buf, 0);
3755 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3756 {
3757 const char *obuf;
3758 ptid_t result;
3759
3760 result = read_ptid (&rs->buf[2], &obuf);
3761 if (*obuf != '\0')
3762 remote_debug_printf ("warning: garbage in qC reply");
3763
3764 return result;
3765 }
3766 else
3767 return oldpid;
3768 }
3769
3770 /* List remote threads using the deprecated qL packet. */
3771
3772 int
3773 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3774 {
3775 if (remote_threadlist_iterator (remote_newthread_step, context,
3776 CRAZY_MAX_THREADS) >= 0)
3777 return 1;
3778
3779 return 0;
3780 }
3781
3782 #if defined(HAVE_LIBEXPAT)
3783
3784 static void
3785 start_thread (struct gdb_xml_parser *parser,
3786 const struct gdb_xml_element *element,
3787 void *user_data,
3788 std::vector<gdb_xml_value> &attributes)
3789 {
3790 struct threads_listing_context *data
3791 = (struct threads_listing_context *) user_data;
3792 struct gdb_xml_value *attr;
3793
3794 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3795 ptid_t ptid = read_ptid (id, NULL);
3796
3797 data->items.emplace_back (ptid);
3798 thread_item &item = data->items.back ();
3799
3800 attr = xml_find_attribute (attributes, "core");
3801 if (attr != NULL)
3802 item.core = *(ULONGEST *) attr->value.get ();
3803
3804 attr = xml_find_attribute (attributes, "name");
3805 if (attr != NULL)
3806 item.name = (const char *) attr->value.get ();
3807
3808 attr = xml_find_attribute (attributes, "handle");
3809 if (attr != NULL)
3810 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3811 }
3812
3813 static void
3814 end_thread (struct gdb_xml_parser *parser,
3815 const struct gdb_xml_element *element,
3816 void *user_data, const char *body_text)
3817 {
3818 struct threads_listing_context *data
3819 = (struct threads_listing_context *) user_data;
3820
3821 if (body_text != NULL && *body_text != '\0')
3822 data->items.back ().extra = body_text;
3823 }
3824
3825 const struct gdb_xml_attribute thread_attributes[] = {
3826 { "id", GDB_XML_AF_NONE, NULL, NULL },
3827 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3828 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3829 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3830 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3831 };
3832
3833 const struct gdb_xml_element thread_children[] = {
3834 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3835 };
3836
3837 const struct gdb_xml_element threads_children[] = {
3838 { "thread", thread_attributes, thread_children,
3839 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3840 start_thread, end_thread },
3841 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3842 };
3843
3844 const struct gdb_xml_element threads_elements[] = {
3845 { "threads", NULL, threads_children,
3846 GDB_XML_EF_NONE, NULL, NULL },
3847 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3848 };
3849
3850 #endif
3851
3852 /* List remote threads using qXfer:threads:read. */
3853
3854 int
3855 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
3856 {
3857 #if defined(HAVE_LIBEXPAT)
3858 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3859 {
3860 gdb::optional<gdb::char_vector> xml
3861 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
3862
3863 if (xml && (*xml)[0] != '\0')
3864 {
3865 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3866 threads_elements, xml->data (), context);
3867 }
3868
3869 return 1;
3870 }
3871 #endif
3872
3873 return 0;
3874 }
3875
3876 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3877
3878 int
3879 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
3880 {
3881 struct remote_state *rs = get_remote_state ();
3882
3883 if (rs->use_threadinfo_query)
3884 {
3885 const char *bufp;
3886
3887 putpkt ("qfThreadInfo");
3888 getpkt (&rs->buf, 0);
3889 bufp = rs->buf.data ();
3890 if (bufp[0] != '\0') /* q packet recognized */
3891 {
3892 while (*bufp++ == 'm') /* reply contains one or more TID */
3893 {
3894 do
3895 {
3896 ptid_t ptid = read_ptid (bufp, &bufp);
3897 context->items.emplace_back (ptid);
3898 }
3899 while (*bufp++ == ','); /* comma-separated list */
3900 putpkt ("qsThreadInfo");
3901 getpkt (&rs->buf, 0);
3902 bufp = rs->buf.data ();
3903 }
3904 return 1;
3905 }
3906 else
3907 {
3908 /* Packet not recognized. */
3909 rs->use_threadinfo_query = 0;
3910 }
3911 }
3912
3913 return 0;
3914 }
3915
3916 /* Return true if INF only has one non-exited thread. */
3917
3918 static bool
3919 has_single_non_exited_thread (inferior *inf)
3920 {
3921 int count = 0;
3922 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
3923 if (++count > 1)
3924 break;
3925 return count == 1;
3926 }
3927
3928 /* Implement the to_update_thread_list function for the remote
3929 targets. */
3930
3931 void
3932 remote_target::update_thread_list ()
3933 {
3934 struct threads_listing_context context;
3935 int got_list = 0;
3936
3937 /* We have a few different mechanisms to fetch the thread list. Try
3938 them all, starting with the most preferred one first, falling
3939 back to older methods. */
3940 if (remote_get_threads_with_qxfer (&context)
3941 || remote_get_threads_with_qthreadinfo (&context)
3942 || remote_get_threads_with_ql (&context))
3943 {
3944 got_list = 1;
3945
3946 if (context.items.empty ()
3947 && remote_thread_always_alive (inferior_ptid))
3948 {
3949 /* Some targets don't really support threads, but still
3950 reply an (empty) thread list in response to the thread
3951 listing packets, instead of replying "packet not
3952 supported". Exit early so we don't delete the main
3953 thread. */
3954 return;
3955 }
3956
3957 /* CONTEXT now holds the current thread list on the remote
3958 target end. Delete GDB-side threads no longer found on the
3959 target. */
3960 for (thread_info *tp : all_threads_safe ())
3961 {
3962 if (tp->inf->process_target () != this)
3963 continue;
3964
3965 if (!context.contains_thread (tp->ptid))
3966 {
3967 /* Do not remove the thread if it is the last thread in
3968 the inferior. This situation happens when we have a
3969 pending exit process status to process. Otherwise we
3970 may end up with a seemingly live inferior (i.e. pid
3971 != 0) that has no threads. */
3972 if (has_single_non_exited_thread (tp->inf))
3973 continue;
3974
3975 /* Not found. */
3976 delete_thread (tp);
3977 }
3978 }
3979
3980 /* Remove any unreported fork child threads from CONTEXT so
3981 that we don't interfere with follow fork, which is where
3982 creation of such threads is handled. */
3983 remove_new_fork_children (&context);
3984
3985 /* And now add threads we don't know about yet to our list. */
3986 for (thread_item &item : context.items)
3987 {
3988 if (item.ptid != null_ptid)
3989 {
3990 /* In non-stop mode, we assume new found threads are
3991 executing until proven otherwise with a stop reply.
3992 In all-stop, we can only get here if all threads are
3993 stopped. */
3994 bool executing = target_is_non_stop_p ();
3995
3996 remote_notice_new_inferior (item.ptid, executing);
3997
3998 thread_info *tp = find_thread_ptid (this, item.ptid);
3999 remote_thread_info *info = get_remote_thread_info (tp);
4000 info->core = item.core;
4001 info->extra = std::move (item.extra);
4002 info->name = std::move (item.name);
4003 info->thread_handle = std::move (item.thread_handle);
4004 }
4005 }
4006 }
4007
4008 if (!got_list)
4009 {
4010 /* If no thread listing method is supported, then query whether
4011 each known thread is alive, one by one, with the T packet.
4012 If the target doesn't support threads at all, then this is a
4013 no-op. See remote_thread_alive. */
4014 prune_threads ();
4015 }
4016 }
4017
4018 /*
4019 * Collect a descriptive string about the given thread.
4020 * The target may say anything it wants to about the thread
4021 * (typically info about its blocked / runnable state, name, etc.).
4022 * This string will appear in the info threads display.
4023 *
4024 * Optional: targets are not required to implement this function.
4025 */
4026
4027 const char *
4028 remote_target::extra_thread_info (thread_info *tp)
4029 {
4030 struct remote_state *rs = get_remote_state ();
4031 int set;
4032 threadref id;
4033 struct gdb_ext_thread_info threadinfo;
4034
4035 if (rs->remote_desc == 0) /* paranoia */
4036 internal_error (__FILE__, __LINE__,
4037 _("remote_threads_extra_info"));
4038
4039 if (tp->ptid == magic_null_ptid
4040 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4041 /* This is the main thread which was added by GDB. The remote
4042 server doesn't know about it. */
4043 return NULL;
4044
4045 std::string &extra = get_remote_thread_info (tp)->extra;
4046
4047 /* If already have cached info, use it. */
4048 if (!extra.empty ())
4049 return extra.c_str ();
4050
4051 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4052 {
4053 /* If we're using qXfer:threads:read, then the extra info is
4054 included in the XML. So if we didn't have anything cached,
4055 it's because there's really no extra info. */
4056 return NULL;
4057 }
4058
4059 if (rs->use_threadextra_query)
4060 {
4061 char *b = rs->buf.data ();
4062 char *endb = b + get_remote_packet_size ();
4063
4064 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4065 b += strlen (b);
4066 write_ptid (b, endb, tp->ptid);
4067
4068 putpkt (rs->buf);
4069 getpkt (&rs->buf, 0);
4070 if (rs->buf[0] != 0)
4071 {
4072 extra.resize (strlen (rs->buf.data ()) / 2);
4073 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4074 return extra.c_str ();
4075 }
4076 }
4077
4078 /* If the above query fails, fall back to the old method. */
4079 rs->use_threadextra_query = 0;
4080 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4081 | TAG_MOREDISPLAY | TAG_DISPLAY;
4082 int_to_threadref (&id, tp->ptid.lwp ());
4083 if (remote_get_threadinfo (&id, set, &threadinfo))
4084 if (threadinfo.active)
4085 {
4086 if (*threadinfo.shortname)
4087 string_appendf (extra, " Name: %s", threadinfo.shortname);
4088 if (*threadinfo.display)
4089 {
4090 if (!extra.empty ())
4091 extra += ',';
4092 string_appendf (extra, " State: %s", threadinfo.display);
4093 }
4094 if (*threadinfo.more_display)
4095 {
4096 if (!extra.empty ())
4097 extra += ',';
4098 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4099 }
4100 return extra.c_str ();
4101 }
4102 return NULL;
4103 }
4104 \f
4105
4106 bool
4107 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4108 struct static_tracepoint_marker *marker)
4109 {
4110 struct remote_state *rs = get_remote_state ();
4111 char *p = rs->buf.data ();
4112
4113 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4114 p += strlen (p);
4115 p += hexnumstr (p, addr);
4116 putpkt (rs->buf);
4117 getpkt (&rs->buf, 0);
4118 p = rs->buf.data ();
4119
4120 if (*p == 'E')
4121 error (_("Remote failure reply: %s"), p);
4122
4123 if (*p++ == 'm')
4124 {
4125 parse_static_tracepoint_marker_definition (p, NULL, marker);
4126 return true;
4127 }
4128
4129 return false;
4130 }
4131
4132 std::vector<static_tracepoint_marker>
4133 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4134 {
4135 struct remote_state *rs = get_remote_state ();
4136 std::vector<static_tracepoint_marker> markers;
4137 const char *p;
4138 static_tracepoint_marker marker;
4139
4140 /* Ask for a first packet of static tracepoint marker
4141 definition. */
4142 putpkt ("qTfSTM");
4143 getpkt (&rs->buf, 0);
4144 p = rs->buf.data ();
4145 if (*p == 'E')
4146 error (_("Remote failure reply: %s"), p);
4147
4148 while (*p++ == 'm')
4149 {
4150 do
4151 {
4152 parse_static_tracepoint_marker_definition (p, &p, &marker);
4153
4154 if (strid == NULL || marker.str_id == strid)
4155 markers.push_back (std::move (marker));
4156 }
4157 while (*p++ == ','); /* comma-separated list */
4158 /* Ask for another packet of static tracepoint definition. */
4159 putpkt ("qTsSTM");
4160 getpkt (&rs->buf, 0);
4161 p = rs->buf.data ();
4162 }
4163
4164 return markers;
4165 }
4166
4167 \f
4168 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4169
4170 ptid_t
4171 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4172 {
4173 return ptid_t (inferior_ptid.pid (), lwp);
4174 }
4175 \f
4176
4177 /* Restart the remote side; this is an extended protocol operation. */
4178
4179 void
4180 remote_target::extended_remote_restart ()
4181 {
4182 struct remote_state *rs = get_remote_state ();
4183
4184 /* Send the restart command; for reasons I don't understand the
4185 remote side really expects a number after the "R". */
4186 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4187 putpkt (rs->buf);
4188
4189 remote_fileio_reset ();
4190 }
4191 \f
4192 /* Clean up connection to a remote debugger. */
4193
4194 void
4195 remote_target::close ()
4196 {
4197 /* Make sure we leave stdin registered in the event loop. */
4198 terminal_ours ();
4199
4200 trace_reset_local_state ();
4201
4202 delete this;
4203 }
4204
4205 remote_target::~remote_target ()
4206 {
4207 struct remote_state *rs = get_remote_state ();
4208
4209 /* Check for NULL because we may get here with a partially
4210 constructed target/connection. */
4211 if (rs->remote_desc == nullptr)
4212 return;
4213
4214 serial_close (rs->remote_desc);
4215
4216 /* We are destroying the remote target, so we should discard
4217 everything of this target. */
4218 discard_pending_stop_replies_in_queue ();
4219
4220 if (rs->remote_async_inferior_event_token)
4221 delete_async_event_handler (&rs->remote_async_inferior_event_token);
4222
4223 delete rs->notif_state;
4224 }
4225
4226 /* Query the remote side for the text, data and bss offsets. */
4227
4228 void
4229 remote_target::get_offsets ()
4230 {
4231 struct remote_state *rs = get_remote_state ();
4232 char *buf;
4233 char *ptr;
4234 int lose, num_segments = 0, do_sections, do_segments;
4235 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4236
4237 if (current_program_space->symfile_object_file == NULL)
4238 return;
4239
4240 putpkt ("qOffsets");
4241 getpkt (&rs->buf, 0);
4242 buf = rs->buf.data ();
4243
4244 if (buf[0] == '\000')
4245 return; /* Return silently. Stub doesn't support
4246 this command. */
4247 if (buf[0] == 'E')
4248 {
4249 warning (_("Remote failure reply: %s"), buf);
4250 return;
4251 }
4252
4253 /* Pick up each field in turn. This used to be done with scanf, but
4254 scanf will make trouble if CORE_ADDR size doesn't match
4255 conversion directives correctly. The following code will work
4256 with any size of CORE_ADDR. */
4257 text_addr = data_addr = bss_addr = 0;
4258 ptr = buf;
4259 lose = 0;
4260
4261 if (startswith (ptr, "Text="))
4262 {
4263 ptr += 5;
4264 /* Don't use strtol, could lose on big values. */
4265 while (*ptr && *ptr != ';')
4266 text_addr = (text_addr << 4) + fromhex (*ptr++);
4267
4268 if (startswith (ptr, ";Data="))
4269 {
4270 ptr += 6;
4271 while (*ptr && *ptr != ';')
4272 data_addr = (data_addr << 4) + fromhex (*ptr++);
4273 }
4274 else
4275 lose = 1;
4276
4277 if (!lose && startswith (ptr, ";Bss="))
4278 {
4279 ptr += 5;
4280 while (*ptr && *ptr != ';')
4281 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4282
4283 if (bss_addr != data_addr)
4284 warning (_("Target reported unsupported offsets: %s"), buf);
4285 }
4286 else
4287 lose = 1;
4288 }
4289 else if (startswith (ptr, "TextSeg="))
4290 {
4291 ptr += 8;
4292 /* Don't use strtol, could lose on big values. */
4293 while (*ptr && *ptr != ';')
4294 text_addr = (text_addr << 4) + fromhex (*ptr++);
4295 num_segments = 1;
4296
4297 if (startswith (ptr, ";DataSeg="))
4298 {
4299 ptr += 9;
4300 while (*ptr && *ptr != ';')
4301 data_addr = (data_addr << 4) + fromhex (*ptr++);
4302 num_segments++;
4303 }
4304 }
4305 else
4306 lose = 1;
4307
4308 if (lose)
4309 error (_("Malformed response to offset query, %s"), buf);
4310 else if (*ptr != '\0')
4311 warning (_("Target reported unsupported offsets: %s"), buf);
4312
4313 objfile *objf = current_program_space->symfile_object_file;
4314 section_offsets offs = objf->section_offsets;
4315
4316 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd);
4317 do_segments = (data != NULL);
4318 do_sections = num_segments == 0;
4319
4320 if (num_segments > 0)
4321 {
4322 segments[0] = text_addr;
4323 segments[1] = data_addr;
4324 }
4325 /* If we have two segments, we can still try to relocate everything
4326 by assuming that the .text and .data offsets apply to the whole
4327 text and data segments. Convert the offsets given in the packet
4328 to base addresses for symfile_map_offsets_to_segments. */
4329 else if (data != nullptr && data->segments.size () == 2)
4330 {
4331 segments[0] = data->segments[0].base + text_addr;
4332 segments[1] = data->segments[1].base + data_addr;
4333 num_segments = 2;
4334 }
4335 /* If the object file has only one segment, assume that it is text
4336 rather than data; main programs with no writable data are rare,
4337 but programs with no code are useless. Of course the code might
4338 have ended up in the data segment... to detect that we would need
4339 the permissions here. */
4340 else if (data && data->segments.size () == 1)
4341 {
4342 segments[0] = data->segments[0].base + text_addr;
4343 num_segments = 1;
4344 }
4345 /* There's no way to relocate by segment. */
4346 else
4347 do_segments = 0;
4348
4349 if (do_segments)
4350 {
4351 int ret = symfile_map_offsets_to_segments (objf->obfd,
4352 data.get (), offs,
4353 num_segments, segments);
4354
4355 if (ret == 0 && !do_sections)
4356 error (_("Can not handle qOffsets TextSeg "
4357 "response with this symbol file"));
4358
4359 if (ret > 0)
4360 do_sections = 0;
4361 }
4362
4363 if (do_sections)
4364 {
4365 offs[SECT_OFF_TEXT (objf)] = text_addr;
4366
4367 /* This is a temporary kludge to force data and bss to use the
4368 same offsets because that's what nlmconv does now. The real
4369 solution requires changes to the stub and remote.c that I
4370 don't have time to do right now. */
4371
4372 offs[SECT_OFF_DATA (objf)] = data_addr;
4373 offs[SECT_OFF_BSS (objf)] = data_addr;
4374 }
4375
4376 objfile_relocate (objf, offs);
4377 }
4378
4379 /* Send interrupt_sequence to remote target. */
4380
4381 void
4382 remote_target::send_interrupt_sequence ()
4383 {
4384 struct remote_state *rs = get_remote_state ();
4385
4386 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4387 remote_serial_write ("\x03", 1);
4388 else if (interrupt_sequence_mode == interrupt_sequence_break)
4389 serial_send_break (rs->remote_desc);
4390 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4391 {
4392 serial_send_break (rs->remote_desc);
4393 remote_serial_write ("g", 1);
4394 }
4395 else
4396 internal_error (__FILE__, __LINE__,
4397 _("Invalid value for interrupt_sequence_mode: %s."),
4398 interrupt_sequence_mode);
4399 }
4400
4401
4402 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4403 and extract the PTID. Returns NULL_PTID if not found. */
4404
4405 static ptid_t
4406 stop_reply_extract_thread (const char *stop_reply)
4407 {
4408 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4409 {
4410 const char *p;
4411
4412 /* Txx r:val ; r:val (...) */
4413 p = &stop_reply[3];
4414
4415 /* Look for "register" named "thread". */
4416 while (*p != '\0')
4417 {
4418 const char *p1;
4419
4420 p1 = strchr (p, ':');
4421 if (p1 == NULL)
4422 return null_ptid;
4423
4424 if (strncmp (p, "thread", p1 - p) == 0)
4425 return read_ptid (++p1, &p);
4426
4427 p1 = strchr (p, ';');
4428 if (p1 == NULL)
4429 return null_ptid;
4430 p1++;
4431
4432 p = p1;
4433 }
4434 }
4435
4436 return null_ptid;
4437 }
4438
4439 /* Determine the remote side's current thread. If we have a stop
4440 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4441 "thread" register we can extract the current thread from. If not,
4442 ask the remote which is the current thread with qC. The former
4443 method avoids a roundtrip. */
4444
4445 ptid_t
4446 remote_target::get_current_thread (const char *wait_status)
4447 {
4448 ptid_t ptid = null_ptid;
4449
4450 /* Note we don't use remote_parse_stop_reply as that makes use of
4451 the target architecture, which we haven't yet fully determined at
4452 this point. */
4453 if (wait_status != NULL)
4454 ptid = stop_reply_extract_thread (wait_status);
4455 if (ptid == null_ptid)
4456 ptid = remote_current_thread (inferior_ptid);
4457
4458 return ptid;
4459 }
4460
4461 /* Query the remote target for which is the current thread/process,
4462 add it to our tables, and update INFERIOR_PTID. The caller is
4463 responsible for setting the state such that the remote end is ready
4464 to return the current thread.
4465
4466 This function is called after handling the '?' or 'vRun' packets,
4467 whose response is a stop reply from which we can also try
4468 extracting the thread. If the target doesn't support the explicit
4469 qC query, we infer the current thread from that stop reply, passed
4470 in in WAIT_STATUS, which may be NULL.
4471
4472 The function returns pointer to the main thread of the inferior. */
4473
4474 thread_info *
4475 remote_target::add_current_inferior_and_thread (const char *wait_status)
4476 {
4477 struct remote_state *rs = get_remote_state ();
4478 bool fake_pid_p = false;
4479
4480 switch_to_no_thread ();
4481
4482 /* Now, if we have thread information, update the current thread's
4483 ptid. */
4484 ptid_t curr_ptid = get_current_thread (wait_status);
4485
4486 if (curr_ptid != null_ptid)
4487 {
4488 if (!remote_multi_process_p (rs))
4489 fake_pid_p = true;
4490 }
4491 else
4492 {
4493 /* Without this, some commands which require an active target
4494 (such as kill) won't work. This variable serves (at least)
4495 double duty as both the pid of the target process (if it has
4496 such), and as a flag indicating that a target is active. */
4497 curr_ptid = magic_null_ptid;
4498 fake_pid_p = true;
4499 }
4500
4501 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4502
4503 /* Add the main thread and switch to it. Don't try reading
4504 registers yet, since we haven't fetched the target description
4505 yet. */
4506 thread_info *tp = add_thread_silent (this, curr_ptid);
4507 switch_to_thread_no_regs (tp);
4508
4509 return tp;
4510 }
4511
4512 /* Print info about a thread that was found already stopped on
4513 connection. */
4514
4515 void
4516 remote_target::print_one_stopped_thread (thread_info *thread)
4517 {
4518 target_waitstatus ws;
4519
4520 /* If there is a pending waitstatus, use it. If there isn't it's because
4521 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4522 and process_initial_stop_replies decided it wasn't interesting to save
4523 and report to the core. */
4524 if (thread->has_pending_waitstatus ())
4525 {
4526 ws = thread->pending_waitstatus ();
4527 thread->clear_pending_waitstatus ();
4528 }
4529 else
4530 {
4531 ws.set_stopped (GDB_SIGNAL_0);
4532 }
4533
4534 switch_to_thread (thread);
4535 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4536 set_current_sal_from_frame (get_current_frame ());
4537
4538 /* For "info program". */
4539 set_last_target_status (this, thread->ptid, ws);
4540
4541 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4542 {
4543 enum gdb_signal sig = ws.sig ();
4544
4545 if (signal_print_state (sig))
4546 gdb::observers::signal_received.notify (sig);
4547 }
4548 gdb::observers::normal_stop.notify (NULL, 1);
4549 }
4550
4551 /* Process all initial stop replies the remote side sent in response
4552 to the ? packet. These indicate threads that were already stopped
4553 on initial connection. We mark these threads as stopped and print
4554 their current frame before giving the user the prompt. */
4555
4556 void
4557 remote_target::process_initial_stop_replies (int from_tty)
4558 {
4559 int pending_stop_replies = stop_reply_queue_length ();
4560 struct thread_info *selected = NULL;
4561 struct thread_info *lowest_stopped = NULL;
4562 struct thread_info *first = NULL;
4563
4564 /* This is only used when the target is non-stop. */
4565 gdb_assert (target_is_non_stop_p ());
4566
4567 /* Consume the initial pending events. */
4568 while (pending_stop_replies-- > 0)
4569 {
4570 ptid_t waiton_ptid = minus_one_ptid;
4571 ptid_t event_ptid;
4572 struct target_waitstatus ws;
4573 int ignore_event = 0;
4574
4575 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4576 if (remote_debug)
4577 print_target_wait_results (waiton_ptid, event_ptid, ws);
4578
4579 switch (ws.kind ())
4580 {
4581 case TARGET_WAITKIND_IGNORE:
4582 case TARGET_WAITKIND_NO_RESUMED:
4583 case TARGET_WAITKIND_SIGNALLED:
4584 case TARGET_WAITKIND_EXITED:
4585 /* We shouldn't see these, but if we do, just ignore. */
4586 remote_debug_printf ("event ignored");
4587 ignore_event = 1;
4588 break;
4589
4590 default:
4591 break;
4592 }
4593
4594 if (ignore_event)
4595 continue;
4596
4597 thread_info *evthread = find_thread_ptid (this, event_ptid);
4598
4599 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4600 {
4601 enum gdb_signal sig = ws.sig ();
4602
4603 /* Stubs traditionally report SIGTRAP as initial signal,
4604 instead of signal 0. Suppress it. */
4605 if (sig == GDB_SIGNAL_TRAP)
4606 sig = GDB_SIGNAL_0;
4607 evthread->set_stop_signal (sig);
4608 ws.set_stopped (sig);
4609 }
4610
4611 if (ws.kind () != TARGET_WAITKIND_STOPPED
4612 || ws.sig () != GDB_SIGNAL_0)
4613 evthread->set_pending_waitstatus (ws);
4614
4615 set_executing (this, event_ptid, false);
4616 set_running (this, event_ptid, false);
4617 get_remote_thread_info (evthread)->set_not_resumed ();
4618 }
4619
4620 /* "Notice" the new inferiors before anything related to
4621 registers/memory. */
4622 for (inferior *inf : all_non_exited_inferiors (this))
4623 {
4624 inf->needs_setup = 1;
4625
4626 if (non_stop)
4627 {
4628 thread_info *thread = any_live_thread_of_inferior (inf);
4629 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4630 from_tty);
4631 }
4632 }
4633
4634 /* If all-stop on top of non-stop, pause all threads. Note this
4635 records the threads' stop pc, so must be done after "noticing"
4636 the inferiors. */
4637 if (!non_stop)
4638 {
4639 {
4640 /* At this point, the remote target is not async. It needs to be for
4641 the poll in stop_all_threads to consider events from it, so enable
4642 it temporarily. */
4643 gdb_assert (!this->is_async_p ());
4644 SCOPE_EXIT { target_async (0); };
4645 target_async (1);
4646 stop_all_threads ();
4647 }
4648
4649 /* If all threads of an inferior were already stopped, we
4650 haven't setup the inferior yet. */
4651 for (inferior *inf : all_non_exited_inferiors (this))
4652 {
4653 if (inf->needs_setup)
4654 {
4655 thread_info *thread = any_live_thread_of_inferior (inf);
4656 switch_to_thread_no_regs (thread);
4657 setup_inferior (0);
4658 }
4659 }
4660 }
4661
4662 /* Now go over all threads that are stopped, and print their current
4663 frame. If all-stop, then if there's a signalled thread, pick
4664 that as current. */
4665 for (thread_info *thread : all_non_exited_threads (this))
4666 {
4667 if (first == NULL)
4668 first = thread;
4669
4670 if (!non_stop)
4671 thread->set_running (false);
4672 else if (thread->state != THREAD_STOPPED)
4673 continue;
4674
4675 if (selected == nullptr && thread->has_pending_waitstatus ())
4676 selected = thread;
4677
4678 if (lowest_stopped == NULL
4679 || thread->inf->num < lowest_stopped->inf->num
4680 || thread->per_inf_num < lowest_stopped->per_inf_num)
4681 lowest_stopped = thread;
4682
4683 if (non_stop)
4684 print_one_stopped_thread (thread);
4685 }
4686
4687 /* In all-stop, we only print the status of one thread, and leave
4688 others with their status pending. */
4689 if (!non_stop)
4690 {
4691 thread_info *thread = selected;
4692 if (thread == NULL)
4693 thread = lowest_stopped;
4694 if (thread == NULL)
4695 thread = first;
4696
4697 print_one_stopped_thread (thread);
4698 }
4699 }
4700
4701 /* Mark a remote_target as marking (by setting the starting_up flag within
4702 its remote_state) for the lifetime of this object. The reference count
4703 on the remote target is temporarily incremented, to prevent the target
4704 being deleted under our feet. */
4705
4706 struct scoped_mark_target_starting
4707 {
4708 /* Constructor, TARGET is the target to be marked as starting, its
4709 reference count will be incremented. */
4710 scoped_mark_target_starting (remote_target *target)
4711 : m_remote_target (target)
4712 {
4713 m_remote_target->incref ();
4714 remote_state *rs = m_remote_target->get_remote_state ();
4715 rs->starting_up = true;
4716 }
4717
4718 /* Destructor, mark the target being worked on as no longer starting, and
4719 decrement the reference count. */
4720 ~scoped_mark_target_starting ()
4721 {
4722 remote_state *rs = m_remote_target->get_remote_state ();
4723 rs->starting_up = false;
4724 decref_target (m_remote_target);
4725 }
4726
4727 private:
4728
4729 /* The target on which we are operating. */
4730 remote_target *m_remote_target;
4731 };
4732
4733 /* Helper for remote_target::start_remote, start the remote connection and
4734 sync state. Return true if everything goes OK, otherwise, return false.
4735 This function exists so that the scoped_restore created within it will
4736 expire before we return to remote_target::start_remote. */
4737
4738 bool
4739 remote_target::start_remote_1 (int from_tty, int extended_p)
4740 {
4741 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4742
4743 struct remote_state *rs = get_remote_state ();
4744 struct packet_config *noack_config;
4745
4746 /* Signal other parts that we're going through the initial setup,
4747 and so things may not be stable yet. E.g., we don't try to
4748 install tracepoints until we've relocated symbols. Also, a
4749 Ctrl-C before we're connected and synced up can't interrupt the
4750 target. Instead, it offers to drop the (potentially wedged)
4751 connection. */
4752 scoped_mark_target_starting target_is_starting (this);
4753
4754 QUIT;
4755
4756 if (interrupt_on_connect)
4757 send_interrupt_sequence ();
4758
4759 /* Ack any packet which the remote side has already sent. */
4760 remote_serial_write ("+", 1);
4761
4762 /* The first packet we send to the target is the optional "supported
4763 packets" request. If the target can answer this, it will tell us
4764 which later probes to skip. */
4765 remote_query_supported ();
4766
4767 /* If the stub wants to get a QAllow, compose one and send it. */
4768 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4769 set_permissions ();
4770
4771 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4772 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4773 as a reply to known packet. For packet "vFile:setfs:" it is an
4774 invalid reply and GDB would return error in
4775 remote_hostio_set_filesystem, making remote files access impossible.
4776 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4777 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4778 {
4779 const char v_mustreplyempty[] = "vMustReplyEmpty";
4780
4781 putpkt (v_mustreplyempty);
4782 getpkt (&rs->buf, 0);
4783 if (strcmp (rs->buf.data (), "OK") == 0)
4784 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4785 else if (strcmp (rs->buf.data (), "") != 0)
4786 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4787 rs->buf.data ());
4788 }
4789
4790 /* Next, we possibly activate noack mode.
4791
4792 If the QStartNoAckMode packet configuration is set to AUTO,
4793 enable noack mode if the stub reported a wish for it with
4794 qSupported.
4795
4796 If set to TRUE, then enable noack mode even if the stub didn't
4797 report it in qSupported. If the stub doesn't reply OK, the
4798 session ends with an error.
4799
4800 If FALSE, then don't activate noack mode, regardless of what the
4801 stub claimed should be the default with qSupported. */
4802
4803 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4804 if (packet_config_support (noack_config) != PACKET_DISABLE)
4805 {
4806 putpkt ("QStartNoAckMode");
4807 getpkt (&rs->buf, 0);
4808 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4809 rs->noack_mode = 1;
4810 }
4811
4812 if (extended_p)
4813 {
4814 /* Tell the remote that we are using the extended protocol. */
4815 putpkt ("!");
4816 getpkt (&rs->buf, 0);
4817 }
4818
4819 /* Let the target know which signals it is allowed to pass down to
4820 the program. */
4821 update_signals_program_target ();
4822
4823 /* Next, if the target can specify a description, read it. We do
4824 this before anything involving memory or registers. */
4825 target_find_description ();
4826
4827 /* Next, now that we know something about the target, update the
4828 address spaces in the program spaces. */
4829 update_address_spaces ();
4830
4831 /* On OSs where the list of libraries is global to all
4832 processes, we fetch them early. */
4833 if (gdbarch_has_global_solist (target_gdbarch ()))
4834 solib_add (NULL, from_tty, auto_solib_add);
4835
4836 if (target_is_non_stop_p ())
4837 {
4838 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4839 error (_("Non-stop mode requested, but remote "
4840 "does not support non-stop"));
4841
4842 putpkt ("QNonStop:1");
4843 getpkt (&rs->buf, 0);
4844
4845 if (strcmp (rs->buf.data (), "OK") != 0)
4846 error (_("Remote refused setting non-stop mode with: %s"),
4847 rs->buf.data ());
4848
4849 /* Find about threads and processes the stub is already
4850 controlling. We default to adding them in the running state.
4851 The '?' query below will then tell us about which threads are
4852 stopped. */
4853 this->update_thread_list ();
4854 }
4855 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4856 {
4857 /* Don't assume that the stub can operate in all-stop mode.
4858 Request it explicitly. */
4859 putpkt ("QNonStop:0");
4860 getpkt (&rs->buf, 0);
4861
4862 if (strcmp (rs->buf.data (), "OK") != 0)
4863 error (_("Remote refused setting all-stop mode with: %s"),
4864 rs->buf.data ());
4865 }
4866
4867 /* Upload TSVs regardless of whether the target is running or not. The
4868 remote stub, such as GDBserver, may have some predefined or builtin
4869 TSVs, even if the target is not running. */
4870 if (get_trace_status (current_trace_status ()) != -1)
4871 {
4872 struct uploaded_tsv *uploaded_tsvs = NULL;
4873
4874 upload_trace_state_variables (&uploaded_tsvs);
4875 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4876 }
4877
4878 /* Check whether the target is running now. */
4879 putpkt ("?");
4880 getpkt (&rs->buf, 0);
4881
4882 if (!target_is_non_stop_p ())
4883 {
4884 char *wait_status = NULL;
4885
4886 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4887 {
4888 if (!extended_p)
4889 error (_("The target is not running (try extended-remote?)"));
4890 return false;
4891 }
4892 else
4893 {
4894 /* Save the reply for later. */
4895 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
4896 strcpy (wait_status, rs->buf.data ());
4897 }
4898
4899 /* Fetch thread list. */
4900 target_update_thread_list ();
4901
4902 /* Let the stub know that we want it to return the thread. */
4903 set_continue_thread (minus_one_ptid);
4904
4905 if (thread_count (this) == 0)
4906 {
4907 /* Target has no concept of threads at all. GDB treats
4908 non-threaded target as single-threaded; add a main
4909 thread. */
4910 thread_info *tp = add_current_inferior_and_thread (wait_status);
4911 get_remote_thread_info (tp)->set_resumed ();
4912 }
4913 else
4914 {
4915 /* We have thread information; select the thread the target
4916 says should be current. If we're reconnecting to a
4917 multi-threaded program, this will ideally be the thread
4918 that last reported an event before GDB disconnected. */
4919 ptid_t curr_thread = get_current_thread (wait_status);
4920 if (curr_thread == null_ptid)
4921 {
4922 /* Odd... The target was able to list threads, but not
4923 tell us which thread was current (no "thread"
4924 register in T stop reply?). Just pick the first
4925 thread in the thread list then. */
4926
4927 remote_debug_printf ("warning: couldn't determine remote "
4928 "current thread; picking first in list.");
4929
4930 for (thread_info *tp : all_non_exited_threads (this,
4931 minus_one_ptid))
4932 {
4933 switch_to_thread (tp);
4934 break;
4935 }
4936 }
4937 else
4938 switch_to_thread (find_thread_ptid (this, curr_thread));
4939 }
4940
4941 /* init_wait_for_inferior should be called before get_offsets in order
4942 to manage `inserted' flag in bp loc in a correct state.
4943 breakpoint_init_inferior, called from init_wait_for_inferior, set
4944 `inserted' flag to 0, while before breakpoint_re_set, called from
4945 start_remote, set `inserted' flag to 1. In the initialization of
4946 inferior, breakpoint_init_inferior should be called first, and then
4947 breakpoint_re_set can be called. If this order is broken, state of
4948 `inserted' flag is wrong, and cause some problems on breakpoint
4949 manipulation. */
4950 init_wait_for_inferior ();
4951
4952 get_offsets (); /* Get text, data & bss offsets. */
4953
4954 /* If we could not find a description using qXfer, and we know
4955 how to do it some other way, try again. This is not
4956 supported for non-stop; it could be, but it is tricky if
4957 there are no stopped threads when we connect. */
4958 if (remote_read_description_p (this)
4959 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4960 {
4961 target_clear_description ();
4962 target_find_description ();
4963 }
4964
4965 /* Use the previously fetched status. */
4966 gdb_assert (wait_status != NULL);
4967 struct notif_event *reply
4968 = remote_notif_parse (this, &notif_client_stop, wait_status);
4969 push_stop_reply ((struct stop_reply *) reply);
4970
4971 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
4972 }
4973 else
4974 {
4975 /* Clear WFI global state. Do this before finding about new
4976 threads and inferiors, and setting the current inferior.
4977 Otherwise we would clear the proceed status of the current
4978 inferior when we want its stop_soon state to be preserved
4979 (see notice_new_inferior). */
4980 init_wait_for_inferior ();
4981
4982 /* In non-stop, we will either get an "OK", meaning that there
4983 are no stopped threads at this time; or, a regular stop
4984 reply. In the latter case, there may be more than one thread
4985 stopped --- we pull them all out using the vStopped
4986 mechanism. */
4987 if (strcmp (rs->buf.data (), "OK") != 0)
4988 {
4989 struct notif_client *notif = &notif_client_stop;
4990
4991 /* remote_notif_get_pending_replies acks this one, and gets
4992 the rest out. */
4993 rs->notif_state->pending_event[notif_client_stop.id]
4994 = remote_notif_parse (this, notif, rs->buf.data ());
4995 remote_notif_get_pending_events (notif);
4996 }
4997
4998 if (thread_count (this) == 0)
4999 {
5000 if (!extended_p)
5001 error (_("The target is not running (try extended-remote?)"));
5002 return false;
5003 }
5004
5005 /* Report all signals during attach/startup. */
5006 pass_signals ({});
5007
5008 /* If there are already stopped threads, mark them stopped and
5009 report their stops before giving the prompt to the user. */
5010 process_initial_stop_replies (from_tty);
5011
5012 if (target_can_async_p ())
5013 target_async (1);
5014 }
5015
5016 /* If we connected to a live target, do some additional setup. */
5017 if (target_has_execution ())
5018 {
5019 /* No use without a symbol-file. */
5020 if (current_program_space->symfile_object_file)
5021 remote_check_symbols ();
5022 }
5023
5024 /* Possibly the target has been engaged in a trace run started
5025 previously; find out where things are at. */
5026 if (get_trace_status (current_trace_status ()) != -1)
5027 {
5028 struct uploaded_tp *uploaded_tps = NULL;
5029
5030 if (current_trace_status ()->running)
5031 printf_filtered (_("Trace is already running on the target.\n"));
5032
5033 upload_tracepoints (&uploaded_tps);
5034
5035 merge_uploaded_tracepoints (&uploaded_tps);
5036 }
5037
5038 /* Possibly the target has been engaged in a btrace record started
5039 previously; find out where things are at. */
5040 remote_btrace_maybe_reopen ();
5041
5042 return true;
5043 }
5044
5045 /* Start the remote connection and sync state. */
5046
5047 void
5048 remote_target::start_remote (int from_tty, int extended_p)
5049 {
5050 if (start_remote_1 (from_tty, extended_p)
5051 && breakpoints_should_be_inserted_now ())
5052 insert_breakpoints ();
5053 }
5054
5055 const char *
5056 remote_target::connection_string ()
5057 {
5058 remote_state *rs = get_remote_state ();
5059
5060 if (rs->remote_desc->name != NULL)
5061 return rs->remote_desc->name;
5062 else
5063 return NULL;
5064 }
5065
5066 /* Open a connection to a remote debugger.
5067 NAME is the filename used for communication. */
5068
5069 void
5070 remote_target::open (const char *name, int from_tty)
5071 {
5072 open_1 (name, from_tty, 0);
5073 }
5074
5075 /* Open a connection to a remote debugger using the extended
5076 remote gdb protocol. NAME is the filename used for communication. */
5077
5078 void
5079 extended_remote_target::open (const char *name, int from_tty)
5080 {
5081 open_1 (name, from_tty, 1 /*extended_p */);
5082 }
5083
5084 /* Reset all packets back to "unknown support". Called when opening a
5085 new connection to a remote target. */
5086
5087 static void
5088 reset_all_packet_configs_support (void)
5089 {
5090 int i;
5091
5092 for (i = 0; i < PACKET_MAX; i++)
5093 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5094 }
5095
5096 /* Initialize all packet configs. */
5097
5098 static void
5099 init_all_packet_configs (void)
5100 {
5101 int i;
5102
5103 for (i = 0; i < PACKET_MAX; i++)
5104 {
5105 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5106 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5107 }
5108 }
5109
5110 /* Symbol look-up. */
5111
5112 void
5113 remote_target::remote_check_symbols ()
5114 {
5115 char *tmp;
5116 int end;
5117
5118 /* The remote side has no concept of inferiors that aren't running
5119 yet, it only knows about running processes. If we're connected
5120 but our current inferior is not running, we should not invite the
5121 remote target to request symbol lookups related to its
5122 (unrelated) current process. */
5123 if (!target_has_execution ())
5124 return;
5125
5126 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5127 return;
5128
5129 /* Make sure the remote is pointing at the right process. Note
5130 there's no way to select "no process". */
5131 set_general_process ();
5132
5133 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5134 because we need both at the same time. */
5135 gdb::char_vector msg (get_remote_packet_size ());
5136 gdb::char_vector reply (get_remote_packet_size ());
5137
5138 /* Invite target to request symbol lookups. */
5139
5140 putpkt ("qSymbol::");
5141 getpkt (&reply, 0);
5142 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
5143
5144 while (startswith (reply.data (), "qSymbol:"))
5145 {
5146 struct bound_minimal_symbol sym;
5147
5148 tmp = &reply[8];
5149 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5150 strlen (tmp) / 2);
5151 msg[end] = '\0';
5152 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5153 if (sym.minsym == NULL)
5154 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5155 &reply[8]);
5156 else
5157 {
5158 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5159 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
5160
5161 /* If this is a function address, return the start of code
5162 instead of any data function descriptor. */
5163 sym_addr = gdbarch_convert_from_func_ptr_addr
5164 (target_gdbarch (), sym_addr, current_inferior ()->top_target ());
5165
5166 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5167 phex_nz (sym_addr, addr_size), &reply[8]);
5168 }
5169
5170 putpkt (msg.data ());
5171 getpkt (&reply, 0);
5172 }
5173 }
5174
5175 static struct serial *
5176 remote_serial_open (const char *name)
5177 {
5178 static int udp_warning = 0;
5179
5180 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5181 of in ser-tcp.c, because it is the remote protocol assuming that the
5182 serial connection is reliable and not the serial connection promising
5183 to be. */
5184 if (!udp_warning && startswith (name, "udp:"))
5185 {
5186 warning (_("The remote protocol may be unreliable over UDP.\n"
5187 "Some events may be lost, rendering further debugging "
5188 "impossible."));
5189 udp_warning = 1;
5190 }
5191
5192 return serial_open (name);
5193 }
5194
5195 /* Inform the target of our permission settings. The permission flags
5196 work without this, but if the target knows the settings, it can do
5197 a couple things. First, it can add its own check, to catch cases
5198 that somehow manage to get by the permissions checks in target
5199 methods. Second, if the target is wired to disallow particular
5200 settings (for instance, a system in the field that is not set up to
5201 be able to stop at a breakpoint), it can object to any unavailable
5202 permissions. */
5203
5204 void
5205 remote_target::set_permissions ()
5206 {
5207 struct remote_state *rs = get_remote_state ();
5208
5209 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5210 "WriteReg:%x;WriteMem:%x;"
5211 "InsertBreak:%x;InsertTrace:%x;"
5212 "InsertFastTrace:%x;Stop:%x",
5213 may_write_registers, may_write_memory,
5214 may_insert_breakpoints, may_insert_tracepoints,
5215 may_insert_fast_tracepoints, may_stop);
5216 putpkt (rs->buf);
5217 getpkt (&rs->buf, 0);
5218
5219 /* If the target didn't like the packet, warn the user. Do not try
5220 to undo the user's settings, that would just be maddening. */
5221 if (strcmp (rs->buf.data (), "OK") != 0)
5222 warning (_("Remote refused setting permissions with: %s"),
5223 rs->buf.data ());
5224 }
5225
5226 /* This type describes each known response to the qSupported
5227 packet. */
5228 struct protocol_feature
5229 {
5230 /* The name of this protocol feature. */
5231 const char *name;
5232
5233 /* The default for this protocol feature. */
5234 enum packet_support default_support;
5235
5236 /* The function to call when this feature is reported, or after
5237 qSupported processing if the feature is not supported.
5238 The first argument points to this structure. The second
5239 argument indicates whether the packet requested support be
5240 enabled, disabled, or probed (or the default, if this function
5241 is being called at the end of processing and this feature was
5242 not reported). The third argument may be NULL; if not NULL, it
5243 is a NUL-terminated string taken from the packet following
5244 this feature's name and an equals sign. */
5245 void (*func) (remote_target *remote, const struct protocol_feature *,
5246 enum packet_support, const char *);
5247
5248 /* The corresponding packet for this feature. Only used if
5249 FUNC is remote_supported_packet. */
5250 int packet;
5251 };
5252
5253 static void
5254 remote_supported_packet (remote_target *remote,
5255 const struct protocol_feature *feature,
5256 enum packet_support support,
5257 const char *argument)
5258 {
5259 if (argument)
5260 {
5261 warning (_("Remote qSupported response supplied an unexpected value for"
5262 " \"%s\"."), feature->name);
5263 return;
5264 }
5265
5266 remote_protocol_packets[feature->packet].support = support;
5267 }
5268
5269 void
5270 remote_target::remote_packet_size (const protocol_feature *feature,
5271 enum packet_support support, const char *value)
5272 {
5273 struct remote_state *rs = get_remote_state ();
5274
5275 int packet_size;
5276 char *value_end;
5277
5278 if (support != PACKET_ENABLE)
5279 return;
5280
5281 if (value == NULL || *value == '\0')
5282 {
5283 warning (_("Remote target reported \"%s\" without a size."),
5284 feature->name);
5285 return;
5286 }
5287
5288 errno = 0;
5289 packet_size = strtol (value, &value_end, 16);
5290 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5291 {
5292 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5293 feature->name, value);
5294 return;
5295 }
5296
5297 /* Record the new maximum packet size. */
5298 rs->explicit_packet_size = packet_size;
5299 }
5300
5301 static void
5302 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5303 enum packet_support support, const char *value)
5304 {
5305 remote->remote_packet_size (feature, support, value);
5306 }
5307
5308 static const struct protocol_feature remote_protocol_features[] = {
5309 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5310 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5311 PACKET_qXfer_auxv },
5312 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5313 PACKET_qXfer_exec_file },
5314 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5315 PACKET_qXfer_features },
5316 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5317 PACKET_qXfer_libraries },
5318 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5319 PACKET_qXfer_libraries_svr4 },
5320 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5321 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5322 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5323 PACKET_qXfer_memory_map },
5324 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5325 PACKET_qXfer_osdata },
5326 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5327 PACKET_qXfer_threads },
5328 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5329 PACKET_qXfer_traceframe_info },
5330 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5331 PACKET_QPassSignals },
5332 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5333 PACKET_QCatchSyscalls },
5334 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5335 PACKET_QProgramSignals },
5336 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5337 PACKET_QSetWorkingDir },
5338 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5339 PACKET_QStartupWithShell },
5340 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5341 PACKET_QEnvironmentHexEncoded },
5342 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5343 PACKET_QEnvironmentReset },
5344 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5345 PACKET_QEnvironmentUnset },
5346 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5347 PACKET_QStartNoAckMode },
5348 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5349 PACKET_multiprocess_feature },
5350 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5351 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5352 PACKET_qXfer_siginfo_read },
5353 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5354 PACKET_qXfer_siginfo_write },
5355 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5356 PACKET_ConditionalTracepoints },
5357 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5358 PACKET_ConditionalBreakpoints },
5359 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5360 PACKET_BreakpointCommands },
5361 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5362 PACKET_FastTracepoints },
5363 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5364 PACKET_StaticTracepoints },
5365 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5366 PACKET_InstallInTrace},
5367 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5368 PACKET_DisconnectedTracing_feature },
5369 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5370 PACKET_bc },
5371 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5372 PACKET_bs },
5373 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5374 PACKET_TracepointSource },
5375 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5376 PACKET_QAllow },
5377 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5378 PACKET_EnableDisableTracepoints_feature },
5379 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5380 PACKET_qXfer_fdpic },
5381 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5382 PACKET_qXfer_uib },
5383 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5384 PACKET_QDisableRandomization },
5385 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5386 { "QTBuffer:size", PACKET_DISABLE,
5387 remote_supported_packet, PACKET_QTBuffer_size},
5388 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5389 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5390 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5391 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5392 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5393 PACKET_qXfer_btrace },
5394 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5395 PACKET_qXfer_btrace_conf },
5396 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5397 PACKET_Qbtrace_conf_bts_size },
5398 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5399 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5400 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5401 PACKET_fork_event_feature },
5402 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5403 PACKET_vfork_event_feature },
5404 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5405 PACKET_exec_event_feature },
5406 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5407 PACKET_Qbtrace_conf_pt_size },
5408 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5409 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5410 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5411 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5412 PACKET_memory_tagging_feature },
5413 };
5414
5415 static char *remote_support_xml;
5416
5417 /* Register string appended to "xmlRegisters=" in qSupported query. */
5418
5419 void
5420 register_remote_support_xml (const char *xml)
5421 {
5422 #if defined(HAVE_LIBEXPAT)
5423 if (remote_support_xml == NULL)
5424 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5425 else
5426 {
5427 char *copy = xstrdup (remote_support_xml + 13);
5428 char *saveptr;
5429 char *p = strtok_r (copy, ",", &saveptr);
5430
5431 do
5432 {
5433 if (strcmp (p, xml) == 0)
5434 {
5435 /* already there */
5436 xfree (copy);
5437 return;
5438 }
5439 }
5440 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5441 xfree (copy);
5442
5443 remote_support_xml = reconcat (remote_support_xml,
5444 remote_support_xml, ",", xml,
5445 (char *) NULL);
5446 }
5447 #endif
5448 }
5449
5450 static void
5451 remote_query_supported_append (std::string *msg, const char *append)
5452 {
5453 if (!msg->empty ())
5454 msg->append (";");
5455 msg->append (append);
5456 }
5457
5458 void
5459 remote_target::remote_query_supported ()
5460 {
5461 struct remote_state *rs = get_remote_state ();
5462 char *next;
5463 int i;
5464 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5465
5466 /* The packet support flags are handled differently for this packet
5467 than for most others. We treat an error, a disabled packet, and
5468 an empty response identically: any features which must be reported
5469 to be used will be automatically disabled. An empty buffer
5470 accomplishes this, since that is also the representation for a list
5471 containing no features. */
5472
5473 rs->buf[0] = 0;
5474 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5475 {
5476 std::string q;
5477
5478 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5479 remote_query_supported_append (&q, "multiprocess+");
5480
5481 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5482 remote_query_supported_append (&q, "swbreak+");
5483 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5484 remote_query_supported_append (&q, "hwbreak+");
5485
5486 remote_query_supported_append (&q, "qRelocInsn+");
5487
5488 if (packet_set_cmd_state (PACKET_fork_event_feature)
5489 != AUTO_BOOLEAN_FALSE)
5490 remote_query_supported_append (&q, "fork-events+");
5491 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5492 != AUTO_BOOLEAN_FALSE)
5493 remote_query_supported_append (&q, "vfork-events+");
5494 if (packet_set_cmd_state (PACKET_exec_event_feature)
5495 != AUTO_BOOLEAN_FALSE)
5496 remote_query_supported_append (&q, "exec-events+");
5497
5498 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5499 remote_query_supported_append (&q, "vContSupported+");
5500
5501 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5502 remote_query_supported_append (&q, "QThreadEvents+");
5503
5504 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5505 remote_query_supported_append (&q, "no-resumed+");
5506
5507 if (packet_set_cmd_state (PACKET_memory_tagging_feature)
5508 != AUTO_BOOLEAN_FALSE)
5509 remote_query_supported_append (&q, "memory-tagging+");
5510
5511 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5512 the qSupported:xmlRegisters=i386 handling. */
5513 if (remote_support_xml != NULL
5514 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5515 remote_query_supported_append (&q, remote_support_xml);
5516
5517 q = "qSupported:" + q;
5518 putpkt (q.c_str ());
5519
5520 getpkt (&rs->buf, 0);
5521
5522 /* If an error occured, warn, but do not return - just reset the
5523 buffer to empty and go on to disable features. */
5524 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5525 == PACKET_ERROR)
5526 {
5527 warning (_("Remote failure reply: %s"), rs->buf.data ());
5528 rs->buf[0] = 0;
5529 }
5530 }
5531
5532 memset (seen, 0, sizeof (seen));
5533
5534 next = rs->buf.data ();
5535 while (*next)
5536 {
5537 enum packet_support is_supported;
5538 char *p, *end, *name_end, *value;
5539
5540 /* First separate out this item from the rest of the packet. If
5541 there's another item after this, we overwrite the separator
5542 (terminated strings are much easier to work with). */
5543 p = next;
5544 end = strchr (p, ';');
5545 if (end == NULL)
5546 {
5547 end = p + strlen (p);
5548 next = end;
5549 }
5550 else
5551 {
5552 *end = '\0';
5553 next = end + 1;
5554
5555 if (end == p)
5556 {
5557 warning (_("empty item in \"qSupported\" response"));
5558 continue;
5559 }
5560 }
5561
5562 name_end = strchr (p, '=');
5563 if (name_end)
5564 {
5565 /* This is a name=value entry. */
5566 is_supported = PACKET_ENABLE;
5567 value = name_end + 1;
5568 *name_end = '\0';
5569 }
5570 else
5571 {
5572 value = NULL;
5573 switch (end[-1])
5574 {
5575 case '+':
5576 is_supported = PACKET_ENABLE;
5577 break;
5578
5579 case '-':
5580 is_supported = PACKET_DISABLE;
5581 break;
5582
5583 case '?':
5584 is_supported = PACKET_SUPPORT_UNKNOWN;
5585 break;
5586
5587 default:
5588 warning (_("unrecognized item \"%s\" "
5589 "in \"qSupported\" response"), p);
5590 continue;
5591 }
5592 end[-1] = '\0';
5593 }
5594
5595 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5596 if (strcmp (remote_protocol_features[i].name, p) == 0)
5597 {
5598 const struct protocol_feature *feature;
5599
5600 seen[i] = 1;
5601 feature = &remote_protocol_features[i];
5602 feature->func (this, feature, is_supported, value);
5603 break;
5604 }
5605 }
5606
5607 /* If we increased the packet size, make sure to increase the global
5608 buffer size also. We delay this until after parsing the entire
5609 qSupported packet, because this is the same buffer we were
5610 parsing. */
5611 if (rs->buf.size () < rs->explicit_packet_size)
5612 rs->buf.resize (rs->explicit_packet_size);
5613
5614 /* Handle the defaults for unmentioned features. */
5615 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5616 if (!seen[i])
5617 {
5618 const struct protocol_feature *feature;
5619
5620 feature = &remote_protocol_features[i];
5621 feature->func (this, feature, feature->default_support, NULL);
5622 }
5623 }
5624
5625 /* Serial QUIT handler for the remote serial descriptor.
5626
5627 Defers handling a Ctrl-C until we're done with the current
5628 command/response packet sequence, unless:
5629
5630 - We're setting up the connection. Don't send a remote interrupt
5631 request, as we're not fully synced yet. Quit immediately
5632 instead.
5633
5634 - The target has been resumed in the foreground
5635 (target_terminal::is_ours is false) with a synchronous resume
5636 packet, and we're blocked waiting for the stop reply, thus a
5637 Ctrl-C should be immediately sent to the target.
5638
5639 - We get a second Ctrl-C while still within the same serial read or
5640 write. In that case the serial is seemingly wedged --- offer to
5641 quit/disconnect.
5642
5643 - We see a second Ctrl-C without target response, after having
5644 previously interrupted the target. In that case the target/stub
5645 is probably wedged --- offer to quit/disconnect.
5646 */
5647
5648 void
5649 remote_target::remote_serial_quit_handler ()
5650 {
5651 struct remote_state *rs = get_remote_state ();
5652
5653 if (check_quit_flag ())
5654 {
5655 /* If we're starting up, we're not fully synced yet. Quit
5656 immediately. */
5657 if (rs->starting_up)
5658 quit ();
5659 else if (rs->got_ctrlc_during_io)
5660 {
5661 if (query (_("The target is not responding to GDB commands.\n"
5662 "Stop debugging it? ")))
5663 remote_unpush_and_throw (this);
5664 }
5665 /* If ^C has already been sent once, offer to disconnect. */
5666 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5667 interrupt_query ();
5668 /* All-stop protocol, and blocked waiting for stop reply. Send
5669 an interrupt request. */
5670 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5671 target_interrupt ();
5672 else
5673 rs->got_ctrlc_during_io = 1;
5674 }
5675 }
5676
5677 /* The remote_target that is current while the quit handler is
5678 overridden with remote_serial_quit_handler. */
5679 static remote_target *curr_quit_handler_target;
5680
5681 static void
5682 remote_serial_quit_handler ()
5683 {
5684 curr_quit_handler_target->remote_serial_quit_handler ();
5685 }
5686
5687 /* Remove the remote target from the target stack of each inferior
5688 that is using it. Upper targets depend on it so remove them
5689 first. */
5690
5691 static void
5692 remote_unpush_target (remote_target *target)
5693 {
5694 /* We have to unpush the target from all inferiors, even those that
5695 aren't running. */
5696 scoped_restore_current_inferior restore_current_inferior;
5697
5698 for (inferior *inf : all_inferiors (target))
5699 {
5700 switch_to_inferior_no_thread (inf);
5701 pop_all_targets_at_and_above (process_stratum);
5702 generic_mourn_inferior ();
5703 }
5704
5705 /* Don't rely on target_close doing this when the target is popped
5706 from the last remote inferior above, because something may be
5707 holding a reference to the target higher up on the stack, meaning
5708 target_close won't be called yet. We lost the connection to the
5709 target, so clear these now, otherwise we may later throw
5710 TARGET_CLOSE_ERROR while trying to tell the remote target to
5711 close the file. */
5712 fileio_handles_invalidate_target (target);
5713 }
5714
5715 static void
5716 remote_unpush_and_throw (remote_target *target)
5717 {
5718 remote_unpush_target (target);
5719 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5720 }
5721
5722 void
5723 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5724 {
5725 remote_target *curr_remote = get_current_remote_target ();
5726
5727 if (name == 0)
5728 error (_("To open a remote debug connection, you need to specify what\n"
5729 "serial device is attached to the remote system\n"
5730 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5731
5732 /* If we're connected to a running target, target_preopen will kill it.
5733 Ask this question first, before target_preopen has a chance to kill
5734 anything. */
5735 if (curr_remote != NULL && !target_has_execution ())
5736 {
5737 if (from_tty
5738 && !query (_("Already connected to a remote target. Disconnect? ")))
5739 error (_("Still connected."));
5740 }
5741
5742 /* Here the possibly existing remote target gets unpushed. */
5743 target_preopen (from_tty);
5744
5745 remote_fileio_reset ();
5746 reopen_exec_file ();
5747 reread_symbols (from_tty);
5748
5749 remote_target *remote
5750 = (extended_p ? new extended_remote_target () : new remote_target ());
5751 target_ops_up target_holder (remote);
5752
5753 remote_state *rs = remote->get_remote_state ();
5754
5755 /* See FIXME above. */
5756 if (!target_async_permitted)
5757 rs->wait_forever_enabled_p = 1;
5758
5759 rs->remote_desc = remote_serial_open (name);
5760 if (!rs->remote_desc)
5761 perror_with_name (name);
5762
5763 if (baud_rate != -1)
5764 {
5765 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5766 {
5767 /* The requested speed could not be set. Error out to
5768 top level after closing remote_desc. Take care to
5769 set remote_desc to NULL to avoid closing remote_desc
5770 more than once. */
5771 serial_close (rs->remote_desc);
5772 rs->remote_desc = NULL;
5773 perror_with_name (name);
5774 }
5775 }
5776
5777 serial_setparity (rs->remote_desc, serial_parity);
5778 serial_raw (rs->remote_desc);
5779
5780 /* If there is something sitting in the buffer we might take it as a
5781 response to a command, which would be bad. */
5782 serial_flush_input (rs->remote_desc);
5783
5784 if (from_tty)
5785 {
5786 puts_filtered ("Remote debugging using ");
5787 puts_filtered (name);
5788 puts_filtered ("\n");
5789 }
5790
5791 /* Switch to using the remote target now. */
5792 current_inferior ()->push_target (std::move (target_holder));
5793
5794 /* Register extra event sources in the event loop. */
5795 rs->remote_async_inferior_event_token
5796 = create_async_event_handler (remote_async_inferior_event_handler, nullptr,
5797 "remote");
5798 rs->notif_state = remote_notif_state_allocate (remote);
5799
5800 /* Reset the target state; these things will be queried either by
5801 remote_query_supported or as they are needed. */
5802 reset_all_packet_configs_support ();
5803 rs->explicit_packet_size = 0;
5804 rs->noack_mode = 0;
5805 rs->extended = extended_p;
5806 rs->waiting_for_stop_reply = 0;
5807 rs->ctrlc_pending_p = 0;
5808 rs->got_ctrlc_during_io = 0;
5809
5810 rs->general_thread = not_sent_ptid;
5811 rs->continue_thread = not_sent_ptid;
5812 rs->remote_traceframe_number = -1;
5813
5814 rs->last_resume_exec_dir = EXEC_FORWARD;
5815
5816 /* Probe for ability to use "ThreadInfo" query, as required. */
5817 rs->use_threadinfo_query = 1;
5818 rs->use_threadextra_query = 1;
5819
5820 rs->readahead_cache.invalidate ();
5821
5822 if (target_async_permitted)
5823 {
5824 /* FIXME: cagney/1999-09-23: During the initial connection it is
5825 assumed that the target is already ready and able to respond to
5826 requests. Unfortunately remote_start_remote() eventually calls
5827 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5828 around this. Eventually a mechanism that allows
5829 wait_for_inferior() to expect/get timeouts will be
5830 implemented. */
5831 rs->wait_forever_enabled_p = 0;
5832 }
5833
5834 /* First delete any symbols previously loaded from shared libraries. */
5835 no_shared_libraries (NULL, 0);
5836
5837 /* Start the remote connection. If error() or QUIT, discard this
5838 target (we'd otherwise be in an inconsistent state) and then
5839 propogate the error on up the exception chain. This ensures that
5840 the caller doesn't stumble along blindly assuming that the
5841 function succeeded. The CLI doesn't have this problem but other
5842 UI's, such as MI do.
5843
5844 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5845 this function should return an error indication letting the
5846 caller restore the previous state. Unfortunately the command
5847 ``target remote'' is directly wired to this function making that
5848 impossible. On a positive note, the CLI side of this problem has
5849 been fixed - the function set_cmd_context() makes it possible for
5850 all the ``target ....'' commands to share a common callback
5851 function. See cli-dump.c. */
5852 {
5853
5854 try
5855 {
5856 remote->start_remote (from_tty, extended_p);
5857 }
5858 catch (const gdb_exception &ex)
5859 {
5860 /* Pop the partially set up target - unless something else did
5861 already before throwing the exception. */
5862 if (ex.error != TARGET_CLOSE_ERROR)
5863 remote_unpush_target (remote);
5864 throw;
5865 }
5866 }
5867
5868 remote_btrace_reset (rs);
5869
5870 if (target_async_permitted)
5871 rs->wait_forever_enabled_p = 1;
5872 }
5873
5874 /* Determine if WS represents a fork status. */
5875
5876 static bool
5877 is_fork_status (target_waitkind kind)
5878 {
5879 return (kind == TARGET_WAITKIND_FORKED
5880 || kind == TARGET_WAITKIND_VFORKED);
5881 }
5882
5883 /* Return THREAD's pending status if it is a pending fork parent, else
5884 return nullptr. */
5885
5886 static const target_waitstatus *
5887 thread_pending_fork_status (struct thread_info *thread)
5888 {
5889 const target_waitstatus &ws
5890 = (thread->has_pending_waitstatus ()
5891 ? thread->pending_waitstatus ()
5892 : thread->pending_follow);
5893
5894 if (!is_fork_status (ws.kind ()))
5895 return nullptr;
5896
5897 return &ws;
5898 }
5899
5900 /* Detach the specified process. */
5901
5902 void
5903 remote_target::remote_detach_pid (int pid)
5904 {
5905 struct remote_state *rs = get_remote_state ();
5906
5907 /* This should not be necessary, but the handling for D;PID in
5908 GDBserver versions prior to 8.2 incorrectly assumes that the
5909 selected process points to the same process we're detaching,
5910 leading to misbehavior (and possibly GDBserver crashing) when it
5911 does not. Since it's easy and cheap, work around it by forcing
5912 GDBserver to select GDB's current process. */
5913 set_general_process ();
5914
5915 if (remote_multi_process_p (rs))
5916 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
5917 else
5918 strcpy (rs->buf.data (), "D");
5919
5920 putpkt (rs->buf);
5921 getpkt (&rs->buf, 0);
5922
5923 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5924 ;
5925 else if (rs->buf[0] == '\0')
5926 error (_("Remote doesn't know how to detach"));
5927 else
5928 error (_("Can't detach process."));
5929 }
5930
5931 /* This detaches a program to which we previously attached, using
5932 inferior_ptid to identify the process. After this is done, GDB
5933 can be used to debug some other program. We better not have left
5934 any breakpoints in the target program or it'll die when it hits
5935 one. */
5936
5937 void
5938 remote_target::remote_detach_1 (inferior *inf, int from_tty)
5939 {
5940 int pid = inferior_ptid.pid ();
5941 struct remote_state *rs = get_remote_state ();
5942 int is_fork_parent;
5943
5944 if (!target_has_execution ())
5945 error (_("No process to detach from."));
5946
5947 target_announce_detach (from_tty);
5948
5949 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
5950 {
5951 /* If we're in breakpoints-always-inserted mode, or the inferior
5952 is running, we have to remove breakpoints before detaching.
5953 We don't do this in common code instead because not all
5954 targets support removing breakpoints while the target is
5955 running. The remote target / gdbserver does, though. */
5956 remove_breakpoints_inf (current_inferior ());
5957 }
5958
5959 /* Tell the remote target to detach. */
5960 remote_detach_pid (pid);
5961
5962 /* Exit only if this is the only active inferior. */
5963 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
5964 puts_filtered (_("Ending remote debugging.\n"));
5965
5966 /* See if any thread of the inferior we are detaching has a pending fork
5967 status. In that case, we must detach from the child resulting from
5968 that fork. */
5969 for (thread_info *thread : inf->non_exited_threads ())
5970 {
5971 const target_waitstatus *ws = thread_pending_fork_status (thread);
5972
5973 if (ws == nullptr)
5974 continue;
5975
5976 remote_detach_pid (ws->child_ptid ().pid ());
5977 }
5978
5979 /* Check also for any pending fork events in the stop reply queue. */
5980 remote_notif_get_pending_events (&notif_client_stop);
5981 for (stop_reply_up &reply : rs->stop_reply_queue)
5982 {
5983 if (reply->ptid.pid () != pid)
5984 continue;
5985
5986 if (!is_fork_status (reply->ws.kind ()))
5987 continue;
5988
5989 remote_detach_pid (reply->ws.child_ptid ().pid ());
5990 }
5991
5992 thread_info *tp = find_thread_ptid (this, inferior_ptid);
5993
5994 /* Check to see if we are detaching a fork parent. Note that if we
5995 are detaching a fork child, tp == NULL. */
5996 is_fork_parent = (tp != NULL
5997 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
5998
5999 /* If doing detach-on-fork, we don't mourn, because that will delete
6000 breakpoints that should be available for the followed inferior. */
6001 if (!is_fork_parent)
6002 {
6003 /* Save the pid as a string before mourning, since that will
6004 unpush the remote target, and we need the string after. */
6005 std::string infpid = target_pid_to_str (ptid_t (pid));
6006
6007 target_mourn_inferior (inferior_ptid);
6008 if (print_inferior_events)
6009 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
6010 inf->num, infpid.c_str ());
6011 }
6012 else
6013 {
6014 switch_to_no_thread ();
6015 detach_inferior (current_inferior ());
6016 }
6017 }
6018
6019 void
6020 remote_target::detach (inferior *inf, int from_tty)
6021 {
6022 remote_detach_1 (inf, from_tty);
6023 }
6024
6025 void
6026 extended_remote_target::detach (inferior *inf, int from_tty)
6027 {
6028 remote_detach_1 (inf, from_tty);
6029 }
6030
6031 /* Target follow-fork function for remote targets. On entry, and
6032 at return, the current inferior is the fork parent.
6033
6034 Note that although this is currently only used for extended-remote,
6035 it is named remote_follow_fork in anticipation of using it for the
6036 remote target as well. */
6037
6038 void
6039 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6040 target_waitkind fork_kind, bool follow_child,
6041 bool detach_fork)
6042 {
6043 process_stratum_target::follow_fork (child_inf, child_ptid,
6044 fork_kind, follow_child, detach_fork);
6045
6046 struct remote_state *rs = get_remote_state ();
6047
6048 if ((fork_kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
6049 || (fork_kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
6050 {
6051 /* When following the parent and detaching the child, we detach
6052 the child here. For the case of following the child and
6053 detaching the parent, the detach is done in the target-
6054 independent follow fork code in infrun.c. We can't use
6055 target_detach when detaching an unfollowed child because
6056 the client side doesn't know anything about the child. */
6057 if (detach_fork && !follow_child)
6058 {
6059 /* Detach the fork child. */
6060 remote_detach_pid (child_ptid.pid ());
6061 }
6062 }
6063 }
6064
6065 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6066 in the program space of the new inferior. */
6067
6068 void
6069 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6070 const char *execd_pathname)
6071 {
6072 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6073
6074 /* We know that this is a target file name, so if it has the "target:"
6075 prefix we strip it off before saving it in the program space. */
6076 if (is_target_filename (execd_pathname))
6077 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6078
6079 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6080 }
6081
6082 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6083
6084 void
6085 remote_target::disconnect (const char *args, int from_tty)
6086 {
6087 if (args)
6088 error (_("Argument given to \"disconnect\" when remotely debugging."));
6089
6090 /* Make sure we unpush even the extended remote targets. Calling
6091 target_mourn_inferior won't unpush, and
6092 remote_target::mourn_inferior won't unpush if there is more than
6093 one inferior left. */
6094 remote_unpush_target (this);
6095
6096 if (from_tty)
6097 puts_filtered ("Ending remote debugging.\n");
6098 }
6099
6100 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6101 be chatty about it. */
6102
6103 void
6104 extended_remote_target::attach (const char *args, int from_tty)
6105 {
6106 struct remote_state *rs = get_remote_state ();
6107 int pid;
6108 char *wait_status = NULL;
6109
6110 pid = parse_pid_to_attach (args);
6111
6112 /* Remote PID can be freely equal to getpid, do not check it here the same
6113 way as in other targets. */
6114
6115 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
6116 error (_("This target does not support attaching to a process"));
6117
6118 if (from_tty)
6119 {
6120 const char *exec_file = get_exec_file (0);
6121
6122 if (exec_file)
6123 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
6124 target_pid_to_str (ptid_t (pid)).c_str ());
6125 else
6126 printf_unfiltered (_("Attaching to %s\n"),
6127 target_pid_to_str (ptid_t (pid)).c_str ());
6128 }
6129
6130 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6131 putpkt (rs->buf);
6132 getpkt (&rs->buf, 0);
6133
6134 switch (packet_ok (rs->buf,
6135 &remote_protocol_packets[PACKET_vAttach]))
6136 {
6137 case PACKET_OK:
6138 if (!target_is_non_stop_p ())
6139 {
6140 /* Save the reply for later. */
6141 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6142 strcpy (wait_status, rs->buf.data ());
6143 }
6144 else if (strcmp (rs->buf.data (), "OK") != 0)
6145 error (_("Attaching to %s failed with: %s"),
6146 target_pid_to_str (ptid_t (pid)).c_str (),
6147 rs->buf.data ());
6148 break;
6149 case PACKET_UNKNOWN:
6150 error (_("This target does not support attaching to a process"));
6151 default:
6152 error (_("Attaching to %s failed"),
6153 target_pid_to_str (ptid_t (pid)).c_str ());
6154 }
6155
6156 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6157
6158 inferior_ptid = ptid_t (pid);
6159
6160 if (target_is_non_stop_p ())
6161 {
6162 /* Get list of threads. */
6163 update_thread_list ();
6164
6165 thread_info *thread = first_thread_of_inferior (current_inferior ());
6166 if (thread != nullptr)
6167 switch_to_thread (thread);
6168
6169 /* Invalidate our notion of the remote current thread. */
6170 record_currthread (rs, minus_one_ptid);
6171 }
6172 else
6173 {
6174 /* Now, if we have thread information, update the main thread's
6175 ptid. */
6176 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6177
6178 /* Add the main thread to the thread list. We add the thread
6179 silently in this case (the final true parameter). */
6180 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
6181
6182 switch_to_thread (thr);
6183 }
6184
6185 /* Next, if the target can specify a description, read it. We do
6186 this before anything involving memory or registers. */
6187 target_find_description ();
6188
6189 if (!target_is_non_stop_p ())
6190 {
6191 /* Use the previously fetched status. */
6192 gdb_assert (wait_status != NULL);
6193
6194 struct notif_event *reply
6195 = remote_notif_parse (this, &notif_client_stop, wait_status);
6196
6197 push_stop_reply ((struct stop_reply *) reply);
6198
6199 if (target_can_async_p ())
6200 target_async (1);
6201 }
6202 else
6203 {
6204 gdb_assert (wait_status == NULL);
6205
6206 gdb_assert (target_can_async_p ());
6207 target_async (1);
6208 }
6209 }
6210
6211 /* Implementation of the to_post_attach method. */
6212
6213 void
6214 extended_remote_target::post_attach (int pid)
6215 {
6216 /* Get text, data & bss offsets. */
6217 get_offsets ();
6218
6219 /* In certain cases GDB might not have had the chance to start
6220 symbol lookup up until now. This could happen if the debugged
6221 binary is not using shared libraries, the vsyscall page is not
6222 present (on Linux) and the binary itself hadn't changed since the
6223 debugging process was started. */
6224 if (current_program_space->symfile_object_file != NULL)
6225 remote_check_symbols();
6226 }
6227
6228 \f
6229 /* Check for the availability of vCont. This function should also check
6230 the response. */
6231
6232 void
6233 remote_target::remote_vcont_probe ()
6234 {
6235 remote_state *rs = get_remote_state ();
6236 char *buf;
6237
6238 strcpy (rs->buf.data (), "vCont?");
6239 putpkt (rs->buf);
6240 getpkt (&rs->buf, 0);
6241 buf = rs->buf.data ();
6242
6243 /* Make sure that the features we assume are supported. */
6244 if (startswith (buf, "vCont"))
6245 {
6246 char *p = &buf[5];
6247 int support_c, support_C;
6248
6249 rs->supports_vCont.s = 0;
6250 rs->supports_vCont.S = 0;
6251 support_c = 0;
6252 support_C = 0;
6253 rs->supports_vCont.t = 0;
6254 rs->supports_vCont.r = 0;
6255 while (p && *p == ';')
6256 {
6257 p++;
6258 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6259 rs->supports_vCont.s = 1;
6260 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6261 rs->supports_vCont.S = 1;
6262 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6263 support_c = 1;
6264 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6265 support_C = 1;
6266 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6267 rs->supports_vCont.t = 1;
6268 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6269 rs->supports_vCont.r = 1;
6270
6271 p = strchr (p, ';');
6272 }
6273
6274 /* If c, and C are not all supported, we can't use vCont. Clearing
6275 BUF will make packet_ok disable the packet. */
6276 if (!support_c || !support_C)
6277 buf[0] = 0;
6278 }
6279
6280 packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCont]);
6281 rs->supports_vCont_probed = true;
6282 }
6283
6284 /* Helper function for building "vCont" resumptions. Write a
6285 resumption to P. ENDP points to one-passed-the-end of the buffer
6286 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6287 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6288 resumed thread should be single-stepped and/or signalled. If PTID
6289 equals minus_one_ptid, then all threads are resumed; if PTID
6290 represents a process, then all threads of the process are resumed;
6291 the thread to be stepped and/or signalled is given in the global
6292 INFERIOR_PTID. */
6293
6294 char *
6295 remote_target::append_resumption (char *p, char *endp,
6296 ptid_t ptid, int step, gdb_signal siggnal)
6297 {
6298 struct remote_state *rs = get_remote_state ();
6299
6300 if (step && siggnal != GDB_SIGNAL_0)
6301 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6302 else if (step
6303 /* GDB is willing to range step. */
6304 && use_range_stepping
6305 /* Target supports range stepping. */
6306 && rs->supports_vCont.r
6307 /* We don't currently support range stepping multiple
6308 threads with a wildcard (though the protocol allows it,
6309 so stubs shouldn't make an active effort to forbid
6310 it). */
6311 && !(remote_multi_process_p (rs) && ptid.is_pid ()))
6312 {
6313 struct thread_info *tp;
6314
6315 if (ptid == minus_one_ptid)
6316 {
6317 /* If we don't know about the target thread's tid, then
6318 we're resuming magic_null_ptid (see caller). */
6319 tp = find_thread_ptid (this, magic_null_ptid);
6320 }
6321 else
6322 tp = find_thread_ptid (this, ptid);
6323 gdb_assert (tp != NULL);
6324
6325 if (tp->control.may_range_step)
6326 {
6327 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6328
6329 p += xsnprintf (p, endp - p, ";r%s,%s",
6330 phex_nz (tp->control.step_range_start,
6331 addr_size),
6332 phex_nz (tp->control.step_range_end,
6333 addr_size));
6334 }
6335 else
6336 p += xsnprintf (p, endp - p, ";s");
6337 }
6338 else if (step)
6339 p += xsnprintf (p, endp - p, ";s");
6340 else if (siggnal != GDB_SIGNAL_0)
6341 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6342 else
6343 p += xsnprintf (p, endp - p, ";c");
6344
6345 if (remote_multi_process_p (rs) && ptid.is_pid ())
6346 {
6347 ptid_t nptid;
6348
6349 /* All (-1) threads of process. */
6350 nptid = ptid_t (ptid.pid (), -1);
6351
6352 p += xsnprintf (p, endp - p, ":");
6353 p = write_ptid (p, endp, nptid);
6354 }
6355 else if (ptid != minus_one_ptid)
6356 {
6357 p += xsnprintf (p, endp - p, ":");
6358 p = write_ptid (p, endp, ptid);
6359 }
6360
6361 return p;
6362 }
6363
6364 /* Clear the thread's private info on resume. */
6365
6366 static void
6367 resume_clear_thread_private_info (struct thread_info *thread)
6368 {
6369 if (thread->priv != NULL)
6370 {
6371 remote_thread_info *priv = get_remote_thread_info (thread);
6372
6373 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6374 priv->watch_data_address = 0;
6375 }
6376 }
6377
6378 /* Append a vCont continue-with-signal action for threads that have a
6379 non-zero stop signal. */
6380
6381 char *
6382 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6383 ptid_t ptid)
6384 {
6385 for (thread_info *thread : all_non_exited_threads (this, ptid))
6386 if (inferior_ptid != thread->ptid
6387 && thread->stop_signal () != GDB_SIGNAL_0)
6388 {
6389 p = append_resumption (p, endp, thread->ptid,
6390 0, thread->stop_signal ());
6391 thread->set_stop_signal (GDB_SIGNAL_0);
6392 resume_clear_thread_private_info (thread);
6393 }
6394
6395 return p;
6396 }
6397
6398 /* Set the target running, using the packets that use Hc
6399 (c/s/C/S). */
6400
6401 void
6402 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6403 gdb_signal siggnal)
6404 {
6405 struct remote_state *rs = get_remote_state ();
6406 char *buf;
6407
6408 rs->last_sent_signal = siggnal;
6409 rs->last_sent_step = step;
6410
6411 /* The c/s/C/S resume packets use Hc, so set the continue
6412 thread. */
6413 if (ptid == minus_one_ptid)
6414 set_continue_thread (any_thread_ptid);
6415 else
6416 set_continue_thread (ptid);
6417
6418 for (thread_info *thread : all_non_exited_threads (this))
6419 resume_clear_thread_private_info (thread);
6420
6421 buf = rs->buf.data ();
6422 if (::execution_direction == EXEC_REVERSE)
6423 {
6424 /* We don't pass signals to the target in reverse exec mode. */
6425 if (info_verbose && siggnal != GDB_SIGNAL_0)
6426 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6427 siggnal);
6428
6429 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6430 error (_("Remote reverse-step not supported."));
6431 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6432 error (_("Remote reverse-continue not supported."));
6433
6434 strcpy (buf, step ? "bs" : "bc");
6435 }
6436 else if (siggnal != GDB_SIGNAL_0)
6437 {
6438 buf[0] = step ? 'S' : 'C';
6439 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6440 buf[2] = tohex (((int) siggnal) & 0xf);
6441 buf[3] = '\0';
6442 }
6443 else
6444 strcpy (buf, step ? "s" : "c");
6445
6446 putpkt (buf);
6447 }
6448
6449 /* Resume the remote inferior by using a "vCont" packet. The thread
6450 to be resumed is PTID; STEP and SIGGNAL indicate whether the
6451 resumed thread should be single-stepped and/or signalled. If PTID
6452 equals minus_one_ptid, then all threads are resumed; the thread to
6453 be stepped and/or signalled is given in the global INFERIOR_PTID.
6454 This function returns non-zero iff it resumes the inferior.
6455
6456 This function issues a strict subset of all possible vCont commands
6457 at the moment. */
6458
6459 int
6460 remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6461 enum gdb_signal siggnal)
6462 {
6463 struct remote_state *rs = get_remote_state ();
6464 char *p;
6465 char *endp;
6466
6467 /* No reverse execution actions defined for vCont. */
6468 if (::execution_direction == EXEC_REVERSE)
6469 return 0;
6470
6471 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6472 remote_vcont_probe ();
6473
6474 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6475 return 0;
6476
6477 p = rs->buf.data ();
6478 endp = p + get_remote_packet_size ();
6479
6480 /* If we could generate a wider range of packets, we'd have to worry
6481 about overflowing BUF. Should there be a generic
6482 "multi-part-packet" packet? */
6483
6484 p += xsnprintf (p, endp - p, "vCont");
6485
6486 if (ptid == magic_null_ptid)
6487 {
6488 /* MAGIC_NULL_PTID means that we don't have any active threads,
6489 so we don't have any TID numbers the inferior will
6490 understand. Make sure to only send forms that do not specify
6491 a TID. */
6492 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6493 }
6494 else if (ptid == minus_one_ptid || ptid.is_pid ())
6495 {
6496 /* Resume all threads (of all processes, or of a single
6497 process), with preference for INFERIOR_PTID. This assumes
6498 inferior_ptid belongs to the set of all threads we are about
6499 to resume. */
6500 if (step || siggnal != GDB_SIGNAL_0)
6501 {
6502 /* Step inferior_ptid, with or without signal. */
6503 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6504 }
6505
6506 /* Also pass down any pending signaled resumption for other
6507 threads not the current. */
6508 p = append_pending_thread_resumptions (p, endp, ptid);
6509
6510 /* And continue others without a signal. */
6511 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
6512 }
6513 else
6514 {
6515 /* Scheduler locking; resume only PTID. */
6516 append_resumption (p, endp, ptid, step, siggnal);
6517 }
6518
6519 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6520 putpkt (rs->buf);
6521
6522 if (target_is_non_stop_p ())
6523 {
6524 /* In non-stop, the stub replies to vCont with "OK". The stop
6525 reply will be reported asynchronously by means of a `%Stop'
6526 notification. */
6527 getpkt (&rs->buf, 0);
6528 if (strcmp (rs->buf.data (), "OK") != 0)
6529 error (_("Unexpected vCont reply in non-stop mode: %s"),
6530 rs->buf.data ());
6531 }
6532
6533 return 1;
6534 }
6535
6536 /* Tell the remote machine to resume. */
6537
6538 void
6539 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
6540 {
6541 struct remote_state *rs = get_remote_state ();
6542
6543 /* When connected in non-stop mode, the core resumes threads
6544 individually. Resuming remote threads directly in target_resume
6545 would thus result in sending one packet per thread. Instead, to
6546 minimize roundtrip latency, here we just store the resume
6547 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6548 resumption will be done in remote_target::commit_resume, where we'll be
6549 able to do vCont action coalescing. */
6550 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6551 {
6552 remote_thread_info *remote_thr;
6553
6554 if (minus_one_ptid == ptid || ptid.is_pid ())
6555 remote_thr = get_remote_thread_info (this, inferior_ptid);
6556 else
6557 remote_thr = get_remote_thread_info (this, ptid);
6558
6559 /* We don't expect the core to ask to resume an already resumed (from
6560 its point of view) thread. */
6561 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6562
6563 remote_thr->set_resumed_pending_vcont (step, siggnal);
6564 return;
6565 }
6566
6567 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6568 (explained in remote-notif.c:handle_notification) so
6569 remote_notif_process is not called. We need find a place where
6570 it is safe to start a 'vNotif' sequence. It is good to do it
6571 before resuming inferior, because inferior was stopped and no RSP
6572 traffic at that moment. */
6573 if (!target_is_non_stop_p ())
6574 remote_notif_process (rs->notif_state, &notif_client_stop);
6575
6576 rs->last_resume_exec_dir = ::execution_direction;
6577
6578 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6579 if (!remote_resume_with_vcont (ptid, step, siggnal))
6580 remote_resume_with_hc (ptid, step, siggnal);
6581
6582 /* Update resumed state tracked by the remote target. */
6583 for (thread_info *tp : all_non_exited_threads (this, ptid))
6584 get_remote_thread_info (tp)->set_resumed ();
6585
6586 /* We are about to start executing the inferior, let's register it
6587 with the event loop. NOTE: this is the one place where all the
6588 execution commands end up. We could alternatively do this in each
6589 of the execution commands in infcmd.c. */
6590 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6591 into infcmd.c in order to allow inferior function calls to work
6592 NOT asynchronously. */
6593 if (target_can_async_p ())
6594 target_async (1);
6595
6596 /* We've just told the target to resume. The remote server will
6597 wait for the inferior to stop, and then send a stop reply. In
6598 the mean time, we can't start another command/query ourselves
6599 because the stub wouldn't be ready to process it. This applies
6600 only to the base all-stop protocol, however. In non-stop (which
6601 only supports vCont), the stub replies with an "OK", and is
6602 immediate able to process further serial input. */
6603 if (!target_is_non_stop_p ())
6604 rs->waiting_for_stop_reply = 1;
6605 }
6606
6607 /* Private per-inferior info for target remote processes. */
6608
6609 struct remote_inferior : public private_inferior
6610 {
6611 /* Whether we can send a wildcard vCont for this process. */
6612 bool may_wildcard_vcont = true;
6613 };
6614
6615 /* Get the remote private inferior data associated to INF. */
6616
6617 static remote_inferior *
6618 get_remote_inferior (inferior *inf)
6619 {
6620 if (inf->priv == NULL)
6621 inf->priv.reset (new remote_inferior);
6622
6623 return static_cast<remote_inferior *> (inf->priv.get ());
6624 }
6625
6626 /* Class used to track the construction of a vCont packet in the
6627 outgoing packet buffer. This is used to send multiple vCont
6628 packets if we have more actions than would fit a single packet. */
6629
6630 class vcont_builder
6631 {
6632 public:
6633 explicit vcont_builder (remote_target *remote)
6634 : m_remote (remote)
6635 {
6636 restart ();
6637 }
6638
6639 void flush ();
6640 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6641
6642 private:
6643 void restart ();
6644
6645 /* The remote target. */
6646 remote_target *m_remote;
6647
6648 /* Pointer to the first action. P points here if no action has been
6649 appended yet. */
6650 char *m_first_action;
6651
6652 /* Where the next action will be appended. */
6653 char *m_p;
6654
6655 /* The end of the buffer. Must never write past this. */
6656 char *m_endp;
6657 };
6658
6659 /* Prepare the outgoing buffer for a new vCont packet. */
6660
6661 void
6662 vcont_builder::restart ()
6663 {
6664 struct remote_state *rs = m_remote->get_remote_state ();
6665
6666 m_p = rs->buf.data ();
6667 m_endp = m_p + m_remote->get_remote_packet_size ();
6668 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6669 m_first_action = m_p;
6670 }
6671
6672 /* If the vCont packet being built has any action, send it to the
6673 remote end. */
6674
6675 void
6676 vcont_builder::flush ()
6677 {
6678 struct remote_state *rs;
6679
6680 if (m_p == m_first_action)
6681 return;
6682
6683 rs = m_remote->get_remote_state ();
6684 m_remote->putpkt (rs->buf);
6685 m_remote->getpkt (&rs->buf, 0);
6686 if (strcmp (rs->buf.data (), "OK") != 0)
6687 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
6688 }
6689
6690 /* The largest action is range-stepping, with its two addresses. This
6691 is more than sufficient. If a new, bigger action is created, it'll
6692 quickly trigger a failed assertion in append_resumption (and we'll
6693 just bump this). */
6694 #define MAX_ACTION_SIZE 200
6695
6696 /* Append a new vCont action in the outgoing packet being built. If
6697 the action doesn't fit the packet along with previous actions, push
6698 what we've got so far to the remote end and start over a new vCont
6699 packet (with the new action). */
6700
6701 void
6702 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6703 {
6704 char buf[MAX_ACTION_SIZE + 1];
6705
6706 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6707 ptid, step, siggnal);
6708
6709 /* Check whether this new action would fit in the vCont packet along
6710 with previous actions. If not, send what we've got so far and
6711 start a new vCont packet. */
6712 size_t rsize = endp - buf;
6713 if (rsize > m_endp - m_p)
6714 {
6715 flush ();
6716 restart ();
6717
6718 /* Should now fit. */
6719 gdb_assert (rsize <= m_endp - m_p);
6720 }
6721
6722 memcpy (m_p, buf, rsize);
6723 m_p += rsize;
6724 *m_p = '\0';
6725 }
6726
6727 /* to_commit_resume implementation. */
6728
6729 void
6730 remote_target::commit_resumed ()
6731 {
6732 /* If connected in all-stop mode, we'd send the remote resume
6733 request directly from remote_resume. Likewise if
6734 reverse-debugging, as there are no defined vCont actions for
6735 reverse execution. */
6736 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6737 return;
6738
6739 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6740 instead of resuming all threads of each process individually.
6741 However, if any thread of a process must remain halted, we can't
6742 send wildcard resumes and must send one action per thread.
6743
6744 Care must be taken to not resume threads/processes the server
6745 side already told us are stopped, but the core doesn't know about
6746 yet, because the events are still in the vStopped notification
6747 queue. For example:
6748
6749 #1 => vCont s:p1.1;c
6750 #2 <= OK
6751 #3 <= %Stopped T05 p1.1
6752 #4 => vStopped
6753 #5 <= T05 p1.2
6754 #6 => vStopped
6755 #7 <= OK
6756 #8 (infrun handles the stop for p1.1 and continues stepping)
6757 #9 => vCont s:p1.1;c
6758
6759 The last vCont above would resume thread p1.2 by mistake, because
6760 the server has no idea that the event for p1.2 had not been
6761 handled yet.
6762
6763 The server side must similarly ignore resume actions for the
6764 thread that has a pending %Stopped notification (and any other
6765 threads with events pending), until GDB acks the notification
6766 with vStopped. Otherwise, e.g., the following case is
6767 mishandled:
6768
6769 #1 => g (or any other packet)
6770 #2 <= [registers]
6771 #3 <= %Stopped T05 p1.2
6772 #4 => vCont s:p1.1;c
6773 #5 <= OK
6774
6775 Above, the server must not resume thread p1.2. GDB can't know
6776 that p1.2 stopped until it acks the %Stopped notification, and
6777 since from GDB's perspective all threads should be running, it
6778 sends a "c" action.
6779
6780 Finally, special care must also be given to handling fork/vfork
6781 events. A (v)fork event actually tells us that two processes
6782 stopped -- the parent and the child. Until we follow the fork,
6783 we must not resume the child. Therefore, if we have a pending
6784 fork follow, we must not send a global wildcard resume action
6785 (vCont;c). We can still send process-wide wildcards though. */
6786
6787 /* Start by assuming a global wildcard (vCont;c) is possible. */
6788 bool may_global_wildcard_vcont = true;
6789
6790 /* And assume every process is individually wildcard-able too. */
6791 for (inferior *inf : all_non_exited_inferiors (this))
6792 {
6793 remote_inferior *priv = get_remote_inferior (inf);
6794
6795 priv->may_wildcard_vcont = true;
6796 }
6797
6798 /* Check for any pending events (not reported or processed yet) and
6799 disable process and global wildcard resumes appropriately. */
6800 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6801
6802 bool any_pending_vcont_resume = false;
6803
6804 for (thread_info *tp : all_non_exited_threads (this))
6805 {
6806 remote_thread_info *priv = get_remote_thread_info (tp);
6807
6808 /* If a thread of a process is not meant to be resumed, then we
6809 can't wildcard that process. */
6810 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
6811 {
6812 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6813
6814 /* And if we can't wildcard a process, we can't wildcard
6815 everything either. */
6816 may_global_wildcard_vcont = false;
6817 continue;
6818 }
6819
6820 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
6821 any_pending_vcont_resume = true;
6822
6823 /* If a thread is the parent of an unfollowed fork, then we
6824 can't do a global wildcard, as that would resume the fork
6825 child. */
6826 if (thread_pending_fork_status (tp) != nullptr)
6827 may_global_wildcard_vcont = false;
6828 }
6829
6830 /* We didn't have any resumed thread pending a vCont resume, so nothing to
6831 do. */
6832 if (!any_pending_vcont_resume)
6833 return;
6834
6835 /* Now let's build the vCont packet(s). Actions must be appended
6836 from narrower to wider scopes (thread -> process -> global). If
6837 we end up with too many actions for a single packet vcont_builder
6838 flushes the current vCont packet to the remote side and starts a
6839 new one. */
6840 struct vcont_builder vcont_builder (this);
6841
6842 /* Threads first. */
6843 for (thread_info *tp : all_non_exited_threads (this))
6844 {
6845 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6846
6847 /* If the thread was previously vCont-resumed, no need to send a specific
6848 action for it. If we didn't receive a resume request for it, don't
6849 send an action for it either. */
6850 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
6851 continue;
6852
6853 gdb_assert (!thread_is_in_step_over_chain (tp));
6854
6855 /* We should never be commit-resuming a thread that has a stop reply.
6856 Otherwise, we would end up reporting a stop event for a thread while
6857 it is running on the remote target. */
6858 remote_state *rs = get_remote_state ();
6859 for (const auto &stop_reply : rs->stop_reply_queue)
6860 gdb_assert (stop_reply->ptid != tp->ptid);
6861
6862 const resumed_pending_vcont_info &info
6863 = remote_thr->resumed_pending_vcont_info ();
6864
6865 /* Check if we need to send a specific action for this thread. If not,
6866 it will be included in a wildcard resume instead. */
6867 if (info.step || info.sig != GDB_SIGNAL_0
6868 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
6869 vcont_builder.push_action (tp->ptid, info.step, info.sig);
6870
6871 remote_thr->set_resumed ();
6872 }
6873
6874 /* Now check whether we can send any process-wide wildcard. This is
6875 to avoid sending a global wildcard in the case nothing is
6876 supposed to be resumed. */
6877 bool any_process_wildcard = false;
6878
6879 for (inferior *inf : all_non_exited_inferiors (this))
6880 {
6881 if (get_remote_inferior (inf)->may_wildcard_vcont)
6882 {
6883 any_process_wildcard = true;
6884 break;
6885 }
6886 }
6887
6888 if (any_process_wildcard)
6889 {
6890 /* If all processes are wildcard-able, then send a single "c"
6891 action, otherwise, send an "all (-1) threads of process"
6892 continue action for each running process, if any. */
6893 if (may_global_wildcard_vcont)
6894 {
6895 vcont_builder.push_action (minus_one_ptid,
6896 false, GDB_SIGNAL_0);
6897 }
6898 else
6899 {
6900 for (inferior *inf : all_non_exited_inferiors (this))
6901 {
6902 if (get_remote_inferior (inf)->may_wildcard_vcont)
6903 {
6904 vcont_builder.push_action (ptid_t (inf->pid),
6905 false, GDB_SIGNAL_0);
6906 }
6907 }
6908 }
6909 }
6910
6911 vcont_builder.flush ();
6912 }
6913
6914 /* Implementation of target_has_pending_events. */
6915
6916 bool
6917 remote_target::has_pending_events ()
6918 {
6919 if (target_can_async_p ())
6920 {
6921 remote_state *rs = get_remote_state ();
6922
6923 if (async_event_handler_marked (rs->remote_async_inferior_event_token))
6924 return true;
6925
6926 /* Note that BUFCNT can be negative, indicating sticky
6927 error. */
6928 if (rs->remote_desc->bufcnt != 0)
6929 return true;
6930 }
6931 return false;
6932 }
6933
6934 \f
6935
6936 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6937 thread, all threads of a remote process, or all threads of all
6938 processes. */
6939
6940 void
6941 remote_target::remote_stop_ns (ptid_t ptid)
6942 {
6943 struct remote_state *rs = get_remote_state ();
6944 char *p = rs->buf.data ();
6945 char *endp = p + get_remote_packet_size ();
6946
6947 /* If any thread that needs to stop was resumed but pending a vCont
6948 resume, generate a phony stop_reply. However, first check
6949 whether the thread wasn't resumed with a signal. Generating a
6950 phony stop in that case would result in losing the signal. */
6951 bool needs_commit = false;
6952 for (thread_info *tp : all_non_exited_threads (this, ptid))
6953 {
6954 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6955
6956 if (remote_thr->get_resume_state ()
6957 == resume_state::RESUMED_PENDING_VCONT)
6958 {
6959 const resumed_pending_vcont_info &info
6960 = remote_thr->resumed_pending_vcont_info ();
6961 if (info.sig != GDB_SIGNAL_0)
6962 {
6963 /* This signal must be forwarded to the inferior. We
6964 could commit-resume just this thread, but its simpler
6965 to just commit-resume everything. */
6966 needs_commit = true;
6967 break;
6968 }
6969 }
6970 }
6971
6972 if (needs_commit)
6973 commit_resumed ();
6974 else
6975 for (thread_info *tp : all_non_exited_threads (this, ptid))
6976 {
6977 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6978
6979 if (remote_thr->get_resume_state ()
6980 == resume_state::RESUMED_PENDING_VCONT)
6981 {
6982 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
6983 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
6984 tp->ptid.lwp (),
6985 pulongest (tp->ptid.tid ()));
6986
6987 /* Check that the thread wasn't resumed with a signal.
6988 Generating a phony stop would result in losing the
6989 signal. */
6990 const resumed_pending_vcont_info &info
6991 = remote_thr->resumed_pending_vcont_info ();
6992 gdb_assert (info.sig == GDB_SIGNAL_0);
6993
6994 stop_reply *sr = new stop_reply ();
6995 sr->ptid = tp->ptid;
6996 sr->rs = rs;
6997 sr->ws.set_stopped (GDB_SIGNAL_0);
6998 sr->arch = tp->inf->gdbarch;
6999 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7000 sr->watch_data_address = 0;
7001 sr->core = 0;
7002 this->push_stop_reply (sr);
7003
7004 /* Pretend that this thread was actually resumed on the
7005 remote target, then stopped. If we leave it in the
7006 RESUMED_PENDING_VCONT state and the commit_resumed
7007 method is called while the stop reply is still in the
7008 queue, we'll end up reporting a stop event to the core
7009 for that thread while it is running on the remote
7010 target... that would be bad. */
7011 remote_thr->set_resumed ();
7012 }
7013 }
7014
7015 /* FIXME: This supports_vCont_probed check is a workaround until
7016 packet_support is per-connection. */
7017 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN
7018 || !rs->supports_vCont_probed)
7019 remote_vcont_probe ();
7020
7021 if (!rs->supports_vCont.t)
7022 error (_("Remote server does not support stopping threads"));
7023
7024 if (ptid == minus_one_ptid
7025 || (!remote_multi_process_p (rs) && ptid.is_pid ()))
7026 p += xsnprintf (p, endp - p, "vCont;t");
7027 else
7028 {
7029 ptid_t nptid;
7030
7031 p += xsnprintf (p, endp - p, "vCont;t:");
7032
7033 if (ptid.is_pid ())
7034 /* All (-1) threads of process. */
7035 nptid = ptid_t (ptid.pid (), -1);
7036 else
7037 {
7038 /* Small optimization: if we already have a stop reply for
7039 this thread, no use in telling the stub we want this
7040 stopped. */
7041 if (peek_stop_reply (ptid))
7042 return;
7043
7044 nptid = ptid;
7045 }
7046
7047 write_ptid (p, endp, nptid);
7048 }
7049
7050 /* In non-stop, we get an immediate OK reply. The stop reply will
7051 come in asynchronously by notification. */
7052 putpkt (rs->buf);
7053 getpkt (&rs->buf, 0);
7054 if (strcmp (rs->buf.data (), "OK") != 0)
7055 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7056 rs->buf.data ());
7057 }
7058
7059 /* All-stop version of target_interrupt. Sends a break or a ^C to
7060 interrupt the remote target. It is undefined which thread of which
7061 process reports the interrupt. */
7062
7063 void
7064 remote_target::remote_interrupt_as ()
7065 {
7066 struct remote_state *rs = get_remote_state ();
7067
7068 rs->ctrlc_pending_p = 1;
7069
7070 /* If the inferior is stopped already, but the core didn't know
7071 about it yet, just ignore the request. The pending stop events
7072 will be collected in remote_wait. */
7073 if (stop_reply_queue_length () > 0)
7074 return;
7075
7076 /* Send interrupt_sequence to remote target. */
7077 send_interrupt_sequence ();
7078 }
7079
7080 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7081 the remote target. It is undefined which thread of which process
7082 reports the interrupt. Throws an error if the packet is not
7083 supported by the server. */
7084
7085 void
7086 remote_target::remote_interrupt_ns ()
7087 {
7088 struct remote_state *rs = get_remote_state ();
7089 char *p = rs->buf.data ();
7090 char *endp = p + get_remote_packet_size ();
7091
7092 xsnprintf (p, endp - p, "vCtrlC");
7093
7094 /* In non-stop, we get an immediate OK reply. The stop reply will
7095 come in asynchronously by notification. */
7096 putpkt (rs->buf);
7097 getpkt (&rs->buf, 0);
7098
7099 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
7100 {
7101 case PACKET_OK:
7102 break;
7103 case PACKET_UNKNOWN:
7104 error (_("No support for interrupting the remote target."));
7105 case PACKET_ERROR:
7106 error (_("Interrupting target failed: %s"), rs->buf.data ());
7107 }
7108 }
7109
7110 /* Implement the to_stop function for the remote targets. */
7111
7112 void
7113 remote_target::stop (ptid_t ptid)
7114 {
7115 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7116
7117 if (target_is_non_stop_p ())
7118 remote_stop_ns (ptid);
7119 else
7120 {
7121 /* We don't currently have a way to transparently pause the
7122 remote target in all-stop mode. Interrupt it instead. */
7123 remote_interrupt_as ();
7124 }
7125 }
7126
7127 /* Implement the to_interrupt function for the remote targets. */
7128
7129 void
7130 remote_target::interrupt ()
7131 {
7132 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7133
7134 if (target_is_non_stop_p ())
7135 remote_interrupt_ns ();
7136 else
7137 remote_interrupt_as ();
7138 }
7139
7140 /* Implement the to_pass_ctrlc function for the remote targets. */
7141
7142 void
7143 remote_target::pass_ctrlc ()
7144 {
7145 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7146
7147 struct remote_state *rs = get_remote_state ();
7148
7149 /* If we're starting up, we're not fully synced yet. Quit
7150 immediately. */
7151 if (rs->starting_up)
7152 quit ();
7153 /* If ^C has already been sent once, offer to disconnect. */
7154 else if (rs->ctrlc_pending_p)
7155 interrupt_query ();
7156 else
7157 target_interrupt ();
7158 }
7159
7160 /* Ask the user what to do when an interrupt is received. */
7161
7162 void
7163 remote_target::interrupt_query ()
7164 {
7165 struct remote_state *rs = get_remote_state ();
7166
7167 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7168 {
7169 if (query (_("The target is not responding to interrupt requests.\n"
7170 "Stop debugging it? ")))
7171 {
7172 remote_unpush_target (this);
7173 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7174 }
7175 }
7176 else
7177 {
7178 if (query (_("Interrupted while waiting for the program.\n"
7179 "Give up waiting? ")))
7180 quit ();
7181 }
7182 }
7183
7184 /* Enable/disable target terminal ownership. Most targets can use
7185 terminal groups to control terminal ownership. Remote targets are
7186 different in that explicit transfer of ownership to/from GDB/target
7187 is required. */
7188
7189 void
7190 remote_target::terminal_inferior ()
7191 {
7192 /* NOTE: At this point we could also register our selves as the
7193 recipient of all input. Any characters typed could then be
7194 passed on down to the target. */
7195 }
7196
7197 void
7198 remote_target::terminal_ours ()
7199 {
7200 }
7201
7202 static void
7203 remote_console_output (const char *msg)
7204 {
7205 const char *p;
7206
7207 for (p = msg; p[0] && p[1]; p += 2)
7208 {
7209 char tb[2];
7210 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7211
7212 tb[0] = c;
7213 tb[1] = 0;
7214 gdb_stdtarg->puts (tb);
7215 }
7216 gdb_stdtarg->flush ();
7217 }
7218
7219 /* Return the length of the stop reply queue. */
7220
7221 int
7222 remote_target::stop_reply_queue_length ()
7223 {
7224 remote_state *rs = get_remote_state ();
7225 return rs->stop_reply_queue.size ();
7226 }
7227
7228 static void
7229 remote_notif_stop_parse (remote_target *remote,
7230 struct notif_client *self, const char *buf,
7231 struct notif_event *event)
7232 {
7233 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7234 }
7235
7236 static void
7237 remote_notif_stop_ack (remote_target *remote,
7238 struct notif_client *self, const char *buf,
7239 struct notif_event *event)
7240 {
7241 struct stop_reply *stop_reply = (struct stop_reply *) event;
7242
7243 /* acknowledge */
7244 putpkt (remote, self->ack_command);
7245
7246 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7247 the notification. It was left in the queue because we need to
7248 acknowledge it and pull the rest of the notifications out. */
7249 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7250 remote->push_stop_reply (stop_reply);
7251 }
7252
7253 static int
7254 remote_notif_stop_can_get_pending_events (remote_target *remote,
7255 struct notif_client *self)
7256 {
7257 /* We can't get pending events in remote_notif_process for
7258 notification stop, and we have to do this in remote_wait_ns
7259 instead. If we fetch all queued events from stub, remote stub
7260 may exit and we have no chance to process them back in
7261 remote_wait_ns. */
7262 remote_state *rs = remote->get_remote_state ();
7263 mark_async_event_handler (rs->remote_async_inferior_event_token);
7264 return 0;
7265 }
7266
7267 stop_reply::~stop_reply ()
7268 {
7269 for (cached_reg_t &reg : regcache)
7270 xfree (reg.data);
7271 }
7272
7273 static notif_event_up
7274 remote_notif_stop_alloc_reply ()
7275 {
7276 return notif_event_up (new struct stop_reply ());
7277 }
7278
7279 /* A client of notification Stop. */
7280
7281 struct notif_client notif_client_stop =
7282 {
7283 "Stop",
7284 "vStopped",
7285 remote_notif_stop_parse,
7286 remote_notif_stop_ack,
7287 remote_notif_stop_can_get_pending_events,
7288 remote_notif_stop_alloc_reply,
7289 REMOTE_NOTIF_STOP,
7290 };
7291
7292 /* If CONTEXT contains any fork child threads that have not been
7293 reported yet, remove them from the CONTEXT list. If such a
7294 thread exists it is because we are stopped at a fork catchpoint
7295 and have not yet called follow_fork, which will set up the
7296 host-side data structures for the new process. */
7297
7298 void
7299 remote_target::remove_new_fork_children (threads_listing_context *context)
7300 {
7301 struct notif_client *notif = &notif_client_stop;
7302
7303 /* For any threads stopped at a fork event, remove the corresponding
7304 fork child threads from the CONTEXT list. */
7305 for (thread_info *thread : all_non_exited_threads (this))
7306 {
7307 const target_waitstatus *ws = thread_pending_fork_status (thread);
7308
7309 if (ws == nullptr)
7310 continue;
7311
7312 context->remove_thread (ws->child_ptid ());
7313 }
7314
7315 /* Check for any pending fork events (not reported or processed yet)
7316 in process PID and remove those fork child threads from the
7317 CONTEXT list as well. */
7318 remote_notif_get_pending_events (notif);
7319 for (auto &event : get_remote_state ()->stop_reply_queue)
7320 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7321 || event->ws.kind () == TARGET_WAITKIND_VFORKED
7322 || event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7323 context->remove_thread (event->ws.child_ptid ());
7324 }
7325
7326 /* Check whether any event pending in the vStopped queue would prevent a
7327 global or process wildcard vCont action. Set *may_global_wildcard to
7328 false if we can't do a global wildcard (vCont;c), and clear the event
7329 inferior's may_wildcard_vcont flag if we can't do a process-wide
7330 wildcard resume (vCont;c:pPID.-1). */
7331
7332 void
7333 remote_target::check_pending_events_prevent_wildcard_vcont
7334 (bool *may_global_wildcard)
7335 {
7336 struct notif_client *notif = &notif_client_stop;
7337
7338 remote_notif_get_pending_events (notif);
7339 for (auto &event : get_remote_state ()->stop_reply_queue)
7340 {
7341 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7342 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7343 continue;
7344
7345 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7346 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7347 *may_global_wildcard = false;
7348
7349 /* This may be the first time we heard about this process.
7350 Regardless, we must not do a global wildcard resume, otherwise
7351 we'd resume this process too. */
7352 *may_global_wildcard = false;
7353 if (event->ptid != null_ptid)
7354 {
7355 inferior *inf = find_inferior_ptid (this, event->ptid);
7356 if (inf != NULL)
7357 get_remote_inferior (inf)->may_wildcard_vcont = false;
7358 }
7359 }
7360 }
7361
7362 /* Discard all pending stop replies of inferior INF. */
7363
7364 void
7365 remote_target::discard_pending_stop_replies (struct inferior *inf)
7366 {
7367 struct stop_reply *reply;
7368 struct remote_state *rs = get_remote_state ();
7369 struct remote_notif_state *rns = rs->notif_state;
7370
7371 /* This function can be notified when an inferior exists. When the
7372 target is not remote, the notification state is NULL. */
7373 if (rs->remote_desc == NULL)
7374 return;
7375
7376 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7377
7378 /* Discard the in-flight notification. */
7379 if (reply != NULL && reply->ptid.pid () == inf->pid)
7380 {
7381 /* Leave the notification pending, since the server expects that
7382 we acknowledge it with vStopped. But clear its contents, so
7383 that later on when we acknowledge it, we also discard it. */
7384 remote_debug_printf
7385 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7386 reply->ptid.to_string().c_str(),
7387 reply->ws.to_string ().c_str ());
7388 reply->ws.set_ignore ();
7389 }
7390
7391 /* Discard the stop replies we have already pulled with
7392 vStopped. */
7393 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7394 rs->stop_reply_queue.end (),
7395 [=] (const stop_reply_up &event)
7396 {
7397 return event->ptid.pid () == inf->pid;
7398 });
7399 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7400 remote_debug_printf
7401 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7402 reply->ptid.to_string().c_str(),
7403 reply->ws.to_string ().c_str ());
7404 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7405 }
7406
7407 /* Discard the stop replies for RS in stop_reply_queue. */
7408
7409 void
7410 remote_target::discard_pending_stop_replies_in_queue ()
7411 {
7412 remote_state *rs = get_remote_state ();
7413
7414 /* Discard the stop replies we have already pulled with
7415 vStopped. */
7416 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7417 rs->stop_reply_queue.end (),
7418 [=] (const stop_reply_up &event)
7419 {
7420 return event->rs == rs;
7421 });
7422 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7423 }
7424
7425 /* Remove the first reply in 'stop_reply_queue' which matches
7426 PTID. */
7427
7428 struct stop_reply *
7429 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7430 {
7431 remote_state *rs = get_remote_state ();
7432
7433 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7434 rs->stop_reply_queue.end (),
7435 [=] (const stop_reply_up &event)
7436 {
7437 return event->ptid.matches (ptid);
7438 });
7439 struct stop_reply *result;
7440 if (iter == rs->stop_reply_queue.end ())
7441 result = nullptr;
7442 else
7443 {
7444 result = iter->release ();
7445 rs->stop_reply_queue.erase (iter);
7446 }
7447
7448 if (notif_debug)
7449 fprintf_unfiltered (gdb_stdlog,
7450 "notif: discard queued event: 'Stop' in %s\n",
7451 target_pid_to_str (ptid).c_str ());
7452
7453 return result;
7454 }
7455
7456 /* Look for a queued stop reply belonging to PTID. If one is found,
7457 remove it from the queue, and return it. Returns NULL if none is
7458 found. If there are still queued events left to process, tell the
7459 event loop to get back to target_wait soon. */
7460
7461 struct stop_reply *
7462 remote_target::queued_stop_reply (ptid_t ptid)
7463 {
7464 remote_state *rs = get_remote_state ();
7465 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7466
7467 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7468 {
7469 /* There's still at least an event left. */
7470 mark_async_event_handler (rs->remote_async_inferior_event_token);
7471 }
7472
7473 return r;
7474 }
7475
7476 /* Push a fully parsed stop reply in the stop reply queue. Since we
7477 know that we now have at least one queued event left to pass to the
7478 core side, tell the event loop to get back to target_wait soon. */
7479
7480 void
7481 remote_target::push_stop_reply (struct stop_reply *new_event)
7482 {
7483 remote_state *rs = get_remote_state ();
7484 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7485
7486 if (notif_debug)
7487 fprintf_unfiltered (gdb_stdlog,
7488 "notif: push 'Stop' %s to queue %d\n",
7489 target_pid_to_str (new_event->ptid).c_str (),
7490 int (rs->stop_reply_queue.size ()));
7491
7492 /* Mark the pending event queue only if async mode is currently enabled.
7493 If async mode is not currently enabled, then, if it later becomes
7494 enabled, and there are events in this queue, we will mark the event
7495 token at that point, see remote_target::async. */
7496 if (target_is_async_p ())
7497 mark_async_event_handler (rs->remote_async_inferior_event_token);
7498 }
7499
7500 /* Returns true if we have a stop reply for PTID. */
7501
7502 int
7503 remote_target::peek_stop_reply (ptid_t ptid)
7504 {
7505 remote_state *rs = get_remote_state ();
7506 for (auto &event : rs->stop_reply_queue)
7507 if (ptid == event->ptid
7508 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7509 return 1;
7510 return 0;
7511 }
7512
7513 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7514 starting with P and ending with PEND matches PREFIX. */
7515
7516 static int
7517 strprefix (const char *p, const char *pend, const char *prefix)
7518 {
7519 for ( ; p < pend; p++, prefix++)
7520 if (*p != *prefix)
7521 return 0;
7522 return *prefix == '\0';
7523 }
7524
7525 /* Parse the stop reply in BUF. Either the function succeeds, and the
7526 result is stored in EVENT, or throws an error. */
7527
7528 void
7529 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7530 {
7531 remote_arch_state *rsa = NULL;
7532 ULONGEST addr;
7533 const char *p;
7534 int skipregs = 0;
7535
7536 event->ptid = null_ptid;
7537 event->rs = get_remote_state ();
7538 event->ws.set_ignore ();
7539 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7540 event->regcache.clear ();
7541 event->core = -1;
7542
7543 switch (buf[0])
7544 {
7545 case 'T': /* Status with PC, SP, FP, ... */
7546 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7547 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7548 ss = signal number
7549 n... = register number
7550 r... = register contents
7551 */
7552
7553 p = &buf[3]; /* after Txx */
7554 while (*p)
7555 {
7556 const char *p1;
7557 int fieldsize;
7558
7559 p1 = strchr (p, ':');
7560 if (p1 == NULL)
7561 error (_("Malformed packet(a) (missing colon): %s\n\
7562 Packet: '%s'\n"),
7563 p, buf);
7564 if (p == p1)
7565 error (_("Malformed packet(a) (missing register number): %s\n\
7566 Packet: '%s'\n"),
7567 p, buf);
7568
7569 /* Some "registers" are actually extended stop information.
7570 Note if you're adding a new entry here: GDB 7.9 and
7571 earlier assume that all register "numbers" that start
7572 with an hex digit are real register numbers. Make sure
7573 the server only sends such a packet if it knows the
7574 client understands it. */
7575
7576 if (strprefix (p, p1, "thread"))
7577 event->ptid = read_ptid (++p1, &p);
7578 else if (strprefix (p, p1, "syscall_entry"))
7579 {
7580 ULONGEST sysno;
7581
7582 p = unpack_varlen_hex (++p1, &sysno);
7583 event->ws.set_syscall_entry ((int) sysno);
7584 }
7585 else if (strprefix (p, p1, "syscall_return"))
7586 {
7587 ULONGEST sysno;
7588
7589 p = unpack_varlen_hex (++p1, &sysno);
7590 event->ws.set_syscall_return ((int) sysno);
7591 }
7592 else if (strprefix (p, p1, "watch")
7593 || strprefix (p, p1, "rwatch")
7594 || strprefix (p, p1, "awatch"))
7595 {
7596 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7597 p = unpack_varlen_hex (++p1, &addr);
7598 event->watch_data_address = (CORE_ADDR) addr;
7599 }
7600 else if (strprefix (p, p1, "swbreak"))
7601 {
7602 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7603
7604 /* Make sure the stub doesn't forget to indicate support
7605 with qSupported. */
7606 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7607 error (_("Unexpected swbreak stop reason"));
7608
7609 /* The value part is documented as "must be empty",
7610 though we ignore it, in case we ever decide to make
7611 use of it in a backward compatible way. */
7612 p = strchrnul (p1 + 1, ';');
7613 }
7614 else if (strprefix (p, p1, "hwbreak"))
7615 {
7616 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7617
7618 /* Make sure the stub doesn't forget to indicate support
7619 with qSupported. */
7620 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7621 error (_("Unexpected hwbreak stop reason"));
7622
7623 /* See above. */
7624 p = strchrnul (p1 + 1, ';');
7625 }
7626 else if (strprefix (p, p1, "library"))
7627 {
7628 event->ws.set_loaded ();
7629 p = strchrnul (p1 + 1, ';');
7630 }
7631 else if (strprefix (p, p1, "replaylog"))
7632 {
7633 event->ws.set_no_history ();
7634 /* p1 will indicate "begin" or "end", but it makes
7635 no difference for now, so ignore it. */
7636 p = strchrnul (p1 + 1, ';');
7637 }
7638 else if (strprefix (p, p1, "core"))
7639 {
7640 ULONGEST c;
7641
7642 p = unpack_varlen_hex (++p1, &c);
7643 event->core = c;
7644 }
7645 else if (strprefix (p, p1, "fork"))
7646 event->ws.set_forked (read_ptid (++p1, &p));
7647 else if (strprefix (p, p1, "vfork"))
7648 event->ws.set_vforked (read_ptid (++p1, &p));
7649 else if (strprefix (p, p1, "vforkdone"))
7650 {
7651 event->ws.set_vfork_done ();
7652 p = strchrnul (p1 + 1, ';');
7653 }
7654 else if (strprefix (p, p1, "exec"))
7655 {
7656 ULONGEST ignored;
7657 int pathlen;
7658
7659 /* Determine the length of the execd pathname. */
7660 p = unpack_varlen_hex (++p1, &ignored);
7661 pathlen = (p - p1) / 2;
7662
7663 /* Save the pathname for event reporting and for
7664 the next run command. */
7665 gdb::unique_xmalloc_ptr<char> pathname
7666 ((char *) xmalloc (pathlen + 1));
7667 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
7668 pathname.get ()[pathlen] = '\0';
7669
7670 /* This is freed during event handling. */
7671 event->ws.set_execd (std::move (pathname));
7672
7673 /* Skip the registers included in this packet, since
7674 they may be for an architecture different from the
7675 one used by the original program. */
7676 skipregs = 1;
7677 }
7678 else if (strprefix (p, p1, "create"))
7679 {
7680 event->ws.set_thread_created ();
7681 p = strchrnul (p1 + 1, ';');
7682 }
7683 else
7684 {
7685 ULONGEST pnum;
7686 const char *p_temp;
7687
7688 if (skipregs)
7689 {
7690 p = strchrnul (p1 + 1, ';');
7691 p++;
7692 continue;
7693 }
7694
7695 /* Maybe a real ``P'' register number. */
7696 p_temp = unpack_varlen_hex (p, &pnum);
7697 /* If the first invalid character is the colon, we got a
7698 register number. Otherwise, it's an unknown stop
7699 reason. */
7700 if (p_temp == p1)
7701 {
7702 /* If we haven't parsed the event's thread yet, find
7703 it now, in order to find the architecture of the
7704 reported expedited registers. */
7705 if (event->ptid == null_ptid)
7706 {
7707 /* If there is no thread-id information then leave
7708 the event->ptid as null_ptid. Later in
7709 process_stop_reply we will pick a suitable
7710 thread. */
7711 const char *thr = strstr (p1 + 1, ";thread:");
7712 if (thr != NULL)
7713 event->ptid = read_ptid (thr + strlen (";thread:"),
7714 NULL);
7715 }
7716
7717 if (rsa == NULL)
7718 {
7719 inferior *inf
7720 = (event->ptid == null_ptid
7721 ? NULL
7722 : find_inferior_ptid (this, event->ptid));
7723 /* If this is the first time we learn anything
7724 about this process, skip the registers
7725 included in this packet, since we don't yet
7726 know which architecture to use to parse them.
7727 We'll determine the architecture later when
7728 we process the stop reply and retrieve the
7729 target description, via
7730 remote_notice_new_inferior ->
7731 post_create_inferior. */
7732 if (inf == NULL)
7733 {
7734 p = strchrnul (p1 + 1, ';');
7735 p++;
7736 continue;
7737 }
7738
7739 event->arch = inf->gdbarch;
7740 rsa = event->rs->get_remote_arch_state (event->arch);
7741 }
7742
7743 packet_reg *reg
7744 = packet_reg_from_pnum (event->arch, rsa, pnum);
7745 cached_reg_t cached_reg;
7746
7747 if (reg == NULL)
7748 error (_("Remote sent bad register number %s: %s\n\
7749 Packet: '%s'\n"),
7750 hex_string (pnum), p, buf);
7751
7752 cached_reg.num = reg->regnum;
7753 cached_reg.data = (gdb_byte *)
7754 xmalloc (register_size (event->arch, reg->regnum));
7755
7756 p = p1 + 1;
7757 fieldsize = hex2bin (p, cached_reg.data,
7758 register_size (event->arch, reg->regnum));
7759 p += 2 * fieldsize;
7760 if (fieldsize < register_size (event->arch, reg->regnum))
7761 warning (_("Remote reply is too short: %s"), buf);
7762
7763 event->regcache.push_back (cached_reg);
7764 }
7765 else
7766 {
7767 /* Not a number. Silently skip unknown optional
7768 info. */
7769 p = strchrnul (p1 + 1, ';');
7770 }
7771 }
7772
7773 if (*p != ';')
7774 error (_("Remote register badly formatted: %s\nhere: %s"),
7775 buf, p);
7776 ++p;
7777 }
7778
7779 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
7780 break;
7781
7782 /* fall through */
7783 case 'S': /* Old style status, just signal only. */
7784 {
7785 int sig;
7786
7787 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7788 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7789 event->ws.set_stopped ((enum gdb_signal) sig);
7790 else
7791 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
7792 }
7793 break;
7794 case 'w': /* Thread exited. */
7795 {
7796 ULONGEST value;
7797
7798 p = unpack_varlen_hex (&buf[1], &value);
7799 event->ws.set_thread_exited (value);
7800 if (*p != ';')
7801 error (_("stop reply packet badly formatted: %s"), buf);
7802 event->ptid = read_ptid (++p, NULL);
7803 break;
7804 }
7805 case 'W': /* Target exited. */
7806 case 'X':
7807 {
7808 ULONGEST value;
7809
7810 /* GDB used to accept only 2 hex chars here. Stubs should
7811 only send more if they detect GDB supports multi-process
7812 support. */
7813 p = unpack_varlen_hex (&buf[1], &value);
7814
7815 if (buf[0] == 'W')
7816 {
7817 /* The remote process exited. */
7818 event->ws.set_exited (value);
7819 }
7820 else
7821 {
7822 /* The remote process exited with a signal. */
7823 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7824 event->ws.set_signalled ((enum gdb_signal) value);
7825 else
7826 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
7827 }
7828
7829 /* If no process is specified, return null_ptid, and let the
7830 caller figure out the right process to use. */
7831 int pid = 0;
7832 if (*p == '\0')
7833 ;
7834 else if (*p == ';')
7835 {
7836 p++;
7837
7838 if (*p == '\0')
7839 ;
7840 else if (startswith (p, "process:"))
7841 {
7842 ULONGEST upid;
7843
7844 p += sizeof ("process:") - 1;
7845 unpack_varlen_hex (p, &upid);
7846 pid = upid;
7847 }
7848 else
7849 error (_("unknown stop reply packet: %s"), buf);
7850 }
7851 else
7852 error (_("unknown stop reply packet: %s"), buf);
7853 event->ptid = ptid_t (pid);
7854 }
7855 break;
7856 case 'N':
7857 event->ws.set_no_resumed ();
7858 event->ptid = minus_one_ptid;
7859 break;
7860 }
7861 }
7862
7863 /* When the stub wants to tell GDB about a new notification reply, it
7864 sends a notification (%Stop, for example). Those can come it at
7865 any time, hence, we have to make sure that any pending
7866 putpkt/getpkt sequence we're making is finished, before querying
7867 the stub for more events with the corresponding ack command
7868 (vStopped, for example). E.g., if we started a vStopped sequence
7869 immediately upon receiving the notification, something like this
7870 could happen:
7871
7872 1.1) --> Hg 1
7873 1.2) <-- OK
7874 1.3) --> g
7875 1.4) <-- %Stop
7876 1.5) --> vStopped
7877 1.6) <-- (registers reply to step #1.3)
7878
7879 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7880 query.
7881
7882 To solve this, whenever we parse a %Stop notification successfully,
7883 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7884 doing whatever we were doing:
7885
7886 2.1) --> Hg 1
7887 2.2) <-- OK
7888 2.3) --> g
7889 2.4) <-- %Stop
7890 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7891 2.5) <-- (registers reply to step #2.3)
7892
7893 Eventually after step #2.5, we return to the event loop, which
7894 notices there's an event on the
7895 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7896 associated callback --- the function below. At this point, we're
7897 always safe to start a vStopped sequence. :
7898
7899 2.6) --> vStopped
7900 2.7) <-- T05 thread:2
7901 2.8) --> vStopped
7902 2.9) --> OK
7903 */
7904
7905 void
7906 remote_target::remote_notif_get_pending_events (notif_client *nc)
7907 {
7908 struct remote_state *rs = get_remote_state ();
7909
7910 if (rs->notif_state->pending_event[nc->id] != NULL)
7911 {
7912 if (notif_debug)
7913 fprintf_unfiltered (gdb_stdlog,
7914 "notif: process: '%s' ack pending event\n",
7915 nc->name);
7916
7917 /* acknowledge */
7918 nc->ack (this, nc, rs->buf.data (),
7919 rs->notif_state->pending_event[nc->id]);
7920 rs->notif_state->pending_event[nc->id] = NULL;
7921
7922 while (1)
7923 {
7924 getpkt (&rs->buf, 0);
7925 if (strcmp (rs->buf.data (), "OK") == 0)
7926 break;
7927 else
7928 remote_notif_ack (this, nc, rs->buf.data ());
7929 }
7930 }
7931 else
7932 {
7933 if (notif_debug)
7934 fprintf_unfiltered (gdb_stdlog,
7935 "notif: process: '%s' no pending reply\n",
7936 nc->name);
7937 }
7938 }
7939
7940 /* Wrapper around remote_target::remote_notif_get_pending_events to
7941 avoid having to export the whole remote_target class. */
7942
7943 void
7944 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7945 {
7946 remote->remote_notif_get_pending_events (nc);
7947 }
7948
7949 /* Called from process_stop_reply when the stop packet we are responding
7950 to didn't include a process-id or thread-id. STATUS is the stop event
7951 we are responding to.
7952
7953 It is the task of this function to select a suitable thread (or process)
7954 and return its ptid, this is the thread (or process) we will assume the
7955 stop event came from.
7956
7957 In some cases there isn't really any choice about which thread (or
7958 process) is selected, a basic remote with a single process containing a
7959 single thread might choose not to send any process-id or thread-id in
7960 its stop packets, this function will select and return the one and only
7961 thread.
7962
7963 However, if a target supports multiple threads (or processes) and still
7964 doesn't include a thread-id (or process-id) in its stop packet then
7965 first, this is a badly behaving target, and second, we're going to have
7966 to select a thread (or process) at random and use that. This function
7967 will print a warning to the user if it detects that there is the
7968 possibility that GDB is guessing which thread (or process) to
7969 report.
7970
7971 Note that this is called before GDB fetches the updated thread list from the
7972 target. So it's possible for the stop reply to be ambiguous and for GDB to
7973 not realize it. For example, if there's initially one thread, the target
7974 spawns a second thread, and then sends a stop reply without an id that
7975 concerns the first thread. GDB will assume the stop reply is about the
7976 first thread - the only thread it knows about - without printing a warning.
7977 Anyway, if the remote meant for the stop reply to be about the second thread,
7978 then it would be really broken, because GDB doesn't know about that thread
7979 yet. */
7980
7981 ptid_t
7982 remote_target::select_thread_for_ambiguous_stop_reply
7983 (const target_waitstatus &status)
7984 {
7985 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7986
7987 /* Some stop events apply to all threads in an inferior, while others
7988 only apply to a single thread. */
7989 bool process_wide_stop
7990 = (status.kind () == TARGET_WAITKIND_EXITED
7991 || status.kind () == TARGET_WAITKIND_SIGNALLED);
7992
7993 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
7994
7995 thread_info *first_resumed_thread = nullptr;
7996 bool ambiguous = false;
7997
7998 /* Consider all non-exited threads of the target, find the first resumed
7999 one. */
8000 for (thread_info *thr : all_non_exited_threads (this))
8001 {
8002 remote_thread_info *remote_thr = get_remote_thread_info (thr);
8003
8004 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8005 continue;
8006
8007 if (first_resumed_thread == nullptr)
8008 first_resumed_thread = thr;
8009 else if (!process_wide_stop
8010 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8011 ambiguous = true;
8012 }
8013
8014 gdb_assert (first_resumed_thread != nullptr);
8015
8016 remote_debug_printf ("first resumed thread is %s",
8017 pid_to_str (first_resumed_thread->ptid).c_str ());
8018 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8019
8020 /* Warn if the remote target is sending ambiguous stop replies. */
8021 if (ambiguous)
8022 {
8023 static bool warned = false;
8024
8025 if (!warned)
8026 {
8027 /* If you are seeing this warning then the remote target has
8028 stopped without specifying a thread-id, but the target
8029 does have multiple threads (or inferiors), and so GDB is
8030 having to guess which thread stopped.
8031
8032 Examples of what might cause this are the target sending
8033 and 'S' stop packet, or a 'T' stop packet and not
8034 including a thread-id.
8035
8036 Additionally, the target might send a 'W' or 'X packet
8037 without including a process-id, when the target has
8038 multiple running inferiors. */
8039 if (process_wide_stop)
8040 warning (_("multi-inferior target stopped without "
8041 "sending a process-id, using first "
8042 "non-exited inferior"));
8043 else
8044 warning (_("multi-threaded target stopped without "
8045 "sending a thread-id, using first "
8046 "non-exited thread"));
8047 warned = true;
8048 }
8049 }
8050
8051 /* If this is a stop for all threads then don't use a particular threads
8052 ptid, instead create a new ptid where only the pid field is set. */
8053 if (process_wide_stop)
8054 return ptid_t (first_resumed_thread->ptid.pid ());
8055 else
8056 return first_resumed_thread->ptid;
8057 }
8058
8059 /* Called when it is decided that STOP_REPLY holds the info of the
8060 event that is to be returned to the core. This function always
8061 destroys STOP_REPLY. */
8062
8063 ptid_t
8064 remote_target::process_stop_reply (struct stop_reply *stop_reply,
8065 struct target_waitstatus *status)
8066 {
8067 *status = stop_reply->ws;
8068 ptid_t ptid = stop_reply->ptid;
8069
8070 /* If no thread/process was reported by the stub then select a suitable
8071 thread/process. */
8072 if (ptid == null_ptid)
8073 ptid = select_thread_for_ambiguous_stop_reply (*status);
8074 gdb_assert (ptid != null_ptid);
8075
8076 if (status->kind () != TARGET_WAITKIND_EXITED
8077 && status->kind () != TARGET_WAITKIND_SIGNALLED
8078 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8079 {
8080 /* Expedited registers. */
8081 if (!stop_reply->regcache.empty ())
8082 {
8083 struct regcache *regcache
8084 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
8085
8086 for (cached_reg_t &reg : stop_reply->regcache)
8087 {
8088 regcache->raw_supply (reg.num, reg.data);
8089 xfree (reg.data);
8090 }
8091
8092 stop_reply->regcache.clear ();
8093 }
8094
8095 remote_notice_new_inferior (ptid, false);
8096 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8097 remote_thr->core = stop_reply->core;
8098 remote_thr->stop_reason = stop_reply->stop_reason;
8099 remote_thr->watch_data_address = stop_reply->watch_data_address;
8100
8101 if (target_is_non_stop_p ())
8102 {
8103 /* If the target works in non-stop mode, a stop-reply indicates that
8104 only this thread stopped. */
8105 remote_thr->set_not_resumed ();
8106 }
8107 else
8108 {
8109 /* If the target works in all-stop mode, a stop-reply indicates that
8110 all the target's threads stopped. */
8111 for (thread_info *tp : all_non_exited_threads (this))
8112 get_remote_thread_info (tp)->set_not_resumed ();
8113 }
8114 }
8115
8116 delete stop_reply;
8117 return ptid;
8118 }
8119
8120 /* The non-stop mode version of target_wait. */
8121
8122 ptid_t
8123 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8124 target_wait_flags options)
8125 {
8126 struct remote_state *rs = get_remote_state ();
8127 struct stop_reply *stop_reply;
8128 int ret;
8129 int is_notif = 0;
8130
8131 /* If in non-stop mode, get out of getpkt even if a
8132 notification is received. */
8133
8134 ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
8135 while (1)
8136 {
8137 if (ret != -1 && !is_notif)
8138 switch (rs->buf[0])
8139 {
8140 case 'E': /* Error of some sort. */
8141 /* We're out of sync with the target now. Did it continue
8142 or not? We can't tell which thread it was in non-stop,
8143 so just ignore this. */
8144 warning (_("Remote failure reply: %s"), rs->buf.data ());
8145 break;
8146 case 'O': /* Console output. */
8147 remote_console_output (&rs->buf[1]);
8148 break;
8149 default:
8150 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8151 break;
8152 }
8153
8154 /* Acknowledge a pending stop reply that may have arrived in the
8155 mean time. */
8156 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8157 remote_notif_get_pending_events (&notif_client_stop);
8158
8159 /* If indeed we noticed a stop reply, we're done. */
8160 stop_reply = queued_stop_reply (ptid);
8161 if (stop_reply != NULL)
8162 return process_stop_reply (stop_reply, status);
8163
8164 /* Still no event. If we're just polling for an event, then
8165 return to the event loop. */
8166 if (options & TARGET_WNOHANG)
8167 {
8168 status->set_ignore ();
8169 return minus_one_ptid;
8170 }
8171
8172 /* Otherwise do a blocking wait. */
8173 ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
8174 }
8175 }
8176
8177 /* Return the first resumed thread. */
8178
8179 static ptid_t
8180 first_remote_resumed_thread (remote_target *target)
8181 {
8182 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8183 if (tp->resumed ())
8184 return tp->ptid;
8185 return null_ptid;
8186 }
8187
8188 /* Wait until the remote machine stops, then return, storing status in
8189 STATUS just as `wait' would. */
8190
8191 ptid_t
8192 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8193 target_wait_flags options)
8194 {
8195 struct remote_state *rs = get_remote_state ();
8196 ptid_t event_ptid = null_ptid;
8197 char *buf;
8198 struct stop_reply *stop_reply;
8199
8200 again:
8201
8202 status->set_ignore ();
8203
8204 stop_reply = queued_stop_reply (ptid);
8205 if (stop_reply != NULL)
8206 {
8207 /* None of the paths that push a stop reply onto the queue should
8208 have set the waiting_for_stop_reply flag. */
8209 gdb_assert (!rs->waiting_for_stop_reply);
8210 event_ptid = process_stop_reply (stop_reply, status);
8211 }
8212 else
8213 {
8214 int forever = ((options & TARGET_WNOHANG) == 0
8215 && rs->wait_forever_enabled_p);
8216
8217 if (!rs->waiting_for_stop_reply)
8218 {
8219 status->set_no_resumed ();
8220 return minus_one_ptid;
8221 }
8222
8223 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8224 _never_ wait for ever -> test on target_is_async_p().
8225 However, before we do that we need to ensure that the caller
8226 knows how to take the target into/out of async mode. */
8227 int is_notif;
8228 int ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
8229
8230 /* GDB gets a notification. Return to core as this event is
8231 not interesting. */
8232 if (ret != -1 && is_notif)
8233 return minus_one_ptid;
8234
8235 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8236 return minus_one_ptid;
8237
8238 buf = rs->buf.data ();
8239
8240 /* Assume that the target has acknowledged Ctrl-C unless we receive
8241 an 'F' or 'O' packet. */
8242 if (buf[0] != 'F' && buf[0] != 'O')
8243 rs->ctrlc_pending_p = 0;
8244
8245 switch (buf[0])
8246 {
8247 case 'E': /* Error of some sort. */
8248 /* We're out of sync with the target now. Did it continue or
8249 not? Not is more likely, so report a stop. */
8250 rs->waiting_for_stop_reply = 0;
8251
8252 warning (_("Remote failure reply: %s"), buf);
8253 status->set_stopped (GDB_SIGNAL_0);
8254 break;
8255 case 'F': /* File-I/O request. */
8256 /* GDB may access the inferior memory while handling the File-I/O
8257 request, but we don't want GDB accessing memory while waiting
8258 for a stop reply. See the comments in putpkt_binary. Set
8259 waiting_for_stop_reply to 0 temporarily. */
8260 rs->waiting_for_stop_reply = 0;
8261 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8262 rs->ctrlc_pending_p = 0;
8263 /* GDB handled the File-I/O request, and the target is running
8264 again. Keep waiting for events. */
8265 rs->waiting_for_stop_reply = 1;
8266 break;
8267 case 'N': case 'T': case 'S': case 'X': case 'W':
8268 {
8269 /* There is a stop reply to handle. */
8270 rs->waiting_for_stop_reply = 0;
8271
8272 stop_reply
8273 = (struct stop_reply *) remote_notif_parse (this,
8274 &notif_client_stop,
8275 rs->buf.data ());
8276
8277 event_ptid = process_stop_reply (stop_reply, status);
8278 break;
8279 }
8280 case 'O': /* Console output. */
8281 remote_console_output (buf + 1);
8282 break;
8283 case '\0':
8284 if (rs->last_sent_signal != GDB_SIGNAL_0)
8285 {
8286 /* Zero length reply means that we tried 'S' or 'C' and the
8287 remote system doesn't support it. */
8288 target_terminal::ours_for_output ();
8289 printf_filtered
8290 ("Can't send signals to this remote system. %s not sent.\n",
8291 gdb_signal_to_name (rs->last_sent_signal));
8292 rs->last_sent_signal = GDB_SIGNAL_0;
8293 target_terminal::inferior ();
8294
8295 strcpy (buf, rs->last_sent_step ? "s" : "c");
8296 putpkt (buf);
8297 break;
8298 }
8299 /* fallthrough */
8300 default:
8301 warning (_("Invalid remote reply: %s"), buf);
8302 break;
8303 }
8304 }
8305
8306 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8307 return minus_one_ptid;
8308 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8309 {
8310 /* Nothing interesting happened. If we're doing a non-blocking
8311 poll, we're done. Otherwise, go back to waiting. */
8312 if (options & TARGET_WNOHANG)
8313 return minus_one_ptid;
8314 else
8315 goto again;
8316 }
8317 else if (status->kind () != TARGET_WAITKIND_EXITED
8318 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8319 {
8320 if (event_ptid != null_ptid)
8321 record_currthread (rs, event_ptid);
8322 else
8323 event_ptid = first_remote_resumed_thread (this);
8324 }
8325 else
8326 {
8327 /* A process exit. Invalidate our notion of current thread. */
8328 record_currthread (rs, minus_one_ptid);
8329 /* It's possible that the packet did not include a pid. */
8330 if (event_ptid == null_ptid)
8331 event_ptid = first_remote_resumed_thread (this);
8332 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8333 if (event_ptid == null_ptid)
8334 event_ptid = magic_null_ptid;
8335 }
8336
8337 return event_ptid;
8338 }
8339
8340 /* Wait until the remote machine stops, then return, storing status in
8341 STATUS just as `wait' would. */
8342
8343 ptid_t
8344 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8345 target_wait_flags options)
8346 {
8347 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8348
8349 remote_state *rs = get_remote_state ();
8350
8351 /* Start by clearing the flag that asks for our wait method to be called,
8352 we'll mark it again at the end if needed. If the target is not in
8353 async mode then the async token should not be marked. */
8354 if (target_is_async_p ())
8355 clear_async_event_handler (rs->remote_async_inferior_event_token);
8356 else
8357 gdb_assert (!async_event_handler_marked
8358 (rs->remote_async_inferior_event_token));
8359
8360 ptid_t event_ptid;
8361
8362 if (target_is_non_stop_p ())
8363 event_ptid = wait_ns (ptid, status, options);
8364 else
8365 event_ptid = wait_as (ptid, status, options);
8366
8367 if (target_is_async_p ())
8368 {
8369 /* If there are events left in the queue, or unacknowledged
8370 notifications, then tell the event loop to call us again. */
8371 if (!rs->stop_reply_queue.empty ()
8372 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8373 mark_async_event_handler (rs->remote_async_inferior_event_token);
8374 }
8375
8376 return event_ptid;
8377 }
8378
8379 /* Fetch a single register using a 'p' packet. */
8380
8381 int
8382 remote_target::fetch_register_using_p (struct regcache *regcache,
8383 packet_reg *reg)
8384 {
8385 struct gdbarch *gdbarch = regcache->arch ();
8386 struct remote_state *rs = get_remote_state ();
8387 char *buf, *p;
8388 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8389 int i;
8390
8391 if (packet_support (PACKET_p) == PACKET_DISABLE)
8392 return 0;
8393
8394 if (reg->pnum == -1)
8395 return 0;
8396
8397 p = rs->buf.data ();
8398 *p++ = 'p';
8399 p += hexnumstr (p, reg->pnum);
8400 *p++ = '\0';
8401 putpkt (rs->buf);
8402 getpkt (&rs->buf, 0);
8403
8404 buf = rs->buf.data ();
8405
8406 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_p]))
8407 {
8408 case PACKET_OK:
8409 break;
8410 case PACKET_UNKNOWN:
8411 return 0;
8412 case PACKET_ERROR:
8413 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8414 gdbarch_register_name (regcache->arch (),
8415 reg->regnum),
8416 buf);
8417 }
8418
8419 /* If this register is unfetchable, tell the regcache. */
8420 if (buf[0] == 'x')
8421 {
8422 regcache->raw_supply (reg->regnum, NULL);
8423 return 1;
8424 }
8425
8426 /* Otherwise, parse and supply the value. */
8427 p = buf;
8428 i = 0;
8429 while (p[0] != 0)
8430 {
8431 if (p[1] == 0)
8432 error (_("fetch_register_using_p: early buf termination"));
8433
8434 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8435 p += 2;
8436 }
8437 regcache->raw_supply (reg->regnum, regp);
8438 return 1;
8439 }
8440
8441 /* Fetch the registers included in the target's 'g' packet. */
8442
8443 int
8444 remote_target::send_g_packet ()
8445 {
8446 struct remote_state *rs = get_remote_state ();
8447 int buf_len;
8448
8449 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8450 putpkt (rs->buf);
8451 getpkt (&rs->buf, 0);
8452 if (packet_check_result (rs->buf) == PACKET_ERROR)
8453 error (_("Could not read registers; remote failure reply '%s'"),
8454 rs->buf.data ());
8455
8456 /* We can get out of synch in various cases. If the first character
8457 in the buffer is not a hex character, assume that has happened
8458 and try to fetch another packet to read. */
8459 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8460 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8461 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8462 && rs->buf[0] != 'x') /* New: unavailable register value. */
8463 {
8464 remote_debug_printf ("Bad register packet; fetching a new packet");
8465 getpkt (&rs->buf, 0);
8466 }
8467
8468 buf_len = strlen (rs->buf.data ());
8469
8470 /* Sanity check the received packet. */
8471 if (buf_len % 2 != 0)
8472 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8473
8474 return buf_len / 2;
8475 }
8476
8477 void
8478 remote_target::process_g_packet (struct regcache *regcache)
8479 {
8480 struct gdbarch *gdbarch = regcache->arch ();
8481 struct remote_state *rs = get_remote_state ();
8482 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8483 int i, buf_len;
8484 char *p;
8485 char *regs;
8486
8487 buf_len = strlen (rs->buf.data ());
8488
8489 /* Further sanity checks, with knowledge of the architecture. */
8490 if (buf_len > 2 * rsa->sizeof_g_packet)
8491 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8492 "bytes): %s"),
8493 rsa->sizeof_g_packet, buf_len / 2,
8494 rs->buf.data ());
8495
8496 /* Save the size of the packet sent to us by the target. It is used
8497 as a heuristic when determining the max size of packets that the
8498 target can safely receive. */
8499 if (rsa->actual_register_packet_size == 0)
8500 rsa->actual_register_packet_size = buf_len;
8501
8502 /* If this is smaller than we guessed the 'g' packet would be,
8503 update our records. A 'g' reply that doesn't include a register's
8504 value implies either that the register is not available, or that
8505 the 'p' packet must be used. */
8506 if (buf_len < 2 * rsa->sizeof_g_packet)
8507 {
8508 long sizeof_g_packet = buf_len / 2;
8509
8510 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8511 {
8512 long offset = rsa->regs[i].offset;
8513 long reg_size = register_size (gdbarch, i);
8514
8515 if (rsa->regs[i].pnum == -1)
8516 continue;
8517
8518 if (offset >= sizeof_g_packet)
8519 rsa->regs[i].in_g_packet = 0;
8520 else if (offset + reg_size > sizeof_g_packet)
8521 error (_("Truncated register %d in remote 'g' packet"), i);
8522 else
8523 rsa->regs[i].in_g_packet = 1;
8524 }
8525
8526 /* Looks valid enough, we can assume this is the correct length
8527 for a 'g' packet. It's important not to adjust
8528 rsa->sizeof_g_packet if we have truncated registers otherwise
8529 this "if" won't be run the next time the method is called
8530 with a packet of the same size and one of the internal errors
8531 below will trigger instead. */
8532 rsa->sizeof_g_packet = sizeof_g_packet;
8533 }
8534
8535 regs = (char *) alloca (rsa->sizeof_g_packet);
8536
8537 /* Unimplemented registers read as all bits zero. */
8538 memset (regs, 0, rsa->sizeof_g_packet);
8539
8540 /* Reply describes registers byte by byte, each byte encoded as two
8541 hex characters. Suck them all up, then supply them to the
8542 register cacheing/storage mechanism. */
8543
8544 p = rs->buf.data ();
8545 for (i = 0; i < rsa->sizeof_g_packet; i++)
8546 {
8547 if (p[0] == 0 || p[1] == 0)
8548 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8549 internal_error (__FILE__, __LINE__,
8550 _("unexpected end of 'g' packet reply"));
8551
8552 if (p[0] == 'x' && p[1] == 'x')
8553 regs[i] = 0; /* 'x' */
8554 else
8555 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8556 p += 2;
8557 }
8558
8559 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8560 {
8561 struct packet_reg *r = &rsa->regs[i];
8562 long reg_size = register_size (gdbarch, i);
8563
8564 if (r->in_g_packet)
8565 {
8566 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8567 /* This shouldn't happen - we adjusted in_g_packet above. */
8568 internal_error (__FILE__, __LINE__,
8569 _("unexpected end of 'g' packet reply"));
8570 else if (rs->buf[r->offset * 2] == 'x')
8571 {
8572 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8573 /* The register isn't available, mark it as such (at
8574 the same time setting the value to zero). */
8575 regcache->raw_supply (r->regnum, NULL);
8576 }
8577 else
8578 regcache->raw_supply (r->regnum, regs + r->offset);
8579 }
8580 }
8581 }
8582
8583 void
8584 remote_target::fetch_registers_using_g (struct regcache *regcache)
8585 {
8586 send_g_packet ();
8587 process_g_packet (regcache);
8588 }
8589
8590 /* Make the remote selected traceframe match GDB's selected
8591 traceframe. */
8592
8593 void
8594 remote_target::set_remote_traceframe ()
8595 {
8596 int newnum;
8597 struct remote_state *rs = get_remote_state ();
8598
8599 if (rs->remote_traceframe_number == get_traceframe_number ())
8600 return;
8601
8602 /* Avoid recursion, remote_trace_find calls us again. */
8603 rs->remote_traceframe_number = get_traceframe_number ();
8604
8605 newnum = target_trace_find (tfind_number,
8606 get_traceframe_number (), 0, 0, NULL);
8607
8608 /* Should not happen. If it does, all bets are off. */
8609 if (newnum != get_traceframe_number ())
8610 warning (_("could not set remote traceframe"));
8611 }
8612
8613 void
8614 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8615 {
8616 struct gdbarch *gdbarch = regcache->arch ();
8617 struct remote_state *rs = get_remote_state ();
8618 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8619 int i;
8620
8621 set_remote_traceframe ();
8622 set_general_thread (regcache->ptid ());
8623
8624 if (regnum >= 0)
8625 {
8626 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8627
8628 gdb_assert (reg != NULL);
8629
8630 /* If this register might be in the 'g' packet, try that first -
8631 we are likely to read more than one register. If this is the
8632 first 'g' packet, we might be overly optimistic about its
8633 contents, so fall back to 'p'. */
8634 if (reg->in_g_packet)
8635 {
8636 fetch_registers_using_g (regcache);
8637 if (reg->in_g_packet)
8638 return;
8639 }
8640
8641 if (fetch_register_using_p (regcache, reg))
8642 return;
8643
8644 /* This register is not available. */
8645 regcache->raw_supply (reg->regnum, NULL);
8646
8647 return;
8648 }
8649
8650 fetch_registers_using_g (regcache);
8651
8652 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8653 if (!rsa->regs[i].in_g_packet)
8654 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8655 {
8656 /* This register is not available. */
8657 regcache->raw_supply (i, NULL);
8658 }
8659 }
8660
8661 /* Prepare to store registers. Since we may send them all (using a
8662 'G' request), we have to read out the ones we don't want to change
8663 first. */
8664
8665 void
8666 remote_target::prepare_to_store (struct regcache *regcache)
8667 {
8668 struct remote_state *rs = get_remote_state ();
8669 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8670 int i;
8671
8672 /* Make sure the entire registers array is valid. */
8673 switch (packet_support (PACKET_P))
8674 {
8675 case PACKET_DISABLE:
8676 case PACKET_SUPPORT_UNKNOWN:
8677 /* Make sure all the necessary registers are cached. */
8678 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8679 if (rsa->regs[i].in_g_packet)
8680 regcache->raw_update (rsa->regs[i].regnum);
8681 break;
8682 case PACKET_ENABLE:
8683 break;
8684 }
8685 }
8686
8687 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8688 packet was not recognized. */
8689
8690 int
8691 remote_target::store_register_using_P (const struct regcache *regcache,
8692 packet_reg *reg)
8693 {
8694 struct gdbarch *gdbarch = regcache->arch ();
8695 struct remote_state *rs = get_remote_state ();
8696 /* Try storing a single register. */
8697 char *buf = rs->buf.data ();
8698 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8699 char *p;
8700
8701 if (packet_support (PACKET_P) == PACKET_DISABLE)
8702 return 0;
8703
8704 if (reg->pnum == -1)
8705 return 0;
8706
8707 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8708 p = buf + strlen (buf);
8709 regcache->raw_collect (reg->regnum, regp);
8710 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8711 putpkt (rs->buf);
8712 getpkt (&rs->buf, 0);
8713
8714 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8715 {
8716 case PACKET_OK:
8717 return 1;
8718 case PACKET_ERROR:
8719 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8720 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
8721 case PACKET_UNKNOWN:
8722 return 0;
8723 default:
8724 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8725 }
8726 }
8727
8728 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8729 contents of the register cache buffer. FIXME: ignores errors. */
8730
8731 void
8732 remote_target::store_registers_using_G (const struct regcache *regcache)
8733 {
8734 struct remote_state *rs = get_remote_state ();
8735 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8736 gdb_byte *regs;
8737 char *p;
8738
8739 /* Extract all the registers in the regcache copying them into a
8740 local buffer. */
8741 {
8742 int i;
8743
8744 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8745 memset (regs, 0, rsa->sizeof_g_packet);
8746 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8747 {
8748 struct packet_reg *r = &rsa->regs[i];
8749
8750 if (r->in_g_packet)
8751 regcache->raw_collect (r->regnum, regs + r->offset);
8752 }
8753 }
8754
8755 /* Command describes registers byte by byte,
8756 each byte encoded as two hex characters. */
8757 p = rs->buf.data ();
8758 *p++ = 'G';
8759 bin2hex (regs, p, rsa->sizeof_g_packet);
8760 putpkt (rs->buf);
8761 getpkt (&rs->buf, 0);
8762 if (packet_check_result (rs->buf) == PACKET_ERROR)
8763 error (_("Could not write registers; remote failure reply '%s'"),
8764 rs->buf.data ());
8765 }
8766
8767 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8768 of the register cache buffer. FIXME: ignores errors. */
8769
8770 void
8771 remote_target::store_registers (struct regcache *regcache, int regnum)
8772 {
8773 struct gdbarch *gdbarch = regcache->arch ();
8774 struct remote_state *rs = get_remote_state ();
8775 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8776 int i;
8777
8778 set_remote_traceframe ();
8779 set_general_thread (regcache->ptid ());
8780
8781 if (regnum >= 0)
8782 {
8783 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8784
8785 gdb_assert (reg != NULL);
8786
8787 /* Always prefer to store registers using the 'P' packet if
8788 possible; we often change only a small number of registers.
8789 Sometimes we change a larger number; we'd need help from a
8790 higher layer to know to use 'G'. */
8791 if (store_register_using_P (regcache, reg))
8792 return;
8793
8794 /* For now, don't complain if we have no way to write the
8795 register. GDB loses track of unavailable registers too
8796 easily. Some day, this may be an error. We don't have
8797 any way to read the register, either... */
8798 if (!reg->in_g_packet)
8799 return;
8800
8801 store_registers_using_G (regcache);
8802 return;
8803 }
8804
8805 store_registers_using_G (regcache);
8806
8807 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8808 if (!rsa->regs[i].in_g_packet)
8809 if (!store_register_using_P (regcache, &rsa->regs[i]))
8810 /* See above for why we do not issue an error here. */
8811 continue;
8812 }
8813 \f
8814
8815 /* Return the number of hex digits in num. */
8816
8817 static int
8818 hexnumlen (ULONGEST num)
8819 {
8820 int i;
8821
8822 for (i = 0; num != 0; i++)
8823 num >>= 4;
8824
8825 return std::max (i, 1);
8826 }
8827
8828 /* Set BUF to the minimum number of hex digits representing NUM. */
8829
8830 static int
8831 hexnumstr (char *buf, ULONGEST num)
8832 {
8833 int len = hexnumlen (num);
8834
8835 return hexnumnstr (buf, num, len);
8836 }
8837
8838
8839 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
8840
8841 static int
8842 hexnumnstr (char *buf, ULONGEST num, int width)
8843 {
8844 int i;
8845
8846 buf[width] = '\0';
8847
8848 for (i = width - 1; i >= 0; i--)
8849 {
8850 buf[i] = "0123456789abcdef"[(num & 0xf)];
8851 num >>= 4;
8852 }
8853
8854 return width;
8855 }
8856
8857 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8858
8859 static CORE_ADDR
8860 remote_address_masked (CORE_ADDR addr)
8861 {
8862 unsigned int address_size = remote_address_size;
8863
8864 /* If "remoteaddresssize" was not set, default to target address size. */
8865 if (!address_size)
8866 address_size = gdbarch_addr_bit (target_gdbarch ());
8867
8868 if (address_size > 0
8869 && address_size < (sizeof (ULONGEST) * 8))
8870 {
8871 /* Only create a mask when that mask can safely be constructed
8872 in a ULONGEST variable. */
8873 ULONGEST mask = 1;
8874
8875 mask = (mask << address_size) - 1;
8876 addr &= mask;
8877 }
8878 return addr;
8879 }
8880
8881 /* Determine whether the remote target supports binary downloading.
8882 This is accomplished by sending a no-op memory write of zero length
8883 to the target at the specified address. It does not suffice to send
8884 the whole packet, since many stubs strip the eighth bit and
8885 subsequently compute a wrong checksum, which causes real havoc with
8886 remote_write_bytes.
8887
8888 NOTE: This can still lose if the serial line is not eight-bit
8889 clean. In cases like this, the user should clear "remote
8890 X-packet". */
8891
8892 void
8893 remote_target::check_binary_download (CORE_ADDR addr)
8894 {
8895 struct remote_state *rs = get_remote_state ();
8896
8897 switch (packet_support (PACKET_X))
8898 {
8899 case PACKET_DISABLE:
8900 break;
8901 case PACKET_ENABLE:
8902 break;
8903 case PACKET_SUPPORT_UNKNOWN:
8904 {
8905 char *p;
8906
8907 p = rs->buf.data ();
8908 *p++ = 'X';
8909 p += hexnumstr (p, (ULONGEST) addr);
8910 *p++ = ',';
8911 p += hexnumstr (p, (ULONGEST) 0);
8912 *p++ = ':';
8913 *p = '\0';
8914
8915 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
8916 getpkt (&rs->buf, 0);
8917
8918 if (rs->buf[0] == '\0')
8919 {
8920 remote_debug_printf ("binary downloading NOT supported by target");
8921 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8922 }
8923 else
8924 {
8925 remote_debug_printf ("binary downloading supported by target");
8926 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8927 }
8928 break;
8929 }
8930 }
8931 }
8932
8933 /* Helper function to resize the payload in order to try to get a good
8934 alignment. We try to write an amount of data such that the next write will
8935 start on an address aligned on REMOTE_ALIGN_WRITES. */
8936
8937 static int
8938 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8939 {
8940 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8941 }
8942
8943 /* Write memory data directly to the remote machine.
8944 This does not inform the data cache; the data cache uses this.
8945 HEADER is the starting part of the packet.
8946 MEMADDR is the address in the remote memory space.
8947 MYADDR is the address of the buffer in our space.
8948 LEN_UNITS is the number of addressable units to write.
8949 UNIT_SIZE is the length in bytes of an addressable unit.
8950 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8951 should send data as binary ('X'), or hex-encoded ('M').
8952
8953 The function creates packet of the form
8954 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8955
8956 where encoding of <DATA> is terminated by PACKET_FORMAT.
8957
8958 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8959 are omitted.
8960
8961 Return the transferred status, error or OK (an
8962 'enum target_xfer_status' value). Save the number of addressable units
8963 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8964
8965 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8966 exchange between gdb and the stub could look like (?? in place of the
8967 checksum):
8968
8969 -> $m1000,4#??
8970 <- aaaabbbbccccdddd
8971
8972 -> $M1000,3:eeeeffffeeee#??
8973 <- OK
8974
8975 -> $m1000,4#??
8976 <- eeeeffffeeeedddd */
8977
8978 target_xfer_status
8979 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8980 const gdb_byte *myaddr,
8981 ULONGEST len_units,
8982 int unit_size,
8983 ULONGEST *xfered_len_units,
8984 char packet_format, int use_length)
8985 {
8986 struct remote_state *rs = get_remote_state ();
8987 char *p;
8988 char *plen = NULL;
8989 int plenlen = 0;
8990 int todo_units;
8991 int units_written;
8992 int payload_capacity_bytes;
8993 int payload_length_bytes;
8994
8995 if (packet_format != 'X' && packet_format != 'M')
8996 internal_error (__FILE__, __LINE__,
8997 _("remote_write_bytes_aux: bad packet format"));
8998
8999 if (len_units == 0)
9000 return TARGET_XFER_EOF;
9001
9002 payload_capacity_bytes = get_memory_write_packet_size ();
9003
9004 /* The packet buffer will be large enough for the payload;
9005 get_memory_packet_size ensures this. */
9006 rs->buf[0] = '\0';
9007
9008 /* Compute the size of the actual payload by subtracting out the
9009 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9010
9011 payload_capacity_bytes -= strlen ("$,:#NN");
9012 if (!use_length)
9013 /* The comma won't be used. */
9014 payload_capacity_bytes += 1;
9015 payload_capacity_bytes -= strlen (header);
9016 payload_capacity_bytes -= hexnumlen (memaddr);
9017
9018 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9019
9020 strcat (rs->buf.data (), header);
9021 p = rs->buf.data () + strlen (header);
9022
9023 /* Compute a best guess of the number of bytes actually transfered. */
9024 if (packet_format == 'X')
9025 {
9026 /* Best guess at number of bytes that will fit. */
9027 todo_units = std::min (len_units,
9028 (ULONGEST) payload_capacity_bytes / unit_size);
9029 if (use_length)
9030 payload_capacity_bytes -= hexnumlen (todo_units);
9031 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9032 }
9033 else
9034 {
9035 /* Number of bytes that will fit. */
9036 todo_units
9037 = std::min (len_units,
9038 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9039 if (use_length)
9040 payload_capacity_bytes -= hexnumlen (todo_units);
9041 todo_units = std::min (todo_units,
9042 (payload_capacity_bytes / unit_size) / 2);
9043 }
9044
9045 if (todo_units <= 0)
9046 internal_error (__FILE__, __LINE__,
9047 _("minimum packet size too small to write data"));
9048
9049 /* If we already need another packet, then try to align the end
9050 of this packet to a useful boundary. */
9051 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9052 todo_units = align_for_efficient_write (todo_units, memaddr);
9053
9054 /* Append "<memaddr>". */
9055 memaddr = remote_address_masked (memaddr);
9056 p += hexnumstr (p, (ULONGEST) memaddr);
9057
9058 if (use_length)
9059 {
9060 /* Append ",". */
9061 *p++ = ',';
9062
9063 /* Append the length and retain its location and size. It may need to be
9064 adjusted once the packet body has been created. */
9065 plen = p;
9066 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9067 p += plenlen;
9068 }
9069
9070 /* Append ":". */
9071 *p++ = ':';
9072 *p = '\0';
9073
9074 /* Append the packet body. */
9075 if (packet_format == 'X')
9076 {
9077 /* Binary mode. Send target system values byte by byte, in
9078 increasing byte addresses. Only escape certain critical
9079 characters. */
9080 payload_length_bytes =
9081 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9082 &units_written, payload_capacity_bytes);
9083
9084 /* If not all TODO units fit, then we'll need another packet. Make
9085 a second try to keep the end of the packet aligned. Don't do
9086 this if the packet is tiny. */
9087 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9088 {
9089 int new_todo_units;
9090
9091 new_todo_units = align_for_efficient_write (units_written, memaddr);
9092
9093 if (new_todo_units != units_written)
9094 payload_length_bytes =
9095 remote_escape_output (myaddr, new_todo_units, unit_size,
9096 (gdb_byte *) p, &units_written,
9097 payload_capacity_bytes);
9098 }
9099
9100 p += payload_length_bytes;
9101 if (use_length && units_written < todo_units)
9102 {
9103 /* Escape chars have filled up the buffer prematurely,
9104 and we have actually sent fewer units than planned.
9105 Fix-up the length field of the packet. Use the same
9106 number of characters as before. */
9107 plen += hexnumnstr (plen, (ULONGEST) units_written,
9108 plenlen);
9109 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9110 }
9111 }
9112 else
9113 {
9114 /* Normal mode: Send target system values byte by byte, in
9115 increasing byte addresses. Each byte is encoded as a two hex
9116 value. */
9117 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9118 units_written = todo_units;
9119 }
9120
9121 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9122 getpkt (&rs->buf, 0);
9123
9124 if (rs->buf[0] == 'E')
9125 return TARGET_XFER_E_IO;
9126
9127 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9128 send fewer units than we'd planned. */
9129 *xfered_len_units = (ULONGEST) units_written;
9130 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9131 }
9132
9133 /* Write memory data directly to the remote machine.
9134 This does not inform the data cache; the data cache uses this.
9135 MEMADDR is the address in the remote memory space.
9136 MYADDR is the address of the buffer in our space.
9137 LEN is the number of bytes.
9138
9139 Return the transferred status, error or OK (an
9140 'enum target_xfer_status' value). Save the number of bytes
9141 transferred in *XFERED_LEN. Only transfer a single packet. */
9142
9143 target_xfer_status
9144 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9145 ULONGEST len, int unit_size,
9146 ULONGEST *xfered_len)
9147 {
9148 const char *packet_format = NULL;
9149
9150 /* Check whether the target supports binary download. */
9151 check_binary_download (memaddr);
9152
9153 switch (packet_support (PACKET_X))
9154 {
9155 case PACKET_ENABLE:
9156 packet_format = "X";
9157 break;
9158 case PACKET_DISABLE:
9159 packet_format = "M";
9160 break;
9161 case PACKET_SUPPORT_UNKNOWN:
9162 internal_error (__FILE__, __LINE__,
9163 _("remote_write_bytes: bad internal state"));
9164 default:
9165 internal_error (__FILE__, __LINE__, _("bad switch"));
9166 }
9167
9168 return remote_write_bytes_aux (packet_format,
9169 memaddr, myaddr, len, unit_size, xfered_len,
9170 packet_format[0], 1);
9171 }
9172
9173 /* Read memory data directly from the remote machine.
9174 This does not use the data cache; the data cache uses this.
9175 MEMADDR is the address in the remote memory space.
9176 MYADDR is the address of the buffer in our space.
9177 LEN_UNITS is the number of addressable memory units to read..
9178 UNIT_SIZE is the length in bytes of an addressable unit.
9179
9180 Return the transferred status, error or OK (an
9181 'enum target_xfer_status' value). Save the number of bytes
9182 transferred in *XFERED_LEN_UNITS.
9183
9184 See the comment of remote_write_bytes_aux for an example of
9185 memory read/write exchange between gdb and the stub. */
9186
9187 target_xfer_status
9188 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9189 ULONGEST len_units,
9190 int unit_size, ULONGEST *xfered_len_units)
9191 {
9192 struct remote_state *rs = get_remote_state ();
9193 int buf_size_bytes; /* Max size of packet output buffer. */
9194 char *p;
9195 int todo_units;
9196 int decoded_bytes;
9197
9198 buf_size_bytes = get_memory_read_packet_size ();
9199 /* The packet buffer will be large enough for the payload;
9200 get_memory_packet_size ensures this. */
9201
9202 /* Number of units that will fit. */
9203 todo_units = std::min (len_units,
9204 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9205
9206 /* Construct "m"<memaddr>","<len>". */
9207 memaddr = remote_address_masked (memaddr);
9208 p = rs->buf.data ();
9209 *p++ = 'm';
9210 p += hexnumstr (p, (ULONGEST) memaddr);
9211 *p++ = ',';
9212 p += hexnumstr (p, (ULONGEST) todo_units);
9213 *p = '\0';
9214 putpkt (rs->buf);
9215 getpkt (&rs->buf, 0);
9216 if (rs->buf[0] == 'E'
9217 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9218 && rs->buf[3] == '\0')
9219 return TARGET_XFER_E_IO;
9220 /* Reply describes memory byte by byte, each byte encoded as two hex
9221 characters. */
9222 p = rs->buf.data ();
9223 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9224 /* Return what we have. Let higher layers handle partial reads. */
9225 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9226 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9227 }
9228
9229 /* Using the set of read-only target sections of remote, read live
9230 read-only memory.
9231
9232 For interface/parameters/return description see target.h,
9233 to_xfer_partial. */
9234
9235 target_xfer_status
9236 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9237 ULONGEST memaddr,
9238 ULONGEST len,
9239 int unit_size,
9240 ULONGEST *xfered_len)
9241 {
9242 const struct target_section *secp;
9243
9244 secp = target_section_by_addr (this, memaddr);
9245 if (secp != NULL
9246 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9247 {
9248 ULONGEST memend = memaddr + len;
9249
9250 const target_section_table *table = target_get_section_table (this);
9251 for (const target_section &p : *table)
9252 {
9253 if (memaddr >= p.addr)
9254 {
9255 if (memend <= p.endaddr)
9256 {
9257 /* Entire transfer is within this section. */
9258 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9259 xfered_len);
9260 }
9261 else if (memaddr >= p.endaddr)
9262 {
9263 /* This section ends before the transfer starts. */
9264 continue;
9265 }
9266 else
9267 {
9268 /* This section overlaps the transfer. Just do half. */
9269 len = p.endaddr - memaddr;
9270 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9271 xfered_len);
9272 }
9273 }
9274 }
9275 }
9276
9277 return TARGET_XFER_EOF;
9278 }
9279
9280 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9281 first if the requested memory is unavailable in traceframe.
9282 Otherwise, fall back to remote_read_bytes_1. */
9283
9284 target_xfer_status
9285 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9286 gdb_byte *myaddr, ULONGEST len, int unit_size,
9287 ULONGEST *xfered_len)
9288 {
9289 if (len == 0)
9290 return TARGET_XFER_EOF;
9291
9292 if (get_traceframe_number () != -1)
9293 {
9294 std::vector<mem_range> available;
9295
9296 /* If we fail to get the set of available memory, then the
9297 target does not support querying traceframe info, and so we
9298 attempt reading from the traceframe anyway (assuming the
9299 target implements the old QTro packet then). */
9300 if (traceframe_available_memory (&available, memaddr, len))
9301 {
9302 if (available.empty () || available[0].start != memaddr)
9303 {
9304 enum target_xfer_status res;
9305
9306 /* Don't read into the traceframe's available
9307 memory. */
9308 if (!available.empty ())
9309 {
9310 LONGEST oldlen = len;
9311
9312 len = available[0].start - memaddr;
9313 gdb_assert (len <= oldlen);
9314 }
9315
9316 /* This goes through the topmost target again. */
9317 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9318 len, unit_size, xfered_len);
9319 if (res == TARGET_XFER_OK)
9320 return TARGET_XFER_OK;
9321 else
9322 {
9323 /* No use trying further, we know some memory starting
9324 at MEMADDR isn't available. */
9325 *xfered_len = len;
9326 return (*xfered_len != 0) ?
9327 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9328 }
9329 }
9330
9331 /* Don't try to read more than how much is available, in
9332 case the target implements the deprecated QTro packet to
9333 cater for older GDBs (the target's knowledge of read-only
9334 sections may be outdated by now). */
9335 len = available[0].length;
9336 }
9337 }
9338
9339 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9340 }
9341
9342 \f
9343
9344 /* Sends a packet with content determined by the printf format string
9345 FORMAT and the remaining arguments, then gets the reply. Returns
9346 whether the packet was a success, a failure, or unknown. */
9347
9348 packet_result
9349 remote_target::remote_send_printf (const char *format, ...)
9350 {
9351 struct remote_state *rs = get_remote_state ();
9352 int max_size = get_remote_packet_size ();
9353 va_list ap;
9354
9355 va_start (ap, format);
9356
9357 rs->buf[0] = '\0';
9358 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9359
9360 va_end (ap);
9361
9362 if (size >= max_size)
9363 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
9364
9365 if (putpkt (rs->buf) < 0)
9366 error (_("Communication problem with target."));
9367
9368 rs->buf[0] = '\0';
9369 getpkt (&rs->buf, 0);
9370
9371 return packet_check_result (rs->buf);
9372 }
9373
9374 /* Flash writing can take quite some time. We'll set
9375 effectively infinite timeout for flash operations.
9376 In future, we'll need to decide on a better approach. */
9377 static const int remote_flash_timeout = 1000;
9378
9379 void
9380 remote_target::flash_erase (ULONGEST address, LONGEST length)
9381 {
9382 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9383 enum packet_result ret;
9384 scoped_restore restore_timeout
9385 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9386
9387 ret = remote_send_printf ("vFlashErase:%s,%s",
9388 phex (address, addr_size),
9389 phex (length, 4));
9390 switch (ret)
9391 {
9392 case PACKET_UNKNOWN:
9393 error (_("Remote target does not support flash erase"));
9394 case PACKET_ERROR:
9395 error (_("Error erasing flash with vFlashErase packet"));
9396 default:
9397 break;
9398 }
9399 }
9400
9401 target_xfer_status
9402 remote_target::remote_flash_write (ULONGEST address,
9403 ULONGEST length, ULONGEST *xfered_len,
9404 const gdb_byte *data)
9405 {
9406 scoped_restore restore_timeout
9407 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9408 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9409 xfered_len,'X', 0);
9410 }
9411
9412 void
9413 remote_target::flash_done ()
9414 {
9415 int ret;
9416
9417 scoped_restore restore_timeout
9418 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9419
9420 ret = remote_send_printf ("vFlashDone");
9421
9422 switch (ret)
9423 {
9424 case PACKET_UNKNOWN:
9425 error (_("Remote target does not support vFlashDone"));
9426 case PACKET_ERROR:
9427 error (_("Error finishing flash operation"));
9428 default:
9429 break;
9430 }
9431 }
9432
9433 void
9434 remote_target::files_info ()
9435 {
9436 puts_filtered ("Debugging a target over a serial line.\n");
9437 }
9438 \f
9439 /* Stuff for dealing with the packets which are part of this protocol.
9440 See comment at top of file for details. */
9441
9442 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9443 error to higher layers. Called when a serial error is detected.
9444 The exception message is STRING, followed by a colon and a blank,
9445 the system error message for errno at function entry and final dot
9446 for output compatibility with throw_perror_with_name. */
9447
9448 static void
9449 unpush_and_perror (remote_target *target, const char *string)
9450 {
9451 int saved_errno = errno;
9452
9453 remote_unpush_target (target);
9454 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9455 safe_strerror (saved_errno));
9456 }
9457
9458 /* Read a single character from the remote end. The current quit
9459 handler is overridden to avoid quitting in the middle of packet
9460 sequence, as that would break communication with the remote server.
9461 See remote_serial_quit_handler for more detail. */
9462
9463 int
9464 remote_target::readchar (int timeout)
9465 {
9466 int ch;
9467 struct remote_state *rs = get_remote_state ();
9468
9469 {
9470 scoped_restore restore_quit_target
9471 = make_scoped_restore (&curr_quit_handler_target, this);
9472 scoped_restore restore_quit
9473 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9474
9475 rs->got_ctrlc_during_io = 0;
9476
9477 ch = serial_readchar (rs->remote_desc, timeout);
9478
9479 if (rs->got_ctrlc_during_io)
9480 set_quit_flag ();
9481 }
9482
9483 if (ch >= 0)
9484 return ch;
9485
9486 switch ((enum serial_rc) ch)
9487 {
9488 case SERIAL_EOF:
9489 remote_unpush_target (this);
9490 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9491 /* no return */
9492 case SERIAL_ERROR:
9493 unpush_and_perror (this, _("Remote communication error. "
9494 "Target disconnected."));
9495 /* no return */
9496 case SERIAL_TIMEOUT:
9497 break;
9498 }
9499 return ch;
9500 }
9501
9502 /* Wrapper for serial_write that closes the target and throws if
9503 writing fails. The current quit handler is overridden to avoid
9504 quitting in the middle of packet sequence, as that would break
9505 communication with the remote server. See
9506 remote_serial_quit_handler for more detail. */
9507
9508 void
9509 remote_target::remote_serial_write (const char *str, int len)
9510 {
9511 struct remote_state *rs = get_remote_state ();
9512
9513 scoped_restore restore_quit_target
9514 = make_scoped_restore (&curr_quit_handler_target, this);
9515 scoped_restore restore_quit
9516 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9517
9518 rs->got_ctrlc_during_io = 0;
9519
9520 if (serial_write (rs->remote_desc, str, len))
9521 {
9522 unpush_and_perror (this, _("Remote communication error. "
9523 "Target disconnected."));
9524 }
9525
9526 if (rs->got_ctrlc_during_io)
9527 set_quit_flag ();
9528 }
9529
9530 /* Return a string representing an escaped version of BUF, of len N.
9531 E.g. \n is converted to \\n, \t to \\t, etc. */
9532
9533 static std::string
9534 escape_buffer (const char *buf, int n)
9535 {
9536 string_file stb;
9537
9538 stb.putstrn (buf, n, '\\');
9539 return std::move (stb.string ());
9540 }
9541
9542 int
9543 remote_target::putpkt (const char *buf)
9544 {
9545 return putpkt_binary (buf, strlen (buf));
9546 }
9547
9548 /* Wrapper around remote_target::putpkt to avoid exporting
9549 remote_target. */
9550
9551 int
9552 putpkt (remote_target *remote, const char *buf)
9553 {
9554 return remote->putpkt (buf);
9555 }
9556
9557 /* Send a packet to the remote machine, with error checking. The data
9558 of the packet is in BUF. The string in BUF can be at most
9559 get_remote_packet_size () - 5 to account for the $, # and checksum,
9560 and for a possible /0 if we are debugging (remote_debug) and want
9561 to print the sent packet as a string. */
9562
9563 int
9564 remote_target::putpkt_binary (const char *buf, int cnt)
9565 {
9566 struct remote_state *rs = get_remote_state ();
9567 int i;
9568 unsigned char csum = 0;
9569 gdb::def_vector<char> data (cnt + 6);
9570 char *buf2 = data.data ();
9571
9572 int ch;
9573 int tcount = 0;
9574 char *p;
9575
9576 /* Catch cases like trying to read memory or listing threads while
9577 we're waiting for a stop reply. The remote server wouldn't be
9578 ready to handle this request, so we'd hang and timeout. We don't
9579 have to worry about this in synchronous mode, because in that
9580 case it's not possible to issue a command while the target is
9581 running. This is not a problem in non-stop mode, because in that
9582 case, the stub is always ready to process serial input. */
9583 if (!target_is_non_stop_p ()
9584 && target_is_async_p ()
9585 && rs->waiting_for_stop_reply)
9586 {
9587 error (_("Cannot execute this command while the target is running.\n"
9588 "Use the \"interrupt\" command to stop the target\n"
9589 "and then try again."));
9590 }
9591
9592 /* Copy the packet into buffer BUF2, encapsulating it
9593 and giving it a checksum. */
9594
9595 p = buf2;
9596 *p++ = '$';
9597
9598 for (i = 0; i < cnt; i++)
9599 {
9600 csum += buf[i];
9601 *p++ = buf[i];
9602 }
9603 *p++ = '#';
9604 *p++ = tohex ((csum >> 4) & 0xf);
9605 *p++ = tohex (csum & 0xf);
9606
9607 /* Send it over and over until we get a positive ack. */
9608
9609 while (1)
9610 {
9611 if (remote_debug)
9612 {
9613 *p = '\0';
9614
9615 int len = (int) (p - buf2);
9616 int max_chars;
9617
9618 if (remote_packet_max_chars < 0)
9619 max_chars = len;
9620 else
9621 max_chars = remote_packet_max_chars;
9622
9623 std::string str
9624 = escape_buffer (buf2, std::min (len, max_chars));
9625
9626 if (len > max_chars)
9627 remote_debug_printf_nofunc
9628 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9629 len - max_chars);
9630 else
9631 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9632 }
9633 remote_serial_write (buf2, p - buf2);
9634
9635 /* If this is a no acks version of the remote protocol, send the
9636 packet and move on. */
9637 if (rs->noack_mode)
9638 break;
9639
9640 /* Read until either a timeout occurs (-2) or '+' is read.
9641 Handle any notification that arrives in the mean time. */
9642 while (1)
9643 {
9644 ch = readchar (remote_timeout);
9645
9646 switch (ch)
9647 {
9648 case '+':
9649 remote_debug_printf_nofunc ("Received Ack");
9650 return 1;
9651 case '-':
9652 remote_debug_printf_nofunc ("Received Nak");
9653 /* FALLTHROUGH */
9654 case SERIAL_TIMEOUT:
9655 tcount++;
9656 if (tcount > 3)
9657 return 0;
9658 break; /* Retransmit buffer. */
9659 case '$':
9660 {
9661 remote_debug_printf ("Packet instead of Ack, ignoring it");
9662 /* It's probably an old response sent because an ACK
9663 was lost. Gobble up the packet and ack it so it
9664 doesn't get retransmitted when we resend this
9665 packet. */
9666 skip_frame ();
9667 remote_serial_write ("+", 1);
9668 continue; /* Now, go look for +. */
9669 }
9670
9671 case '%':
9672 {
9673 int val;
9674
9675 /* If we got a notification, handle it, and go back to looking
9676 for an ack. */
9677 /* We've found the start of a notification. Now
9678 collect the data. */
9679 val = read_frame (&rs->buf);
9680 if (val >= 0)
9681 {
9682 remote_debug_printf_nofunc
9683 (" Notification received: %s",
9684 escape_buffer (rs->buf.data (), val).c_str ());
9685
9686 handle_notification (rs->notif_state, rs->buf.data ());
9687 /* We're in sync now, rewait for the ack. */
9688 tcount = 0;
9689 }
9690 else
9691 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9692 rs->buf.data ());
9693 continue;
9694 }
9695 /* fall-through */
9696 default:
9697 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9698 rs->buf.data ());
9699 continue;
9700 }
9701 break; /* Here to retransmit. */
9702 }
9703
9704 #if 0
9705 /* This is wrong. If doing a long backtrace, the user should be
9706 able to get out next time we call QUIT, without anything as
9707 violent as interrupt_query. If we want to provide a way out of
9708 here without getting to the next QUIT, it should be based on
9709 hitting ^C twice as in remote_wait. */
9710 if (quit_flag)
9711 {
9712 quit_flag = 0;
9713 interrupt_query ();
9714 }
9715 #endif
9716 }
9717
9718 return 0;
9719 }
9720
9721 /* Come here after finding the start of a frame when we expected an
9722 ack. Do our best to discard the rest of this packet. */
9723
9724 void
9725 remote_target::skip_frame ()
9726 {
9727 int c;
9728
9729 while (1)
9730 {
9731 c = readchar (remote_timeout);
9732 switch (c)
9733 {
9734 case SERIAL_TIMEOUT:
9735 /* Nothing we can do. */
9736 return;
9737 case '#':
9738 /* Discard the two bytes of checksum and stop. */
9739 c = readchar (remote_timeout);
9740 if (c >= 0)
9741 c = readchar (remote_timeout);
9742
9743 return;
9744 case '*': /* Run length encoding. */
9745 /* Discard the repeat count. */
9746 c = readchar (remote_timeout);
9747 if (c < 0)
9748 return;
9749 break;
9750 default:
9751 /* A regular character. */
9752 break;
9753 }
9754 }
9755 }
9756
9757 /* Come here after finding the start of the frame. Collect the rest
9758 into *BUF, verifying the checksum, length, and handling run-length
9759 compression. NUL terminate the buffer. If there is not enough room,
9760 expand *BUF.
9761
9762 Returns -1 on error, number of characters in buffer (ignoring the
9763 trailing NULL) on success. (could be extended to return one of the
9764 SERIAL status indications). */
9765
9766 long
9767 remote_target::read_frame (gdb::char_vector *buf_p)
9768 {
9769 unsigned char csum;
9770 long bc;
9771 int c;
9772 char *buf = buf_p->data ();
9773 struct remote_state *rs = get_remote_state ();
9774
9775 csum = 0;
9776 bc = 0;
9777
9778 while (1)
9779 {
9780 c = readchar (remote_timeout);
9781 switch (c)
9782 {
9783 case SERIAL_TIMEOUT:
9784 remote_debug_printf ("Timeout in mid-packet, retrying");
9785 return -1;
9786
9787 case '$':
9788 remote_debug_printf ("Saw new packet start in middle of old one");
9789 return -1; /* Start a new packet, count retries. */
9790
9791 case '#':
9792 {
9793 unsigned char pktcsum;
9794 int check_0 = 0;
9795 int check_1 = 0;
9796
9797 buf[bc] = '\0';
9798
9799 check_0 = readchar (remote_timeout);
9800 if (check_0 >= 0)
9801 check_1 = readchar (remote_timeout);
9802
9803 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9804 {
9805 remote_debug_printf ("Timeout in checksum, retrying");
9806 return -1;
9807 }
9808 else if (check_0 < 0 || check_1 < 0)
9809 {
9810 remote_debug_printf ("Communication error in checksum");
9811 return -1;
9812 }
9813
9814 /* Don't recompute the checksum; with no ack packets we
9815 don't have any way to indicate a packet retransmission
9816 is necessary. */
9817 if (rs->noack_mode)
9818 return bc;
9819
9820 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9821 if (csum == pktcsum)
9822 return bc;
9823
9824 remote_debug_printf
9825 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
9826 pktcsum, csum, escape_buffer (buf, bc).c_str ());
9827
9828 /* Number of characters in buffer ignoring trailing
9829 NULL. */
9830 return -1;
9831 }
9832 case '*': /* Run length encoding. */
9833 {
9834 int repeat;
9835
9836 csum += c;
9837 c = readchar (remote_timeout);
9838 csum += c;
9839 repeat = c - ' ' + 3; /* Compute repeat count. */
9840
9841 /* The character before ``*'' is repeated. */
9842
9843 if (repeat > 0 && repeat <= 255 && bc > 0)
9844 {
9845 if (bc + repeat - 1 >= buf_p->size () - 1)
9846 {
9847 /* Make some more room in the buffer. */
9848 buf_p->resize (buf_p->size () + repeat);
9849 buf = buf_p->data ();
9850 }
9851
9852 memset (&buf[bc], buf[bc - 1], repeat);
9853 bc += repeat;
9854 continue;
9855 }
9856
9857 buf[bc] = '\0';
9858 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9859 return -1;
9860 }
9861 default:
9862 if (bc >= buf_p->size () - 1)
9863 {
9864 /* Make some more room in the buffer. */
9865 buf_p->resize (buf_p->size () * 2);
9866 buf = buf_p->data ();
9867 }
9868
9869 buf[bc++] = c;
9870 csum += c;
9871 continue;
9872 }
9873 }
9874 }
9875
9876 /* Set this to the maximum number of seconds to wait instead of waiting forever
9877 in target_wait(). If this timer times out, then it generates an error and
9878 the command is aborted. This replaces most of the need for timeouts in the
9879 GDB test suite, and makes it possible to distinguish between a hung target
9880 and one with slow communications. */
9881
9882 static int watchdog = 0;
9883 static void
9884 show_watchdog (struct ui_file *file, int from_tty,
9885 struct cmd_list_element *c, const char *value)
9886 {
9887 fprintf_filtered (file, _("Watchdog timer is %s.\n"), value);
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. */
9895 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9896 don't have to change all the calls to getpkt to deal with the
9897 return value, because at the moment I don't know what the right
9898 thing to do it for those. */
9899
9900 void
9901 remote_target::getpkt (gdb::char_vector *buf, int forever)
9902 {
9903 getpkt_sane (buf, forever);
9904 }
9905
9906
9907 /* Read a packet from the remote machine, with error checking, and
9908 store it in *BUF. Resize *BUF if necessary to hold the result. If
9909 FOREVER, wait forever rather than timing out; this is used (in
9910 synchronous mode) to wait for a target that is is executing user
9911 code to stop. If FOREVER == 0, this function is allowed to time
9912 out gracefully and return an indication of this to the caller.
9913 Otherwise return the number of bytes read. If EXPECTING_NOTIF,
9914 consider receiving a notification enough reason to return to the
9915 caller. *IS_NOTIF is an output boolean that indicates whether *BUF
9916 holds a notification or not (a regular packet). */
9917
9918 int
9919 remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
9920 int forever, int expecting_notif,
9921 int *is_notif)
9922 {
9923 struct remote_state *rs = get_remote_state ();
9924 int c;
9925 int tries;
9926 int timeout;
9927 int val = -1;
9928
9929 strcpy (buf->data (), "timeout");
9930
9931 if (forever)
9932 timeout = watchdog > 0 ? watchdog : -1;
9933 else if (expecting_notif)
9934 timeout = 0; /* There should already be a char in the buffer. If
9935 not, bail out. */
9936 else
9937 timeout = remote_timeout;
9938
9939 #define MAX_TRIES 3
9940
9941 /* Process any number of notifications, and then return when
9942 we get a packet. */
9943 for (;;)
9944 {
9945 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9946 times. */
9947 for (tries = 1; tries <= MAX_TRIES; tries++)
9948 {
9949 /* This can loop forever if the remote side sends us
9950 characters continuously, but if it pauses, we'll get
9951 SERIAL_TIMEOUT from readchar because of timeout. Then
9952 we'll count that as a retry.
9953
9954 Note that even when forever is set, we will only wait
9955 forever prior to the start of a packet. After that, we
9956 expect characters to arrive at a brisk pace. They should
9957 show up within remote_timeout intervals. */
9958 do
9959 c = readchar (timeout);
9960 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9961
9962 if (c == SERIAL_TIMEOUT)
9963 {
9964 if (expecting_notif)
9965 return -1; /* Don't complain, it's normal to not get
9966 anything in this case. */
9967
9968 if (forever) /* Watchdog went off? Kill the target. */
9969 {
9970 remote_unpush_target (this);
9971 throw_error (TARGET_CLOSE_ERROR,
9972 _("Watchdog timeout has expired. "
9973 "Target detached."));
9974 }
9975
9976 remote_debug_printf ("Timed out.");
9977 }
9978 else
9979 {
9980 /* We've found the start of a packet or notification.
9981 Now collect the data. */
9982 val = read_frame (buf);
9983 if (val >= 0)
9984 break;
9985 }
9986
9987 remote_serial_write ("-", 1);
9988 }
9989
9990 if (tries > MAX_TRIES)
9991 {
9992 /* We have tried hard enough, and just can't receive the
9993 packet/notification. Give up. */
9994 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9995
9996 /* Skip the ack char if we're in no-ack mode. */
9997 if (!rs->noack_mode)
9998 remote_serial_write ("+", 1);
9999 return -1;
10000 }
10001
10002 /* If we got an ordinary packet, return that to our caller. */
10003 if (c == '$')
10004 {
10005 if (remote_debug)
10006 {
10007 int max_chars;
10008
10009 if (remote_packet_max_chars < 0)
10010 max_chars = val;
10011 else
10012 max_chars = remote_packet_max_chars;
10013
10014 std::string str
10015 = escape_buffer (buf->data (),
10016 std::min (val, max_chars));
10017
10018 if (val > max_chars)
10019 remote_debug_printf_nofunc
10020 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10021 val - max_chars);
10022 else
10023 remote_debug_printf_nofunc ("Packet received: %s",
10024 str.c_str ());
10025 }
10026
10027 /* Skip the ack char if we're in no-ack mode. */
10028 if (!rs->noack_mode)
10029 remote_serial_write ("+", 1);
10030 if (is_notif != NULL)
10031 *is_notif = 0;
10032 return val;
10033 }
10034
10035 /* If we got a notification, handle it, and go back to looking
10036 for a packet. */
10037 else
10038 {
10039 gdb_assert (c == '%');
10040
10041 remote_debug_printf_nofunc
10042 (" Notification received: %s",
10043 escape_buffer (buf->data (), val).c_str ());
10044
10045 if (is_notif != NULL)
10046 *is_notif = 1;
10047
10048 handle_notification (rs->notif_state, buf->data ());
10049
10050 /* Notifications require no acknowledgement. */
10051
10052 if (expecting_notif)
10053 return val;
10054 }
10055 }
10056 }
10057
10058 int
10059 remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
10060 {
10061 return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
10062 }
10063
10064 int
10065 remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
10066 int *is_notif)
10067 {
10068 return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
10069 }
10070
10071 /* Kill any new fork children of inferior INF that haven't been
10072 processed by follow_fork. */
10073
10074 void
10075 remote_target::kill_new_fork_children (inferior *inf)
10076 {
10077 remote_state *rs = get_remote_state ();
10078 struct notif_client *notif = &notif_client_stop;
10079
10080 /* Kill the fork child threads of any threads in inferior INF that are stopped
10081 at a fork event. */
10082 for (thread_info *thread : inf->non_exited_threads ())
10083 {
10084 const target_waitstatus *ws = thread_pending_fork_status (thread);
10085
10086 if (ws == nullptr)
10087 continue;
10088
10089 int child_pid = ws->child_ptid ().pid ();
10090 int res = remote_vkill (child_pid);
10091
10092 if (res != 0)
10093 error (_("Can't kill fork child process %d"), child_pid);
10094 }
10095
10096 /* Check for any pending fork events (not reported or processed yet)
10097 in inferior INF and kill those fork child threads as well. */
10098 remote_notif_get_pending_events (notif);
10099 for (auto &event : rs->stop_reply_queue)
10100 {
10101 if (event->ptid.pid () != inf->pid)
10102 continue;
10103
10104 if (!is_fork_status (event->ws.kind ()))
10105 continue;
10106
10107 int child_pid = event->ws.child_ptid ().pid ();
10108 int res = remote_vkill (child_pid);
10109
10110 if (res != 0)
10111 error (_("Can't kill fork child process %d"), child_pid);
10112 }
10113 }
10114
10115 \f
10116 /* Target hook to kill the current inferior. */
10117
10118 void
10119 remote_target::kill ()
10120 {
10121 int res = -1;
10122 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10123 struct remote_state *rs = get_remote_state ();
10124
10125 gdb_assert (inf != nullptr);
10126
10127 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
10128 {
10129 /* If we're stopped while forking and we haven't followed yet,
10130 kill the child task. We need to do this before killing the
10131 parent task because if this is a vfork then the parent will
10132 be sleeping. */
10133 kill_new_fork_children (inf);
10134
10135 res = remote_vkill (inf->pid);
10136 if (res == 0)
10137 {
10138 target_mourn_inferior (inferior_ptid);
10139 return;
10140 }
10141 }
10142
10143 /* If we are in 'target remote' mode and we are killing the only
10144 inferior, then we will tell gdbserver to exit and unpush the
10145 target. */
10146 if (res == -1 && !remote_multi_process_p (rs)
10147 && number_of_live_inferiors (this) == 1)
10148 {
10149 remote_kill_k ();
10150
10151 /* We've killed the remote end, we get to mourn it. If we are
10152 not in extended mode, mourning the inferior also unpushes
10153 remote_ops from the target stack, which closes the remote
10154 connection. */
10155 target_mourn_inferior (inferior_ptid);
10156
10157 return;
10158 }
10159
10160 error (_("Can't kill process"));
10161 }
10162
10163 /* Send a kill request to the target using the 'vKill' packet. */
10164
10165 int
10166 remote_target::remote_vkill (int pid)
10167 {
10168 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
10169 return -1;
10170
10171 remote_state *rs = get_remote_state ();
10172
10173 /* Tell the remote target to detach. */
10174 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10175 putpkt (rs->buf);
10176 getpkt (&rs->buf, 0);
10177
10178 switch (packet_ok (rs->buf,
10179 &remote_protocol_packets[PACKET_vKill]))
10180 {
10181 case PACKET_OK:
10182 return 0;
10183 case PACKET_ERROR:
10184 return 1;
10185 case PACKET_UNKNOWN:
10186 return -1;
10187 default:
10188 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
10189 }
10190 }
10191
10192 /* Send a kill request to the target using the 'k' packet. */
10193
10194 void
10195 remote_target::remote_kill_k ()
10196 {
10197 /* Catch errors so the user can quit from gdb even when we
10198 aren't on speaking terms with the remote system. */
10199 try
10200 {
10201 putpkt ("k");
10202 }
10203 catch (const gdb_exception_error &ex)
10204 {
10205 if (ex.error == TARGET_CLOSE_ERROR)
10206 {
10207 /* If we got an (EOF) error that caused the target
10208 to go away, then we're done, that's what we wanted.
10209 "k" is susceptible to cause a premature EOF, given
10210 that the remote server isn't actually required to
10211 reply to "k", and it can happen that it doesn't
10212 even get to reply ACK to the "k". */
10213 return;
10214 }
10215
10216 /* Otherwise, something went wrong. We didn't actually kill
10217 the target. Just propagate the exception, and let the
10218 user or higher layers decide what to do. */
10219 throw;
10220 }
10221 }
10222
10223 void
10224 remote_target::mourn_inferior ()
10225 {
10226 struct remote_state *rs = get_remote_state ();
10227
10228 /* We're no longer interested in notification events of an inferior
10229 that exited or was killed/detached. */
10230 discard_pending_stop_replies (current_inferior ());
10231
10232 /* In 'target remote' mode with one inferior, we close the connection. */
10233 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10234 {
10235 remote_unpush_target (this);
10236 return;
10237 }
10238
10239 /* In case we got here due to an error, but we're going to stay
10240 connected. */
10241 rs->waiting_for_stop_reply = 0;
10242
10243 /* If the current general thread belonged to the process we just
10244 detached from or has exited, the remote side current general
10245 thread becomes undefined. Considering a case like this:
10246
10247 - We just got here due to a detach.
10248 - The process that we're detaching from happens to immediately
10249 report a global breakpoint being hit in non-stop mode, in the
10250 same thread we had selected before.
10251 - GDB attaches to this process again.
10252 - This event happens to be the next event we handle.
10253
10254 GDB would consider that the current general thread didn't need to
10255 be set on the stub side (with Hg), since for all it knew,
10256 GENERAL_THREAD hadn't changed.
10257
10258 Notice that although in all-stop mode, the remote server always
10259 sets the current thread to the thread reporting the stop event,
10260 that doesn't happen in non-stop mode; in non-stop, the stub *must
10261 not* change the current thread when reporting a breakpoint hit,
10262 due to the decoupling of event reporting and event handling.
10263
10264 To keep things simple, we always invalidate our notion of the
10265 current thread. */
10266 record_currthread (rs, minus_one_ptid);
10267
10268 /* Call common code to mark the inferior as not running. */
10269 generic_mourn_inferior ();
10270 }
10271
10272 bool
10273 extended_remote_target::supports_disable_randomization ()
10274 {
10275 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
10276 }
10277
10278 void
10279 remote_target::extended_remote_disable_randomization (int val)
10280 {
10281 struct remote_state *rs = get_remote_state ();
10282 char *reply;
10283
10284 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10285 "QDisableRandomization:%x", val);
10286 putpkt (rs->buf);
10287 reply = remote_get_noisy_reply ();
10288 if (*reply == '\0')
10289 error (_("Target does not support QDisableRandomization."));
10290 if (strcmp (reply, "OK") != 0)
10291 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10292 }
10293
10294 int
10295 remote_target::extended_remote_run (const std::string &args)
10296 {
10297 struct remote_state *rs = get_remote_state ();
10298 int len;
10299 const char *remote_exec_file = get_remote_exec_file ();
10300
10301 /* If the user has disabled vRun support, or we have detected that
10302 support is not available, do not try it. */
10303 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
10304 return -1;
10305
10306 strcpy (rs->buf.data (), "vRun;");
10307 len = strlen (rs->buf.data ());
10308
10309 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10310 error (_("Remote file name too long for run packet"));
10311 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10312 strlen (remote_exec_file));
10313
10314 if (!args.empty ())
10315 {
10316 int i;
10317
10318 gdb_argv argv (args.c_str ());
10319 for (i = 0; argv[i] != NULL; i++)
10320 {
10321 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10322 error (_("Argument list too long for run packet"));
10323 rs->buf[len++] = ';';
10324 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10325 strlen (argv[i]));
10326 }
10327 }
10328
10329 rs->buf[len++] = '\0';
10330
10331 putpkt (rs->buf);
10332 getpkt (&rs->buf, 0);
10333
10334 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
10335 {
10336 case PACKET_OK:
10337 /* We have a wait response. All is well. */
10338 return 0;
10339 case PACKET_UNKNOWN:
10340 return -1;
10341 case PACKET_ERROR:
10342 if (remote_exec_file[0] == '\0')
10343 error (_("Running the default executable on the remote target failed; "
10344 "try \"set remote exec-file\"?"));
10345 else
10346 error (_("Running \"%s\" on the remote target failed"),
10347 remote_exec_file);
10348 default:
10349 gdb_assert_not_reached ("bad switch");
10350 }
10351 }
10352
10353 /* Helper function to send set/unset environment packets. ACTION is
10354 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10355 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10356 sent. */
10357
10358 void
10359 remote_target::send_environment_packet (const char *action,
10360 const char *packet,
10361 const char *value)
10362 {
10363 remote_state *rs = get_remote_state ();
10364
10365 /* Convert the environment variable to an hex string, which
10366 is the best format to be transmitted over the wire. */
10367 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10368 strlen (value));
10369
10370 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10371 "%s:%s", packet, encoded_value.c_str ());
10372
10373 putpkt (rs->buf);
10374 getpkt (&rs->buf, 0);
10375 if (strcmp (rs->buf.data (), "OK") != 0)
10376 warning (_("Unable to %s environment variable '%s' on remote."),
10377 action, value);
10378 }
10379
10380 /* Helper function to handle the QEnvironment* packets. */
10381
10382 void
10383 remote_target::extended_remote_environment_support ()
10384 {
10385 remote_state *rs = get_remote_state ();
10386
10387 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10388 {
10389 putpkt ("QEnvironmentReset");
10390 getpkt (&rs->buf, 0);
10391 if (strcmp (rs->buf.data (), "OK") != 0)
10392 warning (_("Unable to reset environment on remote."));
10393 }
10394
10395 gdb_environ *e = &current_inferior ()->environment;
10396
10397 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10398 for (const std::string &el : e->user_set_env ())
10399 send_environment_packet ("set", "QEnvironmentHexEncoded",
10400 el.c_str ());
10401
10402 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10403 for (const std::string &el : e->user_unset_env ())
10404 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10405 }
10406
10407 /* Helper function to set the current working directory for the
10408 inferior in the remote target. */
10409
10410 void
10411 remote_target::extended_remote_set_inferior_cwd ()
10412 {
10413 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10414 {
10415 const std::string &inferior_cwd = current_inferior ()->cwd ();
10416 remote_state *rs = get_remote_state ();
10417
10418 if (!inferior_cwd.empty ())
10419 {
10420 std::string hexpath
10421 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10422 inferior_cwd.size ());
10423
10424 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10425 "QSetWorkingDir:%s", hexpath.c_str ());
10426 }
10427 else
10428 {
10429 /* An empty inferior_cwd means that the user wants us to
10430 reset the remote server's inferior's cwd. */
10431 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10432 "QSetWorkingDir:");
10433 }
10434
10435 putpkt (rs->buf);
10436 getpkt (&rs->buf, 0);
10437 if (packet_ok (rs->buf,
10438 &remote_protocol_packets[PACKET_QSetWorkingDir])
10439 != PACKET_OK)
10440 error (_("\
10441 Remote replied unexpectedly while setting the inferior's working\n\
10442 directory: %s"),
10443 rs->buf.data ());
10444
10445 }
10446 }
10447
10448 /* In the extended protocol we want to be able to do things like
10449 "run" and have them basically work as expected. So we need
10450 a special create_inferior function. We support changing the
10451 executable file and the command line arguments, but not the
10452 environment. */
10453
10454 void
10455 extended_remote_target::create_inferior (const char *exec_file,
10456 const std::string &args,
10457 char **env, int from_tty)
10458 {
10459 int run_worked;
10460 char *stop_reply;
10461 struct remote_state *rs = get_remote_state ();
10462 const char *remote_exec_file = get_remote_exec_file ();
10463
10464 /* If running asynchronously, register the target file descriptor
10465 with the event loop. */
10466 if (target_can_async_p ())
10467 target_async (1);
10468
10469 /* Disable address space randomization if requested (and supported). */
10470 if (supports_disable_randomization ())
10471 extended_remote_disable_randomization (disable_randomization);
10472
10473 /* If startup-with-shell is on, we inform gdbserver to start the
10474 remote inferior using a shell. */
10475 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10476 {
10477 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10478 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10479 putpkt (rs->buf);
10480 getpkt (&rs->buf, 0);
10481 if (strcmp (rs->buf.data (), "OK") != 0)
10482 error (_("\
10483 Remote replied unexpectedly while setting startup-with-shell: %s"),
10484 rs->buf.data ());
10485 }
10486
10487 extended_remote_environment_support ();
10488
10489 extended_remote_set_inferior_cwd ();
10490
10491 /* Now restart the remote server. */
10492 run_worked = extended_remote_run (args) != -1;
10493 if (!run_worked)
10494 {
10495 /* vRun was not supported. Fail if we need it to do what the
10496 user requested. */
10497 if (remote_exec_file[0])
10498 error (_("Remote target does not support \"set remote exec-file\""));
10499 if (!args.empty ())
10500 error (_("Remote target does not support \"set args\" or run ARGS"));
10501
10502 /* Fall back to "R". */
10503 extended_remote_restart ();
10504 }
10505
10506 /* vRun's success return is a stop reply. */
10507 stop_reply = run_worked ? rs->buf.data () : NULL;
10508 add_current_inferior_and_thread (stop_reply);
10509
10510 /* Get updated offsets, if the stub uses qOffsets. */
10511 get_offsets ();
10512 }
10513 \f
10514
10515 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10516 the list of conditions (in agent expression bytecode format), if any, the
10517 target needs to evaluate. The output is placed into the packet buffer
10518 started from BUF and ended at BUF_END. */
10519
10520 static int
10521 remote_add_target_side_condition (struct gdbarch *gdbarch,
10522 struct bp_target_info *bp_tgt, char *buf,
10523 char *buf_end)
10524 {
10525 if (bp_tgt->conditions.empty ())
10526 return 0;
10527
10528 buf += strlen (buf);
10529 xsnprintf (buf, buf_end - buf, "%s", ";");
10530 buf++;
10531
10532 /* Send conditions to the target. */
10533 for (agent_expr *aexpr : bp_tgt->conditions)
10534 {
10535 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10536 buf += strlen (buf);
10537 for (int i = 0; i < aexpr->len; ++i)
10538 buf = pack_hex_byte (buf, aexpr->buf[i]);
10539 *buf = '\0';
10540 }
10541 return 0;
10542 }
10543
10544 static void
10545 remote_add_target_side_commands (struct gdbarch *gdbarch,
10546 struct bp_target_info *bp_tgt, char *buf)
10547 {
10548 if (bp_tgt->tcommands.empty ())
10549 return;
10550
10551 buf += strlen (buf);
10552
10553 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10554 buf += strlen (buf);
10555
10556 /* Concatenate all the agent expressions that are commands into the
10557 cmds parameter. */
10558 for (agent_expr *aexpr : bp_tgt->tcommands)
10559 {
10560 sprintf (buf, "X%x,", aexpr->len);
10561 buf += strlen (buf);
10562 for (int i = 0; i < aexpr->len; ++i)
10563 buf = pack_hex_byte (buf, aexpr->buf[i]);
10564 *buf = '\0';
10565 }
10566 }
10567
10568 /* Insert a breakpoint. On targets that have software breakpoint
10569 support, we ask the remote target to do the work; on targets
10570 which don't, we insert a traditional memory breakpoint. */
10571
10572 int
10573 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10574 struct bp_target_info *bp_tgt)
10575 {
10576 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10577 If it succeeds, then set the support to PACKET_ENABLE. If it
10578 fails, and the user has explicitly requested the Z support then
10579 report an error, otherwise, mark it disabled and go on. */
10580
10581 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10582 {
10583 CORE_ADDR addr = bp_tgt->reqstd_address;
10584 struct remote_state *rs;
10585 char *p, *endbuf;
10586
10587 /* Make sure the remote is pointing at the right process, if
10588 necessary. */
10589 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10590 set_general_process ();
10591
10592 rs = get_remote_state ();
10593 p = rs->buf.data ();
10594 endbuf = p + get_remote_packet_size ();
10595
10596 *(p++) = 'Z';
10597 *(p++) = '0';
10598 *(p++) = ',';
10599 addr = (ULONGEST) remote_address_masked (addr);
10600 p += hexnumstr (p, addr);
10601 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10602
10603 if (supports_evaluation_of_breakpoint_conditions ())
10604 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10605
10606 if (can_run_breakpoint_commands ())
10607 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10608
10609 putpkt (rs->buf);
10610 getpkt (&rs->buf, 0);
10611
10612 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10613 {
10614 case PACKET_ERROR:
10615 return -1;
10616 case PACKET_OK:
10617 return 0;
10618 case PACKET_UNKNOWN:
10619 break;
10620 }
10621 }
10622
10623 /* If this breakpoint has target-side commands but this stub doesn't
10624 support Z0 packets, throw error. */
10625 if (!bp_tgt->tcommands.empty ())
10626 throw_error (NOT_SUPPORTED_ERROR, _("\
10627 Target doesn't support breakpoints that have target side commands."));
10628
10629 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10630 }
10631
10632 int
10633 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10634 struct bp_target_info *bp_tgt,
10635 enum remove_bp_reason reason)
10636 {
10637 CORE_ADDR addr = bp_tgt->placed_address;
10638 struct remote_state *rs = get_remote_state ();
10639
10640 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10641 {
10642 char *p = rs->buf.data ();
10643 char *endbuf = p + get_remote_packet_size ();
10644
10645 /* Make sure the remote is pointing at the right process, if
10646 necessary. */
10647 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10648 set_general_process ();
10649
10650 *(p++) = 'z';
10651 *(p++) = '0';
10652 *(p++) = ',';
10653
10654 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10655 p += hexnumstr (p, addr);
10656 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10657
10658 putpkt (rs->buf);
10659 getpkt (&rs->buf, 0);
10660
10661 return (rs->buf[0] == 'E');
10662 }
10663
10664 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10665 }
10666
10667 static enum Z_packet_type
10668 watchpoint_to_Z_packet (int type)
10669 {
10670 switch (type)
10671 {
10672 case hw_write:
10673 return Z_PACKET_WRITE_WP;
10674 break;
10675 case hw_read:
10676 return Z_PACKET_READ_WP;
10677 break;
10678 case hw_access:
10679 return Z_PACKET_ACCESS_WP;
10680 break;
10681 default:
10682 internal_error (__FILE__, __LINE__,
10683 _("hw_bp_to_z: bad watchpoint type %d"), type);
10684 }
10685 }
10686
10687 int
10688 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10689 enum target_hw_bp_type type, struct expression *cond)
10690 {
10691 struct remote_state *rs = get_remote_state ();
10692 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10693 char *p;
10694 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10695
10696 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10697 return 1;
10698
10699 /* Make sure the remote is pointing at the right process, if
10700 necessary. */
10701 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10702 set_general_process ();
10703
10704 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10705 p = strchr (rs->buf.data (), '\0');
10706 addr = remote_address_masked (addr);
10707 p += hexnumstr (p, (ULONGEST) addr);
10708 xsnprintf (p, endbuf - p, ",%x", len);
10709
10710 putpkt (rs->buf);
10711 getpkt (&rs->buf, 0);
10712
10713 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10714 {
10715 case PACKET_ERROR:
10716 return -1;
10717 case PACKET_UNKNOWN:
10718 return 1;
10719 case PACKET_OK:
10720 return 0;
10721 }
10722 internal_error (__FILE__, __LINE__,
10723 _("remote_insert_watchpoint: reached end of function"));
10724 }
10725
10726 bool
10727 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10728 CORE_ADDR start, int length)
10729 {
10730 CORE_ADDR diff = remote_address_masked (addr - start);
10731
10732 return diff < length;
10733 }
10734
10735
10736 int
10737 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10738 enum target_hw_bp_type type, struct expression *cond)
10739 {
10740 struct remote_state *rs = get_remote_state ();
10741 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10742 char *p;
10743 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10744
10745 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10746 return -1;
10747
10748 /* Make sure the remote is pointing at the right process, if
10749 necessary. */
10750 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10751 set_general_process ();
10752
10753 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10754 p = strchr (rs->buf.data (), '\0');
10755 addr = remote_address_masked (addr);
10756 p += hexnumstr (p, (ULONGEST) addr);
10757 xsnprintf (p, endbuf - p, ",%x", len);
10758 putpkt (rs->buf);
10759 getpkt (&rs->buf, 0);
10760
10761 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10762 {
10763 case PACKET_ERROR:
10764 case PACKET_UNKNOWN:
10765 return -1;
10766 case PACKET_OK:
10767 return 0;
10768 }
10769 internal_error (__FILE__, __LINE__,
10770 _("remote_remove_watchpoint: reached end of function"));
10771 }
10772
10773
10774 static int remote_hw_watchpoint_limit = -1;
10775 static int remote_hw_watchpoint_length_limit = -1;
10776 static int remote_hw_breakpoint_limit = -1;
10777
10778 int
10779 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10780 {
10781 if (remote_hw_watchpoint_length_limit == 0)
10782 return 0;
10783 else if (remote_hw_watchpoint_length_limit < 0)
10784 return 1;
10785 else if (len <= remote_hw_watchpoint_length_limit)
10786 return 1;
10787 else
10788 return 0;
10789 }
10790
10791 int
10792 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10793 {
10794 if (type == bp_hardware_breakpoint)
10795 {
10796 if (remote_hw_breakpoint_limit == 0)
10797 return 0;
10798 else if (remote_hw_breakpoint_limit < 0)
10799 return 1;
10800 else if (cnt <= remote_hw_breakpoint_limit)
10801 return 1;
10802 }
10803 else
10804 {
10805 if (remote_hw_watchpoint_limit == 0)
10806 return 0;
10807 else if (remote_hw_watchpoint_limit < 0)
10808 return 1;
10809 else if (ot)
10810 return -1;
10811 else if (cnt <= remote_hw_watchpoint_limit)
10812 return 1;
10813 }
10814 return -1;
10815 }
10816
10817 /* The to_stopped_by_sw_breakpoint method of target remote. */
10818
10819 bool
10820 remote_target::stopped_by_sw_breakpoint ()
10821 {
10822 struct thread_info *thread = inferior_thread ();
10823
10824 return (thread->priv != NULL
10825 && (get_remote_thread_info (thread)->stop_reason
10826 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10827 }
10828
10829 /* The to_supports_stopped_by_sw_breakpoint method of target
10830 remote. */
10831
10832 bool
10833 remote_target::supports_stopped_by_sw_breakpoint ()
10834 {
10835 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10836 }
10837
10838 /* The to_stopped_by_hw_breakpoint method of target remote. */
10839
10840 bool
10841 remote_target::stopped_by_hw_breakpoint ()
10842 {
10843 struct thread_info *thread = inferior_thread ();
10844
10845 return (thread->priv != NULL
10846 && (get_remote_thread_info (thread)->stop_reason
10847 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10848 }
10849
10850 /* The to_supports_stopped_by_hw_breakpoint method of target
10851 remote. */
10852
10853 bool
10854 remote_target::supports_stopped_by_hw_breakpoint ()
10855 {
10856 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10857 }
10858
10859 bool
10860 remote_target::stopped_by_watchpoint ()
10861 {
10862 struct thread_info *thread = inferior_thread ();
10863
10864 return (thread->priv != NULL
10865 && (get_remote_thread_info (thread)->stop_reason
10866 == TARGET_STOPPED_BY_WATCHPOINT));
10867 }
10868
10869 bool
10870 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10871 {
10872 struct thread_info *thread = inferior_thread ();
10873
10874 if (thread->priv != NULL
10875 && (get_remote_thread_info (thread)->stop_reason
10876 == TARGET_STOPPED_BY_WATCHPOINT))
10877 {
10878 *addr_p = get_remote_thread_info (thread)->watch_data_address;
10879 return true;
10880 }
10881
10882 return false;
10883 }
10884
10885
10886 int
10887 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10888 struct bp_target_info *bp_tgt)
10889 {
10890 CORE_ADDR addr = bp_tgt->reqstd_address;
10891 struct remote_state *rs;
10892 char *p, *endbuf;
10893 char *message;
10894
10895 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10896 return -1;
10897
10898 /* Make sure the remote is pointing at the right process, if
10899 necessary. */
10900 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10901 set_general_process ();
10902
10903 rs = get_remote_state ();
10904 p = rs->buf.data ();
10905 endbuf = p + get_remote_packet_size ();
10906
10907 *(p++) = 'Z';
10908 *(p++) = '1';
10909 *(p++) = ',';
10910
10911 addr = remote_address_masked (addr);
10912 p += hexnumstr (p, (ULONGEST) addr);
10913 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10914
10915 if (supports_evaluation_of_breakpoint_conditions ())
10916 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10917
10918 if (can_run_breakpoint_commands ())
10919 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10920
10921 putpkt (rs->buf);
10922 getpkt (&rs->buf, 0);
10923
10924 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10925 {
10926 case PACKET_ERROR:
10927 if (rs->buf[1] == '.')
10928 {
10929 message = strchr (&rs->buf[2], '.');
10930 if (message)
10931 error (_("Remote failure reply: %s"), message + 1);
10932 }
10933 return -1;
10934 case PACKET_UNKNOWN:
10935 return -1;
10936 case PACKET_OK:
10937 return 0;
10938 }
10939 internal_error (__FILE__, __LINE__,
10940 _("remote_insert_hw_breakpoint: reached end of function"));
10941 }
10942
10943
10944 int
10945 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10946 struct bp_target_info *bp_tgt)
10947 {
10948 CORE_ADDR addr;
10949 struct remote_state *rs = get_remote_state ();
10950 char *p = rs->buf.data ();
10951 char *endbuf = p + get_remote_packet_size ();
10952
10953 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10954 return -1;
10955
10956 /* Make sure the remote is pointing at the right process, if
10957 necessary. */
10958 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10959 set_general_process ();
10960
10961 *(p++) = 'z';
10962 *(p++) = '1';
10963 *(p++) = ',';
10964
10965 addr = remote_address_masked (bp_tgt->placed_address);
10966 p += hexnumstr (p, (ULONGEST) addr);
10967 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10968
10969 putpkt (rs->buf);
10970 getpkt (&rs->buf, 0);
10971
10972 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10973 {
10974 case PACKET_ERROR:
10975 case PACKET_UNKNOWN:
10976 return -1;
10977 case PACKET_OK:
10978 return 0;
10979 }
10980 internal_error (__FILE__, __LINE__,
10981 _("remote_remove_hw_breakpoint: reached end of function"));
10982 }
10983
10984 /* Verify memory using the "qCRC:" request. */
10985
10986 int
10987 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10988 {
10989 struct remote_state *rs = get_remote_state ();
10990 unsigned long host_crc, target_crc;
10991 char *tmp;
10992
10993 /* It doesn't make sense to use qCRC if the remote target is
10994 connected but not running. */
10995 if (target_has_execution ()
10996 && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10997 {
10998 enum packet_result result;
10999
11000 /* Make sure the remote is pointing at the right process. */
11001 set_general_process ();
11002
11003 /* FIXME: assumes lma can fit into long. */
11004 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
11005 (long) lma, (long) size);
11006 putpkt (rs->buf);
11007
11008 /* Be clever; compute the host_crc before waiting for target
11009 reply. */
11010 host_crc = xcrc32 (data, size, 0xffffffff);
11011
11012 getpkt (&rs->buf, 0);
11013
11014 result = packet_ok (rs->buf,
11015 &remote_protocol_packets[PACKET_qCRC]);
11016 if (result == PACKET_ERROR)
11017 return -1;
11018 else if (result == PACKET_OK)
11019 {
11020 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11021 target_crc = target_crc * 16 + fromhex (*tmp);
11022
11023 return (host_crc == target_crc);
11024 }
11025 }
11026
11027 return simple_verify_memory (this, data, lma, size);
11028 }
11029
11030 /* compare-sections command
11031
11032 With no arguments, compares each loadable section in the exec bfd
11033 with the same memory range on the target, and reports mismatches.
11034 Useful for verifying the image on the target against the exec file. */
11035
11036 static void
11037 compare_sections_command (const char *args, int from_tty)
11038 {
11039 asection *s;
11040 const char *sectname;
11041 bfd_size_type size;
11042 bfd_vma lma;
11043 int matched = 0;
11044 int mismatched = 0;
11045 int res;
11046 int read_only = 0;
11047
11048 if (!current_program_space->exec_bfd ())
11049 error (_("command cannot be used without an exec file"));
11050
11051 if (args != NULL && strcmp (args, "-r") == 0)
11052 {
11053 read_only = 1;
11054 args = NULL;
11055 }
11056
11057 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11058 {
11059 if (!(s->flags & SEC_LOAD))
11060 continue; /* Skip non-loadable section. */
11061
11062 if (read_only && (s->flags & SEC_READONLY) == 0)
11063 continue; /* Skip writeable sections */
11064
11065 size = bfd_section_size (s);
11066 if (size == 0)
11067 continue; /* Skip zero-length section. */
11068
11069 sectname = bfd_section_name (s);
11070 if (args && strcmp (args, sectname) != 0)
11071 continue; /* Not the section selected by user. */
11072
11073 matched = 1; /* Do this section. */
11074 lma = s->lma;
11075
11076 gdb::byte_vector sectdata (size);
11077 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11078 sectdata.data (), 0, size);
11079
11080 res = target_verify_memory (sectdata.data (), lma, size);
11081
11082 if (res == -1)
11083 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11084 paddress (target_gdbarch (), lma),
11085 paddress (target_gdbarch (), lma + size));
11086
11087 printf_filtered ("Section %s, range %s -- %s: ", sectname,
11088 paddress (target_gdbarch (), lma),
11089 paddress (target_gdbarch (), lma + size));
11090 if (res)
11091 printf_filtered ("matched.\n");
11092 else
11093 {
11094 printf_filtered ("MIS-MATCHED!\n");
11095 mismatched++;
11096 }
11097 }
11098 if (mismatched > 0)
11099 warning (_("One or more sections of the target image does not match\n\
11100 the loaded file\n"));
11101 if (args && !matched)
11102 printf_filtered (_("No loaded section named '%s'.\n"), args);
11103 }
11104
11105 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11106 into remote target. The number of bytes written to the remote
11107 target is returned, or -1 for error. */
11108
11109 target_xfer_status
11110 remote_target::remote_write_qxfer (const char *object_name,
11111 const char *annex, const gdb_byte *writebuf,
11112 ULONGEST offset, LONGEST len,
11113 ULONGEST *xfered_len,
11114 struct packet_config *packet)
11115 {
11116 int i, buf_len;
11117 ULONGEST n;
11118 struct remote_state *rs = get_remote_state ();
11119 int max_size = get_memory_write_packet_size ();
11120
11121 if (packet_config_support (packet) == PACKET_DISABLE)
11122 return TARGET_XFER_E_IO;
11123
11124 /* Insert header. */
11125 i = snprintf (rs->buf.data (), max_size,
11126 "qXfer:%s:write:%s:%s:",
11127 object_name, annex ? annex : "",
11128 phex_nz (offset, sizeof offset));
11129 max_size -= (i + 1);
11130
11131 /* Escape as much data as fits into rs->buf. */
11132 buf_len = remote_escape_output
11133 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11134
11135 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11136 || getpkt_sane (&rs->buf, 0) < 0
11137 || packet_ok (rs->buf, packet) != PACKET_OK)
11138 return TARGET_XFER_E_IO;
11139
11140 unpack_varlen_hex (rs->buf.data (), &n);
11141
11142 *xfered_len = n;
11143 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11144 }
11145
11146 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11147 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11148 number of bytes read is returned, or 0 for EOF, or -1 for error.
11149 The number of bytes read may be less than LEN without indicating an
11150 EOF. PACKET is checked and updated to indicate whether the remote
11151 target supports this object. */
11152
11153 target_xfer_status
11154 remote_target::remote_read_qxfer (const char *object_name,
11155 const char *annex,
11156 gdb_byte *readbuf, ULONGEST offset,
11157 LONGEST len,
11158 ULONGEST *xfered_len,
11159 struct packet_config *packet)
11160 {
11161 struct remote_state *rs = get_remote_state ();
11162 LONGEST i, n, packet_len;
11163
11164 if (packet_config_support (packet) == PACKET_DISABLE)
11165 return TARGET_XFER_E_IO;
11166
11167 /* Check whether we've cached an end-of-object packet that matches
11168 this request. */
11169 if (rs->finished_object)
11170 {
11171 if (strcmp (object_name, rs->finished_object) == 0
11172 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11173 && offset == rs->finished_offset)
11174 return TARGET_XFER_EOF;
11175
11176
11177 /* Otherwise, we're now reading something different. Discard
11178 the cache. */
11179 xfree (rs->finished_object);
11180 xfree (rs->finished_annex);
11181 rs->finished_object = NULL;
11182 rs->finished_annex = NULL;
11183 }
11184
11185 /* Request only enough to fit in a single packet. The actual data
11186 may not, since we don't know how much of it will need to be escaped;
11187 the target is free to respond with slightly less data. We subtract
11188 five to account for the response type and the protocol frame. */
11189 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11190 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11191 "qXfer:%s:read:%s:%s,%s",
11192 object_name, annex ? annex : "",
11193 phex_nz (offset, sizeof offset),
11194 phex_nz (n, sizeof n));
11195 i = putpkt (rs->buf);
11196 if (i < 0)
11197 return TARGET_XFER_E_IO;
11198
11199 rs->buf[0] = '\0';
11200 packet_len = getpkt_sane (&rs->buf, 0);
11201 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
11202 return TARGET_XFER_E_IO;
11203
11204 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11205 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11206
11207 /* 'm' means there is (or at least might be) more data after this
11208 batch. That does not make sense unless there's at least one byte
11209 of data in this reply. */
11210 if (rs->buf[0] == 'm' && packet_len == 1)
11211 error (_("Remote qXfer reply contained no data."));
11212
11213 /* Got some data. */
11214 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11215 packet_len - 1, readbuf, n);
11216
11217 /* 'l' is an EOF marker, possibly including a final block of data,
11218 or possibly empty. If we have the final block of a non-empty
11219 object, record this fact to bypass a subsequent partial read. */
11220 if (rs->buf[0] == 'l' && offset + i > 0)
11221 {
11222 rs->finished_object = xstrdup (object_name);
11223 rs->finished_annex = xstrdup (annex ? annex : "");
11224 rs->finished_offset = offset + i;
11225 }
11226
11227 if (i == 0)
11228 return TARGET_XFER_EOF;
11229 else
11230 {
11231 *xfered_len = i;
11232 return TARGET_XFER_OK;
11233 }
11234 }
11235
11236 enum target_xfer_status
11237 remote_target::xfer_partial (enum target_object object,
11238 const char *annex, gdb_byte *readbuf,
11239 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11240 ULONGEST *xfered_len)
11241 {
11242 struct remote_state *rs;
11243 int i;
11244 char *p2;
11245 char query_type;
11246 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
11247
11248 set_remote_traceframe ();
11249 set_general_thread (inferior_ptid);
11250
11251 rs = get_remote_state ();
11252
11253 /* Handle memory using the standard memory routines. */
11254 if (object == TARGET_OBJECT_MEMORY)
11255 {
11256 /* If the remote target is connected but not running, we should
11257 pass this request down to a lower stratum (e.g. the executable
11258 file). */
11259 if (!target_has_execution ())
11260 return TARGET_XFER_EOF;
11261
11262 if (writebuf != NULL)
11263 return remote_write_bytes (offset, writebuf, len, unit_size,
11264 xfered_len);
11265 else
11266 return remote_read_bytes (offset, readbuf, len, unit_size,
11267 xfered_len);
11268 }
11269
11270 /* Handle extra signal info using qxfer packets. */
11271 if (object == TARGET_OBJECT_SIGNAL_INFO)
11272 {
11273 if (readbuf)
11274 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11275 xfered_len, &remote_protocol_packets
11276 [PACKET_qXfer_siginfo_read]);
11277 else
11278 return remote_write_qxfer ("siginfo", annex,
11279 writebuf, offset, len, xfered_len,
11280 &remote_protocol_packets
11281 [PACKET_qXfer_siginfo_write]);
11282 }
11283
11284 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11285 {
11286 if (readbuf)
11287 return remote_read_qxfer ("statictrace", annex,
11288 readbuf, offset, len, xfered_len,
11289 &remote_protocol_packets
11290 [PACKET_qXfer_statictrace_read]);
11291 else
11292 return TARGET_XFER_E_IO;
11293 }
11294
11295 /* Only handle flash writes. */
11296 if (writebuf != NULL)
11297 {
11298 switch (object)
11299 {
11300 case TARGET_OBJECT_FLASH:
11301 return remote_flash_write (offset, len, xfered_len,
11302 writebuf);
11303
11304 default:
11305 return TARGET_XFER_E_IO;
11306 }
11307 }
11308
11309 /* Map pre-existing objects onto letters. DO NOT do this for new
11310 objects!!! Instead specify new query packets. */
11311 switch (object)
11312 {
11313 case TARGET_OBJECT_AVR:
11314 query_type = 'R';
11315 break;
11316
11317 case TARGET_OBJECT_AUXV:
11318 gdb_assert (annex == NULL);
11319 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
11320 xfered_len,
11321 &remote_protocol_packets[PACKET_qXfer_auxv]);
11322
11323 case TARGET_OBJECT_AVAILABLE_FEATURES:
11324 return remote_read_qxfer
11325 ("features", annex, readbuf, offset, len, xfered_len,
11326 &remote_protocol_packets[PACKET_qXfer_features]);
11327
11328 case TARGET_OBJECT_LIBRARIES:
11329 return remote_read_qxfer
11330 ("libraries", annex, readbuf, offset, len, xfered_len,
11331 &remote_protocol_packets[PACKET_qXfer_libraries]);
11332
11333 case TARGET_OBJECT_LIBRARIES_SVR4:
11334 return remote_read_qxfer
11335 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11336 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
11337
11338 case TARGET_OBJECT_MEMORY_MAP:
11339 gdb_assert (annex == NULL);
11340 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
11341 xfered_len,
11342 &remote_protocol_packets[PACKET_qXfer_memory_map]);
11343
11344 case TARGET_OBJECT_OSDATA:
11345 /* Should only get here if we're connected. */
11346 gdb_assert (rs->remote_desc);
11347 return remote_read_qxfer
11348 ("osdata", annex, readbuf, offset, len, xfered_len,
11349 &remote_protocol_packets[PACKET_qXfer_osdata]);
11350
11351 case TARGET_OBJECT_THREADS:
11352 gdb_assert (annex == NULL);
11353 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
11354 xfered_len,
11355 &remote_protocol_packets[PACKET_qXfer_threads]);
11356
11357 case TARGET_OBJECT_TRACEFRAME_INFO:
11358 gdb_assert (annex == NULL);
11359 return remote_read_qxfer
11360 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11361 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
11362
11363 case TARGET_OBJECT_FDPIC:
11364 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
11365 xfered_len,
11366 &remote_protocol_packets[PACKET_qXfer_fdpic]);
11367
11368 case TARGET_OBJECT_OPENVMS_UIB:
11369 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
11370 xfered_len,
11371 &remote_protocol_packets[PACKET_qXfer_uib]);
11372
11373 case TARGET_OBJECT_BTRACE:
11374 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
11375 xfered_len,
11376 &remote_protocol_packets[PACKET_qXfer_btrace]);
11377
11378 case TARGET_OBJECT_BTRACE_CONF:
11379 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
11380 len, xfered_len,
11381 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11382
11383 case TARGET_OBJECT_EXEC_FILE:
11384 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
11385 len, xfered_len,
11386 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11387
11388 default:
11389 return TARGET_XFER_E_IO;
11390 }
11391
11392 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11393 large enough let the caller deal with it. */
11394 if (len < get_remote_packet_size ())
11395 return TARGET_XFER_E_IO;
11396 len = get_remote_packet_size ();
11397
11398 /* Except for querying the minimum buffer size, target must be open. */
11399 if (!rs->remote_desc)
11400 error (_("remote query is only available after target open"));
11401
11402 gdb_assert (annex != NULL);
11403 gdb_assert (readbuf != NULL);
11404
11405 p2 = rs->buf.data ();
11406 *p2++ = 'q';
11407 *p2++ = query_type;
11408
11409 /* We used one buffer char for the remote protocol q command and
11410 another for the query type. As the remote protocol encapsulation
11411 uses 4 chars plus one extra in case we are debugging
11412 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11413 string. */
11414 i = 0;
11415 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11416 {
11417 /* Bad caller may have sent forbidden characters. */
11418 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11419 *p2++ = annex[i];
11420 i++;
11421 }
11422 *p2 = '\0';
11423 gdb_assert (annex[i] == '\0');
11424
11425 i = putpkt (rs->buf);
11426 if (i < 0)
11427 return TARGET_XFER_E_IO;
11428
11429 getpkt (&rs->buf, 0);
11430 strcpy ((char *) readbuf, rs->buf.data ());
11431
11432 *xfered_len = strlen ((char *) readbuf);
11433 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11434 }
11435
11436 /* Implementation of to_get_memory_xfer_limit. */
11437
11438 ULONGEST
11439 remote_target::get_memory_xfer_limit ()
11440 {
11441 return get_memory_write_packet_size ();
11442 }
11443
11444 int
11445 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11446 const gdb_byte *pattern, ULONGEST pattern_len,
11447 CORE_ADDR *found_addrp)
11448 {
11449 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11450 struct remote_state *rs = get_remote_state ();
11451 int max_size = get_memory_write_packet_size ();
11452 struct packet_config *packet =
11453 &remote_protocol_packets[PACKET_qSearch_memory];
11454 /* Number of packet bytes used to encode the pattern;
11455 this could be more than PATTERN_LEN due to escape characters. */
11456 int escaped_pattern_len;
11457 /* Amount of pattern that was encodable in the packet. */
11458 int used_pattern_len;
11459 int i;
11460 int found;
11461 ULONGEST found_addr;
11462
11463 auto read_memory = [=] (CORE_ADDR addr, gdb_byte *result, size_t len)
11464 {
11465 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11466 == len);
11467 };
11468
11469 /* Don't go to the target if we don't have to. This is done before
11470 checking packet_config_support to avoid the possibility that a
11471 success for this edge case means the facility works in
11472 general. */
11473 if (pattern_len > search_space_len)
11474 return 0;
11475 if (pattern_len == 0)
11476 {
11477 *found_addrp = start_addr;
11478 return 1;
11479 }
11480
11481 /* If we already know the packet isn't supported, fall back to the simple
11482 way of searching memory. */
11483
11484 if (packet_config_support (packet) == PACKET_DISABLE)
11485 {
11486 /* Target doesn't provided special support, fall back and use the
11487 standard support (copy memory and do the search here). */
11488 return simple_search_memory (read_memory, start_addr, search_space_len,
11489 pattern, pattern_len, found_addrp);
11490 }
11491
11492 /* Make sure the remote is pointing at the right process. */
11493 set_general_process ();
11494
11495 /* Insert header. */
11496 i = snprintf (rs->buf.data (), max_size,
11497 "qSearch:memory:%s;%s;",
11498 phex_nz (start_addr, addr_size),
11499 phex_nz (search_space_len, sizeof (search_space_len)));
11500 max_size -= (i + 1);
11501
11502 /* Escape as much data as fits into rs->buf. */
11503 escaped_pattern_len =
11504 remote_escape_output (pattern, pattern_len, 1,
11505 (gdb_byte *) rs->buf.data () + i,
11506 &used_pattern_len, max_size);
11507
11508 /* Bail if the pattern is too large. */
11509 if (used_pattern_len != pattern_len)
11510 error (_("Pattern is too large to transmit to remote target."));
11511
11512 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11513 || getpkt_sane (&rs->buf, 0) < 0
11514 || packet_ok (rs->buf, packet) != PACKET_OK)
11515 {
11516 /* The request may not have worked because the command is not
11517 supported. If so, fall back to the simple way. */
11518 if (packet_config_support (packet) == PACKET_DISABLE)
11519 {
11520 return simple_search_memory (read_memory, start_addr, search_space_len,
11521 pattern, pattern_len, found_addrp);
11522 }
11523 return -1;
11524 }
11525
11526 if (rs->buf[0] == '0')
11527 found = 0;
11528 else if (rs->buf[0] == '1')
11529 {
11530 found = 1;
11531 if (rs->buf[1] != ',')
11532 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11533 unpack_varlen_hex (&rs->buf[2], &found_addr);
11534 *found_addrp = found_addr;
11535 }
11536 else
11537 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11538
11539 return found;
11540 }
11541
11542 void
11543 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11544 {
11545 struct remote_state *rs = get_remote_state ();
11546 char *p = rs->buf.data ();
11547
11548 if (!rs->remote_desc)
11549 error (_("remote rcmd is only available after target open"));
11550
11551 /* Send a NULL command across as an empty command. */
11552 if (command == NULL)
11553 command = "";
11554
11555 /* The query prefix. */
11556 strcpy (rs->buf.data (), "qRcmd,");
11557 p = strchr (rs->buf.data (), '\0');
11558
11559 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11560 > get_remote_packet_size ())
11561 error (_("\"monitor\" command ``%s'' is too long."), command);
11562
11563 /* Encode the actual command. */
11564 bin2hex ((const gdb_byte *) command, p, strlen (command));
11565
11566 if (putpkt (rs->buf) < 0)
11567 error (_("Communication problem with target."));
11568
11569 /* get/display the response */
11570 while (1)
11571 {
11572 char *buf;
11573
11574 /* XXX - see also remote_get_noisy_reply(). */
11575 QUIT; /* Allow user to bail out with ^C. */
11576 rs->buf[0] = '\0';
11577 if (getpkt_sane (&rs->buf, 0) == -1)
11578 {
11579 /* Timeout. Continue to (try to) read responses.
11580 This is better than stopping with an error, assuming the stub
11581 is still executing the (long) monitor command.
11582 If needed, the user can interrupt gdb using C-c, obtaining
11583 an effect similar to stop on timeout. */
11584 continue;
11585 }
11586 buf = rs->buf.data ();
11587 if (buf[0] == '\0')
11588 error (_("Target does not support this command."));
11589 if (buf[0] == 'O' && buf[1] != 'K')
11590 {
11591 remote_console_output (buf + 1); /* 'O' message from stub. */
11592 continue;
11593 }
11594 if (strcmp (buf, "OK") == 0)
11595 break;
11596 if (strlen (buf) == 3 && buf[0] == 'E'
11597 && isdigit (buf[1]) && isdigit (buf[2]))
11598 {
11599 error (_("Protocol error with Rcmd"));
11600 }
11601 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11602 {
11603 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11604
11605 fputc_unfiltered (c, outbuf);
11606 }
11607 break;
11608 }
11609 }
11610
11611 std::vector<mem_region>
11612 remote_target::memory_map ()
11613 {
11614 std::vector<mem_region> result;
11615 gdb::optional<gdb::char_vector> text
11616 = target_read_stralloc (current_inferior ()->top_target (),
11617 TARGET_OBJECT_MEMORY_MAP, NULL);
11618
11619 if (text)
11620 result = parse_memory_map (text->data ());
11621
11622 return result;
11623 }
11624
11625 /* Set of callbacks used to implement the 'maint packet' command. */
11626
11627 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
11628 {
11629 /* Called before the packet is sent. BUF is the packet content before
11630 the protocol specific prefix, suffix, and escaping is added. */
11631
11632 void sending (gdb::array_view<const char> &buf) override
11633 {
11634 puts_filtered ("sending: ");
11635 print_packet (buf);
11636 puts_filtered ("\n");
11637 }
11638
11639 /* Called with BUF, the reply from the remote target. */
11640
11641 void received (gdb::array_view<const char> &buf) override
11642 {
11643 puts_filtered ("received: \"");
11644 print_packet (buf);
11645 puts_filtered ("\"\n");
11646 }
11647
11648 private:
11649
11650 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11651 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11652
11653 static void
11654 print_packet (gdb::array_view<const char> &buf)
11655 {
11656 string_file stb;
11657
11658 for (int i = 0; i < buf.size (); ++i)
11659 {
11660 gdb_byte c = buf[i];
11661 if (isprint (c))
11662 fputc_unfiltered (c, &stb);
11663 else
11664 fprintf_unfiltered (&stb, "\\x%02x", (unsigned char) c);
11665 }
11666
11667 puts_filtered (stb.string ().c_str ());
11668 }
11669 };
11670
11671 /* See remote.h. */
11672
11673 void
11674 send_remote_packet (gdb::array_view<const char> &buf,
11675 send_remote_packet_callbacks *callbacks)
11676 {
11677 if (buf.size () == 0 || buf.data ()[0] == '\0')
11678 error (_("a remote packet must not be empty"));
11679
11680 remote_target *remote = get_current_remote_target ();
11681 if (remote == nullptr)
11682 error (_("packets can only be sent to a remote target"));
11683
11684 callbacks->sending (buf);
11685
11686 remote->putpkt_binary (buf.data (), buf.size ());
11687 remote_state *rs = remote->get_remote_state ();
11688 int bytes = remote->getpkt_sane (&rs->buf, 0);
11689
11690 if (bytes < 0)
11691 error (_("error while fetching packet from remote target"));
11692
11693 gdb::array_view<const char> view (&rs->buf[0], bytes);
11694 callbacks->received (view);
11695 }
11696
11697 /* Entry point for the 'maint packet' command. */
11698
11699 static void
11700 cli_packet_command (const char *args, int from_tty)
11701 {
11702 cli_packet_command_callbacks cb;
11703 gdb::array_view<const char> view
11704 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11705 send_remote_packet (view, &cb);
11706 }
11707
11708 #if 0
11709 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11710
11711 static void display_thread_info (struct gdb_ext_thread_info *info);
11712
11713 static void threadset_test_cmd (char *cmd, int tty);
11714
11715 static void threadalive_test (char *cmd, int tty);
11716
11717 static void threadlist_test_cmd (char *cmd, int tty);
11718
11719 int get_and_display_threadinfo (threadref *ref);
11720
11721 static void threadinfo_test_cmd (char *cmd, int tty);
11722
11723 static int thread_display_step (threadref *ref, void *context);
11724
11725 static void threadlist_update_test_cmd (char *cmd, int tty);
11726
11727 static void init_remote_threadtests (void);
11728
11729 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11730
11731 static void
11732 threadset_test_cmd (const char *cmd, int tty)
11733 {
11734 int sample_thread = SAMPLE_THREAD;
11735
11736 printf_filtered (_("Remote threadset test\n"));
11737 set_general_thread (sample_thread);
11738 }
11739
11740
11741 static void
11742 threadalive_test (const char *cmd, int tty)
11743 {
11744 int sample_thread = SAMPLE_THREAD;
11745 int pid = inferior_ptid.pid ();
11746 ptid_t ptid = ptid_t (pid, sample_thread, 0);
11747
11748 if (remote_thread_alive (ptid))
11749 printf_filtered ("PASS: Thread alive test\n");
11750 else
11751 printf_filtered ("FAIL: Thread alive test\n");
11752 }
11753
11754 void output_threadid (char *title, threadref *ref);
11755
11756 void
11757 output_threadid (char *title, threadref *ref)
11758 {
11759 char hexid[20];
11760
11761 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
11762 hexid[16] = 0;
11763 printf_filtered ("%s %s\n", title, (&hexid[0]));
11764 }
11765
11766 static void
11767 threadlist_test_cmd (const char *cmd, int tty)
11768 {
11769 int startflag = 1;
11770 threadref nextthread;
11771 int done, result_count;
11772 threadref threadlist[3];
11773
11774 printf_filtered ("Remote Threadlist test\n");
11775 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11776 &result_count, &threadlist[0]))
11777 printf_filtered ("FAIL: threadlist test\n");
11778 else
11779 {
11780 threadref *scan = threadlist;
11781 threadref *limit = scan + result_count;
11782
11783 while (scan < limit)
11784 output_threadid (" thread ", scan++);
11785 }
11786 }
11787
11788 void
11789 display_thread_info (struct gdb_ext_thread_info *info)
11790 {
11791 output_threadid ("Threadid: ", &info->threadid);
11792 printf_filtered ("Name: %s\n ", info->shortname);
11793 printf_filtered ("State: %s\n", info->display);
11794 printf_filtered ("other: %s\n\n", info->more_display);
11795 }
11796
11797 int
11798 get_and_display_threadinfo (threadref *ref)
11799 {
11800 int result;
11801 int set;
11802 struct gdb_ext_thread_info threadinfo;
11803
11804 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11805 | TAG_MOREDISPLAY | TAG_DISPLAY;
11806 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11807 display_thread_info (&threadinfo);
11808 return result;
11809 }
11810
11811 static void
11812 threadinfo_test_cmd (const char *cmd, int tty)
11813 {
11814 int athread = SAMPLE_THREAD;
11815 threadref thread;
11816 int set;
11817
11818 int_to_threadref (&thread, athread);
11819 printf_filtered ("Remote Threadinfo test\n");
11820 if (!get_and_display_threadinfo (&thread))
11821 printf_filtered ("FAIL cannot get thread info\n");
11822 }
11823
11824 static int
11825 thread_display_step (threadref *ref, void *context)
11826 {
11827 /* output_threadid(" threadstep ",ref); *//* simple test */
11828 return get_and_display_threadinfo (ref);
11829 }
11830
11831 static void
11832 threadlist_update_test_cmd (const char *cmd, int tty)
11833 {
11834 printf_filtered ("Remote Threadlist update test\n");
11835 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11836 }
11837
11838 static void
11839 init_remote_threadtests (void)
11840 {
11841 add_com ("tlist", class_obscure, threadlist_test_cmd,
11842 _("Fetch and print the remote list of "
11843 "thread identifiers, one pkt only."));
11844 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11845 _("Fetch and display info about one thread."));
11846 add_com ("tset", class_obscure, threadset_test_cmd,
11847 _("Test setting to a different thread."));
11848 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11849 _("Iterate through updating all remote thread info."));
11850 add_com ("talive", class_obscure, threadalive_test,
11851 _("Remote thread alive test."));
11852 }
11853
11854 #endif /* 0 */
11855
11856 /* Convert a thread ID to a string. */
11857
11858 std::string
11859 remote_target::pid_to_str (ptid_t ptid)
11860 {
11861 struct remote_state *rs = get_remote_state ();
11862
11863 if (ptid == null_ptid)
11864 return normal_pid_to_str (ptid);
11865 else if (ptid.is_pid ())
11866 {
11867 /* Printing an inferior target id. */
11868
11869 /* When multi-process extensions are off, there's no way in the
11870 remote protocol to know the remote process id, if there's any
11871 at all. There's one exception --- when we're connected with
11872 target extended-remote, and we manually attached to a process
11873 with "attach PID". We don't record anywhere a flag that
11874 allows us to distinguish that case from the case of
11875 connecting with extended-remote and the stub already being
11876 attached to a process, and reporting yes to qAttached, hence
11877 no smart special casing here. */
11878 if (!remote_multi_process_p (rs))
11879 return "Remote target";
11880
11881 return normal_pid_to_str (ptid);
11882 }
11883 else
11884 {
11885 if (magic_null_ptid == ptid)
11886 return "Thread <main>";
11887 else if (remote_multi_process_p (rs))
11888 if (ptid.lwp () == 0)
11889 return normal_pid_to_str (ptid);
11890 else
11891 return string_printf ("Thread %d.%ld",
11892 ptid.pid (), ptid.lwp ());
11893 else
11894 return string_printf ("Thread %ld", ptid.lwp ());
11895 }
11896 }
11897
11898 /* Get the address of the thread local variable in OBJFILE which is
11899 stored at OFFSET within the thread local storage for thread PTID. */
11900
11901 CORE_ADDR
11902 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11903 CORE_ADDR offset)
11904 {
11905 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11906 {
11907 struct remote_state *rs = get_remote_state ();
11908 char *p = rs->buf.data ();
11909 char *endp = p + get_remote_packet_size ();
11910 enum packet_result result;
11911
11912 strcpy (p, "qGetTLSAddr:");
11913 p += strlen (p);
11914 p = write_ptid (p, endp, ptid);
11915 *p++ = ',';
11916 p += hexnumstr (p, offset);
11917 *p++ = ',';
11918 p += hexnumstr (p, lm);
11919 *p++ = '\0';
11920
11921 putpkt (rs->buf);
11922 getpkt (&rs->buf, 0);
11923 result = packet_ok (rs->buf,
11924 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11925 if (result == PACKET_OK)
11926 {
11927 ULONGEST addr;
11928
11929 unpack_varlen_hex (rs->buf.data (), &addr);
11930 return addr;
11931 }
11932 else if (result == PACKET_UNKNOWN)
11933 throw_error (TLS_GENERIC_ERROR,
11934 _("Remote target doesn't support qGetTLSAddr packet"));
11935 else
11936 throw_error (TLS_GENERIC_ERROR,
11937 _("Remote target failed to process qGetTLSAddr request"));
11938 }
11939 else
11940 throw_error (TLS_GENERIC_ERROR,
11941 _("TLS not supported or disabled on this target"));
11942 /* Not reached. */
11943 return 0;
11944 }
11945
11946 /* Provide thread local base, i.e. Thread Information Block address.
11947 Returns 1 if ptid is found and thread_local_base is non zero. */
11948
11949 bool
11950 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11951 {
11952 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11953 {
11954 struct remote_state *rs = get_remote_state ();
11955 char *p = rs->buf.data ();
11956 char *endp = p + get_remote_packet_size ();
11957 enum packet_result result;
11958
11959 strcpy (p, "qGetTIBAddr:");
11960 p += strlen (p);
11961 p = write_ptid (p, endp, ptid);
11962 *p++ = '\0';
11963
11964 putpkt (rs->buf);
11965 getpkt (&rs->buf, 0);
11966 result = packet_ok (rs->buf,
11967 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11968 if (result == PACKET_OK)
11969 {
11970 ULONGEST val;
11971 unpack_varlen_hex (rs->buf.data (), &val);
11972 if (addr)
11973 *addr = (CORE_ADDR) val;
11974 return true;
11975 }
11976 else if (result == PACKET_UNKNOWN)
11977 error (_("Remote target doesn't support qGetTIBAddr packet"));
11978 else
11979 error (_("Remote target failed to process qGetTIBAddr request"));
11980 }
11981 else
11982 error (_("qGetTIBAddr not supported or disabled on this target"));
11983 /* Not reached. */
11984 return false;
11985 }
11986
11987 /* Support for inferring a target description based on the current
11988 architecture and the size of a 'g' packet. While the 'g' packet
11989 can have any size (since optional registers can be left off the
11990 end), some sizes are easily recognizable given knowledge of the
11991 approximate architecture. */
11992
11993 struct remote_g_packet_guess
11994 {
11995 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
11996 : bytes (bytes_),
11997 tdesc (tdesc_)
11998 {
11999 }
12000
12001 int bytes;
12002 const struct target_desc *tdesc;
12003 };
12004
12005 struct remote_g_packet_data : public allocate_on_obstack
12006 {
12007 std::vector<remote_g_packet_guess> guesses;
12008 };
12009
12010 static struct gdbarch_data *remote_g_packet_data_handle;
12011
12012 static void *
12013 remote_g_packet_data_init (struct obstack *obstack)
12014 {
12015 return new (obstack) remote_g_packet_data;
12016 }
12017
12018 void
12019 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12020 const struct target_desc *tdesc)
12021 {
12022 struct remote_g_packet_data *data
12023 = ((struct remote_g_packet_data *)
12024 gdbarch_data (gdbarch, remote_g_packet_data_handle));
12025
12026 gdb_assert (tdesc != NULL);
12027
12028 for (const remote_g_packet_guess &guess : data->guesses)
12029 if (guess.bytes == bytes)
12030 internal_error (__FILE__, __LINE__,
12031 _("Duplicate g packet description added for size %d"),
12032 bytes);
12033
12034 data->guesses.emplace_back (bytes, tdesc);
12035 }
12036
12037 /* Return true if remote_read_description would do anything on this target
12038 and architecture, false otherwise. */
12039
12040 static bool
12041 remote_read_description_p (struct target_ops *target)
12042 {
12043 struct remote_g_packet_data *data
12044 = ((struct remote_g_packet_data *)
12045 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
12046
12047 return !data->guesses.empty ();
12048 }
12049
12050 const struct target_desc *
12051 remote_target::read_description ()
12052 {
12053 struct remote_g_packet_data *data
12054 = ((struct remote_g_packet_data *)
12055 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
12056
12057 /* Do not try this during initial connection, when we do not know
12058 whether there is a running but stopped thread. */
12059 if (!target_has_execution () || inferior_ptid == null_ptid)
12060 return beneath ()->read_description ();
12061
12062 if (!data->guesses.empty ())
12063 {
12064 int bytes = send_g_packet ();
12065
12066 for (const remote_g_packet_guess &guess : data->guesses)
12067 if (guess.bytes == bytes)
12068 return guess.tdesc;
12069
12070 /* We discard the g packet. A minor optimization would be to
12071 hold on to it, and fill the register cache once we have selected
12072 an architecture, but it's too tricky to do safely. */
12073 }
12074
12075 return beneath ()->read_description ();
12076 }
12077
12078 /* Remote file transfer support. This is host-initiated I/O, not
12079 target-initiated; for target-initiated, see remote-fileio.c. */
12080
12081 /* If *LEFT is at least the length of STRING, copy STRING to
12082 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12083 decrease *LEFT. Otherwise raise an error. */
12084
12085 static void
12086 remote_buffer_add_string (char **buffer, int *left, const char *string)
12087 {
12088 int len = strlen (string);
12089
12090 if (len > *left)
12091 error (_("Packet too long for target."));
12092
12093 memcpy (*buffer, string, len);
12094 *buffer += len;
12095 *left -= len;
12096
12097 /* NUL-terminate the buffer as a convenience, if there is
12098 room. */
12099 if (*left)
12100 **buffer = '\0';
12101 }
12102
12103 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12104 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12105 decrease *LEFT. Otherwise raise an error. */
12106
12107 static void
12108 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12109 int len)
12110 {
12111 if (2 * len > *left)
12112 error (_("Packet too long for target."));
12113
12114 bin2hex (bytes, *buffer, len);
12115 *buffer += 2 * len;
12116 *left -= 2 * len;
12117
12118 /* NUL-terminate the buffer as a convenience, if there is
12119 room. */
12120 if (*left)
12121 **buffer = '\0';
12122 }
12123
12124 /* If *LEFT is large enough, convert VALUE to hex and add it to
12125 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12126 decrease *LEFT. Otherwise raise an error. */
12127
12128 static void
12129 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12130 {
12131 int len = hexnumlen (value);
12132
12133 if (len > *left)
12134 error (_("Packet too long for target."));
12135
12136 hexnumstr (*buffer, value);
12137 *buffer += len;
12138 *left -= len;
12139
12140 /* NUL-terminate the buffer as a convenience, if there is
12141 room. */
12142 if (*left)
12143 **buffer = '\0';
12144 }
12145
12146 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12147 value, *REMOTE_ERRNO to the remote error number or zero if none
12148 was included, and *ATTACHMENT to point to the start of the annex
12149 if any. The length of the packet isn't needed here; there may
12150 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12151
12152 Return 0 if the packet could be parsed, -1 if it could not. If
12153 -1 is returned, the other variables may not be initialized. */
12154
12155 static int
12156 remote_hostio_parse_result (const char *buffer, int *retcode,
12157 int *remote_errno, const char **attachment)
12158 {
12159 char *p, *p2;
12160
12161 *remote_errno = 0;
12162 *attachment = NULL;
12163
12164 if (buffer[0] != 'F')
12165 return -1;
12166
12167 errno = 0;
12168 *retcode = strtol (&buffer[1], &p, 16);
12169 if (errno != 0 || p == &buffer[1])
12170 return -1;
12171
12172 /* Check for ",errno". */
12173 if (*p == ',')
12174 {
12175 errno = 0;
12176 *remote_errno = strtol (p + 1, &p2, 16);
12177 if (errno != 0 || p + 1 == p2)
12178 return -1;
12179 p = p2;
12180 }
12181
12182 /* Check for ";attachment". If there is no attachment, the
12183 packet should end here. */
12184 if (*p == ';')
12185 {
12186 *attachment = p + 1;
12187 return 0;
12188 }
12189 else if (*p == '\0')
12190 return 0;
12191 else
12192 return -1;
12193 }
12194
12195 /* Send a prepared I/O packet to the target and read its response.
12196 The prepared packet is in the global RS->BUF before this function
12197 is called, and the answer is there when we return.
12198
12199 COMMAND_BYTES is the length of the request to send, which may include
12200 binary data. WHICH_PACKET is the packet configuration to check
12201 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12202 is set to the error number and -1 is returned. Otherwise the value
12203 returned by the function is returned.
12204
12205 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12206 attachment is expected; an error will be reported if there's a
12207 mismatch. If one is found, *ATTACHMENT will be set to point into
12208 the packet buffer and *ATTACHMENT_LEN will be set to the
12209 attachment's length. */
12210
12211 int
12212 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12213 int *remote_errno, const char **attachment,
12214 int *attachment_len)
12215 {
12216 struct remote_state *rs = get_remote_state ();
12217 int ret, bytes_read;
12218 const char *attachment_tmp;
12219
12220 if (packet_support (which_packet) == PACKET_DISABLE)
12221 {
12222 *remote_errno = FILEIO_ENOSYS;
12223 return -1;
12224 }
12225
12226 putpkt_binary (rs->buf.data (), command_bytes);
12227 bytes_read = getpkt_sane (&rs->buf, 0);
12228
12229 /* If it timed out, something is wrong. Don't try to parse the
12230 buffer. */
12231 if (bytes_read < 0)
12232 {
12233 *remote_errno = FILEIO_EINVAL;
12234 return -1;
12235 }
12236
12237 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
12238 {
12239 case PACKET_ERROR:
12240 *remote_errno = FILEIO_EINVAL;
12241 return -1;
12242 case PACKET_UNKNOWN:
12243 *remote_errno = FILEIO_ENOSYS;
12244 return -1;
12245 case PACKET_OK:
12246 break;
12247 }
12248
12249 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12250 &attachment_tmp))
12251 {
12252 *remote_errno = FILEIO_EINVAL;
12253 return -1;
12254 }
12255
12256 /* Make sure we saw an attachment if and only if we expected one. */
12257 if ((attachment_tmp == NULL && attachment != NULL)
12258 || (attachment_tmp != NULL && attachment == NULL))
12259 {
12260 *remote_errno = FILEIO_EINVAL;
12261 return -1;
12262 }
12263
12264 /* If an attachment was found, it must point into the packet buffer;
12265 work out how many bytes there were. */
12266 if (attachment_tmp != NULL)
12267 {
12268 *attachment = attachment_tmp;
12269 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12270 }
12271
12272 return ret;
12273 }
12274
12275 /* See declaration.h. */
12276
12277 void
12278 readahead_cache::invalidate ()
12279 {
12280 this->fd = -1;
12281 }
12282
12283 /* See declaration.h. */
12284
12285 void
12286 readahead_cache::invalidate_fd (int fd)
12287 {
12288 if (this->fd == fd)
12289 this->fd = -1;
12290 }
12291
12292 /* Set the filesystem remote_hostio functions that take FILENAME
12293 arguments will use. Return 0 on success, or -1 if an error
12294 occurs (and set *REMOTE_ERRNO). */
12295
12296 int
12297 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12298 int *remote_errno)
12299 {
12300 struct remote_state *rs = get_remote_state ();
12301 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12302 char *p = rs->buf.data ();
12303 int left = get_remote_packet_size () - 1;
12304 char arg[9];
12305 int ret;
12306
12307 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12308 return 0;
12309
12310 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12311 return 0;
12312
12313 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12314
12315 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12316 remote_buffer_add_string (&p, &left, arg);
12317
12318 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12319 remote_errno, NULL, NULL);
12320
12321 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12322 return 0;
12323
12324 if (ret == 0)
12325 rs->fs_pid = required_pid;
12326
12327 return ret;
12328 }
12329
12330 /* Implementation of to_fileio_open. */
12331
12332 int
12333 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12334 int flags, int mode, int warn_if_slow,
12335 int *remote_errno)
12336 {
12337 struct remote_state *rs = get_remote_state ();
12338 char *p = rs->buf.data ();
12339 int left = get_remote_packet_size () - 1;
12340
12341 if (warn_if_slow)
12342 {
12343 static int warning_issued = 0;
12344
12345 printf_unfiltered (_("Reading %s from remote target...\n"),
12346 filename);
12347
12348 if (!warning_issued)
12349 {
12350 warning (_("File transfers from remote targets can be slow."
12351 " Use \"set sysroot\" to access files locally"
12352 " instead."));
12353 warning_issued = 1;
12354 }
12355 }
12356
12357 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12358 return -1;
12359
12360 remote_buffer_add_string (&p, &left, "vFile:open:");
12361
12362 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12363 strlen (filename));
12364 remote_buffer_add_string (&p, &left, ",");
12365
12366 remote_buffer_add_int (&p, &left, flags);
12367 remote_buffer_add_string (&p, &left, ",");
12368
12369 remote_buffer_add_int (&p, &left, mode);
12370
12371 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12372 remote_errno, NULL, NULL);
12373 }
12374
12375 int
12376 remote_target::fileio_open (struct inferior *inf, const char *filename,
12377 int flags, int mode, int warn_if_slow,
12378 int *remote_errno)
12379 {
12380 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12381 remote_errno);
12382 }
12383
12384 /* Implementation of to_fileio_pwrite. */
12385
12386 int
12387 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12388 ULONGEST offset, int *remote_errno)
12389 {
12390 struct remote_state *rs = get_remote_state ();
12391 char *p = rs->buf.data ();
12392 int left = get_remote_packet_size ();
12393 int out_len;
12394
12395 rs->readahead_cache.invalidate_fd (fd);
12396
12397 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12398
12399 remote_buffer_add_int (&p, &left, fd);
12400 remote_buffer_add_string (&p, &left, ",");
12401
12402 remote_buffer_add_int (&p, &left, offset);
12403 remote_buffer_add_string (&p, &left, ",");
12404
12405 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12406 (get_remote_packet_size ()
12407 - (p - rs->buf.data ())));
12408
12409 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12410 remote_errno, NULL, NULL);
12411 }
12412
12413 int
12414 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12415 ULONGEST offset, int *remote_errno)
12416 {
12417 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12418 }
12419
12420 /* Helper for the implementation of to_fileio_pread. Read the file
12421 from the remote side with vFile:pread. */
12422
12423 int
12424 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12425 ULONGEST offset, int *remote_errno)
12426 {
12427 struct remote_state *rs = get_remote_state ();
12428 char *p = rs->buf.data ();
12429 const char *attachment;
12430 int left = get_remote_packet_size ();
12431 int ret, attachment_len;
12432 int read_len;
12433
12434 remote_buffer_add_string (&p, &left, "vFile:pread:");
12435
12436 remote_buffer_add_int (&p, &left, fd);
12437 remote_buffer_add_string (&p, &left, ",");
12438
12439 remote_buffer_add_int (&p, &left, len);
12440 remote_buffer_add_string (&p, &left, ",");
12441
12442 remote_buffer_add_int (&p, &left, offset);
12443
12444 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12445 remote_errno, &attachment,
12446 &attachment_len);
12447
12448 if (ret < 0)
12449 return ret;
12450
12451 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12452 read_buf, len);
12453 if (read_len != ret)
12454 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12455
12456 return ret;
12457 }
12458
12459 /* See declaration.h. */
12460
12461 int
12462 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12463 ULONGEST offset)
12464 {
12465 if (this->fd == fd
12466 && this->offset <= offset
12467 && offset < this->offset + this->bufsize)
12468 {
12469 ULONGEST max = this->offset + this->bufsize;
12470
12471 if (offset + len > max)
12472 len = max - offset;
12473
12474 memcpy (read_buf, this->buf + offset - this->offset, len);
12475 return len;
12476 }
12477
12478 return 0;
12479 }
12480
12481 /* Implementation of to_fileio_pread. */
12482
12483 int
12484 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12485 ULONGEST offset, int *remote_errno)
12486 {
12487 int ret;
12488 struct remote_state *rs = get_remote_state ();
12489 readahead_cache *cache = &rs->readahead_cache;
12490
12491 ret = cache->pread (fd, read_buf, len, offset);
12492 if (ret > 0)
12493 {
12494 cache->hit_count++;
12495
12496 remote_debug_printf ("readahead cache hit %s",
12497 pulongest (cache->hit_count));
12498 return ret;
12499 }
12500
12501 cache->miss_count++;
12502
12503 remote_debug_printf ("readahead cache miss %s",
12504 pulongest (cache->miss_count));
12505
12506 cache->fd = fd;
12507 cache->offset = offset;
12508 cache->bufsize = get_remote_packet_size ();
12509 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12510
12511 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12512 cache->offset, remote_errno);
12513 if (ret <= 0)
12514 {
12515 cache->invalidate_fd (fd);
12516 return ret;
12517 }
12518
12519 cache->bufsize = ret;
12520 return cache->pread (fd, read_buf, len, offset);
12521 }
12522
12523 int
12524 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12525 ULONGEST offset, int *remote_errno)
12526 {
12527 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12528 }
12529
12530 /* Implementation of to_fileio_close. */
12531
12532 int
12533 remote_target::remote_hostio_close (int fd, int *remote_errno)
12534 {
12535 struct remote_state *rs = get_remote_state ();
12536 char *p = rs->buf.data ();
12537 int left = get_remote_packet_size () - 1;
12538
12539 rs->readahead_cache.invalidate_fd (fd);
12540
12541 remote_buffer_add_string (&p, &left, "vFile:close:");
12542
12543 remote_buffer_add_int (&p, &left, fd);
12544
12545 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12546 remote_errno, NULL, NULL);
12547 }
12548
12549 int
12550 remote_target::fileio_close (int fd, int *remote_errno)
12551 {
12552 return remote_hostio_close (fd, remote_errno);
12553 }
12554
12555 /* Implementation of to_fileio_unlink. */
12556
12557 int
12558 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12559 int *remote_errno)
12560 {
12561 struct remote_state *rs = get_remote_state ();
12562 char *p = rs->buf.data ();
12563 int left = get_remote_packet_size () - 1;
12564
12565 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12566 return -1;
12567
12568 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12569
12570 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12571 strlen (filename));
12572
12573 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12574 remote_errno, NULL, NULL);
12575 }
12576
12577 int
12578 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12579 int *remote_errno)
12580 {
12581 return remote_hostio_unlink (inf, filename, remote_errno);
12582 }
12583
12584 /* Implementation of to_fileio_readlink. */
12585
12586 gdb::optional<std::string>
12587 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12588 int *remote_errno)
12589 {
12590 struct remote_state *rs = get_remote_state ();
12591 char *p = rs->buf.data ();
12592 const char *attachment;
12593 int left = get_remote_packet_size ();
12594 int len, attachment_len;
12595 int read_len;
12596
12597 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12598 return {};
12599
12600 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12601
12602 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12603 strlen (filename));
12604
12605 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12606 remote_errno, &attachment,
12607 &attachment_len);
12608
12609 if (len < 0)
12610 return {};
12611
12612 std::string ret (len, '\0');
12613
12614 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12615 (gdb_byte *) &ret[0], len);
12616 if (read_len != len)
12617 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12618
12619 return ret;
12620 }
12621
12622 /* Implementation of to_fileio_fstat. */
12623
12624 int
12625 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12626 {
12627 struct remote_state *rs = get_remote_state ();
12628 char *p = rs->buf.data ();
12629 int left = get_remote_packet_size ();
12630 int attachment_len, ret;
12631 const char *attachment;
12632 struct fio_stat fst;
12633 int read_len;
12634
12635 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12636
12637 remote_buffer_add_int (&p, &left, fd);
12638
12639 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12640 remote_errno, &attachment,
12641 &attachment_len);
12642 if (ret < 0)
12643 {
12644 if (*remote_errno != FILEIO_ENOSYS)
12645 return ret;
12646
12647 /* Strictly we should return -1, ENOSYS here, but when
12648 "set sysroot remote:" was implemented in August 2008
12649 BFD's need for a stat function was sidestepped with
12650 this hack. This was not remedied until March 2015
12651 so we retain the previous behavior to avoid breaking
12652 compatibility.
12653
12654 Note that the memset is a March 2015 addition; older
12655 GDBs set st_size *and nothing else* so the structure
12656 would have garbage in all other fields. This might
12657 break something but retaining the previous behavior
12658 here would be just too wrong. */
12659
12660 memset (st, 0, sizeof (struct stat));
12661 st->st_size = INT_MAX;
12662 return 0;
12663 }
12664
12665 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12666 (gdb_byte *) &fst, sizeof (fst));
12667
12668 if (read_len != ret)
12669 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12670
12671 if (read_len != sizeof (fst))
12672 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12673 read_len, (int) sizeof (fst));
12674
12675 remote_fileio_to_host_stat (&fst, st);
12676
12677 return 0;
12678 }
12679
12680 /* Implementation of to_filesystem_is_local. */
12681
12682 bool
12683 remote_target::filesystem_is_local ()
12684 {
12685 /* Valgrind GDB presents itself as a remote target but works
12686 on the local filesystem: it does not implement remote get
12687 and users are not expected to set a sysroot. To handle
12688 this case we treat the remote filesystem as local if the
12689 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12690 does not support vFile:open. */
12691 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
12692 {
12693 enum packet_support ps = packet_support (PACKET_vFile_open);
12694
12695 if (ps == PACKET_SUPPORT_UNKNOWN)
12696 {
12697 int fd, remote_errno;
12698
12699 /* Try opening a file to probe support. The supplied
12700 filename is irrelevant, we only care about whether
12701 the stub recognizes the packet or not. */
12702 fd = remote_hostio_open (NULL, "just probing",
12703 FILEIO_O_RDONLY, 0700, 0,
12704 &remote_errno);
12705
12706 if (fd >= 0)
12707 remote_hostio_close (fd, &remote_errno);
12708
12709 ps = packet_support (PACKET_vFile_open);
12710 }
12711
12712 if (ps == PACKET_DISABLE)
12713 {
12714 static int warning_issued = 0;
12715
12716 if (!warning_issued)
12717 {
12718 warning (_("remote target does not support file"
12719 " transfer, attempting to access files"
12720 " from local filesystem."));
12721 warning_issued = 1;
12722 }
12723
12724 return true;
12725 }
12726 }
12727
12728 return false;
12729 }
12730
12731 static int
12732 remote_fileio_errno_to_host (int errnum)
12733 {
12734 switch (errnum)
12735 {
12736 case FILEIO_EPERM:
12737 return EPERM;
12738 case FILEIO_ENOENT:
12739 return ENOENT;
12740 case FILEIO_EINTR:
12741 return EINTR;
12742 case FILEIO_EIO:
12743 return EIO;
12744 case FILEIO_EBADF:
12745 return EBADF;
12746 case FILEIO_EACCES:
12747 return EACCES;
12748 case FILEIO_EFAULT:
12749 return EFAULT;
12750 case FILEIO_EBUSY:
12751 return EBUSY;
12752 case FILEIO_EEXIST:
12753 return EEXIST;
12754 case FILEIO_ENODEV:
12755 return ENODEV;
12756 case FILEIO_ENOTDIR:
12757 return ENOTDIR;
12758 case FILEIO_EISDIR:
12759 return EISDIR;
12760 case FILEIO_EINVAL:
12761 return EINVAL;
12762 case FILEIO_ENFILE:
12763 return ENFILE;
12764 case FILEIO_EMFILE:
12765 return EMFILE;
12766 case FILEIO_EFBIG:
12767 return EFBIG;
12768 case FILEIO_ENOSPC:
12769 return ENOSPC;
12770 case FILEIO_ESPIPE:
12771 return ESPIPE;
12772 case FILEIO_EROFS:
12773 return EROFS;
12774 case FILEIO_ENOSYS:
12775 return ENOSYS;
12776 case FILEIO_ENAMETOOLONG:
12777 return ENAMETOOLONG;
12778 }
12779 return -1;
12780 }
12781
12782 static char *
12783 remote_hostio_error (int errnum)
12784 {
12785 int host_error = remote_fileio_errno_to_host (errnum);
12786
12787 if (host_error == -1)
12788 error (_("Unknown remote I/O error %d"), errnum);
12789 else
12790 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12791 }
12792
12793 /* A RAII wrapper around a remote file descriptor. */
12794
12795 class scoped_remote_fd
12796 {
12797 public:
12798 scoped_remote_fd (remote_target *remote, int fd)
12799 : m_remote (remote), m_fd (fd)
12800 {
12801 }
12802
12803 ~scoped_remote_fd ()
12804 {
12805 if (m_fd != -1)
12806 {
12807 try
12808 {
12809 int remote_errno;
12810 m_remote->remote_hostio_close (m_fd, &remote_errno);
12811 }
12812 catch (...)
12813 {
12814 /* Swallow exception before it escapes the dtor. If
12815 something goes wrong, likely the connection is gone,
12816 and there's nothing else that can be done. */
12817 }
12818 }
12819 }
12820
12821 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12822
12823 /* Release ownership of the file descriptor, and return it. */
12824 ATTRIBUTE_UNUSED_RESULT int release () noexcept
12825 {
12826 int fd = m_fd;
12827 m_fd = -1;
12828 return fd;
12829 }
12830
12831 /* Return the owned file descriptor. */
12832 int get () const noexcept
12833 {
12834 return m_fd;
12835 }
12836
12837 private:
12838 /* The remote target. */
12839 remote_target *m_remote;
12840
12841 /* The owned remote I/O file descriptor. */
12842 int m_fd;
12843 };
12844
12845 void
12846 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12847 {
12848 remote_target *remote = get_current_remote_target ();
12849
12850 if (remote == nullptr)
12851 error (_("command can only be used with remote target"));
12852
12853 remote->remote_file_put (local_file, remote_file, from_tty);
12854 }
12855
12856 void
12857 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12858 int from_tty)
12859 {
12860 int retcode, remote_errno, bytes, io_size;
12861 int bytes_in_buffer;
12862 int saw_eof;
12863 ULONGEST offset;
12864
12865 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12866 if (file == NULL)
12867 perror_with_name (local_file);
12868
12869 scoped_remote_fd fd
12870 (this, remote_hostio_open (NULL,
12871 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12872 | FILEIO_O_TRUNC),
12873 0700, 0, &remote_errno));
12874 if (fd.get () == -1)
12875 remote_hostio_error (remote_errno);
12876
12877 /* Send up to this many bytes at once. They won't all fit in the
12878 remote packet limit, so we'll transfer slightly fewer. */
12879 io_size = get_remote_packet_size ();
12880 gdb::byte_vector buffer (io_size);
12881
12882 bytes_in_buffer = 0;
12883 saw_eof = 0;
12884 offset = 0;
12885 while (bytes_in_buffer || !saw_eof)
12886 {
12887 if (!saw_eof)
12888 {
12889 bytes = fread (buffer.data () + bytes_in_buffer, 1,
12890 io_size - bytes_in_buffer,
12891 file.get ());
12892 if (bytes == 0)
12893 {
12894 if (ferror (file.get ()))
12895 error (_("Error reading %s."), local_file);
12896 else
12897 {
12898 /* EOF. Unless there is something still in the
12899 buffer from the last iteration, we are done. */
12900 saw_eof = 1;
12901 if (bytes_in_buffer == 0)
12902 break;
12903 }
12904 }
12905 }
12906 else
12907 bytes = 0;
12908
12909 bytes += bytes_in_buffer;
12910 bytes_in_buffer = 0;
12911
12912 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12913 offset, &remote_errno);
12914
12915 if (retcode < 0)
12916 remote_hostio_error (remote_errno);
12917 else if (retcode == 0)
12918 error (_("Remote write of %d bytes returned 0!"), bytes);
12919 else if (retcode < bytes)
12920 {
12921 /* Short write. Save the rest of the read data for the next
12922 write. */
12923 bytes_in_buffer = bytes - retcode;
12924 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
12925 }
12926
12927 offset += retcode;
12928 }
12929
12930 if (remote_hostio_close (fd.release (), &remote_errno))
12931 remote_hostio_error (remote_errno);
12932
12933 if (from_tty)
12934 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12935 }
12936
12937 void
12938 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12939 {
12940 remote_target *remote = get_current_remote_target ();
12941
12942 if (remote == nullptr)
12943 error (_("command can only be used with remote target"));
12944
12945 remote->remote_file_get (remote_file, local_file, from_tty);
12946 }
12947
12948 void
12949 remote_target::remote_file_get (const char *remote_file, const char *local_file,
12950 int from_tty)
12951 {
12952 int remote_errno, bytes, io_size;
12953 ULONGEST offset;
12954
12955 scoped_remote_fd fd
12956 (this, remote_hostio_open (NULL,
12957 remote_file, FILEIO_O_RDONLY, 0, 0,
12958 &remote_errno));
12959 if (fd.get () == -1)
12960 remote_hostio_error (remote_errno);
12961
12962 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12963 if (file == NULL)
12964 perror_with_name (local_file);
12965
12966 /* Send up to this many bytes at once. They won't all fit in the
12967 remote packet limit, so we'll transfer slightly fewer. */
12968 io_size = get_remote_packet_size ();
12969 gdb::byte_vector buffer (io_size);
12970
12971 offset = 0;
12972 while (1)
12973 {
12974 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
12975 &remote_errno);
12976 if (bytes == 0)
12977 /* Success, but no bytes, means end-of-file. */
12978 break;
12979 if (bytes == -1)
12980 remote_hostio_error (remote_errno);
12981
12982 offset += bytes;
12983
12984 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
12985 if (bytes == 0)
12986 perror_with_name (local_file);
12987 }
12988
12989 if (remote_hostio_close (fd.release (), &remote_errno))
12990 remote_hostio_error (remote_errno);
12991
12992 if (from_tty)
12993 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12994 }
12995
12996 void
12997 remote_file_delete (const char *remote_file, int from_tty)
12998 {
12999 remote_target *remote = get_current_remote_target ();
13000
13001 if (remote == nullptr)
13002 error (_("command can only be used with remote target"));
13003
13004 remote->remote_file_delete (remote_file, from_tty);
13005 }
13006
13007 void
13008 remote_target::remote_file_delete (const char *remote_file, int from_tty)
13009 {
13010 int retcode, remote_errno;
13011
13012 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
13013 if (retcode == -1)
13014 remote_hostio_error (remote_errno);
13015
13016 if (from_tty)
13017 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
13018 }
13019
13020 static void
13021 remote_put_command (const char *args, int from_tty)
13022 {
13023 if (args == NULL)
13024 error_no_arg (_("file to put"));
13025
13026 gdb_argv argv (args);
13027 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13028 error (_("Invalid parameters to remote put"));
13029
13030 remote_file_put (argv[0], argv[1], from_tty);
13031 }
13032
13033 static void
13034 remote_get_command (const char *args, int from_tty)
13035 {
13036 if (args == NULL)
13037 error_no_arg (_("file to get"));
13038
13039 gdb_argv argv (args);
13040 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13041 error (_("Invalid parameters to remote get"));
13042
13043 remote_file_get (argv[0], argv[1], from_tty);
13044 }
13045
13046 static void
13047 remote_delete_command (const char *args, int from_tty)
13048 {
13049 if (args == NULL)
13050 error_no_arg (_("file to delete"));
13051
13052 gdb_argv argv (args);
13053 if (argv[0] == NULL || argv[1] != NULL)
13054 error (_("Invalid parameters to remote delete"));
13055
13056 remote_file_delete (argv[0], from_tty);
13057 }
13058
13059 bool
13060 remote_target::can_execute_reverse ()
13061 {
13062 if (packet_support (PACKET_bs) == PACKET_ENABLE
13063 || packet_support (PACKET_bc) == PACKET_ENABLE)
13064 return true;
13065 else
13066 return false;
13067 }
13068
13069 bool
13070 remote_target::supports_non_stop ()
13071 {
13072 return true;
13073 }
13074
13075 bool
13076 remote_target::supports_disable_randomization ()
13077 {
13078 /* Only supported in extended mode. */
13079 return false;
13080 }
13081
13082 bool
13083 remote_target::supports_multi_process ()
13084 {
13085 struct remote_state *rs = get_remote_state ();
13086
13087 return remote_multi_process_p (rs);
13088 }
13089
13090 static int
13091 remote_supports_cond_tracepoints ()
13092 {
13093 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
13094 }
13095
13096 bool
13097 remote_target::supports_evaluation_of_breakpoint_conditions ()
13098 {
13099 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
13100 }
13101
13102 static int
13103 remote_supports_fast_tracepoints ()
13104 {
13105 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13106 }
13107
13108 static int
13109 remote_supports_static_tracepoints ()
13110 {
13111 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13112 }
13113
13114 static int
13115 remote_supports_install_in_trace ()
13116 {
13117 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13118 }
13119
13120 bool
13121 remote_target::supports_enable_disable_tracepoint ()
13122 {
13123 return (packet_support (PACKET_EnableDisableTracepoints_feature)
13124 == PACKET_ENABLE);
13125 }
13126
13127 bool
13128 remote_target::supports_string_tracing ()
13129 {
13130 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13131 }
13132
13133 bool
13134 remote_target::can_run_breakpoint_commands ()
13135 {
13136 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13137 }
13138
13139 void
13140 remote_target::trace_init ()
13141 {
13142 struct remote_state *rs = get_remote_state ();
13143
13144 putpkt ("QTinit");
13145 remote_get_noisy_reply ();
13146 if (strcmp (rs->buf.data (), "OK") != 0)
13147 error (_("Target does not support this command."));
13148 }
13149
13150 /* Recursive routine to walk through command list including loops, and
13151 download packets for each command. */
13152
13153 void
13154 remote_target::remote_download_command_source (int num, ULONGEST addr,
13155 struct command_line *cmds)
13156 {
13157 struct remote_state *rs = get_remote_state ();
13158 struct command_line *cmd;
13159
13160 for (cmd = cmds; cmd; cmd = cmd->next)
13161 {
13162 QUIT; /* Allow user to bail out with ^C. */
13163 strcpy (rs->buf.data (), "QTDPsrc:");
13164 encode_source_string (num, addr, "cmd", cmd->line,
13165 rs->buf.data () + strlen (rs->buf.data ()),
13166 rs->buf.size () - strlen (rs->buf.data ()));
13167 putpkt (rs->buf);
13168 remote_get_noisy_reply ();
13169 if (strcmp (rs->buf.data (), "OK"))
13170 warning (_("Target does not support source download."));
13171
13172 if (cmd->control_type == while_control
13173 || cmd->control_type == while_stepping_control)
13174 {
13175 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13176
13177 QUIT; /* Allow user to bail out with ^C. */
13178 strcpy (rs->buf.data (), "QTDPsrc:");
13179 encode_source_string (num, addr, "cmd", "end",
13180 rs->buf.data () + strlen (rs->buf.data ()),
13181 rs->buf.size () - strlen (rs->buf.data ()));
13182 putpkt (rs->buf);
13183 remote_get_noisy_reply ();
13184 if (strcmp (rs->buf.data (), "OK"))
13185 warning (_("Target does not support source download."));
13186 }
13187 }
13188 }
13189
13190 void
13191 remote_target::download_tracepoint (struct bp_location *loc)
13192 {
13193 CORE_ADDR tpaddr;
13194 char addrbuf[40];
13195 std::vector<std::string> tdp_actions;
13196 std::vector<std::string> stepping_actions;
13197 char *pkt;
13198 struct breakpoint *b = loc->owner;
13199 struct tracepoint *t = (struct tracepoint *) b;
13200 struct remote_state *rs = get_remote_state ();
13201 int ret;
13202 const char *err_msg = _("Tracepoint packet too large for target.");
13203 size_t size_left;
13204
13205 /* We use a buffer other than rs->buf because we'll build strings
13206 across multiple statements, and other statements in between could
13207 modify rs->buf. */
13208 gdb::char_vector buf (get_remote_packet_size ());
13209
13210 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13211
13212 tpaddr = loc->address;
13213 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13214 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13215 b->number, addrbuf, /* address */
13216 (b->enable_state == bp_enabled ? 'E' : 'D'),
13217 t->step_count, t->pass_count);
13218
13219 if (ret < 0 || ret >= buf.size ())
13220 error ("%s", err_msg);
13221
13222 /* Fast tracepoints are mostly handled by the target, but we can
13223 tell the target how big of an instruction block should be moved
13224 around. */
13225 if (b->type == bp_fast_tracepoint)
13226 {
13227 /* Only test for support at download time; we may not know
13228 target capabilities at definition time. */
13229 if (remote_supports_fast_tracepoints ())
13230 {
13231 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13232 NULL))
13233 {
13234 size_left = buf.size () - strlen (buf.data ());
13235 ret = snprintf (buf.data () + strlen (buf.data ()),
13236 size_left, ":F%x",
13237 gdb_insn_length (loc->gdbarch, tpaddr));
13238
13239 if (ret < 0 || ret >= size_left)
13240 error ("%s", err_msg);
13241 }
13242 else
13243 /* If it passed validation at definition but fails now,
13244 something is very wrong. */
13245 internal_error (__FILE__, __LINE__,
13246 _("Fast tracepoint not "
13247 "valid during download"));
13248 }
13249 else
13250 /* Fast tracepoints are functionally identical to regular
13251 tracepoints, so don't take lack of support as a reason to
13252 give up on the trace run. */
13253 warning (_("Target does not support fast tracepoints, "
13254 "downloading %d as regular tracepoint"), b->number);
13255 }
13256 else if (b->type == bp_static_tracepoint)
13257 {
13258 /* Only test for support at download time; we may not know
13259 target capabilities at definition time. */
13260 if (remote_supports_static_tracepoints ())
13261 {
13262 struct static_tracepoint_marker marker;
13263
13264 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13265 {
13266 size_left = buf.size () - strlen (buf.data ());
13267 ret = snprintf (buf.data () + strlen (buf.data ()),
13268 size_left, ":S");
13269
13270 if (ret < 0 || ret >= size_left)
13271 error ("%s", err_msg);
13272 }
13273 else
13274 error (_("Static tracepoint not valid during download"));
13275 }
13276 else
13277 /* Fast tracepoints are functionally identical to regular
13278 tracepoints, so don't take lack of support as a reason
13279 to give up on the trace run. */
13280 error (_("Target does not support static tracepoints"));
13281 }
13282 /* If the tracepoint has a conditional, make it into an agent
13283 expression and append to the definition. */
13284 if (loc->cond)
13285 {
13286 /* Only test support at download time, we may not know target
13287 capabilities at definition time. */
13288 if (remote_supports_cond_tracepoints ())
13289 {
13290 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13291 loc->cond.get ());
13292
13293 size_left = buf.size () - strlen (buf.data ());
13294
13295 ret = snprintf (buf.data () + strlen (buf.data ()),
13296 size_left, ":X%x,", aexpr->len);
13297
13298 if (ret < 0 || ret >= size_left)
13299 error ("%s", err_msg);
13300
13301 size_left = buf.size () - strlen (buf.data ());
13302
13303 /* Two bytes to encode each aexpr byte, plus the terminating
13304 null byte. */
13305 if (aexpr->len * 2 + 1 > size_left)
13306 error ("%s", err_msg);
13307
13308 pkt = buf.data () + strlen (buf.data ());
13309
13310 for (int ndx = 0; ndx < aexpr->len; ++ndx)
13311 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13312 *pkt = '\0';
13313 }
13314 else
13315 warning (_("Target does not support conditional tracepoints, "
13316 "ignoring tp %d cond"), b->number);
13317 }
13318
13319 if (b->commands || !default_collect.empty ())
13320 {
13321 size_left = buf.size () - strlen (buf.data ());
13322
13323 ret = snprintf (buf.data () + strlen (buf.data ()),
13324 size_left, "-");
13325
13326 if (ret < 0 || ret >= size_left)
13327 error ("%s", err_msg);
13328 }
13329
13330 putpkt (buf.data ());
13331 remote_get_noisy_reply ();
13332 if (strcmp (rs->buf.data (), "OK"))
13333 error (_("Target does not support tracepoints."));
13334
13335 /* do_single_steps (t); */
13336 for (auto action_it = tdp_actions.begin ();
13337 action_it != tdp_actions.end (); action_it++)
13338 {
13339 QUIT; /* Allow user to bail out with ^C. */
13340
13341 bool has_more = ((action_it + 1) != tdp_actions.end ()
13342 || !stepping_actions.empty ());
13343
13344 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13345 b->number, addrbuf, /* address */
13346 action_it->c_str (),
13347 has_more ? '-' : 0);
13348
13349 if (ret < 0 || ret >= buf.size ())
13350 error ("%s", err_msg);
13351
13352 putpkt (buf.data ());
13353 remote_get_noisy_reply ();
13354 if (strcmp (rs->buf.data (), "OK"))
13355 error (_("Error on target while setting tracepoints."));
13356 }
13357
13358 for (auto action_it = stepping_actions.begin ();
13359 action_it != stepping_actions.end (); action_it++)
13360 {
13361 QUIT; /* Allow user to bail out with ^C. */
13362
13363 bool is_first = action_it == stepping_actions.begin ();
13364 bool has_more = (action_it + 1) != stepping_actions.end ();
13365
13366 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13367 b->number, addrbuf, /* address */
13368 is_first ? "S" : "",
13369 action_it->c_str (),
13370 has_more ? "-" : "");
13371
13372 if (ret < 0 || ret >= buf.size ())
13373 error ("%s", err_msg);
13374
13375 putpkt (buf.data ());
13376 remote_get_noisy_reply ();
13377 if (strcmp (rs->buf.data (), "OK"))
13378 error (_("Error on target while setting tracepoints."));
13379 }
13380
13381 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13382 {
13383 if (b->location != NULL)
13384 {
13385 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13386
13387 if (ret < 0 || ret >= buf.size ())
13388 error ("%s", err_msg);
13389
13390 encode_source_string (b->number, loc->address, "at",
13391 event_location_to_string (b->location.get ()),
13392 buf.data () + strlen (buf.data ()),
13393 buf.size () - strlen (buf.data ()));
13394 putpkt (buf.data ());
13395 remote_get_noisy_reply ();
13396 if (strcmp (rs->buf.data (), "OK"))
13397 warning (_("Target does not support source download."));
13398 }
13399 if (b->cond_string)
13400 {
13401 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13402
13403 if (ret < 0 || ret >= buf.size ())
13404 error ("%s", err_msg);
13405
13406 encode_source_string (b->number, loc->address,
13407 "cond", b->cond_string.get (),
13408 buf.data () + strlen (buf.data ()),
13409 buf.size () - strlen (buf.data ()));
13410 putpkt (buf.data ());
13411 remote_get_noisy_reply ();
13412 if (strcmp (rs->buf.data (), "OK"))
13413 warning (_("Target does not support source download."));
13414 }
13415 remote_download_command_source (b->number, loc->address,
13416 breakpoint_commands (b));
13417 }
13418 }
13419
13420 bool
13421 remote_target::can_download_tracepoint ()
13422 {
13423 struct remote_state *rs = get_remote_state ();
13424 struct trace_status *ts;
13425 int status;
13426
13427 /* Don't try to install tracepoints until we've relocated our
13428 symbols, and fetched and merged the target's tracepoint list with
13429 ours. */
13430 if (rs->starting_up)
13431 return false;
13432
13433 ts = current_trace_status ();
13434 status = get_trace_status (ts);
13435
13436 if (status == -1 || !ts->running_known || !ts->running)
13437 return false;
13438
13439 /* If we are in a tracing experiment, but remote stub doesn't support
13440 installing tracepoint in trace, we have to return. */
13441 if (!remote_supports_install_in_trace ())
13442 return false;
13443
13444 return true;
13445 }
13446
13447
13448 void
13449 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13450 {
13451 struct remote_state *rs = get_remote_state ();
13452 char *p;
13453
13454 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13455 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13456 tsv.builtin);
13457 p = rs->buf.data () + strlen (rs->buf.data ());
13458 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13459 >= get_remote_packet_size ())
13460 error (_("Trace state variable name too long for tsv definition packet"));
13461 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13462 *p++ = '\0';
13463 putpkt (rs->buf);
13464 remote_get_noisy_reply ();
13465 if (rs->buf[0] == '\0')
13466 error (_("Target does not support this command."));
13467 if (strcmp (rs->buf.data (), "OK") != 0)
13468 error (_("Error on target while downloading trace state variable."));
13469 }
13470
13471 void
13472 remote_target::enable_tracepoint (struct bp_location *location)
13473 {
13474 struct remote_state *rs = get_remote_state ();
13475
13476 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13477 location->owner->number,
13478 phex (location->address, sizeof (CORE_ADDR)));
13479 putpkt (rs->buf);
13480 remote_get_noisy_reply ();
13481 if (rs->buf[0] == '\0')
13482 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13483 if (strcmp (rs->buf.data (), "OK") != 0)
13484 error (_("Error on target while enabling tracepoint."));
13485 }
13486
13487 void
13488 remote_target::disable_tracepoint (struct bp_location *location)
13489 {
13490 struct remote_state *rs = get_remote_state ();
13491
13492 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13493 location->owner->number,
13494 phex (location->address, sizeof (CORE_ADDR)));
13495 putpkt (rs->buf);
13496 remote_get_noisy_reply ();
13497 if (rs->buf[0] == '\0')
13498 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13499 if (strcmp (rs->buf.data (), "OK") != 0)
13500 error (_("Error on target while disabling tracepoint."));
13501 }
13502
13503 void
13504 remote_target::trace_set_readonly_regions ()
13505 {
13506 asection *s;
13507 bfd_size_type size;
13508 bfd_vma vma;
13509 int anysecs = 0;
13510 int offset = 0;
13511
13512 if (!current_program_space->exec_bfd ())
13513 return; /* No information to give. */
13514
13515 struct remote_state *rs = get_remote_state ();
13516
13517 strcpy (rs->buf.data (), "QTro");
13518 offset = strlen (rs->buf.data ());
13519 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
13520 {
13521 char tmp1[40], tmp2[40];
13522 int sec_length;
13523
13524 if ((s->flags & SEC_LOAD) == 0 ||
13525 /* (s->flags & SEC_CODE) == 0 || */
13526 (s->flags & SEC_READONLY) == 0)
13527 continue;
13528
13529 anysecs = 1;
13530 vma = bfd_section_vma (s);
13531 size = bfd_section_size (s);
13532 sprintf_vma (tmp1, vma);
13533 sprintf_vma (tmp2, vma + size);
13534 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13535 if (offset + sec_length + 1 > rs->buf.size ())
13536 {
13537 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
13538 warning (_("\
13539 Too many sections for read-only sections definition packet."));
13540 break;
13541 }
13542 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13543 tmp1, tmp2);
13544 offset += sec_length;
13545 }
13546 if (anysecs)
13547 {
13548 putpkt (rs->buf);
13549 getpkt (&rs->buf, 0);
13550 }
13551 }
13552
13553 void
13554 remote_target::trace_start ()
13555 {
13556 struct remote_state *rs = get_remote_state ();
13557
13558 putpkt ("QTStart");
13559 remote_get_noisy_reply ();
13560 if (rs->buf[0] == '\0')
13561 error (_("Target does not support this command."));
13562 if (strcmp (rs->buf.data (), "OK") != 0)
13563 error (_("Bogus reply from target: %s"), rs->buf.data ());
13564 }
13565
13566 int
13567 remote_target::get_trace_status (struct trace_status *ts)
13568 {
13569 /* Initialize it just to avoid a GCC false warning. */
13570 char *p = NULL;
13571 enum packet_result result;
13572 struct remote_state *rs = get_remote_state ();
13573
13574 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13575 return -1;
13576
13577 /* FIXME we need to get register block size some other way. */
13578 trace_regblock_size
13579 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13580
13581 putpkt ("qTStatus");
13582
13583 try
13584 {
13585 p = remote_get_noisy_reply ();
13586 }
13587 catch (const gdb_exception_error &ex)
13588 {
13589 if (ex.error != TARGET_CLOSE_ERROR)
13590 {
13591 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13592 return -1;
13593 }
13594 throw;
13595 }
13596
13597 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13598
13599 /* If the remote target doesn't do tracing, flag it. */
13600 if (result == PACKET_UNKNOWN)
13601 return -1;
13602
13603 /* We're working with a live target. */
13604 ts->filename = NULL;
13605
13606 if (*p++ != 'T')
13607 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13608
13609 /* Function 'parse_trace_status' sets default value of each field of
13610 'ts' at first, so we don't have to do it here. */
13611 parse_trace_status (p, ts);
13612
13613 return ts->running;
13614 }
13615
13616 void
13617 remote_target::get_tracepoint_status (struct breakpoint *bp,
13618 struct uploaded_tp *utp)
13619 {
13620 struct remote_state *rs = get_remote_state ();
13621 char *reply;
13622 struct tracepoint *tp = (struct tracepoint *) bp;
13623 size_t size = get_remote_packet_size ();
13624
13625 if (tp)
13626 {
13627 tp->hit_count = 0;
13628 tp->traceframe_usage = 0;
13629 for (bp_location *loc : tp->locations ())
13630 {
13631 /* If the tracepoint was never downloaded, don't go asking for
13632 any status. */
13633 if (tp->number_on_target == 0)
13634 continue;
13635 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13636 phex_nz (loc->address, 0));
13637 putpkt (rs->buf);
13638 reply = remote_get_noisy_reply ();
13639 if (reply && *reply)
13640 {
13641 if (*reply == 'V')
13642 parse_tracepoint_status (reply + 1, bp, utp);
13643 }
13644 }
13645 }
13646 else if (utp)
13647 {
13648 utp->hit_count = 0;
13649 utp->traceframe_usage = 0;
13650 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13651 phex_nz (utp->addr, 0));
13652 putpkt (rs->buf);
13653 reply = remote_get_noisy_reply ();
13654 if (reply && *reply)
13655 {
13656 if (*reply == 'V')
13657 parse_tracepoint_status (reply + 1, bp, utp);
13658 }
13659 }
13660 }
13661
13662 void
13663 remote_target::trace_stop ()
13664 {
13665 struct remote_state *rs = get_remote_state ();
13666
13667 putpkt ("QTStop");
13668 remote_get_noisy_reply ();
13669 if (rs->buf[0] == '\0')
13670 error (_("Target does not support this command."));
13671 if (strcmp (rs->buf.data (), "OK") != 0)
13672 error (_("Bogus reply from target: %s"), rs->buf.data ());
13673 }
13674
13675 int
13676 remote_target::trace_find (enum trace_find_type type, int num,
13677 CORE_ADDR addr1, CORE_ADDR addr2,
13678 int *tpp)
13679 {
13680 struct remote_state *rs = get_remote_state ();
13681 char *endbuf = rs->buf.data () + get_remote_packet_size ();
13682 char *p, *reply;
13683 int target_frameno = -1, target_tracept = -1;
13684
13685 /* Lookups other than by absolute frame number depend on the current
13686 trace selected, so make sure it is correct on the remote end
13687 first. */
13688 if (type != tfind_number)
13689 set_remote_traceframe ();
13690
13691 p = rs->buf.data ();
13692 strcpy (p, "QTFrame:");
13693 p = strchr (p, '\0');
13694 switch (type)
13695 {
13696 case tfind_number:
13697 xsnprintf (p, endbuf - p, "%x", num);
13698 break;
13699 case tfind_pc:
13700 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13701 break;
13702 case tfind_tp:
13703 xsnprintf (p, endbuf - p, "tdp:%x", num);
13704 break;
13705 case tfind_range:
13706 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13707 phex_nz (addr2, 0));
13708 break;
13709 case tfind_outside:
13710 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13711 phex_nz (addr2, 0));
13712 break;
13713 default:
13714 error (_("Unknown trace find type %d"), type);
13715 }
13716
13717 putpkt (rs->buf);
13718 reply = remote_get_noisy_reply ();
13719 if (*reply == '\0')
13720 error (_("Target does not support this command."));
13721
13722 while (reply && *reply)
13723 switch (*reply)
13724 {
13725 case 'F':
13726 p = ++reply;
13727 target_frameno = (int) strtol (p, &reply, 16);
13728 if (reply == p)
13729 error (_("Unable to parse trace frame number"));
13730 /* Don't update our remote traceframe number cache on failure
13731 to select a remote traceframe. */
13732 if (target_frameno == -1)
13733 return -1;
13734 break;
13735 case 'T':
13736 p = ++reply;
13737 target_tracept = (int) strtol (p, &reply, 16);
13738 if (reply == p)
13739 error (_("Unable to parse tracepoint number"));
13740 break;
13741 case 'O': /* "OK"? */
13742 if (reply[1] == 'K' && reply[2] == '\0')
13743 reply += 2;
13744 else
13745 error (_("Bogus reply from target: %s"), reply);
13746 break;
13747 default:
13748 error (_("Bogus reply from target: %s"), reply);
13749 }
13750 if (tpp)
13751 *tpp = target_tracept;
13752
13753 rs->remote_traceframe_number = target_frameno;
13754 return target_frameno;
13755 }
13756
13757 bool
13758 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13759 {
13760 struct remote_state *rs = get_remote_state ();
13761 char *reply;
13762 ULONGEST uval;
13763
13764 set_remote_traceframe ();
13765
13766 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
13767 putpkt (rs->buf);
13768 reply = remote_get_noisy_reply ();
13769 if (reply && *reply)
13770 {
13771 if (*reply == 'V')
13772 {
13773 unpack_varlen_hex (reply + 1, &uval);
13774 *val = (LONGEST) uval;
13775 return true;
13776 }
13777 }
13778 return false;
13779 }
13780
13781 int
13782 remote_target::save_trace_data (const char *filename)
13783 {
13784 struct remote_state *rs = get_remote_state ();
13785 char *p, *reply;
13786
13787 p = rs->buf.data ();
13788 strcpy (p, "QTSave:");
13789 p += strlen (p);
13790 if ((p - rs->buf.data ()) + strlen (filename) * 2
13791 >= get_remote_packet_size ())
13792 error (_("Remote file name too long for trace save packet"));
13793 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13794 *p++ = '\0';
13795 putpkt (rs->buf);
13796 reply = remote_get_noisy_reply ();
13797 if (*reply == '\0')
13798 error (_("Target does not support this command."));
13799 if (strcmp (reply, "OK") != 0)
13800 error (_("Bogus reply from target: %s"), reply);
13801 return 0;
13802 }
13803
13804 /* This is basically a memory transfer, but needs to be its own packet
13805 because we don't know how the target actually organizes its trace
13806 memory, plus we want to be able to ask for as much as possible, but
13807 not be unhappy if we don't get as much as we ask for. */
13808
13809 LONGEST
13810 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13811 {
13812 struct remote_state *rs = get_remote_state ();
13813 char *reply;
13814 char *p;
13815 int rslt;
13816
13817 p = rs->buf.data ();
13818 strcpy (p, "qTBuffer:");
13819 p += strlen (p);
13820 p += hexnumstr (p, offset);
13821 *p++ = ',';
13822 p += hexnumstr (p, len);
13823 *p++ = '\0';
13824
13825 putpkt (rs->buf);
13826 reply = remote_get_noisy_reply ();
13827 if (reply && *reply)
13828 {
13829 /* 'l' by itself means we're at the end of the buffer and
13830 there is nothing more to get. */
13831 if (*reply == 'l')
13832 return 0;
13833
13834 /* Convert the reply into binary. Limit the number of bytes to
13835 convert according to our passed-in buffer size, rather than
13836 what was returned in the packet; if the target is
13837 unexpectedly generous and gives us a bigger reply than we
13838 asked for, we don't want to crash. */
13839 rslt = hex2bin (reply, buf, len);
13840 return rslt;
13841 }
13842
13843 /* Something went wrong, flag as an error. */
13844 return -1;
13845 }
13846
13847 void
13848 remote_target::set_disconnected_tracing (int val)
13849 {
13850 struct remote_state *rs = get_remote_state ();
13851
13852 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13853 {
13854 char *reply;
13855
13856 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13857 "QTDisconnected:%x", val);
13858 putpkt (rs->buf);
13859 reply = remote_get_noisy_reply ();
13860 if (*reply == '\0')
13861 error (_("Target does not support this command."));
13862 if (strcmp (reply, "OK") != 0)
13863 error (_("Bogus reply from target: %s"), reply);
13864 }
13865 else if (val)
13866 warning (_("Target does not support disconnected tracing."));
13867 }
13868
13869 int
13870 remote_target::core_of_thread (ptid_t ptid)
13871 {
13872 thread_info *info = find_thread_ptid (this, ptid);
13873
13874 if (info != NULL && info->priv != NULL)
13875 return get_remote_thread_info (info)->core;
13876
13877 return -1;
13878 }
13879
13880 void
13881 remote_target::set_circular_trace_buffer (int val)
13882 {
13883 struct remote_state *rs = get_remote_state ();
13884 char *reply;
13885
13886 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13887 "QTBuffer:circular:%x", val);
13888 putpkt (rs->buf);
13889 reply = remote_get_noisy_reply ();
13890 if (*reply == '\0')
13891 error (_("Target does not support this command."));
13892 if (strcmp (reply, "OK") != 0)
13893 error (_("Bogus reply from target: %s"), reply);
13894 }
13895
13896 traceframe_info_up
13897 remote_target::traceframe_info ()
13898 {
13899 gdb::optional<gdb::char_vector> text
13900 = target_read_stralloc (current_inferior ()->top_target (),
13901 TARGET_OBJECT_TRACEFRAME_INFO,
13902 NULL);
13903 if (text)
13904 return parse_traceframe_info (text->data ());
13905
13906 return NULL;
13907 }
13908
13909 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13910 instruction on which a fast tracepoint may be placed. Returns -1
13911 if the packet is not supported, and 0 if the minimum instruction
13912 length is unknown. */
13913
13914 int
13915 remote_target::get_min_fast_tracepoint_insn_len ()
13916 {
13917 struct remote_state *rs = get_remote_state ();
13918 char *reply;
13919
13920 /* If we're not debugging a process yet, the IPA can't be
13921 loaded. */
13922 if (!target_has_execution ())
13923 return 0;
13924
13925 /* Make sure the remote is pointing at the right process. */
13926 set_general_process ();
13927
13928 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
13929 putpkt (rs->buf);
13930 reply = remote_get_noisy_reply ();
13931 if (*reply == '\0')
13932 return -1;
13933 else
13934 {
13935 ULONGEST min_insn_len;
13936
13937 unpack_varlen_hex (reply, &min_insn_len);
13938
13939 return (int) min_insn_len;
13940 }
13941 }
13942
13943 void
13944 remote_target::set_trace_buffer_size (LONGEST val)
13945 {
13946 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13947 {
13948 struct remote_state *rs = get_remote_state ();
13949 char *buf = rs->buf.data ();
13950 char *endbuf = buf + get_remote_packet_size ();
13951 enum packet_result result;
13952
13953 gdb_assert (val >= 0 || val == -1);
13954 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13955 /* Send -1 as literal "-1" to avoid host size dependency. */
13956 if (val < 0)
13957 {
13958 *buf++ = '-';
13959 buf += hexnumstr (buf, (ULONGEST) -val);
13960 }
13961 else
13962 buf += hexnumstr (buf, (ULONGEST) val);
13963
13964 putpkt (rs->buf);
13965 remote_get_noisy_reply ();
13966 result = packet_ok (rs->buf,
13967 &remote_protocol_packets[PACKET_QTBuffer_size]);
13968
13969 if (result != PACKET_OK)
13970 warning (_("Bogus reply from target: %s"), rs->buf.data ());
13971 }
13972 }
13973
13974 bool
13975 remote_target::set_trace_notes (const char *user, const char *notes,
13976 const char *stop_notes)
13977 {
13978 struct remote_state *rs = get_remote_state ();
13979 char *reply;
13980 char *buf = rs->buf.data ();
13981 char *endbuf = buf + get_remote_packet_size ();
13982 int nbytes;
13983
13984 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13985 if (user)
13986 {
13987 buf += xsnprintf (buf, endbuf - buf, "user:");
13988 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13989 buf += 2 * nbytes;
13990 *buf++ = ';';
13991 }
13992 if (notes)
13993 {
13994 buf += xsnprintf (buf, endbuf - buf, "notes:");
13995 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13996 buf += 2 * nbytes;
13997 *buf++ = ';';
13998 }
13999 if (stop_notes)
14000 {
14001 buf += xsnprintf (buf, endbuf - buf, "tstop:");
14002 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
14003 buf += 2 * nbytes;
14004 *buf++ = ';';
14005 }
14006 /* Ensure the buffer is terminated. */
14007 *buf = '\0';
14008
14009 putpkt (rs->buf);
14010 reply = remote_get_noisy_reply ();
14011 if (*reply == '\0')
14012 return false;
14013
14014 if (strcmp (reply, "OK") != 0)
14015 error (_("Bogus reply from target: %s"), reply);
14016
14017 return true;
14018 }
14019
14020 bool
14021 remote_target::use_agent (bool use)
14022 {
14023 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
14024 {
14025 struct remote_state *rs = get_remote_state ();
14026
14027 /* If the stub supports QAgent. */
14028 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
14029 putpkt (rs->buf);
14030 getpkt (&rs->buf, 0);
14031
14032 if (strcmp (rs->buf.data (), "OK") == 0)
14033 {
14034 ::use_agent = use;
14035 return true;
14036 }
14037 }
14038
14039 return false;
14040 }
14041
14042 bool
14043 remote_target::can_use_agent ()
14044 {
14045 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
14046 }
14047
14048 struct btrace_target_info
14049 {
14050 /* The ptid of the traced thread. */
14051 ptid_t ptid;
14052
14053 /* The obtained branch trace configuration. */
14054 struct btrace_config conf;
14055 };
14056
14057 /* Reset our idea of our target's btrace configuration. */
14058
14059 static void
14060 remote_btrace_reset (remote_state *rs)
14061 {
14062 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14063 }
14064
14065 /* Synchronize the configuration with the target. */
14066
14067 void
14068 remote_target::btrace_sync_conf (const btrace_config *conf)
14069 {
14070 struct packet_config *packet;
14071 struct remote_state *rs;
14072 char *buf, *pos, *endbuf;
14073
14074 rs = get_remote_state ();
14075 buf = rs->buf.data ();
14076 endbuf = buf + get_remote_packet_size ();
14077
14078 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
14079 if (packet_config_support (packet) == PACKET_ENABLE
14080 && conf->bts.size != rs->btrace_config.bts.size)
14081 {
14082 pos = buf;
14083 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
14084 conf->bts.size);
14085
14086 putpkt (buf);
14087 getpkt (&rs->buf, 0);
14088
14089 if (packet_ok (buf, packet) == PACKET_ERROR)
14090 {
14091 if (buf[0] == 'E' && buf[1] == '.')
14092 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14093 else
14094 error (_("Failed to configure the BTS buffer size."));
14095 }
14096
14097 rs->btrace_config.bts.size = conf->bts.size;
14098 }
14099
14100 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
14101 if (packet_config_support (packet) == PACKET_ENABLE
14102 && conf->pt.size != rs->btrace_config.pt.size)
14103 {
14104 pos = buf;
14105 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
14106 conf->pt.size);
14107
14108 putpkt (buf);
14109 getpkt (&rs->buf, 0);
14110
14111 if (packet_ok (buf, packet) == PACKET_ERROR)
14112 {
14113 if (buf[0] == 'E' && buf[1] == '.')
14114 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14115 else
14116 error (_("Failed to configure the trace buffer size."));
14117 }
14118
14119 rs->btrace_config.pt.size = conf->pt.size;
14120 }
14121 }
14122
14123 /* Read the current thread's btrace configuration from the target and
14124 store it into CONF. */
14125
14126 static void
14127 btrace_read_config (struct btrace_config *conf)
14128 {
14129 gdb::optional<gdb::char_vector> xml
14130 = target_read_stralloc (current_inferior ()->top_target (),
14131 TARGET_OBJECT_BTRACE_CONF, "");
14132 if (xml)
14133 parse_xml_btrace_conf (conf, xml->data ());
14134 }
14135
14136 /* Maybe reopen target btrace. */
14137
14138 void
14139 remote_target::remote_btrace_maybe_reopen ()
14140 {
14141 struct remote_state *rs = get_remote_state ();
14142 int btrace_target_pushed = 0;
14143 #if !defined (HAVE_LIBIPT)
14144 int warned = 0;
14145 #endif
14146
14147 /* Don't bother walking the entirety of the remote thread list when
14148 we know the feature isn't supported by the remote. */
14149 if (packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14150 return;
14151
14152 scoped_restore_current_thread restore_thread;
14153
14154 for (thread_info *tp : all_non_exited_threads (this))
14155 {
14156 set_general_thread (tp->ptid);
14157
14158 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14159 btrace_read_config (&rs->btrace_config);
14160
14161 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14162 continue;
14163
14164 #if !defined (HAVE_LIBIPT)
14165 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14166 {
14167 if (!warned)
14168 {
14169 warned = 1;
14170 warning (_("Target is recording using Intel Processor Trace "
14171 "but support was disabled at compile time."));
14172 }
14173
14174 continue;
14175 }
14176 #endif /* !defined (HAVE_LIBIPT) */
14177
14178 /* Push target, once, but before anything else happens. This way our
14179 changes to the threads will be cleaned up by unpushing the target
14180 in case btrace_read_config () throws. */
14181 if (!btrace_target_pushed)
14182 {
14183 btrace_target_pushed = 1;
14184 record_btrace_push_target ();
14185 printf_filtered (_("Target is recording using %s.\n"),
14186 btrace_format_string (rs->btrace_config.format));
14187 }
14188
14189 tp->btrace.target = XCNEW (struct btrace_target_info);
14190 tp->btrace.target->ptid = tp->ptid;
14191 tp->btrace.target->conf = rs->btrace_config;
14192 }
14193 }
14194
14195 /* Enable branch tracing. */
14196
14197 struct btrace_target_info *
14198 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
14199 {
14200 struct btrace_target_info *tinfo = NULL;
14201 struct packet_config *packet = NULL;
14202 struct remote_state *rs = get_remote_state ();
14203 char *buf = rs->buf.data ();
14204 char *endbuf = buf + get_remote_packet_size ();
14205
14206 switch (conf->format)
14207 {
14208 case BTRACE_FORMAT_BTS:
14209 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
14210 break;
14211
14212 case BTRACE_FORMAT_PT:
14213 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
14214 break;
14215 }
14216
14217 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14218 error (_("Target does not support branch tracing."));
14219
14220 btrace_sync_conf (conf);
14221
14222 set_general_thread (ptid);
14223
14224 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14225 putpkt (rs->buf);
14226 getpkt (&rs->buf, 0);
14227
14228 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14229 {
14230 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14231 error (_("Could not enable branch tracing for %s: %s"),
14232 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14233 else
14234 error (_("Could not enable branch tracing for %s."),
14235 target_pid_to_str (ptid).c_str ());
14236 }
14237
14238 tinfo = XCNEW (struct btrace_target_info);
14239 tinfo->ptid = ptid;
14240
14241 /* If we fail to read the configuration, we lose some information, but the
14242 tracing itself is not impacted. */
14243 try
14244 {
14245 btrace_read_config (&tinfo->conf);
14246 }
14247 catch (const gdb_exception_error &err)
14248 {
14249 if (err.message != NULL)
14250 warning ("%s", err.what ());
14251 }
14252
14253 return tinfo;
14254 }
14255
14256 /* Disable branch tracing. */
14257
14258 void
14259 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14260 {
14261 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
14262 struct remote_state *rs = get_remote_state ();
14263 char *buf = rs->buf.data ();
14264 char *endbuf = buf + get_remote_packet_size ();
14265
14266 if (packet_config_support (packet) != PACKET_ENABLE)
14267 error (_("Target does not support branch tracing."));
14268
14269 set_general_thread (tinfo->ptid);
14270
14271 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14272 putpkt (rs->buf);
14273 getpkt (&rs->buf, 0);
14274
14275 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14276 {
14277 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14278 error (_("Could not disable branch tracing for %s: %s"),
14279 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14280 else
14281 error (_("Could not disable branch tracing for %s."),
14282 target_pid_to_str (tinfo->ptid).c_str ());
14283 }
14284
14285 xfree (tinfo);
14286 }
14287
14288 /* Teardown branch tracing. */
14289
14290 void
14291 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14292 {
14293 /* We must not talk to the target during teardown. */
14294 xfree (tinfo);
14295 }
14296
14297 /* Read the branch trace. */
14298
14299 enum btrace_error
14300 remote_target::read_btrace (struct btrace_data *btrace,
14301 struct btrace_target_info *tinfo,
14302 enum btrace_read_type type)
14303 {
14304 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
14305 const char *annex;
14306
14307 if (packet_config_support (packet) != PACKET_ENABLE)
14308 error (_("Target does not support branch tracing."));
14309
14310 #if !defined(HAVE_LIBEXPAT)
14311 error (_("Cannot process branch tracing result. XML parsing not supported."));
14312 #endif
14313
14314 switch (type)
14315 {
14316 case BTRACE_READ_ALL:
14317 annex = "all";
14318 break;
14319 case BTRACE_READ_NEW:
14320 annex = "new";
14321 break;
14322 case BTRACE_READ_DELTA:
14323 annex = "delta";
14324 break;
14325 default:
14326 internal_error (__FILE__, __LINE__,
14327 _("Bad branch tracing read type: %u."),
14328 (unsigned int) type);
14329 }
14330
14331 gdb::optional<gdb::char_vector> xml
14332 = target_read_stralloc (current_inferior ()->top_target (),
14333 TARGET_OBJECT_BTRACE, annex);
14334 if (!xml)
14335 return BTRACE_ERR_UNKNOWN;
14336
14337 parse_xml_btrace (btrace, xml->data ());
14338
14339 return BTRACE_ERR_NONE;
14340 }
14341
14342 const struct btrace_config *
14343 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14344 {
14345 return &tinfo->conf;
14346 }
14347
14348 bool
14349 remote_target::augmented_libraries_svr4_read ()
14350 {
14351 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
14352 == PACKET_ENABLE);
14353 }
14354
14355 /* Implementation of to_load. */
14356
14357 void
14358 remote_target::load (const char *name, int from_tty)
14359 {
14360 generic_load (name, from_tty);
14361 }
14362
14363 /* Accepts an integer PID; returns a string representing a file that
14364 can be opened on the remote side to get the symbols for the child
14365 process. Returns NULL if the operation is not supported. */
14366
14367 char *
14368 remote_target::pid_to_exec_file (int pid)
14369 {
14370 static gdb::optional<gdb::char_vector> filename;
14371 char *annex = NULL;
14372
14373 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14374 return NULL;
14375
14376 inferior *inf = find_inferior_pid (this, pid);
14377 if (inf == NULL)
14378 internal_error (__FILE__, __LINE__,
14379 _("not currently attached to process %d"), pid);
14380
14381 if (!inf->fake_pid_p)
14382 {
14383 const int annex_size = 9;
14384
14385 annex = (char *) alloca (annex_size);
14386 xsnprintf (annex, annex_size, "%x", pid);
14387 }
14388
14389 filename = target_read_stralloc (current_inferior ()->top_target (),
14390 TARGET_OBJECT_EXEC_FILE, annex);
14391
14392 return filename ? filename->data () : nullptr;
14393 }
14394
14395 /* Implement the to_can_do_single_step target_ops method. */
14396
14397 int
14398 remote_target::can_do_single_step ()
14399 {
14400 /* We can only tell whether target supports single step or not by
14401 supported s and S vCont actions if the stub supports vContSupported
14402 feature. If the stub doesn't support vContSupported feature,
14403 we have conservatively to think target doesn't supports single
14404 step. */
14405 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14406 {
14407 struct remote_state *rs = get_remote_state ();
14408
14409 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14410 remote_vcont_probe ();
14411
14412 return rs->supports_vCont.s && rs->supports_vCont.S;
14413 }
14414 else
14415 return 0;
14416 }
14417
14418 /* Implementation of the to_execution_direction method for the remote
14419 target. */
14420
14421 enum exec_direction_kind
14422 remote_target::execution_direction ()
14423 {
14424 struct remote_state *rs = get_remote_state ();
14425
14426 return rs->last_resume_exec_dir;
14427 }
14428
14429 /* Return pointer to the thread_info struct which corresponds to
14430 THREAD_HANDLE (having length HANDLE_LEN). */
14431
14432 thread_info *
14433 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14434 int handle_len,
14435 inferior *inf)
14436 {
14437 for (thread_info *tp : all_non_exited_threads (this))
14438 {
14439 remote_thread_info *priv = get_remote_thread_info (tp);
14440
14441 if (tp->inf == inf && priv != NULL)
14442 {
14443 if (handle_len != priv->thread_handle.size ())
14444 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14445 handle_len, priv->thread_handle.size ());
14446 if (memcmp (thread_handle, priv->thread_handle.data (),
14447 handle_len) == 0)
14448 return tp;
14449 }
14450 }
14451
14452 return NULL;
14453 }
14454
14455 gdb::byte_vector
14456 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14457 {
14458 remote_thread_info *priv = get_remote_thread_info (tp);
14459 return priv->thread_handle;
14460 }
14461
14462 bool
14463 remote_target::can_async_p ()
14464 {
14465 /* This flag should be checked in the common target.c code. */
14466 gdb_assert (target_async_permitted);
14467
14468 /* We're async whenever the serial device can. */
14469 struct remote_state *rs = get_remote_state ();
14470 return serial_can_async_p (rs->remote_desc);
14471 }
14472
14473 bool
14474 remote_target::is_async_p ()
14475 {
14476 /* We're async whenever the serial device is. */
14477 struct remote_state *rs = get_remote_state ();
14478 return serial_is_async_p (rs->remote_desc);
14479 }
14480
14481 /* Pass the SERIAL event on and up to the client. One day this code
14482 will be able to delay notifying the client of an event until the
14483 point where an entire packet has been received. */
14484
14485 static serial_event_ftype remote_async_serial_handler;
14486
14487 static void
14488 remote_async_serial_handler (struct serial *scb, void *context)
14489 {
14490 /* Don't propogate error information up to the client. Instead let
14491 the client find out about the error by querying the target. */
14492 inferior_event_handler (INF_REG_EVENT);
14493 }
14494
14495 static void
14496 remote_async_inferior_event_handler (gdb_client_data data)
14497 {
14498 inferior_event_handler (INF_REG_EVENT);
14499 }
14500
14501 int
14502 remote_target::async_wait_fd ()
14503 {
14504 struct remote_state *rs = get_remote_state ();
14505 return rs->remote_desc->fd;
14506 }
14507
14508 void
14509 remote_target::async (int enable)
14510 {
14511 struct remote_state *rs = get_remote_state ();
14512
14513 if (enable)
14514 {
14515 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14516
14517 /* If there are pending events in the stop reply queue tell the
14518 event loop to process them. */
14519 if (!rs->stop_reply_queue.empty ())
14520 mark_async_event_handler (rs->remote_async_inferior_event_token);
14521 /* For simplicity, below we clear the pending events token
14522 without remembering whether it is marked, so here we always
14523 mark it. If there's actually no pending notification to
14524 process, this ends up being a no-op (other than a spurious
14525 event-loop wakeup). */
14526 if (target_is_non_stop_p ())
14527 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14528 }
14529 else
14530 {
14531 serial_async (rs->remote_desc, NULL, NULL);
14532 /* If the core is disabling async, it doesn't want to be
14533 disturbed with target events. Clear all async event sources
14534 too. */
14535 clear_async_event_handler (rs->remote_async_inferior_event_token);
14536 if (target_is_non_stop_p ())
14537 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14538 }
14539 }
14540
14541 /* Implementation of the to_thread_events method. */
14542
14543 void
14544 remote_target::thread_events (int enable)
14545 {
14546 struct remote_state *rs = get_remote_state ();
14547 size_t size = get_remote_packet_size ();
14548
14549 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14550 return;
14551
14552 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
14553 putpkt (rs->buf);
14554 getpkt (&rs->buf, 0);
14555
14556 switch (packet_ok (rs->buf,
14557 &remote_protocol_packets[PACKET_QThreadEvents]))
14558 {
14559 case PACKET_OK:
14560 if (strcmp (rs->buf.data (), "OK") != 0)
14561 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
14562 break;
14563 case PACKET_ERROR:
14564 warning (_("Remote failure reply: %s"), rs->buf.data ());
14565 break;
14566 case PACKET_UNKNOWN:
14567 break;
14568 }
14569 }
14570
14571 static void
14572 show_remote_cmd (const char *args, int from_tty)
14573 {
14574 /* We can't just use cmd_show_list here, because we want to skip
14575 the redundant "show remote Z-packet" and the legacy aliases. */
14576 struct cmd_list_element *list = remote_show_cmdlist;
14577 struct ui_out *uiout = current_uiout;
14578
14579 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14580 for (; list != NULL; list = list->next)
14581 if (strcmp (list->name, "Z-packet") == 0)
14582 continue;
14583 else if (list->type == not_set_cmd)
14584 /* Alias commands are exactly like the original, except they
14585 don't have the normal type. */
14586 continue;
14587 else
14588 {
14589 ui_out_emit_tuple option_emitter (uiout, "option");
14590
14591 uiout->field_string ("name", list->name);
14592 uiout->text (": ");
14593 if (list->type == show_cmd)
14594 do_show_command (NULL, from_tty, list);
14595 else
14596 cmd_func (list, NULL, from_tty);
14597 }
14598 }
14599
14600
14601 /* Function to be called whenever a new objfile (shlib) is detected. */
14602 static void
14603 remote_new_objfile (struct objfile *objfile)
14604 {
14605 remote_target *remote = get_current_remote_target ();
14606
14607 /* First, check whether the current inferior's process target is a remote
14608 target. */
14609 if (remote == nullptr)
14610 return;
14611
14612 /* When we are attaching or handling a fork child and the shared library
14613 subsystem reads the list of loaded libraries, we receive new objfile
14614 events in between each found library. The libraries are read in an
14615 undefined order, so if we gave the remote side a chance to look up
14616 symbols between each objfile, we might give it an inconsistent picture
14617 of the inferior. It could appear that a library A appears loaded but
14618 a library B does not, even though library A requires library B. That
14619 would present a state that couldn't normally exist in the inferior.
14620
14621 So, skip these events, we'll give the remote a chance to look up symbols
14622 once all the loaded libraries and their symbols are known to GDB. */
14623 if (current_inferior ()->in_initial_library_scan)
14624 return;
14625
14626 remote->remote_check_symbols ();
14627 }
14628
14629 /* Pull all the tracepoints defined on the target and create local
14630 data structures representing them. We don't want to create real
14631 tracepoints yet, we don't want to mess up the user's existing
14632 collection. */
14633
14634 int
14635 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14636 {
14637 struct remote_state *rs = get_remote_state ();
14638 char *p;
14639
14640 /* Ask for a first packet of tracepoint definition. */
14641 putpkt ("qTfP");
14642 getpkt (&rs->buf, 0);
14643 p = rs->buf.data ();
14644 while (*p && *p != 'l')
14645 {
14646 parse_tracepoint_definition (p, utpp);
14647 /* Ask for another packet of tracepoint definition. */
14648 putpkt ("qTsP");
14649 getpkt (&rs->buf, 0);
14650 p = rs->buf.data ();
14651 }
14652 return 0;
14653 }
14654
14655 int
14656 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14657 {
14658 struct remote_state *rs = get_remote_state ();
14659 char *p;
14660
14661 /* Ask for a first packet of variable definition. */
14662 putpkt ("qTfV");
14663 getpkt (&rs->buf, 0);
14664 p = rs->buf.data ();
14665 while (*p && *p != 'l')
14666 {
14667 parse_tsv_definition (p, utsvp);
14668 /* Ask for another packet of variable definition. */
14669 putpkt ("qTsV");
14670 getpkt (&rs->buf, 0);
14671 p = rs->buf.data ();
14672 }
14673 return 0;
14674 }
14675
14676 /* The "set/show range-stepping" show hook. */
14677
14678 static void
14679 show_range_stepping (struct ui_file *file, int from_tty,
14680 struct cmd_list_element *c,
14681 const char *value)
14682 {
14683 fprintf_filtered (file,
14684 _("Debugger's willingness to use range stepping "
14685 "is %s.\n"), value);
14686 }
14687
14688 /* Return true if the vCont;r action is supported by the remote
14689 stub. */
14690
14691 bool
14692 remote_target::vcont_r_supported ()
14693 {
14694 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14695 remote_vcont_probe ();
14696
14697 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14698 && get_remote_state ()->supports_vCont.r);
14699 }
14700
14701 /* The "set/show range-stepping" set hook. */
14702
14703 static void
14704 set_range_stepping (const char *ignore_args, int from_tty,
14705 struct cmd_list_element *c)
14706 {
14707 /* When enabling, check whether range stepping is actually supported
14708 by the target, and warn if not. */
14709 if (use_range_stepping)
14710 {
14711 remote_target *remote = get_current_remote_target ();
14712 if (remote == NULL
14713 || !remote->vcont_r_supported ())
14714 warning (_("Range stepping is not supported by the current target"));
14715 }
14716 }
14717
14718 static void
14719 show_remote_debug (struct ui_file *file, int from_tty,
14720 struct cmd_list_element *c, const char *value)
14721 {
14722 fprintf_filtered (file, _("Debugging of remote protocol is %s.\n"),
14723 value);
14724 }
14725
14726 static void
14727 show_remote_timeout (struct ui_file *file, int from_tty,
14728 struct cmd_list_element *c, const char *value)
14729 {
14730 fprintf_filtered (file,
14731 _("Timeout limit to wait for target to respond is %s.\n"),
14732 value);
14733 }
14734
14735 /* Implement the "supports_memory_tagging" target_ops method. */
14736
14737 bool
14738 remote_target::supports_memory_tagging ()
14739 {
14740 return remote_memory_tagging_p ();
14741 }
14742
14743 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
14744
14745 static void
14746 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14747 size_t len, int type)
14748 {
14749 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14750
14751 std::string request = string_printf ("qMemTags:%s,%s:%s",
14752 phex_nz (address, addr_size),
14753 phex_nz (len, sizeof (len)),
14754 phex_nz (type, sizeof (type)));
14755
14756 strcpy (packet.data (), request.c_str ());
14757 }
14758
14759 /* Parse the qMemTags packet reply into TAGS.
14760
14761 Return true if successful, false otherwise. */
14762
14763 static bool
14764 parse_fetch_memtags_reply (const gdb::char_vector &reply,
14765 gdb::byte_vector &tags)
14766 {
14767 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
14768 return false;
14769
14770 /* Copy the tag data. */
14771 tags = hex2bin (reply.data () + 1);
14772
14773 return true;
14774 }
14775
14776 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
14777
14778 static void
14779 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14780 size_t len, int type,
14781 const gdb::byte_vector &tags)
14782 {
14783 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14784
14785 /* Put together the main packet, address and length. */
14786 std::string request = string_printf ("QMemTags:%s,%s:%s:",
14787 phex_nz (address, addr_size),
14788 phex_nz (len, sizeof (len)),
14789 phex_nz (type, sizeof (type)));
14790 request += bin2hex (tags.data (), tags.size ());
14791
14792 /* Check if we have exceeded the maximum packet size. */
14793 if (packet.size () < request.length ())
14794 error (_("Contents too big for packet QMemTags."));
14795
14796 strcpy (packet.data (), request.c_str ());
14797 }
14798
14799 /* Implement the "fetch_memtags" target_ops method. */
14800
14801 bool
14802 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
14803 gdb::byte_vector &tags, int type)
14804 {
14805 /* Make sure the qMemTags packet is supported. */
14806 if (!remote_memory_tagging_p ())
14807 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
14808
14809 struct remote_state *rs = get_remote_state ();
14810
14811 create_fetch_memtags_request (rs->buf, address, len, type);
14812
14813 putpkt (rs->buf);
14814 getpkt (&rs->buf, 0);
14815
14816 return parse_fetch_memtags_reply (rs->buf, tags);
14817 }
14818
14819 /* Implement the "store_memtags" target_ops method. */
14820
14821 bool
14822 remote_target::store_memtags (CORE_ADDR address, size_t len,
14823 const gdb::byte_vector &tags, int type)
14824 {
14825 /* Make sure the QMemTags packet is supported. */
14826 if (!remote_memory_tagging_p ())
14827 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
14828
14829 struct remote_state *rs = get_remote_state ();
14830
14831 create_store_memtags_request (rs->buf, address, len, type, tags);
14832
14833 putpkt (rs->buf);
14834 getpkt (&rs->buf, 0);
14835
14836 /* Verify if the request was successful. */
14837 return packet_check_result (rs->buf.data ()) == PACKET_OK;
14838 }
14839
14840 /* Return true if remote target T is non-stop. */
14841
14842 bool
14843 remote_target_is_non_stop_p (remote_target *t)
14844 {
14845 scoped_restore_current_thread restore_thread;
14846 switch_to_target_no_thread (t);
14847
14848 return target_is_non_stop_p ();
14849 }
14850
14851 #if GDB_SELF_TEST
14852
14853 namespace selftests {
14854
14855 static void
14856 test_memory_tagging_functions ()
14857 {
14858 remote_target remote;
14859
14860 struct packet_config *config
14861 = &remote_protocol_packets[PACKET_memory_tagging_feature];
14862
14863 scoped_restore restore_memtag_support_
14864 = make_scoped_restore (&config->support);
14865
14866 /* Test memory tagging packet support. */
14867 config->support = PACKET_SUPPORT_UNKNOWN;
14868 SELF_CHECK (remote.supports_memory_tagging () == false);
14869 config->support = PACKET_DISABLE;
14870 SELF_CHECK (remote.supports_memory_tagging () == false);
14871 config->support = PACKET_ENABLE;
14872 SELF_CHECK (remote.supports_memory_tagging () == true);
14873
14874 /* Setup testing. */
14875 gdb::char_vector packet;
14876 gdb::byte_vector tags, bv;
14877 std::string expected, reply;
14878 packet.resize (32000);
14879
14880 /* Test creating a qMemTags request. */
14881
14882 expected = "qMemTags:0,0:0";
14883 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
14884 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14885
14886 expected = "qMemTags:deadbeef,10:1";
14887 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
14888 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14889
14890 /* Test parsing a qMemTags reply. */
14891
14892 /* Error reply, tags vector unmodified. */
14893 reply = "E00";
14894 strcpy (packet.data (), reply.c_str ());
14895 tags.resize (0);
14896 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
14897 SELF_CHECK (tags.size () == 0);
14898
14899 /* Valid reply, tags vector updated. */
14900 tags.resize (0);
14901 bv.resize (0);
14902
14903 for (int i = 0; i < 5; i++)
14904 bv.push_back (i);
14905
14906 reply = "m" + bin2hex (bv.data (), bv.size ());
14907 strcpy (packet.data (), reply.c_str ());
14908
14909 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
14910 SELF_CHECK (tags.size () == 5);
14911
14912 for (int i = 0; i < 5; i++)
14913 SELF_CHECK (tags[i] == i);
14914
14915 /* Test creating a QMemTags request. */
14916
14917 /* Empty tag data. */
14918 tags.resize (0);
14919 expected = "QMemTags:0,0:0:";
14920 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
14921 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14922 expected.length ()) == 0);
14923
14924 /* Non-empty tag data. */
14925 tags.resize (0);
14926 for (int i = 0; i < 5; i++)
14927 tags.push_back (i);
14928 expected = "QMemTags:deadbeef,ff:1:0001020304";
14929 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
14930 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14931 expected.length ()) == 0);
14932 }
14933
14934 } // namespace selftests
14935 #endif /* GDB_SELF_TEST */
14936
14937 void _initialize_remote ();
14938 void
14939 _initialize_remote ()
14940 {
14941 /* architecture specific data */
14942 remote_g_packet_data_handle =
14943 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14944
14945 add_target (remote_target_info, remote_target::open);
14946 add_target (extended_remote_target_info, extended_remote_target::open);
14947
14948 /* Hook into new objfile notification. */
14949 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
14950
14951 #if 0
14952 init_remote_threadtests ();
14953 #endif
14954
14955 /* set/show remote ... */
14956
14957 add_basic_prefix_cmd ("remote", class_maintenance, _("\
14958 Remote protocol specific variables.\n\
14959 Configure various remote-protocol specific variables such as\n\
14960 the packets being used."),
14961 &remote_set_cmdlist,
14962 0 /* allow-unknown */, &setlist);
14963 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14964 Remote protocol specific variables.\n\
14965 Configure various remote-protocol specific variables such as\n\
14966 the packets being used."),
14967 &remote_show_cmdlist,
14968 0 /* allow-unknown */, &showlist);
14969
14970 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14971 Compare section data on target to the exec file.\n\
14972 Argument is a single section name (default: all loaded sections).\n\
14973 To compare only read-only loaded sections, specify the -r option."),
14974 &cmdlist);
14975
14976 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
14977 Send an arbitrary packet to a remote target.\n\
14978 maintenance packet TEXT\n\
14979 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14980 this command sends the string TEXT to the inferior, and displays the\n\
14981 response packet. GDB supplies the initial `$' character, and the\n\
14982 terminating `#' character and checksum."),
14983 &maintenancelist);
14984
14985 set_show_commands remotebreak_cmds
14986 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14987 Set whether to send break if interrupted."), _("\
14988 Show whether to send break if interrupted."), _("\
14989 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14990 set_remotebreak, show_remotebreak,
14991 &setlist, &showlist);
14992 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
14993 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
14994
14995 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14996 interrupt_sequence_modes, &interrupt_sequence_mode,
14997 _("\
14998 Set interrupt sequence to remote target."), _("\
14999 Show interrupt sequence to remote target."), _("\
15000 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
15001 NULL, show_interrupt_sequence,
15002 &remote_set_cmdlist,
15003 &remote_show_cmdlist);
15004
15005 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
15006 &interrupt_on_connect, _("\
15007 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15008 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15009 If set, interrupt sequence is sent to remote target."),
15010 NULL, NULL,
15011 &remote_set_cmdlist, &remote_show_cmdlist);
15012
15013 /* Install commands for configuring memory read/write packets. */
15014
15015 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
15016 Set the maximum number of bytes per memory write packet (deprecated)."),
15017 &setlist);
15018 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
15019 Show the maximum number of bytes per memory write packet (deprecated)."),
15020 &showlist);
15021 add_cmd ("memory-write-packet-size", no_class,
15022 set_memory_write_packet_size, _("\
15023 Set the maximum number of bytes per memory-write packet.\n\
15024 Specify the number of bytes in a packet or 0 (zero) for the\n\
15025 default packet size. The actual limit is further reduced\n\
15026 dependent on the target. Specify ``fixed'' to disable the\n\
15027 further restriction and ``limit'' to enable that restriction."),
15028 &remote_set_cmdlist);
15029 add_cmd ("memory-read-packet-size", no_class,
15030 set_memory_read_packet_size, _("\
15031 Set the maximum number of bytes per memory-read packet.\n\
15032 Specify the number of bytes in a packet or 0 (zero) for the\n\
15033 default packet size. The actual limit is further reduced\n\
15034 dependent on the target. Specify ``fixed'' to disable the\n\
15035 further restriction and ``limit'' to enable that restriction."),
15036 &remote_set_cmdlist);
15037 add_cmd ("memory-write-packet-size", no_class,
15038 show_memory_write_packet_size,
15039 _("Show the maximum number of bytes per memory-write packet."),
15040 &remote_show_cmdlist);
15041 add_cmd ("memory-read-packet-size", no_class,
15042 show_memory_read_packet_size,
15043 _("Show the maximum number of bytes per memory-read packet."),
15044 &remote_show_cmdlist);
15045
15046 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
15047 &remote_hw_watchpoint_limit, _("\
15048 Set the maximum number of target hardware watchpoints."), _("\
15049 Show the maximum number of target hardware watchpoints."), _("\
15050 Specify \"unlimited\" for unlimited hardware watchpoints."),
15051 NULL, show_hardware_watchpoint_limit,
15052 &remote_set_cmdlist,
15053 &remote_show_cmdlist);
15054 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15055 no_class,
15056 &remote_hw_watchpoint_length_limit, _("\
15057 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15058 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15059 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15060 NULL, show_hardware_watchpoint_length_limit,
15061 &remote_set_cmdlist, &remote_show_cmdlist);
15062 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
15063 &remote_hw_breakpoint_limit, _("\
15064 Set the maximum number of target hardware breakpoints."), _("\
15065 Show the maximum number of target hardware breakpoints."), _("\
15066 Specify \"unlimited\" for unlimited hardware breakpoints."),
15067 NULL, show_hardware_breakpoint_limit,
15068 &remote_set_cmdlist, &remote_show_cmdlist);
15069
15070 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15071 &remote_address_size, _("\
15072 Set the maximum size of the address (in bits) in a memory packet."), _("\
15073 Show the maximum size of the address (in bits) in a memory packet."), NULL,
15074 NULL,
15075 NULL, /* FIXME: i18n: */
15076 &setlist, &showlist);
15077
15078 init_all_packet_configs ();
15079
15080 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
15081 "X", "binary-download", 1);
15082
15083 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
15084 "vCont", "verbose-resume", 0);
15085
15086 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
15087 "QPassSignals", "pass-signals", 0);
15088
15089 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
15090 "QCatchSyscalls", "catch-syscalls", 0);
15091
15092 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
15093 "QProgramSignals", "program-signals", 0);
15094
15095 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
15096 "QSetWorkingDir", "set-working-dir", 0);
15097
15098 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
15099 "QStartupWithShell", "startup-with-shell", 0);
15100
15101 add_packet_config_cmd (&remote_protocol_packets
15102 [PACKET_QEnvironmentHexEncoded],
15103 "QEnvironmentHexEncoded", "environment-hex-encoded",
15104 0);
15105
15106 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
15107 "QEnvironmentReset", "environment-reset",
15108 0);
15109
15110 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
15111 "QEnvironmentUnset", "environment-unset",
15112 0);
15113
15114 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
15115 "qSymbol", "symbol-lookup", 0);
15116
15117 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
15118 "P", "set-register", 1);
15119
15120 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
15121 "p", "fetch-register", 1);
15122
15123 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
15124 "Z0", "software-breakpoint", 0);
15125
15126 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
15127 "Z1", "hardware-breakpoint", 0);
15128
15129 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
15130 "Z2", "write-watchpoint", 0);
15131
15132 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
15133 "Z3", "read-watchpoint", 0);
15134
15135 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
15136 "Z4", "access-watchpoint", 0);
15137
15138 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
15139 "qXfer:auxv:read", "read-aux-vector", 0);
15140
15141 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
15142 "qXfer:exec-file:read", "pid-to-exec-file", 0);
15143
15144 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
15145 "qXfer:features:read", "target-features", 0);
15146
15147 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
15148 "qXfer:libraries:read", "library-info", 0);
15149
15150 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
15151 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15152
15153 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
15154 "qXfer:memory-map:read", "memory-map", 0);
15155
15156 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
15157 "qXfer:osdata:read", "osdata", 0);
15158
15159 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
15160 "qXfer:threads:read", "threads", 0);
15161
15162 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
15163 "qXfer:siginfo:read", "read-siginfo-object", 0);
15164
15165 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
15166 "qXfer:siginfo:write", "write-siginfo-object", 0);
15167
15168 add_packet_config_cmd
15169 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
15170 "qXfer:traceframe-info:read", "traceframe-info", 0);
15171
15172 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
15173 "qXfer:uib:read", "unwind-info-block", 0);
15174
15175 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
15176 "qGetTLSAddr", "get-thread-local-storage-address",
15177 0);
15178
15179 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
15180 "qGetTIBAddr", "get-thread-information-block-address",
15181 0);
15182
15183 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
15184 "bc", "reverse-continue", 0);
15185
15186 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
15187 "bs", "reverse-step", 0);
15188
15189 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
15190 "qSupported", "supported-packets", 0);
15191
15192 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
15193 "qSearch:memory", "search-memory", 0);
15194
15195 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
15196 "qTStatus", "trace-status", 0);
15197
15198 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
15199 "vFile:setfs", "hostio-setfs", 0);
15200
15201 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
15202 "vFile:open", "hostio-open", 0);
15203
15204 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
15205 "vFile:pread", "hostio-pread", 0);
15206
15207 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
15208 "vFile:pwrite", "hostio-pwrite", 0);
15209
15210 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
15211 "vFile:close", "hostio-close", 0);
15212
15213 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
15214 "vFile:unlink", "hostio-unlink", 0);
15215
15216 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
15217 "vFile:readlink", "hostio-readlink", 0);
15218
15219 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
15220 "vFile:fstat", "hostio-fstat", 0);
15221
15222 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
15223 "vAttach", "attach", 0);
15224
15225 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
15226 "vRun", "run", 0);
15227
15228 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
15229 "QStartNoAckMode", "noack", 0);
15230
15231 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
15232 "vKill", "kill", 0);
15233
15234 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
15235 "qAttached", "query-attached", 0);
15236
15237 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
15238 "ConditionalTracepoints",
15239 "conditional-tracepoints", 0);
15240
15241 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
15242 "ConditionalBreakpoints",
15243 "conditional-breakpoints", 0);
15244
15245 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
15246 "BreakpointCommands",
15247 "breakpoint-commands", 0);
15248
15249 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
15250 "FastTracepoints", "fast-tracepoints", 0);
15251
15252 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
15253 "TracepointSource", "TracepointSource", 0);
15254
15255 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
15256 "QAllow", "allow", 0);
15257
15258 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
15259 "StaticTracepoints", "static-tracepoints", 0);
15260
15261 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
15262 "InstallInTrace", "install-in-trace", 0);
15263
15264 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
15265 "qXfer:statictrace:read", "read-sdata-object", 0);
15266
15267 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
15268 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
15269
15270 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
15271 "QDisableRandomization", "disable-randomization", 0);
15272
15273 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
15274 "QAgent", "agent", 0);
15275
15276 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
15277 "QTBuffer:size", "trace-buffer-size", 0);
15278
15279 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
15280 "Qbtrace:off", "disable-btrace", 0);
15281
15282 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
15283 "Qbtrace:bts", "enable-btrace-bts", 0);
15284
15285 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
15286 "Qbtrace:pt", "enable-btrace-pt", 0);
15287
15288 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
15289 "qXfer:btrace", "read-btrace", 0);
15290
15291 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
15292 "qXfer:btrace-conf", "read-btrace-conf", 0);
15293
15294 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
15295 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
15296
15297 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
15298 "multiprocess-feature", "multiprocess-feature", 0);
15299
15300 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
15301 "swbreak-feature", "swbreak-feature", 0);
15302
15303 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
15304 "hwbreak-feature", "hwbreak-feature", 0);
15305
15306 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
15307 "fork-event-feature", "fork-event-feature", 0);
15308
15309 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
15310 "vfork-event-feature", "vfork-event-feature", 0);
15311
15312 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
15313 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
15314
15315 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
15316 "vContSupported", "verbose-resume-supported", 0);
15317
15318 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
15319 "exec-event-feature", "exec-event-feature", 0);
15320
15321 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
15322 "vCtrlC", "ctrl-c", 0);
15323
15324 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
15325 "QThreadEvents", "thread-events", 0);
15326
15327 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
15328 "N stop reply", "no-resumed-stop-reply", 0);
15329
15330 add_packet_config_cmd (&remote_protocol_packets[PACKET_memory_tagging_feature],
15331 "memory-tagging-feature", "memory-tagging-feature", 0);
15332
15333 /* Assert that we've registered "set remote foo-packet" commands
15334 for all packet configs. */
15335 {
15336 int i;
15337
15338 for (i = 0; i < PACKET_MAX; i++)
15339 {
15340 /* Ideally all configs would have a command associated. Some
15341 still don't though. */
15342 int excepted;
15343
15344 switch (i)
15345 {
15346 case PACKET_QNonStop:
15347 case PACKET_EnableDisableTracepoints_feature:
15348 case PACKET_tracenz_feature:
15349 case PACKET_DisconnectedTracing_feature:
15350 case PACKET_augmented_libraries_svr4_read_feature:
15351 case PACKET_qCRC:
15352 /* Additions to this list need to be well justified:
15353 pre-existing packets are OK; new packets are not. */
15354 excepted = 1;
15355 break;
15356 default:
15357 excepted = 0;
15358 break;
15359 }
15360
15361 /* This catches both forgetting to add a config command, and
15362 forgetting to remove a packet from the exception list. */
15363 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
15364 }
15365 }
15366
15367 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15368 Z sub-packet has its own set and show commands, but users may
15369 have sets to this variable in their .gdbinit files (or in their
15370 documentation). */
15371 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
15372 &remote_Z_packet_detect, _("\
15373 Set use of remote protocol `Z' packets."), _("\
15374 Show use of remote protocol `Z' packets."), _("\
15375 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
15376 packets."),
15377 set_remote_protocol_Z_packet_cmd,
15378 show_remote_protocol_Z_packet_cmd,
15379 /* FIXME: i18n: Use of remote protocol
15380 `Z' packets is %s. */
15381 &remote_set_cmdlist, &remote_show_cmdlist);
15382
15383 add_basic_prefix_cmd ("remote", class_files, _("\
15384 Manipulate files on the remote system.\n\
15385 Transfer files to and from the remote target system."),
15386 &remote_cmdlist,
15387 0 /* allow-unknown */, &cmdlist);
15388
15389 add_cmd ("put", class_files, remote_put_command,
15390 _("Copy a local file to the remote system."),
15391 &remote_cmdlist);
15392
15393 add_cmd ("get", class_files, remote_get_command,
15394 _("Copy a remote file to the local system."),
15395 &remote_cmdlist);
15396
15397 add_cmd ("delete", class_files, remote_delete_command,
15398 _("Delete a remote file."),
15399 &remote_cmdlist);
15400
15401 add_setshow_string_noescape_cmd ("exec-file", class_files,
15402 &remote_exec_file_var, _("\
15403 Set the remote pathname for \"run\"."), _("\
15404 Show the remote pathname for \"run\"."), NULL,
15405 set_remote_exec_file,
15406 show_remote_exec_file,
15407 &remote_set_cmdlist,
15408 &remote_show_cmdlist);
15409
15410 add_setshow_boolean_cmd ("range-stepping", class_run,
15411 &use_range_stepping, _("\
15412 Enable or disable range stepping."), _("\
15413 Show whether target-assisted range stepping is enabled."), _("\
15414 If on, and the target supports it, when stepping a source line, GDB\n\
15415 tells the target to step the corresponding range of addresses itself instead\n\
15416 of issuing multiple single-steps. This speeds up source level\n\
15417 stepping. If off, GDB always issues single-steps, even if range\n\
15418 stepping is supported by the target. The default is on."),
15419 set_range_stepping,
15420 show_range_stepping,
15421 &setlist,
15422 &showlist);
15423
15424 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15425 Set watchdog timer."), _("\
15426 Show watchdog timer."), _("\
15427 When non-zero, this timeout is used instead of waiting forever for a target\n\
15428 to finish a low-level step or continue operation. If the specified amount\n\
15429 of time passes without a response from the target, an error occurs."),
15430 NULL,
15431 show_watchdog,
15432 &setlist, &showlist);
15433
15434 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15435 &remote_packet_max_chars, _("\
15436 Set the maximum number of characters to display for each remote packet."), _("\
15437 Show the maximum number of characters to display for each remote packet."), _("\
15438 Specify \"unlimited\" to display all the characters."),
15439 NULL, show_remote_packet_max_chars,
15440 &setdebuglist, &showdebuglist);
15441
15442 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15443 _("Set debugging of remote protocol."),
15444 _("Show debugging of remote protocol."),
15445 _("\
15446 When enabled, each packet sent or received with the remote target\n\
15447 is displayed."),
15448 NULL,
15449 show_remote_debug,
15450 &setdebuglist, &showdebuglist);
15451
15452 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15453 &remote_timeout, _("\
15454 Set timeout limit to wait for target to respond."), _("\
15455 Show timeout limit to wait for target to respond."), _("\
15456 This value is used to set the time limit for gdb to wait for a response\n\
15457 from the target."),
15458 NULL,
15459 show_remote_timeout,
15460 &setlist, &showlist);
15461
15462 /* Eventually initialize fileio. See fileio.c */
15463 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
15464
15465 #if GDB_SELF_TEST
15466 selftests::register_test ("remote_memory_tagging",
15467 selftests::test_memory_tagging_functions);
15468 #endif
15469 }