f0f3dcbabb000abe656c12da042f07064c600bc1
[binutils-gdb.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3 Copyright (C) 1988-2021 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20 /* See the GDB User Guide for details of the GDB remote protocol. */
21
22 #include "defs.h"
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "bfd.h"
28 #include "symfile.h"
29 #include "target.h"
30 #include "process-stratum-target.h"
31 #include "gdbcmd.h"
32 #include "objfiles.h"
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
35 #include "remote.h"
36 #include "remote-notif.h"
37 #include "regcache.h"
38 #include "value.h"
39 #include "observable.h"
40 #include "solib.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
44 #include "gdb_bfd.h"
45 #include "gdbsupport/filestuff.h"
46 #include "gdbsupport/rsp-low.h"
47 #include "disasm.h"
48 #include "location.h"
49
50 #include "gdbsupport/gdb_sys_time.h"
51
52 #include "gdbsupport/event-loop.h"
53 #include "event-top.h"
54 #include "inf-loop.h"
55
56 #include <signal.h>
57 #include "serial.h"
58
59 #include "gdbcore.h"
60
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
63 #include <sys/stat.h>
64 #include "xml-support.h"
65
66 #include "memory-map.h"
67
68 #include "tracepoint.h"
69 #include "ax.h"
70 #include "ax-gdb.h"
71 #include "gdbsupport/agent.h"
72 #include "btrace.h"
73 #include "record-btrace.h"
74 #include <algorithm>
75 #include "gdbsupport/scoped_restore.h"
76 #include "gdbsupport/environ.h"
77 #include "gdbsupport/byte-vector.h"
78 #include "gdbsupport/search.h"
79 #include <algorithm>
80 #include <unordered_map>
81 #include "async-event.h"
82 #include "gdbsupport/selftest.h"
83
84 /* The remote target. */
85
86 static const char remote_doc[] = N_("\
87 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
88 Specify the serial device it is connected to\n\
89 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
90
91 /* See remote.h */
92
93 bool remote_debug = false;
94
95 #define OPAQUETHREADBYTES 8
96
97 /* a 64 bit opaque identifier */
98 typedef unsigned char threadref[OPAQUETHREADBYTES];
99
100 struct gdb_ext_thread_info;
101 struct threads_listing_context;
102 typedef int (*rmt_thread_action) (threadref *ref, void *context);
103 struct protocol_feature;
104 struct packet_reg;
105
106 struct stop_reply;
107 typedef std::unique_ptr<stop_reply> stop_reply_up;
108
109 /* Generic configuration support for packets the stub optionally
110 supports. Allows the user to specify the use of the packet as well
111 as allowing GDB to auto-detect support in the remote stub. */
112
113 enum packet_support
114 {
115 PACKET_SUPPORT_UNKNOWN = 0,
116 PACKET_ENABLE,
117 PACKET_DISABLE
118 };
119
120 /* Analyze a packet's return value and update the packet config
121 accordingly. */
122
123 enum packet_result
124 {
125 PACKET_ERROR,
126 PACKET_OK,
127 PACKET_UNKNOWN
128 };
129
130 struct threads_listing_context;
131
132 /* Stub vCont actions support.
133
134 Each field is a boolean flag indicating whether the stub reports
135 support for the corresponding action. */
136
137 struct vCont_action_support
138 {
139 /* vCont;t */
140 bool t = false;
141
142 /* vCont;r */
143 bool r = false;
144
145 /* vCont;s */
146 bool s = false;
147
148 /* vCont;S */
149 bool S = false;
150 };
151
152 /* About this many threadids fit in a packet. */
153
154 #define MAXTHREADLISTRESULTS 32
155
156 /* Data for the vFile:pread readahead cache. */
157
158 struct readahead_cache
159 {
160 /* Invalidate the readahead cache. */
161 void invalidate ();
162
163 /* Invalidate the readahead cache if it is holding data for FD. */
164 void invalidate_fd (int fd);
165
166 /* Serve pread from the readahead cache. Returns number of bytes
167 read, or 0 if the request can't be served from the cache. */
168 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
169
170 /* The file descriptor for the file that is being cached. -1 if the
171 cache is invalid. */
172 int fd = -1;
173
174 /* The offset into the file that the cache buffer corresponds
175 to. */
176 ULONGEST offset = 0;
177
178 /* The buffer holding the cache contents. */
179 gdb_byte *buf = nullptr;
180 /* The buffer's size. We try to read as much as fits into a packet
181 at a time. */
182 size_t bufsize = 0;
183
184 /* Cache hit and miss counters. */
185 ULONGEST hit_count = 0;
186 ULONGEST miss_count = 0;
187 };
188
189 /* Description of the remote protocol for a given architecture. */
190
191 struct packet_reg
192 {
193 long offset; /* Offset into G packet. */
194 long regnum; /* GDB's internal register number. */
195 LONGEST pnum; /* Remote protocol register number. */
196 int in_g_packet; /* Always part of G packet. */
197 /* long size in bytes; == register_size (target_gdbarch (), regnum);
198 at present. */
199 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
200 at present. */
201 };
202
203 struct remote_arch_state
204 {
205 explicit remote_arch_state (struct gdbarch *gdbarch);
206
207 /* Description of the remote protocol registers. */
208 long sizeof_g_packet;
209
210 /* Description of the remote protocol registers indexed by REGNUM
211 (making an array gdbarch_num_regs in size). */
212 std::unique_ptr<packet_reg[]> regs;
213
214 /* This is the size (in chars) of the first response to the ``g''
215 packet. It is used as a heuristic when determining the maximum
216 size of memory-read and memory-write packets. A target will
217 typically only reserve a buffer large enough to hold the ``g''
218 packet. The size does not include packet overhead (headers and
219 trailers). */
220 long actual_register_packet_size;
221
222 /* This is the maximum size (in chars) of a non read/write packet.
223 It is also used as a cap on the size of read/write packets. */
224 long remote_packet_size;
225 };
226
227 /* Description of the remote protocol state for the currently
228 connected target. This is per-target state, and independent of the
229 selected architecture. */
230
231 class remote_state
232 {
233 public:
234
235 remote_state ();
236 ~remote_state ();
237
238 /* Get the remote arch state for GDBARCH. */
239 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
240
241 public: /* data */
242
243 /* A buffer to use for incoming packets, and its current size. The
244 buffer is grown dynamically for larger incoming packets.
245 Outgoing packets may also be constructed in this buffer.
246 The size of the buffer is always at least REMOTE_PACKET_SIZE;
247 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
248 packets. */
249 gdb::char_vector buf;
250
251 /* True if we're going through initial connection setup (finding out
252 about the remote side's threads, relocating symbols, etc.). */
253 bool starting_up = false;
254
255 /* If we negotiated packet size explicitly (and thus can bypass
256 heuristics for the largest packet size that will not overflow
257 a buffer in the stub), this will be set to that packet size.
258 Otherwise zero, meaning to use the guessed size. */
259 long explicit_packet_size = 0;
260
261 /* 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
765 void btrace_sync_conf (const btrace_config *conf);
766
767 void remote_btrace_maybe_reopen ();
768
769 void remove_new_fork_children (threads_listing_context *context);
770 void kill_new_fork_children (inferior *inf);
771 void discard_pending_stop_replies (struct inferior *inf);
772 int stop_reply_queue_length ();
773
774 void check_pending_events_prevent_wildcard_vcont
775 (bool *may_global_wildcard_vcont);
776
777 void discard_pending_stop_replies_in_queue ();
778 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
779 struct stop_reply *queued_stop_reply (ptid_t ptid);
780 int peek_stop_reply (ptid_t ptid);
781 void remote_parse_stop_reply (const char *buf, stop_reply *event);
782
783 void remote_stop_ns (ptid_t ptid);
784 void remote_interrupt_as ();
785 void remote_interrupt_ns ();
786
787 char *remote_get_noisy_reply ();
788 int remote_query_attached (int pid);
789 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
790 int try_open_exec);
791
792 ptid_t remote_current_thread (ptid_t oldpid);
793 ptid_t get_current_thread (const char *wait_status);
794
795 void set_thread (ptid_t ptid, int gen);
796 void set_general_thread (ptid_t ptid);
797 void set_continue_thread (ptid_t ptid);
798 void set_general_process ();
799
800 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
801
802 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
803 gdb_ext_thread_info *info);
804 int remote_get_threadinfo (threadref *threadid, int fieldset,
805 gdb_ext_thread_info *info);
806
807 int parse_threadlist_response (const char *pkt, int result_limit,
808 threadref *original_echo,
809 threadref *resultlist,
810 int *doneflag);
811 int remote_get_threadlist (int startflag, threadref *nextthread,
812 int result_limit, int *done, int *result_count,
813 threadref *threadlist);
814
815 int remote_threadlist_iterator (rmt_thread_action stepfunction,
816 void *context, int looplimit);
817
818 int remote_get_threads_with_ql (threads_listing_context *context);
819 int remote_get_threads_with_qxfer (threads_listing_context *context);
820 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
821
822 void extended_remote_restart ();
823
824 void get_offsets ();
825
826 void remote_check_symbols ();
827
828 void remote_supported_packet (const struct protocol_feature *feature,
829 enum packet_support support,
830 const char *argument);
831
832 void remote_query_supported ();
833
834 void remote_packet_size (const protocol_feature *feature,
835 packet_support support, const char *value);
836
837 void remote_serial_quit_handler ();
838
839 void remote_detach_pid (int pid);
840
841 void remote_vcont_probe ();
842
843 void remote_resume_with_hc (ptid_t ptid, int step,
844 gdb_signal siggnal);
845
846 void send_interrupt_sequence ();
847 void interrupt_query ();
848
849 void remote_notif_get_pending_events (notif_client *nc);
850
851 int fetch_register_using_p (struct regcache *regcache,
852 packet_reg *reg);
853 int send_g_packet ();
854 void process_g_packet (struct regcache *regcache);
855 void fetch_registers_using_g (struct regcache *regcache);
856 int store_register_using_P (const struct regcache *regcache,
857 packet_reg *reg);
858 void store_registers_using_G (const struct regcache *regcache);
859
860 void set_remote_traceframe ();
861
862 void check_binary_download (CORE_ADDR addr);
863
864 target_xfer_status remote_write_bytes_aux (const char *header,
865 CORE_ADDR memaddr,
866 const gdb_byte *myaddr,
867 ULONGEST len_units,
868 int unit_size,
869 ULONGEST *xfered_len_units,
870 char packet_format,
871 int use_length);
872
873 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
874 const gdb_byte *myaddr, ULONGEST len,
875 int unit_size, ULONGEST *xfered_len);
876
877 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
878 ULONGEST len_units,
879 int unit_size, ULONGEST *xfered_len_units);
880
881 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
882 ULONGEST memaddr,
883 ULONGEST len,
884 int unit_size,
885 ULONGEST *xfered_len);
886
887 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
888 gdb_byte *myaddr, ULONGEST len,
889 int unit_size,
890 ULONGEST *xfered_len);
891
892 packet_result remote_send_printf (const char *format, ...)
893 ATTRIBUTE_PRINTF (2, 3);
894
895 target_xfer_status remote_flash_write (ULONGEST address,
896 ULONGEST length, ULONGEST *xfered_len,
897 const gdb_byte *data);
898
899 int readchar (int timeout);
900
901 void remote_serial_write (const char *str, int len);
902
903 int putpkt (const char *buf);
904 int putpkt_binary (const char *buf, int cnt);
905
906 int putpkt (const gdb::char_vector &buf)
907 {
908 return putpkt (buf.data ());
909 }
910
911 void skip_frame ();
912 long read_frame (gdb::char_vector *buf_p);
913 void getpkt (gdb::char_vector *buf, int forever);
914 int getpkt_or_notif_sane_1 (gdb::char_vector *buf, int forever,
915 int expecting_notif, int *is_notif);
916 int getpkt_sane (gdb::char_vector *buf, int forever);
917 int getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
918 int *is_notif);
919 int remote_vkill (int pid);
920 void remote_kill_k ();
921
922 void extended_remote_disable_randomization (int val);
923 int extended_remote_run (const std::string &args);
924
925 void send_environment_packet (const char *action,
926 const char *packet,
927 const char *value);
928
929 void extended_remote_environment_support ();
930 void extended_remote_set_inferior_cwd ();
931
932 target_xfer_status remote_write_qxfer (const char *object_name,
933 const char *annex,
934 const gdb_byte *writebuf,
935 ULONGEST offset, LONGEST len,
936 ULONGEST *xfered_len,
937 struct packet_config *packet);
938
939 target_xfer_status remote_read_qxfer (const char *object_name,
940 const char *annex,
941 gdb_byte *readbuf, ULONGEST offset,
942 LONGEST len,
943 ULONGEST *xfered_len,
944 struct packet_config *packet);
945
946 void push_stop_reply (struct stop_reply *new_event);
947
948 bool vcont_r_supported ();
949
950 private:
951
952 bool start_remote_1 (int from_tty, int extended_p);
953
954 /* The remote state. Don't reference this directly. Use the
955 get_remote_state method instead. */
956 remote_state m_remote_state;
957 };
958
959 static const target_info extended_remote_target_info = {
960 "extended-remote",
961 N_("Extended remote serial target in gdb-specific protocol"),
962 remote_doc
963 };
964
965 /* Set up the extended remote target by extending the standard remote
966 target and adding to it. */
967
968 class extended_remote_target final : public remote_target
969 {
970 public:
971 const target_info &info () const override
972 { return extended_remote_target_info; }
973
974 /* Open an extended-remote connection. */
975 static void open (const char *, int);
976
977 bool can_create_inferior () override { return true; }
978 void create_inferior (const char *, const std::string &,
979 char **, int) override;
980
981 void detach (inferior *, int) override;
982
983 bool can_attach () override { return true; }
984 void attach (const char *, int) override;
985
986 void post_attach (int) override;
987 bool supports_disable_randomization () override;
988 };
989
990 struct stop_reply : public notif_event
991 {
992 ~stop_reply ();
993
994 /* The identifier of the thread about this event */
995 ptid_t ptid;
996
997 /* The remote state this event is associated with. When the remote
998 connection, represented by a remote_state object, is closed,
999 all the associated stop_reply events should be released. */
1000 struct remote_state *rs;
1001
1002 struct target_waitstatus ws;
1003
1004 /* The architecture associated with the expedited registers. */
1005 gdbarch *arch;
1006
1007 /* Expedited registers. This makes remote debugging a bit more
1008 efficient for those targets that provide critical registers as
1009 part of their normal status mechanism (as another roundtrip to
1010 fetch them is avoided). */
1011 std::vector<cached_reg_t> regcache;
1012
1013 enum target_stop_reason stop_reason;
1014
1015 CORE_ADDR watch_data_address;
1016
1017 int core;
1018 };
1019
1020 /* See remote.h. */
1021
1022 bool
1023 is_remote_target (process_stratum_target *target)
1024 {
1025 remote_target *rt = dynamic_cast<remote_target *> (target);
1026 return rt != nullptr;
1027 }
1028
1029 /* Per-program-space data key. */
1030 static const struct program_space_key<char, gdb::xfree_deleter<char>>
1031 remote_pspace_data;
1032
1033 /* The variable registered as the control variable used by the
1034 remote exec-file commands. While the remote exec-file setting is
1035 per-program-space, the set/show machinery uses this as the
1036 location of the remote exec-file value. */
1037 static std::string remote_exec_file_var;
1038
1039 /* The size to align memory write packets, when practical. The protocol
1040 does not guarantee any alignment, and gdb will generate short
1041 writes and unaligned writes, but even as a best-effort attempt this
1042 can improve bulk transfers. For instance, if a write is misaligned
1043 relative to the target's data bus, the stub may need to make an extra
1044 round trip fetching data from the target. This doesn't make a
1045 huge difference, but it's easy to do, so we try to be helpful.
1046
1047 The alignment chosen is arbitrary; usually data bus width is
1048 important here, not the possibly larger cache line size. */
1049 enum { REMOTE_ALIGN_WRITES = 16 };
1050
1051 /* Prototypes for local functions. */
1052
1053 static int hexnumlen (ULONGEST num);
1054
1055 static int stubhex (int ch);
1056
1057 static int hexnumstr (char *, ULONGEST);
1058
1059 static int hexnumnstr (char *, ULONGEST, int);
1060
1061 static CORE_ADDR remote_address_masked (CORE_ADDR);
1062
1063 static int stub_unpack_int (const char *buff, int fieldlength);
1064
1065 struct packet_config;
1066
1067 static void show_packet_config_cmd (struct packet_config *config);
1068
1069 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1070 int from_tty,
1071 struct cmd_list_element *c,
1072 const char *value);
1073
1074 static ptid_t read_ptid (const char *buf, const char **obuf);
1075
1076 static void remote_async_inferior_event_handler (gdb_client_data);
1077
1078 static bool remote_read_description_p (struct target_ops *target);
1079
1080 static void remote_console_output (const char *msg);
1081
1082 static void remote_btrace_reset (remote_state *rs);
1083
1084 static void remote_unpush_and_throw (remote_target *target);
1085
1086 /* For "remote". */
1087
1088 static struct cmd_list_element *remote_cmdlist;
1089
1090 /* For "set remote" and "show remote". */
1091
1092 static struct cmd_list_element *remote_set_cmdlist;
1093 static struct cmd_list_element *remote_show_cmdlist;
1094
1095 /* Controls whether GDB is willing to use range stepping. */
1096
1097 static bool use_range_stepping = true;
1098
1099 /* From the remote target's point of view, each thread is in one of these three
1100 states. */
1101 enum class resume_state
1102 {
1103 /* Not resumed - we haven't been asked to resume this thread. */
1104 NOT_RESUMED,
1105
1106 /* We have been asked to resume this thread, but haven't sent a vCont action
1107 for it yet. We'll need to consider it next time commit_resume is
1108 called. */
1109 RESUMED_PENDING_VCONT,
1110
1111 /* We have been asked to resume this thread, and we have sent a vCont action
1112 for it. */
1113 RESUMED,
1114 };
1115
1116 /* Information about a thread's pending vCont-resume. Used when a thread is in
1117 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1118 stores this information which is then picked up by
1119 remote_target::commit_resume to know which is the proper action for this
1120 thread to include in the vCont packet. */
1121 struct resumed_pending_vcont_info
1122 {
1123 /* True if the last resume call for this thread was a step request, false
1124 if a continue request. */
1125 bool step;
1126
1127 /* The signal specified in the last resume call for this thread. */
1128 gdb_signal sig;
1129 };
1130
1131 /* Private data that we'll store in (struct thread_info)->priv. */
1132 struct remote_thread_info : public private_thread_info
1133 {
1134 std::string extra;
1135 std::string name;
1136 int core = -1;
1137
1138 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1139 sequence of bytes. */
1140 gdb::byte_vector thread_handle;
1141
1142 /* Whether the target stopped for a breakpoint/watchpoint. */
1143 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1144
1145 /* This is set to the data address of the access causing the target
1146 to stop for a watchpoint. */
1147 CORE_ADDR watch_data_address = 0;
1148
1149 /* Get the thread's resume state. */
1150 enum resume_state get_resume_state () const
1151 {
1152 return m_resume_state;
1153 }
1154
1155 /* Put the thread in the NOT_RESUMED state. */
1156 void set_not_resumed ()
1157 {
1158 m_resume_state = resume_state::NOT_RESUMED;
1159 }
1160
1161 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1162 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1163 {
1164 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1165 m_resumed_pending_vcont_info.step = step;
1166 m_resumed_pending_vcont_info.sig = sig;
1167 }
1168
1169 /* Get the information this thread's pending vCont-resumption.
1170
1171 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1172 state. */
1173 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1174 {
1175 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1176
1177 return m_resumed_pending_vcont_info;
1178 }
1179
1180 /* Put the thread in the VCONT_RESUMED state. */
1181 void set_resumed ()
1182 {
1183 m_resume_state = resume_state::RESUMED;
1184 }
1185
1186 private:
1187 /* Resume state for this thread. This is used to implement vCont action
1188 coalescing (only when the target operates in non-stop mode).
1189
1190 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1191 which notes that this thread must be considered in the next commit_resume
1192 call.
1193
1194 remote_target::commit_resume sends a vCont packet with actions for the
1195 threads in the RESUMED_PENDING_VCONT state and moves them to the
1196 VCONT_RESUMED state.
1197
1198 When reporting a stop to the core for a thread, that thread is moved back
1199 to the NOT_RESUMED state. */
1200 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1201
1202 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1203 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1204 };
1205
1206 remote_state::remote_state ()
1207 : buf (400)
1208 {
1209 }
1210
1211 remote_state::~remote_state ()
1212 {
1213 xfree (this->last_pass_packet);
1214 xfree (this->last_program_signals_packet);
1215 xfree (this->finished_object);
1216 xfree (this->finished_annex);
1217 }
1218
1219 /* Utility: generate error from an incoming stub packet. */
1220 static void
1221 trace_error (char *buf)
1222 {
1223 if (*buf++ != 'E')
1224 return; /* not an error msg */
1225 switch (*buf)
1226 {
1227 case '1': /* malformed packet error */
1228 if (*++buf == '0') /* general case: */
1229 error (_("remote.c: error in outgoing packet."));
1230 else
1231 error (_("remote.c: error in outgoing packet at field #%ld."),
1232 strtol (buf, NULL, 16));
1233 default:
1234 error (_("Target returns error code '%s'."), buf);
1235 }
1236 }
1237
1238 /* Utility: wait for reply from stub, while accepting "O" packets. */
1239
1240 char *
1241 remote_target::remote_get_noisy_reply ()
1242 {
1243 struct remote_state *rs = get_remote_state ();
1244
1245 do /* Loop on reply from remote stub. */
1246 {
1247 char *buf;
1248
1249 QUIT; /* Allow user to bail out with ^C. */
1250 getpkt (&rs->buf, 0);
1251 buf = rs->buf.data ();
1252 if (buf[0] == 'E')
1253 trace_error (buf);
1254 else if (startswith (buf, "qRelocInsn:"))
1255 {
1256 ULONGEST ul;
1257 CORE_ADDR from, to, org_to;
1258 const char *p, *pp;
1259 int adjusted_size = 0;
1260 int relocated = 0;
1261
1262 p = buf + strlen ("qRelocInsn:");
1263 pp = unpack_varlen_hex (p, &ul);
1264 if (*pp != ';')
1265 error (_("invalid qRelocInsn packet: %s"), buf);
1266 from = ul;
1267
1268 p = pp + 1;
1269 unpack_varlen_hex (p, &ul);
1270 to = ul;
1271
1272 org_to = to;
1273
1274 try
1275 {
1276 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
1277 relocated = 1;
1278 }
1279 catch (const gdb_exception &ex)
1280 {
1281 if (ex.error == MEMORY_ERROR)
1282 {
1283 /* Propagate memory errors silently back to the
1284 target. The stub may have limited the range of
1285 addresses we can write to, for example. */
1286 }
1287 else
1288 {
1289 /* Something unexpectedly bad happened. Be verbose
1290 so we can tell what, and propagate the error back
1291 to the stub, so it doesn't get stuck waiting for
1292 a response. */
1293 exception_fprintf (gdb_stderr, ex,
1294 _("warning: relocating instruction: "));
1295 }
1296 putpkt ("E01");
1297 }
1298
1299 if (relocated)
1300 {
1301 adjusted_size = to - org_to;
1302
1303 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1304 putpkt (buf);
1305 }
1306 }
1307 else if (buf[0] == 'O' && buf[1] != 'K')
1308 remote_console_output (buf + 1); /* 'O' message from stub */
1309 else
1310 return buf; /* Here's the actual reply. */
1311 }
1312 while (1);
1313 }
1314
1315 struct remote_arch_state *
1316 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1317 {
1318 remote_arch_state *rsa;
1319
1320 auto it = this->m_arch_states.find (gdbarch);
1321 if (it == this->m_arch_states.end ())
1322 {
1323 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1324 std::forward_as_tuple (gdbarch),
1325 std::forward_as_tuple (gdbarch));
1326 rsa = &p.first->second;
1327
1328 /* Make sure that the packet buffer is plenty big enough for
1329 this architecture. */
1330 if (this->buf.size () < rsa->remote_packet_size)
1331 this->buf.resize (2 * rsa->remote_packet_size);
1332 }
1333 else
1334 rsa = &it->second;
1335
1336 return rsa;
1337 }
1338
1339 /* Fetch the global remote target state. */
1340
1341 remote_state *
1342 remote_target::get_remote_state ()
1343 {
1344 /* Make sure that the remote architecture state has been
1345 initialized, because doing so might reallocate rs->buf. Any
1346 function which calls getpkt also needs to be mindful of changes
1347 to rs->buf, but this call limits the number of places which run
1348 into trouble. */
1349 m_remote_state.get_remote_arch_state (target_gdbarch ());
1350
1351 return &m_remote_state;
1352 }
1353
1354 /* Fetch the remote exec-file from the current program space. */
1355
1356 static const char *
1357 get_remote_exec_file (void)
1358 {
1359 char *remote_exec_file;
1360
1361 remote_exec_file = remote_pspace_data.get (current_program_space);
1362 if (remote_exec_file == NULL)
1363 return "";
1364
1365 return remote_exec_file;
1366 }
1367
1368 /* Set the remote exec file for PSPACE. */
1369
1370 static void
1371 set_pspace_remote_exec_file (struct program_space *pspace,
1372 const char *remote_exec_file)
1373 {
1374 char *old_file = remote_pspace_data.get (pspace);
1375
1376 xfree (old_file);
1377 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1378 }
1379
1380 /* The "set/show remote exec-file" set command hook. */
1381
1382 static void
1383 set_remote_exec_file (const char *ignored, int from_tty,
1384 struct cmd_list_element *c)
1385 {
1386 set_pspace_remote_exec_file (current_program_space,
1387 remote_exec_file_var.c_str ());
1388 }
1389
1390 /* The "set/show remote exec-file" show command hook. */
1391
1392 static void
1393 show_remote_exec_file (struct ui_file *file, int from_tty,
1394 struct cmd_list_element *cmd, const char *value)
1395 {
1396 fprintf_filtered (file, "%s\n", get_remote_exec_file ());
1397 }
1398
1399 static int
1400 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1401 {
1402 int regnum, num_remote_regs, offset;
1403 struct packet_reg **remote_regs;
1404
1405 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1406 {
1407 struct packet_reg *r = &regs[regnum];
1408
1409 if (register_size (gdbarch, regnum) == 0)
1410 /* Do not try to fetch zero-sized (placeholder) registers. */
1411 r->pnum = -1;
1412 else
1413 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1414
1415 r->regnum = regnum;
1416 }
1417
1418 /* Define the g/G packet format as the contents of each register
1419 with a remote protocol number, in order of ascending protocol
1420 number. */
1421
1422 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1423 for (num_remote_regs = 0, regnum = 0;
1424 regnum < gdbarch_num_regs (gdbarch);
1425 regnum++)
1426 if (regs[regnum].pnum != -1)
1427 remote_regs[num_remote_regs++] = &regs[regnum];
1428
1429 std::sort (remote_regs, remote_regs + num_remote_regs,
1430 [] (const packet_reg *a, const packet_reg *b)
1431 { return a->pnum < b->pnum; });
1432
1433 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1434 {
1435 remote_regs[regnum]->in_g_packet = 1;
1436 remote_regs[regnum]->offset = offset;
1437 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1438 }
1439
1440 return offset;
1441 }
1442
1443 /* Given the architecture described by GDBARCH, return the remote
1444 protocol register's number and the register's offset in the g/G
1445 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1446 If the target does not have a mapping for REGNUM, return false,
1447 otherwise, return true. */
1448
1449 int
1450 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1451 int *pnum, int *poffset)
1452 {
1453 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1454
1455 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1456
1457 map_regcache_remote_table (gdbarch, regs.data ());
1458
1459 *pnum = regs[regnum].pnum;
1460 *poffset = regs[regnum].offset;
1461
1462 return *pnum != -1;
1463 }
1464
1465 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1466 {
1467 /* Use the architecture to build a regnum<->pnum table, which will be
1468 1:1 unless a feature set specifies otherwise. */
1469 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1470
1471 /* Record the maximum possible size of the g packet - it may turn out
1472 to be smaller. */
1473 this->sizeof_g_packet
1474 = map_regcache_remote_table (gdbarch, this->regs.get ());
1475
1476 /* Default maximum number of characters in a packet body. Many
1477 remote stubs have a hardwired buffer size of 400 bytes
1478 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1479 as the maximum packet-size to ensure that the packet and an extra
1480 NUL character can always fit in the buffer. This stops GDB
1481 trashing stubs that try to squeeze an extra NUL into what is
1482 already a full buffer (As of 1999-12-04 that was most stubs). */
1483 this->remote_packet_size = 400 - 1;
1484
1485 /* This one is filled in when a ``g'' packet is received. */
1486 this->actual_register_packet_size = 0;
1487
1488 /* Should rsa->sizeof_g_packet needs more space than the
1489 default, adjust the size accordingly. Remember that each byte is
1490 encoded as two characters. 32 is the overhead for the packet
1491 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1492 (``$NN:G...#NN'') is a better guess, the below has been padded a
1493 little. */
1494 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1495 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1496 }
1497
1498 /* Get a pointer to the current remote target. If not connected to a
1499 remote target, return NULL. */
1500
1501 static remote_target *
1502 get_current_remote_target ()
1503 {
1504 target_ops *proc_target = current_inferior ()->process_target ();
1505 return dynamic_cast<remote_target *> (proc_target);
1506 }
1507
1508 /* Return the current allowed size of a remote packet. This is
1509 inferred from the current architecture, and should be used to
1510 limit the length of outgoing packets. */
1511 long
1512 remote_target::get_remote_packet_size ()
1513 {
1514 struct remote_state *rs = get_remote_state ();
1515 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1516
1517 if (rs->explicit_packet_size)
1518 return rs->explicit_packet_size;
1519
1520 return rsa->remote_packet_size;
1521 }
1522
1523 static struct packet_reg *
1524 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1525 long regnum)
1526 {
1527 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1528 return NULL;
1529 else
1530 {
1531 struct packet_reg *r = &rsa->regs[regnum];
1532
1533 gdb_assert (r->regnum == regnum);
1534 return r;
1535 }
1536 }
1537
1538 static struct packet_reg *
1539 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1540 LONGEST pnum)
1541 {
1542 int i;
1543
1544 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1545 {
1546 struct packet_reg *r = &rsa->regs[i];
1547
1548 if (r->pnum == pnum)
1549 return r;
1550 }
1551 return NULL;
1552 }
1553
1554 /* Allow the user to specify what sequence to send to the remote
1555 when he requests a program interruption: Although ^C is usually
1556 what remote systems expect (this is the default, here), it is
1557 sometimes preferable to send a break. On other systems such
1558 as the Linux kernel, a break followed by g, which is Magic SysRq g
1559 is required in order to interrupt the execution. */
1560 const char interrupt_sequence_control_c[] = "Ctrl-C";
1561 const char interrupt_sequence_break[] = "BREAK";
1562 const char interrupt_sequence_break_g[] = "BREAK-g";
1563 static const char *const interrupt_sequence_modes[] =
1564 {
1565 interrupt_sequence_control_c,
1566 interrupt_sequence_break,
1567 interrupt_sequence_break_g,
1568 NULL
1569 };
1570 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1571
1572 static void
1573 show_interrupt_sequence (struct ui_file *file, int from_tty,
1574 struct cmd_list_element *c,
1575 const char *value)
1576 {
1577 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1578 fprintf_filtered (file,
1579 _("Send the ASCII ETX character (Ctrl-c) "
1580 "to the remote target to interrupt the "
1581 "execution of the program.\n"));
1582 else if (interrupt_sequence_mode == interrupt_sequence_break)
1583 fprintf_filtered (file,
1584 _("send a break signal to the remote target "
1585 "to interrupt the execution of the program.\n"));
1586 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1587 fprintf_filtered (file,
1588 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1589 "the remote target to interrupt the execution "
1590 "of Linux kernel.\n"));
1591 else
1592 internal_error (__FILE__, __LINE__,
1593 _("Invalid value for interrupt_sequence_mode: %s."),
1594 interrupt_sequence_mode);
1595 }
1596
1597 /* This boolean variable specifies whether interrupt_sequence is sent
1598 to the remote target when gdb connects to it.
1599 This is mostly needed when you debug the Linux kernel: The Linux kernel
1600 expects BREAK g which is Magic SysRq g for connecting gdb. */
1601 static bool interrupt_on_connect = false;
1602
1603 /* This variable is used to implement the "set/show remotebreak" commands.
1604 Since these commands are now deprecated in favor of "set/show remote
1605 interrupt-sequence", it no longer has any effect on the code. */
1606 static bool remote_break;
1607
1608 static void
1609 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1610 {
1611 if (remote_break)
1612 interrupt_sequence_mode = interrupt_sequence_break;
1613 else
1614 interrupt_sequence_mode = interrupt_sequence_control_c;
1615 }
1616
1617 static void
1618 show_remotebreak (struct ui_file *file, int from_tty,
1619 struct cmd_list_element *c,
1620 const char *value)
1621 {
1622 }
1623
1624 /* This variable sets the number of bits in an address that are to be
1625 sent in a memory ("M" or "m") packet. Normally, after stripping
1626 leading zeros, the entire address would be sent. This variable
1627 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1628 initial implementation of remote.c restricted the address sent in
1629 memory packets to ``host::sizeof long'' bytes - (typically 32
1630 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1631 address was never sent. Since fixing this bug may cause a break in
1632 some remote targets this variable is principally provided to
1633 facilitate backward compatibility. */
1634
1635 static unsigned int remote_address_size;
1636
1637 \f
1638 /* User configurable variables for the number of characters in a
1639 memory read/write packet. MIN (rsa->remote_packet_size,
1640 rsa->sizeof_g_packet) is the default. Some targets need smaller
1641 values (fifo overruns, et.al.) and some users need larger values
1642 (speed up transfers). The variables ``preferred_*'' (the user
1643 request), ``current_*'' (what was actually set) and ``forced_*''
1644 (Positive - a soft limit, negative - a hard limit). */
1645
1646 struct memory_packet_config
1647 {
1648 const char *name;
1649 long size;
1650 int fixed_p;
1651 };
1652
1653 /* The default max memory-write-packet-size, when the setting is
1654 "fixed". The 16k is historical. (It came from older GDB's using
1655 alloca for buffers and the knowledge (folklore?) that some hosts
1656 don't cope very well with large alloca calls.) */
1657 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1658
1659 /* The minimum remote packet size for memory transfers. Ensures we
1660 can write at least one byte. */
1661 #define MIN_MEMORY_PACKET_SIZE 20
1662
1663 /* Get the memory packet size, assuming it is fixed. */
1664
1665 static long
1666 get_fixed_memory_packet_size (struct memory_packet_config *config)
1667 {
1668 gdb_assert (config->fixed_p);
1669
1670 if (config->size <= 0)
1671 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1672 else
1673 return config->size;
1674 }
1675
1676 /* Compute the current size of a read/write packet. Since this makes
1677 use of ``actual_register_packet_size'' the computation is dynamic. */
1678
1679 long
1680 remote_target::get_memory_packet_size (struct memory_packet_config *config)
1681 {
1682 struct remote_state *rs = get_remote_state ();
1683 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1684
1685 long what_they_get;
1686 if (config->fixed_p)
1687 what_they_get = get_fixed_memory_packet_size (config);
1688 else
1689 {
1690 what_they_get = get_remote_packet_size ();
1691 /* Limit the packet to the size specified by the user. */
1692 if (config->size > 0
1693 && what_they_get > config->size)
1694 what_they_get = config->size;
1695
1696 /* Limit it to the size of the targets ``g'' response unless we have
1697 permission from the stub to use a larger packet size. */
1698 if (rs->explicit_packet_size == 0
1699 && rsa->actual_register_packet_size > 0
1700 && what_they_get > rsa->actual_register_packet_size)
1701 what_they_get = rsa->actual_register_packet_size;
1702 }
1703 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1704 what_they_get = MIN_MEMORY_PACKET_SIZE;
1705
1706 /* Make sure there is room in the global buffer for this packet
1707 (including its trailing NUL byte). */
1708 if (rs->buf.size () < what_they_get + 1)
1709 rs->buf.resize (2 * what_they_get);
1710
1711 return what_they_get;
1712 }
1713
1714 /* Update the size of a read/write packet. If they user wants
1715 something really big then do a sanity check. */
1716
1717 static void
1718 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1719 {
1720 int fixed_p = config->fixed_p;
1721 long size = config->size;
1722
1723 if (args == NULL)
1724 error (_("Argument required (integer, `fixed' or `limited')."));
1725 else if (strcmp (args, "hard") == 0
1726 || strcmp (args, "fixed") == 0)
1727 fixed_p = 1;
1728 else if (strcmp (args, "soft") == 0
1729 || strcmp (args, "limit") == 0)
1730 fixed_p = 0;
1731 else
1732 {
1733 char *end;
1734
1735 size = strtoul (args, &end, 0);
1736 if (args == end)
1737 error (_("Invalid %s (bad syntax)."), config->name);
1738
1739 /* Instead of explicitly capping the size of a packet to or
1740 disallowing it, the user is allowed to set the size to
1741 something arbitrarily large. */
1742 }
1743
1744 /* Extra checks? */
1745 if (fixed_p && !config->fixed_p)
1746 {
1747 /* So that the query shows the correct value. */
1748 long query_size = (size <= 0
1749 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1750 : size);
1751
1752 if (! query (_("The target may not be able to correctly handle a %s\n"
1753 "of %ld bytes. Change the packet size? "),
1754 config->name, query_size))
1755 error (_("Packet size not changed."));
1756 }
1757 /* Update the config. */
1758 config->fixed_p = fixed_p;
1759 config->size = size;
1760 }
1761
1762 static void
1763 show_memory_packet_size (struct memory_packet_config *config)
1764 {
1765 if (config->size == 0)
1766 printf_filtered (_("The %s is 0 (default). "), config->name);
1767 else
1768 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1769 if (config->fixed_p)
1770 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1771 get_fixed_memory_packet_size (config));
1772 else
1773 {
1774 remote_target *remote = get_current_remote_target ();
1775
1776 if (remote != NULL)
1777 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1778 remote->get_memory_packet_size (config));
1779 else
1780 puts_filtered ("The actual limit will be further reduced "
1781 "dependent on the target.\n");
1782 }
1783 }
1784
1785 /* FIXME: needs to be per-remote-target. */
1786 static struct memory_packet_config memory_write_packet_config =
1787 {
1788 "memory-write-packet-size",
1789 };
1790
1791 static void
1792 set_memory_write_packet_size (const char *args, int from_tty)
1793 {
1794 set_memory_packet_size (args, &memory_write_packet_config);
1795 }
1796
1797 static void
1798 show_memory_write_packet_size (const char *args, int from_tty)
1799 {
1800 show_memory_packet_size (&memory_write_packet_config);
1801 }
1802
1803 /* Show the number of hardware watchpoints that can be used. */
1804
1805 static void
1806 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
1807 struct cmd_list_element *c,
1808 const char *value)
1809 {
1810 fprintf_filtered (file, _("The maximum number of target hardware "
1811 "watchpoints is %s.\n"), value);
1812 }
1813
1814 /* Show the length limit (in bytes) for hardware watchpoints. */
1815
1816 static void
1817 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
1818 struct cmd_list_element *c,
1819 const char *value)
1820 {
1821 fprintf_filtered (file, _("The maximum length (in bytes) of a target "
1822 "hardware watchpoint is %s.\n"), value);
1823 }
1824
1825 /* Show the number of hardware breakpoints that can be used. */
1826
1827 static void
1828 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
1829 struct cmd_list_element *c,
1830 const char *value)
1831 {
1832 fprintf_filtered (file, _("The maximum number of target hardware "
1833 "breakpoints is %s.\n"), value);
1834 }
1835
1836 /* Controls the maximum number of characters to display in the debug output
1837 for each remote packet. The remaining characters are omitted. */
1838
1839 static int remote_packet_max_chars = 512;
1840
1841 /* Show the maximum number of characters to display for each remote packet
1842 when remote debugging is enabled. */
1843
1844 static void
1845 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
1846 struct cmd_list_element *c,
1847 const char *value)
1848 {
1849 fprintf_filtered (file, _("Number of remote packet characters to "
1850 "display is %s.\n"), value);
1851 }
1852
1853 long
1854 remote_target::get_memory_write_packet_size ()
1855 {
1856 return get_memory_packet_size (&memory_write_packet_config);
1857 }
1858
1859 /* FIXME: needs to be per-remote-target. */
1860 static struct memory_packet_config memory_read_packet_config =
1861 {
1862 "memory-read-packet-size",
1863 };
1864
1865 static void
1866 set_memory_read_packet_size (const char *args, int from_tty)
1867 {
1868 set_memory_packet_size (args, &memory_read_packet_config);
1869 }
1870
1871 static void
1872 show_memory_read_packet_size (const char *args, int from_tty)
1873 {
1874 show_memory_packet_size (&memory_read_packet_config);
1875 }
1876
1877 long
1878 remote_target::get_memory_read_packet_size ()
1879 {
1880 long size = get_memory_packet_size (&memory_read_packet_config);
1881
1882 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1883 extra buffer size argument before the memory read size can be
1884 increased beyond this. */
1885 if (size > get_remote_packet_size ())
1886 size = get_remote_packet_size ();
1887 return size;
1888 }
1889
1890 \f
1891
1892 struct packet_config
1893 {
1894 const char *name;
1895 const char *title;
1896
1897 /* If auto, GDB auto-detects support for this packet or feature,
1898 either through qSupported, or by trying the packet and looking
1899 at the response. If true, GDB assumes the target supports this
1900 packet. If false, the packet is disabled. Configs that don't
1901 have an associated command always have this set to auto. */
1902 enum auto_boolean detect;
1903
1904 /* The "show remote foo-packet" command created for this packet. */
1905 cmd_list_element *show_cmd;
1906
1907 /* Does the target support this packet? */
1908 enum packet_support support;
1909 };
1910
1911 static enum packet_support packet_config_support (struct packet_config *config);
1912 static enum packet_support packet_support (int packet);
1913
1914 static void
1915 show_packet_config_cmd (struct packet_config *config)
1916 {
1917 const char *support = "internal-error";
1918
1919 switch (packet_config_support (config))
1920 {
1921 case PACKET_ENABLE:
1922 support = "enabled";
1923 break;
1924 case PACKET_DISABLE:
1925 support = "disabled";
1926 break;
1927 case PACKET_SUPPORT_UNKNOWN:
1928 support = "unknown";
1929 break;
1930 }
1931 switch (config->detect)
1932 {
1933 case AUTO_BOOLEAN_AUTO:
1934 printf_filtered (_("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 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1941 config->name, support);
1942 break;
1943 }
1944 }
1945
1946 static void
1947 add_packet_config_cmd (struct packet_config *config, const char *name,
1948 const char *title, int legacy)
1949 {
1950 config->name = name;
1951 config->title = title;
1952 gdb::unique_xmalloc_ptr<char> set_doc
1953 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
1954 name, title);
1955 gdb::unique_xmalloc_ptr<char> show_doc
1956 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
1957 name, title);
1958 /* set/show TITLE-packet {auto,on,off} */
1959 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
1960 set_show_commands cmds
1961 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
1962 &config->detect, set_doc.get (),
1963 show_doc.get (), NULL, /* help_doc */
1964 NULL,
1965 show_remote_protocol_packet_cmd,
1966 &remote_set_cmdlist, &remote_show_cmdlist);
1967 config->show_cmd = cmds.show;
1968
1969 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1970 if (legacy)
1971 {
1972 /* It's not clear who should take ownership of this string, so, for
1973 now, make it static, and give copies to each of the add_alias_cmd
1974 calls below. */
1975 static gdb::unique_xmalloc_ptr<char> legacy_name
1976 = xstrprintf ("%s-packet", name);
1977 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
1978 &remote_set_cmdlist);
1979 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
1980 &remote_show_cmdlist);
1981 }
1982 }
1983
1984 static enum packet_result
1985 packet_check_result (const char *buf)
1986 {
1987 if (buf[0] != '\0')
1988 {
1989 /* The stub recognized the packet request. Check that the
1990 operation succeeded. */
1991 if (buf[0] == 'E'
1992 && isxdigit (buf[1]) && isxdigit (buf[2])
1993 && buf[3] == '\0')
1994 /* "Enn" - definitely an error. */
1995 return PACKET_ERROR;
1996
1997 /* Always treat "E." as an error. This will be used for
1998 more verbose error messages, such as E.memtypes. */
1999 if (buf[0] == 'E' && buf[1] == '.')
2000 return PACKET_ERROR;
2001
2002 /* The packet may or may not be OK. Just assume it is. */
2003 return PACKET_OK;
2004 }
2005 else
2006 /* The stub does not support the packet. */
2007 return PACKET_UNKNOWN;
2008 }
2009
2010 static enum packet_result
2011 packet_check_result (const gdb::char_vector &buf)
2012 {
2013 return packet_check_result (buf.data ());
2014 }
2015
2016 static enum packet_result
2017 packet_ok (const char *buf, struct packet_config *config)
2018 {
2019 enum packet_result result;
2020
2021 if (config->detect != AUTO_BOOLEAN_TRUE
2022 && config->support == PACKET_DISABLE)
2023 internal_error (__FILE__, __LINE__,
2024 _("packet_ok: attempt to use a disabled packet"));
2025
2026 result = packet_check_result (buf);
2027 switch (result)
2028 {
2029 case PACKET_OK:
2030 case PACKET_ERROR:
2031 /* The stub recognized the packet request. */
2032 if (config->support == PACKET_SUPPORT_UNKNOWN)
2033 {
2034 remote_debug_printf ("Packet %s (%s) is supported",
2035 config->name, config->title);
2036 config->support = PACKET_ENABLE;
2037 }
2038 break;
2039 case PACKET_UNKNOWN:
2040 /* The stub does not support the packet. */
2041 if (config->detect == AUTO_BOOLEAN_AUTO
2042 && config->support == PACKET_ENABLE)
2043 {
2044 /* If the stub previously indicated that the packet was
2045 supported then there is a protocol error. */
2046 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2047 config->name, config->title);
2048 }
2049 else if (config->detect == AUTO_BOOLEAN_TRUE)
2050 {
2051 /* The user set it wrong. */
2052 error (_("Enabled packet %s (%s) not recognized by stub"),
2053 config->name, config->title);
2054 }
2055
2056 remote_debug_printf ("Packet %s (%s) is NOT supported",
2057 config->name, config->title);
2058 config->support = PACKET_DISABLE;
2059 break;
2060 }
2061
2062 return result;
2063 }
2064
2065 static enum packet_result
2066 packet_ok (const gdb::char_vector &buf, struct packet_config *config)
2067 {
2068 return packet_ok (buf.data (), config);
2069 }
2070
2071 enum {
2072 PACKET_vCont = 0,
2073 PACKET_X,
2074 PACKET_qSymbol,
2075 PACKET_P,
2076 PACKET_p,
2077 PACKET_Z0,
2078 PACKET_Z1,
2079 PACKET_Z2,
2080 PACKET_Z3,
2081 PACKET_Z4,
2082 PACKET_vFile_setfs,
2083 PACKET_vFile_open,
2084 PACKET_vFile_pread,
2085 PACKET_vFile_pwrite,
2086 PACKET_vFile_close,
2087 PACKET_vFile_unlink,
2088 PACKET_vFile_readlink,
2089 PACKET_vFile_fstat,
2090 PACKET_qXfer_auxv,
2091 PACKET_qXfer_features,
2092 PACKET_qXfer_exec_file,
2093 PACKET_qXfer_libraries,
2094 PACKET_qXfer_libraries_svr4,
2095 PACKET_qXfer_memory_map,
2096 PACKET_qXfer_osdata,
2097 PACKET_qXfer_threads,
2098 PACKET_qXfer_statictrace_read,
2099 PACKET_qXfer_traceframe_info,
2100 PACKET_qXfer_uib,
2101 PACKET_qGetTIBAddr,
2102 PACKET_qGetTLSAddr,
2103 PACKET_qSupported,
2104 PACKET_qTStatus,
2105 PACKET_QPassSignals,
2106 PACKET_QCatchSyscalls,
2107 PACKET_QProgramSignals,
2108 PACKET_QSetWorkingDir,
2109 PACKET_QStartupWithShell,
2110 PACKET_QEnvironmentHexEncoded,
2111 PACKET_QEnvironmentReset,
2112 PACKET_QEnvironmentUnset,
2113 PACKET_qCRC,
2114 PACKET_qSearch_memory,
2115 PACKET_vAttach,
2116 PACKET_vRun,
2117 PACKET_QStartNoAckMode,
2118 PACKET_vKill,
2119 PACKET_qXfer_siginfo_read,
2120 PACKET_qXfer_siginfo_write,
2121 PACKET_qAttached,
2122
2123 /* Support for conditional tracepoints. */
2124 PACKET_ConditionalTracepoints,
2125
2126 /* Support for target-side breakpoint conditions. */
2127 PACKET_ConditionalBreakpoints,
2128
2129 /* Support for target-side breakpoint commands. */
2130 PACKET_BreakpointCommands,
2131
2132 /* Support for fast tracepoints. */
2133 PACKET_FastTracepoints,
2134
2135 /* Support for static tracepoints. */
2136 PACKET_StaticTracepoints,
2137
2138 /* Support for installing tracepoints while a trace experiment is
2139 running. */
2140 PACKET_InstallInTrace,
2141
2142 PACKET_bc,
2143 PACKET_bs,
2144 PACKET_TracepointSource,
2145 PACKET_QAllow,
2146 PACKET_qXfer_fdpic,
2147 PACKET_QDisableRandomization,
2148 PACKET_QAgent,
2149 PACKET_QTBuffer_size,
2150 PACKET_Qbtrace_off,
2151 PACKET_Qbtrace_bts,
2152 PACKET_Qbtrace_pt,
2153 PACKET_qXfer_btrace,
2154
2155 /* Support for the QNonStop packet. */
2156 PACKET_QNonStop,
2157
2158 /* Support for the QThreadEvents packet. */
2159 PACKET_QThreadEvents,
2160
2161 /* Support for multi-process extensions. */
2162 PACKET_multiprocess_feature,
2163
2164 /* Support for enabling and disabling tracepoints while a trace
2165 experiment is running. */
2166 PACKET_EnableDisableTracepoints_feature,
2167
2168 /* Support for collecting strings using the tracenz bytecode. */
2169 PACKET_tracenz_feature,
2170
2171 /* Support for continuing to run a trace experiment while GDB is
2172 disconnected. */
2173 PACKET_DisconnectedTracing_feature,
2174
2175 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2176 PACKET_augmented_libraries_svr4_read_feature,
2177
2178 /* Support for the qXfer:btrace-conf:read packet. */
2179 PACKET_qXfer_btrace_conf,
2180
2181 /* Support for the Qbtrace-conf:bts:size packet. */
2182 PACKET_Qbtrace_conf_bts_size,
2183
2184 /* Support for swbreak+ feature. */
2185 PACKET_swbreak_feature,
2186
2187 /* Support for hwbreak+ feature. */
2188 PACKET_hwbreak_feature,
2189
2190 /* Support for fork events. */
2191 PACKET_fork_event_feature,
2192
2193 /* Support for vfork events. */
2194 PACKET_vfork_event_feature,
2195
2196 /* Support for the Qbtrace-conf:pt:size packet. */
2197 PACKET_Qbtrace_conf_pt_size,
2198
2199 /* Support for exec events. */
2200 PACKET_exec_event_feature,
2201
2202 /* Support for query supported vCont actions. */
2203 PACKET_vContSupported,
2204
2205 /* Support remote CTRL-C. */
2206 PACKET_vCtrlC,
2207
2208 /* Support TARGET_WAITKIND_NO_RESUMED. */
2209 PACKET_no_resumed,
2210
2211 /* Support for memory tagging, allocation tag fetch/store
2212 packets and the tag violation stop replies. */
2213 PACKET_memory_tagging_feature,
2214
2215 PACKET_MAX
2216 };
2217
2218 /* FIXME: needs to be per-remote-target. Ignoring this for now,
2219 assuming all remote targets are the same server (thus all support
2220 the same packets). */
2221 static struct packet_config remote_protocol_packets[PACKET_MAX];
2222
2223 /* Returns the packet's corresponding "set remote foo-packet" command
2224 state. See struct packet_config for more details. */
2225
2226 static enum auto_boolean
2227 packet_set_cmd_state (int packet)
2228 {
2229 return remote_protocol_packets[packet].detect;
2230 }
2231
2232 /* Returns whether a given packet or feature is supported. This takes
2233 into account the state of the corresponding "set remote foo-packet"
2234 command, which may be used to bypass auto-detection. */
2235
2236 static enum packet_support
2237 packet_config_support (struct packet_config *config)
2238 {
2239 switch (config->detect)
2240 {
2241 case AUTO_BOOLEAN_TRUE:
2242 return PACKET_ENABLE;
2243 case AUTO_BOOLEAN_FALSE:
2244 return PACKET_DISABLE;
2245 case AUTO_BOOLEAN_AUTO:
2246 return config->support;
2247 default:
2248 gdb_assert_not_reached ("bad switch");
2249 }
2250 }
2251
2252 /* Same as packet_config_support, but takes the packet's enum value as
2253 argument. */
2254
2255 static enum packet_support
2256 packet_support (int packet)
2257 {
2258 struct packet_config *config = &remote_protocol_packets[packet];
2259
2260 return packet_config_support (config);
2261 }
2262
2263 static void
2264 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2265 struct cmd_list_element *c,
2266 const char *value)
2267 {
2268 struct packet_config *packet;
2269 gdb_assert (c->var.has_value ());
2270
2271 for (packet = remote_protocol_packets;
2272 packet < &remote_protocol_packets[PACKET_MAX];
2273 packet++)
2274 {
2275 if (c == packet->show_cmd)
2276 {
2277 show_packet_config_cmd (packet);
2278 return;
2279 }
2280 }
2281 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
2282 c->name);
2283 }
2284
2285 /* Should we try one of the 'Z' requests? */
2286
2287 enum Z_packet_type
2288 {
2289 Z_PACKET_SOFTWARE_BP,
2290 Z_PACKET_HARDWARE_BP,
2291 Z_PACKET_WRITE_WP,
2292 Z_PACKET_READ_WP,
2293 Z_PACKET_ACCESS_WP,
2294 NR_Z_PACKET_TYPES
2295 };
2296
2297 /* For compatibility with older distributions. Provide a ``set remote
2298 Z-packet ...'' command that updates all the Z packet types. */
2299
2300 static enum auto_boolean remote_Z_packet_detect;
2301
2302 static void
2303 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2304 struct cmd_list_element *c)
2305 {
2306 int i;
2307
2308 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2309 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2310 }
2311
2312 static void
2313 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2314 struct cmd_list_element *c,
2315 const char *value)
2316 {
2317 int i;
2318
2319 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2320 {
2321 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
2322 }
2323 }
2324
2325 /* Returns true if the multi-process extensions are in effect. */
2326
2327 static int
2328 remote_multi_process_p (struct remote_state *rs)
2329 {
2330 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2331 }
2332
2333 /* Returns true if fork events are supported. */
2334
2335 static int
2336 remote_fork_event_p (struct remote_state *rs)
2337 {
2338 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2339 }
2340
2341 /* Returns true if vfork events are supported. */
2342
2343 static int
2344 remote_vfork_event_p (struct remote_state *rs)
2345 {
2346 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2347 }
2348
2349 /* Returns true if exec events are supported. */
2350
2351 static int
2352 remote_exec_event_p (struct remote_state *rs)
2353 {
2354 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2355 }
2356
2357 /* Returns true if memory tagging is supported, false otherwise. */
2358
2359 static bool
2360 remote_memory_tagging_p ()
2361 {
2362 return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE;
2363 }
2364
2365 /* Insert fork catchpoint target routine. If fork events are enabled
2366 then return success, nothing more to do. */
2367
2368 int
2369 remote_target::insert_fork_catchpoint (int pid)
2370 {
2371 struct remote_state *rs = get_remote_state ();
2372
2373 return !remote_fork_event_p (rs);
2374 }
2375
2376 /* Remove fork catchpoint target routine. Nothing to do, just
2377 return success. */
2378
2379 int
2380 remote_target::remove_fork_catchpoint (int pid)
2381 {
2382 return 0;
2383 }
2384
2385 /* Insert vfork catchpoint target routine. If vfork events are enabled
2386 then return success, nothing more to do. */
2387
2388 int
2389 remote_target::insert_vfork_catchpoint (int pid)
2390 {
2391 struct remote_state *rs = get_remote_state ();
2392
2393 return !remote_vfork_event_p (rs);
2394 }
2395
2396 /* Remove vfork catchpoint target routine. Nothing to do, just
2397 return success. */
2398
2399 int
2400 remote_target::remove_vfork_catchpoint (int pid)
2401 {
2402 return 0;
2403 }
2404
2405 /* Insert exec catchpoint target routine. If exec events are
2406 enabled, just return success. */
2407
2408 int
2409 remote_target::insert_exec_catchpoint (int pid)
2410 {
2411 struct remote_state *rs = get_remote_state ();
2412
2413 return !remote_exec_event_p (rs);
2414 }
2415
2416 /* Remove exec catchpoint target routine. Nothing to do, just
2417 return success. */
2418
2419 int
2420 remote_target::remove_exec_catchpoint (int pid)
2421 {
2422 return 0;
2423 }
2424
2425 \f
2426
2427 /* Take advantage of the fact that the TID field is not used, to tag
2428 special ptids with it set to != 0. */
2429 static const ptid_t magic_null_ptid (42000, -1, 1);
2430 static const ptid_t not_sent_ptid (42000, -2, 1);
2431 static const ptid_t any_thread_ptid (42000, 0, 1);
2432
2433 /* Find out if the stub attached to PID (and hence GDB should offer to
2434 detach instead of killing it when bailing out). */
2435
2436 int
2437 remote_target::remote_query_attached (int pid)
2438 {
2439 struct remote_state *rs = get_remote_state ();
2440 size_t size = get_remote_packet_size ();
2441
2442 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2443 return 0;
2444
2445 if (remote_multi_process_p (rs))
2446 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2447 else
2448 xsnprintf (rs->buf.data (), size, "qAttached");
2449
2450 putpkt (rs->buf);
2451 getpkt (&rs->buf, 0);
2452
2453 switch (packet_ok (rs->buf,
2454 &remote_protocol_packets[PACKET_qAttached]))
2455 {
2456 case PACKET_OK:
2457 if (strcmp (rs->buf.data (), "1") == 0)
2458 return 1;
2459 break;
2460 case PACKET_ERROR:
2461 warning (_("Remote failure reply: %s"), rs->buf.data ());
2462 break;
2463 case PACKET_UNKNOWN:
2464 break;
2465 }
2466
2467 return 0;
2468 }
2469
2470 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2471 has been invented by GDB, instead of reported by the target. Since
2472 we can be connected to a remote system before before knowing about
2473 any inferior, mark the target with execution when we find the first
2474 inferior. If ATTACHED is 1, then we had just attached to this
2475 inferior. If it is 0, then we just created this inferior. If it
2476 is -1, then try querying the remote stub to find out if it had
2477 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2478 attempt to open this inferior's executable as the main executable
2479 if no main executable is open already. */
2480
2481 inferior *
2482 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2483 int try_open_exec)
2484 {
2485 struct inferior *inf;
2486
2487 /* Check whether this process we're learning about is to be
2488 considered attached, or if is to be considered to have been
2489 spawned by the stub. */
2490 if (attached == -1)
2491 attached = remote_query_attached (pid);
2492
2493 if (gdbarch_has_global_solist (target_gdbarch ()))
2494 {
2495 /* If the target shares code across all inferiors, then every
2496 attach adds a new inferior. */
2497 inf = add_inferior (pid);
2498
2499 /* ... and every inferior is bound to the same program space.
2500 However, each inferior may still have its own address
2501 space. */
2502 inf->aspace = maybe_new_address_space ();
2503 inf->pspace = current_program_space;
2504 }
2505 else
2506 {
2507 /* In the traditional debugging scenario, there's a 1-1 match
2508 between program/address spaces. We simply bind the inferior
2509 to the program space's address space. */
2510 inf = current_inferior ();
2511
2512 /* However, if the current inferior is already bound to a
2513 process, find some other empty inferior. */
2514 if (inf->pid != 0)
2515 {
2516 inf = nullptr;
2517 for (inferior *it : all_inferiors ())
2518 if (it->pid == 0)
2519 {
2520 inf = it;
2521 break;
2522 }
2523 }
2524 if (inf == nullptr)
2525 {
2526 /* Since all inferiors were already bound to a process, add
2527 a new inferior. */
2528 inf = add_inferior_with_spaces ();
2529 }
2530 switch_to_inferior_no_thread (inf);
2531 inf->push_target (this);
2532 inferior_appeared (inf, pid);
2533 }
2534
2535 inf->attach_flag = attached;
2536 inf->fake_pid_p = fake_pid_p;
2537
2538 /* If no main executable is currently open then attempt to
2539 open the file that was executed to create this inferior. */
2540 if (try_open_exec && get_exec_file (0) == NULL)
2541 exec_file_locate_attach (pid, 0, 1);
2542
2543 /* Check for exec file mismatch, and let the user solve it. */
2544 validate_exec_file (1);
2545
2546 return inf;
2547 }
2548
2549 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2550 static remote_thread_info *get_remote_thread_info (remote_target *target,
2551 ptid_t ptid);
2552
2553 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2554 according to RUNNING. */
2555
2556 thread_info *
2557 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing)
2558 {
2559 struct remote_state *rs = get_remote_state ();
2560 struct thread_info *thread;
2561
2562 /* GDB historically didn't pull threads in the initial connection
2563 setup. If the remote target doesn't even have a concept of
2564 threads (e.g., a bare-metal target), even if internally we
2565 consider that a single-threaded target, mentioning a new thread
2566 might be confusing to the user. Be silent then, preserving the
2567 age old behavior. */
2568 if (rs->starting_up)
2569 thread = add_thread_silent (this, ptid);
2570 else
2571 thread = add_thread (this, ptid);
2572
2573 /* We start by assuming threads are resumed. That state then gets updated
2574 when we process a matching stop reply. */
2575 get_remote_thread_info (thread)->set_resumed ();
2576
2577 set_executing (this, ptid, executing);
2578 set_running (this, ptid, running);
2579
2580 return thread;
2581 }
2582
2583 /* Come here when we learn about a thread id from the remote target.
2584 It may be the first time we hear about such thread, so take the
2585 opportunity to add it to GDB's thread list. In case this is the
2586 first time we're noticing its corresponding inferior, add it to
2587 GDB's inferior list as well. EXECUTING indicates whether the
2588 thread is (internally) executing or stopped. */
2589
2590 void
2591 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2592 {
2593 /* In non-stop mode, we assume new found threads are (externally)
2594 running until proven otherwise with a stop reply. In all-stop,
2595 we can only get here if all threads are stopped. */
2596 bool running = target_is_non_stop_p ();
2597
2598 /* If this is a new thread, add it to GDB's thread list.
2599 If we leave it up to WFI to do this, bad things will happen. */
2600
2601 thread_info *tp = find_thread_ptid (this, currthread);
2602 if (tp != NULL && tp->state == THREAD_EXITED)
2603 {
2604 /* We're seeing an event on a thread id we knew had exited.
2605 This has to be a new thread reusing the old id. Add it. */
2606 remote_add_thread (currthread, running, executing);
2607 return;
2608 }
2609
2610 if (!in_thread_list (this, currthread))
2611 {
2612 struct inferior *inf = NULL;
2613 int pid = currthread.pid ();
2614
2615 if (inferior_ptid.is_pid ()
2616 && pid == inferior_ptid.pid ())
2617 {
2618 /* inferior_ptid has no thread member yet. This can happen
2619 with the vAttach -> remote_wait,"TAAthread:" path if the
2620 stub doesn't support qC. This is the first stop reported
2621 after an attach, so this is the main thread. Update the
2622 ptid in the thread list. */
2623 if (in_thread_list (this, ptid_t (pid)))
2624 thread_change_ptid (this, inferior_ptid, currthread);
2625 else
2626 {
2627 thread_info *thr
2628 = remote_add_thread (currthread, running, executing);
2629 switch_to_thread (thr);
2630 }
2631 return;
2632 }
2633
2634 if (magic_null_ptid == inferior_ptid)
2635 {
2636 /* inferior_ptid is not set yet. This can happen with the
2637 vRun -> remote_wait,"TAAthread:" path if the stub
2638 doesn't support qC. This is the first stop reported
2639 after an attach, so this is the main thread. Update the
2640 ptid in the thread list. */
2641 thread_change_ptid (this, inferior_ptid, currthread);
2642 return;
2643 }
2644
2645 /* When connecting to a target remote, or to a target
2646 extended-remote which already was debugging an inferior, we
2647 may not know about it yet. Add it before adding its child
2648 thread, so notifications are emitted in a sensible order. */
2649 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2650 {
2651 struct remote_state *rs = get_remote_state ();
2652 bool fake_pid_p = !remote_multi_process_p (rs);
2653
2654 inf = remote_add_inferior (fake_pid_p,
2655 currthread.pid (), -1, 1);
2656 }
2657
2658 /* This is really a new thread. Add it. */
2659 thread_info *new_thr
2660 = remote_add_thread (currthread, running, executing);
2661
2662 /* If we found a new inferior, let the common code do whatever
2663 it needs to with it (e.g., read shared libraries, insert
2664 breakpoints), unless we're just setting up an all-stop
2665 connection. */
2666 if (inf != NULL)
2667 {
2668 struct remote_state *rs = get_remote_state ();
2669
2670 if (!rs->starting_up)
2671 notice_new_inferior (new_thr, executing, 0);
2672 }
2673 }
2674 }
2675
2676 /* Return THREAD's private thread data, creating it if necessary. */
2677
2678 static remote_thread_info *
2679 get_remote_thread_info (thread_info *thread)
2680 {
2681 gdb_assert (thread != NULL);
2682
2683 if (thread->priv == NULL)
2684 thread->priv.reset (new remote_thread_info);
2685
2686 return static_cast<remote_thread_info *> (thread->priv.get ());
2687 }
2688
2689 /* Return PTID's private thread data, creating it if necessary. */
2690
2691 static remote_thread_info *
2692 get_remote_thread_info (remote_target *target, ptid_t ptid)
2693 {
2694 thread_info *thr = find_thread_ptid (target, ptid);
2695 return get_remote_thread_info (thr);
2696 }
2697
2698 /* Call this function as a result of
2699 1) A halt indication (T packet) containing a thread id
2700 2) A direct query of currthread
2701 3) Successful execution of set thread */
2702
2703 static void
2704 record_currthread (struct remote_state *rs, ptid_t currthread)
2705 {
2706 rs->general_thread = currthread;
2707 }
2708
2709 /* If 'QPassSignals' is supported, tell the remote stub what signals
2710 it can simply pass through to the inferior without reporting. */
2711
2712 void
2713 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2714 {
2715 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2716 {
2717 char *pass_packet, *p;
2718 int count = 0;
2719 struct remote_state *rs = get_remote_state ();
2720
2721 gdb_assert (pass_signals.size () < 256);
2722 for (size_t i = 0; i < pass_signals.size (); i++)
2723 {
2724 if (pass_signals[i])
2725 count++;
2726 }
2727 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2728 strcpy (pass_packet, "QPassSignals:");
2729 p = pass_packet + strlen (pass_packet);
2730 for (size_t i = 0; i < pass_signals.size (); i++)
2731 {
2732 if (pass_signals[i])
2733 {
2734 if (i >= 16)
2735 *p++ = tohex (i >> 4);
2736 *p++ = tohex (i & 15);
2737 if (count)
2738 *p++ = ';';
2739 else
2740 break;
2741 count--;
2742 }
2743 }
2744 *p = 0;
2745 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2746 {
2747 putpkt (pass_packet);
2748 getpkt (&rs->buf, 0);
2749 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2750 xfree (rs->last_pass_packet);
2751 rs->last_pass_packet = pass_packet;
2752 }
2753 else
2754 xfree (pass_packet);
2755 }
2756 }
2757
2758 /* If 'QCatchSyscalls' is supported, tell the remote stub
2759 to report syscalls to GDB. */
2760
2761 int
2762 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2763 gdb::array_view<const int> syscall_counts)
2764 {
2765 const char *catch_packet;
2766 enum packet_result result;
2767 int n_sysno = 0;
2768
2769 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2770 {
2771 /* Not supported. */
2772 return 1;
2773 }
2774
2775 if (needed && any_count == 0)
2776 {
2777 /* Count how many syscalls are to be caught. */
2778 for (size_t i = 0; i < syscall_counts.size (); i++)
2779 {
2780 if (syscall_counts[i] != 0)
2781 n_sysno++;
2782 }
2783 }
2784
2785 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
2786 pid, needed, any_count, n_sysno);
2787
2788 std::string built_packet;
2789 if (needed)
2790 {
2791 /* Prepare a packet with the sysno list, assuming max 8+1
2792 characters for a sysno. If the resulting packet size is too
2793 big, fallback on the non-selective packet. */
2794 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2795 built_packet.reserve (maxpktsz);
2796 built_packet = "QCatchSyscalls:1";
2797 if (any_count == 0)
2798 {
2799 /* Add in each syscall to be caught. */
2800 for (size_t i = 0; i < syscall_counts.size (); i++)
2801 {
2802 if (syscall_counts[i] != 0)
2803 string_appendf (built_packet, ";%zx", i);
2804 }
2805 }
2806 if (built_packet.size () > get_remote_packet_size ())
2807 {
2808 /* catch_packet too big. Fallback to less efficient
2809 non selective mode, with GDB doing the filtering. */
2810 catch_packet = "QCatchSyscalls:1";
2811 }
2812 else
2813 catch_packet = built_packet.c_str ();
2814 }
2815 else
2816 catch_packet = "QCatchSyscalls:0";
2817
2818 struct remote_state *rs = get_remote_state ();
2819
2820 putpkt (catch_packet);
2821 getpkt (&rs->buf, 0);
2822 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2823 if (result == PACKET_OK)
2824 return 0;
2825 else
2826 return -1;
2827 }
2828
2829 /* If 'QProgramSignals' is supported, tell the remote stub what
2830 signals it should pass through to the inferior when detaching. */
2831
2832 void
2833 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
2834 {
2835 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2836 {
2837 char *packet, *p;
2838 int count = 0;
2839 struct remote_state *rs = get_remote_state ();
2840
2841 gdb_assert (signals.size () < 256);
2842 for (size_t i = 0; i < signals.size (); i++)
2843 {
2844 if (signals[i])
2845 count++;
2846 }
2847 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2848 strcpy (packet, "QProgramSignals:");
2849 p = packet + strlen (packet);
2850 for (size_t i = 0; i < signals.size (); i++)
2851 {
2852 if (signal_pass_state (i))
2853 {
2854 if (i >= 16)
2855 *p++ = tohex (i >> 4);
2856 *p++ = tohex (i & 15);
2857 if (count)
2858 *p++ = ';';
2859 else
2860 break;
2861 count--;
2862 }
2863 }
2864 *p = 0;
2865 if (!rs->last_program_signals_packet
2866 || strcmp (rs->last_program_signals_packet, packet) != 0)
2867 {
2868 putpkt (packet);
2869 getpkt (&rs->buf, 0);
2870 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2871 xfree (rs->last_program_signals_packet);
2872 rs->last_program_signals_packet = packet;
2873 }
2874 else
2875 xfree (packet);
2876 }
2877 }
2878
2879 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2880 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2881 thread. If GEN is set, set the general thread, if not, then set
2882 the step/continue thread. */
2883 void
2884 remote_target::set_thread (ptid_t ptid, int gen)
2885 {
2886 struct remote_state *rs = get_remote_state ();
2887 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2888 char *buf = rs->buf.data ();
2889 char *endbuf = buf + get_remote_packet_size ();
2890
2891 if (state == ptid)
2892 return;
2893
2894 *buf++ = 'H';
2895 *buf++ = gen ? 'g' : 'c';
2896 if (ptid == magic_null_ptid)
2897 xsnprintf (buf, endbuf - buf, "0");
2898 else if (ptid == any_thread_ptid)
2899 xsnprintf (buf, endbuf - buf, "0");
2900 else if (ptid == minus_one_ptid)
2901 xsnprintf (buf, endbuf - buf, "-1");
2902 else
2903 write_ptid (buf, endbuf, ptid);
2904 putpkt (rs->buf);
2905 getpkt (&rs->buf, 0);
2906 if (gen)
2907 rs->general_thread = ptid;
2908 else
2909 rs->continue_thread = ptid;
2910 }
2911
2912 void
2913 remote_target::set_general_thread (ptid_t ptid)
2914 {
2915 set_thread (ptid, 1);
2916 }
2917
2918 void
2919 remote_target::set_continue_thread (ptid_t ptid)
2920 {
2921 set_thread (ptid, 0);
2922 }
2923
2924 /* Change the remote current process. Which thread within the process
2925 ends up selected isn't important, as long as it is the same process
2926 as what INFERIOR_PTID points to.
2927
2928 This comes from that fact that there is no explicit notion of
2929 "selected process" in the protocol. The selected process for
2930 general operations is the process the selected general thread
2931 belongs to. */
2932
2933 void
2934 remote_target::set_general_process ()
2935 {
2936 struct remote_state *rs = get_remote_state ();
2937
2938 /* If the remote can't handle multiple processes, don't bother. */
2939 if (!remote_multi_process_p (rs))
2940 return;
2941
2942 /* We only need to change the remote current thread if it's pointing
2943 at some other process. */
2944 if (rs->general_thread.pid () != inferior_ptid.pid ())
2945 set_general_thread (inferior_ptid);
2946 }
2947
2948 \f
2949 /* Return nonzero if this is the main thread that we made up ourselves
2950 to model non-threaded targets as single-threaded. */
2951
2952 static int
2953 remote_thread_always_alive (ptid_t ptid)
2954 {
2955 if (ptid == magic_null_ptid)
2956 /* The main thread is always alive. */
2957 return 1;
2958
2959 if (ptid.pid () != 0 && ptid.lwp () == 0)
2960 /* The main thread is always alive. This can happen after a
2961 vAttach, if the remote side doesn't support
2962 multi-threading. */
2963 return 1;
2964
2965 return 0;
2966 }
2967
2968 /* Return nonzero if the thread PTID is still alive on the remote
2969 system. */
2970
2971 bool
2972 remote_target::thread_alive (ptid_t ptid)
2973 {
2974 struct remote_state *rs = get_remote_state ();
2975 char *p, *endp;
2976
2977 /* Check if this is a thread that we made up ourselves to model
2978 non-threaded targets as single-threaded. */
2979 if (remote_thread_always_alive (ptid))
2980 return 1;
2981
2982 p = rs->buf.data ();
2983 endp = p + get_remote_packet_size ();
2984
2985 *p++ = 'T';
2986 write_ptid (p, endp, ptid);
2987
2988 putpkt (rs->buf);
2989 getpkt (&rs->buf, 0);
2990 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2991 }
2992
2993 /* Return a pointer to a thread name if we know it and NULL otherwise.
2994 The thread_info object owns the memory for the name. */
2995
2996 const char *
2997 remote_target::thread_name (struct thread_info *info)
2998 {
2999 if (info->priv != NULL)
3000 {
3001 const std::string &name = get_remote_thread_info (info)->name;
3002 return !name.empty () ? name.c_str () : NULL;
3003 }
3004
3005 return NULL;
3006 }
3007
3008 /* About these extended threadlist and threadinfo packets. They are
3009 variable length packets but, the fields within them are often fixed
3010 length. They are redundant enough to send over UDP as is the
3011 remote protocol in general. There is a matching unit test module
3012 in libstub. */
3013
3014 /* WARNING: This threadref data structure comes from the remote O.S.,
3015 libstub protocol encoding, and remote.c. It is not particularly
3016 changable. */
3017
3018 /* Right now, the internal structure is int. We want it to be bigger.
3019 Plan to fix this. */
3020
3021 typedef int gdb_threadref; /* Internal GDB thread reference. */
3022
3023 /* gdb_ext_thread_info is an internal GDB data structure which is
3024 equivalent to the reply of the remote threadinfo packet. */
3025
3026 struct gdb_ext_thread_info
3027 {
3028 threadref threadid; /* External form of thread reference. */
3029 int active; /* Has state interesting to GDB?
3030 regs, stack. */
3031 char display[256]; /* Brief state display, name,
3032 blocked/suspended. */
3033 char shortname[32]; /* To be used to name threads. */
3034 char more_display[256]; /* Long info, statistics, queue depth,
3035 whatever. */
3036 };
3037
3038 /* The volume of remote transfers can be limited by submitting
3039 a mask containing bits specifying the desired information.
3040 Use a union of these values as the 'selection' parameter to
3041 get_thread_info. FIXME: Make these TAG names more thread specific. */
3042
3043 #define TAG_THREADID 1
3044 #define TAG_EXISTS 2
3045 #define TAG_DISPLAY 4
3046 #define TAG_THREADNAME 8
3047 #define TAG_MOREDISPLAY 16
3048
3049 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3050
3051 static const char *unpack_nibble (const char *buf, int *val);
3052
3053 static const char *unpack_byte (const char *buf, int *value);
3054
3055 static char *pack_int (char *buf, int value);
3056
3057 static const char *unpack_int (const char *buf, int *value);
3058
3059 static const char *unpack_string (const char *src, char *dest, int length);
3060
3061 static char *pack_threadid (char *pkt, threadref *id);
3062
3063 static const char *unpack_threadid (const char *inbuf, threadref *id);
3064
3065 void int_to_threadref (threadref *id, int value);
3066
3067 static int threadref_to_int (threadref *ref);
3068
3069 static void copy_threadref (threadref *dest, threadref *src);
3070
3071 static int threadmatch (threadref *dest, threadref *src);
3072
3073 static char *pack_threadinfo_request (char *pkt, int mode,
3074 threadref *id);
3075
3076 static char *pack_threadlist_request (char *pkt, int startflag,
3077 int threadcount,
3078 threadref *nextthread);
3079
3080 static int remote_newthread_step (threadref *ref, void *context);
3081
3082
3083 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3084 buffer we're allowed to write to. Returns
3085 BUF+CHARACTERS_WRITTEN. */
3086
3087 char *
3088 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3089 {
3090 int pid, tid;
3091 struct remote_state *rs = get_remote_state ();
3092
3093 if (remote_multi_process_p (rs))
3094 {
3095 pid = ptid.pid ();
3096 if (pid < 0)
3097 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3098 else
3099 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3100 }
3101 tid = ptid.lwp ();
3102 if (tid < 0)
3103 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3104 else
3105 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3106
3107 return buf;
3108 }
3109
3110 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3111 last parsed char. Returns null_ptid if no thread id is found, and
3112 throws an error if the thread id has an invalid format. */
3113
3114 static ptid_t
3115 read_ptid (const char *buf, const char **obuf)
3116 {
3117 const char *p = buf;
3118 const char *pp;
3119 ULONGEST pid = 0, tid = 0;
3120
3121 if (*p == 'p')
3122 {
3123 /* Multi-process ptid. */
3124 pp = unpack_varlen_hex (p + 1, &pid);
3125 if (*pp != '.')
3126 error (_("invalid remote ptid: %s"), p);
3127
3128 p = pp;
3129 pp = unpack_varlen_hex (p + 1, &tid);
3130 if (obuf)
3131 *obuf = pp;
3132 return ptid_t (pid, tid);
3133 }
3134
3135 /* No multi-process. Just a tid. */
3136 pp = unpack_varlen_hex (p, &tid);
3137
3138 /* Return null_ptid when no thread id is found. */
3139 if (p == pp)
3140 {
3141 if (obuf)
3142 *obuf = pp;
3143 return null_ptid;
3144 }
3145
3146 /* Since the stub is not sending a process id, then default to
3147 what's in inferior_ptid, unless it's null at this point. If so,
3148 then since there's no way to know the pid of the reported
3149 threads, use the magic number. */
3150 if (inferior_ptid == null_ptid)
3151 pid = magic_null_ptid.pid ();
3152 else
3153 pid = inferior_ptid.pid ();
3154
3155 if (obuf)
3156 *obuf = pp;
3157 return ptid_t (pid, tid);
3158 }
3159
3160 static int
3161 stubhex (int ch)
3162 {
3163 if (ch >= 'a' && ch <= 'f')
3164 return ch - 'a' + 10;
3165 if (ch >= '0' && ch <= '9')
3166 return ch - '0';
3167 if (ch >= 'A' && ch <= 'F')
3168 return ch - 'A' + 10;
3169 return -1;
3170 }
3171
3172 static int
3173 stub_unpack_int (const char *buff, int fieldlength)
3174 {
3175 int nibble;
3176 int retval = 0;
3177
3178 while (fieldlength)
3179 {
3180 nibble = stubhex (*buff++);
3181 retval |= nibble;
3182 fieldlength--;
3183 if (fieldlength)
3184 retval = retval << 4;
3185 }
3186 return retval;
3187 }
3188
3189 static const char *
3190 unpack_nibble (const char *buf, int *val)
3191 {
3192 *val = fromhex (*buf++);
3193 return buf;
3194 }
3195
3196 static const char *
3197 unpack_byte (const char *buf, int *value)
3198 {
3199 *value = stub_unpack_int (buf, 2);
3200 return buf + 2;
3201 }
3202
3203 static char *
3204 pack_int (char *buf, int value)
3205 {
3206 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3207 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3208 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3209 buf = pack_hex_byte (buf, (value & 0xff));
3210 return buf;
3211 }
3212
3213 static const char *
3214 unpack_int (const char *buf, int *value)
3215 {
3216 *value = stub_unpack_int (buf, 8);
3217 return buf + 8;
3218 }
3219
3220 #if 0 /* Currently unused, uncomment when needed. */
3221 static char *pack_string (char *pkt, char *string);
3222
3223 static char *
3224 pack_string (char *pkt, char *string)
3225 {
3226 char ch;
3227 int len;
3228
3229 len = strlen (string);
3230 if (len > 200)
3231 len = 200; /* Bigger than most GDB packets, junk??? */
3232 pkt = pack_hex_byte (pkt, len);
3233 while (len-- > 0)
3234 {
3235 ch = *string++;
3236 if ((ch == '\0') || (ch == '#'))
3237 ch = '*'; /* Protect encapsulation. */
3238 *pkt++ = ch;
3239 }
3240 return pkt;
3241 }
3242 #endif /* 0 (unused) */
3243
3244 static const char *
3245 unpack_string (const char *src, char *dest, int length)
3246 {
3247 while (length--)
3248 *dest++ = *src++;
3249 *dest = '\0';
3250 return src;
3251 }
3252
3253 static char *
3254 pack_threadid (char *pkt, threadref *id)
3255 {
3256 char *limit;
3257 unsigned char *altid;
3258
3259 altid = (unsigned char *) id;
3260 limit = pkt + BUF_THREAD_ID_SIZE;
3261 while (pkt < limit)
3262 pkt = pack_hex_byte (pkt, *altid++);
3263 return pkt;
3264 }
3265
3266
3267 static const char *
3268 unpack_threadid (const char *inbuf, threadref *id)
3269 {
3270 char *altref;
3271 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3272 int x, y;
3273
3274 altref = (char *) id;
3275
3276 while (inbuf < limit)
3277 {
3278 x = stubhex (*inbuf++);
3279 y = stubhex (*inbuf++);
3280 *altref++ = (x << 4) | y;
3281 }
3282 return inbuf;
3283 }
3284
3285 /* Externally, threadrefs are 64 bits but internally, they are still
3286 ints. This is due to a mismatch of specifications. We would like
3287 to use 64bit thread references internally. This is an adapter
3288 function. */
3289
3290 void
3291 int_to_threadref (threadref *id, int value)
3292 {
3293 unsigned char *scan;
3294
3295 scan = (unsigned char *) id;
3296 {
3297 int i = 4;
3298 while (i--)
3299 *scan++ = 0;
3300 }
3301 *scan++ = (value >> 24) & 0xff;
3302 *scan++ = (value >> 16) & 0xff;
3303 *scan++ = (value >> 8) & 0xff;
3304 *scan++ = (value & 0xff);
3305 }
3306
3307 static int
3308 threadref_to_int (threadref *ref)
3309 {
3310 int i, value = 0;
3311 unsigned char *scan;
3312
3313 scan = *ref;
3314 scan += 4;
3315 i = 4;
3316 while (i-- > 0)
3317 value = (value << 8) | ((*scan++) & 0xff);
3318 return value;
3319 }
3320
3321 static void
3322 copy_threadref (threadref *dest, threadref *src)
3323 {
3324 int i;
3325 unsigned char *csrc, *cdest;
3326
3327 csrc = (unsigned char *) src;
3328 cdest = (unsigned char *) dest;
3329 i = 8;
3330 while (i--)
3331 *cdest++ = *csrc++;
3332 }
3333
3334 static int
3335 threadmatch (threadref *dest, threadref *src)
3336 {
3337 /* Things are broken right now, so just assume we got a match. */
3338 #if 0
3339 unsigned char *srcp, *destp;
3340 int i, result;
3341 srcp = (char *) src;
3342 destp = (char *) dest;
3343
3344 result = 1;
3345 while (i-- > 0)
3346 result &= (*srcp++ == *destp++) ? 1 : 0;
3347 return result;
3348 #endif
3349 return 1;
3350 }
3351
3352 /*
3353 threadid:1, # always request threadid
3354 context_exists:2,
3355 display:4,
3356 unique_name:8,
3357 more_display:16
3358 */
3359
3360 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3361
3362 static char *
3363 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3364 {
3365 *pkt++ = 'q'; /* Info Query */
3366 *pkt++ = 'P'; /* process or thread info */
3367 pkt = pack_int (pkt, mode); /* mode */
3368 pkt = pack_threadid (pkt, id); /* threadid */
3369 *pkt = '\0'; /* terminate */
3370 return pkt;
3371 }
3372
3373 /* These values tag the fields in a thread info response packet. */
3374 /* Tagging the fields allows us to request specific fields and to
3375 add more fields as time goes by. */
3376
3377 #define TAG_THREADID 1 /* Echo the thread identifier. */
3378 #define TAG_EXISTS 2 /* Is this process defined enough to
3379 fetch registers and its stack? */
3380 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3381 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3382 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3383 the process. */
3384
3385 int
3386 remote_target::remote_unpack_thread_info_response (const char *pkt,
3387 threadref *expectedref,
3388 gdb_ext_thread_info *info)
3389 {
3390 struct remote_state *rs = get_remote_state ();
3391 int mask, length;
3392 int tag;
3393 threadref ref;
3394 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3395 int retval = 1;
3396
3397 /* info->threadid = 0; FIXME: implement zero_threadref. */
3398 info->active = 0;
3399 info->display[0] = '\0';
3400 info->shortname[0] = '\0';
3401 info->more_display[0] = '\0';
3402
3403 /* Assume the characters indicating the packet type have been
3404 stripped. */
3405 pkt = unpack_int (pkt, &mask); /* arg mask */
3406 pkt = unpack_threadid (pkt, &ref);
3407
3408 if (mask == 0)
3409 warning (_("Incomplete response to threadinfo request."));
3410 if (!threadmatch (&ref, expectedref))
3411 { /* This is an answer to a different request. */
3412 warning (_("ERROR RMT Thread info mismatch."));
3413 return 0;
3414 }
3415 copy_threadref (&info->threadid, &ref);
3416
3417 /* Loop on tagged fields , try to bail if something goes wrong. */
3418
3419 /* Packets are terminated with nulls. */
3420 while ((pkt < limit) && mask && *pkt)
3421 {
3422 pkt = unpack_int (pkt, &tag); /* tag */
3423 pkt = unpack_byte (pkt, &length); /* length */
3424 if (!(tag & mask)) /* Tags out of synch with mask. */
3425 {
3426 warning (_("ERROR RMT: threadinfo tag mismatch."));
3427 retval = 0;
3428 break;
3429 }
3430 if (tag == TAG_THREADID)
3431 {
3432 if (length != 16)
3433 {
3434 warning (_("ERROR RMT: length of threadid is not 16."));
3435 retval = 0;
3436 break;
3437 }
3438 pkt = unpack_threadid (pkt, &ref);
3439 mask = mask & ~TAG_THREADID;
3440 continue;
3441 }
3442 if (tag == TAG_EXISTS)
3443 {
3444 info->active = stub_unpack_int (pkt, length);
3445 pkt += length;
3446 mask = mask & ~(TAG_EXISTS);
3447 if (length > 8)
3448 {
3449 warning (_("ERROR RMT: 'exists' length too long."));
3450 retval = 0;
3451 break;
3452 }
3453 continue;
3454 }
3455 if (tag == TAG_THREADNAME)
3456 {
3457 pkt = unpack_string (pkt, &info->shortname[0], length);
3458 mask = mask & ~TAG_THREADNAME;
3459 continue;
3460 }
3461 if (tag == TAG_DISPLAY)
3462 {
3463 pkt = unpack_string (pkt, &info->display[0], length);
3464 mask = mask & ~TAG_DISPLAY;
3465 continue;
3466 }
3467 if (tag == TAG_MOREDISPLAY)
3468 {
3469 pkt = unpack_string (pkt, &info->more_display[0], length);
3470 mask = mask & ~TAG_MOREDISPLAY;
3471 continue;
3472 }
3473 warning (_("ERROR RMT: unknown thread info tag."));
3474 break; /* Not a tag we know about. */
3475 }
3476 return retval;
3477 }
3478
3479 int
3480 remote_target::remote_get_threadinfo (threadref *threadid,
3481 int fieldset,
3482 gdb_ext_thread_info *info)
3483 {
3484 struct remote_state *rs = get_remote_state ();
3485 int result;
3486
3487 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3488 putpkt (rs->buf);
3489 getpkt (&rs->buf, 0);
3490
3491 if (rs->buf[0] == '\0')
3492 return 0;
3493
3494 result = remote_unpack_thread_info_response (&rs->buf[2],
3495 threadid, info);
3496 return result;
3497 }
3498
3499 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3500
3501 static char *
3502 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3503 threadref *nextthread)
3504 {
3505 *pkt++ = 'q'; /* info query packet */
3506 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3507 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3508 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3509 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3510 *pkt = '\0';
3511 return pkt;
3512 }
3513
3514 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3515
3516 int
3517 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3518 threadref *original_echo,
3519 threadref *resultlist,
3520 int *doneflag)
3521 {
3522 struct remote_state *rs = get_remote_state ();
3523 int count, resultcount, done;
3524
3525 resultcount = 0;
3526 /* Assume the 'q' and 'M chars have been stripped. */
3527 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3528 /* done parse past here */
3529 pkt = unpack_byte (pkt, &count); /* count field */
3530 pkt = unpack_nibble (pkt, &done);
3531 /* The first threadid is the argument threadid. */
3532 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3533 while ((count-- > 0) && (pkt < limit))
3534 {
3535 pkt = unpack_threadid (pkt, resultlist++);
3536 if (resultcount++ >= result_limit)
3537 break;
3538 }
3539 if (doneflag)
3540 *doneflag = done;
3541 return resultcount;
3542 }
3543
3544 /* Fetch the next batch of threads from the remote. Returns -1 if the
3545 qL packet is not supported, 0 on error and 1 on success. */
3546
3547 int
3548 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3549 int result_limit, int *done, int *result_count,
3550 threadref *threadlist)
3551 {
3552 struct remote_state *rs = get_remote_state ();
3553 int result = 1;
3554
3555 /* Truncate result limit to be smaller than the packet size. */
3556 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3557 >= get_remote_packet_size ())
3558 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3559
3560 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3561 nextthread);
3562 putpkt (rs->buf);
3563 getpkt (&rs->buf, 0);
3564 if (rs->buf[0] == '\0')
3565 {
3566 /* Packet not supported. */
3567 return -1;
3568 }
3569
3570 *result_count =
3571 parse_threadlist_response (&rs->buf[2], result_limit,
3572 &rs->echo_nextthread, threadlist, done);
3573
3574 if (!threadmatch (&rs->echo_nextthread, nextthread))
3575 {
3576 /* FIXME: This is a good reason to drop the packet. */
3577 /* Possibly, there is a duplicate response. */
3578 /* Possibilities :
3579 retransmit immediatly - race conditions
3580 retransmit after timeout - yes
3581 exit
3582 wait for packet, then exit
3583 */
3584 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3585 return 0; /* I choose simply exiting. */
3586 }
3587 if (*result_count <= 0)
3588 {
3589 if (*done != 1)
3590 {
3591 warning (_("RMT ERROR : failed to get remote thread list."));
3592 result = 0;
3593 }
3594 return result; /* break; */
3595 }
3596 if (*result_count > result_limit)
3597 {
3598 *result_count = 0;
3599 warning (_("RMT ERROR: threadlist response longer than requested."));
3600 return 0;
3601 }
3602 return result;
3603 }
3604
3605 /* Fetch the list of remote threads, with the qL packet, and call
3606 STEPFUNCTION for each thread found. Stops iterating and returns 1
3607 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3608 STEPFUNCTION returns false. If the packet is not supported,
3609 returns -1. */
3610
3611 int
3612 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3613 void *context, int looplimit)
3614 {
3615 struct remote_state *rs = get_remote_state ();
3616 int done, i, result_count;
3617 int startflag = 1;
3618 int result = 1;
3619 int loopcount = 0;
3620
3621 done = 0;
3622 while (!done)
3623 {
3624 if (loopcount++ > looplimit)
3625 {
3626 result = 0;
3627 warning (_("Remote fetch threadlist -infinite loop-."));
3628 break;
3629 }
3630 result = remote_get_threadlist (startflag, &rs->nextthread,
3631 MAXTHREADLISTRESULTS,
3632 &done, &result_count,
3633 rs->resultthreadlist);
3634 if (result <= 0)
3635 break;
3636 /* Clear for later iterations. */
3637 startflag = 0;
3638 /* Setup to resume next batch of thread references, set nextthread. */
3639 if (result_count >= 1)
3640 copy_threadref (&rs->nextthread,
3641 &rs->resultthreadlist[result_count - 1]);
3642 i = 0;
3643 while (result_count--)
3644 {
3645 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3646 {
3647 result = 0;
3648 break;
3649 }
3650 }
3651 }
3652 return result;
3653 }
3654
3655 /* A thread found on the remote target. */
3656
3657 struct thread_item
3658 {
3659 explicit thread_item (ptid_t ptid_)
3660 : ptid (ptid_)
3661 {}
3662
3663 thread_item (thread_item &&other) = default;
3664 thread_item &operator= (thread_item &&other) = default;
3665
3666 DISABLE_COPY_AND_ASSIGN (thread_item);
3667
3668 /* The thread's PTID. */
3669 ptid_t ptid;
3670
3671 /* The thread's extra info. */
3672 std::string extra;
3673
3674 /* The thread's name. */
3675 std::string name;
3676
3677 /* The core the thread was running on. -1 if not known. */
3678 int core = -1;
3679
3680 /* The thread handle associated with the thread. */
3681 gdb::byte_vector thread_handle;
3682 };
3683
3684 /* Context passed around to the various methods listing remote
3685 threads. As new threads are found, they're added to the ITEMS
3686 vector. */
3687
3688 struct threads_listing_context
3689 {
3690 /* Return true if this object contains an entry for a thread with ptid
3691 PTID. */
3692
3693 bool contains_thread (ptid_t ptid) const
3694 {
3695 auto match_ptid = [&] (const thread_item &item)
3696 {
3697 return item.ptid == ptid;
3698 };
3699
3700 auto it = std::find_if (this->items.begin (),
3701 this->items.end (),
3702 match_ptid);
3703
3704 return it != this->items.end ();
3705 }
3706
3707 /* Remove the thread with ptid PTID. */
3708
3709 void remove_thread (ptid_t ptid)
3710 {
3711 auto match_ptid = [&] (const thread_item &item)
3712 {
3713 return item.ptid == ptid;
3714 };
3715
3716 auto it = std::remove_if (this->items.begin (),
3717 this->items.end (),
3718 match_ptid);
3719
3720 if (it != this->items.end ())
3721 this->items.erase (it);
3722 }
3723
3724 /* The threads found on the remote target. */
3725 std::vector<thread_item> items;
3726 };
3727
3728 static int
3729 remote_newthread_step (threadref *ref, void *data)
3730 {
3731 struct threads_listing_context *context
3732 = (struct threads_listing_context *) data;
3733 int pid = inferior_ptid.pid ();
3734 int lwp = threadref_to_int (ref);
3735 ptid_t ptid (pid, lwp);
3736
3737 context->items.emplace_back (ptid);
3738
3739 return 1; /* continue iterator */
3740 }
3741
3742 #define CRAZY_MAX_THREADS 1000
3743
3744 ptid_t
3745 remote_target::remote_current_thread (ptid_t oldpid)
3746 {
3747 struct remote_state *rs = get_remote_state ();
3748
3749 putpkt ("qC");
3750 getpkt (&rs->buf, 0);
3751 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3752 {
3753 const char *obuf;
3754 ptid_t result;
3755
3756 result = read_ptid (&rs->buf[2], &obuf);
3757 if (*obuf != '\0')
3758 remote_debug_printf ("warning: garbage in qC reply");
3759
3760 return result;
3761 }
3762 else
3763 return oldpid;
3764 }
3765
3766 /* List remote threads using the deprecated qL packet. */
3767
3768 int
3769 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3770 {
3771 if (remote_threadlist_iterator (remote_newthread_step, context,
3772 CRAZY_MAX_THREADS) >= 0)
3773 return 1;
3774
3775 return 0;
3776 }
3777
3778 #if defined(HAVE_LIBEXPAT)
3779
3780 static void
3781 start_thread (struct gdb_xml_parser *parser,
3782 const struct gdb_xml_element *element,
3783 void *user_data,
3784 std::vector<gdb_xml_value> &attributes)
3785 {
3786 struct threads_listing_context *data
3787 = (struct threads_listing_context *) user_data;
3788 struct gdb_xml_value *attr;
3789
3790 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3791 ptid_t ptid = read_ptid (id, NULL);
3792
3793 data->items.emplace_back (ptid);
3794 thread_item &item = data->items.back ();
3795
3796 attr = xml_find_attribute (attributes, "core");
3797 if (attr != NULL)
3798 item.core = *(ULONGEST *) attr->value.get ();
3799
3800 attr = xml_find_attribute (attributes, "name");
3801 if (attr != NULL)
3802 item.name = (const char *) attr->value.get ();
3803
3804 attr = xml_find_attribute (attributes, "handle");
3805 if (attr != NULL)
3806 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3807 }
3808
3809 static void
3810 end_thread (struct gdb_xml_parser *parser,
3811 const struct gdb_xml_element *element,
3812 void *user_data, const char *body_text)
3813 {
3814 struct threads_listing_context *data
3815 = (struct threads_listing_context *) user_data;
3816
3817 if (body_text != NULL && *body_text != '\0')
3818 data->items.back ().extra = body_text;
3819 }
3820
3821 const struct gdb_xml_attribute thread_attributes[] = {
3822 { "id", GDB_XML_AF_NONE, NULL, NULL },
3823 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3824 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3825 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3826 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3827 };
3828
3829 const struct gdb_xml_element thread_children[] = {
3830 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3831 };
3832
3833 const struct gdb_xml_element threads_children[] = {
3834 { "thread", thread_attributes, thread_children,
3835 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3836 start_thread, end_thread },
3837 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3838 };
3839
3840 const struct gdb_xml_element threads_elements[] = {
3841 { "threads", NULL, threads_children,
3842 GDB_XML_EF_NONE, NULL, NULL },
3843 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3844 };
3845
3846 #endif
3847
3848 /* List remote threads using qXfer:threads:read. */
3849
3850 int
3851 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
3852 {
3853 #if defined(HAVE_LIBEXPAT)
3854 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3855 {
3856 gdb::optional<gdb::char_vector> xml
3857 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
3858
3859 if (xml && (*xml)[0] != '\0')
3860 {
3861 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3862 threads_elements, xml->data (), context);
3863 }
3864
3865 return 1;
3866 }
3867 #endif
3868
3869 return 0;
3870 }
3871
3872 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3873
3874 int
3875 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
3876 {
3877 struct remote_state *rs = get_remote_state ();
3878
3879 if (rs->use_threadinfo_query)
3880 {
3881 const char *bufp;
3882
3883 putpkt ("qfThreadInfo");
3884 getpkt (&rs->buf, 0);
3885 bufp = rs->buf.data ();
3886 if (bufp[0] != '\0') /* q packet recognized */
3887 {
3888 while (*bufp++ == 'm') /* reply contains one or more TID */
3889 {
3890 do
3891 {
3892 ptid_t ptid = read_ptid (bufp, &bufp);
3893 context->items.emplace_back (ptid);
3894 }
3895 while (*bufp++ == ','); /* comma-separated list */
3896 putpkt ("qsThreadInfo");
3897 getpkt (&rs->buf, 0);
3898 bufp = rs->buf.data ();
3899 }
3900 return 1;
3901 }
3902 else
3903 {
3904 /* Packet not recognized. */
3905 rs->use_threadinfo_query = 0;
3906 }
3907 }
3908
3909 return 0;
3910 }
3911
3912 /* Return true if INF only has one non-exited thread. */
3913
3914 static bool
3915 has_single_non_exited_thread (inferior *inf)
3916 {
3917 int count = 0;
3918 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
3919 if (++count > 1)
3920 break;
3921 return count == 1;
3922 }
3923
3924 /* Implement the to_update_thread_list function for the remote
3925 targets. */
3926
3927 void
3928 remote_target::update_thread_list ()
3929 {
3930 struct threads_listing_context context;
3931 int got_list = 0;
3932
3933 /* We have a few different mechanisms to fetch the thread list. Try
3934 them all, starting with the most preferred one first, falling
3935 back to older methods. */
3936 if (remote_get_threads_with_qxfer (&context)
3937 || remote_get_threads_with_qthreadinfo (&context)
3938 || remote_get_threads_with_ql (&context))
3939 {
3940 got_list = 1;
3941
3942 if (context.items.empty ()
3943 && remote_thread_always_alive (inferior_ptid))
3944 {
3945 /* Some targets don't really support threads, but still
3946 reply an (empty) thread list in response to the thread
3947 listing packets, instead of replying "packet not
3948 supported". Exit early so we don't delete the main
3949 thread. */
3950 return;
3951 }
3952
3953 /* CONTEXT now holds the current thread list on the remote
3954 target end. Delete GDB-side threads no longer found on the
3955 target. */
3956 for (thread_info *tp : all_threads_safe ())
3957 {
3958 if (tp->inf->process_target () != this)
3959 continue;
3960
3961 if (!context.contains_thread (tp->ptid))
3962 {
3963 /* Do not remove the thread if it is the last thread in
3964 the inferior. This situation happens when we have a
3965 pending exit process status to process. Otherwise we
3966 may end up with a seemingly live inferior (i.e. pid
3967 != 0) that has no threads. */
3968 if (has_single_non_exited_thread (tp->inf))
3969 continue;
3970
3971 /* Not found. */
3972 delete_thread (tp);
3973 }
3974 }
3975
3976 /* Remove any unreported fork child threads from CONTEXT so
3977 that we don't interfere with follow fork, which is where
3978 creation of such threads is handled. */
3979 remove_new_fork_children (&context);
3980
3981 /* And now add threads we don't know about yet to our list. */
3982 for (thread_item &item : context.items)
3983 {
3984 if (item.ptid != null_ptid)
3985 {
3986 /* In non-stop mode, we assume new found threads are
3987 executing until proven otherwise with a stop reply.
3988 In all-stop, we can only get here if all threads are
3989 stopped. */
3990 bool executing = target_is_non_stop_p ();
3991
3992 remote_notice_new_inferior (item.ptid, executing);
3993
3994 thread_info *tp = find_thread_ptid (this, item.ptid);
3995 remote_thread_info *info = get_remote_thread_info (tp);
3996 info->core = item.core;
3997 info->extra = std::move (item.extra);
3998 info->name = std::move (item.name);
3999 info->thread_handle = std::move (item.thread_handle);
4000 }
4001 }
4002 }
4003
4004 if (!got_list)
4005 {
4006 /* If no thread listing method is supported, then query whether
4007 each known thread is alive, one by one, with the T packet.
4008 If the target doesn't support threads at all, then this is a
4009 no-op. See remote_thread_alive. */
4010 prune_threads ();
4011 }
4012 }
4013
4014 /*
4015 * Collect a descriptive string about the given thread.
4016 * The target may say anything it wants to about the thread
4017 * (typically info about its blocked / runnable state, name, etc.).
4018 * This string will appear in the info threads display.
4019 *
4020 * Optional: targets are not required to implement this function.
4021 */
4022
4023 const char *
4024 remote_target::extra_thread_info (thread_info *tp)
4025 {
4026 struct remote_state *rs = get_remote_state ();
4027 int set;
4028 threadref id;
4029 struct gdb_ext_thread_info threadinfo;
4030
4031 if (rs->remote_desc == 0) /* paranoia */
4032 internal_error (__FILE__, __LINE__,
4033 _("remote_threads_extra_info"));
4034
4035 if (tp->ptid == magic_null_ptid
4036 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4037 /* This is the main thread which was added by GDB. The remote
4038 server doesn't know about it. */
4039 return NULL;
4040
4041 std::string &extra = get_remote_thread_info (tp)->extra;
4042
4043 /* If already have cached info, use it. */
4044 if (!extra.empty ())
4045 return extra.c_str ();
4046
4047 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4048 {
4049 /* If we're using qXfer:threads:read, then the extra info is
4050 included in the XML. So if we didn't have anything cached,
4051 it's because there's really no extra info. */
4052 return NULL;
4053 }
4054
4055 if (rs->use_threadextra_query)
4056 {
4057 char *b = rs->buf.data ();
4058 char *endb = b + get_remote_packet_size ();
4059
4060 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4061 b += strlen (b);
4062 write_ptid (b, endb, tp->ptid);
4063
4064 putpkt (rs->buf);
4065 getpkt (&rs->buf, 0);
4066 if (rs->buf[0] != 0)
4067 {
4068 extra.resize (strlen (rs->buf.data ()) / 2);
4069 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4070 return extra.c_str ();
4071 }
4072 }
4073
4074 /* If the above query fails, fall back to the old method. */
4075 rs->use_threadextra_query = 0;
4076 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4077 | TAG_MOREDISPLAY | TAG_DISPLAY;
4078 int_to_threadref (&id, tp->ptid.lwp ());
4079 if (remote_get_threadinfo (&id, set, &threadinfo))
4080 if (threadinfo.active)
4081 {
4082 if (*threadinfo.shortname)
4083 string_appendf (extra, " Name: %s", threadinfo.shortname);
4084 if (*threadinfo.display)
4085 {
4086 if (!extra.empty ())
4087 extra += ',';
4088 string_appendf (extra, " State: %s", threadinfo.display);
4089 }
4090 if (*threadinfo.more_display)
4091 {
4092 if (!extra.empty ())
4093 extra += ',';
4094 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4095 }
4096 return extra.c_str ();
4097 }
4098 return NULL;
4099 }
4100 \f
4101
4102 bool
4103 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4104 struct static_tracepoint_marker *marker)
4105 {
4106 struct remote_state *rs = get_remote_state ();
4107 char *p = rs->buf.data ();
4108
4109 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4110 p += strlen (p);
4111 p += hexnumstr (p, addr);
4112 putpkt (rs->buf);
4113 getpkt (&rs->buf, 0);
4114 p = rs->buf.data ();
4115
4116 if (*p == 'E')
4117 error (_("Remote failure reply: %s"), p);
4118
4119 if (*p++ == 'm')
4120 {
4121 parse_static_tracepoint_marker_definition (p, NULL, marker);
4122 return true;
4123 }
4124
4125 return false;
4126 }
4127
4128 std::vector<static_tracepoint_marker>
4129 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4130 {
4131 struct remote_state *rs = get_remote_state ();
4132 std::vector<static_tracepoint_marker> markers;
4133 const char *p;
4134 static_tracepoint_marker marker;
4135
4136 /* Ask for a first packet of static tracepoint marker
4137 definition. */
4138 putpkt ("qTfSTM");
4139 getpkt (&rs->buf, 0);
4140 p = rs->buf.data ();
4141 if (*p == 'E')
4142 error (_("Remote failure reply: %s"), p);
4143
4144 while (*p++ == 'm')
4145 {
4146 do
4147 {
4148 parse_static_tracepoint_marker_definition (p, &p, &marker);
4149
4150 if (strid == NULL || marker.str_id == strid)
4151 markers.push_back (std::move (marker));
4152 }
4153 while (*p++ == ','); /* comma-separated list */
4154 /* Ask for another packet of static tracepoint definition. */
4155 putpkt ("qTsSTM");
4156 getpkt (&rs->buf, 0);
4157 p = rs->buf.data ();
4158 }
4159
4160 return markers;
4161 }
4162
4163 \f
4164 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4165
4166 ptid_t
4167 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4168 {
4169 return ptid_t (inferior_ptid.pid (), lwp);
4170 }
4171 \f
4172
4173 /* Restart the remote side; this is an extended protocol operation. */
4174
4175 void
4176 remote_target::extended_remote_restart ()
4177 {
4178 struct remote_state *rs = get_remote_state ();
4179
4180 /* Send the restart command; for reasons I don't understand the
4181 remote side really expects a number after the "R". */
4182 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4183 putpkt (rs->buf);
4184
4185 remote_fileio_reset ();
4186 }
4187 \f
4188 /* Clean up connection to a remote debugger. */
4189
4190 void
4191 remote_target::close ()
4192 {
4193 /* Make sure we leave stdin registered in the event loop. */
4194 terminal_ours ();
4195
4196 trace_reset_local_state ();
4197
4198 delete this;
4199 }
4200
4201 remote_target::~remote_target ()
4202 {
4203 struct remote_state *rs = get_remote_state ();
4204
4205 /* Check for NULL because we may get here with a partially
4206 constructed target/connection. */
4207 if (rs->remote_desc == nullptr)
4208 return;
4209
4210 serial_close (rs->remote_desc);
4211
4212 /* We are destroying the remote target, so we should discard
4213 everything of this target. */
4214 discard_pending_stop_replies_in_queue ();
4215
4216 if (rs->remote_async_inferior_event_token)
4217 delete_async_event_handler (&rs->remote_async_inferior_event_token);
4218
4219 delete rs->notif_state;
4220 }
4221
4222 /* Query the remote side for the text, data and bss offsets. */
4223
4224 void
4225 remote_target::get_offsets ()
4226 {
4227 struct remote_state *rs = get_remote_state ();
4228 char *buf;
4229 char *ptr;
4230 int lose, num_segments = 0, do_sections, do_segments;
4231 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4232
4233 if (current_program_space->symfile_object_file == NULL)
4234 return;
4235
4236 putpkt ("qOffsets");
4237 getpkt (&rs->buf, 0);
4238 buf = rs->buf.data ();
4239
4240 if (buf[0] == '\000')
4241 return; /* Return silently. Stub doesn't support
4242 this command. */
4243 if (buf[0] == 'E')
4244 {
4245 warning (_("Remote failure reply: %s"), buf);
4246 return;
4247 }
4248
4249 /* Pick up each field in turn. This used to be done with scanf, but
4250 scanf will make trouble if CORE_ADDR size doesn't match
4251 conversion directives correctly. The following code will work
4252 with any size of CORE_ADDR. */
4253 text_addr = data_addr = bss_addr = 0;
4254 ptr = buf;
4255 lose = 0;
4256
4257 if (startswith (ptr, "Text="))
4258 {
4259 ptr += 5;
4260 /* Don't use strtol, could lose on big values. */
4261 while (*ptr && *ptr != ';')
4262 text_addr = (text_addr << 4) + fromhex (*ptr++);
4263
4264 if (startswith (ptr, ";Data="))
4265 {
4266 ptr += 6;
4267 while (*ptr && *ptr != ';')
4268 data_addr = (data_addr << 4) + fromhex (*ptr++);
4269 }
4270 else
4271 lose = 1;
4272
4273 if (!lose && startswith (ptr, ";Bss="))
4274 {
4275 ptr += 5;
4276 while (*ptr && *ptr != ';')
4277 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4278
4279 if (bss_addr != data_addr)
4280 warning (_("Target reported unsupported offsets: %s"), buf);
4281 }
4282 else
4283 lose = 1;
4284 }
4285 else if (startswith (ptr, "TextSeg="))
4286 {
4287 ptr += 8;
4288 /* Don't use strtol, could lose on big values. */
4289 while (*ptr && *ptr != ';')
4290 text_addr = (text_addr << 4) + fromhex (*ptr++);
4291 num_segments = 1;
4292
4293 if (startswith (ptr, ";DataSeg="))
4294 {
4295 ptr += 9;
4296 while (*ptr && *ptr != ';')
4297 data_addr = (data_addr << 4) + fromhex (*ptr++);
4298 num_segments++;
4299 }
4300 }
4301 else
4302 lose = 1;
4303
4304 if (lose)
4305 error (_("Malformed response to offset query, %s"), buf);
4306 else if (*ptr != '\0')
4307 warning (_("Target reported unsupported offsets: %s"), buf);
4308
4309 objfile *objf = current_program_space->symfile_object_file;
4310 section_offsets offs = objf->section_offsets;
4311
4312 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd);
4313 do_segments = (data != NULL);
4314 do_sections = num_segments == 0;
4315
4316 if (num_segments > 0)
4317 {
4318 segments[0] = text_addr;
4319 segments[1] = data_addr;
4320 }
4321 /* If we have two segments, we can still try to relocate everything
4322 by assuming that the .text and .data offsets apply to the whole
4323 text and data segments. Convert the offsets given in the packet
4324 to base addresses for symfile_map_offsets_to_segments. */
4325 else if (data != nullptr && data->segments.size () == 2)
4326 {
4327 segments[0] = data->segments[0].base + text_addr;
4328 segments[1] = data->segments[1].base + data_addr;
4329 num_segments = 2;
4330 }
4331 /* If the object file has only one segment, assume that it is text
4332 rather than data; main programs with no writable data are rare,
4333 but programs with no code are useless. Of course the code might
4334 have ended up in the data segment... to detect that we would need
4335 the permissions here. */
4336 else if (data && data->segments.size () == 1)
4337 {
4338 segments[0] = data->segments[0].base + text_addr;
4339 num_segments = 1;
4340 }
4341 /* There's no way to relocate by segment. */
4342 else
4343 do_segments = 0;
4344
4345 if (do_segments)
4346 {
4347 int ret = symfile_map_offsets_to_segments (objf->obfd,
4348 data.get (), offs,
4349 num_segments, segments);
4350
4351 if (ret == 0 && !do_sections)
4352 error (_("Can not handle qOffsets TextSeg "
4353 "response with this symbol file"));
4354
4355 if (ret > 0)
4356 do_sections = 0;
4357 }
4358
4359 if (do_sections)
4360 {
4361 offs[SECT_OFF_TEXT (objf)] = text_addr;
4362
4363 /* This is a temporary kludge to force data and bss to use the
4364 same offsets because that's what nlmconv does now. The real
4365 solution requires changes to the stub and remote.c that I
4366 don't have time to do right now. */
4367
4368 offs[SECT_OFF_DATA (objf)] = data_addr;
4369 offs[SECT_OFF_BSS (objf)] = data_addr;
4370 }
4371
4372 objfile_relocate (objf, offs);
4373 }
4374
4375 /* Send interrupt_sequence to remote target. */
4376
4377 void
4378 remote_target::send_interrupt_sequence ()
4379 {
4380 struct remote_state *rs = get_remote_state ();
4381
4382 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4383 remote_serial_write ("\x03", 1);
4384 else if (interrupt_sequence_mode == interrupt_sequence_break)
4385 serial_send_break (rs->remote_desc);
4386 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4387 {
4388 serial_send_break (rs->remote_desc);
4389 remote_serial_write ("g", 1);
4390 }
4391 else
4392 internal_error (__FILE__, __LINE__,
4393 _("Invalid value for interrupt_sequence_mode: %s."),
4394 interrupt_sequence_mode);
4395 }
4396
4397
4398 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4399 and extract the PTID. Returns NULL_PTID if not found. */
4400
4401 static ptid_t
4402 stop_reply_extract_thread (const char *stop_reply)
4403 {
4404 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4405 {
4406 const char *p;
4407
4408 /* Txx r:val ; r:val (...) */
4409 p = &stop_reply[3];
4410
4411 /* Look for "register" named "thread". */
4412 while (*p != '\0')
4413 {
4414 const char *p1;
4415
4416 p1 = strchr (p, ':');
4417 if (p1 == NULL)
4418 return null_ptid;
4419
4420 if (strncmp (p, "thread", p1 - p) == 0)
4421 return read_ptid (++p1, &p);
4422
4423 p1 = strchr (p, ';');
4424 if (p1 == NULL)
4425 return null_ptid;
4426 p1++;
4427
4428 p = p1;
4429 }
4430 }
4431
4432 return null_ptid;
4433 }
4434
4435 /* Determine the remote side's current thread. If we have a stop
4436 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4437 "thread" register we can extract the current thread from. If not,
4438 ask the remote which is the current thread with qC. The former
4439 method avoids a roundtrip. */
4440
4441 ptid_t
4442 remote_target::get_current_thread (const char *wait_status)
4443 {
4444 ptid_t ptid = null_ptid;
4445
4446 /* Note we don't use remote_parse_stop_reply as that makes use of
4447 the target architecture, which we haven't yet fully determined at
4448 this point. */
4449 if (wait_status != NULL)
4450 ptid = stop_reply_extract_thread (wait_status);
4451 if (ptid == null_ptid)
4452 ptid = remote_current_thread (inferior_ptid);
4453
4454 return ptid;
4455 }
4456
4457 /* Query the remote target for which is the current thread/process,
4458 add it to our tables, and update INFERIOR_PTID. The caller is
4459 responsible for setting the state such that the remote end is ready
4460 to return the current thread.
4461
4462 This function is called after handling the '?' or 'vRun' packets,
4463 whose response is a stop reply from which we can also try
4464 extracting the thread. If the target doesn't support the explicit
4465 qC query, we infer the current thread from that stop reply, passed
4466 in in WAIT_STATUS, which may be NULL.
4467
4468 The function returns pointer to the main thread of the inferior. */
4469
4470 thread_info *
4471 remote_target::add_current_inferior_and_thread (const char *wait_status)
4472 {
4473 struct remote_state *rs = get_remote_state ();
4474 bool fake_pid_p = false;
4475
4476 switch_to_no_thread ();
4477
4478 /* Now, if we have thread information, update the current thread's
4479 ptid. */
4480 ptid_t curr_ptid = get_current_thread (wait_status);
4481
4482 if (curr_ptid != null_ptid)
4483 {
4484 if (!remote_multi_process_p (rs))
4485 fake_pid_p = true;
4486 }
4487 else
4488 {
4489 /* Without this, some commands which require an active target
4490 (such as kill) won't work. This variable serves (at least)
4491 double duty as both the pid of the target process (if it has
4492 such), and as a flag indicating that a target is active. */
4493 curr_ptid = magic_null_ptid;
4494 fake_pid_p = true;
4495 }
4496
4497 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4498
4499 /* Add the main thread and switch to it. Don't try reading
4500 registers yet, since we haven't fetched the target description
4501 yet. */
4502 thread_info *tp = add_thread_silent (this, curr_ptid);
4503 switch_to_thread_no_regs (tp);
4504
4505 return tp;
4506 }
4507
4508 /* Print info about a thread that was found already stopped on
4509 connection. */
4510
4511 void
4512 remote_target::print_one_stopped_thread (thread_info *thread)
4513 {
4514 target_waitstatus ws;
4515
4516 /* If there is a pending waitstatus, use it. If there isn't it's because
4517 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4518 and process_initial_stop_replies decided it wasn't interesting to save
4519 and report to the core. */
4520 if (thread->has_pending_waitstatus ())
4521 {
4522 ws = thread->pending_waitstatus ();
4523 thread->clear_pending_waitstatus ();
4524 }
4525 else
4526 {
4527 ws.set_stopped (GDB_SIGNAL_0);
4528 }
4529
4530 switch_to_thread (thread);
4531 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4532 set_current_sal_from_frame (get_current_frame ());
4533
4534 /* For "info program". */
4535 set_last_target_status (this, thread->ptid, ws);
4536
4537 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4538 {
4539 enum gdb_signal sig = ws.sig ();
4540
4541 if (signal_print_state (sig))
4542 gdb::observers::signal_received.notify (sig);
4543 }
4544 gdb::observers::normal_stop.notify (NULL, 1);
4545 }
4546
4547 /* Process all initial stop replies the remote side sent in response
4548 to the ? packet. These indicate threads that were already stopped
4549 on initial connection. We mark these threads as stopped and print
4550 their current frame before giving the user the prompt. */
4551
4552 void
4553 remote_target::process_initial_stop_replies (int from_tty)
4554 {
4555 int pending_stop_replies = stop_reply_queue_length ();
4556 struct thread_info *selected = NULL;
4557 struct thread_info *lowest_stopped = NULL;
4558 struct thread_info *first = NULL;
4559
4560 /* This is only used when the target is non-stop. */
4561 gdb_assert (target_is_non_stop_p ());
4562
4563 /* Consume the initial pending events. */
4564 while (pending_stop_replies-- > 0)
4565 {
4566 ptid_t waiton_ptid = minus_one_ptid;
4567 ptid_t event_ptid;
4568 struct target_waitstatus ws;
4569 int ignore_event = 0;
4570
4571 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4572 if (remote_debug)
4573 print_target_wait_results (waiton_ptid, event_ptid, ws);
4574
4575 switch (ws.kind ())
4576 {
4577 case TARGET_WAITKIND_IGNORE:
4578 case TARGET_WAITKIND_NO_RESUMED:
4579 case TARGET_WAITKIND_SIGNALLED:
4580 case TARGET_WAITKIND_EXITED:
4581 /* We shouldn't see these, but if we do, just ignore. */
4582 remote_debug_printf ("event ignored");
4583 ignore_event = 1;
4584 break;
4585
4586 default:
4587 break;
4588 }
4589
4590 if (ignore_event)
4591 continue;
4592
4593 thread_info *evthread = find_thread_ptid (this, event_ptid);
4594
4595 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4596 {
4597 enum gdb_signal sig = ws.sig ();
4598
4599 /* Stubs traditionally report SIGTRAP as initial signal,
4600 instead of signal 0. Suppress it. */
4601 if (sig == GDB_SIGNAL_TRAP)
4602 sig = GDB_SIGNAL_0;
4603 evthread->set_stop_signal (sig);
4604 ws.set_stopped (sig);
4605 }
4606
4607 if (ws.kind () != TARGET_WAITKIND_STOPPED
4608 || ws.sig () != GDB_SIGNAL_0)
4609 evthread->set_pending_waitstatus (ws);
4610
4611 set_executing (this, event_ptid, false);
4612 set_running (this, event_ptid, false);
4613 get_remote_thread_info (evthread)->set_not_resumed ();
4614 }
4615
4616 /* "Notice" the new inferiors before anything related to
4617 registers/memory. */
4618 for (inferior *inf : all_non_exited_inferiors (this))
4619 {
4620 inf->needs_setup = 1;
4621
4622 if (non_stop)
4623 {
4624 thread_info *thread = any_live_thread_of_inferior (inf);
4625 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4626 from_tty);
4627 }
4628 }
4629
4630 /* If all-stop on top of non-stop, pause all threads. Note this
4631 records the threads' stop pc, so must be done after "noticing"
4632 the inferiors. */
4633 if (!non_stop)
4634 {
4635 {
4636 /* At this point, the remote target is not async. It needs to be for
4637 the poll in stop_all_threads to consider events from it, so enable
4638 it temporarily. */
4639 gdb_assert (!this->is_async_p ());
4640 SCOPE_EXIT { target_async (0); };
4641 target_async (1);
4642 stop_all_threads ();
4643 }
4644
4645 /* If all threads of an inferior were already stopped, we
4646 haven't setup the inferior yet. */
4647 for (inferior *inf : all_non_exited_inferiors (this))
4648 {
4649 if (inf->needs_setup)
4650 {
4651 thread_info *thread = any_live_thread_of_inferior (inf);
4652 switch_to_thread_no_regs (thread);
4653 setup_inferior (0);
4654 }
4655 }
4656 }
4657
4658 /* Now go over all threads that are stopped, and print their current
4659 frame. If all-stop, then if there's a signalled thread, pick
4660 that as current. */
4661 for (thread_info *thread : all_non_exited_threads (this))
4662 {
4663 if (first == NULL)
4664 first = thread;
4665
4666 if (!non_stop)
4667 thread->set_running (false);
4668 else if (thread->state != THREAD_STOPPED)
4669 continue;
4670
4671 if (selected == nullptr && thread->has_pending_waitstatus ())
4672 selected = thread;
4673
4674 if (lowest_stopped == NULL
4675 || thread->inf->num < lowest_stopped->inf->num
4676 || thread->per_inf_num < lowest_stopped->per_inf_num)
4677 lowest_stopped = thread;
4678
4679 if (non_stop)
4680 print_one_stopped_thread (thread);
4681 }
4682
4683 /* In all-stop, we only print the status of one thread, and leave
4684 others with their status pending. */
4685 if (!non_stop)
4686 {
4687 thread_info *thread = selected;
4688 if (thread == NULL)
4689 thread = lowest_stopped;
4690 if (thread == NULL)
4691 thread = first;
4692
4693 print_one_stopped_thread (thread);
4694 }
4695 }
4696
4697 /* Mark a remote_target as marking (by setting the starting_up flag within
4698 its remote_state) for the lifetime of this object. The reference count
4699 on the remote target is temporarily incremented, to prevent the target
4700 being deleted under our feet. */
4701
4702 struct scoped_mark_target_starting
4703 {
4704 /* Constructor, TARGET is the target to be marked as starting, its
4705 reference count will be incremented. */
4706 scoped_mark_target_starting (remote_target *target)
4707 : m_remote_target (target)
4708 {
4709 m_remote_target->incref ();
4710 remote_state *rs = m_remote_target->get_remote_state ();
4711 rs->starting_up = true;
4712 }
4713
4714 /* Destructor, mark the target being worked on as no longer starting, and
4715 decrement the reference count. */
4716 ~scoped_mark_target_starting ()
4717 {
4718 remote_state *rs = m_remote_target->get_remote_state ();
4719 rs->starting_up = false;
4720 decref_target (m_remote_target);
4721 }
4722
4723 private:
4724
4725 /* The target on which we are operating. */
4726 remote_target *m_remote_target;
4727 };
4728
4729 /* Helper for remote_target::start_remote, start the remote connection and
4730 sync state. Return true if everything goes OK, otherwise, return false.
4731 This function exists so that the scoped_restore created within it will
4732 expire before we return to remote_target::start_remote. */
4733
4734 bool
4735 remote_target::start_remote_1 (int from_tty, int extended_p)
4736 {
4737 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4738
4739 struct remote_state *rs = get_remote_state ();
4740 struct packet_config *noack_config;
4741
4742 /* Signal other parts that we're going through the initial setup,
4743 and so things may not be stable yet. E.g., we don't try to
4744 install tracepoints until we've relocated symbols. Also, a
4745 Ctrl-C before we're connected and synced up can't interrupt the
4746 target. Instead, it offers to drop the (potentially wedged)
4747 connection. */
4748 scoped_mark_target_starting target_is_starting (this);
4749
4750 QUIT;
4751
4752 if (interrupt_on_connect)
4753 send_interrupt_sequence ();
4754
4755 /* Ack any packet which the remote side has already sent. */
4756 remote_serial_write ("+", 1);
4757
4758 /* The first packet we send to the target is the optional "supported
4759 packets" request. If the target can answer this, it will tell us
4760 which later probes to skip. */
4761 remote_query_supported ();
4762
4763 /* If the stub wants to get a QAllow, compose one and send it. */
4764 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4765 set_permissions ();
4766
4767 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4768 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4769 as a reply to known packet. For packet "vFile:setfs:" it is an
4770 invalid reply and GDB would return error in
4771 remote_hostio_set_filesystem, making remote files access impossible.
4772 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4773 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4774 {
4775 const char v_mustreplyempty[] = "vMustReplyEmpty";
4776
4777 putpkt (v_mustreplyempty);
4778 getpkt (&rs->buf, 0);
4779 if (strcmp (rs->buf.data (), "OK") == 0)
4780 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4781 else if (strcmp (rs->buf.data (), "") != 0)
4782 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4783 rs->buf.data ());
4784 }
4785
4786 /* Next, we possibly activate noack mode.
4787
4788 If the QStartNoAckMode packet configuration is set to AUTO,
4789 enable noack mode if the stub reported a wish for it with
4790 qSupported.
4791
4792 If set to TRUE, then enable noack mode even if the stub didn't
4793 report it in qSupported. If the stub doesn't reply OK, the
4794 session ends with an error.
4795
4796 If FALSE, then don't activate noack mode, regardless of what the
4797 stub claimed should be the default with qSupported. */
4798
4799 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4800 if (packet_config_support (noack_config) != PACKET_DISABLE)
4801 {
4802 putpkt ("QStartNoAckMode");
4803 getpkt (&rs->buf, 0);
4804 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4805 rs->noack_mode = 1;
4806 }
4807
4808 if (extended_p)
4809 {
4810 /* Tell the remote that we are using the extended protocol. */
4811 putpkt ("!");
4812 getpkt (&rs->buf, 0);
4813 }
4814
4815 /* Let the target know which signals it is allowed to pass down to
4816 the program. */
4817 update_signals_program_target ();
4818
4819 /* Next, if the target can specify a description, read it. We do
4820 this before anything involving memory or registers. */
4821 target_find_description ();
4822
4823 /* Next, now that we know something about the target, update the
4824 address spaces in the program spaces. */
4825 update_address_spaces ();
4826
4827 /* On OSs where the list of libraries is global to all
4828 processes, we fetch them early. */
4829 if (gdbarch_has_global_solist (target_gdbarch ()))
4830 solib_add (NULL, from_tty, auto_solib_add);
4831
4832 if (target_is_non_stop_p ())
4833 {
4834 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4835 error (_("Non-stop mode requested, but remote "
4836 "does not support non-stop"));
4837
4838 putpkt ("QNonStop:1");
4839 getpkt (&rs->buf, 0);
4840
4841 if (strcmp (rs->buf.data (), "OK") != 0)
4842 error (_("Remote refused setting non-stop mode with: %s"),
4843 rs->buf.data ());
4844
4845 /* Find about threads and processes the stub is already
4846 controlling. We default to adding them in the running state.
4847 The '?' query below will then tell us about which threads are
4848 stopped. */
4849 this->update_thread_list ();
4850 }
4851 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4852 {
4853 /* Don't assume that the stub can operate in all-stop mode.
4854 Request it explicitly. */
4855 putpkt ("QNonStop:0");
4856 getpkt (&rs->buf, 0);
4857
4858 if (strcmp (rs->buf.data (), "OK") != 0)
4859 error (_("Remote refused setting all-stop mode with: %s"),
4860 rs->buf.data ());
4861 }
4862
4863 /* Upload TSVs regardless of whether the target is running or not. The
4864 remote stub, such as GDBserver, may have some predefined or builtin
4865 TSVs, even if the target is not running. */
4866 if (get_trace_status (current_trace_status ()) != -1)
4867 {
4868 struct uploaded_tsv *uploaded_tsvs = NULL;
4869
4870 upload_trace_state_variables (&uploaded_tsvs);
4871 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4872 }
4873
4874 /* Check whether the target is running now. */
4875 putpkt ("?");
4876 getpkt (&rs->buf, 0);
4877
4878 if (!target_is_non_stop_p ())
4879 {
4880 char *wait_status = NULL;
4881
4882 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4883 {
4884 if (!extended_p)
4885 error (_("The target is not running (try extended-remote?)"));
4886 return false;
4887 }
4888 else
4889 {
4890 /* Save the reply for later. */
4891 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
4892 strcpy (wait_status, rs->buf.data ());
4893 }
4894
4895 /* Fetch thread list. */
4896 target_update_thread_list ();
4897
4898 /* Let the stub know that we want it to return the thread. */
4899 set_continue_thread (minus_one_ptid);
4900
4901 if (thread_count (this) == 0)
4902 {
4903 /* Target has no concept of threads at all. GDB treats
4904 non-threaded target as single-threaded; add a main
4905 thread. */
4906 thread_info *tp = add_current_inferior_and_thread (wait_status);
4907 get_remote_thread_info (tp)->set_resumed ();
4908 }
4909 else
4910 {
4911 /* We have thread information; select the thread the target
4912 says should be current. If we're reconnecting to a
4913 multi-threaded program, this will ideally be the thread
4914 that last reported an event before GDB disconnected. */
4915 ptid_t curr_thread = get_current_thread (wait_status);
4916 if (curr_thread == null_ptid)
4917 {
4918 /* Odd... The target was able to list threads, but not
4919 tell us which thread was current (no "thread"
4920 register in T stop reply?). Just pick the first
4921 thread in the thread list then. */
4922
4923 remote_debug_printf ("warning: couldn't determine remote "
4924 "current thread; picking first in list.");
4925
4926 for (thread_info *tp : all_non_exited_threads (this,
4927 minus_one_ptid))
4928 {
4929 switch_to_thread (tp);
4930 break;
4931 }
4932 }
4933 else
4934 switch_to_thread (find_thread_ptid (this, curr_thread));
4935 }
4936
4937 /* init_wait_for_inferior should be called before get_offsets in order
4938 to manage `inserted' flag in bp loc in a correct state.
4939 breakpoint_init_inferior, called from init_wait_for_inferior, set
4940 `inserted' flag to 0, while before breakpoint_re_set, called from
4941 start_remote, set `inserted' flag to 1. In the initialization of
4942 inferior, breakpoint_init_inferior should be called first, and then
4943 breakpoint_re_set can be called. If this order is broken, state of
4944 `inserted' flag is wrong, and cause some problems on breakpoint
4945 manipulation. */
4946 init_wait_for_inferior ();
4947
4948 get_offsets (); /* Get text, data & bss offsets. */
4949
4950 /* If we could not find a description using qXfer, and we know
4951 how to do it some other way, try again. This is not
4952 supported for non-stop; it could be, but it is tricky if
4953 there are no stopped threads when we connect. */
4954 if (remote_read_description_p (this)
4955 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4956 {
4957 target_clear_description ();
4958 target_find_description ();
4959 }
4960
4961 /* Use the previously fetched status. */
4962 gdb_assert (wait_status != NULL);
4963 struct notif_event *reply
4964 = remote_notif_parse (this, &notif_client_stop, wait_status);
4965 push_stop_reply ((struct stop_reply *) reply);
4966
4967 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
4968 }
4969 else
4970 {
4971 /* Clear WFI global state. Do this before finding about new
4972 threads and inferiors, and setting the current inferior.
4973 Otherwise we would clear the proceed status of the current
4974 inferior when we want its stop_soon state to be preserved
4975 (see notice_new_inferior). */
4976 init_wait_for_inferior ();
4977
4978 /* In non-stop, we will either get an "OK", meaning that there
4979 are no stopped threads at this time; or, a regular stop
4980 reply. In the latter case, there may be more than one thread
4981 stopped --- we pull them all out using the vStopped
4982 mechanism. */
4983 if (strcmp (rs->buf.data (), "OK") != 0)
4984 {
4985 struct notif_client *notif = &notif_client_stop;
4986
4987 /* remote_notif_get_pending_replies acks this one, and gets
4988 the rest out. */
4989 rs->notif_state->pending_event[notif_client_stop.id]
4990 = remote_notif_parse (this, notif, rs->buf.data ());
4991 remote_notif_get_pending_events (notif);
4992 }
4993
4994 if (thread_count (this) == 0)
4995 {
4996 if (!extended_p)
4997 error (_("The target is not running (try extended-remote?)"));
4998 return false;
4999 }
5000
5001 /* Report all signals during attach/startup. */
5002 pass_signals ({});
5003
5004 /* If there are already stopped threads, mark them stopped and
5005 report their stops before giving the prompt to the user. */
5006 process_initial_stop_replies (from_tty);
5007
5008 if (target_can_async_p ())
5009 target_async (1);
5010 }
5011
5012 /* If we connected to a live target, do some additional setup. */
5013 if (target_has_execution ())
5014 {
5015 /* No use without a symbol-file. */
5016 if (current_program_space->symfile_object_file)
5017 remote_check_symbols ();
5018 }
5019
5020 /* Possibly the target has been engaged in a trace run started
5021 previously; find out where things are at. */
5022 if (get_trace_status (current_trace_status ()) != -1)
5023 {
5024 struct uploaded_tp *uploaded_tps = NULL;
5025
5026 if (current_trace_status ()->running)
5027 printf_filtered (_("Trace is already running on the target.\n"));
5028
5029 upload_tracepoints (&uploaded_tps);
5030
5031 merge_uploaded_tracepoints (&uploaded_tps);
5032 }
5033
5034 /* Possibly the target has been engaged in a btrace record started
5035 previously; find out where things are at. */
5036 remote_btrace_maybe_reopen ();
5037
5038 return true;
5039 }
5040
5041 /* Start the remote connection and sync state. */
5042
5043 void
5044 remote_target::start_remote (int from_tty, int extended_p)
5045 {
5046 if (start_remote_1 (from_tty, extended_p)
5047 && breakpoints_should_be_inserted_now ())
5048 insert_breakpoints ();
5049 }
5050
5051 const char *
5052 remote_target::connection_string ()
5053 {
5054 remote_state *rs = get_remote_state ();
5055
5056 if (rs->remote_desc->name != NULL)
5057 return rs->remote_desc->name;
5058 else
5059 return NULL;
5060 }
5061
5062 /* Open a connection to a remote debugger.
5063 NAME is the filename used for communication. */
5064
5065 void
5066 remote_target::open (const char *name, int from_tty)
5067 {
5068 open_1 (name, from_tty, 0);
5069 }
5070
5071 /* Open a connection to a remote debugger using the extended
5072 remote gdb protocol. NAME is the filename used for communication. */
5073
5074 void
5075 extended_remote_target::open (const char *name, int from_tty)
5076 {
5077 open_1 (name, from_tty, 1 /*extended_p */);
5078 }
5079
5080 /* Reset all packets back to "unknown support". Called when opening a
5081 new connection to a remote target. */
5082
5083 static void
5084 reset_all_packet_configs_support (void)
5085 {
5086 int i;
5087
5088 for (i = 0; i < PACKET_MAX; i++)
5089 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5090 }
5091
5092 /* Initialize all packet configs. */
5093
5094 static void
5095 init_all_packet_configs (void)
5096 {
5097 int i;
5098
5099 for (i = 0; i < PACKET_MAX; i++)
5100 {
5101 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5102 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5103 }
5104 }
5105
5106 /* Symbol look-up. */
5107
5108 void
5109 remote_target::remote_check_symbols ()
5110 {
5111 char *tmp;
5112 int end;
5113
5114 /* The remote side has no concept of inferiors that aren't running
5115 yet, it only knows about running processes. If we're connected
5116 but our current inferior is not running, we should not invite the
5117 remote target to request symbol lookups related to its
5118 (unrelated) current process. */
5119 if (!target_has_execution ())
5120 return;
5121
5122 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5123 return;
5124
5125 /* Make sure the remote is pointing at the right process. Note
5126 there's no way to select "no process". */
5127 set_general_process ();
5128
5129 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5130 because we need both at the same time. */
5131 gdb::char_vector msg (get_remote_packet_size ());
5132 gdb::char_vector reply (get_remote_packet_size ());
5133
5134 /* Invite target to request symbol lookups. */
5135
5136 putpkt ("qSymbol::");
5137 getpkt (&reply, 0);
5138 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
5139
5140 while (startswith (reply.data (), "qSymbol:"))
5141 {
5142 struct bound_minimal_symbol sym;
5143
5144 tmp = &reply[8];
5145 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5146 strlen (tmp) / 2);
5147 msg[end] = '\0';
5148 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5149 if (sym.minsym == NULL)
5150 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5151 &reply[8]);
5152 else
5153 {
5154 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5155 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
5156
5157 /* If this is a function address, return the start of code
5158 instead of any data function descriptor. */
5159 sym_addr = gdbarch_convert_from_func_ptr_addr
5160 (target_gdbarch (), sym_addr, current_inferior ()->top_target ());
5161
5162 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5163 phex_nz (sym_addr, addr_size), &reply[8]);
5164 }
5165
5166 putpkt (msg.data ());
5167 getpkt (&reply, 0);
5168 }
5169 }
5170
5171 static struct serial *
5172 remote_serial_open (const char *name)
5173 {
5174 static int udp_warning = 0;
5175
5176 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5177 of in ser-tcp.c, because it is the remote protocol assuming that the
5178 serial connection is reliable and not the serial connection promising
5179 to be. */
5180 if (!udp_warning && startswith (name, "udp:"))
5181 {
5182 warning (_("The remote protocol may be unreliable over UDP.\n"
5183 "Some events may be lost, rendering further debugging "
5184 "impossible."));
5185 udp_warning = 1;
5186 }
5187
5188 return serial_open (name);
5189 }
5190
5191 /* Inform the target of our permission settings. The permission flags
5192 work without this, but if the target knows the settings, it can do
5193 a couple things. First, it can add its own check, to catch cases
5194 that somehow manage to get by the permissions checks in target
5195 methods. Second, if the target is wired to disallow particular
5196 settings (for instance, a system in the field that is not set up to
5197 be able to stop at a breakpoint), it can object to any unavailable
5198 permissions. */
5199
5200 void
5201 remote_target::set_permissions ()
5202 {
5203 struct remote_state *rs = get_remote_state ();
5204
5205 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5206 "WriteReg:%x;WriteMem:%x;"
5207 "InsertBreak:%x;InsertTrace:%x;"
5208 "InsertFastTrace:%x;Stop:%x",
5209 may_write_registers, may_write_memory,
5210 may_insert_breakpoints, may_insert_tracepoints,
5211 may_insert_fast_tracepoints, may_stop);
5212 putpkt (rs->buf);
5213 getpkt (&rs->buf, 0);
5214
5215 /* If the target didn't like the packet, warn the user. Do not try
5216 to undo the user's settings, that would just be maddening. */
5217 if (strcmp (rs->buf.data (), "OK") != 0)
5218 warning (_("Remote refused setting permissions with: %s"),
5219 rs->buf.data ());
5220 }
5221
5222 /* This type describes each known response to the qSupported
5223 packet. */
5224 struct protocol_feature
5225 {
5226 /* The name of this protocol feature. */
5227 const char *name;
5228
5229 /* The default for this protocol feature. */
5230 enum packet_support default_support;
5231
5232 /* The function to call when this feature is reported, or after
5233 qSupported processing if the feature is not supported.
5234 The first argument points to this structure. The second
5235 argument indicates whether the packet requested support be
5236 enabled, disabled, or probed (or the default, if this function
5237 is being called at the end of processing and this feature was
5238 not reported). The third argument may be NULL; if not NULL, it
5239 is a NUL-terminated string taken from the packet following
5240 this feature's name and an equals sign. */
5241 void (*func) (remote_target *remote, const struct protocol_feature *,
5242 enum packet_support, const char *);
5243
5244 /* The corresponding packet for this feature. Only used if
5245 FUNC is remote_supported_packet. */
5246 int packet;
5247 };
5248
5249 static void
5250 remote_supported_packet (remote_target *remote,
5251 const struct protocol_feature *feature,
5252 enum packet_support support,
5253 const char *argument)
5254 {
5255 if (argument)
5256 {
5257 warning (_("Remote qSupported response supplied an unexpected value for"
5258 " \"%s\"."), feature->name);
5259 return;
5260 }
5261
5262 remote_protocol_packets[feature->packet].support = support;
5263 }
5264
5265 void
5266 remote_target::remote_packet_size (const protocol_feature *feature,
5267 enum packet_support support, const char *value)
5268 {
5269 struct remote_state *rs = get_remote_state ();
5270
5271 int packet_size;
5272 char *value_end;
5273
5274 if (support != PACKET_ENABLE)
5275 return;
5276
5277 if (value == NULL || *value == '\0')
5278 {
5279 warning (_("Remote target reported \"%s\" without a size."),
5280 feature->name);
5281 return;
5282 }
5283
5284 errno = 0;
5285 packet_size = strtol (value, &value_end, 16);
5286 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5287 {
5288 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5289 feature->name, value);
5290 return;
5291 }
5292
5293 /* Record the new maximum packet size. */
5294 rs->explicit_packet_size = packet_size;
5295 }
5296
5297 static void
5298 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5299 enum packet_support support, const char *value)
5300 {
5301 remote->remote_packet_size (feature, support, value);
5302 }
5303
5304 static const struct protocol_feature remote_protocol_features[] = {
5305 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5306 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5307 PACKET_qXfer_auxv },
5308 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5309 PACKET_qXfer_exec_file },
5310 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5311 PACKET_qXfer_features },
5312 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5313 PACKET_qXfer_libraries },
5314 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5315 PACKET_qXfer_libraries_svr4 },
5316 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5317 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5318 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5319 PACKET_qXfer_memory_map },
5320 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5321 PACKET_qXfer_osdata },
5322 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5323 PACKET_qXfer_threads },
5324 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5325 PACKET_qXfer_traceframe_info },
5326 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5327 PACKET_QPassSignals },
5328 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5329 PACKET_QCatchSyscalls },
5330 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5331 PACKET_QProgramSignals },
5332 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5333 PACKET_QSetWorkingDir },
5334 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5335 PACKET_QStartupWithShell },
5336 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5337 PACKET_QEnvironmentHexEncoded },
5338 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5339 PACKET_QEnvironmentReset },
5340 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5341 PACKET_QEnvironmentUnset },
5342 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5343 PACKET_QStartNoAckMode },
5344 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5345 PACKET_multiprocess_feature },
5346 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5347 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5348 PACKET_qXfer_siginfo_read },
5349 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5350 PACKET_qXfer_siginfo_write },
5351 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5352 PACKET_ConditionalTracepoints },
5353 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5354 PACKET_ConditionalBreakpoints },
5355 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5356 PACKET_BreakpointCommands },
5357 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5358 PACKET_FastTracepoints },
5359 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5360 PACKET_StaticTracepoints },
5361 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5362 PACKET_InstallInTrace},
5363 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5364 PACKET_DisconnectedTracing_feature },
5365 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5366 PACKET_bc },
5367 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5368 PACKET_bs },
5369 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5370 PACKET_TracepointSource },
5371 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5372 PACKET_QAllow },
5373 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5374 PACKET_EnableDisableTracepoints_feature },
5375 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5376 PACKET_qXfer_fdpic },
5377 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5378 PACKET_qXfer_uib },
5379 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5380 PACKET_QDisableRandomization },
5381 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5382 { "QTBuffer:size", PACKET_DISABLE,
5383 remote_supported_packet, PACKET_QTBuffer_size},
5384 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5385 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5386 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5387 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5388 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5389 PACKET_qXfer_btrace },
5390 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5391 PACKET_qXfer_btrace_conf },
5392 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5393 PACKET_Qbtrace_conf_bts_size },
5394 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5395 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5396 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5397 PACKET_fork_event_feature },
5398 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5399 PACKET_vfork_event_feature },
5400 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5401 PACKET_exec_event_feature },
5402 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5403 PACKET_Qbtrace_conf_pt_size },
5404 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5405 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5406 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5407 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5408 PACKET_memory_tagging_feature },
5409 };
5410
5411 static char *remote_support_xml;
5412
5413 /* Register string appended to "xmlRegisters=" in qSupported query. */
5414
5415 void
5416 register_remote_support_xml (const char *xml)
5417 {
5418 #if defined(HAVE_LIBEXPAT)
5419 if (remote_support_xml == NULL)
5420 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5421 else
5422 {
5423 char *copy = xstrdup (remote_support_xml + 13);
5424 char *saveptr;
5425 char *p = strtok_r (copy, ",", &saveptr);
5426
5427 do
5428 {
5429 if (strcmp (p, xml) == 0)
5430 {
5431 /* already there */
5432 xfree (copy);
5433 return;
5434 }
5435 }
5436 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5437 xfree (copy);
5438
5439 remote_support_xml = reconcat (remote_support_xml,
5440 remote_support_xml, ",", xml,
5441 (char *) NULL);
5442 }
5443 #endif
5444 }
5445
5446 static void
5447 remote_query_supported_append (std::string *msg, const char *append)
5448 {
5449 if (!msg->empty ())
5450 msg->append (";");
5451 msg->append (append);
5452 }
5453
5454 void
5455 remote_target::remote_query_supported ()
5456 {
5457 struct remote_state *rs = get_remote_state ();
5458 char *next;
5459 int i;
5460 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5461
5462 /* The packet support flags are handled differently for this packet
5463 than for most others. We treat an error, a disabled packet, and
5464 an empty response identically: any features which must be reported
5465 to be used will be automatically disabled. An empty buffer
5466 accomplishes this, since that is also the representation for a list
5467 containing no features. */
5468
5469 rs->buf[0] = 0;
5470 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5471 {
5472 std::string q;
5473
5474 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5475 remote_query_supported_append (&q, "multiprocess+");
5476
5477 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5478 remote_query_supported_append (&q, "swbreak+");
5479 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5480 remote_query_supported_append (&q, "hwbreak+");
5481
5482 remote_query_supported_append (&q, "qRelocInsn+");
5483
5484 if (packet_set_cmd_state (PACKET_fork_event_feature)
5485 != AUTO_BOOLEAN_FALSE)
5486 remote_query_supported_append (&q, "fork-events+");
5487 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5488 != AUTO_BOOLEAN_FALSE)
5489 remote_query_supported_append (&q, "vfork-events+");
5490 if (packet_set_cmd_state (PACKET_exec_event_feature)
5491 != AUTO_BOOLEAN_FALSE)
5492 remote_query_supported_append (&q, "exec-events+");
5493
5494 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5495 remote_query_supported_append (&q, "vContSupported+");
5496
5497 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5498 remote_query_supported_append (&q, "QThreadEvents+");
5499
5500 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5501 remote_query_supported_append (&q, "no-resumed+");
5502
5503 if (packet_set_cmd_state (PACKET_memory_tagging_feature)
5504 != AUTO_BOOLEAN_FALSE)
5505 remote_query_supported_append (&q, "memory-tagging+");
5506
5507 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5508 the qSupported:xmlRegisters=i386 handling. */
5509 if (remote_support_xml != NULL
5510 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5511 remote_query_supported_append (&q, remote_support_xml);
5512
5513 q = "qSupported:" + q;
5514 putpkt (q.c_str ());
5515
5516 getpkt (&rs->buf, 0);
5517
5518 /* If an error occured, warn, but do not return - just reset the
5519 buffer to empty and go on to disable features. */
5520 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5521 == PACKET_ERROR)
5522 {
5523 warning (_("Remote failure reply: %s"), rs->buf.data ());
5524 rs->buf[0] = 0;
5525 }
5526 }
5527
5528 memset (seen, 0, sizeof (seen));
5529
5530 next = rs->buf.data ();
5531 while (*next)
5532 {
5533 enum packet_support is_supported;
5534 char *p, *end, *name_end, *value;
5535
5536 /* First separate out this item from the rest of the packet. If
5537 there's another item after this, we overwrite the separator
5538 (terminated strings are much easier to work with). */
5539 p = next;
5540 end = strchr (p, ';');
5541 if (end == NULL)
5542 {
5543 end = p + strlen (p);
5544 next = end;
5545 }
5546 else
5547 {
5548 *end = '\0';
5549 next = end + 1;
5550
5551 if (end == p)
5552 {
5553 warning (_("empty item in \"qSupported\" response"));
5554 continue;
5555 }
5556 }
5557
5558 name_end = strchr (p, '=');
5559 if (name_end)
5560 {
5561 /* This is a name=value entry. */
5562 is_supported = PACKET_ENABLE;
5563 value = name_end + 1;
5564 *name_end = '\0';
5565 }
5566 else
5567 {
5568 value = NULL;
5569 switch (end[-1])
5570 {
5571 case '+':
5572 is_supported = PACKET_ENABLE;
5573 break;
5574
5575 case '-':
5576 is_supported = PACKET_DISABLE;
5577 break;
5578
5579 case '?':
5580 is_supported = PACKET_SUPPORT_UNKNOWN;
5581 break;
5582
5583 default:
5584 warning (_("unrecognized item \"%s\" "
5585 "in \"qSupported\" response"), p);
5586 continue;
5587 }
5588 end[-1] = '\0';
5589 }
5590
5591 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5592 if (strcmp (remote_protocol_features[i].name, p) == 0)
5593 {
5594 const struct protocol_feature *feature;
5595
5596 seen[i] = 1;
5597 feature = &remote_protocol_features[i];
5598 feature->func (this, feature, is_supported, value);
5599 break;
5600 }
5601 }
5602
5603 /* If we increased the packet size, make sure to increase the global
5604 buffer size also. We delay this until after parsing the entire
5605 qSupported packet, because this is the same buffer we were
5606 parsing. */
5607 if (rs->buf.size () < rs->explicit_packet_size)
5608 rs->buf.resize (rs->explicit_packet_size);
5609
5610 /* Handle the defaults for unmentioned features. */
5611 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5612 if (!seen[i])
5613 {
5614 const struct protocol_feature *feature;
5615
5616 feature = &remote_protocol_features[i];
5617 feature->func (this, feature, feature->default_support, NULL);
5618 }
5619 }
5620
5621 /* Serial QUIT handler for the remote serial descriptor.
5622
5623 Defers handling a Ctrl-C until we're done with the current
5624 command/response packet sequence, unless:
5625
5626 - We're setting up the connection. Don't send a remote interrupt
5627 request, as we're not fully synced yet. Quit immediately
5628 instead.
5629
5630 - The target has been resumed in the foreground
5631 (target_terminal::is_ours is false) with a synchronous resume
5632 packet, and we're blocked waiting for the stop reply, thus a
5633 Ctrl-C should be immediately sent to the target.
5634
5635 - We get a second Ctrl-C while still within the same serial read or
5636 write. In that case the serial is seemingly wedged --- offer to
5637 quit/disconnect.
5638
5639 - We see a second Ctrl-C without target response, after having
5640 previously interrupted the target. In that case the target/stub
5641 is probably wedged --- offer to quit/disconnect.
5642 */
5643
5644 void
5645 remote_target::remote_serial_quit_handler ()
5646 {
5647 struct remote_state *rs = get_remote_state ();
5648
5649 if (check_quit_flag ())
5650 {
5651 /* If we're starting up, we're not fully synced yet. Quit
5652 immediately. */
5653 if (rs->starting_up)
5654 quit ();
5655 else if (rs->got_ctrlc_during_io)
5656 {
5657 if (query (_("The target is not responding to GDB commands.\n"
5658 "Stop debugging it? ")))
5659 remote_unpush_and_throw (this);
5660 }
5661 /* If ^C has already been sent once, offer to disconnect. */
5662 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5663 interrupt_query ();
5664 /* All-stop protocol, and blocked waiting for stop reply. Send
5665 an interrupt request. */
5666 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5667 target_interrupt ();
5668 else
5669 rs->got_ctrlc_during_io = 1;
5670 }
5671 }
5672
5673 /* The remote_target that is current while the quit handler is
5674 overridden with remote_serial_quit_handler. */
5675 static remote_target *curr_quit_handler_target;
5676
5677 static void
5678 remote_serial_quit_handler ()
5679 {
5680 curr_quit_handler_target->remote_serial_quit_handler ();
5681 }
5682
5683 /* Remove the remote target from the target stack of each inferior
5684 that is using it. Upper targets depend on it so remove them
5685 first. */
5686
5687 static void
5688 remote_unpush_target (remote_target *target)
5689 {
5690 /* We have to unpush the target from all inferiors, even those that
5691 aren't running. */
5692 scoped_restore_current_inferior restore_current_inferior;
5693
5694 for (inferior *inf : all_inferiors (target))
5695 {
5696 switch_to_inferior_no_thread (inf);
5697 pop_all_targets_at_and_above (process_stratum);
5698 generic_mourn_inferior ();
5699 }
5700
5701 /* Don't rely on target_close doing this when the target is popped
5702 from the last remote inferior above, because something may be
5703 holding a reference to the target higher up on the stack, meaning
5704 target_close won't be called yet. We lost the connection to the
5705 target, so clear these now, otherwise we may later throw
5706 TARGET_CLOSE_ERROR while trying to tell the remote target to
5707 close the file. */
5708 fileio_handles_invalidate_target (target);
5709 }
5710
5711 static void
5712 remote_unpush_and_throw (remote_target *target)
5713 {
5714 remote_unpush_target (target);
5715 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5716 }
5717
5718 void
5719 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5720 {
5721 remote_target *curr_remote = get_current_remote_target ();
5722
5723 if (name == 0)
5724 error (_("To open a remote debug connection, you need to specify what\n"
5725 "serial device is attached to the remote system\n"
5726 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5727
5728 /* If we're connected to a running target, target_preopen will kill it.
5729 Ask this question first, before target_preopen has a chance to kill
5730 anything. */
5731 if (curr_remote != NULL && !target_has_execution ())
5732 {
5733 if (from_tty
5734 && !query (_("Already connected to a remote target. Disconnect? ")))
5735 error (_("Still connected."));
5736 }
5737
5738 /* Here the possibly existing remote target gets unpushed. */
5739 target_preopen (from_tty);
5740
5741 remote_fileio_reset ();
5742 reopen_exec_file ();
5743 reread_symbols (from_tty);
5744
5745 remote_target *remote
5746 = (extended_p ? new extended_remote_target () : new remote_target ());
5747 target_ops_up target_holder (remote);
5748
5749 remote_state *rs = remote->get_remote_state ();
5750
5751 /* See FIXME above. */
5752 if (!target_async_permitted)
5753 rs->wait_forever_enabled_p = 1;
5754
5755 rs->remote_desc = remote_serial_open (name);
5756 if (!rs->remote_desc)
5757 perror_with_name (name);
5758
5759 if (baud_rate != -1)
5760 {
5761 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5762 {
5763 /* The requested speed could not be set. Error out to
5764 top level after closing remote_desc. Take care to
5765 set remote_desc to NULL to avoid closing remote_desc
5766 more than once. */
5767 serial_close (rs->remote_desc);
5768 rs->remote_desc = NULL;
5769 perror_with_name (name);
5770 }
5771 }
5772
5773 serial_setparity (rs->remote_desc, serial_parity);
5774 serial_raw (rs->remote_desc);
5775
5776 /* If there is something sitting in the buffer we might take it as a
5777 response to a command, which would be bad. */
5778 serial_flush_input (rs->remote_desc);
5779
5780 if (from_tty)
5781 {
5782 puts_filtered ("Remote debugging using ");
5783 puts_filtered (name);
5784 puts_filtered ("\n");
5785 }
5786
5787 /* Switch to using the remote target now. */
5788 current_inferior ()->push_target (std::move (target_holder));
5789
5790 /* Register extra event sources in the event loop. */
5791 rs->remote_async_inferior_event_token
5792 = create_async_event_handler (remote_async_inferior_event_handler, nullptr,
5793 "remote");
5794 rs->notif_state = remote_notif_state_allocate (remote);
5795
5796 /* Reset the target state; these things will be queried either by
5797 remote_query_supported or as they are needed. */
5798 reset_all_packet_configs_support ();
5799 rs->explicit_packet_size = 0;
5800 rs->noack_mode = 0;
5801 rs->extended = extended_p;
5802 rs->waiting_for_stop_reply = 0;
5803 rs->ctrlc_pending_p = 0;
5804 rs->got_ctrlc_during_io = 0;
5805
5806 rs->general_thread = not_sent_ptid;
5807 rs->continue_thread = not_sent_ptid;
5808 rs->remote_traceframe_number = -1;
5809
5810 rs->last_resume_exec_dir = EXEC_FORWARD;
5811
5812 /* Probe for ability to use "ThreadInfo" query, as required. */
5813 rs->use_threadinfo_query = 1;
5814 rs->use_threadextra_query = 1;
5815
5816 rs->readahead_cache.invalidate ();
5817
5818 if (target_async_permitted)
5819 {
5820 /* FIXME: cagney/1999-09-23: During the initial connection it is
5821 assumed that the target is already ready and able to respond to
5822 requests. Unfortunately remote_start_remote() eventually calls
5823 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5824 around this. Eventually a mechanism that allows
5825 wait_for_inferior() to expect/get timeouts will be
5826 implemented. */
5827 rs->wait_forever_enabled_p = 0;
5828 }
5829
5830 /* First delete any symbols previously loaded from shared libraries. */
5831 no_shared_libraries (NULL, 0);
5832
5833 /* Start the remote connection. If error() or QUIT, discard this
5834 target (we'd otherwise be in an inconsistent state) and then
5835 propogate the error on up the exception chain. This ensures that
5836 the caller doesn't stumble along blindly assuming that the
5837 function succeeded. The CLI doesn't have this problem but other
5838 UI's, such as MI do.
5839
5840 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5841 this function should return an error indication letting the
5842 caller restore the previous state. Unfortunately the command
5843 ``target remote'' is directly wired to this function making that
5844 impossible. On a positive note, the CLI side of this problem has
5845 been fixed - the function set_cmd_context() makes it possible for
5846 all the ``target ....'' commands to share a common callback
5847 function. See cli-dump.c. */
5848 {
5849
5850 try
5851 {
5852 remote->start_remote (from_tty, extended_p);
5853 }
5854 catch (const gdb_exception &ex)
5855 {
5856 /* Pop the partially set up target - unless something else did
5857 already before throwing the exception. */
5858 if (ex.error != TARGET_CLOSE_ERROR)
5859 remote_unpush_target (remote);
5860 throw;
5861 }
5862 }
5863
5864 remote_btrace_reset (rs);
5865
5866 if (target_async_permitted)
5867 rs->wait_forever_enabled_p = 1;
5868 }
5869
5870 /* Determine if WS represents a fork status. */
5871
5872 static bool
5873 is_fork_status (target_waitkind kind)
5874 {
5875 return (kind == TARGET_WAITKIND_FORKED
5876 || kind == TARGET_WAITKIND_VFORKED);
5877 }
5878
5879 /* Return THREAD's pending status if it is a pending fork parent, else
5880 return nullptr. */
5881
5882 static const target_waitstatus *
5883 thread_pending_fork_status (struct thread_info *thread)
5884 {
5885 const target_waitstatus &ws
5886 = (thread->has_pending_waitstatus ()
5887 ? thread->pending_waitstatus ()
5888 : thread->pending_follow);
5889
5890 if (!is_fork_status (ws.kind ()))
5891 return nullptr;
5892
5893 return &ws;
5894 }
5895
5896 /* Detach the specified process. */
5897
5898 void
5899 remote_target::remote_detach_pid (int pid)
5900 {
5901 struct remote_state *rs = get_remote_state ();
5902
5903 /* This should not be necessary, but the handling for D;PID in
5904 GDBserver versions prior to 8.2 incorrectly assumes that the
5905 selected process points to the same process we're detaching,
5906 leading to misbehavior (and possibly GDBserver crashing) when it
5907 does not. Since it's easy and cheap, work around it by forcing
5908 GDBserver to select GDB's current process. */
5909 set_general_process ();
5910
5911 if (remote_multi_process_p (rs))
5912 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
5913 else
5914 strcpy (rs->buf.data (), "D");
5915
5916 putpkt (rs->buf);
5917 getpkt (&rs->buf, 0);
5918
5919 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5920 ;
5921 else if (rs->buf[0] == '\0')
5922 error (_("Remote doesn't know how to detach"));
5923 else
5924 error (_("Can't detach process."));
5925 }
5926
5927 /* This detaches a program to which we previously attached, using
5928 inferior_ptid to identify the process. After this is done, GDB
5929 can be used to debug some other program. We better not have left
5930 any breakpoints in the target program or it'll die when it hits
5931 one. */
5932
5933 void
5934 remote_target::remote_detach_1 (inferior *inf, int from_tty)
5935 {
5936 int pid = inferior_ptid.pid ();
5937 struct remote_state *rs = get_remote_state ();
5938 int is_fork_parent;
5939
5940 if (!target_has_execution ())
5941 error (_("No process to detach from."));
5942
5943 target_announce_detach (from_tty);
5944
5945 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
5946 {
5947 /* If we're in breakpoints-always-inserted mode, or the inferior
5948 is running, we have to remove breakpoints before detaching.
5949 We don't do this in common code instead because not all
5950 targets support removing breakpoints while the target is
5951 running. The remote target / gdbserver does, though. */
5952 remove_breakpoints_inf (current_inferior ());
5953 }
5954
5955 /* Tell the remote target to detach. */
5956 remote_detach_pid (pid);
5957
5958 /* Exit only if this is the only active inferior. */
5959 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
5960 puts_filtered (_("Ending remote debugging.\n"));
5961
5962 /* See if any thread of the inferior we are detaching has a pending fork
5963 status. In that case, we must detach from the child resulting from
5964 that fork. */
5965 for (thread_info *thread : inf->non_exited_threads ())
5966 {
5967 const target_waitstatus *ws = thread_pending_fork_status (thread);
5968
5969 if (ws == nullptr)
5970 continue;
5971
5972 remote_detach_pid (ws->child_ptid ().pid ());
5973 }
5974
5975 /* Check also for any pending fork events in the stop reply queue. */
5976 remote_notif_get_pending_events (&notif_client_stop);
5977 for (stop_reply_up &reply : rs->stop_reply_queue)
5978 {
5979 if (reply->ptid.pid () != pid)
5980 continue;
5981
5982 if (!is_fork_status (reply->ws.kind ()))
5983 continue;
5984
5985 remote_detach_pid (reply->ws.child_ptid ().pid ());
5986 }
5987
5988 thread_info *tp = find_thread_ptid (this, inferior_ptid);
5989
5990 /* Check to see if we are detaching a fork parent. Note that if we
5991 are detaching a fork child, tp == NULL. */
5992 is_fork_parent = (tp != NULL
5993 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
5994
5995 /* If doing detach-on-fork, we don't mourn, because that will delete
5996 breakpoints that should be available for the followed inferior. */
5997 if (!is_fork_parent)
5998 {
5999 /* Save the pid as a string before mourning, since that will
6000 unpush the remote target, and we need the string after. */
6001 std::string infpid = target_pid_to_str (ptid_t (pid));
6002
6003 target_mourn_inferior (inferior_ptid);
6004 if (print_inferior_events)
6005 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
6006 inf->num, infpid.c_str ());
6007 }
6008 else
6009 {
6010 switch_to_no_thread ();
6011 detach_inferior (current_inferior ());
6012 }
6013 }
6014
6015 void
6016 remote_target::detach (inferior *inf, int from_tty)
6017 {
6018 remote_detach_1 (inf, from_tty);
6019 }
6020
6021 void
6022 extended_remote_target::detach (inferior *inf, int from_tty)
6023 {
6024 remote_detach_1 (inf, from_tty);
6025 }
6026
6027 /* Target follow-fork function for remote targets. On entry, and
6028 at return, the current inferior is the fork parent.
6029
6030 Note that although this is currently only used for extended-remote,
6031 it is named remote_follow_fork in anticipation of using it for the
6032 remote target as well. */
6033
6034 void
6035 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6036 target_waitkind fork_kind, bool follow_child,
6037 bool detach_fork)
6038 {
6039 process_stratum_target::follow_fork (child_inf, child_ptid,
6040 fork_kind, follow_child, detach_fork);
6041
6042 struct remote_state *rs = get_remote_state ();
6043
6044 if ((fork_kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
6045 || (fork_kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
6046 {
6047 /* When following the parent and detaching the child, we detach
6048 the child here. For the case of following the child and
6049 detaching the parent, the detach is done in the target-
6050 independent follow fork code in infrun.c. We can't use
6051 target_detach when detaching an unfollowed child because
6052 the client side doesn't know anything about the child. */
6053 if (detach_fork && !follow_child)
6054 {
6055 /* Detach the fork child. */
6056 remote_detach_pid (child_ptid.pid ());
6057 }
6058 }
6059 }
6060
6061 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6062 in the program space of the new inferior. */
6063
6064 void
6065 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6066 const char *execd_pathname)
6067 {
6068 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6069
6070 /* We know that this is a target file name, so if it has the "target:"
6071 prefix we strip it off before saving it in the program space. */
6072 if (is_target_filename (execd_pathname))
6073 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6074
6075 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6076 }
6077
6078 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6079
6080 void
6081 remote_target::disconnect (const char *args, int from_tty)
6082 {
6083 if (args)
6084 error (_("Argument given to \"disconnect\" when remotely debugging."));
6085
6086 /* Make sure we unpush even the extended remote targets. Calling
6087 target_mourn_inferior won't unpush, and
6088 remote_target::mourn_inferior won't unpush if there is more than
6089 one inferior left. */
6090 remote_unpush_target (this);
6091
6092 if (from_tty)
6093 puts_filtered ("Ending remote debugging.\n");
6094 }
6095
6096 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6097 be chatty about it. */
6098
6099 void
6100 extended_remote_target::attach (const char *args, int from_tty)
6101 {
6102 struct remote_state *rs = get_remote_state ();
6103 int pid;
6104 char *wait_status = NULL;
6105
6106 pid = parse_pid_to_attach (args);
6107
6108 /* Remote PID can be freely equal to getpid, do not check it here the same
6109 way as in other targets. */
6110
6111 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
6112 error (_("This target does not support attaching to a process"));
6113
6114 if (from_tty)
6115 {
6116 const char *exec_file = get_exec_file (0);
6117
6118 if (exec_file)
6119 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
6120 target_pid_to_str (ptid_t (pid)).c_str ());
6121 else
6122 printf_unfiltered (_("Attaching to %s\n"),
6123 target_pid_to_str (ptid_t (pid)).c_str ());
6124 }
6125
6126 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6127 putpkt (rs->buf);
6128 getpkt (&rs->buf, 0);
6129
6130 switch (packet_ok (rs->buf,
6131 &remote_protocol_packets[PACKET_vAttach]))
6132 {
6133 case PACKET_OK:
6134 if (!target_is_non_stop_p ())
6135 {
6136 /* Save the reply for later. */
6137 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6138 strcpy (wait_status, rs->buf.data ());
6139 }
6140 else if (strcmp (rs->buf.data (), "OK") != 0)
6141 error (_("Attaching to %s failed with: %s"),
6142 target_pid_to_str (ptid_t (pid)).c_str (),
6143 rs->buf.data ());
6144 break;
6145 case PACKET_UNKNOWN:
6146 error (_("This target does not support attaching to a process"));
6147 default:
6148 error (_("Attaching to %s failed"),
6149 target_pid_to_str (ptid_t (pid)).c_str ());
6150 }
6151
6152 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6153
6154 inferior_ptid = ptid_t (pid);
6155
6156 if (target_is_non_stop_p ())
6157 {
6158 /* Get list of threads. */
6159 update_thread_list ();
6160
6161 thread_info *thread = first_thread_of_inferior (current_inferior ());
6162 if (thread != nullptr)
6163 switch_to_thread (thread);
6164
6165 /* Invalidate our notion of the remote current thread. */
6166 record_currthread (rs, minus_one_ptid);
6167 }
6168 else
6169 {
6170 /* Now, if we have thread information, update the main thread's
6171 ptid. */
6172 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6173
6174 /* Add the main thread to the thread list. */
6175 thread_info *thr = add_thread_silent (this, curr_ptid);
6176
6177 switch_to_thread (thr);
6178
6179 /* Don't consider the thread stopped until we've processed the
6180 saved stop reply. */
6181 set_executing (this, thr->ptid, true);
6182 }
6183
6184 /* Next, if the target can specify a description, read it. We do
6185 this before anything involving memory or registers. */
6186 target_find_description ();
6187
6188 if (!target_is_non_stop_p ())
6189 {
6190 /* Use the previously fetched status. */
6191 gdb_assert (wait_status != NULL);
6192
6193 struct notif_event *reply
6194 = remote_notif_parse (this, &notif_client_stop, wait_status);
6195
6196 push_stop_reply ((struct stop_reply *) reply);
6197
6198 if (target_can_async_p ())
6199 target_async (1);
6200 }
6201 else
6202 {
6203 gdb_assert (wait_status == NULL);
6204
6205 gdb_assert (target_can_async_p ());
6206 target_async (1);
6207 }
6208 }
6209
6210 /* Implementation of the to_post_attach method. */
6211
6212 void
6213 extended_remote_target::post_attach (int pid)
6214 {
6215 /* Get text, data & bss offsets. */
6216 get_offsets ();
6217
6218 /* In certain cases GDB might not have had the chance to start
6219 symbol lookup up until now. This could happen if the debugged
6220 binary is not using shared libraries, the vsyscall page is not
6221 present (on Linux) and the binary itself hadn't changed since the
6222 debugging process was started. */
6223 if (current_program_space->symfile_object_file != NULL)
6224 remote_check_symbols();
6225 }
6226
6227 \f
6228 /* Check for the availability of vCont. This function should also check
6229 the response. */
6230
6231 void
6232 remote_target::remote_vcont_probe ()
6233 {
6234 remote_state *rs = get_remote_state ();
6235 char *buf;
6236
6237 strcpy (rs->buf.data (), "vCont?");
6238 putpkt (rs->buf);
6239 getpkt (&rs->buf, 0);
6240 buf = rs->buf.data ();
6241
6242 /* Make sure that the features we assume are supported. */
6243 if (startswith (buf, "vCont"))
6244 {
6245 char *p = &buf[5];
6246 int support_c, support_C;
6247
6248 rs->supports_vCont.s = 0;
6249 rs->supports_vCont.S = 0;
6250 support_c = 0;
6251 support_C = 0;
6252 rs->supports_vCont.t = 0;
6253 rs->supports_vCont.r = 0;
6254 while (p && *p == ';')
6255 {
6256 p++;
6257 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6258 rs->supports_vCont.s = 1;
6259 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6260 rs->supports_vCont.S = 1;
6261 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6262 support_c = 1;
6263 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6264 support_C = 1;
6265 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6266 rs->supports_vCont.t = 1;
6267 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6268 rs->supports_vCont.r = 1;
6269
6270 p = strchr (p, ';');
6271 }
6272
6273 /* If c, and C are not all supported, we can't use vCont. Clearing
6274 BUF will make packet_ok disable the packet. */
6275 if (!support_c || !support_C)
6276 buf[0] = 0;
6277 }
6278
6279 packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCont]);
6280 rs->supports_vCont_probed = true;
6281 }
6282
6283 /* Helper function for building "vCont" resumptions. Write a
6284 resumption to P. ENDP points to one-passed-the-end of the buffer
6285 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6286 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6287 resumed thread should be single-stepped and/or signalled. If PTID
6288 equals minus_one_ptid, then all threads are resumed; if PTID
6289 represents a process, then all threads of the process are resumed;
6290 the thread to be stepped and/or signalled is given in the global
6291 INFERIOR_PTID. */
6292
6293 char *
6294 remote_target::append_resumption (char *p, char *endp,
6295 ptid_t ptid, int step, gdb_signal siggnal)
6296 {
6297 struct remote_state *rs = get_remote_state ();
6298
6299 if (step && siggnal != GDB_SIGNAL_0)
6300 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6301 else if (step
6302 /* GDB is willing to range step. */
6303 && use_range_stepping
6304 /* Target supports range stepping. */
6305 && rs->supports_vCont.r
6306 /* We don't currently support range stepping multiple
6307 threads with a wildcard (though the protocol allows it,
6308 so stubs shouldn't make an active effort to forbid
6309 it). */
6310 && !(remote_multi_process_p (rs) && ptid.is_pid ()))
6311 {
6312 struct thread_info *tp;
6313
6314 if (ptid == minus_one_ptid)
6315 {
6316 /* If we don't know about the target thread's tid, then
6317 we're resuming magic_null_ptid (see caller). */
6318 tp = find_thread_ptid (this, magic_null_ptid);
6319 }
6320 else
6321 tp = find_thread_ptid (this, ptid);
6322 gdb_assert (tp != NULL);
6323
6324 if (tp->control.may_range_step)
6325 {
6326 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6327
6328 p += xsnprintf (p, endp - p, ";r%s,%s",
6329 phex_nz (tp->control.step_range_start,
6330 addr_size),
6331 phex_nz (tp->control.step_range_end,
6332 addr_size));
6333 }
6334 else
6335 p += xsnprintf (p, endp - p, ";s");
6336 }
6337 else if (step)
6338 p += xsnprintf (p, endp - p, ";s");
6339 else if (siggnal != GDB_SIGNAL_0)
6340 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6341 else
6342 p += xsnprintf (p, endp - p, ";c");
6343
6344 if (remote_multi_process_p (rs) && ptid.is_pid ())
6345 {
6346 ptid_t nptid;
6347
6348 /* All (-1) threads of process. */
6349 nptid = ptid_t (ptid.pid (), -1);
6350
6351 p += xsnprintf (p, endp - p, ":");
6352 p = write_ptid (p, endp, nptid);
6353 }
6354 else if (ptid != minus_one_ptid)
6355 {
6356 p += xsnprintf (p, endp - p, ":");
6357 p = write_ptid (p, endp, ptid);
6358 }
6359
6360 return p;
6361 }
6362
6363 /* Clear the thread's private info on resume. */
6364
6365 static void
6366 resume_clear_thread_private_info (struct thread_info *thread)
6367 {
6368 if (thread->priv != NULL)
6369 {
6370 remote_thread_info *priv = get_remote_thread_info (thread);
6371
6372 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6373 priv->watch_data_address = 0;
6374 }
6375 }
6376
6377 /* Append a vCont continue-with-signal action for threads that have a
6378 non-zero stop signal. */
6379
6380 char *
6381 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6382 ptid_t ptid)
6383 {
6384 for (thread_info *thread : all_non_exited_threads (this, ptid))
6385 if (inferior_ptid != thread->ptid
6386 && thread->stop_signal () != GDB_SIGNAL_0)
6387 {
6388 p = append_resumption (p, endp, thread->ptid,
6389 0, thread->stop_signal ());
6390 thread->set_stop_signal (GDB_SIGNAL_0);
6391 resume_clear_thread_private_info (thread);
6392 }
6393
6394 return p;
6395 }
6396
6397 /* Set the target running, using the packets that use Hc
6398 (c/s/C/S). */
6399
6400 void
6401 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6402 gdb_signal siggnal)
6403 {
6404 struct remote_state *rs = get_remote_state ();
6405 char *buf;
6406
6407 rs->last_sent_signal = siggnal;
6408 rs->last_sent_step = step;
6409
6410 /* The c/s/C/S resume packets use Hc, so set the continue
6411 thread. */
6412 if (ptid == minus_one_ptid)
6413 set_continue_thread (any_thread_ptid);
6414 else
6415 set_continue_thread (ptid);
6416
6417 for (thread_info *thread : all_non_exited_threads (this))
6418 resume_clear_thread_private_info (thread);
6419
6420 buf = rs->buf.data ();
6421 if (::execution_direction == EXEC_REVERSE)
6422 {
6423 /* We don't pass signals to the target in reverse exec mode. */
6424 if (info_verbose && siggnal != GDB_SIGNAL_0)
6425 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6426 siggnal);
6427
6428 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6429 error (_("Remote reverse-step not supported."));
6430 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6431 error (_("Remote reverse-continue not supported."));
6432
6433 strcpy (buf, step ? "bs" : "bc");
6434 }
6435 else if (siggnal != GDB_SIGNAL_0)
6436 {
6437 buf[0] = step ? 'S' : 'C';
6438 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6439 buf[2] = tohex (((int) siggnal) & 0xf);
6440 buf[3] = '\0';
6441 }
6442 else
6443 strcpy (buf, step ? "s" : "c");
6444
6445 putpkt (buf);
6446 }
6447
6448 /* Resume the remote inferior by using a "vCont" packet. The thread
6449 to be resumed is PTID; STEP and SIGGNAL indicate whether the
6450 resumed thread should be single-stepped and/or signalled. If PTID
6451 equals minus_one_ptid, then all threads are resumed; the thread to
6452 be stepped and/or signalled is given in the global INFERIOR_PTID.
6453 This function returns non-zero iff it resumes the inferior.
6454
6455 This function issues a strict subset of all possible vCont commands
6456 at the moment. */
6457
6458 int
6459 remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6460 enum gdb_signal siggnal)
6461 {
6462 struct remote_state *rs = get_remote_state ();
6463 char *p;
6464 char *endp;
6465
6466 /* No reverse execution actions defined for vCont. */
6467 if (::execution_direction == EXEC_REVERSE)
6468 return 0;
6469
6470 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6471 remote_vcont_probe ();
6472
6473 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6474 return 0;
6475
6476 p = rs->buf.data ();
6477 endp = p + get_remote_packet_size ();
6478
6479 /* If we could generate a wider range of packets, we'd have to worry
6480 about overflowing BUF. Should there be a generic
6481 "multi-part-packet" packet? */
6482
6483 p += xsnprintf (p, endp - p, "vCont");
6484
6485 if (ptid == magic_null_ptid)
6486 {
6487 /* MAGIC_NULL_PTID means that we don't have any active threads,
6488 so we don't have any TID numbers the inferior will
6489 understand. Make sure to only send forms that do not specify
6490 a TID. */
6491 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6492 }
6493 else if (ptid == minus_one_ptid || ptid.is_pid ())
6494 {
6495 /* Resume all threads (of all processes, or of a single
6496 process), with preference for INFERIOR_PTID. This assumes
6497 inferior_ptid belongs to the set of all threads we are about
6498 to resume. */
6499 if (step || siggnal != GDB_SIGNAL_0)
6500 {
6501 /* Step inferior_ptid, with or without signal. */
6502 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6503 }
6504
6505 /* Also pass down any pending signaled resumption for other
6506 threads not the current. */
6507 p = append_pending_thread_resumptions (p, endp, ptid);
6508
6509 /* And continue others without a signal. */
6510 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
6511 }
6512 else
6513 {
6514 /* Scheduler locking; resume only PTID. */
6515 append_resumption (p, endp, ptid, step, siggnal);
6516 }
6517
6518 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6519 putpkt (rs->buf);
6520
6521 if (target_is_non_stop_p ())
6522 {
6523 /* In non-stop, the stub replies to vCont with "OK". The stop
6524 reply will be reported asynchronously by means of a `%Stop'
6525 notification. */
6526 getpkt (&rs->buf, 0);
6527 if (strcmp (rs->buf.data (), "OK") != 0)
6528 error (_("Unexpected vCont reply in non-stop mode: %s"),
6529 rs->buf.data ());
6530 }
6531
6532 return 1;
6533 }
6534
6535 /* Tell the remote machine to resume. */
6536
6537 void
6538 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
6539 {
6540 struct remote_state *rs = get_remote_state ();
6541
6542 /* When connected in non-stop mode, the core resumes threads
6543 individually. Resuming remote threads directly in target_resume
6544 would thus result in sending one packet per thread. Instead, to
6545 minimize roundtrip latency, here we just store the resume
6546 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6547 resumption will be done in remote_target::commit_resume, where we'll be
6548 able to do vCont action coalescing. */
6549 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6550 {
6551 remote_thread_info *remote_thr;
6552
6553 if (minus_one_ptid == ptid || ptid.is_pid ())
6554 remote_thr = get_remote_thread_info (this, inferior_ptid);
6555 else
6556 remote_thr = get_remote_thread_info (this, ptid);
6557
6558 /* We don't expect the core to ask to resume an already resumed (from
6559 its point of view) thread. */
6560 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6561
6562 remote_thr->set_resumed_pending_vcont (step, siggnal);
6563 return;
6564 }
6565
6566 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6567 (explained in remote-notif.c:handle_notification) so
6568 remote_notif_process is not called. We need find a place where
6569 it is safe to start a 'vNotif' sequence. It is good to do it
6570 before resuming inferior, because inferior was stopped and no RSP
6571 traffic at that moment. */
6572 if (!target_is_non_stop_p ())
6573 remote_notif_process (rs->notif_state, &notif_client_stop);
6574
6575 rs->last_resume_exec_dir = ::execution_direction;
6576
6577 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6578 if (!remote_resume_with_vcont (ptid, step, siggnal))
6579 remote_resume_with_hc (ptid, step, siggnal);
6580
6581 /* Update resumed state tracked by the remote target. */
6582 for (thread_info *tp : all_non_exited_threads (this, ptid))
6583 get_remote_thread_info (tp)->set_resumed ();
6584
6585 /* We are about to start executing the inferior, let's register it
6586 with the event loop. NOTE: this is the one place where all the
6587 execution commands end up. We could alternatively do this in each
6588 of the execution commands in infcmd.c. */
6589 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6590 into infcmd.c in order to allow inferior function calls to work
6591 NOT asynchronously. */
6592 if (target_can_async_p ())
6593 target_async (1);
6594
6595 /* We've just told the target to resume. The remote server will
6596 wait for the inferior to stop, and then send a stop reply. In
6597 the mean time, we can't start another command/query ourselves
6598 because the stub wouldn't be ready to process it. This applies
6599 only to the base all-stop protocol, however. In non-stop (which
6600 only supports vCont), the stub replies with an "OK", and is
6601 immediate able to process further serial input. */
6602 if (!target_is_non_stop_p ())
6603 rs->waiting_for_stop_reply = 1;
6604 }
6605
6606 /* Private per-inferior info for target remote processes. */
6607
6608 struct remote_inferior : public private_inferior
6609 {
6610 /* Whether we can send a wildcard vCont for this process. */
6611 bool may_wildcard_vcont = true;
6612 };
6613
6614 /* Get the remote private inferior data associated to INF. */
6615
6616 static remote_inferior *
6617 get_remote_inferior (inferior *inf)
6618 {
6619 if (inf->priv == NULL)
6620 inf->priv.reset (new remote_inferior);
6621
6622 return static_cast<remote_inferior *> (inf->priv.get ());
6623 }
6624
6625 /* Class used to track the construction of a vCont packet in the
6626 outgoing packet buffer. This is used to send multiple vCont
6627 packets if we have more actions than would fit a single packet. */
6628
6629 class vcont_builder
6630 {
6631 public:
6632 explicit vcont_builder (remote_target *remote)
6633 : m_remote (remote)
6634 {
6635 restart ();
6636 }
6637
6638 void flush ();
6639 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6640
6641 private:
6642 void restart ();
6643
6644 /* The remote target. */
6645 remote_target *m_remote;
6646
6647 /* Pointer to the first action. P points here if no action has been
6648 appended yet. */
6649 char *m_first_action;
6650
6651 /* Where the next action will be appended. */
6652 char *m_p;
6653
6654 /* The end of the buffer. Must never write past this. */
6655 char *m_endp;
6656 };
6657
6658 /* Prepare the outgoing buffer for a new vCont packet. */
6659
6660 void
6661 vcont_builder::restart ()
6662 {
6663 struct remote_state *rs = m_remote->get_remote_state ();
6664
6665 m_p = rs->buf.data ();
6666 m_endp = m_p + m_remote->get_remote_packet_size ();
6667 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6668 m_first_action = m_p;
6669 }
6670
6671 /* If the vCont packet being built has any action, send it to the
6672 remote end. */
6673
6674 void
6675 vcont_builder::flush ()
6676 {
6677 struct remote_state *rs;
6678
6679 if (m_p == m_first_action)
6680 return;
6681
6682 rs = m_remote->get_remote_state ();
6683 m_remote->putpkt (rs->buf);
6684 m_remote->getpkt (&rs->buf, 0);
6685 if (strcmp (rs->buf.data (), "OK") != 0)
6686 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
6687 }
6688
6689 /* The largest action is range-stepping, with its two addresses. This
6690 is more than sufficient. If a new, bigger action is created, it'll
6691 quickly trigger a failed assertion in append_resumption (and we'll
6692 just bump this). */
6693 #define MAX_ACTION_SIZE 200
6694
6695 /* Append a new vCont action in the outgoing packet being built. If
6696 the action doesn't fit the packet along with previous actions, push
6697 what we've got so far to the remote end and start over a new vCont
6698 packet (with the new action). */
6699
6700 void
6701 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6702 {
6703 char buf[MAX_ACTION_SIZE + 1];
6704
6705 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6706 ptid, step, siggnal);
6707
6708 /* Check whether this new action would fit in the vCont packet along
6709 with previous actions. If not, send what we've got so far and
6710 start a new vCont packet. */
6711 size_t rsize = endp - buf;
6712 if (rsize > m_endp - m_p)
6713 {
6714 flush ();
6715 restart ();
6716
6717 /* Should now fit. */
6718 gdb_assert (rsize <= m_endp - m_p);
6719 }
6720
6721 memcpy (m_p, buf, rsize);
6722 m_p += rsize;
6723 *m_p = '\0';
6724 }
6725
6726 /* to_commit_resume implementation. */
6727
6728 void
6729 remote_target::commit_resumed ()
6730 {
6731 /* If connected in all-stop mode, we'd send the remote resume
6732 request directly from remote_resume. Likewise if
6733 reverse-debugging, as there are no defined vCont actions for
6734 reverse execution. */
6735 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6736 return;
6737
6738 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6739 instead of resuming all threads of each process individually.
6740 However, if any thread of a process must remain halted, we can't
6741 send wildcard resumes and must send one action per thread.
6742
6743 Care must be taken to not resume threads/processes the server
6744 side already told us are stopped, but the core doesn't know about
6745 yet, because the events are still in the vStopped notification
6746 queue. For example:
6747
6748 #1 => vCont s:p1.1;c
6749 #2 <= OK
6750 #3 <= %Stopped T05 p1.1
6751 #4 => vStopped
6752 #5 <= T05 p1.2
6753 #6 => vStopped
6754 #7 <= OK
6755 #8 (infrun handles the stop for p1.1 and continues stepping)
6756 #9 => vCont s:p1.1;c
6757
6758 The last vCont above would resume thread p1.2 by mistake, because
6759 the server has no idea that the event for p1.2 had not been
6760 handled yet.
6761
6762 The server side must similarly ignore resume actions for the
6763 thread that has a pending %Stopped notification (and any other
6764 threads with events pending), until GDB acks the notification
6765 with vStopped. Otherwise, e.g., the following case is
6766 mishandled:
6767
6768 #1 => g (or any other packet)
6769 #2 <= [registers]
6770 #3 <= %Stopped T05 p1.2
6771 #4 => vCont s:p1.1;c
6772 #5 <= OK
6773
6774 Above, the server must not resume thread p1.2. GDB can't know
6775 that p1.2 stopped until it acks the %Stopped notification, and
6776 since from GDB's perspective all threads should be running, it
6777 sends a "c" action.
6778
6779 Finally, special care must also be given to handling fork/vfork
6780 events. A (v)fork event actually tells us that two processes
6781 stopped -- the parent and the child. Until we follow the fork,
6782 we must not resume the child. Therefore, if we have a pending
6783 fork follow, we must not send a global wildcard resume action
6784 (vCont;c). We can still send process-wide wildcards though. */
6785
6786 /* Start by assuming a global wildcard (vCont;c) is possible. */
6787 bool may_global_wildcard_vcont = true;
6788
6789 /* And assume every process is individually wildcard-able too. */
6790 for (inferior *inf : all_non_exited_inferiors (this))
6791 {
6792 remote_inferior *priv = get_remote_inferior (inf);
6793
6794 priv->may_wildcard_vcont = true;
6795 }
6796
6797 /* Check for any pending events (not reported or processed yet) and
6798 disable process and global wildcard resumes appropriately. */
6799 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6800
6801 bool any_pending_vcont_resume = false;
6802
6803 for (thread_info *tp : all_non_exited_threads (this))
6804 {
6805 remote_thread_info *priv = get_remote_thread_info (tp);
6806
6807 /* If a thread of a process is not meant to be resumed, then we
6808 can't wildcard that process. */
6809 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
6810 {
6811 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6812
6813 /* And if we can't wildcard a process, we can't wildcard
6814 everything either. */
6815 may_global_wildcard_vcont = false;
6816 continue;
6817 }
6818
6819 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
6820 any_pending_vcont_resume = true;
6821
6822 /* If a thread is the parent of an unfollowed fork, then we
6823 can't do a global wildcard, as that would resume the fork
6824 child. */
6825 if (thread_pending_fork_status (tp) != nullptr)
6826 may_global_wildcard_vcont = false;
6827 }
6828
6829 /* We didn't have any resumed thread pending a vCont resume, so nothing to
6830 do. */
6831 if (!any_pending_vcont_resume)
6832 return;
6833
6834 /* Now let's build the vCont packet(s). Actions must be appended
6835 from narrower to wider scopes (thread -> process -> global). If
6836 we end up with too many actions for a single packet vcont_builder
6837 flushes the current vCont packet to the remote side and starts a
6838 new one. */
6839 struct vcont_builder vcont_builder (this);
6840
6841 /* Threads first. */
6842 for (thread_info *tp : all_non_exited_threads (this))
6843 {
6844 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6845
6846 /* If the thread was previously vCont-resumed, no need to send a specific
6847 action for it. If we didn't receive a resume request for it, don't
6848 send an action for it either. */
6849 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
6850 continue;
6851
6852 gdb_assert (!thread_is_in_step_over_chain (tp));
6853
6854 /* We should never be commit-resuming a thread that has a stop reply.
6855 Otherwise, we would end up reporting a stop event for a thread while
6856 it is running on the remote target. */
6857 remote_state *rs = get_remote_state ();
6858 for (const auto &stop_reply : rs->stop_reply_queue)
6859 gdb_assert (stop_reply->ptid != tp->ptid);
6860
6861 const resumed_pending_vcont_info &info
6862 = remote_thr->resumed_pending_vcont_info ();
6863
6864 /* Check if we need to send a specific action for this thread. If not,
6865 it will be included in a wildcard resume instead. */
6866 if (info.step || info.sig != GDB_SIGNAL_0
6867 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
6868 vcont_builder.push_action (tp->ptid, info.step, info.sig);
6869
6870 remote_thr->set_resumed ();
6871 }
6872
6873 /* Now check whether we can send any process-wide wildcard. This is
6874 to avoid sending a global wildcard in the case nothing is
6875 supposed to be resumed. */
6876 bool any_process_wildcard = false;
6877
6878 for (inferior *inf : all_non_exited_inferiors (this))
6879 {
6880 if (get_remote_inferior (inf)->may_wildcard_vcont)
6881 {
6882 any_process_wildcard = true;
6883 break;
6884 }
6885 }
6886
6887 if (any_process_wildcard)
6888 {
6889 /* If all processes are wildcard-able, then send a single "c"
6890 action, otherwise, send an "all (-1) threads of process"
6891 continue action for each running process, if any. */
6892 if (may_global_wildcard_vcont)
6893 {
6894 vcont_builder.push_action (minus_one_ptid,
6895 false, GDB_SIGNAL_0);
6896 }
6897 else
6898 {
6899 for (inferior *inf : all_non_exited_inferiors (this))
6900 {
6901 if (get_remote_inferior (inf)->may_wildcard_vcont)
6902 {
6903 vcont_builder.push_action (ptid_t (inf->pid),
6904 false, GDB_SIGNAL_0);
6905 }
6906 }
6907 }
6908 }
6909
6910 vcont_builder.flush ();
6911 }
6912
6913 /* Implementation of target_has_pending_events. */
6914
6915 bool
6916 remote_target::has_pending_events ()
6917 {
6918 if (target_can_async_p ())
6919 {
6920 remote_state *rs = get_remote_state ();
6921
6922 if (async_event_handler_marked (rs->remote_async_inferior_event_token))
6923 return true;
6924
6925 /* Note that BUFCNT can be negative, indicating sticky
6926 error. */
6927 if (rs->remote_desc->bufcnt != 0)
6928 return true;
6929 }
6930 return false;
6931 }
6932
6933 \f
6934
6935 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6936 thread, all threads of a remote process, or all threads of all
6937 processes. */
6938
6939 void
6940 remote_target::remote_stop_ns (ptid_t ptid)
6941 {
6942 struct remote_state *rs = get_remote_state ();
6943 char *p = rs->buf.data ();
6944 char *endp = p + get_remote_packet_size ();
6945
6946 /* If any thread that needs to stop was resumed but pending a vCont
6947 resume, generate a phony stop_reply. However, first check
6948 whether the thread wasn't resumed with a signal. Generating a
6949 phony stop in that case would result in losing the signal. */
6950 bool needs_commit = false;
6951 for (thread_info *tp : all_non_exited_threads (this, ptid))
6952 {
6953 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6954
6955 if (remote_thr->get_resume_state ()
6956 == resume_state::RESUMED_PENDING_VCONT)
6957 {
6958 const resumed_pending_vcont_info &info
6959 = remote_thr->resumed_pending_vcont_info ();
6960 if (info.sig != GDB_SIGNAL_0)
6961 {
6962 /* This signal must be forwarded to the inferior. We
6963 could commit-resume just this thread, but its simpler
6964 to just commit-resume everything. */
6965 needs_commit = true;
6966 break;
6967 }
6968 }
6969 }
6970
6971 if (needs_commit)
6972 commit_resumed ();
6973 else
6974 for (thread_info *tp : all_non_exited_threads (this, ptid))
6975 {
6976 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6977
6978 if (remote_thr->get_resume_state ()
6979 == resume_state::RESUMED_PENDING_VCONT)
6980 {
6981 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
6982 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
6983 tp->ptid.lwp (),
6984 pulongest (tp->ptid.tid ()));
6985
6986 /* Check that the thread wasn't resumed with a signal.
6987 Generating a phony stop would result in losing the
6988 signal. */
6989 const resumed_pending_vcont_info &info
6990 = remote_thr->resumed_pending_vcont_info ();
6991 gdb_assert (info.sig == GDB_SIGNAL_0);
6992
6993 stop_reply *sr = new stop_reply ();
6994 sr->ptid = tp->ptid;
6995 sr->rs = rs;
6996 sr->ws.set_stopped (GDB_SIGNAL_0);
6997 sr->arch = tp->inf->gdbarch;
6998 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6999 sr->watch_data_address = 0;
7000 sr->core = 0;
7001 this->push_stop_reply (sr);
7002
7003 /* Pretend that this thread was actually resumed on the
7004 remote target, then stopped. If we leave it in the
7005 RESUMED_PENDING_VCONT state and the commit_resumed
7006 method is called while the stop reply is still in the
7007 queue, we'll end up reporting a stop event to the core
7008 for that thread while it is running on the remote
7009 target... that would be bad. */
7010 remote_thr->set_resumed ();
7011 }
7012 }
7013
7014 /* FIXME: This supports_vCont_probed check is a workaround until
7015 packet_support is per-connection. */
7016 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN
7017 || !rs->supports_vCont_probed)
7018 remote_vcont_probe ();
7019
7020 if (!rs->supports_vCont.t)
7021 error (_("Remote server does not support stopping threads"));
7022
7023 if (ptid == minus_one_ptid
7024 || (!remote_multi_process_p (rs) && ptid.is_pid ()))
7025 p += xsnprintf (p, endp - p, "vCont;t");
7026 else
7027 {
7028 ptid_t nptid;
7029
7030 p += xsnprintf (p, endp - p, "vCont;t:");
7031
7032 if (ptid.is_pid ())
7033 /* All (-1) threads of process. */
7034 nptid = ptid_t (ptid.pid (), -1);
7035 else
7036 {
7037 /* Small optimization: if we already have a stop reply for
7038 this thread, no use in telling the stub we want this
7039 stopped. */
7040 if (peek_stop_reply (ptid))
7041 return;
7042
7043 nptid = ptid;
7044 }
7045
7046 write_ptid (p, endp, nptid);
7047 }
7048
7049 /* In non-stop, we get an immediate OK reply. The stop reply will
7050 come in asynchronously by notification. */
7051 putpkt (rs->buf);
7052 getpkt (&rs->buf, 0);
7053 if (strcmp (rs->buf.data (), "OK") != 0)
7054 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7055 rs->buf.data ());
7056 }
7057
7058 /* All-stop version of target_interrupt. Sends a break or a ^C to
7059 interrupt the remote target. It is undefined which thread of which
7060 process reports the interrupt. */
7061
7062 void
7063 remote_target::remote_interrupt_as ()
7064 {
7065 struct remote_state *rs = get_remote_state ();
7066
7067 rs->ctrlc_pending_p = 1;
7068
7069 /* If the inferior is stopped already, but the core didn't know
7070 about it yet, just ignore the request. The pending stop events
7071 will be collected in remote_wait. */
7072 if (stop_reply_queue_length () > 0)
7073 return;
7074
7075 /* Send interrupt_sequence to remote target. */
7076 send_interrupt_sequence ();
7077 }
7078
7079 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7080 the remote target. It is undefined which thread of which process
7081 reports the interrupt. Throws an error if the packet is not
7082 supported by the server. */
7083
7084 void
7085 remote_target::remote_interrupt_ns ()
7086 {
7087 struct remote_state *rs = get_remote_state ();
7088 char *p = rs->buf.data ();
7089 char *endp = p + get_remote_packet_size ();
7090
7091 xsnprintf (p, endp - p, "vCtrlC");
7092
7093 /* In non-stop, we get an immediate OK reply. The stop reply will
7094 come in asynchronously by notification. */
7095 putpkt (rs->buf);
7096 getpkt (&rs->buf, 0);
7097
7098 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
7099 {
7100 case PACKET_OK:
7101 break;
7102 case PACKET_UNKNOWN:
7103 error (_("No support for interrupting the remote target."));
7104 case PACKET_ERROR:
7105 error (_("Interrupting target failed: %s"), rs->buf.data ());
7106 }
7107 }
7108
7109 /* Implement the to_stop function for the remote targets. */
7110
7111 void
7112 remote_target::stop (ptid_t ptid)
7113 {
7114 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7115
7116 if (target_is_non_stop_p ())
7117 remote_stop_ns (ptid);
7118 else
7119 {
7120 /* We don't currently have a way to transparently pause the
7121 remote target in all-stop mode. Interrupt it instead. */
7122 remote_interrupt_as ();
7123 }
7124 }
7125
7126 /* Implement the to_interrupt function for the remote targets. */
7127
7128 void
7129 remote_target::interrupt ()
7130 {
7131 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7132
7133 if (target_is_non_stop_p ())
7134 remote_interrupt_ns ();
7135 else
7136 remote_interrupt_as ();
7137 }
7138
7139 /* Implement the to_pass_ctrlc function for the remote targets. */
7140
7141 void
7142 remote_target::pass_ctrlc ()
7143 {
7144 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7145
7146 struct remote_state *rs = get_remote_state ();
7147
7148 /* If we're starting up, we're not fully synced yet. Quit
7149 immediately. */
7150 if (rs->starting_up)
7151 quit ();
7152 /* If ^C has already been sent once, offer to disconnect. */
7153 else if (rs->ctrlc_pending_p)
7154 interrupt_query ();
7155 else
7156 target_interrupt ();
7157 }
7158
7159 /* Ask the user what to do when an interrupt is received. */
7160
7161 void
7162 remote_target::interrupt_query ()
7163 {
7164 struct remote_state *rs = get_remote_state ();
7165
7166 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7167 {
7168 if (query (_("The target is not responding to interrupt requests.\n"
7169 "Stop debugging it? ")))
7170 {
7171 remote_unpush_target (this);
7172 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7173 }
7174 }
7175 else
7176 {
7177 if (query (_("Interrupted while waiting for the program.\n"
7178 "Give up waiting? ")))
7179 quit ();
7180 }
7181 }
7182
7183 /* Enable/disable target terminal ownership. Most targets can use
7184 terminal groups to control terminal ownership. Remote targets are
7185 different in that explicit transfer of ownership to/from GDB/target
7186 is required. */
7187
7188 void
7189 remote_target::terminal_inferior ()
7190 {
7191 /* NOTE: At this point we could also register our selves as the
7192 recipient of all input. Any characters typed could then be
7193 passed on down to the target. */
7194 }
7195
7196 void
7197 remote_target::terminal_ours ()
7198 {
7199 }
7200
7201 static void
7202 remote_console_output (const char *msg)
7203 {
7204 const char *p;
7205
7206 for (p = msg; p[0] && p[1]; p += 2)
7207 {
7208 char tb[2];
7209 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7210
7211 tb[0] = c;
7212 tb[1] = 0;
7213 gdb_stdtarg->puts (tb);
7214 }
7215 gdb_stdtarg->flush ();
7216 }
7217
7218 /* Return the length of the stop reply queue. */
7219
7220 int
7221 remote_target::stop_reply_queue_length ()
7222 {
7223 remote_state *rs = get_remote_state ();
7224 return rs->stop_reply_queue.size ();
7225 }
7226
7227 static void
7228 remote_notif_stop_parse (remote_target *remote,
7229 struct notif_client *self, const char *buf,
7230 struct notif_event *event)
7231 {
7232 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7233 }
7234
7235 static void
7236 remote_notif_stop_ack (remote_target *remote,
7237 struct notif_client *self, const char *buf,
7238 struct notif_event *event)
7239 {
7240 struct stop_reply *stop_reply = (struct stop_reply *) event;
7241
7242 /* acknowledge */
7243 putpkt (remote, self->ack_command);
7244
7245 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7246 the notification. It was left in the queue because we need to
7247 acknowledge it and pull the rest of the notifications out. */
7248 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7249 remote->push_stop_reply (stop_reply);
7250 }
7251
7252 static int
7253 remote_notif_stop_can_get_pending_events (remote_target *remote,
7254 struct notif_client *self)
7255 {
7256 /* We can't get pending events in remote_notif_process for
7257 notification stop, and we have to do this in remote_wait_ns
7258 instead. If we fetch all queued events from stub, remote stub
7259 may exit and we have no chance to process them back in
7260 remote_wait_ns. */
7261 remote_state *rs = remote->get_remote_state ();
7262 mark_async_event_handler (rs->remote_async_inferior_event_token);
7263 return 0;
7264 }
7265
7266 stop_reply::~stop_reply ()
7267 {
7268 for (cached_reg_t &reg : regcache)
7269 xfree (reg.data);
7270 }
7271
7272 static notif_event_up
7273 remote_notif_stop_alloc_reply ()
7274 {
7275 return notif_event_up (new struct stop_reply ());
7276 }
7277
7278 /* A client of notification Stop. */
7279
7280 struct notif_client notif_client_stop =
7281 {
7282 "Stop",
7283 "vStopped",
7284 remote_notif_stop_parse,
7285 remote_notif_stop_ack,
7286 remote_notif_stop_can_get_pending_events,
7287 remote_notif_stop_alloc_reply,
7288 REMOTE_NOTIF_STOP,
7289 };
7290
7291 /* If CONTEXT contains any fork child threads that have not been
7292 reported yet, remove them from the CONTEXT list. If such a
7293 thread exists it is because we are stopped at a fork catchpoint
7294 and have not yet called follow_fork, which will set up the
7295 host-side data structures for the new process. */
7296
7297 void
7298 remote_target::remove_new_fork_children (threads_listing_context *context)
7299 {
7300 struct notif_client *notif = &notif_client_stop;
7301
7302 /* For any threads stopped at a fork event, remove the corresponding
7303 fork child threads from the CONTEXT list. */
7304 for (thread_info *thread : all_non_exited_threads (this))
7305 {
7306 const target_waitstatus *ws = thread_pending_fork_status (thread);
7307
7308 if (ws == nullptr)
7309 continue;
7310
7311 context->remove_thread (ws->child_ptid ());
7312 }
7313
7314 /* Check for any pending fork events (not reported or processed yet)
7315 in process PID and remove those fork child threads from the
7316 CONTEXT list as well. */
7317 remote_notif_get_pending_events (notif);
7318 for (auto &event : get_remote_state ()->stop_reply_queue)
7319 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7320 || event->ws.kind () == TARGET_WAITKIND_VFORKED
7321 || event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7322 context->remove_thread (event->ws.child_ptid ());
7323 }
7324
7325 /* Check whether any event pending in the vStopped queue would prevent a
7326 global or process wildcard vCont action. Set *may_global_wildcard to
7327 false if we can't do a global wildcard (vCont;c), and clear the event
7328 inferior's may_wildcard_vcont flag if we can't do a process-wide
7329 wildcard resume (vCont;c:pPID.-1). */
7330
7331 void
7332 remote_target::check_pending_events_prevent_wildcard_vcont
7333 (bool *may_global_wildcard)
7334 {
7335 struct notif_client *notif = &notif_client_stop;
7336
7337 remote_notif_get_pending_events (notif);
7338 for (auto &event : get_remote_state ()->stop_reply_queue)
7339 {
7340 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7341 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7342 continue;
7343
7344 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7345 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7346 *may_global_wildcard = false;
7347
7348 /* This may be the first time we heard about this process.
7349 Regardless, we must not do a global wildcard resume, otherwise
7350 we'd resume this process too. */
7351 *may_global_wildcard = false;
7352 if (event->ptid != null_ptid)
7353 {
7354 inferior *inf = find_inferior_ptid (this, event->ptid);
7355 if (inf != NULL)
7356 get_remote_inferior (inf)->may_wildcard_vcont = false;
7357 }
7358 }
7359 }
7360
7361 /* Discard all pending stop replies of inferior INF. */
7362
7363 void
7364 remote_target::discard_pending_stop_replies (struct inferior *inf)
7365 {
7366 struct stop_reply *reply;
7367 struct remote_state *rs = get_remote_state ();
7368 struct remote_notif_state *rns = rs->notif_state;
7369
7370 /* This function can be notified when an inferior exists. When the
7371 target is not remote, the notification state is NULL. */
7372 if (rs->remote_desc == NULL)
7373 return;
7374
7375 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7376
7377 /* Discard the in-flight notification. */
7378 if (reply != NULL && reply->ptid.pid () == inf->pid)
7379 {
7380 /* Leave the notification pending, since the server expects that
7381 we acknowledge it with vStopped. But clear its contents, so
7382 that later on when we acknowledge it, we also discard it. */
7383 remote_debug_printf
7384 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7385 reply->ptid.to_string().c_str(),
7386 reply->ws.to_string ().c_str ());
7387 reply->ws.set_ignore ();
7388 }
7389
7390 /* Discard the stop replies we have already pulled with
7391 vStopped. */
7392 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7393 rs->stop_reply_queue.end (),
7394 [=] (const stop_reply_up &event)
7395 {
7396 return event->ptid.pid () == inf->pid;
7397 });
7398 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7399 remote_debug_printf
7400 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7401 reply->ptid.to_string().c_str(),
7402 reply->ws.to_string ().c_str ());
7403 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7404 }
7405
7406 /* Discard the stop replies for RS in stop_reply_queue. */
7407
7408 void
7409 remote_target::discard_pending_stop_replies_in_queue ()
7410 {
7411 remote_state *rs = get_remote_state ();
7412
7413 /* Discard the stop replies we have already pulled with
7414 vStopped. */
7415 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7416 rs->stop_reply_queue.end (),
7417 [=] (const stop_reply_up &event)
7418 {
7419 return event->rs == rs;
7420 });
7421 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7422 }
7423
7424 /* Remove the first reply in 'stop_reply_queue' which matches
7425 PTID. */
7426
7427 struct stop_reply *
7428 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7429 {
7430 remote_state *rs = get_remote_state ();
7431
7432 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7433 rs->stop_reply_queue.end (),
7434 [=] (const stop_reply_up &event)
7435 {
7436 return event->ptid.matches (ptid);
7437 });
7438 struct stop_reply *result;
7439 if (iter == rs->stop_reply_queue.end ())
7440 result = nullptr;
7441 else
7442 {
7443 result = iter->release ();
7444 rs->stop_reply_queue.erase (iter);
7445 }
7446
7447 if (notif_debug)
7448 fprintf_unfiltered (gdb_stdlog,
7449 "notif: discard queued event: 'Stop' in %s\n",
7450 target_pid_to_str (ptid).c_str ());
7451
7452 return result;
7453 }
7454
7455 /* Look for a queued stop reply belonging to PTID. If one is found,
7456 remove it from the queue, and return it. Returns NULL if none is
7457 found. If there are still queued events left to process, tell the
7458 event loop to get back to target_wait soon. */
7459
7460 struct stop_reply *
7461 remote_target::queued_stop_reply (ptid_t ptid)
7462 {
7463 remote_state *rs = get_remote_state ();
7464 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7465
7466 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7467 {
7468 /* There's still at least an event left. */
7469 mark_async_event_handler (rs->remote_async_inferior_event_token);
7470 }
7471
7472 return r;
7473 }
7474
7475 /* Push a fully parsed stop reply in the stop reply queue. Since we
7476 know that we now have at least one queued event left to pass to the
7477 core side, tell the event loop to get back to target_wait soon. */
7478
7479 void
7480 remote_target::push_stop_reply (struct stop_reply *new_event)
7481 {
7482 remote_state *rs = get_remote_state ();
7483 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7484
7485 if (notif_debug)
7486 fprintf_unfiltered (gdb_stdlog,
7487 "notif: push 'Stop' %s to queue %d\n",
7488 target_pid_to_str (new_event->ptid).c_str (),
7489 int (rs->stop_reply_queue.size ()));
7490
7491 /* Mark the pending event queue only if async mode is currently enabled.
7492 If async mode is not currently enabled, then, if it later becomes
7493 enabled, and there are events in this queue, we will mark the event
7494 token at that point, see remote_target::async. */
7495 if (target_is_async_p ())
7496 mark_async_event_handler (rs->remote_async_inferior_event_token);
7497 }
7498
7499 /* Returns true if we have a stop reply for PTID. */
7500
7501 int
7502 remote_target::peek_stop_reply (ptid_t ptid)
7503 {
7504 remote_state *rs = get_remote_state ();
7505 for (auto &event : rs->stop_reply_queue)
7506 if (ptid == event->ptid
7507 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7508 return 1;
7509 return 0;
7510 }
7511
7512 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7513 starting with P and ending with PEND matches PREFIX. */
7514
7515 static int
7516 strprefix (const char *p, const char *pend, const char *prefix)
7517 {
7518 for ( ; p < pend; p++, prefix++)
7519 if (*p != *prefix)
7520 return 0;
7521 return *prefix == '\0';
7522 }
7523
7524 /* Parse the stop reply in BUF. Either the function succeeds, and the
7525 result is stored in EVENT, or throws an error. */
7526
7527 void
7528 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7529 {
7530 remote_arch_state *rsa = NULL;
7531 ULONGEST addr;
7532 const char *p;
7533 int skipregs = 0;
7534
7535 event->ptid = null_ptid;
7536 event->rs = get_remote_state ();
7537 event->ws.set_ignore ();
7538 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7539 event->regcache.clear ();
7540 event->core = -1;
7541
7542 switch (buf[0])
7543 {
7544 case 'T': /* Status with PC, SP, FP, ... */
7545 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7546 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7547 ss = signal number
7548 n... = register number
7549 r... = register contents
7550 */
7551
7552 p = &buf[3]; /* after Txx */
7553 while (*p)
7554 {
7555 const char *p1;
7556 int fieldsize;
7557
7558 p1 = strchr (p, ':');
7559 if (p1 == NULL)
7560 error (_("Malformed packet(a) (missing colon): %s\n\
7561 Packet: '%s'\n"),
7562 p, buf);
7563 if (p == p1)
7564 error (_("Malformed packet(a) (missing register number): %s\n\
7565 Packet: '%s'\n"),
7566 p, buf);
7567
7568 /* Some "registers" are actually extended stop information.
7569 Note if you're adding a new entry here: GDB 7.9 and
7570 earlier assume that all register "numbers" that start
7571 with an hex digit are real register numbers. Make sure
7572 the server only sends such a packet if it knows the
7573 client understands it. */
7574
7575 if (strprefix (p, p1, "thread"))
7576 event->ptid = read_ptid (++p1, &p);
7577 else if (strprefix (p, p1, "syscall_entry"))
7578 {
7579 ULONGEST sysno;
7580
7581 p = unpack_varlen_hex (++p1, &sysno);
7582 event->ws.set_syscall_entry ((int) sysno);
7583 }
7584 else if (strprefix (p, p1, "syscall_return"))
7585 {
7586 ULONGEST sysno;
7587
7588 p = unpack_varlen_hex (++p1, &sysno);
7589 event->ws.set_syscall_return ((int) sysno);
7590 }
7591 else if (strprefix (p, p1, "watch")
7592 || strprefix (p, p1, "rwatch")
7593 || strprefix (p, p1, "awatch"))
7594 {
7595 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7596 p = unpack_varlen_hex (++p1, &addr);
7597 event->watch_data_address = (CORE_ADDR) addr;
7598 }
7599 else if (strprefix (p, p1, "swbreak"))
7600 {
7601 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7602
7603 /* Make sure the stub doesn't forget to indicate support
7604 with qSupported. */
7605 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7606 error (_("Unexpected swbreak stop reason"));
7607
7608 /* The value part is documented as "must be empty",
7609 though we ignore it, in case we ever decide to make
7610 use of it in a backward compatible way. */
7611 p = strchrnul (p1 + 1, ';');
7612 }
7613 else if (strprefix (p, p1, "hwbreak"))
7614 {
7615 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7616
7617 /* Make sure the stub doesn't forget to indicate support
7618 with qSupported. */
7619 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7620 error (_("Unexpected hwbreak stop reason"));
7621
7622 /* See above. */
7623 p = strchrnul (p1 + 1, ';');
7624 }
7625 else if (strprefix (p, p1, "library"))
7626 {
7627 event->ws.set_loaded ();
7628 p = strchrnul (p1 + 1, ';');
7629 }
7630 else if (strprefix (p, p1, "replaylog"))
7631 {
7632 event->ws.set_no_history ();
7633 /* p1 will indicate "begin" or "end", but it makes
7634 no difference for now, so ignore it. */
7635 p = strchrnul (p1 + 1, ';');
7636 }
7637 else if (strprefix (p, p1, "core"))
7638 {
7639 ULONGEST c;
7640
7641 p = unpack_varlen_hex (++p1, &c);
7642 event->core = c;
7643 }
7644 else if (strprefix (p, p1, "fork"))
7645 event->ws.set_forked (read_ptid (++p1, &p));
7646 else if (strprefix (p, p1, "vfork"))
7647 event->ws.set_vforked (read_ptid (++p1, &p));
7648 else if (strprefix (p, p1, "vforkdone"))
7649 {
7650 event->ws.set_vfork_done ();
7651 p = strchrnul (p1 + 1, ';');
7652 }
7653 else if (strprefix (p, p1, "exec"))
7654 {
7655 ULONGEST ignored;
7656 int pathlen;
7657
7658 /* Determine the length of the execd pathname. */
7659 p = unpack_varlen_hex (++p1, &ignored);
7660 pathlen = (p - p1) / 2;
7661
7662 /* Save the pathname for event reporting and for
7663 the next run command. */
7664 gdb::unique_xmalloc_ptr<char> pathname
7665 ((char *) xmalloc (pathlen + 1));
7666 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
7667 pathname.get ()[pathlen] = '\0';
7668
7669 /* This is freed during event handling. */
7670 event->ws.set_execd (std::move (pathname));
7671
7672 /* Skip the registers included in this packet, since
7673 they may be for an architecture different from the
7674 one used by the original program. */
7675 skipregs = 1;
7676 }
7677 else if (strprefix (p, p1, "create"))
7678 {
7679 event->ws.set_thread_created ();
7680 p = strchrnul (p1 + 1, ';');
7681 }
7682 else
7683 {
7684 ULONGEST pnum;
7685 const char *p_temp;
7686
7687 if (skipregs)
7688 {
7689 p = strchrnul (p1 + 1, ';');
7690 p++;
7691 continue;
7692 }
7693
7694 /* Maybe a real ``P'' register number. */
7695 p_temp = unpack_varlen_hex (p, &pnum);
7696 /* If the first invalid character is the colon, we got a
7697 register number. Otherwise, it's an unknown stop
7698 reason. */
7699 if (p_temp == p1)
7700 {
7701 /* If we haven't parsed the event's thread yet, find
7702 it now, in order to find the architecture of the
7703 reported expedited registers. */
7704 if (event->ptid == null_ptid)
7705 {
7706 /* If there is no thread-id information then leave
7707 the event->ptid as null_ptid. Later in
7708 process_stop_reply we will pick a suitable
7709 thread. */
7710 const char *thr = strstr (p1 + 1, ";thread:");
7711 if (thr != NULL)
7712 event->ptid = read_ptid (thr + strlen (";thread:"),
7713 NULL);
7714 }
7715
7716 if (rsa == NULL)
7717 {
7718 inferior *inf
7719 = (event->ptid == null_ptid
7720 ? NULL
7721 : find_inferior_ptid (this, event->ptid));
7722 /* If this is the first time we learn anything
7723 about this process, skip the registers
7724 included in this packet, since we don't yet
7725 know which architecture to use to parse them.
7726 We'll determine the architecture later when
7727 we process the stop reply and retrieve the
7728 target description, via
7729 remote_notice_new_inferior ->
7730 post_create_inferior. */
7731 if (inf == NULL)
7732 {
7733 p = strchrnul (p1 + 1, ';');
7734 p++;
7735 continue;
7736 }
7737
7738 event->arch = inf->gdbarch;
7739 rsa = event->rs->get_remote_arch_state (event->arch);
7740 }
7741
7742 packet_reg *reg
7743 = packet_reg_from_pnum (event->arch, rsa, pnum);
7744 cached_reg_t cached_reg;
7745
7746 if (reg == NULL)
7747 error (_("Remote sent bad register number %s: %s\n\
7748 Packet: '%s'\n"),
7749 hex_string (pnum), p, buf);
7750
7751 cached_reg.num = reg->regnum;
7752 cached_reg.data = (gdb_byte *)
7753 xmalloc (register_size (event->arch, reg->regnum));
7754
7755 p = p1 + 1;
7756 fieldsize = hex2bin (p, cached_reg.data,
7757 register_size (event->arch, reg->regnum));
7758 p += 2 * fieldsize;
7759 if (fieldsize < register_size (event->arch, reg->regnum))
7760 warning (_("Remote reply is too short: %s"), buf);
7761
7762 event->regcache.push_back (cached_reg);
7763 }
7764 else
7765 {
7766 /* Not a number. Silently skip unknown optional
7767 info. */
7768 p = strchrnul (p1 + 1, ';');
7769 }
7770 }
7771
7772 if (*p != ';')
7773 error (_("Remote register badly formatted: %s\nhere: %s"),
7774 buf, p);
7775 ++p;
7776 }
7777
7778 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
7779 break;
7780
7781 /* fall through */
7782 case 'S': /* Old style status, just signal only. */
7783 {
7784 int sig;
7785
7786 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7787 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7788 event->ws.set_stopped ((enum gdb_signal) sig);
7789 else
7790 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
7791 }
7792 break;
7793 case 'w': /* Thread exited. */
7794 {
7795 ULONGEST value;
7796
7797 p = unpack_varlen_hex (&buf[1], &value);
7798 event->ws.set_thread_exited (value);
7799 if (*p != ';')
7800 error (_("stop reply packet badly formatted: %s"), buf);
7801 event->ptid = read_ptid (++p, NULL);
7802 break;
7803 }
7804 case 'W': /* Target exited. */
7805 case 'X':
7806 {
7807 ULONGEST value;
7808
7809 /* GDB used to accept only 2 hex chars here. Stubs should
7810 only send more if they detect GDB supports multi-process
7811 support. */
7812 p = unpack_varlen_hex (&buf[1], &value);
7813
7814 if (buf[0] == 'W')
7815 {
7816 /* The remote process exited. */
7817 event->ws.set_exited (value);
7818 }
7819 else
7820 {
7821 /* The remote process exited with a signal. */
7822 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7823 event->ws.set_signalled ((enum gdb_signal) value);
7824 else
7825 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
7826 }
7827
7828 /* If no process is specified, return null_ptid, and let the
7829 caller figure out the right process to use. */
7830 int pid = 0;
7831 if (*p == '\0')
7832 ;
7833 else if (*p == ';')
7834 {
7835 p++;
7836
7837 if (*p == '\0')
7838 ;
7839 else if (startswith (p, "process:"))
7840 {
7841 ULONGEST upid;
7842
7843 p += sizeof ("process:") - 1;
7844 unpack_varlen_hex (p, &upid);
7845 pid = upid;
7846 }
7847 else
7848 error (_("unknown stop reply packet: %s"), buf);
7849 }
7850 else
7851 error (_("unknown stop reply packet: %s"), buf);
7852 event->ptid = ptid_t (pid);
7853 }
7854 break;
7855 case 'N':
7856 event->ws.set_no_resumed ();
7857 event->ptid = minus_one_ptid;
7858 break;
7859 }
7860 }
7861
7862 /* When the stub wants to tell GDB about a new notification reply, it
7863 sends a notification (%Stop, for example). Those can come it at
7864 any time, hence, we have to make sure that any pending
7865 putpkt/getpkt sequence we're making is finished, before querying
7866 the stub for more events with the corresponding ack command
7867 (vStopped, for example). E.g., if we started a vStopped sequence
7868 immediately upon receiving the notification, something like this
7869 could happen:
7870
7871 1.1) --> Hg 1
7872 1.2) <-- OK
7873 1.3) --> g
7874 1.4) <-- %Stop
7875 1.5) --> vStopped
7876 1.6) <-- (registers reply to step #1.3)
7877
7878 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7879 query.
7880
7881 To solve this, whenever we parse a %Stop notification successfully,
7882 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7883 doing whatever we were doing:
7884
7885 2.1) --> Hg 1
7886 2.2) <-- OK
7887 2.3) --> g
7888 2.4) <-- %Stop
7889 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7890 2.5) <-- (registers reply to step #2.3)
7891
7892 Eventually after step #2.5, we return to the event loop, which
7893 notices there's an event on the
7894 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7895 associated callback --- the function below. At this point, we're
7896 always safe to start a vStopped sequence. :
7897
7898 2.6) --> vStopped
7899 2.7) <-- T05 thread:2
7900 2.8) --> vStopped
7901 2.9) --> OK
7902 */
7903
7904 void
7905 remote_target::remote_notif_get_pending_events (notif_client *nc)
7906 {
7907 struct remote_state *rs = get_remote_state ();
7908
7909 if (rs->notif_state->pending_event[nc->id] != NULL)
7910 {
7911 if (notif_debug)
7912 fprintf_unfiltered (gdb_stdlog,
7913 "notif: process: '%s' ack pending event\n",
7914 nc->name);
7915
7916 /* acknowledge */
7917 nc->ack (this, nc, rs->buf.data (),
7918 rs->notif_state->pending_event[nc->id]);
7919 rs->notif_state->pending_event[nc->id] = NULL;
7920
7921 while (1)
7922 {
7923 getpkt (&rs->buf, 0);
7924 if (strcmp (rs->buf.data (), "OK") == 0)
7925 break;
7926 else
7927 remote_notif_ack (this, nc, rs->buf.data ());
7928 }
7929 }
7930 else
7931 {
7932 if (notif_debug)
7933 fprintf_unfiltered (gdb_stdlog,
7934 "notif: process: '%s' no pending reply\n",
7935 nc->name);
7936 }
7937 }
7938
7939 /* Wrapper around remote_target::remote_notif_get_pending_events to
7940 avoid having to export the whole remote_target class. */
7941
7942 void
7943 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7944 {
7945 remote->remote_notif_get_pending_events (nc);
7946 }
7947
7948 /* Called from process_stop_reply when the stop packet we are responding
7949 to didn't include a process-id or thread-id. STATUS is the stop event
7950 we are responding to.
7951
7952 It is the task of this function to select a suitable thread (or process)
7953 and return its ptid, this is the thread (or process) we will assume the
7954 stop event came from.
7955
7956 In some cases there isn't really any choice about which thread (or
7957 process) is selected, a basic remote with a single process containing a
7958 single thread might choose not to send any process-id or thread-id in
7959 its stop packets, this function will select and return the one and only
7960 thread.
7961
7962 However, if a target supports multiple threads (or processes) and still
7963 doesn't include a thread-id (or process-id) in its stop packet then
7964 first, this is a badly behaving target, and second, we're going to have
7965 to select a thread (or process) at random and use that. This function
7966 will print a warning to the user if it detects that there is the
7967 possibility that GDB is guessing which thread (or process) to
7968 report.
7969
7970 Note that this is called before GDB fetches the updated thread list from the
7971 target. So it's possible for the stop reply to be ambiguous and for GDB to
7972 not realize it. For example, if there's initially one thread, the target
7973 spawns a second thread, and then sends a stop reply without an id that
7974 concerns the first thread. GDB will assume the stop reply is about the
7975 first thread - the only thread it knows about - without printing a warning.
7976 Anyway, if the remote meant for the stop reply to be about the second thread,
7977 then it would be really broken, because GDB doesn't know about that thread
7978 yet. */
7979
7980 ptid_t
7981 remote_target::select_thread_for_ambiguous_stop_reply
7982 (const target_waitstatus &status)
7983 {
7984 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7985
7986 /* Some stop events apply to all threads in an inferior, while others
7987 only apply to a single thread. */
7988 bool process_wide_stop
7989 = (status.kind () == TARGET_WAITKIND_EXITED
7990 || status.kind () == TARGET_WAITKIND_SIGNALLED);
7991
7992 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
7993
7994 thread_info *first_resumed_thread = nullptr;
7995 bool ambiguous = false;
7996
7997 /* Consider all non-exited threads of the target, find the first resumed
7998 one. */
7999 for (thread_info *thr : all_non_exited_threads (this))
8000 {
8001 remote_thread_info *remote_thr = get_remote_thread_info (thr);
8002
8003 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8004 continue;
8005
8006 if (first_resumed_thread == nullptr)
8007 first_resumed_thread = thr;
8008 else if (!process_wide_stop
8009 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8010 ambiguous = true;
8011 }
8012
8013 remote_debug_printf ("first resumed thread is %s",
8014 pid_to_str (first_resumed_thread->ptid).c_str ());
8015 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8016
8017 gdb_assert (first_resumed_thread != nullptr);
8018
8019 /* Warn if the remote target is sending ambiguous stop replies. */
8020 if (ambiguous)
8021 {
8022 static bool warned = false;
8023
8024 if (!warned)
8025 {
8026 /* If you are seeing this warning then the remote target has
8027 stopped without specifying a thread-id, but the target
8028 does have multiple threads (or inferiors), and so GDB is
8029 having to guess which thread stopped.
8030
8031 Examples of what might cause this are the target sending
8032 and 'S' stop packet, or a 'T' stop packet and not
8033 including a thread-id.
8034
8035 Additionally, the target might send a 'W' or 'X packet
8036 without including a process-id, when the target has
8037 multiple running inferiors. */
8038 if (process_wide_stop)
8039 warning (_("multi-inferior target stopped without "
8040 "sending a process-id, using first "
8041 "non-exited inferior"));
8042 else
8043 warning (_("multi-threaded target stopped without "
8044 "sending a thread-id, using first "
8045 "non-exited thread"));
8046 warned = true;
8047 }
8048 }
8049
8050 /* If this is a stop for all threads then don't use a particular threads
8051 ptid, instead create a new ptid where only the pid field is set. */
8052 if (process_wide_stop)
8053 return ptid_t (first_resumed_thread->ptid.pid ());
8054 else
8055 return first_resumed_thread->ptid;
8056 }
8057
8058 /* Called when it is decided that STOP_REPLY holds the info of the
8059 event that is to be returned to the core. This function always
8060 destroys STOP_REPLY. */
8061
8062 ptid_t
8063 remote_target::process_stop_reply (struct stop_reply *stop_reply,
8064 struct target_waitstatus *status)
8065 {
8066 *status = stop_reply->ws;
8067 ptid_t ptid = stop_reply->ptid;
8068
8069 /* If no thread/process was reported by the stub then select a suitable
8070 thread/process. */
8071 if (ptid == null_ptid)
8072 ptid = select_thread_for_ambiguous_stop_reply (*status);
8073 gdb_assert (ptid != null_ptid);
8074
8075 if (status->kind () != TARGET_WAITKIND_EXITED
8076 && status->kind () != TARGET_WAITKIND_SIGNALLED
8077 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8078 {
8079 /* Expedited registers. */
8080 if (!stop_reply->regcache.empty ())
8081 {
8082 struct regcache *regcache
8083 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
8084
8085 for (cached_reg_t &reg : stop_reply->regcache)
8086 {
8087 regcache->raw_supply (reg.num, reg.data);
8088 xfree (reg.data);
8089 }
8090
8091 stop_reply->regcache.clear ();
8092 }
8093
8094 remote_notice_new_inferior (ptid, false);
8095 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8096 remote_thr->core = stop_reply->core;
8097 remote_thr->stop_reason = stop_reply->stop_reason;
8098 remote_thr->watch_data_address = stop_reply->watch_data_address;
8099
8100 if (target_is_non_stop_p ())
8101 {
8102 /* If the target works in non-stop mode, a stop-reply indicates that
8103 only this thread stopped. */
8104 remote_thr->set_not_resumed ();
8105 }
8106 else
8107 {
8108 /* If the target works in all-stop mode, a stop-reply indicates that
8109 all the target's threads stopped. */
8110 for (thread_info *tp : all_non_exited_threads (this))
8111 get_remote_thread_info (tp)->set_not_resumed ();
8112 }
8113 }
8114
8115 delete stop_reply;
8116 return ptid;
8117 }
8118
8119 /* The non-stop mode version of target_wait. */
8120
8121 ptid_t
8122 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8123 target_wait_flags options)
8124 {
8125 struct remote_state *rs = get_remote_state ();
8126 struct stop_reply *stop_reply;
8127 int ret;
8128 int is_notif = 0;
8129
8130 /* If in non-stop mode, get out of getpkt even if a
8131 notification is received. */
8132
8133 ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
8134 while (1)
8135 {
8136 if (ret != -1 && !is_notif)
8137 switch (rs->buf[0])
8138 {
8139 case 'E': /* Error of some sort. */
8140 /* We're out of sync with the target now. Did it continue
8141 or not? We can't tell which thread it was in non-stop,
8142 so just ignore this. */
8143 warning (_("Remote failure reply: %s"), rs->buf.data ());
8144 break;
8145 case 'O': /* Console output. */
8146 remote_console_output (&rs->buf[1]);
8147 break;
8148 default:
8149 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8150 break;
8151 }
8152
8153 /* Acknowledge a pending stop reply that may have arrived in the
8154 mean time. */
8155 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8156 remote_notif_get_pending_events (&notif_client_stop);
8157
8158 /* If indeed we noticed a stop reply, we're done. */
8159 stop_reply = queued_stop_reply (ptid);
8160 if (stop_reply != NULL)
8161 return process_stop_reply (stop_reply, status);
8162
8163 /* Still no event. If we're just polling for an event, then
8164 return to the event loop. */
8165 if (options & TARGET_WNOHANG)
8166 {
8167 status->set_ignore ();
8168 return minus_one_ptid;
8169 }
8170
8171 /* Otherwise do a blocking wait. */
8172 ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
8173 }
8174 }
8175
8176 /* Return the first resumed thread. */
8177
8178 static ptid_t
8179 first_remote_resumed_thread (remote_target *target)
8180 {
8181 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8182 if (tp->resumed ())
8183 return tp->ptid;
8184 return null_ptid;
8185 }
8186
8187 /* Wait until the remote machine stops, then return, storing status in
8188 STATUS just as `wait' would. */
8189
8190 ptid_t
8191 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8192 target_wait_flags options)
8193 {
8194 struct remote_state *rs = get_remote_state ();
8195 ptid_t event_ptid = null_ptid;
8196 char *buf;
8197 struct stop_reply *stop_reply;
8198
8199 again:
8200
8201 status->set_ignore ();
8202
8203 stop_reply = queued_stop_reply (ptid);
8204 if (stop_reply != NULL)
8205 {
8206 /* None of the paths that push a stop reply onto the queue should
8207 have set the waiting_for_stop_reply flag. */
8208 gdb_assert (!rs->waiting_for_stop_reply);
8209 event_ptid = process_stop_reply (stop_reply, status);
8210 }
8211 else
8212 {
8213 int forever = ((options & TARGET_WNOHANG) == 0
8214 && rs->wait_forever_enabled_p);
8215
8216 if (!rs->waiting_for_stop_reply)
8217 {
8218 status->set_no_resumed ();
8219 return minus_one_ptid;
8220 }
8221
8222 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8223 _never_ wait for ever -> test on target_is_async_p().
8224 However, before we do that we need to ensure that the caller
8225 knows how to take the target into/out of async mode. */
8226 int is_notif;
8227 int ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
8228
8229 /* GDB gets a notification. Return to core as this event is
8230 not interesting. */
8231 if (ret != -1 && is_notif)
8232 return minus_one_ptid;
8233
8234 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8235 return minus_one_ptid;
8236
8237 buf = rs->buf.data ();
8238
8239 /* Assume that the target has acknowledged Ctrl-C unless we receive
8240 an 'F' or 'O' packet. */
8241 if (buf[0] != 'F' && buf[0] != 'O')
8242 rs->ctrlc_pending_p = 0;
8243
8244 switch (buf[0])
8245 {
8246 case 'E': /* Error of some sort. */
8247 /* We're out of sync with the target now. Did it continue or
8248 not? Not is more likely, so report a stop. */
8249 rs->waiting_for_stop_reply = 0;
8250
8251 warning (_("Remote failure reply: %s"), buf);
8252 status->set_stopped (GDB_SIGNAL_0);
8253 break;
8254 case 'F': /* File-I/O request. */
8255 /* GDB may access the inferior memory while handling the File-I/O
8256 request, but we don't want GDB accessing memory while waiting
8257 for a stop reply. See the comments in putpkt_binary. Set
8258 waiting_for_stop_reply to 0 temporarily. */
8259 rs->waiting_for_stop_reply = 0;
8260 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8261 rs->ctrlc_pending_p = 0;
8262 /* GDB handled the File-I/O request, and the target is running
8263 again. Keep waiting for events. */
8264 rs->waiting_for_stop_reply = 1;
8265 break;
8266 case 'N': case 'T': case 'S': case 'X': case 'W':
8267 {
8268 /* There is a stop reply to handle. */
8269 rs->waiting_for_stop_reply = 0;
8270
8271 stop_reply
8272 = (struct stop_reply *) remote_notif_parse (this,
8273 &notif_client_stop,
8274 rs->buf.data ());
8275
8276 event_ptid = process_stop_reply (stop_reply, status);
8277 break;
8278 }
8279 case 'O': /* Console output. */
8280 remote_console_output (buf + 1);
8281 break;
8282 case '\0':
8283 if (rs->last_sent_signal != GDB_SIGNAL_0)
8284 {
8285 /* Zero length reply means that we tried 'S' or 'C' and the
8286 remote system doesn't support it. */
8287 target_terminal::ours_for_output ();
8288 printf_filtered
8289 ("Can't send signals to this remote system. %s not sent.\n",
8290 gdb_signal_to_name (rs->last_sent_signal));
8291 rs->last_sent_signal = GDB_SIGNAL_0;
8292 target_terminal::inferior ();
8293
8294 strcpy (buf, rs->last_sent_step ? "s" : "c");
8295 putpkt (buf);
8296 break;
8297 }
8298 /* fallthrough */
8299 default:
8300 warning (_("Invalid remote reply: %s"), buf);
8301 break;
8302 }
8303 }
8304
8305 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8306 return minus_one_ptid;
8307 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8308 {
8309 /* Nothing interesting happened. If we're doing a non-blocking
8310 poll, we're done. Otherwise, go back to waiting. */
8311 if (options & TARGET_WNOHANG)
8312 return minus_one_ptid;
8313 else
8314 goto again;
8315 }
8316 else if (status->kind () != TARGET_WAITKIND_EXITED
8317 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8318 {
8319 if (event_ptid != null_ptid)
8320 record_currthread (rs, event_ptid);
8321 else
8322 event_ptid = first_remote_resumed_thread (this);
8323 }
8324 else
8325 {
8326 /* A process exit. Invalidate our notion of current thread. */
8327 record_currthread (rs, minus_one_ptid);
8328 /* It's possible that the packet did not include a pid. */
8329 if (event_ptid == null_ptid)
8330 event_ptid = first_remote_resumed_thread (this);
8331 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8332 if (event_ptid == null_ptid)
8333 event_ptid = magic_null_ptid;
8334 }
8335
8336 return event_ptid;
8337 }
8338
8339 /* Wait until the remote machine stops, then return, storing status in
8340 STATUS just as `wait' would. */
8341
8342 ptid_t
8343 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8344 target_wait_flags options)
8345 {
8346 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8347
8348 remote_state *rs = get_remote_state ();
8349
8350 /* Start by clearing the flag that asks for our wait method to be called,
8351 we'll mark it again at the end if needed. */
8352 if (target_is_async_p ())
8353 clear_async_event_handler (rs->remote_async_inferior_event_token);
8354
8355 ptid_t event_ptid;
8356
8357 if (target_is_non_stop_p ())
8358 event_ptid = wait_ns (ptid, status, options);
8359 else
8360 event_ptid = wait_as (ptid, status, options);
8361
8362 if (target_is_async_p ())
8363 {
8364 /* If there are events left in the queue, or unacknowledged
8365 notifications, then tell the event loop to call us again. */
8366 if (!rs->stop_reply_queue.empty ()
8367 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8368 mark_async_event_handler (rs->remote_async_inferior_event_token);
8369 }
8370
8371 return event_ptid;
8372 }
8373
8374 /* Fetch a single register using a 'p' packet. */
8375
8376 int
8377 remote_target::fetch_register_using_p (struct regcache *regcache,
8378 packet_reg *reg)
8379 {
8380 struct gdbarch *gdbarch = regcache->arch ();
8381 struct remote_state *rs = get_remote_state ();
8382 char *buf, *p;
8383 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8384 int i;
8385
8386 if (packet_support (PACKET_p) == PACKET_DISABLE)
8387 return 0;
8388
8389 if (reg->pnum == -1)
8390 return 0;
8391
8392 p = rs->buf.data ();
8393 *p++ = 'p';
8394 p += hexnumstr (p, reg->pnum);
8395 *p++ = '\0';
8396 putpkt (rs->buf);
8397 getpkt (&rs->buf, 0);
8398
8399 buf = rs->buf.data ();
8400
8401 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_p]))
8402 {
8403 case PACKET_OK:
8404 break;
8405 case PACKET_UNKNOWN:
8406 return 0;
8407 case PACKET_ERROR:
8408 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8409 gdbarch_register_name (regcache->arch (),
8410 reg->regnum),
8411 buf);
8412 }
8413
8414 /* If this register is unfetchable, tell the regcache. */
8415 if (buf[0] == 'x')
8416 {
8417 regcache->raw_supply (reg->regnum, NULL);
8418 return 1;
8419 }
8420
8421 /* Otherwise, parse and supply the value. */
8422 p = buf;
8423 i = 0;
8424 while (p[0] != 0)
8425 {
8426 if (p[1] == 0)
8427 error (_("fetch_register_using_p: early buf termination"));
8428
8429 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8430 p += 2;
8431 }
8432 regcache->raw_supply (reg->regnum, regp);
8433 return 1;
8434 }
8435
8436 /* Fetch the registers included in the target's 'g' packet. */
8437
8438 int
8439 remote_target::send_g_packet ()
8440 {
8441 struct remote_state *rs = get_remote_state ();
8442 int buf_len;
8443
8444 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8445 putpkt (rs->buf);
8446 getpkt (&rs->buf, 0);
8447 if (packet_check_result (rs->buf) == PACKET_ERROR)
8448 error (_("Could not read registers; remote failure reply '%s'"),
8449 rs->buf.data ());
8450
8451 /* We can get out of synch in various cases. If the first character
8452 in the buffer is not a hex character, assume that has happened
8453 and try to fetch another packet to read. */
8454 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8455 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8456 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8457 && rs->buf[0] != 'x') /* New: unavailable register value. */
8458 {
8459 remote_debug_printf ("Bad register packet; fetching a new packet");
8460 getpkt (&rs->buf, 0);
8461 }
8462
8463 buf_len = strlen (rs->buf.data ());
8464
8465 /* Sanity check the received packet. */
8466 if (buf_len % 2 != 0)
8467 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8468
8469 return buf_len / 2;
8470 }
8471
8472 void
8473 remote_target::process_g_packet (struct regcache *regcache)
8474 {
8475 struct gdbarch *gdbarch = regcache->arch ();
8476 struct remote_state *rs = get_remote_state ();
8477 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8478 int i, buf_len;
8479 char *p;
8480 char *regs;
8481
8482 buf_len = strlen (rs->buf.data ());
8483
8484 /* Further sanity checks, with knowledge of the architecture. */
8485 if (buf_len > 2 * rsa->sizeof_g_packet)
8486 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8487 "bytes): %s"),
8488 rsa->sizeof_g_packet, buf_len / 2,
8489 rs->buf.data ());
8490
8491 /* Save the size of the packet sent to us by the target. It is used
8492 as a heuristic when determining the max size of packets that the
8493 target can safely receive. */
8494 if (rsa->actual_register_packet_size == 0)
8495 rsa->actual_register_packet_size = buf_len;
8496
8497 /* If this is smaller than we guessed the 'g' packet would be,
8498 update our records. A 'g' reply that doesn't include a register's
8499 value implies either that the register is not available, or that
8500 the 'p' packet must be used. */
8501 if (buf_len < 2 * rsa->sizeof_g_packet)
8502 {
8503 long sizeof_g_packet = buf_len / 2;
8504
8505 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8506 {
8507 long offset = rsa->regs[i].offset;
8508 long reg_size = register_size (gdbarch, i);
8509
8510 if (rsa->regs[i].pnum == -1)
8511 continue;
8512
8513 if (offset >= sizeof_g_packet)
8514 rsa->regs[i].in_g_packet = 0;
8515 else if (offset + reg_size > sizeof_g_packet)
8516 error (_("Truncated register %d in remote 'g' packet"), i);
8517 else
8518 rsa->regs[i].in_g_packet = 1;
8519 }
8520
8521 /* Looks valid enough, we can assume this is the correct length
8522 for a 'g' packet. It's important not to adjust
8523 rsa->sizeof_g_packet if we have truncated registers otherwise
8524 this "if" won't be run the next time the method is called
8525 with a packet of the same size and one of the internal errors
8526 below will trigger instead. */
8527 rsa->sizeof_g_packet = sizeof_g_packet;
8528 }
8529
8530 regs = (char *) alloca (rsa->sizeof_g_packet);
8531
8532 /* Unimplemented registers read as all bits zero. */
8533 memset (regs, 0, rsa->sizeof_g_packet);
8534
8535 /* Reply describes registers byte by byte, each byte encoded as two
8536 hex characters. Suck them all up, then supply them to the
8537 register cacheing/storage mechanism. */
8538
8539 p = rs->buf.data ();
8540 for (i = 0; i < rsa->sizeof_g_packet; i++)
8541 {
8542 if (p[0] == 0 || p[1] == 0)
8543 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8544 internal_error (__FILE__, __LINE__,
8545 _("unexpected end of 'g' packet reply"));
8546
8547 if (p[0] == 'x' && p[1] == 'x')
8548 regs[i] = 0; /* 'x' */
8549 else
8550 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8551 p += 2;
8552 }
8553
8554 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8555 {
8556 struct packet_reg *r = &rsa->regs[i];
8557 long reg_size = register_size (gdbarch, i);
8558
8559 if (r->in_g_packet)
8560 {
8561 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8562 /* This shouldn't happen - we adjusted in_g_packet above. */
8563 internal_error (__FILE__, __LINE__,
8564 _("unexpected end of 'g' packet reply"));
8565 else if (rs->buf[r->offset * 2] == 'x')
8566 {
8567 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8568 /* The register isn't available, mark it as such (at
8569 the same time setting the value to zero). */
8570 regcache->raw_supply (r->regnum, NULL);
8571 }
8572 else
8573 regcache->raw_supply (r->regnum, regs + r->offset);
8574 }
8575 }
8576 }
8577
8578 void
8579 remote_target::fetch_registers_using_g (struct regcache *regcache)
8580 {
8581 send_g_packet ();
8582 process_g_packet (regcache);
8583 }
8584
8585 /* Make the remote selected traceframe match GDB's selected
8586 traceframe. */
8587
8588 void
8589 remote_target::set_remote_traceframe ()
8590 {
8591 int newnum;
8592 struct remote_state *rs = get_remote_state ();
8593
8594 if (rs->remote_traceframe_number == get_traceframe_number ())
8595 return;
8596
8597 /* Avoid recursion, remote_trace_find calls us again. */
8598 rs->remote_traceframe_number = get_traceframe_number ();
8599
8600 newnum = target_trace_find (tfind_number,
8601 get_traceframe_number (), 0, 0, NULL);
8602
8603 /* Should not happen. If it does, all bets are off. */
8604 if (newnum != get_traceframe_number ())
8605 warning (_("could not set remote traceframe"));
8606 }
8607
8608 void
8609 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8610 {
8611 struct gdbarch *gdbarch = regcache->arch ();
8612 struct remote_state *rs = get_remote_state ();
8613 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8614 int i;
8615
8616 set_remote_traceframe ();
8617 set_general_thread (regcache->ptid ());
8618
8619 if (regnum >= 0)
8620 {
8621 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8622
8623 gdb_assert (reg != NULL);
8624
8625 /* If this register might be in the 'g' packet, try that first -
8626 we are likely to read more than one register. If this is the
8627 first 'g' packet, we might be overly optimistic about its
8628 contents, so fall back to 'p'. */
8629 if (reg->in_g_packet)
8630 {
8631 fetch_registers_using_g (regcache);
8632 if (reg->in_g_packet)
8633 return;
8634 }
8635
8636 if (fetch_register_using_p (regcache, reg))
8637 return;
8638
8639 /* This register is not available. */
8640 regcache->raw_supply (reg->regnum, NULL);
8641
8642 return;
8643 }
8644
8645 fetch_registers_using_g (regcache);
8646
8647 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8648 if (!rsa->regs[i].in_g_packet)
8649 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8650 {
8651 /* This register is not available. */
8652 regcache->raw_supply (i, NULL);
8653 }
8654 }
8655
8656 /* Prepare to store registers. Since we may send them all (using a
8657 'G' request), we have to read out the ones we don't want to change
8658 first. */
8659
8660 void
8661 remote_target::prepare_to_store (struct regcache *regcache)
8662 {
8663 struct remote_state *rs = get_remote_state ();
8664 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8665 int i;
8666
8667 /* Make sure the entire registers array is valid. */
8668 switch (packet_support (PACKET_P))
8669 {
8670 case PACKET_DISABLE:
8671 case PACKET_SUPPORT_UNKNOWN:
8672 /* Make sure all the necessary registers are cached. */
8673 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8674 if (rsa->regs[i].in_g_packet)
8675 regcache->raw_update (rsa->regs[i].regnum);
8676 break;
8677 case PACKET_ENABLE:
8678 break;
8679 }
8680 }
8681
8682 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8683 packet was not recognized. */
8684
8685 int
8686 remote_target::store_register_using_P (const struct regcache *regcache,
8687 packet_reg *reg)
8688 {
8689 struct gdbarch *gdbarch = regcache->arch ();
8690 struct remote_state *rs = get_remote_state ();
8691 /* Try storing a single register. */
8692 char *buf = rs->buf.data ();
8693 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8694 char *p;
8695
8696 if (packet_support (PACKET_P) == PACKET_DISABLE)
8697 return 0;
8698
8699 if (reg->pnum == -1)
8700 return 0;
8701
8702 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8703 p = buf + strlen (buf);
8704 regcache->raw_collect (reg->regnum, regp);
8705 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8706 putpkt (rs->buf);
8707 getpkt (&rs->buf, 0);
8708
8709 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8710 {
8711 case PACKET_OK:
8712 return 1;
8713 case PACKET_ERROR:
8714 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8715 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
8716 case PACKET_UNKNOWN:
8717 return 0;
8718 default:
8719 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8720 }
8721 }
8722
8723 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8724 contents of the register cache buffer. FIXME: ignores errors. */
8725
8726 void
8727 remote_target::store_registers_using_G (const struct regcache *regcache)
8728 {
8729 struct remote_state *rs = get_remote_state ();
8730 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8731 gdb_byte *regs;
8732 char *p;
8733
8734 /* Extract all the registers in the regcache copying them into a
8735 local buffer. */
8736 {
8737 int i;
8738
8739 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8740 memset (regs, 0, rsa->sizeof_g_packet);
8741 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8742 {
8743 struct packet_reg *r = &rsa->regs[i];
8744
8745 if (r->in_g_packet)
8746 regcache->raw_collect (r->regnum, regs + r->offset);
8747 }
8748 }
8749
8750 /* Command describes registers byte by byte,
8751 each byte encoded as two hex characters. */
8752 p = rs->buf.data ();
8753 *p++ = 'G';
8754 bin2hex (regs, p, rsa->sizeof_g_packet);
8755 putpkt (rs->buf);
8756 getpkt (&rs->buf, 0);
8757 if (packet_check_result (rs->buf) == PACKET_ERROR)
8758 error (_("Could not write registers; remote failure reply '%s'"),
8759 rs->buf.data ());
8760 }
8761
8762 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8763 of the register cache buffer. FIXME: ignores errors. */
8764
8765 void
8766 remote_target::store_registers (struct regcache *regcache, int regnum)
8767 {
8768 struct gdbarch *gdbarch = regcache->arch ();
8769 struct remote_state *rs = get_remote_state ();
8770 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8771 int i;
8772
8773 set_remote_traceframe ();
8774 set_general_thread (regcache->ptid ());
8775
8776 if (regnum >= 0)
8777 {
8778 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8779
8780 gdb_assert (reg != NULL);
8781
8782 /* Always prefer to store registers using the 'P' packet if
8783 possible; we often change only a small number of registers.
8784 Sometimes we change a larger number; we'd need help from a
8785 higher layer to know to use 'G'. */
8786 if (store_register_using_P (regcache, reg))
8787 return;
8788
8789 /* For now, don't complain if we have no way to write the
8790 register. GDB loses track of unavailable registers too
8791 easily. Some day, this may be an error. We don't have
8792 any way to read the register, either... */
8793 if (!reg->in_g_packet)
8794 return;
8795
8796 store_registers_using_G (regcache);
8797 return;
8798 }
8799
8800 store_registers_using_G (regcache);
8801
8802 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8803 if (!rsa->regs[i].in_g_packet)
8804 if (!store_register_using_P (regcache, &rsa->regs[i]))
8805 /* See above for why we do not issue an error here. */
8806 continue;
8807 }
8808 \f
8809
8810 /* Return the number of hex digits in num. */
8811
8812 static int
8813 hexnumlen (ULONGEST num)
8814 {
8815 int i;
8816
8817 for (i = 0; num != 0; i++)
8818 num >>= 4;
8819
8820 return std::max (i, 1);
8821 }
8822
8823 /* Set BUF to the minimum number of hex digits representing NUM. */
8824
8825 static int
8826 hexnumstr (char *buf, ULONGEST num)
8827 {
8828 int len = hexnumlen (num);
8829
8830 return hexnumnstr (buf, num, len);
8831 }
8832
8833
8834 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
8835
8836 static int
8837 hexnumnstr (char *buf, ULONGEST num, int width)
8838 {
8839 int i;
8840
8841 buf[width] = '\0';
8842
8843 for (i = width - 1; i >= 0; i--)
8844 {
8845 buf[i] = "0123456789abcdef"[(num & 0xf)];
8846 num >>= 4;
8847 }
8848
8849 return width;
8850 }
8851
8852 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8853
8854 static CORE_ADDR
8855 remote_address_masked (CORE_ADDR addr)
8856 {
8857 unsigned int address_size = remote_address_size;
8858
8859 /* If "remoteaddresssize" was not set, default to target address size. */
8860 if (!address_size)
8861 address_size = gdbarch_addr_bit (target_gdbarch ());
8862
8863 if (address_size > 0
8864 && address_size < (sizeof (ULONGEST) * 8))
8865 {
8866 /* Only create a mask when that mask can safely be constructed
8867 in a ULONGEST variable. */
8868 ULONGEST mask = 1;
8869
8870 mask = (mask << address_size) - 1;
8871 addr &= mask;
8872 }
8873 return addr;
8874 }
8875
8876 /* Determine whether the remote target supports binary downloading.
8877 This is accomplished by sending a no-op memory write of zero length
8878 to the target at the specified address. It does not suffice to send
8879 the whole packet, since many stubs strip the eighth bit and
8880 subsequently compute a wrong checksum, which causes real havoc with
8881 remote_write_bytes.
8882
8883 NOTE: This can still lose if the serial line is not eight-bit
8884 clean. In cases like this, the user should clear "remote
8885 X-packet". */
8886
8887 void
8888 remote_target::check_binary_download (CORE_ADDR addr)
8889 {
8890 struct remote_state *rs = get_remote_state ();
8891
8892 switch (packet_support (PACKET_X))
8893 {
8894 case PACKET_DISABLE:
8895 break;
8896 case PACKET_ENABLE:
8897 break;
8898 case PACKET_SUPPORT_UNKNOWN:
8899 {
8900 char *p;
8901
8902 p = rs->buf.data ();
8903 *p++ = 'X';
8904 p += hexnumstr (p, (ULONGEST) addr);
8905 *p++ = ',';
8906 p += hexnumstr (p, (ULONGEST) 0);
8907 *p++ = ':';
8908 *p = '\0';
8909
8910 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
8911 getpkt (&rs->buf, 0);
8912
8913 if (rs->buf[0] == '\0')
8914 {
8915 remote_debug_printf ("binary downloading NOT supported by target");
8916 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8917 }
8918 else
8919 {
8920 remote_debug_printf ("binary downloading supported by target");
8921 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8922 }
8923 break;
8924 }
8925 }
8926 }
8927
8928 /* Helper function to resize the payload in order to try to get a good
8929 alignment. We try to write an amount of data such that the next write will
8930 start on an address aligned on REMOTE_ALIGN_WRITES. */
8931
8932 static int
8933 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8934 {
8935 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8936 }
8937
8938 /* Write memory data directly to the remote machine.
8939 This does not inform the data cache; the data cache uses this.
8940 HEADER is the starting part of the packet.
8941 MEMADDR is the address in the remote memory space.
8942 MYADDR is the address of the buffer in our space.
8943 LEN_UNITS is the number of addressable units to write.
8944 UNIT_SIZE is the length in bytes of an addressable unit.
8945 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8946 should send data as binary ('X'), or hex-encoded ('M').
8947
8948 The function creates packet of the form
8949 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8950
8951 where encoding of <DATA> is terminated by PACKET_FORMAT.
8952
8953 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8954 are omitted.
8955
8956 Return the transferred status, error or OK (an
8957 'enum target_xfer_status' value). Save the number of addressable units
8958 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8959
8960 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8961 exchange between gdb and the stub could look like (?? in place of the
8962 checksum):
8963
8964 -> $m1000,4#??
8965 <- aaaabbbbccccdddd
8966
8967 -> $M1000,3:eeeeffffeeee#??
8968 <- OK
8969
8970 -> $m1000,4#??
8971 <- eeeeffffeeeedddd */
8972
8973 target_xfer_status
8974 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8975 const gdb_byte *myaddr,
8976 ULONGEST len_units,
8977 int unit_size,
8978 ULONGEST *xfered_len_units,
8979 char packet_format, int use_length)
8980 {
8981 struct remote_state *rs = get_remote_state ();
8982 char *p;
8983 char *plen = NULL;
8984 int plenlen = 0;
8985 int todo_units;
8986 int units_written;
8987 int payload_capacity_bytes;
8988 int payload_length_bytes;
8989
8990 if (packet_format != 'X' && packet_format != 'M')
8991 internal_error (__FILE__, __LINE__,
8992 _("remote_write_bytes_aux: bad packet format"));
8993
8994 if (len_units == 0)
8995 return TARGET_XFER_EOF;
8996
8997 payload_capacity_bytes = get_memory_write_packet_size ();
8998
8999 /* The packet buffer will be large enough for the payload;
9000 get_memory_packet_size ensures this. */
9001 rs->buf[0] = '\0';
9002
9003 /* Compute the size of the actual payload by subtracting out the
9004 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9005
9006 payload_capacity_bytes -= strlen ("$,:#NN");
9007 if (!use_length)
9008 /* The comma won't be used. */
9009 payload_capacity_bytes += 1;
9010 payload_capacity_bytes -= strlen (header);
9011 payload_capacity_bytes -= hexnumlen (memaddr);
9012
9013 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9014
9015 strcat (rs->buf.data (), header);
9016 p = rs->buf.data () + strlen (header);
9017
9018 /* Compute a best guess of the number of bytes actually transfered. */
9019 if (packet_format == 'X')
9020 {
9021 /* Best guess at number of bytes that will fit. */
9022 todo_units = std::min (len_units,
9023 (ULONGEST) payload_capacity_bytes / unit_size);
9024 if (use_length)
9025 payload_capacity_bytes -= hexnumlen (todo_units);
9026 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9027 }
9028 else
9029 {
9030 /* Number of bytes that will fit. */
9031 todo_units
9032 = std::min (len_units,
9033 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9034 if (use_length)
9035 payload_capacity_bytes -= hexnumlen (todo_units);
9036 todo_units = std::min (todo_units,
9037 (payload_capacity_bytes / unit_size) / 2);
9038 }
9039
9040 if (todo_units <= 0)
9041 internal_error (__FILE__, __LINE__,
9042 _("minimum packet size too small to write data"));
9043
9044 /* If we already need another packet, then try to align the end
9045 of this packet to a useful boundary. */
9046 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9047 todo_units = align_for_efficient_write (todo_units, memaddr);
9048
9049 /* Append "<memaddr>". */
9050 memaddr = remote_address_masked (memaddr);
9051 p += hexnumstr (p, (ULONGEST) memaddr);
9052
9053 if (use_length)
9054 {
9055 /* Append ",". */
9056 *p++ = ',';
9057
9058 /* Append the length and retain its location and size. It may need to be
9059 adjusted once the packet body has been created. */
9060 plen = p;
9061 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9062 p += plenlen;
9063 }
9064
9065 /* Append ":". */
9066 *p++ = ':';
9067 *p = '\0';
9068
9069 /* Append the packet body. */
9070 if (packet_format == 'X')
9071 {
9072 /* Binary mode. Send target system values byte by byte, in
9073 increasing byte addresses. Only escape certain critical
9074 characters. */
9075 payload_length_bytes =
9076 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9077 &units_written, payload_capacity_bytes);
9078
9079 /* If not all TODO units fit, then we'll need another packet. Make
9080 a second try to keep the end of the packet aligned. Don't do
9081 this if the packet is tiny. */
9082 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9083 {
9084 int new_todo_units;
9085
9086 new_todo_units = align_for_efficient_write (units_written, memaddr);
9087
9088 if (new_todo_units != units_written)
9089 payload_length_bytes =
9090 remote_escape_output (myaddr, new_todo_units, unit_size,
9091 (gdb_byte *) p, &units_written,
9092 payload_capacity_bytes);
9093 }
9094
9095 p += payload_length_bytes;
9096 if (use_length && units_written < todo_units)
9097 {
9098 /* Escape chars have filled up the buffer prematurely,
9099 and we have actually sent fewer units than planned.
9100 Fix-up the length field of the packet. Use the same
9101 number of characters as before. */
9102 plen += hexnumnstr (plen, (ULONGEST) units_written,
9103 plenlen);
9104 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9105 }
9106 }
9107 else
9108 {
9109 /* Normal mode: Send target system values byte by byte, in
9110 increasing byte addresses. Each byte is encoded as a two hex
9111 value. */
9112 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9113 units_written = todo_units;
9114 }
9115
9116 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9117 getpkt (&rs->buf, 0);
9118
9119 if (rs->buf[0] == 'E')
9120 return TARGET_XFER_E_IO;
9121
9122 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9123 send fewer units than we'd planned. */
9124 *xfered_len_units = (ULONGEST) units_written;
9125 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9126 }
9127
9128 /* Write memory data directly to the remote machine.
9129 This does not inform the data cache; the data cache uses this.
9130 MEMADDR is the address in the remote memory space.
9131 MYADDR is the address of the buffer in our space.
9132 LEN is the number of bytes.
9133
9134 Return the transferred status, error or OK (an
9135 'enum target_xfer_status' value). Save the number of bytes
9136 transferred in *XFERED_LEN. Only transfer a single packet. */
9137
9138 target_xfer_status
9139 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9140 ULONGEST len, int unit_size,
9141 ULONGEST *xfered_len)
9142 {
9143 const char *packet_format = NULL;
9144
9145 /* Check whether the target supports binary download. */
9146 check_binary_download (memaddr);
9147
9148 switch (packet_support (PACKET_X))
9149 {
9150 case PACKET_ENABLE:
9151 packet_format = "X";
9152 break;
9153 case PACKET_DISABLE:
9154 packet_format = "M";
9155 break;
9156 case PACKET_SUPPORT_UNKNOWN:
9157 internal_error (__FILE__, __LINE__,
9158 _("remote_write_bytes: bad internal state"));
9159 default:
9160 internal_error (__FILE__, __LINE__, _("bad switch"));
9161 }
9162
9163 return remote_write_bytes_aux (packet_format,
9164 memaddr, myaddr, len, unit_size, xfered_len,
9165 packet_format[0], 1);
9166 }
9167
9168 /* Read memory data directly from the remote machine.
9169 This does not use the data cache; the data cache uses this.
9170 MEMADDR is the address in the remote memory space.
9171 MYADDR is the address of the buffer in our space.
9172 LEN_UNITS is the number of addressable memory units to read..
9173 UNIT_SIZE is the length in bytes of an addressable unit.
9174
9175 Return the transferred status, error or OK (an
9176 'enum target_xfer_status' value). Save the number of bytes
9177 transferred in *XFERED_LEN_UNITS.
9178
9179 See the comment of remote_write_bytes_aux for an example of
9180 memory read/write exchange between gdb and the stub. */
9181
9182 target_xfer_status
9183 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9184 ULONGEST len_units,
9185 int unit_size, ULONGEST *xfered_len_units)
9186 {
9187 struct remote_state *rs = get_remote_state ();
9188 int buf_size_bytes; /* Max size of packet output buffer. */
9189 char *p;
9190 int todo_units;
9191 int decoded_bytes;
9192
9193 buf_size_bytes = get_memory_read_packet_size ();
9194 /* The packet buffer will be large enough for the payload;
9195 get_memory_packet_size ensures this. */
9196
9197 /* Number of units that will fit. */
9198 todo_units = std::min (len_units,
9199 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9200
9201 /* Construct "m"<memaddr>","<len>". */
9202 memaddr = remote_address_masked (memaddr);
9203 p = rs->buf.data ();
9204 *p++ = 'm';
9205 p += hexnumstr (p, (ULONGEST) memaddr);
9206 *p++ = ',';
9207 p += hexnumstr (p, (ULONGEST) todo_units);
9208 *p = '\0';
9209 putpkt (rs->buf);
9210 getpkt (&rs->buf, 0);
9211 if (rs->buf[0] == 'E'
9212 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9213 && rs->buf[3] == '\0')
9214 return TARGET_XFER_E_IO;
9215 /* Reply describes memory byte by byte, each byte encoded as two hex
9216 characters. */
9217 p = rs->buf.data ();
9218 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9219 /* Return what we have. Let higher layers handle partial reads. */
9220 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9221 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9222 }
9223
9224 /* Using the set of read-only target sections of remote, read live
9225 read-only memory.
9226
9227 For interface/parameters/return description see target.h,
9228 to_xfer_partial. */
9229
9230 target_xfer_status
9231 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9232 ULONGEST memaddr,
9233 ULONGEST len,
9234 int unit_size,
9235 ULONGEST *xfered_len)
9236 {
9237 const struct target_section *secp;
9238
9239 secp = target_section_by_addr (this, memaddr);
9240 if (secp != NULL
9241 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9242 {
9243 ULONGEST memend = memaddr + len;
9244
9245 const target_section_table *table = target_get_section_table (this);
9246 for (const target_section &p : *table)
9247 {
9248 if (memaddr >= p.addr)
9249 {
9250 if (memend <= p.endaddr)
9251 {
9252 /* Entire transfer is within this section. */
9253 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9254 xfered_len);
9255 }
9256 else if (memaddr >= p.endaddr)
9257 {
9258 /* This section ends before the transfer starts. */
9259 continue;
9260 }
9261 else
9262 {
9263 /* This section overlaps the transfer. Just do half. */
9264 len = p.endaddr - memaddr;
9265 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9266 xfered_len);
9267 }
9268 }
9269 }
9270 }
9271
9272 return TARGET_XFER_EOF;
9273 }
9274
9275 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9276 first if the requested memory is unavailable in traceframe.
9277 Otherwise, fall back to remote_read_bytes_1. */
9278
9279 target_xfer_status
9280 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9281 gdb_byte *myaddr, ULONGEST len, int unit_size,
9282 ULONGEST *xfered_len)
9283 {
9284 if (len == 0)
9285 return TARGET_XFER_EOF;
9286
9287 if (get_traceframe_number () != -1)
9288 {
9289 std::vector<mem_range> available;
9290
9291 /* If we fail to get the set of available memory, then the
9292 target does not support querying traceframe info, and so we
9293 attempt reading from the traceframe anyway (assuming the
9294 target implements the old QTro packet then). */
9295 if (traceframe_available_memory (&available, memaddr, len))
9296 {
9297 if (available.empty () || available[0].start != memaddr)
9298 {
9299 enum target_xfer_status res;
9300
9301 /* Don't read into the traceframe's available
9302 memory. */
9303 if (!available.empty ())
9304 {
9305 LONGEST oldlen = len;
9306
9307 len = available[0].start - memaddr;
9308 gdb_assert (len <= oldlen);
9309 }
9310
9311 /* This goes through the topmost target again. */
9312 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9313 len, unit_size, xfered_len);
9314 if (res == TARGET_XFER_OK)
9315 return TARGET_XFER_OK;
9316 else
9317 {
9318 /* No use trying further, we know some memory starting
9319 at MEMADDR isn't available. */
9320 *xfered_len = len;
9321 return (*xfered_len != 0) ?
9322 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9323 }
9324 }
9325
9326 /* Don't try to read more than how much is available, in
9327 case the target implements the deprecated QTro packet to
9328 cater for older GDBs (the target's knowledge of read-only
9329 sections may be outdated by now). */
9330 len = available[0].length;
9331 }
9332 }
9333
9334 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9335 }
9336
9337 \f
9338
9339 /* Sends a packet with content determined by the printf format string
9340 FORMAT and the remaining arguments, then gets the reply. Returns
9341 whether the packet was a success, a failure, or unknown. */
9342
9343 packet_result
9344 remote_target::remote_send_printf (const char *format, ...)
9345 {
9346 struct remote_state *rs = get_remote_state ();
9347 int max_size = get_remote_packet_size ();
9348 va_list ap;
9349
9350 va_start (ap, format);
9351
9352 rs->buf[0] = '\0';
9353 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9354
9355 va_end (ap);
9356
9357 if (size >= max_size)
9358 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
9359
9360 if (putpkt (rs->buf) < 0)
9361 error (_("Communication problem with target."));
9362
9363 rs->buf[0] = '\0';
9364 getpkt (&rs->buf, 0);
9365
9366 return packet_check_result (rs->buf);
9367 }
9368
9369 /* Flash writing can take quite some time. We'll set
9370 effectively infinite timeout for flash operations.
9371 In future, we'll need to decide on a better approach. */
9372 static const int remote_flash_timeout = 1000;
9373
9374 void
9375 remote_target::flash_erase (ULONGEST address, LONGEST length)
9376 {
9377 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9378 enum packet_result ret;
9379 scoped_restore restore_timeout
9380 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9381
9382 ret = remote_send_printf ("vFlashErase:%s,%s",
9383 phex (address, addr_size),
9384 phex (length, 4));
9385 switch (ret)
9386 {
9387 case PACKET_UNKNOWN:
9388 error (_("Remote target does not support flash erase"));
9389 case PACKET_ERROR:
9390 error (_("Error erasing flash with vFlashErase packet"));
9391 default:
9392 break;
9393 }
9394 }
9395
9396 target_xfer_status
9397 remote_target::remote_flash_write (ULONGEST address,
9398 ULONGEST length, ULONGEST *xfered_len,
9399 const gdb_byte *data)
9400 {
9401 scoped_restore restore_timeout
9402 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9403 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9404 xfered_len,'X', 0);
9405 }
9406
9407 void
9408 remote_target::flash_done ()
9409 {
9410 int ret;
9411
9412 scoped_restore restore_timeout
9413 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9414
9415 ret = remote_send_printf ("vFlashDone");
9416
9417 switch (ret)
9418 {
9419 case PACKET_UNKNOWN:
9420 error (_("Remote target does not support vFlashDone"));
9421 case PACKET_ERROR:
9422 error (_("Error finishing flash operation"));
9423 default:
9424 break;
9425 }
9426 }
9427
9428 void
9429 remote_target::files_info ()
9430 {
9431 puts_filtered ("Debugging a target over a serial line.\n");
9432 }
9433 \f
9434 /* Stuff for dealing with the packets which are part of this protocol.
9435 See comment at top of file for details. */
9436
9437 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9438 error to higher layers. Called when a serial error is detected.
9439 The exception message is STRING, followed by a colon and a blank,
9440 the system error message for errno at function entry and final dot
9441 for output compatibility with throw_perror_with_name. */
9442
9443 static void
9444 unpush_and_perror (remote_target *target, const char *string)
9445 {
9446 int saved_errno = errno;
9447
9448 remote_unpush_target (target);
9449 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9450 safe_strerror (saved_errno));
9451 }
9452
9453 /* Read a single character from the remote end. The current quit
9454 handler is overridden to avoid quitting in the middle of packet
9455 sequence, as that would break communication with the remote server.
9456 See remote_serial_quit_handler for more detail. */
9457
9458 int
9459 remote_target::readchar (int timeout)
9460 {
9461 int ch;
9462 struct remote_state *rs = get_remote_state ();
9463
9464 {
9465 scoped_restore restore_quit_target
9466 = make_scoped_restore (&curr_quit_handler_target, this);
9467 scoped_restore restore_quit
9468 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9469
9470 rs->got_ctrlc_during_io = 0;
9471
9472 ch = serial_readchar (rs->remote_desc, timeout);
9473
9474 if (rs->got_ctrlc_during_io)
9475 set_quit_flag ();
9476 }
9477
9478 if (ch >= 0)
9479 return ch;
9480
9481 switch ((enum serial_rc) ch)
9482 {
9483 case SERIAL_EOF:
9484 remote_unpush_target (this);
9485 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9486 /* no return */
9487 case SERIAL_ERROR:
9488 unpush_and_perror (this, _("Remote communication error. "
9489 "Target disconnected."));
9490 /* no return */
9491 case SERIAL_TIMEOUT:
9492 break;
9493 }
9494 return ch;
9495 }
9496
9497 /* Wrapper for serial_write that closes the target and throws if
9498 writing fails. The current quit handler is overridden to avoid
9499 quitting in the middle of packet sequence, as that would break
9500 communication with the remote server. See
9501 remote_serial_quit_handler for more detail. */
9502
9503 void
9504 remote_target::remote_serial_write (const char *str, int len)
9505 {
9506 struct remote_state *rs = get_remote_state ();
9507
9508 scoped_restore restore_quit_target
9509 = make_scoped_restore (&curr_quit_handler_target, this);
9510 scoped_restore restore_quit
9511 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9512
9513 rs->got_ctrlc_during_io = 0;
9514
9515 if (serial_write (rs->remote_desc, str, len))
9516 {
9517 unpush_and_perror (this, _("Remote communication error. "
9518 "Target disconnected."));
9519 }
9520
9521 if (rs->got_ctrlc_during_io)
9522 set_quit_flag ();
9523 }
9524
9525 /* Return a string representing an escaped version of BUF, of len N.
9526 E.g. \n is converted to \\n, \t to \\t, etc. */
9527
9528 static std::string
9529 escape_buffer (const char *buf, int n)
9530 {
9531 string_file stb;
9532
9533 stb.putstrn (buf, n, '\\');
9534 return std::move (stb.string ());
9535 }
9536
9537 int
9538 remote_target::putpkt (const char *buf)
9539 {
9540 return putpkt_binary (buf, strlen (buf));
9541 }
9542
9543 /* Wrapper around remote_target::putpkt to avoid exporting
9544 remote_target. */
9545
9546 int
9547 putpkt (remote_target *remote, const char *buf)
9548 {
9549 return remote->putpkt (buf);
9550 }
9551
9552 /* Send a packet to the remote machine, with error checking. The data
9553 of the packet is in BUF. The string in BUF can be at most
9554 get_remote_packet_size () - 5 to account for the $, # and checksum,
9555 and for a possible /0 if we are debugging (remote_debug) and want
9556 to print the sent packet as a string. */
9557
9558 int
9559 remote_target::putpkt_binary (const char *buf, int cnt)
9560 {
9561 struct remote_state *rs = get_remote_state ();
9562 int i;
9563 unsigned char csum = 0;
9564 gdb::def_vector<char> data (cnt + 6);
9565 char *buf2 = data.data ();
9566
9567 int ch;
9568 int tcount = 0;
9569 char *p;
9570
9571 /* Catch cases like trying to read memory or listing threads while
9572 we're waiting for a stop reply. The remote server wouldn't be
9573 ready to handle this request, so we'd hang and timeout. We don't
9574 have to worry about this in synchronous mode, because in that
9575 case it's not possible to issue a command while the target is
9576 running. This is not a problem in non-stop mode, because in that
9577 case, the stub is always ready to process serial input. */
9578 if (!target_is_non_stop_p ()
9579 && target_is_async_p ()
9580 && rs->waiting_for_stop_reply)
9581 {
9582 error (_("Cannot execute this command while the target is running.\n"
9583 "Use the \"interrupt\" command to stop the target\n"
9584 "and then try again."));
9585 }
9586
9587 /* Copy the packet into buffer BUF2, encapsulating it
9588 and giving it a checksum. */
9589
9590 p = buf2;
9591 *p++ = '$';
9592
9593 for (i = 0; i < cnt; i++)
9594 {
9595 csum += buf[i];
9596 *p++ = buf[i];
9597 }
9598 *p++ = '#';
9599 *p++ = tohex ((csum >> 4) & 0xf);
9600 *p++ = tohex (csum & 0xf);
9601
9602 /* Send it over and over until we get a positive ack. */
9603
9604 while (1)
9605 {
9606 if (remote_debug)
9607 {
9608 *p = '\0';
9609
9610 int len = (int) (p - buf2);
9611 int max_chars;
9612
9613 if (remote_packet_max_chars < 0)
9614 max_chars = len;
9615 else
9616 max_chars = remote_packet_max_chars;
9617
9618 std::string str
9619 = escape_buffer (buf2, std::min (len, max_chars));
9620
9621 if (len > max_chars)
9622 remote_debug_printf_nofunc
9623 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9624 len - max_chars);
9625 else
9626 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9627 }
9628 remote_serial_write (buf2, p - buf2);
9629
9630 /* If this is a no acks version of the remote protocol, send the
9631 packet and move on. */
9632 if (rs->noack_mode)
9633 break;
9634
9635 /* Read until either a timeout occurs (-2) or '+' is read.
9636 Handle any notification that arrives in the mean time. */
9637 while (1)
9638 {
9639 ch = readchar (remote_timeout);
9640
9641 switch (ch)
9642 {
9643 case '+':
9644 remote_debug_printf_nofunc ("Received Ack");
9645 return 1;
9646 case '-':
9647 remote_debug_printf_nofunc ("Received Nak");
9648 /* FALLTHROUGH */
9649 case SERIAL_TIMEOUT:
9650 tcount++;
9651 if (tcount > 3)
9652 return 0;
9653 break; /* Retransmit buffer. */
9654 case '$':
9655 {
9656 remote_debug_printf ("Packet instead of Ack, ignoring it");
9657 /* It's probably an old response sent because an ACK
9658 was lost. Gobble up the packet and ack it so it
9659 doesn't get retransmitted when we resend this
9660 packet. */
9661 skip_frame ();
9662 remote_serial_write ("+", 1);
9663 continue; /* Now, go look for +. */
9664 }
9665
9666 case '%':
9667 {
9668 int val;
9669
9670 /* If we got a notification, handle it, and go back to looking
9671 for an ack. */
9672 /* We've found the start of a notification. Now
9673 collect the data. */
9674 val = read_frame (&rs->buf);
9675 if (val >= 0)
9676 {
9677 remote_debug_printf_nofunc
9678 (" Notification received: %s",
9679 escape_buffer (rs->buf.data (), val).c_str ());
9680
9681 handle_notification (rs->notif_state, rs->buf.data ());
9682 /* We're in sync now, rewait for the ack. */
9683 tcount = 0;
9684 }
9685 else
9686 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9687 rs->buf.data ());
9688 continue;
9689 }
9690 /* fall-through */
9691 default:
9692 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9693 rs->buf.data ());
9694 continue;
9695 }
9696 break; /* Here to retransmit. */
9697 }
9698
9699 #if 0
9700 /* This is wrong. If doing a long backtrace, the user should be
9701 able to get out next time we call QUIT, without anything as
9702 violent as interrupt_query. If we want to provide a way out of
9703 here without getting to the next QUIT, it should be based on
9704 hitting ^C twice as in remote_wait. */
9705 if (quit_flag)
9706 {
9707 quit_flag = 0;
9708 interrupt_query ();
9709 }
9710 #endif
9711 }
9712
9713 return 0;
9714 }
9715
9716 /* Come here after finding the start of a frame when we expected an
9717 ack. Do our best to discard the rest of this packet. */
9718
9719 void
9720 remote_target::skip_frame ()
9721 {
9722 int c;
9723
9724 while (1)
9725 {
9726 c = readchar (remote_timeout);
9727 switch (c)
9728 {
9729 case SERIAL_TIMEOUT:
9730 /* Nothing we can do. */
9731 return;
9732 case '#':
9733 /* Discard the two bytes of checksum and stop. */
9734 c = readchar (remote_timeout);
9735 if (c >= 0)
9736 c = readchar (remote_timeout);
9737
9738 return;
9739 case '*': /* Run length encoding. */
9740 /* Discard the repeat count. */
9741 c = readchar (remote_timeout);
9742 if (c < 0)
9743 return;
9744 break;
9745 default:
9746 /* A regular character. */
9747 break;
9748 }
9749 }
9750 }
9751
9752 /* Come here after finding the start of the frame. Collect the rest
9753 into *BUF, verifying the checksum, length, and handling run-length
9754 compression. NUL terminate the buffer. If there is not enough room,
9755 expand *BUF.
9756
9757 Returns -1 on error, number of characters in buffer (ignoring the
9758 trailing NULL) on success. (could be extended to return one of the
9759 SERIAL status indications). */
9760
9761 long
9762 remote_target::read_frame (gdb::char_vector *buf_p)
9763 {
9764 unsigned char csum;
9765 long bc;
9766 int c;
9767 char *buf = buf_p->data ();
9768 struct remote_state *rs = get_remote_state ();
9769
9770 csum = 0;
9771 bc = 0;
9772
9773 while (1)
9774 {
9775 c = readchar (remote_timeout);
9776 switch (c)
9777 {
9778 case SERIAL_TIMEOUT:
9779 remote_debug_printf ("Timeout in mid-packet, retrying");
9780 return -1;
9781
9782 case '$':
9783 remote_debug_printf ("Saw new packet start in middle of old one");
9784 return -1; /* Start a new packet, count retries. */
9785
9786 case '#':
9787 {
9788 unsigned char pktcsum;
9789 int check_0 = 0;
9790 int check_1 = 0;
9791
9792 buf[bc] = '\0';
9793
9794 check_0 = readchar (remote_timeout);
9795 if (check_0 >= 0)
9796 check_1 = readchar (remote_timeout);
9797
9798 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9799 {
9800 remote_debug_printf ("Timeout in checksum, retrying");
9801 return -1;
9802 }
9803 else if (check_0 < 0 || check_1 < 0)
9804 {
9805 remote_debug_printf ("Communication error in checksum");
9806 return -1;
9807 }
9808
9809 /* Don't recompute the checksum; with no ack packets we
9810 don't have any way to indicate a packet retransmission
9811 is necessary. */
9812 if (rs->noack_mode)
9813 return bc;
9814
9815 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9816 if (csum == pktcsum)
9817 return bc;
9818
9819 remote_debug_printf
9820 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
9821 pktcsum, csum, escape_buffer (buf, bc).c_str ());
9822
9823 /* Number of characters in buffer ignoring trailing
9824 NULL. */
9825 return -1;
9826 }
9827 case '*': /* Run length encoding. */
9828 {
9829 int repeat;
9830
9831 csum += c;
9832 c = readchar (remote_timeout);
9833 csum += c;
9834 repeat = c - ' ' + 3; /* Compute repeat count. */
9835
9836 /* The character before ``*'' is repeated. */
9837
9838 if (repeat > 0 && repeat <= 255 && bc > 0)
9839 {
9840 if (bc + repeat - 1 >= buf_p->size () - 1)
9841 {
9842 /* Make some more room in the buffer. */
9843 buf_p->resize (buf_p->size () + repeat);
9844 buf = buf_p->data ();
9845 }
9846
9847 memset (&buf[bc], buf[bc - 1], repeat);
9848 bc += repeat;
9849 continue;
9850 }
9851
9852 buf[bc] = '\0';
9853 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9854 return -1;
9855 }
9856 default:
9857 if (bc >= buf_p->size () - 1)
9858 {
9859 /* Make some more room in the buffer. */
9860 buf_p->resize (buf_p->size () * 2);
9861 buf = buf_p->data ();
9862 }
9863
9864 buf[bc++] = c;
9865 csum += c;
9866 continue;
9867 }
9868 }
9869 }
9870
9871 /* Set this to the maximum number of seconds to wait instead of waiting forever
9872 in target_wait(). If this timer times out, then it generates an error and
9873 the command is aborted. This replaces most of the need for timeouts in the
9874 GDB test suite, and makes it possible to distinguish between a hung target
9875 and one with slow communications. */
9876
9877 static int watchdog = 0;
9878 static void
9879 show_watchdog (struct ui_file *file, int from_tty,
9880 struct cmd_list_element *c, const char *value)
9881 {
9882 fprintf_filtered (file, _("Watchdog timer is %s.\n"), value);
9883 }
9884
9885 /* Read a packet from the remote machine, with error checking, and
9886 store it in *BUF. Resize *BUF if necessary to hold the result. If
9887 FOREVER, wait forever rather than timing out; this is used (in
9888 synchronous mode) to wait for a target that is is executing user
9889 code to stop. */
9890 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9891 don't have to change all the calls to getpkt to deal with the
9892 return value, because at the moment I don't know what the right
9893 thing to do it for those. */
9894
9895 void
9896 remote_target::getpkt (gdb::char_vector *buf, int forever)
9897 {
9898 getpkt_sane (buf, forever);
9899 }
9900
9901
9902 /* Read a packet from the remote machine, with error checking, and
9903 store it in *BUF. Resize *BUF if necessary to hold the result. If
9904 FOREVER, wait forever rather than timing out; this is used (in
9905 synchronous mode) to wait for a target that is is executing user
9906 code to stop. If FOREVER == 0, this function is allowed to time
9907 out gracefully and return an indication of this to the caller.
9908 Otherwise return the number of bytes read. If EXPECTING_NOTIF,
9909 consider receiving a notification enough reason to return to the
9910 caller. *IS_NOTIF is an output boolean that indicates whether *BUF
9911 holds a notification or not (a regular packet). */
9912
9913 int
9914 remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
9915 int forever, int expecting_notif,
9916 int *is_notif)
9917 {
9918 struct remote_state *rs = get_remote_state ();
9919 int c;
9920 int tries;
9921 int timeout;
9922 int val = -1;
9923
9924 strcpy (buf->data (), "timeout");
9925
9926 if (forever)
9927 timeout = watchdog > 0 ? watchdog : -1;
9928 else if (expecting_notif)
9929 timeout = 0; /* There should already be a char in the buffer. If
9930 not, bail out. */
9931 else
9932 timeout = remote_timeout;
9933
9934 #define MAX_TRIES 3
9935
9936 /* Process any number of notifications, and then return when
9937 we get a packet. */
9938 for (;;)
9939 {
9940 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9941 times. */
9942 for (tries = 1; tries <= MAX_TRIES; tries++)
9943 {
9944 /* This can loop forever if the remote side sends us
9945 characters continuously, but if it pauses, we'll get
9946 SERIAL_TIMEOUT from readchar because of timeout. Then
9947 we'll count that as a retry.
9948
9949 Note that even when forever is set, we will only wait
9950 forever prior to the start of a packet. After that, we
9951 expect characters to arrive at a brisk pace. They should
9952 show up within remote_timeout intervals. */
9953 do
9954 c = readchar (timeout);
9955 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9956
9957 if (c == SERIAL_TIMEOUT)
9958 {
9959 if (expecting_notif)
9960 return -1; /* Don't complain, it's normal to not get
9961 anything in this case. */
9962
9963 if (forever) /* Watchdog went off? Kill the target. */
9964 {
9965 remote_unpush_target (this);
9966 throw_error (TARGET_CLOSE_ERROR,
9967 _("Watchdog timeout has expired. "
9968 "Target detached."));
9969 }
9970
9971 remote_debug_printf ("Timed out.");
9972 }
9973 else
9974 {
9975 /* We've found the start of a packet or notification.
9976 Now collect the data. */
9977 val = read_frame (buf);
9978 if (val >= 0)
9979 break;
9980 }
9981
9982 remote_serial_write ("-", 1);
9983 }
9984
9985 if (tries > MAX_TRIES)
9986 {
9987 /* We have tried hard enough, and just can't receive the
9988 packet/notification. Give up. */
9989 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9990
9991 /* Skip the ack char if we're in no-ack mode. */
9992 if (!rs->noack_mode)
9993 remote_serial_write ("+", 1);
9994 return -1;
9995 }
9996
9997 /* If we got an ordinary packet, return that to our caller. */
9998 if (c == '$')
9999 {
10000 if (remote_debug)
10001 {
10002 int max_chars;
10003
10004 if (remote_packet_max_chars < 0)
10005 max_chars = val;
10006 else
10007 max_chars = remote_packet_max_chars;
10008
10009 std::string str
10010 = escape_buffer (buf->data (),
10011 std::min (val, max_chars));
10012
10013 if (val > max_chars)
10014 remote_debug_printf_nofunc
10015 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10016 val - max_chars);
10017 else
10018 remote_debug_printf_nofunc ("Packet received: %s",
10019 str.c_str ());
10020 }
10021
10022 /* Skip the ack char if we're in no-ack mode. */
10023 if (!rs->noack_mode)
10024 remote_serial_write ("+", 1);
10025 if (is_notif != NULL)
10026 *is_notif = 0;
10027 return val;
10028 }
10029
10030 /* If we got a notification, handle it, and go back to looking
10031 for a packet. */
10032 else
10033 {
10034 gdb_assert (c == '%');
10035
10036 remote_debug_printf_nofunc
10037 (" Notification received: %s",
10038 escape_buffer (buf->data (), val).c_str ());
10039
10040 if (is_notif != NULL)
10041 *is_notif = 1;
10042
10043 handle_notification (rs->notif_state, buf->data ());
10044
10045 /* Notifications require no acknowledgement. */
10046
10047 if (expecting_notif)
10048 return val;
10049 }
10050 }
10051 }
10052
10053 int
10054 remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
10055 {
10056 return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
10057 }
10058
10059 int
10060 remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
10061 int *is_notif)
10062 {
10063 return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
10064 }
10065
10066 /* Kill any new fork children of inferior INF that haven't been
10067 processed by follow_fork. */
10068
10069 void
10070 remote_target::kill_new_fork_children (inferior *inf)
10071 {
10072 remote_state *rs = get_remote_state ();
10073 struct notif_client *notif = &notif_client_stop;
10074
10075 /* Kill the fork child threads of any threads in inferior INF that are stopped
10076 at a fork event. */
10077 for (thread_info *thread : inf->non_exited_threads ())
10078 {
10079 const target_waitstatus *ws = thread_pending_fork_status (thread);
10080
10081 if (ws == nullptr)
10082 continue;
10083
10084 int child_pid = ws->child_ptid ().pid ();
10085 int res = remote_vkill (child_pid);
10086
10087 if (res != 0)
10088 error (_("Can't kill fork child process %d"), child_pid);
10089 }
10090
10091 /* Check for any pending fork events (not reported or processed yet)
10092 in inferior INF and kill those fork child threads as well. */
10093 remote_notif_get_pending_events (notif);
10094 for (auto &event : rs->stop_reply_queue)
10095 {
10096 if (event->ptid.pid () != inf->pid)
10097 continue;
10098
10099 if (!is_fork_status (event->ws.kind ()))
10100 continue;
10101
10102 int child_pid = event->ws.child_ptid ().pid ();
10103 int res = remote_vkill (child_pid);
10104
10105 if (res != 0)
10106 error (_("Can't kill fork child process %d"), child_pid);
10107 }
10108 }
10109
10110 \f
10111 /* Target hook to kill the current inferior. */
10112
10113 void
10114 remote_target::kill ()
10115 {
10116 int res = -1;
10117 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10118 struct remote_state *rs = get_remote_state ();
10119
10120 gdb_assert (inf != nullptr);
10121
10122 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
10123 {
10124 /* If we're stopped while forking and we haven't followed yet,
10125 kill the child task. We need to do this before killing the
10126 parent task because if this is a vfork then the parent will
10127 be sleeping. */
10128 kill_new_fork_children (inf);
10129
10130 res = remote_vkill (inf->pid);
10131 if (res == 0)
10132 {
10133 target_mourn_inferior (inferior_ptid);
10134 return;
10135 }
10136 }
10137
10138 /* If we are in 'target remote' mode and we are killing the only
10139 inferior, then we will tell gdbserver to exit and unpush the
10140 target. */
10141 if (res == -1 && !remote_multi_process_p (rs)
10142 && number_of_live_inferiors (this) == 1)
10143 {
10144 remote_kill_k ();
10145
10146 /* We've killed the remote end, we get to mourn it. If we are
10147 not in extended mode, mourning the inferior also unpushes
10148 remote_ops from the target stack, which closes the remote
10149 connection. */
10150 target_mourn_inferior (inferior_ptid);
10151
10152 return;
10153 }
10154
10155 error (_("Can't kill process"));
10156 }
10157
10158 /* Send a kill request to the target using the 'vKill' packet. */
10159
10160 int
10161 remote_target::remote_vkill (int pid)
10162 {
10163 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
10164 return -1;
10165
10166 remote_state *rs = get_remote_state ();
10167
10168 /* Tell the remote target to detach. */
10169 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10170 putpkt (rs->buf);
10171 getpkt (&rs->buf, 0);
10172
10173 switch (packet_ok (rs->buf,
10174 &remote_protocol_packets[PACKET_vKill]))
10175 {
10176 case PACKET_OK:
10177 return 0;
10178 case PACKET_ERROR:
10179 return 1;
10180 case PACKET_UNKNOWN:
10181 return -1;
10182 default:
10183 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
10184 }
10185 }
10186
10187 /* Send a kill request to the target using the 'k' packet. */
10188
10189 void
10190 remote_target::remote_kill_k ()
10191 {
10192 /* Catch errors so the user can quit from gdb even when we
10193 aren't on speaking terms with the remote system. */
10194 try
10195 {
10196 putpkt ("k");
10197 }
10198 catch (const gdb_exception_error &ex)
10199 {
10200 if (ex.error == TARGET_CLOSE_ERROR)
10201 {
10202 /* If we got an (EOF) error that caused the target
10203 to go away, then we're done, that's what we wanted.
10204 "k" is susceptible to cause a premature EOF, given
10205 that the remote server isn't actually required to
10206 reply to "k", and it can happen that it doesn't
10207 even get to reply ACK to the "k". */
10208 return;
10209 }
10210
10211 /* Otherwise, something went wrong. We didn't actually kill
10212 the target. Just propagate the exception, and let the
10213 user or higher layers decide what to do. */
10214 throw;
10215 }
10216 }
10217
10218 void
10219 remote_target::mourn_inferior ()
10220 {
10221 struct remote_state *rs = get_remote_state ();
10222
10223 /* We're no longer interested in notification events of an inferior
10224 that exited or was killed/detached. */
10225 discard_pending_stop_replies (current_inferior ());
10226
10227 /* In 'target remote' mode with one inferior, we close the connection. */
10228 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10229 {
10230 remote_unpush_target (this);
10231 return;
10232 }
10233
10234 /* In case we got here due to an error, but we're going to stay
10235 connected. */
10236 rs->waiting_for_stop_reply = 0;
10237
10238 /* If the current general thread belonged to the process we just
10239 detached from or has exited, the remote side current general
10240 thread becomes undefined. Considering a case like this:
10241
10242 - We just got here due to a detach.
10243 - The process that we're detaching from happens to immediately
10244 report a global breakpoint being hit in non-stop mode, in the
10245 same thread we had selected before.
10246 - GDB attaches to this process again.
10247 - This event happens to be the next event we handle.
10248
10249 GDB would consider that the current general thread didn't need to
10250 be set on the stub side (with Hg), since for all it knew,
10251 GENERAL_THREAD hadn't changed.
10252
10253 Notice that although in all-stop mode, the remote server always
10254 sets the current thread to the thread reporting the stop event,
10255 that doesn't happen in non-stop mode; in non-stop, the stub *must
10256 not* change the current thread when reporting a breakpoint hit,
10257 due to the decoupling of event reporting and event handling.
10258
10259 To keep things simple, we always invalidate our notion of the
10260 current thread. */
10261 record_currthread (rs, minus_one_ptid);
10262
10263 /* Call common code to mark the inferior as not running. */
10264 generic_mourn_inferior ();
10265 }
10266
10267 bool
10268 extended_remote_target::supports_disable_randomization ()
10269 {
10270 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
10271 }
10272
10273 void
10274 remote_target::extended_remote_disable_randomization (int val)
10275 {
10276 struct remote_state *rs = get_remote_state ();
10277 char *reply;
10278
10279 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10280 "QDisableRandomization:%x", val);
10281 putpkt (rs->buf);
10282 reply = remote_get_noisy_reply ();
10283 if (*reply == '\0')
10284 error (_("Target does not support QDisableRandomization."));
10285 if (strcmp (reply, "OK") != 0)
10286 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10287 }
10288
10289 int
10290 remote_target::extended_remote_run (const std::string &args)
10291 {
10292 struct remote_state *rs = get_remote_state ();
10293 int len;
10294 const char *remote_exec_file = get_remote_exec_file ();
10295
10296 /* If the user has disabled vRun support, or we have detected that
10297 support is not available, do not try it. */
10298 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
10299 return -1;
10300
10301 strcpy (rs->buf.data (), "vRun;");
10302 len = strlen (rs->buf.data ());
10303
10304 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10305 error (_("Remote file name too long for run packet"));
10306 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10307 strlen (remote_exec_file));
10308
10309 if (!args.empty ())
10310 {
10311 int i;
10312
10313 gdb_argv argv (args.c_str ());
10314 for (i = 0; argv[i] != NULL; i++)
10315 {
10316 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10317 error (_("Argument list too long for run packet"));
10318 rs->buf[len++] = ';';
10319 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10320 strlen (argv[i]));
10321 }
10322 }
10323
10324 rs->buf[len++] = '\0';
10325
10326 putpkt (rs->buf);
10327 getpkt (&rs->buf, 0);
10328
10329 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
10330 {
10331 case PACKET_OK:
10332 /* We have a wait response. All is well. */
10333 return 0;
10334 case PACKET_UNKNOWN:
10335 return -1;
10336 case PACKET_ERROR:
10337 if (remote_exec_file[0] == '\0')
10338 error (_("Running the default executable on the remote target failed; "
10339 "try \"set remote exec-file\"?"));
10340 else
10341 error (_("Running \"%s\" on the remote target failed"),
10342 remote_exec_file);
10343 default:
10344 gdb_assert_not_reached ("bad switch");
10345 }
10346 }
10347
10348 /* Helper function to send set/unset environment packets. ACTION is
10349 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10350 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10351 sent. */
10352
10353 void
10354 remote_target::send_environment_packet (const char *action,
10355 const char *packet,
10356 const char *value)
10357 {
10358 remote_state *rs = get_remote_state ();
10359
10360 /* Convert the environment variable to an hex string, which
10361 is the best format to be transmitted over the wire. */
10362 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10363 strlen (value));
10364
10365 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10366 "%s:%s", packet, encoded_value.c_str ());
10367
10368 putpkt (rs->buf);
10369 getpkt (&rs->buf, 0);
10370 if (strcmp (rs->buf.data (), "OK") != 0)
10371 warning (_("Unable to %s environment variable '%s' on remote."),
10372 action, value);
10373 }
10374
10375 /* Helper function to handle the QEnvironment* packets. */
10376
10377 void
10378 remote_target::extended_remote_environment_support ()
10379 {
10380 remote_state *rs = get_remote_state ();
10381
10382 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10383 {
10384 putpkt ("QEnvironmentReset");
10385 getpkt (&rs->buf, 0);
10386 if (strcmp (rs->buf.data (), "OK") != 0)
10387 warning (_("Unable to reset environment on remote."));
10388 }
10389
10390 gdb_environ *e = &current_inferior ()->environment;
10391
10392 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10393 for (const std::string &el : e->user_set_env ())
10394 send_environment_packet ("set", "QEnvironmentHexEncoded",
10395 el.c_str ());
10396
10397 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10398 for (const std::string &el : e->user_unset_env ())
10399 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10400 }
10401
10402 /* Helper function to set the current working directory for the
10403 inferior in the remote target. */
10404
10405 void
10406 remote_target::extended_remote_set_inferior_cwd ()
10407 {
10408 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10409 {
10410 const std::string &inferior_cwd = current_inferior ()->cwd ();
10411 remote_state *rs = get_remote_state ();
10412
10413 if (!inferior_cwd.empty ())
10414 {
10415 std::string hexpath
10416 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10417 inferior_cwd.size ());
10418
10419 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10420 "QSetWorkingDir:%s", hexpath.c_str ());
10421 }
10422 else
10423 {
10424 /* An empty inferior_cwd means that the user wants us to
10425 reset the remote server's inferior's cwd. */
10426 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10427 "QSetWorkingDir:");
10428 }
10429
10430 putpkt (rs->buf);
10431 getpkt (&rs->buf, 0);
10432 if (packet_ok (rs->buf,
10433 &remote_protocol_packets[PACKET_QSetWorkingDir])
10434 != PACKET_OK)
10435 error (_("\
10436 Remote replied unexpectedly while setting the inferior's working\n\
10437 directory: %s"),
10438 rs->buf.data ());
10439
10440 }
10441 }
10442
10443 /* In the extended protocol we want to be able to do things like
10444 "run" and have them basically work as expected. So we need
10445 a special create_inferior function. We support changing the
10446 executable file and the command line arguments, but not the
10447 environment. */
10448
10449 void
10450 extended_remote_target::create_inferior (const char *exec_file,
10451 const std::string &args,
10452 char **env, int from_tty)
10453 {
10454 int run_worked;
10455 char *stop_reply;
10456 struct remote_state *rs = get_remote_state ();
10457 const char *remote_exec_file = get_remote_exec_file ();
10458
10459 /* If running asynchronously, register the target file descriptor
10460 with the event loop. */
10461 if (target_can_async_p ())
10462 target_async (1);
10463
10464 /* Disable address space randomization if requested (and supported). */
10465 if (supports_disable_randomization ())
10466 extended_remote_disable_randomization (disable_randomization);
10467
10468 /* If startup-with-shell is on, we inform gdbserver to start the
10469 remote inferior using a shell. */
10470 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10471 {
10472 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10473 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10474 putpkt (rs->buf);
10475 getpkt (&rs->buf, 0);
10476 if (strcmp (rs->buf.data (), "OK") != 0)
10477 error (_("\
10478 Remote replied unexpectedly while setting startup-with-shell: %s"),
10479 rs->buf.data ());
10480 }
10481
10482 extended_remote_environment_support ();
10483
10484 extended_remote_set_inferior_cwd ();
10485
10486 /* Now restart the remote server. */
10487 run_worked = extended_remote_run (args) != -1;
10488 if (!run_worked)
10489 {
10490 /* vRun was not supported. Fail if we need it to do what the
10491 user requested. */
10492 if (remote_exec_file[0])
10493 error (_("Remote target does not support \"set remote exec-file\""));
10494 if (!args.empty ())
10495 error (_("Remote target does not support \"set args\" or run ARGS"));
10496
10497 /* Fall back to "R". */
10498 extended_remote_restart ();
10499 }
10500
10501 /* vRun's success return is a stop reply. */
10502 stop_reply = run_worked ? rs->buf.data () : NULL;
10503 add_current_inferior_and_thread (stop_reply);
10504
10505 /* Get updated offsets, if the stub uses qOffsets. */
10506 get_offsets ();
10507 }
10508 \f
10509
10510 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10511 the list of conditions (in agent expression bytecode format), if any, the
10512 target needs to evaluate. The output is placed into the packet buffer
10513 started from BUF and ended at BUF_END. */
10514
10515 static int
10516 remote_add_target_side_condition (struct gdbarch *gdbarch,
10517 struct bp_target_info *bp_tgt, char *buf,
10518 char *buf_end)
10519 {
10520 if (bp_tgt->conditions.empty ())
10521 return 0;
10522
10523 buf += strlen (buf);
10524 xsnprintf (buf, buf_end - buf, "%s", ";");
10525 buf++;
10526
10527 /* Send conditions to the target. */
10528 for (agent_expr *aexpr : bp_tgt->conditions)
10529 {
10530 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10531 buf += strlen (buf);
10532 for (int i = 0; i < aexpr->len; ++i)
10533 buf = pack_hex_byte (buf, aexpr->buf[i]);
10534 *buf = '\0';
10535 }
10536 return 0;
10537 }
10538
10539 static void
10540 remote_add_target_side_commands (struct gdbarch *gdbarch,
10541 struct bp_target_info *bp_tgt, char *buf)
10542 {
10543 if (bp_tgt->tcommands.empty ())
10544 return;
10545
10546 buf += strlen (buf);
10547
10548 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10549 buf += strlen (buf);
10550
10551 /* Concatenate all the agent expressions that are commands into the
10552 cmds parameter. */
10553 for (agent_expr *aexpr : bp_tgt->tcommands)
10554 {
10555 sprintf (buf, "X%x,", aexpr->len);
10556 buf += strlen (buf);
10557 for (int i = 0; i < aexpr->len; ++i)
10558 buf = pack_hex_byte (buf, aexpr->buf[i]);
10559 *buf = '\0';
10560 }
10561 }
10562
10563 /* Insert a breakpoint. On targets that have software breakpoint
10564 support, we ask the remote target to do the work; on targets
10565 which don't, we insert a traditional memory breakpoint. */
10566
10567 int
10568 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10569 struct bp_target_info *bp_tgt)
10570 {
10571 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10572 If it succeeds, then set the support to PACKET_ENABLE. If it
10573 fails, and the user has explicitly requested the Z support then
10574 report an error, otherwise, mark it disabled and go on. */
10575
10576 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10577 {
10578 CORE_ADDR addr = bp_tgt->reqstd_address;
10579 struct remote_state *rs;
10580 char *p, *endbuf;
10581
10582 /* Make sure the remote is pointing at the right process, if
10583 necessary. */
10584 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10585 set_general_process ();
10586
10587 rs = get_remote_state ();
10588 p = rs->buf.data ();
10589 endbuf = p + get_remote_packet_size ();
10590
10591 *(p++) = 'Z';
10592 *(p++) = '0';
10593 *(p++) = ',';
10594 addr = (ULONGEST) remote_address_masked (addr);
10595 p += hexnumstr (p, addr);
10596 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10597
10598 if (supports_evaluation_of_breakpoint_conditions ())
10599 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10600
10601 if (can_run_breakpoint_commands ())
10602 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10603
10604 putpkt (rs->buf);
10605 getpkt (&rs->buf, 0);
10606
10607 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10608 {
10609 case PACKET_ERROR:
10610 return -1;
10611 case PACKET_OK:
10612 return 0;
10613 case PACKET_UNKNOWN:
10614 break;
10615 }
10616 }
10617
10618 /* If this breakpoint has target-side commands but this stub doesn't
10619 support Z0 packets, throw error. */
10620 if (!bp_tgt->tcommands.empty ())
10621 throw_error (NOT_SUPPORTED_ERROR, _("\
10622 Target doesn't support breakpoints that have target side commands."));
10623
10624 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10625 }
10626
10627 int
10628 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10629 struct bp_target_info *bp_tgt,
10630 enum remove_bp_reason reason)
10631 {
10632 CORE_ADDR addr = bp_tgt->placed_address;
10633 struct remote_state *rs = get_remote_state ();
10634
10635 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10636 {
10637 char *p = rs->buf.data ();
10638 char *endbuf = p + get_remote_packet_size ();
10639
10640 /* Make sure the remote is pointing at the right process, if
10641 necessary. */
10642 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10643 set_general_process ();
10644
10645 *(p++) = 'z';
10646 *(p++) = '0';
10647 *(p++) = ',';
10648
10649 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10650 p += hexnumstr (p, addr);
10651 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10652
10653 putpkt (rs->buf);
10654 getpkt (&rs->buf, 0);
10655
10656 return (rs->buf[0] == 'E');
10657 }
10658
10659 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10660 }
10661
10662 static enum Z_packet_type
10663 watchpoint_to_Z_packet (int type)
10664 {
10665 switch (type)
10666 {
10667 case hw_write:
10668 return Z_PACKET_WRITE_WP;
10669 break;
10670 case hw_read:
10671 return Z_PACKET_READ_WP;
10672 break;
10673 case hw_access:
10674 return Z_PACKET_ACCESS_WP;
10675 break;
10676 default:
10677 internal_error (__FILE__, __LINE__,
10678 _("hw_bp_to_z: bad watchpoint type %d"), type);
10679 }
10680 }
10681
10682 int
10683 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10684 enum target_hw_bp_type type, struct expression *cond)
10685 {
10686 struct remote_state *rs = get_remote_state ();
10687 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10688 char *p;
10689 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10690
10691 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10692 return 1;
10693
10694 /* Make sure the remote is pointing at the right process, if
10695 necessary. */
10696 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10697 set_general_process ();
10698
10699 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10700 p = strchr (rs->buf.data (), '\0');
10701 addr = remote_address_masked (addr);
10702 p += hexnumstr (p, (ULONGEST) addr);
10703 xsnprintf (p, endbuf - p, ",%x", len);
10704
10705 putpkt (rs->buf);
10706 getpkt (&rs->buf, 0);
10707
10708 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10709 {
10710 case PACKET_ERROR:
10711 return -1;
10712 case PACKET_UNKNOWN:
10713 return 1;
10714 case PACKET_OK:
10715 return 0;
10716 }
10717 internal_error (__FILE__, __LINE__,
10718 _("remote_insert_watchpoint: reached end of function"));
10719 }
10720
10721 bool
10722 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10723 CORE_ADDR start, int length)
10724 {
10725 CORE_ADDR diff = remote_address_masked (addr - start);
10726
10727 return diff < length;
10728 }
10729
10730
10731 int
10732 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10733 enum target_hw_bp_type type, struct expression *cond)
10734 {
10735 struct remote_state *rs = get_remote_state ();
10736 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10737 char *p;
10738 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10739
10740 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10741 return -1;
10742
10743 /* Make sure the remote is pointing at the right process, if
10744 necessary. */
10745 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10746 set_general_process ();
10747
10748 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10749 p = strchr (rs->buf.data (), '\0');
10750 addr = remote_address_masked (addr);
10751 p += hexnumstr (p, (ULONGEST) addr);
10752 xsnprintf (p, endbuf - p, ",%x", len);
10753 putpkt (rs->buf);
10754 getpkt (&rs->buf, 0);
10755
10756 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10757 {
10758 case PACKET_ERROR:
10759 case PACKET_UNKNOWN:
10760 return -1;
10761 case PACKET_OK:
10762 return 0;
10763 }
10764 internal_error (__FILE__, __LINE__,
10765 _("remote_remove_watchpoint: reached end of function"));
10766 }
10767
10768
10769 static int remote_hw_watchpoint_limit = -1;
10770 static int remote_hw_watchpoint_length_limit = -1;
10771 static int remote_hw_breakpoint_limit = -1;
10772
10773 int
10774 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10775 {
10776 if (remote_hw_watchpoint_length_limit == 0)
10777 return 0;
10778 else if (remote_hw_watchpoint_length_limit < 0)
10779 return 1;
10780 else if (len <= remote_hw_watchpoint_length_limit)
10781 return 1;
10782 else
10783 return 0;
10784 }
10785
10786 int
10787 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10788 {
10789 if (type == bp_hardware_breakpoint)
10790 {
10791 if (remote_hw_breakpoint_limit == 0)
10792 return 0;
10793 else if (remote_hw_breakpoint_limit < 0)
10794 return 1;
10795 else if (cnt <= remote_hw_breakpoint_limit)
10796 return 1;
10797 }
10798 else
10799 {
10800 if (remote_hw_watchpoint_limit == 0)
10801 return 0;
10802 else if (remote_hw_watchpoint_limit < 0)
10803 return 1;
10804 else if (ot)
10805 return -1;
10806 else if (cnt <= remote_hw_watchpoint_limit)
10807 return 1;
10808 }
10809 return -1;
10810 }
10811
10812 /* The to_stopped_by_sw_breakpoint method of target remote. */
10813
10814 bool
10815 remote_target::stopped_by_sw_breakpoint ()
10816 {
10817 struct thread_info *thread = inferior_thread ();
10818
10819 return (thread->priv != NULL
10820 && (get_remote_thread_info (thread)->stop_reason
10821 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10822 }
10823
10824 /* The to_supports_stopped_by_sw_breakpoint method of target
10825 remote. */
10826
10827 bool
10828 remote_target::supports_stopped_by_sw_breakpoint ()
10829 {
10830 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10831 }
10832
10833 /* The to_stopped_by_hw_breakpoint method of target remote. */
10834
10835 bool
10836 remote_target::stopped_by_hw_breakpoint ()
10837 {
10838 struct thread_info *thread = inferior_thread ();
10839
10840 return (thread->priv != NULL
10841 && (get_remote_thread_info (thread)->stop_reason
10842 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10843 }
10844
10845 /* The to_supports_stopped_by_hw_breakpoint method of target
10846 remote. */
10847
10848 bool
10849 remote_target::supports_stopped_by_hw_breakpoint ()
10850 {
10851 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10852 }
10853
10854 bool
10855 remote_target::stopped_by_watchpoint ()
10856 {
10857 struct thread_info *thread = inferior_thread ();
10858
10859 return (thread->priv != NULL
10860 && (get_remote_thread_info (thread)->stop_reason
10861 == TARGET_STOPPED_BY_WATCHPOINT));
10862 }
10863
10864 bool
10865 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10866 {
10867 struct thread_info *thread = inferior_thread ();
10868
10869 if (thread->priv != NULL
10870 && (get_remote_thread_info (thread)->stop_reason
10871 == TARGET_STOPPED_BY_WATCHPOINT))
10872 {
10873 *addr_p = get_remote_thread_info (thread)->watch_data_address;
10874 return true;
10875 }
10876
10877 return false;
10878 }
10879
10880
10881 int
10882 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10883 struct bp_target_info *bp_tgt)
10884 {
10885 CORE_ADDR addr = bp_tgt->reqstd_address;
10886 struct remote_state *rs;
10887 char *p, *endbuf;
10888 char *message;
10889
10890 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10891 return -1;
10892
10893 /* Make sure the remote is pointing at the right process, if
10894 necessary. */
10895 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10896 set_general_process ();
10897
10898 rs = get_remote_state ();
10899 p = rs->buf.data ();
10900 endbuf = p + get_remote_packet_size ();
10901
10902 *(p++) = 'Z';
10903 *(p++) = '1';
10904 *(p++) = ',';
10905
10906 addr = remote_address_masked (addr);
10907 p += hexnumstr (p, (ULONGEST) addr);
10908 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10909
10910 if (supports_evaluation_of_breakpoint_conditions ())
10911 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10912
10913 if (can_run_breakpoint_commands ())
10914 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10915
10916 putpkt (rs->buf);
10917 getpkt (&rs->buf, 0);
10918
10919 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10920 {
10921 case PACKET_ERROR:
10922 if (rs->buf[1] == '.')
10923 {
10924 message = strchr (&rs->buf[2], '.');
10925 if (message)
10926 error (_("Remote failure reply: %s"), message + 1);
10927 }
10928 return -1;
10929 case PACKET_UNKNOWN:
10930 return -1;
10931 case PACKET_OK:
10932 return 0;
10933 }
10934 internal_error (__FILE__, __LINE__,
10935 _("remote_insert_hw_breakpoint: reached end of function"));
10936 }
10937
10938
10939 int
10940 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10941 struct bp_target_info *bp_tgt)
10942 {
10943 CORE_ADDR addr;
10944 struct remote_state *rs = get_remote_state ();
10945 char *p = rs->buf.data ();
10946 char *endbuf = p + get_remote_packet_size ();
10947
10948 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10949 return -1;
10950
10951 /* Make sure the remote is pointing at the right process, if
10952 necessary. */
10953 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10954 set_general_process ();
10955
10956 *(p++) = 'z';
10957 *(p++) = '1';
10958 *(p++) = ',';
10959
10960 addr = remote_address_masked (bp_tgt->placed_address);
10961 p += hexnumstr (p, (ULONGEST) addr);
10962 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10963
10964 putpkt (rs->buf);
10965 getpkt (&rs->buf, 0);
10966
10967 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10968 {
10969 case PACKET_ERROR:
10970 case PACKET_UNKNOWN:
10971 return -1;
10972 case PACKET_OK:
10973 return 0;
10974 }
10975 internal_error (__FILE__, __LINE__,
10976 _("remote_remove_hw_breakpoint: reached end of function"));
10977 }
10978
10979 /* Verify memory using the "qCRC:" request. */
10980
10981 int
10982 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10983 {
10984 struct remote_state *rs = get_remote_state ();
10985 unsigned long host_crc, target_crc;
10986 char *tmp;
10987
10988 /* It doesn't make sense to use qCRC if the remote target is
10989 connected but not running. */
10990 if (target_has_execution ()
10991 && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10992 {
10993 enum packet_result result;
10994
10995 /* Make sure the remote is pointing at the right process. */
10996 set_general_process ();
10997
10998 /* FIXME: assumes lma can fit into long. */
10999 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
11000 (long) lma, (long) size);
11001 putpkt (rs->buf);
11002
11003 /* Be clever; compute the host_crc before waiting for target
11004 reply. */
11005 host_crc = xcrc32 (data, size, 0xffffffff);
11006
11007 getpkt (&rs->buf, 0);
11008
11009 result = packet_ok (rs->buf,
11010 &remote_protocol_packets[PACKET_qCRC]);
11011 if (result == PACKET_ERROR)
11012 return -1;
11013 else if (result == PACKET_OK)
11014 {
11015 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11016 target_crc = target_crc * 16 + fromhex (*tmp);
11017
11018 return (host_crc == target_crc);
11019 }
11020 }
11021
11022 return simple_verify_memory (this, data, lma, size);
11023 }
11024
11025 /* compare-sections command
11026
11027 With no arguments, compares each loadable section in the exec bfd
11028 with the same memory range on the target, and reports mismatches.
11029 Useful for verifying the image on the target against the exec file. */
11030
11031 static void
11032 compare_sections_command (const char *args, int from_tty)
11033 {
11034 asection *s;
11035 const char *sectname;
11036 bfd_size_type size;
11037 bfd_vma lma;
11038 int matched = 0;
11039 int mismatched = 0;
11040 int res;
11041 int read_only = 0;
11042
11043 if (!current_program_space->exec_bfd ())
11044 error (_("command cannot be used without an exec file"));
11045
11046 if (args != NULL && strcmp (args, "-r") == 0)
11047 {
11048 read_only = 1;
11049 args = NULL;
11050 }
11051
11052 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11053 {
11054 if (!(s->flags & SEC_LOAD))
11055 continue; /* Skip non-loadable section. */
11056
11057 if (read_only && (s->flags & SEC_READONLY) == 0)
11058 continue; /* Skip writeable sections */
11059
11060 size = bfd_section_size (s);
11061 if (size == 0)
11062 continue; /* Skip zero-length section. */
11063
11064 sectname = bfd_section_name (s);
11065 if (args && strcmp (args, sectname) != 0)
11066 continue; /* Not the section selected by user. */
11067
11068 matched = 1; /* Do this section. */
11069 lma = s->lma;
11070
11071 gdb::byte_vector sectdata (size);
11072 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11073 sectdata.data (), 0, size);
11074
11075 res = target_verify_memory (sectdata.data (), lma, size);
11076
11077 if (res == -1)
11078 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11079 paddress (target_gdbarch (), lma),
11080 paddress (target_gdbarch (), lma + size));
11081
11082 printf_filtered ("Section %s, range %s -- %s: ", sectname,
11083 paddress (target_gdbarch (), lma),
11084 paddress (target_gdbarch (), lma + size));
11085 if (res)
11086 printf_filtered ("matched.\n");
11087 else
11088 {
11089 printf_filtered ("MIS-MATCHED!\n");
11090 mismatched++;
11091 }
11092 }
11093 if (mismatched > 0)
11094 warning (_("One or more sections of the target image does not match\n\
11095 the loaded file\n"));
11096 if (args && !matched)
11097 printf_filtered (_("No loaded section named '%s'.\n"), args);
11098 }
11099
11100 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11101 into remote target. The number of bytes written to the remote
11102 target is returned, or -1 for error. */
11103
11104 target_xfer_status
11105 remote_target::remote_write_qxfer (const char *object_name,
11106 const char *annex, const gdb_byte *writebuf,
11107 ULONGEST offset, LONGEST len,
11108 ULONGEST *xfered_len,
11109 struct packet_config *packet)
11110 {
11111 int i, buf_len;
11112 ULONGEST n;
11113 struct remote_state *rs = get_remote_state ();
11114 int max_size = get_memory_write_packet_size ();
11115
11116 if (packet_config_support (packet) == PACKET_DISABLE)
11117 return TARGET_XFER_E_IO;
11118
11119 /* Insert header. */
11120 i = snprintf (rs->buf.data (), max_size,
11121 "qXfer:%s:write:%s:%s:",
11122 object_name, annex ? annex : "",
11123 phex_nz (offset, sizeof offset));
11124 max_size -= (i + 1);
11125
11126 /* Escape as much data as fits into rs->buf. */
11127 buf_len = remote_escape_output
11128 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11129
11130 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11131 || getpkt_sane (&rs->buf, 0) < 0
11132 || packet_ok (rs->buf, packet) != PACKET_OK)
11133 return TARGET_XFER_E_IO;
11134
11135 unpack_varlen_hex (rs->buf.data (), &n);
11136
11137 *xfered_len = n;
11138 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11139 }
11140
11141 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11142 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11143 number of bytes read is returned, or 0 for EOF, or -1 for error.
11144 The number of bytes read may be less than LEN without indicating an
11145 EOF. PACKET is checked and updated to indicate whether the remote
11146 target supports this object. */
11147
11148 target_xfer_status
11149 remote_target::remote_read_qxfer (const char *object_name,
11150 const char *annex,
11151 gdb_byte *readbuf, ULONGEST offset,
11152 LONGEST len,
11153 ULONGEST *xfered_len,
11154 struct packet_config *packet)
11155 {
11156 struct remote_state *rs = get_remote_state ();
11157 LONGEST i, n, packet_len;
11158
11159 if (packet_config_support (packet) == PACKET_DISABLE)
11160 return TARGET_XFER_E_IO;
11161
11162 /* Check whether we've cached an end-of-object packet that matches
11163 this request. */
11164 if (rs->finished_object)
11165 {
11166 if (strcmp (object_name, rs->finished_object) == 0
11167 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11168 && offset == rs->finished_offset)
11169 return TARGET_XFER_EOF;
11170
11171
11172 /* Otherwise, we're now reading something different. Discard
11173 the cache. */
11174 xfree (rs->finished_object);
11175 xfree (rs->finished_annex);
11176 rs->finished_object = NULL;
11177 rs->finished_annex = NULL;
11178 }
11179
11180 /* Request only enough to fit in a single packet. The actual data
11181 may not, since we don't know how much of it will need to be escaped;
11182 the target is free to respond with slightly less data. We subtract
11183 five to account for the response type and the protocol frame. */
11184 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11185 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11186 "qXfer:%s:read:%s:%s,%s",
11187 object_name, annex ? annex : "",
11188 phex_nz (offset, sizeof offset),
11189 phex_nz (n, sizeof n));
11190 i = putpkt (rs->buf);
11191 if (i < 0)
11192 return TARGET_XFER_E_IO;
11193
11194 rs->buf[0] = '\0';
11195 packet_len = getpkt_sane (&rs->buf, 0);
11196 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
11197 return TARGET_XFER_E_IO;
11198
11199 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11200 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11201
11202 /* 'm' means there is (or at least might be) more data after this
11203 batch. That does not make sense unless there's at least one byte
11204 of data in this reply. */
11205 if (rs->buf[0] == 'm' && packet_len == 1)
11206 error (_("Remote qXfer reply contained no data."));
11207
11208 /* Got some data. */
11209 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11210 packet_len - 1, readbuf, n);
11211
11212 /* 'l' is an EOF marker, possibly including a final block of data,
11213 or possibly empty. If we have the final block of a non-empty
11214 object, record this fact to bypass a subsequent partial read. */
11215 if (rs->buf[0] == 'l' && offset + i > 0)
11216 {
11217 rs->finished_object = xstrdup (object_name);
11218 rs->finished_annex = xstrdup (annex ? annex : "");
11219 rs->finished_offset = offset + i;
11220 }
11221
11222 if (i == 0)
11223 return TARGET_XFER_EOF;
11224 else
11225 {
11226 *xfered_len = i;
11227 return TARGET_XFER_OK;
11228 }
11229 }
11230
11231 enum target_xfer_status
11232 remote_target::xfer_partial (enum target_object object,
11233 const char *annex, gdb_byte *readbuf,
11234 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11235 ULONGEST *xfered_len)
11236 {
11237 struct remote_state *rs;
11238 int i;
11239 char *p2;
11240 char query_type;
11241 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
11242
11243 set_remote_traceframe ();
11244 set_general_thread (inferior_ptid);
11245
11246 rs = get_remote_state ();
11247
11248 /* Handle memory using the standard memory routines. */
11249 if (object == TARGET_OBJECT_MEMORY)
11250 {
11251 /* If the remote target is connected but not running, we should
11252 pass this request down to a lower stratum (e.g. the executable
11253 file). */
11254 if (!target_has_execution ())
11255 return TARGET_XFER_EOF;
11256
11257 if (writebuf != NULL)
11258 return remote_write_bytes (offset, writebuf, len, unit_size,
11259 xfered_len);
11260 else
11261 return remote_read_bytes (offset, readbuf, len, unit_size,
11262 xfered_len);
11263 }
11264
11265 /* Handle extra signal info using qxfer packets. */
11266 if (object == TARGET_OBJECT_SIGNAL_INFO)
11267 {
11268 if (readbuf)
11269 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11270 xfered_len, &remote_protocol_packets
11271 [PACKET_qXfer_siginfo_read]);
11272 else
11273 return remote_write_qxfer ("siginfo", annex,
11274 writebuf, offset, len, xfered_len,
11275 &remote_protocol_packets
11276 [PACKET_qXfer_siginfo_write]);
11277 }
11278
11279 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11280 {
11281 if (readbuf)
11282 return remote_read_qxfer ("statictrace", annex,
11283 readbuf, offset, len, xfered_len,
11284 &remote_protocol_packets
11285 [PACKET_qXfer_statictrace_read]);
11286 else
11287 return TARGET_XFER_E_IO;
11288 }
11289
11290 /* Only handle flash writes. */
11291 if (writebuf != NULL)
11292 {
11293 switch (object)
11294 {
11295 case TARGET_OBJECT_FLASH:
11296 return remote_flash_write (offset, len, xfered_len,
11297 writebuf);
11298
11299 default:
11300 return TARGET_XFER_E_IO;
11301 }
11302 }
11303
11304 /* Map pre-existing objects onto letters. DO NOT do this for new
11305 objects!!! Instead specify new query packets. */
11306 switch (object)
11307 {
11308 case TARGET_OBJECT_AVR:
11309 query_type = 'R';
11310 break;
11311
11312 case TARGET_OBJECT_AUXV:
11313 gdb_assert (annex == NULL);
11314 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
11315 xfered_len,
11316 &remote_protocol_packets[PACKET_qXfer_auxv]);
11317
11318 case TARGET_OBJECT_AVAILABLE_FEATURES:
11319 return remote_read_qxfer
11320 ("features", annex, readbuf, offset, len, xfered_len,
11321 &remote_protocol_packets[PACKET_qXfer_features]);
11322
11323 case TARGET_OBJECT_LIBRARIES:
11324 return remote_read_qxfer
11325 ("libraries", annex, readbuf, offset, len, xfered_len,
11326 &remote_protocol_packets[PACKET_qXfer_libraries]);
11327
11328 case TARGET_OBJECT_LIBRARIES_SVR4:
11329 return remote_read_qxfer
11330 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11331 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
11332
11333 case TARGET_OBJECT_MEMORY_MAP:
11334 gdb_assert (annex == NULL);
11335 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
11336 xfered_len,
11337 &remote_protocol_packets[PACKET_qXfer_memory_map]);
11338
11339 case TARGET_OBJECT_OSDATA:
11340 /* Should only get here if we're connected. */
11341 gdb_assert (rs->remote_desc);
11342 return remote_read_qxfer
11343 ("osdata", annex, readbuf, offset, len, xfered_len,
11344 &remote_protocol_packets[PACKET_qXfer_osdata]);
11345
11346 case TARGET_OBJECT_THREADS:
11347 gdb_assert (annex == NULL);
11348 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
11349 xfered_len,
11350 &remote_protocol_packets[PACKET_qXfer_threads]);
11351
11352 case TARGET_OBJECT_TRACEFRAME_INFO:
11353 gdb_assert (annex == NULL);
11354 return remote_read_qxfer
11355 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11356 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
11357
11358 case TARGET_OBJECT_FDPIC:
11359 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
11360 xfered_len,
11361 &remote_protocol_packets[PACKET_qXfer_fdpic]);
11362
11363 case TARGET_OBJECT_OPENVMS_UIB:
11364 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
11365 xfered_len,
11366 &remote_protocol_packets[PACKET_qXfer_uib]);
11367
11368 case TARGET_OBJECT_BTRACE:
11369 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
11370 xfered_len,
11371 &remote_protocol_packets[PACKET_qXfer_btrace]);
11372
11373 case TARGET_OBJECT_BTRACE_CONF:
11374 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
11375 len, xfered_len,
11376 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11377
11378 case TARGET_OBJECT_EXEC_FILE:
11379 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
11380 len, xfered_len,
11381 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11382
11383 default:
11384 return TARGET_XFER_E_IO;
11385 }
11386
11387 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11388 large enough let the caller deal with it. */
11389 if (len < get_remote_packet_size ())
11390 return TARGET_XFER_E_IO;
11391 len = get_remote_packet_size ();
11392
11393 /* Except for querying the minimum buffer size, target must be open. */
11394 if (!rs->remote_desc)
11395 error (_("remote query is only available after target open"));
11396
11397 gdb_assert (annex != NULL);
11398 gdb_assert (readbuf != NULL);
11399
11400 p2 = rs->buf.data ();
11401 *p2++ = 'q';
11402 *p2++ = query_type;
11403
11404 /* We used one buffer char for the remote protocol q command and
11405 another for the query type. As the remote protocol encapsulation
11406 uses 4 chars plus one extra in case we are debugging
11407 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11408 string. */
11409 i = 0;
11410 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11411 {
11412 /* Bad caller may have sent forbidden characters. */
11413 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11414 *p2++ = annex[i];
11415 i++;
11416 }
11417 *p2 = '\0';
11418 gdb_assert (annex[i] == '\0');
11419
11420 i = putpkt (rs->buf);
11421 if (i < 0)
11422 return TARGET_XFER_E_IO;
11423
11424 getpkt (&rs->buf, 0);
11425 strcpy ((char *) readbuf, rs->buf.data ());
11426
11427 *xfered_len = strlen ((char *) readbuf);
11428 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11429 }
11430
11431 /* Implementation of to_get_memory_xfer_limit. */
11432
11433 ULONGEST
11434 remote_target::get_memory_xfer_limit ()
11435 {
11436 return get_memory_write_packet_size ();
11437 }
11438
11439 int
11440 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11441 const gdb_byte *pattern, ULONGEST pattern_len,
11442 CORE_ADDR *found_addrp)
11443 {
11444 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11445 struct remote_state *rs = get_remote_state ();
11446 int max_size = get_memory_write_packet_size ();
11447 struct packet_config *packet =
11448 &remote_protocol_packets[PACKET_qSearch_memory];
11449 /* Number of packet bytes used to encode the pattern;
11450 this could be more than PATTERN_LEN due to escape characters. */
11451 int escaped_pattern_len;
11452 /* Amount of pattern that was encodable in the packet. */
11453 int used_pattern_len;
11454 int i;
11455 int found;
11456 ULONGEST found_addr;
11457
11458 auto read_memory = [=] (CORE_ADDR addr, gdb_byte *result, size_t len)
11459 {
11460 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11461 == len);
11462 };
11463
11464 /* Don't go to the target if we don't have to. This is done before
11465 checking packet_config_support to avoid the possibility that a
11466 success for this edge case means the facility works in
11467 general. */
11468 if (pattern_len > search_space_len)
11469 return 0;
11470 if (pattern_len == 0)
11471 {
11472 *found_addrp = start_addr;
11473 return 1;
11474 }
11475
11476 /* If we already know the packet isn't supported, fall back to the simple
11477 way of searching memory. */
11478
11479 if (packet_config_support (packet) == PACKET_DISABLE)
11480 {
11481 /* Target doesn't provided special support, fall back and use the
11482 standard support (copy memory and do the search here). */
11483 return simple_search_memory (read_memory, start_addr, search_space_len,
11484 pattern, pattern_len, found_addrp);
11485 }
11486
11487 /* Make sure the remote is pointing at the right process. */
11488 set_general_process ();
11489
11490 /* Insert header. */
11491 i = snprintf (rs->buf.data (), max_size,
11492 "qSearch:memory:%s;%s;",
11493 phex_nz (start_addr, addr_size),
11494 phex_nz (search_space_len, sizeof (search_space_len)));
11495 max_size -= (i + 1);
11496
11497 /* Escape as much data as fits into rs->buf. */
11498 escaped_pattern_len =
11499 remote_escape_output (pattern, pattern_len, 1,
11500 (gdb_byte *) rs->buf.data () + i,
11501 &used_pattern_len, max_size);
11502
11503 /* Bail if the pattern is too large. */
11504 if (used_pattern_len != pattern_len)
11505 error (_("Pattern is too large to transmit to remote target."));
11506
11507 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11508 || getpkt_sane (&rs->buf, 0) < 0
11509 || packet_ok (rs->buf, packet) != PACKET_OK)
11510 {
11511 /* The request may not have worked because the command is not
11512 supported. If so, fall back to the simple way. */
11513 if (packet_config_support (packet) == PACKET_DISABLE)
11514 {
11515 return simple_search_memory (read_memory, start_addr, search_space_len,
11516 pattern, pattern_len, found_addrp);
11517 }
11518 return -1;
11519 }
11520
11521 if (rs->buf[0] == '0')
11522 found = 0;
11523 else if (rs->buf[0] == '1')
11524 {
11525 found = 1;
11526 if (rs->buf[1] != ',')
11527 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11528 unpack_varlen_hex (&rs->buf[2], &found_addr);
11529 *found_addrp = found_addr;
11530 }
11531 else
11532 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11533
11534 return found;
11535 }
11536
11537 void
11538 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11539 {
11540 struct remote_state *rs = get_remote_state ();
11541 char *p = rs->buf.data ();
11542
11543 if (!rs->remote_desc)
11544 error (_("remote rcmd is only available after target open"));
11545
11546 /* Send a NULL command across as an empty command. */
11547 if (command == NULL)
11548 command = "";
11549
11550 /* The query prefix. */
11551 strcpy (rs->buf.data (), "qRcmd,");
11552 p = strchr (rs->buf.data (), '\0');
11553
11554 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11555 > get_remote_packet_size ())
11556 error (_("\"monitor\" command ``%s'' is too long."), command);
11557
11558 /* Encode the actual command. */
11559 bin2hex ((const gdb_byte *) command, p, strlen (command));
11560
11561 if (putpkt (rs->buf) < 0)
11562 error (_("Communication problem with target."));
11563
11564 /* get/display the response */
11565 while (1)
11566 {
11567 char *buf;
11568
11569 /* XXX - see also remote_get_noisy_reply(). */
11570 QUIT; /* Allow user to bail out with ^C. */
11571 rs->buf[0] = '\0';
11572 if (getpkt_sane (&rs->buf, 0) == -1)
11573 {
11574 /* Timeout. Continue to (try to) read responses.
11575 This is better than stopping with an error, assuming the stub
11576 is still executing the (long) monitor command.
11577 If needed, the user can interrupt gdb using C-c, obtaining
11578 an effect similar to stop on timeout. */
11579 continue;
11580 }
11581 buf = rs->buf.data ();
11582 if (buf[0] == '\0')
11583 error (_("Target does not support this command."));
11584 if (buf[0] == 'O' && buf[1] != 'K')
11585 {
11586 remote_console_output (buf + 1); /* 'O' message from stub. */
11587 continue;
11588 }
11589 if (strcmp (buf, "OK") == 0)
11590 break;
11591 if (strlen (buf) == 3 && buf[0] == 'E'
11592 && isdigit (buf[1]) && isdigit (buf[2]))
11593 {
11594 error (_("Protocol error with Rcmd"));
11595 }
11596 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11597 {
11598 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11599
11600 fputc_unfiltered (c, outbuf);
11601 }
11602 break;
11603 }
11604 }
11605
11606 std::vector<mem_region>
11607 remote_target::memory_map ()
11608 {
11609 std::vector<mem_region> result;
11610 gdb::optional<gdb::char_vector> text
11611 = target_read_stralloc (current_inferior ()->top_target (),
11612 TARGET_OBJECT_MEMORY_MAP, NULL);
11613
11614 if (text)
11615 result = parse_memory_map (text->data ());
11616
11617 return result;
11618 }
11619
11620 /* Set of callbacks used to implement the 'maint packet' command. */
11621
11622 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
11623 {
11624 /* Called before the packet is sent. BUF is the packet content before
11625 the protocol specific prefix, suffix, and escaping is added. */
11626
11627 void sending (gdb::array_view<const char> &buf) override
11628 {
11629 puts_filtered ("sending: ");
11630 print_packet (buf);
11631 puts_filtered ("\n");
11632 }
11633
11634 /* Called with BUF, the reply from the remote target. */
11635
11636 void received (gdb::array_view<const char> &buf) override
11637 {
11638 puts_filtered ("received: \"");
11639 print_packet (buf);
11640 puts_filtered ("\"\n");
11641 }
11642
11643 private:
11644
11645 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11646 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11647
11648 static void
11649 print_packet (gdb::array_view<const char> &buf)
11650 {
11651 string_file stb;
11652
11653 for (int i = 0; i < buf.size (); ++i)
11654 {
11655 gdb_byte c = buf[i];
11656 if (isprint (c))
11657 fputc_unfiltered (c, &stb);
11658 else
11659 fprintf_unfiltered (&stb, "\\x%02x", (unsigned char) c);
11660 }
11661
11662 puts_filtered (stb.string ().c_str ());
11663 }
11664 };
11665
11666 /* See remote.h. */
11667
11668 void
11669 send_remote_packet (gdb::array_view<const char> &buf,
11670 send_remote_packet_callbacks *callbacks)
11671 {
11672 if (buf.size () == 0 || buf.data ()[0] == '\0')
11673 error (_("a remote packet must not be empty"));
11674
11675 remote_target *remote = get_current_remote_target ();
11676 if (remote == nullptr)
11677 error (_("packets can only be sent to a remote target"));
11678
11679 callbacks->sending (buf);
11680
11681 remote->putpkt_binary (buf.data (), buf.size ());
11682 remote_state *rs = remote->get_remote_state ();
11683 int bytes = remote->getpkt_sane (&rs->buf, 0);
11684
11685 if (bytes < 0)
11686 error (_("error while fetching packet from remote target"));
11687
11688 gdb::array_view<const char> view (&rs->buf[0], bytes);
11689 callbacks->received (view);
11690 }
11691
11692 /* Entry point for the 'maint packet' command. */
11693
11694 static void
11695 cli_packet_command (const char *args, int from_tty)
11696 {
11697 cli_packet_command_callbacks cb;
11698 gdb::array_view<const char> view
11699 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11700 send_remote_packet (view, &cb);
11701 }
11702
11703 #if 0
11704 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11705
11706 static void display_thread_info (struct gdb_ext_thread_info *info);
11707
11708 static void threadset_test_cmd (char *cmd, int tty);
11709
11710 static void threadalive_test (char *cmd, int tty);
11711
11712 static void threadlist_test_cmd (char *cmd, int tty);
11713
11714 int get_and_display_threadinfo (threadref *ref);
11715
11716 static void threadinfo_test_cmd (char *cmd, int tty);
11717
11718 static int thread_display_step (threadref *ref, void *context);
11719
11720 static void threadlist_update_test_cmd (char *cmd, int tty);
11721
11722 static void init_remote_threadtests (void);
11723
11724 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11725
11726 static void
11727 threadset_test_cmd (const char *cmd, int tty)
11728 {
11729 int sample_thread = SAMPLE_THREAD;
11730
11731 printf_filtered (_("Remote threadset test\n"));
11732 set_general_thread (sample_thread);
11733 }
11734
11735
11736 static void
11737 threadalive_test (const char *cmd, int tty)
11738 {
11739 int sample_thread = SAMPLE_THREAD;
11740 int pid = inferior_ptid.pid ();
11741 ptid_t ptid = ptid_t (pid, sample_thread, 0);
11742
11743 if (remote_thread_alive (ptid))
11744 printf_filtered ("PASS: Thread alive test\n");
11745 else
11746 printf_filtered ("FAIL: Thread alive test\n");
11747 }
11748
11749 void output_threadid (char *title, threadref *ref);
11750
11751 void
11752 output_threadid (char *title, threadref *ref)
11753 {
11754 char hexid[20];
11755
11756 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
11757 hexid[16] = 0;
11758 printf_filtered ("%s %s\n", title, (&hexid[0]));
11759 }
11760
11761 static void
11762 threadlist_test_cmd (const char *cmd, int tty)
11763 {
11764 int startflag = 1;
11765 threadref nextthread;
11766 int done, result_count;
11767 threadref threadlist[3];
11768
11769 printf_filtered ("Remote Threadlist test\n");
11770 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11771 &result_count, &threadlist[0]))
11772 printf_filtered ("FAIL: threadlist test\n");
11773 else
11774 {
11775 threadref *scan = threadlist;
11776 threadref *limit = scan + result_count;
11777
11778 while (scan < limit)
11779 output_threadid (" thread ", scan++);
11780 }
11781 }
11782
11783 void
11784 display_thread_info (struct gdb_ext_thread_info *info)
11785 {
11786 output_threadid ("Threadid: ", &info->threadid);
11787 printf_filtered ("Name: %s\n ", info->shortname);
11788 printf_filtered ("State: %s\n", info->display);
11789 printf_filtered ("other: %s\n\n", info->more_display);
11790 }
11791
11792 int
11793 get_and_display_threadinfo (threadref *ref)
11794 {
11795 int result;
11796 int set;
11797 struct gdb_ext_thread_info threadinfo;
11798
11799 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11800 | TAG_MOREDISPLAY | TAG_DISPLAY;
11801 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11802 display_thread_info (&threadinfo);
11803 return result;
11804 }
11805
11806 static void
11807 threadinfo_test_cmd (const char *cmd, int tty)
11808 {
11809 int athread = SAMPLE_THREAD;
11810 threadref thread;
11811 int set;
11812
11813 int_to_threadref (&thread, athread);
11814 printf_filtered ("Remote Threadinfo test\n");
11815 if (!get_and_display_threadinfo (&thread))
11816 printf_filtered ("FAIL cannot get thread info\n");
11817 }
11818
11819 static int
11820 thread_display_step (threadref *ref, void *context)
11821 {
11822 /* output_threadid(" threadstep ",ref); *//* simple test */
11823 return get_and_display_threadinfo (ref);
11824 }
11825
11826 static void
11827 threadlist_update_test_cmd (const char *cmd, int tty)
11828 {
11829 printf_filtered ("Remote Threadlist update test\n");
11830 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11831 }
11832
11833 static void
11834 init_remote_threadtests (void)
11835 {
11836 add_com ("tlist", class_obscure, threadlist_test_cmd,
11837 _("Fetch and print the remote list of "
11838 "thread identifiers, one pkt only."));
11839 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11840 _("Fetch and display info about one thread."));
11841 add_com ("tset", class_obscure, threadset_test_cmd,
11842 _("Test setting to a different thread."));
11843 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11844 _("Iterate through updating all remote thread info."));
11845 add_com ("talive", class_obscure, threadalive_test,
11846 _("Remote thread alive test."));
11847 }
11848
11849 #endif /* 0 */
11850
11851 /* Convert a thread ID to a string. */
11852
11853 std::string
11854 remote_target::pid_to_str (ptid_t ptid)
11855 {
11856 struct remote_state *rs = get_remote_state ();
11857
11858 if (ptid == null_ptid)
11859 return normal_pid_to_str (ptid);
11860 else if (ptid.is_pid ())
11861 {
11862 /* Printing an inferior target id. */
11863
11864 /* When multi-process extensions are off, there's no way in the
11865 remote protocol to know the remote process id, if there's any
11866 at all. There's one exception --- when we're connected with
11867 target extended-remote, and we manually attached to a process
11868 with "attach PID". We don't record anywhere a flag that
11869 allows us to distinguish that case from the case of
11870 connecting with extended-remote and the stub already being
11871 attached to a process, and reporting yes to qAttached, hence
11872 no smart special casing here. */
11873 if (!remote_multi_process_p (rs))
11874 return "Remote target";
11875
11876 return normal_pid_to_str (ptid);
11877 }
11878 else
11879 {
11880 if (magic_null_ptid == ptid)
11881 return "Thread <main>";
11882 else if (remote_multi_process_p (rs))
11883 if (ptid.lwp () == 0)
11884 return normal_pid_to_str (ptid);
11885 else
11886 return string_printf ("Thread %d.%ld",
11887 ptid.pid (), ptid.lwp ());
11888 else
11889 return string_printf ("Thread %ld", ptid.lwp ());
11890 }
11891 }
11892
11893 /* Get the address of the thread local variable in OBJFILE which is
11894 stored at OFFSET within the thread local storage for thread PTID. */
11895
11896 CORE_ADDR
11897 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11898 CORE_ADDR offset)
11899 {
11900 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11901 {
11902 struct remote_state *rs = get_remote_state ();
11903 char *p = rs->buf.data ();
11904 char *endp = p + get_remote_packet_size ();
11905 enum packet_result result;
11906
11907 strcpy (p, "qGetTLSAddr:");
11908 p += strlen (p);
11909 p = write_ptid (p, endp, ptid);
11910 *p++ = ',';
11911 p += hexnumstr (p, offset);
11912 *p++ = ',';
11913 p += hexnumstr (p, lm);
11914 *p++ = '\0';
11915
11916 putpkt (rs->buf);
11917 getpkt (&rs->buf, 0);
11918 result = packet_ok (rs->buf,
11919 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11920 if (result == PACKET_OK)
11921 {
11922 ULONGEST addr;
11923
11924 unpack_varlen_hex (rs->buf.data (), &addr);
11925 return addr;
11926 }
11927 else if (result == PACKET_UNKNOWN)
11928 throw_error (TLS_GENERIC_ERROR,
11929 _("Remote target doesn't support qGetTLSAddr packet"));
11930 else
11931 throw_error (TLS_GENERIC_ERROR,
11932 _("Remote target failed to process qGetTLSAddr request"));
11933 }
11934 else
11935 throw_error (TLS_GENERIC_ERROR,
11936 _("TLS not supported or disabled on this target"));
11937 /* Not reached. */
11938 return 0;
11939 }
11940
11941 /* Provide thread local base, i.e. Thread Information Block address.
11942 Returns 1 if ptid is found and thread_local_base is non zero. */
11943
11944 bool
11945 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11946 {
11947 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11948 {
11949 struct remote_state *rs = get_remote_state ();
11950 char *p = rs->buf.data ();
11951 char *endp = p + get_remote_packet_size ();
11952 enum packet_result result;
11953
11954 strcpy (p, "qGetTIBAddr:");
11955 p += strlen (p);
11956 p = write_ptid (p, endp, ptid);
11957 *p++ = '\0';
11958
11959 putpkt (rs->buf);
11960 getpkt (&rs->buf, 0);
11961 result = packet_ok (rs->buf,
11962 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11963 if (result == PACKET_OK)
11964 {
11965 ULONGEST val;
11966 unpack_varlen_hex (rs->buf.data (), &val);
11967 if (addr)
11968 *addr = (CORE_ADDR) val;
11969 return true;
11970 }
11971 else if (result == PACKET_UNKNOWN)
11972 error (_("Remote target doesn't support qGetTIBAddr packet"));
11973 else
11974 error (_("Remote target failed to process qGetTIBAddr request"));
11975 }
11976 else
11977 error (_("qGetTIBAddr not supported or disabled on this target"));
11978 /* Not reached. */
11979 return false;
11980 }
11981
11982 /* Support for inferring a target description based on the current
11983 architecture and the size of a 'g' packet. While the 'g' packet
11984 can have any size (since optional registers can be left off the
11985 end), some sizes are easily recognizable given knowledge of the
11986 approximate architecture. */
11987
11988 struct remote_g_packet_guess
11989 {
11990 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
11991 : bytes (bytes_),
11992 tdesc (tdesc_)
11993 {
11994 }
11995
11996 int bytes;
11997 const struct target_desc *tdesc;
11998 };
11999
12000 struct remote_g_packet_data : public allocate_on_obstack
12001 {
12002 std::vector<remote_g_packet_guess> guesses;
12003 };
12004
12005 static struct gdbarch_data *remote_g_packet_data_handle;
12006
12007 static void *
12008 remote_g_packet_data_init (struct obstack *obstack)
12009 {
12010 return new (obstack) remote_g_packet_data;
12011 }
12012
12013 void
12014 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12015 const struct target_desc *tdesc)
12016 {
12017 struct remote_g_packet_data *data
12018 = ((struct remote_g_packet_data *)
12019 gdbarch_data (gdbarch, remote_g_packet_data_handle));
12020
12021 gdb_assert (tdesc != NULL);
12022
12023 for (const remote_g_packet_guess &guess : data->guesses)
12024 if (guess.bytes == bytes)
12025 internal_error (__FILE__, __LINE__,
12026 _("Duplicate g packet description added for size %d"),
12027 bytes);
12028
12029 data->guesses.emplace_back (bytes, tdesc);
12030 }
12031
12032 /* Return true if remote_read_description would do anything on this target
12033 and architecture, false otherwise. */
12034
12035 static bool
12036 remote_read_description_p (struct target_ops *target)
12037 {
12038 struct remote_g_packet_data *data
12039 = ((struct remote_g_packet_data *)
12040 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
12041
12042 return !data->guesses.empty ();
12043 }
12044
12045 const struct target_desc *
12046 remote_target::read_description ()
12047 {
12048 struct remote_g_packet_data *data
12049 = ((struct remote_g_packet_data *)
12050 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
12051
12052 /* Do not try this during initial connection, when we do not know
12053 whether there is a running but stopped thread. */
12054 if (!target_has_execution () || inferior_ptid == null_ptid)
12055 return beneath ()->read_description ();
12056
12057 if (!data->guesses.empty ())
12058 {
12059 int bytes = send_g_packet ();
12060
12061 for (const remote_g_packet_guess &guess : data->guesses)
12062 if (guess.bytes == bytes)
12063 return guess.tdesc;
12064
12065 /* We discard the g packet. A minor optimization would be to
12066 hold on to it, and fill the register cache once we have selected
12067 an architecture, but it's too tricky to do safely. */
12068 }
12069
12070 return beneath ()->read_description ();
12071 }
12072
12073 /* Remote file transfer support. This is host-initiated I/O, not
12074 target-initiated; for target-initiated, see remote-fileio.c. */
12075
12076 /* If *LEFT is at least the length of STRING, copy STRING to
12077 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12078 decrease *LEFT. Otherwise raise an error. */
12079
12080 static void
12081 remote_buffer_add_string (char **buffer, int *left, const char *string)
12082 {
12083 int len = strlen (string);
12084
12085 if (len > *left)
12086 error (_("Packet too long for target."));
12087
12088 memcpy (*buffer, string, len);
12089 *buffer += len;
12090 *left -= len;
12091
12092 /* NUL-terminate the buffer as a convenience, if there is
12093 room. */
12094 if (*left)
12095 **buffer = '\0';
12096 }
12097
12098 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12099 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12100 decrease *LEFT. Otherwise raise an error. */
12101
12102 static void
12103 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12104 int len)
12105 {
12106 if (2 * len > *left)
12107 error (_("Packet too long for target."));
12108
12109 bin2hex (bytes, *buffer, len);
12110 *buffer += 2 * len;
12111 *left -= 2 * len;
12112
12113 /* NUL-terminate the buffer as a convenience, if there is
12114 room. */
12115 if (*left)
12116 **buffer = '\0';
12117 }
12118
12119 /* If *LEFT is large enough, convert VALUE to hex and add it to
12120 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12121 decrease *LEFT. Otherwise raise an error. */
12122
12123 static void
12124 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12125 {
12126 int len = hexnumlen (value);
12127
12128 if (len > *left)
12129 error (_("Packet too long for target."));
12130
12131 hexnumstr (*buffer, value);
12132 *buffer += len;
12133 *left -= len;
12134
12135 /* NUL-terminate the buffer as a convenience, if there is
12136 room. */
12137 if (*left)
12138 **buffer = '\0';
12139 }
12140
12141 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12142 value, *REMOTE_ERRNO to the remote error number or zero if none
12143 was included, and *ATTACHMENT to point to the start of the annex
12144 if any. The length of the packet isn't needed here; there may
12145 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12146
12147 Return 0 if the packet could be parsed, -1 if it could not. If
12148 -1 is returned, the other variables may not be initialized. */
12149
12150 static int
12151 remote_hostio_parse_result (const char *buffer, int *retcode,
12152 int *remote_errno, const char **attachment)
12153 {
12154 char *p, *p2;
12155
12156 *remote_errno = 0;
12157 *attachment = NULL;
12158
12159 if (buffer[0] != 'F')
12160 return -1;
12161
12162 errno = 0;
12163 *retcode = strtol (&buffer[1], &p, 16);
12164 if (errno != 0 || p == &buffer[1])
12165 return -1;
12166
12167 /* Check for ",errno". */
12168 if (*p == ',')
12169 {
12170 errno = 0;
12171 *remote_errno = strtol (p + 1, &p2, 16);
12172 if (errno != 0 || p + 1 == p2)
12173 return -1;
12174 p = p2;
12175 }
12176
12177 /* Check for ";attachment". If there is no attachment, the
12178 packet should end here. */
12179 if (*p == ';')
12180 {
12181 *attachment = p + 1;
12182 return 0;
12183 }
12184 else if (*p == '\0')
12185 return 0;
12186 else
12187 return -1;
12188 }
12189
12190 /* Send a prepared I/O packet to the target and read its response.
12191 The prepared packet is in the global RS->BUF before this function
12192 is called, and the answer is there when we return.
12193
12194 COMMAND_BYTES is the length of the request to send, which may include
12195 binary data. WHICH_PACKET is the packet configuration to check
12196 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12197 is set to the error number and -1 is returned. Otherwise the value
12198 returned by the function is returned.
12199
12200 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12201 attachment is expected; an error will be reported if there's a
12202 mismatch. If one is found, *ATTACHMENT will be set to point into
12203 the packet buffer and *ATTACHMENT_LEN will be set to the
12204 attachment's length. */
12205
12206 int
12207 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12208 int *remote_errno, const char **attachment,
12209 int *attachment_len)
12210 {
12211 struct remote_state *rs = get_remote_state ();
12212 int ret, bytes_read;
12213 const char *attachment_tmp;
12214
12215 if (packet_support (which_packet) == PACKET_DISABLE)
12216 {
12217 *remote_errno = FILEIO_ENOSYS;
12218 return -1;
12219 }
12220
12221 putpkt_binary (rs->buf.data (), command_bytes);
12222 bytes_read = getpkt_sane (&rs->buf, 0);
12223
12224 /* If it timed out, something is wrong. Don't try to parse the
12225 buffer. */
12226 if (bytes_read < 0)
12227 {
12228 *remote_errno = FILEIO_EINVAL;
12229 return -1;
12230 }
12231
12232 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
12233 {
12234 case PACKET_ERROR:
12235 *remote_errno = FILEIO_EINVAL;
12236 return -1;
12237 case PACKET_UNKNOWN:
12238 *remote_errno = FILEIO_ENOSYS;
12239 return -1;
12240 case PACKET_OK:
12241 break;
12242 }
12243
12244 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12245 &attachment_tmp))
12246 {
12247 *remote_errno = FILEIO_EINVAL;
12248 return -1;
12249 }
12250
12251 /* Make sure we saw an attachment if and only if we expected one. */
12252 if ((attachment_tmp == NULL && attachment != NULL)
12253 || (attachment_tmp != NULL && attachment == NULL))
12254 {
12255 *remote_errno = FILEIO_EINVAL;
12256 return -1;
12257 }
12258
12259 /* If an attachment was found, it must point into the packet buffer;
12260 work out how many bytes there were. */
12261 if (attachment_tmp != NULL)
12262 {
12263 *attachment = attachment_tmp;
12264 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12265 }
12266
12267 return ret;
12268 }
12269
12270 /* See declaration.h. */
12271
12272 void
12273 readahead_cache::invalidate ()
12274 {
12275 this->fd = -1;
12276 }
12277
12278 /* See declaration.h. */
12279
12280 void
12281 readahead_cache::invalidate_fd (int fd)
12282 {
12283 if (this->fd == fd)
12284 this->fd = -1;
12285 }
12286
12287 /* Set the filesystem remote_hostio functions that take FILENAME
12288 arguments will use. Return 0 on success, or -1 if an error
12289 occurs (and set *REMOTE_ERRNO). */
12290
12291 int
12292 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12293 int *remote_errno)
12294 {
12295 struct remote_state *rs = get_remote_state ();
12296 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12297 char *p = rs->buf.data ();
12298 int left = get_remote_packet_size () - 1;
12299 char arg[9];
12300 int ret;
12301
12302 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12303 return 0;
12304
12305 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12306 return 0;
12307
12308 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12309
12310 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12311 remote_buffer_add_string (&p, &left, arg);
12312
12313 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12314 remote_errno, NULL, NULL);
12315
12316 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12317 return 0;
12318
12319 if (ret == 0)
12320 rs->fs_pid = required_pid;
12321
12322 return ret;
12323 }
12324
12325 /* Implementation of to_fileio_open. */
12326
12327 int
12328 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12329 int flags, int mode, int warn_if_slow,
12330 int *remote_errno)
12331 {
12332 struct remote_state *rs = get_remote_state ();
12333 char *p = rs->buf.data ();
12334 int left = get_remote_packet_size () - 1;
12335
12336 if (warn_if_slow)
12337 {
12338 static int warning_issued = 0;
12339
12340 printf_unfiltered (_("Reading %s from remote target...\n"),
12341 filename);
12342
12343 if (!warning_issued)
12344 {
12345 warning (_("File transfers from remote targets can be slow."
12346 " Use \"set sysroot\" to access files locally"
12347 " instead."));
12348 warning_issued = 1;
12349 }
12350 }
12351
12352 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12353 return -1;
12354
12355 remote_buffer_add_string (&p, &left, "vFile:open:");
12356
12357 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12358 strlen (filename));
12359 remote_buffer_add_string (&p, &left, ",");
12360
12361 remote_buffer_add_int (&p, &left, flags);
12362 remote_buffer_add_string (&p, &left, ",");
12363
12364 remote_buffer_add_int (&p, &left, mode);
12365
12366 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12367 remote_errno, NULL, NULL);
12368 }
12369
12370 int
12371 remote_target::fileio_open (struct inferior *inf, const char *filename,
12372 int flags, int mode, int warn_if_slow,
12373 int *remote_errno)
12374 {
12375 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12376 remote_errno);
12377 }
12378
12379 /* Implementation of to_fileio_pwrite. */
12380
12381 int
12382 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12383 ULONGEST offset, int *remote_errno)
12384 {
12385 struct remote_state *rs = get_remote_state ();
12386 char *p = rs->buf.data ();
12387 int left = get_remote_packet_size ();
12388 int out_len;
12389
12390 rs->readahead_cache.invalidate_fd (fd);
12391
12392 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12393
12394 remote_buffer_add_int (&p, &left, fd);
12395 remote_buffer_add_string (&p, &left, ",");
12396
12397 remote_buffer_add_int (&p, &left, offset);
12398 remote_buffer_add_string (&p, &left, ",");
12399
12400 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12401 (get_remote_packet_size ()
12402 - (p - rs->buf.data ())));
12403
12404 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12405 remote_errno, NULL, NULL);
12406 }
12407
12408 int
12409 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12410 ULONGEST offset, int *remote_errno)
12411 {
12412 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12413 }
12414
12415 /* Helper for the implementation of to_fileio_pread. Read the file
12416 from the remote side with vFile:pread. */
12417
12418 int
12419 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12420 ULONGEST offset, int *remote_errno)
12421 {
12422 struct remote_state *rs = get_remote_state ();
12423 char *p = rs->buf.data ();
12424 const char *attachment;
12425 int left = get_remote_packet_size ();
12426 int ret, attachment_len;
12427 int read_len;
12428
12429 remote_buffer_add_string (&p, &left, "vFile:pread:");
12430
12431 remote_buffer_add_int (&p, &left, fd);
12432 remote_buffer_add_string (&p, &left, ",");
12433
12434 remote_buffer_add_int (&p, &left, len);
12435 remote_buffer_add_string (&p, &left, ",");
12436
12437 remote_buffer_add_int (&p, &left, offset);
12438
12439 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12440 remote_errno, &attachment,
12441 &attachment_len);
12442
12443 if (ret < 0)
12444 return ret;
12445
12446 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12447 read_buf, len);
12448 if (read_len != ret)
12449 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12450
12451 return ret;
12452 }
12453
12454 /* See declaration.h. */
12455
12456 int
12457 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12458 ULONGEST offset)
12459 {
12460 if (this->fd == fd
12461 && this->offset <= offset
12462 && offset < this->offset + this->bufsize)
12463 {
12464 ULONGEST max = this->offset + this->bufsize;
12465
12466 if (offset + len > max)
12467 len = max - offset;
12468
12469 memcpy (read_buf, this->buf + offset - this->offset, len);
12470 return len;
12471 }
12472
12473 return 0;
12474 }
12475
12476 /* Implementation of to_fileio_pread. */
12477
12478 int
12479 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12480 ULONGEST offset, int *remote_errno)
12481 {
12482 int ret;
12483 struct remote_state *rs = get_remote_state ();
12484 readahead_cache *cache = &rs->readahead_cache;
12485
12486 ret = cache->pread (fd, read_buf, len, offset);
12487 if (ret > 0)
12488 {
12489 cache->hit_count++;
12490
12491 remote_debug_printf ("readahead cache hit %s",
12492 pulongest (cache->hit_count));
12493 return ret;
12494 }
12495
12496 cache->miss_count++;
12497
12498 remote_debug_printf ("readahead cache miss %s",
12499 pulongest (cache->miss_count));
12500
12501 cache->fd = fd;
12502 cache->offset = offset;
12503 cache->bufsize = get_remote_packet_size ();
12504 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12505
12506 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12507 cache->offset, remote_errno);
12508 if (ret <= 0)
12509 {
12510 cache->invalidate_fd (fd);
12511 return ret;
12512 }
12513
12514 cache->bufsize = ret;
12515 return cache->pread (fd, read_buf, len, offset);
12516 }
12517
12518 int
12519 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12520 ULONGEST offset, int *remote_errno)
12521 {
12522 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12523 }
12524
12525 /* Implementation of to_fileio_close. */
12526
12527 int
12528 remote_target::remote_hostio_close (int fd, int *remote_errno)
12529 {
12530 struct remote_state *rs = get_remote_state ();
12531 char *p = rs->buf.data ();
12532 int left = get_remote_packet_size () - 1;
12533
12534 rs->readahead_cache.invalidate_fd (fd);
12535
12536 remote_buffer_add_string (&p, &left, "vFile:close:");
12537
12538 remote_buffer_add_int (&p, &left, fd);
12539
12540 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12541 remote_errno, NULL, NULL);
12542 }
12543
12544 int
12545 remote_target::fileio_close (int fd, int *remote_errno)
12546 {
12547 return remote_hostio_close (fd, remote_errno);
12548 }
12549
12550 /* Implementation of to_fileio_unlink. */
12551
12552 int
12553 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12554 int *remote_errno)
12555 {
12556 struct remote_state *rs = get_remote_state ();
12557 char *p = rs->buf.data ();
12558 int left = get_remote_packet_size () - 1;
12559
12560 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12561 return -1;
12562
12563 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12564
12565 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12566 strlen (filename));
12567
12568 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12569 remote_errno, NULL, NULL);
12570 }
12571
12572 int
12573 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12574 int *remote_errno)
12575 {
12576 return remote_hostio_unlink (inf, filename, remote_errno);
12577 }
12578
12579 /* Implementation of to_fileio_readlink. */
12580
12581 gdb::optional<std::string>
12582 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12583 int *remote_errno)
12584 {
12585 struct remote_state *rs = get_remote_state ();
12586 char *p = rs->buf.data ();
12587 const char *attachment;
12588 int left = get_remote_packet_size ();
12589 int len, attachment_len;
12590 int read_len;
12591
12592 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12593 return {};
12594
12595 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12596
12597 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12598 strlen (filename));
12599
12600 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12601 remote_errno, &attachment,
12602 &attachment_len);
12603
12604 if (len < 0)
12605 return {};
12606
12607 std::string ret (len, '\0');
12608
12609 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12610 (gdb_byte *) &ret[0], len);
12611 if (read_len != len)
12612 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12613
12614 return ret;
12615 }
12616
12617 /* Implementation of to_fileio_fstat. */
12618
12619 int
12620 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12621 {
12622 struct remote_state *rs = get_remote_state ();
12623 char *p = rs->buf.data ();
12624 int left = get_remote_packet_size ();
12625 int attachment_len, ret;
12626 const char *attachment;
12627 struct fio_stat fst;
12628 int read_len;
12629
12630 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12631
12632 remote_buffer_add_int (&p, &left, fd);
12633
12634 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12635 remote_errno, &attachment,
12636 &attachment_len);
12637 if (ret < 0)
12638 {
12639 if (*remote_errno != FILEIO_ENOSYS)
12640 return ret;
12641
12642 /* Strictly we should return -1, ENOSYS here, but when
12643 "set sysroot remote:" was implemented in August 2008
12644 BFD's need for a stat function was sidestepped with
12645 this hack. This was not remedied until March 2015
12646 so we retain the previous behavior to avoid breaking
12647 compatibility.
12648
12649 Note that the memset is a March 2015 addition; older
12650 GDBs set st_size *and nothing else* so the structure
12651 would have garbage in all other fields. This might
12652 break something but retaining the previous behavior
12653 here would be just too wrong. */
12654
12655 memset (st, 0, sizeof (struct stat));
12656 st->st_size = INT_MAX;
12657 return 0;
12658 }
12659
12660 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12661 (gdb_byte *) &fst, sizeof (fst));
12662
12663 if (read_len != ret)
12664 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12665
12666 if (read_len != sizeof (fst))
12667 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12668 read_len, (int) sizeof (fst));
12669
12670 remote_fileio_to_host_stat (&fst, st);
12671
12672 return 0;
12673 }
12674
12675 /* Implementation of to_filesystem_is_local. */
12676
12677 bool
12678 remote_target::filesystem_is_local ()
12679 {
12680 /* Valgrind GDB presents itself as a remote target but works
12681 on the local filesystem: it does not implement remote get
12682 and users are not expected to set a sysroot. To handle
12683 this case we treat the remote filesystem as local if the
12684 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12685 does not support vFile:open. */
12686 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
12687 {
12688 enum packet_support ps = packet_support (PACKET_vFile_open);
12689
12690 if (ps == PACKET_SUPPORT_UNKNOWN)
12691 {
12692 int fd, remote_errno;
12693
12694 /* Try opening a file to probe support. The supplied
12695 filename is irrelevant, we only care about whether
12696 the stub recognizes the packet or not. */
12697 fd = remote_hostio_open (NULL, "just probing",
12698 FILEIO_O_RDONLY, 0700, 0,
12699 &remote_errno);
12700
12701 if (fd >= 0)
12702 remote_hostio_close (fd, &remote_errno);
12703
12704 ps = packet_support (PACKET_vFile_open);
12705 }
12706
12707 if (ps == PACKET_DISABLE)
12708 {
12709 static int warning_issued = 0;
12710
12711 if (!warning_issued)
12712 {
12713 warning (_("remote target does not support file"
12714 " transfer, attempting to access files"
12715 " from local filesystem."));
12716 warning_issued = 1;
12717 }
12718
12719 return true;
12720 }
12721 }
12722
12723 return false;
12724 }
12725
12726 static int
12727 remote_fileio_errno_to_host (int errnum)
12728 {
12729 switch (errnum)
12730 {
12731 case FILEIO_EPERM:
12732 return EPERM;
12733 case FILEIO_ENOENT:
12734 return ENOENT;
12735 case FILEIO_EINTR:
12736 return EINTR;
12737 case FILEIO_EIO:
12738 return EIO;
12739 case FILEIO_EBADF:
12740 return EBADF;
12741 case FILEIO_EACCES:
12742 return EACCES;
12743 case FILEIO_EFAULT:
12744 return EFAULT;
12745 case FILEIO_EBUSY:
12746 return EBUSY;
12747 case FILEIO_EEXIST:
12748 return EEXIST;
12749 case FILEIO_ENODEV:
12750 return ENODEV;
12751 case FILEIO_ENOTDIR:
12752 return ENOTDIR;
12753 case FILEIO_EISDIR:
12754 return EISDIR;
12755 case FILEIO_EINVAL:
12756 return EINVAL;
12757 case FILEIO_ENFILE:
12758 return ENFILE;
12759 case FILEIO_EMFILE:
12760 return EMFILE;
12761 case FILEIO_EFBIG:
12762 return EFBIG;
12763 case FILEIO_ENOSPC:
12764 return ENOSPC;
12765 case FILEIO_ESPIPE:
12766 return ESPIPE;
12767 case FILEIO_EROFS:
12768 return EROFS;
12769 case FILEIO_ENOSYS:
12770 return ENOSYS;
12771 case FILEIO_ENAMETOOLONG:
12772 return ENAMETOOLONG;
12773 }
12774 return -1;
12775 }
12776
12777 static char *
12778 remote_hostio_error (int errnum)
12779 {
12780 int host_error = remote_fileio_errno_to_host (errnum);
12781
12782 if (host_error == -1)
12783 error (_("Unknown remote I/O error %d"), errnum);
12784 else
12785 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12786 }
12787
12788 /* A RAII wrapper around a remote file descriptor. */
12789
12790 class scoped_remote_fd
12791 {
12792 public:
12793 scoped_remote_fd (remote_target *remote, int fd)
12794 : m_remote (remote), m_fd (fd)
12795 {
12796 }
12797
12798 ~scoped_remote_fd ()
12799 {
12800 if (m_fd != -1)
12801 {
12802 try
12803 {
12804 int remote_errno;
12805 m_remote->remote_hostio_close (m_fd, &remote_errno);
12806 }
12807 catch (...)
12808 {
12809 /* Swallow exception before it escapes the dtor. If
12810 something goes wrong, likely the connection is gone,
12811 and there's nothing else that can be done. */
12812 }
12813 }
12814 }
12815
12816 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12817
12818 /* Release ownership of the file descriptor, and return it. */
12819 ATTRIBUTE_UNUSED_RESULT int release () noexcept
12820 {
12821 int fd = m_fd;
12822 m_fd = -1;
12823 return fd;
12824 }
12825
12826 /* Return the owned file descriptor. */
12827 int get () const noexcept
12828 {
12829 return m_fd;
12830 }
12831
12832 private:
12833 /* The remote target. */
12834 remote_target *m_remote;
12835
12836 /* The owned remote I/O file descriptor. */
12837 int m_fd;
12838 };
12839
12840 void
12841 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12842 {
12843 remote_target *remote = get_current_remote_target ();
12844
12845 if (remote == nullptr)
12846 error (_("command can only be used with remote target"));
12847
12848 remote->remote_file_put (local_file, remote_file, from_tty);
12849 }
12850
12851 void
12852 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12853 int from_tty)
12854 {
12855 int retcode, remote_errno, bytes, io_size;
12856 int bytes_in_buffer;
12857 int saw_eof;
12858 ULONGEST offset;
12859
12860 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12861 if (file == NULL)
12862 perror_with_name (local_file);
12863
12864 scoped_remote_fd fd
12865 (this, remote_hostio_open (NULL,
12866 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12867 | FILEIO_O_TRUNC),
12868 0700, 0, &remote_errno));
12869 if (fd.get () == -1)
12870 remote_hostio_error (remote_errno);
12871
12872 /* Send up to this many bytes at once. They won't all fit in the
12873 remote packet limit, so we'll transfer slightly fewer. */
12874 io_size = get_remote_packet_size ();
12875 gdb::byte_vector buffer (io_size);
12876
12877 bytes_in_buffer = 0;
12878 saw_eof = 0;
12879 offset = 0;
12880 while (bytes_in_buffer || !saw_eof)
12881 {
12882 if (!saw_eof)
12883 {
12884 bytes = fread (buffer.data () + bytes_in_buffer, 1,
12885 io_size - bytes_in_buffer,
12886 file.get ());
12887 if (bytes == 0)
12888 {
12889 if (ferror (file.get ()))
12890 error (_("Error reading %s."), local_file);
12891 else
12892 {
12893 /* EOF. Unless there is something still in the
12894 buffer from the last iteration, we are done. */
12895 saw_eof = 1;
12896 if (bytes_in_buffer == 0)
12897 break;
12898 }
12899 }
12900 }
12901 else
12902 bytes = 0;
12903
12904 bytes += bytes_in_buffer;
12905 bytes_in_buffer = 0;
12906
12907 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12908 offset, &remote_errno);
12909
12910 if (retcode < 0)
12911 remote_hostio_error (remote_errno);
12912 else if (retcode == 0)
12913 error (_("Remote write of %d bytes returned 0!"), bytes);
12914 else if (retcode < bytes)
12915 {
12916 /* Short write. Save the rest of the read data for the next
12917 write. */
12918 bytes_in_buffer = bytes - retcode;
12919 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
12920 }
12921
12922 offset += retcode;
12923 }
12924
12925 if (remote_hostio_close (fd.release (), &remote_errno))
12926 remote_hostio_error (remote_errno);
12927
12928 if (from_tty)
12929 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12930 }
12931
12932 void
12933 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12934 {
12935 remote_target *remote = get_current_remote_target ();
12936
12937 if (remote == nullptr)
12938 error (_("command can only be used with remote target"));
12939
12940 remote->remote_file_get (remote_file, local_file, from_tty);
12941 }
12942
12943 void
12944 remote_target::remote_file_get (const char *remote_file, const char *local_file,
12945 int from_tty)
12946 {
12947 int remote_errno, bytes, io_size;
12948 ULONGEST offset;
12949
12950 scoped_remote_fd fd
12951 (this, remote_hostio_open (NULL,
12952 remote_file, FILEIO_O_RDONLY, 0, 0,
12953 &remote_errno));
12954 if (fd.get () == -1)
12955 remote_hostio_error (remote_errno);
12956
12957 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12958 if (file == NULL)
12959 perror_with_name (local_file);
12960
12961 /* Send up to this many bytes at once. They won't all fit in the
12962 remote packet limit, so we'll transfer slightly fewer. */
12963 io_size = get_remote_packet_size ();
12964 gdb::byte_vector buffer (io_size);
12965
12966 offset = 0;
12967 while (1)
12968 {
12969 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
12970 &remote_errno);
12971 if (bytes == 0)
12972 /* Success, but no bytes, means end-of-file. */
12973 break;
12974 if (bytes == -1)
12975 remote_hostio_error (remote_errno);
12976
12977 offset += bytes;
12978
12979 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
12980 if (bytes == 0)
12981 perror_with_name (local_file);
12982 }
12983
12984 if (remote_hostio_close (fd.release (), &remote_errno))
12985 remote_hostio_error (remote_errno);
12986
12987 if (from_tty)
12988 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12989 }
12990
12991 void
12992 remote_file_delete (const char *remote_file, int from_tty)
12993 {
12994 remote_target *remote = get_current_remote_target ();
12995
12996 if (remote == nullptr)
12997 error (_("command can only be used with remote target"));
12998
12999 remote->remote_file_delete (remote_file, from_tty);
13000 }
13001
13002 void
13003 remote_target::remote_file_delete (const char *remote_file, int from_tty)
13004 {
13005 int retcode, remote_errno;
13006
13007 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
13008 if (retcode == -1)
13009 remote_hostio_error (remote_errno);
13010
13011 if (from_tty)
13012 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
13013 }
13014
13015 static void
13016 remote_put_command (const char *args, int from_tty)
13017 {
13018 if (args == NULL)
13019 error_no_arg (_("file to put"));
13020
13021 gdb_argv argv (args);
13022 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13023 error (_("Invalid parameters to remote put"));
13024
13025 remote_file_put (argv[0], argv[1], from_tty);
13026 }
13027
13028 static void
13029 remote_get_command (const char *args, int from_tty)
13030 {
13031 if (args == NULL)
13032 error_no_arg (_("file to get"));
13033
13034 gdb_argv argv (args);
13035 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13036 error (_("Invalid parameters to remote get"));
13037
13038 remote_file_get (argv[0], argv[1], from_tty);
13039 }
13040
13041 static void
13042 remote_delete_command (const char *args, int from_tty)
13043 {
13044 if (args == NULL)
13045 error_no_arg (_("file to delete"));
13046
13047 gdb_argv argv (args);
13048 if (argv[0] == NULL || argv[1] != NULL)
13049 error (_("Invalid parameters to remote delete"));
13050
13051 remote_file_delete (argv[0], from_tty);
13052 }
13053
13054 bool
13055 remote_target::can_execute_reverse ()
13056 {
13057 if (packet_support (PACKET_bs) == PACKET_ENABLE
13058 || packet_support (PACKET_bc) == PACKET_ENABLE)
13059 return true;
13060 else
13061 return false;
13062 }
13063
13064 bool
13065 remote_target::supports_non_stop ()
13066 {
13067 return true;
13068 }
13069
13070 bool
13071 remote_target::supports_disable_randomization ()
13072 {
13073 /* Only supported in extended mode. */
13074 return false;
13075 }
13076
13077 bool
13078 remote_target::supports_multi_process ()
13079 {
13080 struct remote_state *rs = get_remote_state ();
13081
13082 return remote_multi_process_p (rs);
13083 }
13084
13085 static int
13086 remote_supports_cond_tracepoints ()
13087 {
13088 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
13089 }
13090
13091 bool
13092 remote_target::supports_evaluation_of_breakpoint_conditions ()
13093 {
13094 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
13095 }
13096
13097 static int
13098 remote_supports_fast_tracepoints ()
13099 {
13100 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13101 }
13102
13103 static int
13104 remote_supports_static_tracepoints ()
13105 {
13106 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13107 }
13108
13109 static int
13110 remote_supports_install_in_trace ()
13111 {
13112 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13113 }
13114
13115 bool
13116 remote_target::supports_enable_disable_tracepoint ()
13117 {
13118 return (packet_support (PACKET_EnableDisableTracepoints_feature)
13119 == PACKET_ENABLE);
13120 }
13121
13122 bool
13123 remote_target::supports_string_tracing ()
13124 {
13125 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13126 }
13127
13128 bool
13129 remote_target::can_run_breakpoint_commands ()
13130 {
13131 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13132 }
13133
13134 void
13135 remote_target::trace_init ()
13136 {
13137 struct remote_state *rs = get_remote_state ();
13138
13139 putpkt ("QTinit");
13140 remote_get_noisy_reply ();
13141 if (strcmp (rs->buf.data (), "OK") != 0)
13142 error (_("Target does not support this command."));
13143 }
13144
13145 /* Recursive routine to walk through command list including loops, and
13146 download packets for each command. */
13147
13148 void
13149 remote_target::remote_download_command_source (int num, ULONGEST addr,
13150 struct command_line *cmds)
13151 {
13152 struct remote_state *rs = get_remote_state ();
13153 struct command_line *cmd;
13154
13155 for (cmd = cmds; cmd; cmd = cmd->next)
13156 {
13157 QUIT; /* Allow user to bail out with ^C. */
13158 strcpy (rs->buf.data (), "QTDPsrc:");
13159 encode_source_string (num, addr, "cmd", cmd->line,
13160 rs->buf.data () + strlen (rs->buf.data ()),
13161 rs->buf.size () - strlen (rs->buf.data ()));
13162 putpkt (rs->buf);
13163 remote_get_noisy_reply ();
13164 if (strcmp (rs->buf.data (), "OK"))
13165 warning (_("Target does not support source download."));
13166
13167 if (cmd->control_type == while_control
13168 || cmd->control_type == while_stepping_control)
13169 {
13170 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13171
13172 QUIT; /* Allow user to bail out with ^C. */
13173 strcpy (rs->buf.data (), "QTDPsrc:");
13174 encode_source_string (num, addr, "cmd", "end",
13175 rs->buf.data () + strlen (rs->buf.data ()),
13176 rs->buf.size () - strlen (rs->buf.data ()));
13177 putpkt (rs->buf);
13178 remote_get_noisy_reply ();
13179 if (strcmp (rs->buf.data (), "OK"))
13180 warning (_("Target does not support source download."));
13181 }
13182 }
13183 }
13184
13185 void
13186 remote_target::download_tracepoint (struct bp_location *loc)
13187 {
13188 CORE_ADDR tpaddr;
13189 char addrbuf[40];
13190 std::vector<std::string> tdp_actions;
13191 std::vector<std::string> stepping_actions;
13192 char *pkt;
13193 struct breakpoint *b = loc->owner;
13194 struct tracepoint *t = (struct tracepoint *) b;
13195 struct remote_state *rs = get_remote_state ();
13196 int ret;
13197 const char *err_msg = _("Tracepoint packet too large for target.");
13198 size_t size_left;
13199
13200 /* We use a buffer other than rs->buf because we'll build strings
13201 across multiple statements, and other statements in between could
13202 modify rs->buf. */
13203 gdb::char_vector buf (get_remote_packet_size ());
13204
13205 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13206
13207 tpaddr = loc->address;
13208 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13209 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13210 b->number, addrbuf, /* address */
13211 (b->enable_state == bp_enabled ? 'E' : 'D'),
13212 t->step_count, t->pass_count);
13213
13214 if (ret < 0 || ret >= buf.size ())
13215 error ("%s", err_msg);
13216
13217 /* Fast tracepoints are mostly handled by the target, but we can
13218 tell the target how big of an instruction block should be moved
13219 around. */
13220 if (b->type == bp_fast_tracepoint)
13221 {
13222 /* Only test for support at download time; we may not know
13223 target capabilities at definition time. */
13224 if (remote_supports_fast_tracepoints ())
13225 {
13226 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13227 NULL))
13228 {
13229 size_left = buf.size () - strlen (buf.data ());
13230 ret = snprintf (buf.data () + strlen (buf.data ()),
13231 size_left, ":F%x",
13232 gdb_insn_length (loc->gdbarch, tpaddr));
13233
13234 if (ret < 0 || ret >= size_left)
13235 error ("%s", err_msg);
13236 }
13237 else
13238 /* If it passed validation at definition but fails now,
13239 something is very wrong. */
13240 internal_error (__FILE__, __LINE__,
13241 _("Fast tracepoint not "
13242 "valid during download"));
13243 }
13244 else
13245 /* Fast tracepoints are functionally identical to regular
13246 tracepoints, so don't take lack of support as a reason to
13247 give up on the trace run. */
13248 warning (_("Target does not support fast tracepoints, "
13249 "downloading %d as regular tracepoint"), b->number);
13250 }
13251 else if (b->type == bp_static_tracepoint)
13252 {
13253 /* Only test for support at download time; we may not know
13254 target capabilities at definition time. */
13255 if (remote_supports_static_tracepoints ())
13256 {
13257 struct static_tracepoint_marker marker;
13258
13259 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13260 {
13261 size_left = buf.size () - strlen (buf.data ());
13262 ret = snprintf (buf.data () + strlen (buf.data ()),
13263 size_left, ":S");
13264
13265 if (ret < 0 || ret >= size_left)
13266 error ("%s", err_msg);
13267 }
13268 else
13269 error (_("Static tracepoint not valid during download"));
13270 }
13271 else
13272 /* Fast tracepoints are functionally identical to regular
13273 tracepoints, so don't take lack of support as a reason
13274 to give up on the trace run. */
13275 error (_("Target does not support static tracepoints"));
13276 }
13277 /* If the tracepoint has a conditional, make it into an agent
13278 expression and append to the definition. */
13279 if (loc->cond)
13280 {
13281 /* Only test support at download time, we may not know target
13282 capabilities at definition time. */
13283 if (remote_supports_cond_tracepoints ())
13284 {
13285 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13286 loc->cond.get ());
13287
13288 size_left = buf.size () - strlen (buf.data ());
13289
13290 ret = snprintf (buf.data () + strlen (buf.data ()),
13291 size_left, ":X%x,", aexpr->len);
13292
13293 if (ret < 0 || ret >= size_left)
13294 error ("%s", err_msg);
13295
13296 size_left = buf.size () - strlen (buf.data ());
13297
13298 /* Two bytes to encode each aexpr byte, plus the terminating
13299 null byte. */
13300 if (aexpr->len * 2 + 1 > size_left)
13301 error ("%s", err_msg);
13302
13303 pkt = buf.data () + strlen (buf.data ());
13304
13305 for (int ndx = 0; ndx < aexpr->len; ++ndx)
13306 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13307 *pkt = '\0';
13308 }
13309 else
13310 warning (_("Target does not support conditional tracepoints, "
13311 "ignoring tp %d cond"), b->number);
13312 }
13313
13314 if (b->commands || !default_collect.empty ())
13315 {
13316 size_left = buf.size () - strlen (buf.data ());
13317
13318 ret = snprintf (buf.data () + strlen (buf.data ()),
13319 size_left, "-");
13320
13321 if (ret < 0 || ret >= size_left)
13322 error ("%s", err_msg);
13323 }
13324
13325 putpkt (buf.data ());
13326 remote_get_noisy_reply ();
13327 if (strcmp (rs->buf.data (), "OK"))
13328 error (_("Target does not support tracepoints."));
13329
13330 /* do_single_steps (t); */
13331 for (auto action_it = tdp_actions.begin ();
13332 action_it != tdp_actions.end (); action_it++)
13333 {
13334 QUIT; /* Allow user to bail out with ^C. */
13335
13336 bool has_more = ((action_it + 1) != tdp_actions.end ()
13337 || !stepping_actions.empty ());
13338
13339 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13340 b->number, addrbuf, /* address */
13341 action_it->c_str (),
13342 has_more ? '-' : 0);
13343
13344 if (ret < 0 || ret >= buf.size ())
13345 error ("%s", err_msg);
13346
13347 putpkt (buf.data ());
13348 remote_get_noisy_reply ();
13349 if (strcmp (rs->buf.data (), "OK"))
13350 error (_("Error on target while setting tracepoints."));
13351 }
13352
13353 for (auto action_it = stepping_actions.begin ();
13354 action_it != stepping_actions.end (); action_it++)
13355 {
13356 QUIT; /* Allow user to bail out with ^C. */
13357
13358 bool is_first = action_it == stepping_actions.begin ();
13359 bool has_more = (action_it + 1) != stepping_actions.end ();
13360
13361 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13362 b->number, addrbuf, /* address */
13363 is_first ? "S" : "",
13364 action_it->c_str (),
13365 has_more ? "-" : "");
13366
13367 if (ret < 0 || ret >= buf.size ())
13368 error ("%s", err_msg);
13369
13370 putpkt (buf.data ());
13371 remote_get_noisy_reply ();
13372 if (strcmp (rs->buf.data (), "OK"))
13373 error (_("Error on target while setting tracepoints."));
13374 }
13375
13376 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13377 {
13378 if (b->location != NULL)
13379 {
13380 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13381
13382 if (ret < 0 || ret >= buf.size ())
13383 error ("%s", err_msg);
13384
13385 encode_source_string (b->number, loc->address, "at",
13386 event_location_to_string (b->location.get ()),
13387 buf.data () + strlen (buf.data ()),
13388 buf.size () - strlen (buf.data ()));
13389 putpkt (buf.data ());
13390 remote_get_noisy_reply ();
13391 if (strcmp (rs->buf.data (), "OK"))
13392 warning (_("Target does not support source download."));
13393 }
13394 if (b->cond_string)
13395 {
13396 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13397
13398 if (ret < 0 || ret >= buf.size ())
13399 error ("%s", err_msg);
13400
13401 encode_source_string (b->number, loc->address,
13402 "cond", b->cond_string.get (),
13403 buf.data () + strlen (buf.data ()),
13404 buf.size () - strlen (buf.data ()));
13405 putpkt (buf.data ());
13406 remote_get_noisy_reply ();
13407 if (strcmp (rs->buf.data (), "OK"))
13408 warning (_("Target does not support source download."));
13409 }
13410 remote_download_command_source (b->number, loc->address,
13411 breakpoint_commands (b));
13412 }
13413 }
13414
13415 bool
13416 remote_target::can_download_tracepoint ()
13417 {
13418 struct remote_state *rs = get_remote_state ();
13419 struct trace_status *ts;
13420 int status;
13421
13422 /* Don't try to install tracepoints until we've relocated our
13423 symbols, and fetched and merged the target's tracepoint list with
13424 ours. */
13425 if (rs->starting_up)
13426 return false;
13427
13428 ts = current_trace_status ();
13429 status = get_trace_status (ts);
13430
13431 if (status == -1 || !ts->running_known || !ts->running)
13432 return false;
13433
13434 /* If we are in a tracing experiment, but remote stub doesn't support
13435 installing tracepoint in trace, we have to return. */
13436 if (!remote_supports_install_in_trace ())
13437 return false;
13438
13439 return true;
13440 }
13441
13442
13443 void
13444 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13445 {
13446 struct remote_state *rs = get_remote_state ();
13447 char *p;
13448
13449 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13450 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13451 tsv.builtin);
13452 p = rs->buf.data () + strlen (rs->buf.data ());
13453 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13454 >= get_remote_packet_size ())
13455 error (_("Trace state variable name too long for tsv definition packet"));
13456 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13457 *p++ = '\0';
13458 putpkt (rs->buf);
13459 remote_get_noisy_reply ();
13460 if (rs->buf[0] == '\0')
13461 error (_("Target does not support this command."));
13462 if (strcmp (rs->buf.data (), "OK") != 0)
13463 error (_("Error on target while downloading trace state variable."));
13464 }
13465
13466 void
13467 remote_target::enable_tracepoint (struct bp_location *location)
13468 {
13469 struct remote_state *rs = get_remote_state ();
13470
13471 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13472 location->owner->number,
13473 phex (location->address, sizeof (CORE_ADDR)));
13474 putpkt (rs->buf);
13475 remote_get_noisy_reply ();
13476 if (rs->buf[0] == '\0')
13477 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13478 if (strcmp (rs->buf.data (), "OK") != 0)
13479 error (_("Error on target while enabling tracepoint."));
13480 }
13481
13482 void
13483 remote_target::disable_tracepoint (struct bp_location *location)
13484 {
13485 struct remote_state *rs = get_remote_state ();
13486
13487 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13488 location->owner->number,
13489 phex (location->address, sizeof (CORE_ADDR)));
13490 putpkt (rs->buf);
13491 remote_get_noisy_reply ();
13492 if (rs->buf[0] == '\0')
13493 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13494 if (strcmp (rs->buf.data (), "OK") != 0)
13495 error (_("Error on target while disabling tracepoint."));
13496 }
13497
13498 void
13499 remote_target::trace_set_readonly_regions ()
13500 {
13501 asection *s;
13502 bfd_size_type size;
13503 bfd_vma vma;
13504 int anysecs = 0;
13505 int offset = 0;
13506
13507 if (!current_program_space->exec_bfd ())
13508 return; /* No information to give. */
13509
13510 struct remote_state *rs = get_remote_state ();
13511
13512 strcpy (rs->buf.data (), "QTro");
13513 offset = strlen (rs->buf.data ());
13514 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
13515 {
13516 char tmp1[40], tmp2[40];
13517 int sec_length;
13518
13519 if ((s->flags & SEC_LOAD) == 0 ||
13520 /* (s->flags & SEC_CODE) == 0 || */
13521 (s->flags & SEC_READONLY) == 0)
13522 continue;
13523
13524 anysecs = 1;
13525 vma = bfd_section_vma (s);
13526 size = bfd_section_size (s);
13527 sprintf_vma (tmp1, vma);
13528 sprintf_vma (tmp2, vma + size);
13529 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13530 if (offset + sec_length + 1 > rs->buf.size ())
13531 {
13532 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
13533 warning (_("\
13534 Too many sections for read-only sections definition packet."));
13535 break;
13536 }
13537 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13538 tmp1, tmp2);
13539 offset += sec_length;
13540 }
13541 if (anysecs)
13542 {
13543 putpkt (rs->buf);
13544 getpkt (&rs->buf, 0);
13545 }
13546 }
13547
13548 void
13549 remote_target::trace_start ()
13550 {
13551 struct remote_state *rs = get_remote_state ();
13552
13553 putpkt ("QTStart");
13554 remote_get_noisy_reply ();
13555 if (rs->buf[0] == '\0')
13556 error (_("Target does not support this command."));
13557 if (strcmp (rs->buf.data (), "OK") != 0)
13558 error (_("Bogus reply from target: %s"), rs->buf.data ());
13559 }
13560
13561 int
13562 remote_target::get_trace_status (struct trace_status *ts)
13563 {
13564 /* Initialize it just to avoid a GCC false warning. */
13565 char *p = NULL;
13566 enum packet_result result;
13567 struct remote_state *rs = get_remote_state ();
13568
13569 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13570 return -1;
13571
13572 /* FIXME we need to get register block size some other way. */
13573 trace_regblock_size
13574 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13575
13576 putpkt ("qTStatus");
13577
13578 try
13579 {
13580 p = remote_get_noisy_reply ();
13581 }
13582 catch (const gdb_exception_error &ex)
13583 {
13584 if (ex.error != TARGET_CLOSE_ERROR)
13585 {
13586 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13587 return -1;
13588 }
13589 throw;
13590 }
13591
13592 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13593
13594 /* If the remote target doesn't do tracing, flag it. */
13595 if (result == PACKET_UNKNOWN)
13596 return -1;
13597
13598 /* We're working with a live target. */
13599 ts->filename = NULL;
13600
13601 if (*p++ != 'T')
13602 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13603
13604 /* Function 'parse_trace_status' sets default value of each field of
13605 'ts' at first, so we don't have to do it here. */
13606 parse_trace_status (p, ts);
13607
13608 return ts->running;
13609 }
13610
13611 void
13612 remote_target::get_tracepoint_status (struct breakpoint *bp,
13613 struct uploaded_tp *utp)
13614 {
13615 struct remote_state *rs = get_remote_state ();
13616 char *reply;
13617 struct tracepoint *tp = (struct tracepoint *) bp;
13618 size_t size = get_remote_packet_size ();
13619
13620 if (tp)
13621 {
13622 tp->hit_count = 0;
13623 tp->traceframe_usage = 0;
13624 for (bp_location *loc : tp->locations ())
13625 {
13626 /* If the tracepoint was never downloaded, don't go asking for
13627 any status. */
13628 if (tp->number_on_target == 0)
13629 continue;
13630 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13631 phex_nz (loc->address, 0));
13632 putpkt (rs->buf);
13633 reply = remote_get_noisy_reply ();
13634 if (reply && *reply)
13635 {
13636 if (*reply == 'V')
13637 parse_tracepoint_status (reply + 1, bp, utp);
13638 }
13639 }
13640 }
13641 else if (utp)
13642 {
13643 utp->hit_count = 0;
13644 utp->traceframe_usage = 0;
13645 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13646 phex_nz (utp->addr, 0));
13647 putpkt (rs->buf);
13648 reply = remote_get_noisy_reply ();
13649 if (reply && *reply)
13650 {
13651 if (*reply == 'V')
13652 parse_tracepoint_status (reply + 1, bp, utp);
13653 }
13654 }
13655 }
13656
13657 void
13658 remote_target::trace_stop ()
13659 {
13660 struct remote_state *rs = get_remote_state ();
13661
13662 putpkt ("QTStop");
13663 remote_get_noisy_reply ();
13664 if (rs->buf[0] == '\0')
13665 error (_("Target does not support this command."));
13666 if (strcmp (rs->buf.data (), "OK") != 0)
13667 error (_("Bogus reply from target: %s"), rs->buf.data ());
13668 }
13669
13670 int
13671 remote_target::trace_find (enum trace_find_type type, int num,
13672 CORE_ADDR addr1, CORE_ADDR addr2,
13673 int *tpp)
13674 {
13675 struct remote_state *rs = get_remote_state ();
13676 char *endbuf = rs->buf.data () + get_remote_packet_size ();
13677 char *p, *reply;
13678 int target_frameno = -1, target_tracept = -1;
13679
13680 /* Lookups other than by absolute frame number depend on the current
13681 trace selected, so make sure it is correct on the remote end
13682 first. */
13683 if (type != tfind_number)
13684 set_remote_traceframe ();
13685
13686 p = rs->buf.data ();
13687 strcpy (p, "QTFrame:");
13688 p = strchr (p, '\0');
13689 switch (type)
13690 {
13691 case tfind_number:
13692 xsnprintf (p, endbuf - p, "%x", num);
13693 break;
13694 case tfind_pc:
13695 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13696 break;
13697 case tfind_tp:
13698 xsnprintf (p, endbuf - p, "tdp:%x", num);
13699 break;
13700 case tfind_range:
13701 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13702 phex_nz (addr2, 0));
13703 break;
13704 case tfind_outside:
13705 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13706 phex_nz (addr2, 0));
13707 break;
13708 default:
13709 error (_("Unknown trace find type %d"), type);
13710 }
13711
13712 putpkt (rs->buf);
13713 reply = remote_get_noisy_reply ();
13714 if (*reply == '\0')
13715 error (_("Target does not support this command."));
13716
13717 while (reply && *reply)
13718 switch (*reply)
13719 {
13720 case 'F':
13721 p = ++reply;
13722 target_frameno = (int) strtol (p, &reply, 16);
13723 if (reply == p)
13724 error (_("Unable to parse trace frame number"));
13725 /* Don't update our remote traceframe number cache on failure
13726 to select a remote traceframe. */
13727 if (target_frameno == -1)
13728 return -1;
13729 break;
13730 case 'T':
13731 p = ++reply;
13732 target_tracept = (int) strtol (p, &reply, 16);
13733 if (reply == p)
13734 error (_("Unable to parse tracepoint number"));
13735 break;
13736 case 'O': /* "OK"? */
13737 if (reply[1] == 'K' && reply[2] == '\0')
13738 reply += 2;
13739 else
13740 error (_("Bogus reply from target: %s"), reply);
13741 break;
13742 default:
13743 error (_("Bogus reply from target: %s"), reply);
13744 }
13745 if (tpp)
13746 *tpp = target_tracept;
13747
13748 rs->remote_traceframe_number = target_frameno;
13749 return target_frameno;
13750 }
13751
13752 bool
13753 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13754 {
13755 struct remote_state *rs = get_remote_state ();
13756 char *reply;
13757 ULONGEST uval;
13758
13759 set_remote_traceframe ();
13760
13761 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
13762 putpkt (rs->buf);
13763 reply = remote_get_noisy_reply ();
13764 if (reply && *reply)
13765 {
13766 if (*reply == 'V')
13767 {
13768 unpack_varlen_hex (reply + 1, &uval);
13769 *val = (LONGEST) uval;
13770 return true;
13771 }
13772 }
13773 return false;
13774 }
13775
13776 int
13777 remote_target::save_trace_data (const char *filename)
13778 {
13779 struct remote_state *rs = get_remote_state ();
13780 char *p, *reply;
13781
13782 p = rs->buf.data ();
13783 strcpy (p, "QTSave:");
13784 p += strlen (p);
13785 if ((p - rs->buf.data ()) + strlen (filename) * 2
13786 >= get_remote_packet_size ())
13787 error (_("Remote file name too long for trace save packet"));
13788 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13789 *p++ = '\0';
13790 putpkt (rs->buf);
13791 reply = remote_get_noisy_reply ();
13792 if (*reply == '\0')
13793 error (_("Target does not support this command."));
13794 if (strcmp (reply, "OK") != 0)
13795 error (_("Bogus reply from target: %s"), reply);
13796 return 0;
13797 }
13798
13799 /* This is basically a memory transfer, but needs to be its own packet
13800 because we don't know how the target actually organizes its trace
13801 memory, plus we want to be able to ask for as much as possible, but
13802 not be unhappy if we don't get as much as we ask for. */
13803
13804 LONGEST
13805 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13806 {
13807 struct remote_state *rs = get_remote_state ();
13808 char *reply;
13809 char *p;
13810 int rslt;
13811
13812 p = rs->buf.data ();
13813 strcpy (p, "qTBuffer:");
13814 p += strlen (p);
13815 p += hexnumstr (p, offset);
13816 *p++ = ',';
13817 p += hexnumstr (p, len);
13818 *p++ = '\0';
13819
13820 putpkt (rs->buf);
13821 reply = remote_get_noisy_reply ();
13822 if (reply && *reply)
13823 {
13824 /* 'l' by itself means we're at the end of the buffer and
13825 there is nothing more to get. */
13826 if (*reply == 'l')
13827 return 0;
13828
13829 /* Convert the reply into binary. Limit the number of bytes to
13830 convert according to our passed-in buffer size, rather than
13831 what was returned in the packet; if the target is
13832 unexpectedly generous and gives us a bigger reply than we
13833 asked for, we don't want to crash. */
13834 rslt = hex2bin (reply, buf, len);
13835 return rslt;
13836 }
13837
13838 /* Something went wrong, flag as an error. */
13839 return -1;
13840 }
13841
13842 void
13843 remote_target::set_disconnected_tracing (int val)
13844 {
13845 struct remote_state *rs = get_remote_state ();
13846
13847 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13848 {
13849 char *reply;
13850
13851 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13852 "QTDisconnected:%x", val);
13853 putpkt (rs->buf);
13854 reply = remote_get_noisy_reply ();
13855 if (*reply == '\0')
13856 error (_("Target does not support this command."));
13857 if (strcmp (reply, "OK") != 0)
13858 error (_("Bogus reply from target: %s"), reply);
13859 }
13860 else if (val)
13861 warning (_("Target does not support disconnected tracing."));
13862 }
13863
13864 int
13865 remote_target::core_of_thread (ptid_t ptid)
13866 {
13867 thread_info *info = find_thread_ptid (this, ptid);
13868
13869 if (info != NULL && info->priv != NULL)
13870 return get_remote_thread_info (info)->core;
13871
13872 return -1;
13873 }
13874
13875 void
13876 remote_target::set_circular_trace_buffer (int val)
13877 {
13878 struct remote_state *rs = get_remote_state ();
13879 char *reply;
13880
13881 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13882 "QTBuffer:circular:%x", val);
13883 putpkt (rs->buf);
13884 reply = remote_get_noisy_reply ();
13885 if (*reply == '\0')
13886 error (_("Target does not support this command."));
13887 if (strcmp (reply, "OK") != 0)
13888 error (_("Bogus reply from target: %s"), reply);
13889 }
13890
13891 traceframe_info_up
13892 remote_target::traceframe_info ()
13893 {
13894 gdb::optional<gdb::char_vector> text
13895 = target_read_stralloc (current_inferior ()->top_target (),
13896 TARGET_OBJECT_TRACEFRAME_INFO,
13897 NULL);
13898 if (text)
13899 return parse_traceframe_info (text->data ());
13900
13901 return NULL;
13902 }
13903
13904 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13905 instruction on which a fast tracepoint may be placed. Returns -1
13906 if the packet is not supported, and 0 if the minimum instruction
13907 length is unknown. */
13908
13909 int
13910 remote_target::get_min_fast_tracepoint_insn_len ()
13911 {
13912 struct remote_state *rs = get_remote_state ();
13913 char *reply;
13914
13915 /* If we're not debugging a process yet, the IPA can't be
13916 loaded. */
13917 if (!target_has_execution ())
13918 return 0;
13919
13920 /* Make sure the remote is pointing at the right process. */
13921 set_general_process ();
13922
13923 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
13924 putpkt (rs->buf);
13925 reply = remote_get_noisy_reply ();
13926 if (*reply == '\0')
13927 return -1;
13928 else
13929 {
13930 ULONGEST min_insn_len;
13931
13932 unpack_varlen_hex (reply, &min_insn_len);
13933
13934 return (int) min_insn_len;
13935 }
13936 }
13937
13938 void
13939 remote_target::set_trace_buffer_size (LONGEST val)
13940 {
13941 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13942 {
13943 struct remote_state *rs = get_remote_state ();
13944 char *buf = rs->buf.data ();
13945 char *endbuf = buf + get_remote_packet_size ();
13946 enum packet_result result;
13947
13948 gdb_assert (val >= 0 || val == -1);
13949 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13950 /* Send -1 as literal "-1" to avoid host size dependency. */
13951 if (val < 0)
13952 {
13953 *buf++ = '-';
13954 buf += hexnumstr (buf, (ULONGEST) -val);
13955 }
13956 else
13957 buf += hexnumstr (buf, (ULONGEST) val);
13958
13959 putpkt (rs->buf);
13960 remote_get_noisy_reply ();
13961 result = packet_ok (rs->buf,
13962 &remote_protocol_packets[PACKET_QTBuffer_size]);
13963
13964 if (result != PACKET_OK)
13965 warning (_("Bogus reply from target: %s"), rs->buf.data ());
13966 }
13967 }
13968
13969 bool
13970 remote_target::set_trace_notes (const char *user, const char *notes,
13971 const char *stop_notes)
13972 {
13973 struct remote_state *rs = get_remote_state ();
13974 char *reply;
13975 char *buf = rs->buf.data ();
13976 char *endbuf = buf + get_remote_packet_size ();
13977 int nbytes;
13978
13979 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13980 if (user)
13981 {
13982 buf += xsnprintf (buf, endbuf - buf, "user:");
13983 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13984 buf += 2 * nbytes;
13985 *buf++ = ';';
13986 }
13987 if (notes)
13988 {
13989 buf += xsnprintf (buf, endbuf - buf, "notes:");
13990 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13991 buf += 2 * nbytes;
13992 *buf++ = ';';
13993 }
13994 if (stop_notes)
13995 {
13996 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13997 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13998 buf += 2 * nbytes;
13999 *buf++ = ';';
14000 }
14001 /* Ensure the buffer is terminated. */
14002 *buf = '\0';
14003
14004 putpkt (rs->buf);
14005 reply = remote_get_noisy_reply ();
14006 if (*reply == '\0')
14007 return false;
14008
14009 if (strcmp (reply, "OK") != 0)
14010 error (_("Bogus reply from target: %s"), reply);
14011
14012 return true;
14013 }
14014
14015 bool
14016 remote_target::use_agent (bool use)
14017 {
14018 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
14019 {
14020 struct remote_state *rs = get_remote_state ();
14021
14022 /* If the stub supports QAgent. */
14023 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
14024 putpkt (rs->buf);
14025 getpkt (&rs->buf, 0);
14026
14027 if (strcmp (rs->buf.data (), "OK") == 0)
14028 {
14029 ::use_agent = use;
14030 return true;
14031 }
14032 }
14033
14034 return false;
14035 }
14036
14037 bool
14038 remote_target::can_use_agent ()
14039 {
14040 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
14041 }
14042
14043 struct btrace_target_info
14044 {
14045 /* The ptid of the traced thread. */
14046 ptid_t ptid;
14047
14048 /* The obtained branch trace configuration. */
14049 struct btrace_config conf;
14050 };
14051
14052 /* Reset our idea of our target's btrace configuration. */
14053
14054 static void
14055 remote_btrace_reset (remote_state *rs)
14056 {
14057 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14058 }
14059
14060 /* Synchronize the configuration with the target. */
14061
14062 void
14063 remote_target::btrace_sync_conf (const btrace_config *conf)
14064 {
14065 struct packet_config *packet;
14066 struct remote_state *rs;
14067 char *buf, *pos, *endbuf;
14068
14069 rs = get_remote_state ();
14070 buf = rs->buf.data ();
14071 endbuf = buf + get_remote_packet_size ();
14072
14073 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
14074 if (packet_config_support (packet) == PACKET_ENABLE
14075 && conf->bts.size != rs->btrace_config.bts.size)
14076 {
14077 pos = buf;
14078 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
14079 conf->bts.size);
14080
14081 putpkt (buf);
14082 getpkt (&rs->buf, 0);
14083
14084 if (packet_ok (buf, packet) == PACKET_ERROR)
14085 {
14086 if (buf[0] == 'E' && buf[1] == '.')
14087 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14088 else
14089 error (_("Failed to configure the BTS buffer size."));
14090 }
14091
14092 rs->btrace_config.bts.size = conf->bts.size;
14093 }
14094
14095 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
14096 if (packet_config_support (packet) == PACKET_ENABLE
14097 && conf->pt.size != rs->btrace_config.pt.size)
14098 {
14099 pos = buf;
14100 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
14101 conf->pt.size);
14102
14103 putpkt (buf);
14104 getpkt (&rs->buf, 0);
14105
14106 if (packet_ok (buf, packet) == PACKET_ERROR)
14107 {
14108 if (buf[0] == 'E' && buf[1] == '.')
14109 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14110 else
14111 error (_("Failed to configure the trace buffer size."));
14112 }
14113
14114 rs->btrace_config.pt.size = conf->pt.size;
14115 }
14116 }
14117
14118 /* Read the current thread's btrace configuration from the target and
14119 store it into CONF. */
14120
14121 static void
14122 btrace_read_config (struct btrace_config *conf)
14123 {
14124 gdb::optional<gdb::char_vector> xml
14125 = target_read_stralloc (current_inferior ()->top_target (),
14126 TARGET_OBJECT_BTRACE_CONF, "");
14127 if (xml)
14128 parse_xml_btrace_conf (conf, xml->data ());
14129 }
14130
14131 /* Maybe reopen target btrace. */
14132
14133 void
14134 remote_target::remote_btrace_maybe_reopen ()
14135 {
14136 struct remote_state *rs = get_remote_state ();
14137 int btrace_target_pushed = 0;
14138 #if !defined (HAVE_LIBIPT)
14139 int warned = 0;
14140 #endif
14141
14142 /* Don't bother walking the entirety of the remote thread list when
14143 we know the feature isn't supported by the remote. */
14144 if (packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14145 return;
14146
14147 scoped_restore_current_thread restore_thread;
14148
14149 for (thread_info *tp : all_non_exited_threads (this))
14150 {
14151 set_general_thread (tp->ptid);
14152
14153 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14154 btrace_read_config (&rs->btrace_config);
14155
14156 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14157 continue;
14158
14159 #if !defined (HAVE_LIBIPT)
14160 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14161 {
14162 if (!warned)
14163 {
14164 warned = 1;
14165 warning (_("Target is recording using Intel Processor Trace "
14166 "but support was disabled at compile time."));
14167 }
14168
14169 continue;
14170 }
14171 #endif /* !defined (HAVE_LIBIPT) */
14172
14173 /* Push target, once, but before anything else happens. This way our
14174 changes to the threads will be cleaned up by unpushing the target
14175 in case btrace_read_config () throws. */
14176 if (!btrace_target_pushed)
14177 {
14178 btrace_target_pushed = 1;
14179 record_btrace_push_target ();
14180 printf_filtered (_("Target is recording using %s.\n"),
14181 btrace_format_string (rs->btrace_config.format));
14182 }
14183
14184 tp->btrace.target = XCNEW (struct btrace_target_info);
14185 tp->btrace.target->ptid = tp->ptid;
14186 tp->btrace.target->conf = rs->btrace_config;
14187 }
14188 }
14189
14190 /* Enable branch tracing. */
14191
14192 struct btrace_target_info *
14193 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
14194 {
14195 struct btrace_target_info *tinfo = NULL;
14196 struct packet_config *packet = NULL;
14197 struct remote_state *rs = get_remote_state ();
14198 char *buf = rs->buf.data ();
14199 char *endbuf = buf + get_remote_packet_size ();
14200
14201 switch (conf->format)
14202 {
14203 case BTRACE_FORMAT_BTS:
14204 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
14205 break;
14206
14207 case BTRACE_FORMAT_PT:
14208 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
14209 break;
14210 }
14211
14212 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14213 error (_("Target does not support branch tracing."));
14214
14215 btrace_sync_conf (conf);
14216
14217 set_general_thread (ptid);
14218
14219 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14220 putpkt (rs->buf);
14221 getpkt (&rs->buf, 0);
14222
14223 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14224 {
14225 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14226 error (_("Could not enable branch tracing for %s: %s"),
14227 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14228 else
14229 error (_("Could not enable branch tracing for %s."),
14230 target_pid_to_str (ptid).c_str ());
14231 }
14232
14233 tinfo = XCNEW (struct btrace_target_info);
14234 tinfo->ptid = ptid;
14235
14236 /* If we fail to read the configuration, we lose some information, but the
14237 tracing itself is not impacted. */
14238 try
14239 {
14240 btrace_read_config (&tinfo->conf);
14241 }
14242 catch (const gdb_exception_error &err)
14243 {
14244 if (err.message != NULL)
14245 warning ("%s", err.what ());
14246 }
14247
14248 return tinfo;
14249 }
14250
14251 /* Disable branch tracing. */
14252
14253 void
14254 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14255 {
14256 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
14257 struct remote_state *rs = get_remote_state ();
14258 char *buf = rs->buf.data ();
14259 char *endbuf = buf + get_remote_packet_size ();
14260
14261 if (packet_config_support (packet) != PACKET_ENABLE)
14262 error (_("Target does not support branch tracing."));
14263
14264 set_general_thread (tinfo->ptid);
14265
14266 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14267 putpkt (rs->buf);
14268 getpkt (&rs->buf, 0);
14269
14270 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14271 {
14272 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14273 error (_("Could not disable branch tracing for %s: %s"),
14274 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14275 else
14276 error (_("Could not disable branch tracing for %s."),
14277 target_pid_to_str (tinfo->ptid).c_str ());
14278 }
14279
14280 xfree (tinfo);
14281 }
14282
14283 /* Teardown branch tracing. */
14284
14285 void
14286 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14287 {
14288 /* We must not talk to the target during teardown. */
14289 xfree (tinfo);
14290 }
14291
14292 /* Read the branch trace. */
14293
14294 enum btrace_error
14295 remote_target::read_btrace (struct btrace_data *btrace,
14296 struct btrace_target_info *tinfo,
14297 enum btrace_read_type type)
14298 {
14299 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
14300 const char *annex;
14301
14302 if (packet_config_support (packet) != PACKET_ENABLE)
14303 error (_("Target does not support branch tracing."));
14304
14305 #if !defined(HAVE_LIBEXPAT)
14306 error (_("Cannot process branch tracing result. XML parsing not supported."));
14307 #endif
14308
14309 switch (type)
14310 {
14311 case BTRACE_READ_ALL:
14312 annex = "all";
14313 break;
14314 case BTRACE_READ_NEW:
14315 annex = "new";
14316 break;
14317 case BTRACE_READ_DELTA:
14318 annex = "delta";
14319 break;
14320 default:
14321 internal_error (__FILE__, __LINE__,
14322 _("Bad branch tracing read type: %u."),
14323 (unsigned int) type);
14324 }
14325
14326 gdb::optional<gdb::char_vector> xml
14327 = target_read_stralloc (current_inferior ()->top_target (),
14328 TARGET_OBJECT_BTRACE, annex);
14329 if (!xml)
14330 return BTRACE_ERR_UNKNOWN;
14331
14332 parse_xml_btrace (btrace, xml->data ());
14333
14334 return BTRACE_ERR_NONE;
14335 }
14336
14337 const struct btrace_config *
14338 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14339 {
14340 return &tinfo->conf;
14341 }
14342
14343 bool
14344 remote_target::augmented_libraries_svr4_read ()
14345 {
14346 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
14347 == PACKET_ENABLE);
14348 }
14349
14350 /* Implementation of to_load. */
14351
14352 void
14353 remote_target::load (const char *name, int from_tty)
14354 {
14355 generic_load (name, from_tty);
14356 }
14357
14358 /* Accepts an integer PID; returns a string representing a file that
14359 can be opened on the remote side to get the symbols for the child
14360 process. Returns NULL if the operation is not supported. */
14361
14362 char *
14363 remote_target::pid_to_exec_file (int pid)
14364 {
14365 static gdb::optional<gdb::char_vector> filename;
14366 char *annex = NULL;
14367
14368 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14369 return NULL;
14370
14371 inferior *inf = find_inferior_pid (this, pid);
14372 if (inf == NULL)
14373 internal_error (__FILE__, __LINE__,
14374 _("not currently attached to process %d"), pid);
14375
14376 if (!inf->fake_pid_p)
14377 {
14378 const int annex_size = 9;
14379
14380 annex = (char *) alloca (annex_size);
14381 xsnprintf (annex, annex_size, "%x", pid);
14382 }
14383
14384 filename = target_read_stralloc (current_inferior ()->top_target (),
14385 TARGET_OBJECT_EXEC_FILE, annex);
14386
14387 return filename ? filename->data () : nullptr;
14388 }
14389
14390 /* Implement the to_can_do_single_step target_ops method. */
14391
14392 int
14393 remote_target::can_do_single_step ()
14394 {
14395 /* We can only tell whether target supports single step or not by
14396 supported s and S vCont actions if the stub supports vContSupported
14397 feature. If the stub doesn't support vContSupported feature,
14398 we have conservatively to think target doesn't supports single
14399 step. */
14400 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14401 {
14402 struct remote_state *rs = get_remote_state ();
14403
14404 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14405 remote_vcont_probe ();
14406
14407 return rs->supports_vCont.s && rs->supports_vCont.S;
14408 }
14409 else
14410 return 0;
14411 }
14412
14413 /* Implementation of the to_execution_direction method for the remote
14414 target. */
14415
14416 enum exec_direction_kind
14417 remote_target::execution_direction ()
14418 {
14419 struct remote_state *rs = get_remote_state ();
14420
14421 return rs->last_resume_exec_dir;
14422 }
14423
14424 /* Return pointer to the thread_info struct which corresponds to
14425 THREAD_HANDLE (having length HANDLE_LEN). */
14426
14427 thread_info *
14428 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14429 int handle_len,
14430 inferior *inf)
14431 {
14432 for (thread_info *tp : all_non_exited_threads (this))
14433 {
14434 remote_thread_info *priv = get_remote_thread_info (tp);
14435
14436 if (tp->inf == inf && priv != NULL)
14437 {
14438 if (handle_len != priv->thread_handle.size ())
14439 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14440 handle_len, priv->thread_handle.size ());
14441 if (memcmp (thread_handle, priv->thread_handle.data (),
14442 handle_len) == 0)
14443 return tp;
14444 }
14445 }
14446
14447 return NULL;
14448 }
14449
14450 gdb::byte_vector
14451 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14452 {
14453 remote_thread_info *priv = get_remote_thread_info (tp);
14454 return priv->thread_handle;
14455 }
14456
14457 bool
14458 remote_target::can_async_p ()
14459 {
14460 /* This flag should be checked in the common target.c code. */
14461 gdb_assert (target_async_permitted);
14462
14463 /* We're async whenever the serial device can. */
14464 struct remote_state *rs = get_remote_state ();
14465 return serial_can_async_p (rs->remote_desc);
14466 }
14467
14468 bool
14469 remote_target::is_async_p ()
14470 {
14471 /* We're async whenever the serial device is. */
14472 struct remote_state *rs = get_remote_state ();
14473 return serial_is_async_p (rs->remote_desc);
14474 }
14475
14476 /* Pass the SERIAL event on and up to the client. One day this code
14477 will be able to delay notifying the client of an event until the
14478 point where an entire packet has been received. */
14479
14480 static serial_event_ftype remote_async_serial_handler;
14481
14482 static void
14483 remote_async_serial_handler (struct serial *scb, void *context)
14484 {
14485 /* Don't propogate error information up to the client. Instead let
14486 the client find out about the error by querying the target. */
14487 inferior_event_handler (INF_REG_EVENT);
14488 }
14489
14490 static void
14491 remote_async_inferior_event_handler (gdb_client_data data)
14492 {
14493 inferior_event_handler (INF_REG_EVENT);
14494 }
14495
14496 int
14497 remote_target::async_wait_fd ()
14498 {
14499 struct remote_state *rs = get_remote_state ();
14500 return rs->remote_desc->fd;
14501 }
14502
14503 void
14504 remote_target::async (int enable)
14505 {
14506 struct remote_state *rs = get_remote_state ();
14507
14508 if (enable)
14509 {
14510 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14511
14512 /* If there are pending events in the stop reply queue tell the
14513 event loop to process them. */
14514 if (!rs->stop_reply_queue.empty ())
14515 mark_async_event_handler (rs->remote_async_inferior_event_token);
14516 /* For simplicity, below we clear the pending events token
14517 without remembering whether it is marked, so here we always
14518 mark it. If there's actually no pending notification to
14519 process, this ends up being a no-op (other than a spurious
14520 event-loop wakeup). */
14521 if (target_is_non_stop_p ())
14522 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14523 }
14524 else
14525 {
14526 serial_async (rs->remote_desc, NULL, NULL);
14527 /* If the core is disabling async, it doesn't want to be
14528 disturbed with target events. Clear all async event sources
14529 too. */
14530 clear_async_event_handler (rs->remote_async_inferior_event_token);
14531 if (target_is_non_stop_p ())
14532 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14533 }
14534 }
14535
14536 /* Implementation of the to_thread_events method. */
14537
14538 void
14539 remote_target::thread_events (int enable)
14540 {
14541 struct remote_state *rs = get_remote_state ();
14542 size_t size = get_remote_packet_size ();
14543
14544 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14545 return;
14546
14547 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
14548 putpkt (rs->buf);
14549 getpkt (&rs->buf, 0);
14550
14551 switch (packet_ok (rs->buf,
14552 &remote_protocol_packets[PACKET_QThreadEvents]))
14553 {
14554 case PACKET_OK:
14555 if (strcmp (rs->buf.data (), "OK") != 0)
14556 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
14557 break;
14558 case PACKET_ERROR:
14559 warning (_("Remote failure reply: %s"), rs->buf.data ());
14560 break;
14561 case PACKET_UNKNOWN:
14562 break;
14563 }
14564 }
14565
14566 static void
14567 show_remote_cmd (const char *args, int from_tty)
14568 {
14569 /* We can't just use cmd_show_list here, because we want to skip
14570 the redundant "show remote Z-packet" and the legacy aliases. */
14571 struct cmd_list_element *list = remote_show_cmdlist;
14572 struct ui_out *uiout = current_uiout;
14573
14574 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14575 for (; list != NULL; list = list->next)
14576 if (strcmp (list->name, "Z-packet") == 0)
14577 continue;
14578 else if (list->type == not_set_cmd)
14579 /* Alias commands are exactly like the original, except they
14580 don't have the normal type. */
14581 continue;
14582 else
14583 {
14584 ui_out_emit_tuple option_emitter (uiout, "option");
14585
14586 uiout->field_string ("name", list->name);
14587 uiout->text (": ");
14588 if (list->type == show_cmd)
14589 do_show_command (NULL, from_tty, list);
14590 else
14591 cmd_func (list, NULL, from_tty);
14592 }
14593 }
14594
14595
14596 /* Function to be called whenever a new objfile (shlib) is detected. */
14597 static void
14598 remote_new_objfile (struct objfile *objfile)
14599 {
14600 remote_target *remote = get_current_remote_target ();
14601
14602 /* First, check whether the current inferior's process target is a remote
14603 target. */
14604 if (remote == nullptr)
14605 return;
14606
14607 /* When we are attaching or handling a fork child and the shared library
14608 subsystem reads the list of loaded libraries, we receive new objfile
14609 events in between each found library. The libraries are read in an
14610 undefined order, so if we gave the remote side a chance to look up
14611 symbols between each objfile, we might give it an inconsistent picture
14612 of the inferior. It could appear that a library A appears loaded but
14613 a library B does not, even though library A requires library B. That
14614 would present a state that couldn't normally exist in the inferior.
14615
14616 So, skip these events, we'll give the remote a chance to look up symbols
14617 once all the loaded libraries and their symbols are known to GDB. */
14618 if (current_inferior ()->in_initial_library_scan)
14619 return;
14620
14621 remote->remote_check_symbols ();
14622 }
14623
14624 /* Pull all the tracepoints defined on the target and create local
14625 data structures representing them. We don't want to create real
14626 tracepoints yet, we don't want to mess up the user's existing
14627 collection. */
14628
14629 int
14630 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14631 {
14632 struct remote_state *rs = get_remote_state ();
14633 char *p;
14634
14635 /* Ask for a first packet of tracepoint definition. */
14636 putpkt ("qTfP");
14637 getpkt (&rs->buf, 0);
14638 p = rs->buf.data ();
14639 while (*p && *p != 'l')
14640 {
14641 parse_tracepoint_definition (p, utpp);
14642 /* Ask for another packet of tracepoint definition. */
14643 putpkt ("qTsP");
14644 getpkt (&rs->buf, 0);
14645 p = rs->buf.data ();
14646 }
14647 return 0;
14648 }
14649
14650 int
14651 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14652 {
14653 struct remote_state *rs = get_remote_state ();
14654 char *p;
14655
14656 /* Ask for a first packet of variable definition. */
14657 putpkt ("qTfV");
14658 getpkt (&rs->buf, 0);
14659 p = rs->buf.data ();
14660 while (*p && *p != 'l')
14661 {
14662 parse_tsv_definition (p, utsvp);
14663 /* Ask for another packet of variable definition. */
14664 putpkt ("qTsV");
14665 getpkt (&rs->buf, 0);
14666 p = rs->buf.data ();
14667 }
14668 return 0;
14669 }
14670
14671 /* The "set/show range-stepping" show hook. */
14672
14673 static void
14674 show_range_stepping (struct ui_file *file, int from_tty,
14675 struct cmd_list_element *c,
14676 const char *value)
14677 {
14678 fprintf_filtered (file,
14679 _("Debugger's willingness to use range stepping "
14680 "is %s.\n"), value);
14681 }
14682
14683 /* Return true if the vCont;r action is supported by the remote
14684 stub. */
14685
14686 bool
14687 remote_target::vcont_r_supported ()
14688 {
14689 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14690 remote_vcont_probe ();
14691
14692 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14693 && get_remote_state ()->supports_vCont.r);
14694 }
14695
14696 /* The "set/show range-stepping" set hook. */
14697
14698 static void
14699 set_range_stepping (const char *ignore_args, int from_tty,
14700 struct cmd_list_element *c)
14701 {
14702 /* When enabling, check whether range stepping is actually supported
14703 by the target, and warn if not. */
14704 if (use_range_stepping)
14705 {
14706 remote_target *remote = get_current_remote_target ();
14707 if (remote == NULL
14708 || !remote->vcont_r_supported ())
14709 warning (_("Range stepping is not supported by the current target"));
14710 }
14711 }
14712
14713 static void
14714 show_remote_debug (struct ui_file *file, int from_tty,
14715 struct cmd_list_element *c, const char *value)
14716 {
14717 fprintf_filtered (file, _("Debugging of remote protocol is %s.\n"),
14718 value);
14719 }
14720
14721 static void
14722 show_remote_timeout (struct ui_file *file, int from_tty,
14723 struct cmd_list_element *c, const char *value)
14724 {
14725 fprintf_filtered (file,
14726 _("Timeout limit to wait for target to respond is %s.\n"),
14727 value);
14728 }
14729
14730 /* Implement the "supports_memory_tagging" target_ops method. */
14731
14732 bool
14733 remote_target::supports_memory_tagging ()
14734 {
14735 return remote_memory_tagging_p ();
14736 }
14737
14738 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
14739
14740 static void
14741 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14742 size_t len, int type)
14743 {
14744 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14745
14746 std::string request = string_printf ("qMemTags:%s,%s:%s",
14747 phex_nz (address, addr_size),
14748 phex_nz (len, sizeof (len)),
14749 phex_nz (type, sizeof (type)));
14750
14751 strcpy (packet.data (), request.c_str ());
14752 }
14753
14754 /* Parse the qMemTags packet reply into TAGS.
14755
14756 Return true if successful, false otherwise. */
14757
14758 static bool
14759 parse_fetch_memtags_reply (const gdb::char_vector &reply,
14760 gdb::byte_vector &tags)
14761 {
14762 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
14763 return false;
14764
14765 /* Copy the tag data. */
14766 tags = hex2bin (reply.data () + 1);
14767
14768 return true;
14769 }
14770
14771 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
14772
14773 static void
14774 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14775 size_t len, int type,
14776 const gdb::byte_vector &tags)
14777 {
14778 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14779
14780 /* Put together the main packet, address and length. */
14781 std::string request = string_printf ("QMemTags:%s,%s:%s:",
14782 phex_nz (address, addr_size),
14783 phex_nz (len, sizeof (len)),
14784 phex_nz (type, sizeof (type)));
14785 request += bin2hex (tags.data (), tags.size ());
14786
14787 /* Check if we have exceeded the maximum packet size. */
14788 if (packet.size () < request.length ())
14789 error (_("Contents too big for packet QMemTags."));
14790
14791 strcpy (packet.data (), request.c_str ());
14792 }
14793
14794 /* Implement the "fetch_memtags" target_ops method. */
14795
14796 bool
14797 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
14798 gdb::byte_vector &tags, int type)
14799 {
14800 /* Make sure the qMemTags packet is supported. */
14801 if (!remote_memory_tagging_p ())
14802 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
14803
14804 struct remote_state *rs = get_remote_state ();
14805
14806 create_fetch_memtags_request (rs->buf, address, len, type);
14807
14808 putpkt (rs->buf);
14809 getpkt (&rs->buf, 0);
14810
14811 return parse_fetch_memtags_reply (rs->buf, tags);
14812 }
14813
14814 /* Implement the "store_memtags" target_ops method. */
14815
14816 bool
14817 remote_target::store_memtags (CORE_ADDR address, size_t len,
14818 const gdb::byte_vector &tags, int type)
14819 {
14820 /* Make sure the QMemTags packet is supported. */
14821 if (!remote_memory_tagging_p ())
14822 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
14823
14824 struct remote_state *rs = get_remote_state ();
14825
14826 create_store_memtags_request (rs->buf, address, len, type, tags);
14827
14828 putpkt (rs->buf);
14829 getpkt (&rs->buf, 0);
14830
14831 /* Verify if the request was successful. */
14832 return packet_check_result (rs->buf.data ()) == PACKET_OK;
14833 }
14834
14835 /* Return true if remote target T is non-stop. */
14836
14837 bool
14838 remote_target_is_non_stop_p (remote_target *t)
14839 {
14840 scoped_restore_current_thread restore_thread;
14841 switch_to_target_no_thread (t);
14842
14843 return target_is_non_stop_p ();
14844 }
14845
14846 #if GDB_SELF_TEST
14847
14848 namespace selftests {
14849
14850 static void
14851 test_memory_tagging_functions ()
14852 {
14853 remote_target remote;
14854
14855 struct packet_config *config
14856 = &remote_protocol_packets[PACKET_memory_tagging_feature];
14857
14858 scoped_restore restore_memtag_support_
14859 = make_scoped_restore (&config->support);
14860
14861 /* Test memory tagging packet support. */
14862 config->support = PACKET_SUPPORT_UNKNOWN;
14863 SELF_CHECK (remote.supports_memory_tagging () == false);
14864 config->support = PACKET_DISABLE;
14865 SELF_CHECK (remote.supports_memory_tagging () == false);
14866 config->support = PACKET_ENABLE;
14867 SELF_CHECK (remote.supports_memory_tagging () == true);
14868
14869 /* Setup testing. */
14870 gdb::char_vector packet;
14871 gdb::byte_vector tags, bv;
14872 std::string expected, reply;
14873 packet.resize (32000);
14874
14875 /* Test creating a qMemTags request. */
14876
14877 expected = "qMemTags:0,0:0";
14878 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
14879 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14880
14881 expected = "qMemTags:deadbeef,10:1";
14882 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
14883 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14884
14885 /* Test parsing a qMemTags reply. */
14886
14887 /* Error reply, tags vector unmodified. */
14888 reply = "E00";
14889 strcpy (packet.data (), reply.c_str ());
14890 tags.resize (0);
14891 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
14892 SELF_CHECK (tags.size () == 0);
14893
14894 /* Valid reply, tags vector updated. */
14895 tags.resize (0);
14896 bv.resize (0);
14897
14898 for (int i = 0; i < 5; i++)
14899 bv.push_back (i);
14900
14901 reply = "m" + bin2hex (bv.data (), bv.size ());
14902 strcpy (packet.data (), reply.c_str ());
14903
14904 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
14905 SELF_CHECK (tags.size () == 5);
14906
14907 for (int i = 0; i < 5; i++)
14908 SELF_CHECK (tags[i] == i);
14909
14910 /* Test creating a QMemTags request. */
14911
14912 /* Empty tag data. */
14913 tags.resize (0);
14914 expected = "QMemTags:0,0:0:";
14915 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
14916 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14917 expected.length ()) == 0);
14918
14919 /* Non-empty tag data. */
14920 tags.resize (0);
14921 for (int i = 0; i < 5; i++)
14922 tags.push_back (i);
14923 expected = "QMemTags:deadbeef,ff:1:0001020304";
14924 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
14925 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14926 expected.length ()) == 0);
14927 }
14928
14929 } // namespace selftests
14930 #endif /* GDB_SELF_TEST */
14931
14932 void _initialize_remote ();
14933 void
14934 _initialize_remote ()
14935 {
14936 /* architecture specific data */
14937 remote_g_packet_data_handle =
14938 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14939
14940 add_target (remote_target_info, remote_target::open);
14941 add_target (extended_remote_target_info, extended_remote_target::open);
14942
14943 /* Hook into new objfile notification. */
14944 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
14945
14946 #if 0
14947 init_remote_threadtests ();
14948 #endif
14949
14950 /* set/show remote ... */
14951
14952 add_basic_prefix_cmd ("remote", class_maintenance, _("\
14953 Remote protocol specific variables.\n\
14954 Configure various remote-protocol specific variables such as\n\
14955 the packets being used."),
14956 &remote_set_cmdlist,
14957 0 /* allow-unknown */, &setlist);
14958 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14959 Remote protocol specific variables.\n\
14960 Configure various remote-protocol specific variables such as\n\
14961 the packets being used."),
14962 &remote_show_cmdlist,
14963 0 /* allow-unknown */, &showlist);
14964
14965 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14966 Compare section data on target to the exec file.\n\
14967 Argument is a single section name (default: all loaded sections).\n\
14968 To compare only read-only loaded sections, specify the -r option."),
14969 &cmdlist);
14970
14971 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
14972 Send an arbitrary packet to a remote target.\n\
14973 maintenance packet TEXT\n\
14974 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14975 this command sends the string TEXT to the inferior, and displays the\n\
14976 response packet. GDB supplies the initial `$' character, and the\n\
14977 terminating `#' character and checksum."),
14978 &maintenancelist);
14979
14980 set_show_commands remotebreak_cmds
14981 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14982 Set whether to send break if interrupted."), _("\
14983 Show whether to send break if interrupted."), _("\
14984 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14985 set_remotebreak, show_remotebreak,
14986 &setlist, &showlist);
14987 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
14988 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
14989
14990 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14991 interrupt_sequence_modes, &interrupt_sequence_mode,
14992 _("\
14993 Set interrupt sequence to remote target."), _("\
14994 Show interrupt sequence to remote target."), _("\
14995 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14996 NULL, show_interrupt_sequence,
14997 &remote_set_cmdlist,
14998 &remote_show_cmdlist);
14999
15000 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
15001 &interrupt_on_connect, _("\
15002 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15003 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15004 If set, interrupt sequence is sent to remote target."),
15005 NULL, NULL,
15006 &remote_set_cmdlist, &remote_show_cmdlist);
15007
15008 /* Install commands for configuring memory read/write packets. */
15009
15010 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
15011 Set the maximum number of bytes per memory write packet (deprecated)."),
15012 &setlist);
15013 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
15014 Show the maximum number of bytes per memory write packet (deprecated)."),
15015 &showlist);
15016 add_cmd ("memory-write-packet-size", no_class,
15017 set_memory_write_packet_size, _("\
15018 Set the maximum number of bytes per memory-write packet.\n\
15019 Specify the number of bytes in a packet or 0 (zero) for the\n\
15020 default packet size. The actual limit is further reduced\n\
15021 dependent on the target. Specify ``fixed'' to disable the\n\
15022 further restriction and ``limit'' to enable that restriction."),
15023 &remote_set_cmdlist);
15024 add_cmd ("memory-read-packet-size", no_class,
15025 set_memory_read_packet_size, _("\
15026 Set the maximum number of bytes per memory-read packet.\n\
15027 Specify the number of bytes in a packet or 0 (zero) for the\n\
15028 default packet size. The actual limit is further reduced\n\
15029 dependent on the target. Specify ``fixed'' to disable the\n\
15030 further restriction and ``limit'' to enable that restriction."),
15031 &remote_set_cmdlist);
15032 add_cmd ("memory-write-packet-size", no_class,
15033 show_memory_write_packet_size,
15034 _("Show the maximum number of bytes per memory-write packet."),
15035 &remote_show_cmdlist);
15036 add_cmd ("memory-read-packet-size", no_class,
15037 show_memory_read_packet_size,
15038 _("Show the maximum number of bytes per memory-read packet."),
15039 &remote_show_cmdlist);
15040
15041 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
15042 &remote_hw_watchpoint_limit, _("\
15043 Set the maximum number of target hardware watchpoints."), _("\
15044 Show the maximum number of target hardware watchpoints."), _("\
15045 Specify \"unlimited\" for unlimited hardware watchpoints."),
15046 NULL, show_hardware_watchpoint_limit,
15047 &remote_set_cmdlist,
15048 &remote_show_cmdlist);
15049 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15050 no_class,
15051 &remote_hw_watchpoint_length_limit, _("\
15052 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15053 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15054 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15055 NULL, show_hardware_watchpoint_length_limit,
15056 &remote_set_cmdlist, &remote_show_cmdlist);
15057 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
15058 &remote_hw_breakpoint_limit, _("\
15059 Set the maximum number of target hardware breakpoints."), _("\
15060 Show the maximum number of target hardware breakpoints."), _("\
15061 Specify \"unlimited\" for unlimited hardware breakpoints."),
15062 NULL, show_hardware_breakpoint_limit,
15063 &remote_set_cmdlist, &remote_show_cmdlist);
15064
15065 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15066 &remote_address_size, _("\
15067 Set the maximum size of the address (in bits) in a memory packet."), _("\
15068 Show the maximum size of the address (in bits) in a memory packet."), NULL,
15069 NULL,
15070 NULL, /* FIXME: i18n: */
15071 &setlist, &showlist);
15072
15073 init_all_packet_configs ();
15074
15075 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
15076 "X", "binary-download", 1);
15077
15078 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
15079 "vCont", "verbose-resume", 0);
15080
15081 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
15082 "QPassSignals", "pass-signals", 0);
15083
15084 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
15085 "QCatchSyscalls", "catch-syscalls", 0);
15086
15087 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
15088 "QProgramSignals", "program-signals", 0);
15089
15090 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
15091 "QSetWorkingDir", "set-working-dir", 0);
15092
15093 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
15094 "QStartupWithShell", "startup-with-shell", 0);
15095
15096 add_packet_config_cmd (&remote_protocol_packets
15097 [PACKET_QEnvironmentHexEncoded],
15098 "QEnvironmentHexEncoded", "environment-hex-encoded",
15099 0);
15100
15101 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
15102 "QEnvironmentReset", "environment-reset",
15103 0);
15104
15105 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
15106 "QEnvironmentUnset", "environment-unset",
15107 0);
15108
15109 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
15110 "qSymbol", "symbol-lookup", 0);
15111
15112 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
15113 "P", "set-register", 1);
15114
15115 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
15116 "p", "fetch-register", 1);
15117
15118 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
15119 "Z0", "software-breakpoint", 0);
15120
15121 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
15122 "Z1", "hardware-breakpoint", 0);
15123
15124 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
15125 "Z2", "write-watchpoint", 0);
15126
15127 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
15128 "Z3", "read-watchpoint", 0);
15129
15130 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
15131 "Z4", "access-watchpoint", 0);
15132
15133 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
15134 "qXfer:auxv:read", "read-aux-vector", 0);
15135
15136 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
15137 "qXfer:exec-file:read", "pid-to-exec-file", 0);
15138
15139 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
15140 "qXfer:features:read", "target-features", 0);
15141
15142 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
15143 "qXfer:libraries:read", "library-info", 0);
15144
15145 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
15146 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15147
15148 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
15149 "qXfer:memory-map:read", "memory-map", 0);
15150
15151 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
15152 "qXfer:osdata:read", "osdata", 0);
15153
15154 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
15155 "qXfer:threads:read", "threads", 0);
15156
15157 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
15158 "qXfer:siginfo:read", "read-siginfo-object", 0);
15159
15160 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
15161 "qXfer:siginfo:write", "write-siginfo-object", 0);
15162
15163 add_packet_config_cmd
15164 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
15165 "qXfer:traceframe-info:read", "traceframe-info", 0);
15166
15167 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
15168 "qXfer:uib:read", "unwind-info-block", 0);
15169
15170 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
15171 "qGetTLSAddr", "get-thread-local-storage-address",
15172 0);
15173
15174 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
15175 "qGetTIBAddr", "get-thread-information-block-address",
15176 0);
15177
15178 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
15179 "bc", "reverse-continue", 0);
15180
15181 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
15182 "bs", "reverse-step", 0);
15183
15184 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
15185 "qSupported", "supported-packets", 0);
15186
15187 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
15188 "qSearch:memory", "search-memory", 0);
15189
15190 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
15191 "qTStatus", "trace-status", 0);
15192
15193 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
15194 "vFile:setfs", "hostio-setfs", 0);
15195
15196 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
15197 "vFile:open", "hostio-open", 0);
15198
15199 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
15200 "vFile:pread", "hostio-pread", 0);
15201
15202 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
15203 "vFile:pwrite", "hostio-pwrite", 0);
15204
15205 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
15206 "vFile:close", "hostio-close", 0);
15207
15208 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
15209 "vFile:unlink", "hostio-unlink", 0);
15210
15211 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
15212 "vFile:readlink", "hostio-readlink", 0);
15213
15214 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
15215 "vFile:fstat", "hostio-fstat", 0);
15216
15217 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
15218 "vAttach", "attach", 0);
15219
15220 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
15221 "vRun", "run", 0);
15222
15223 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
15224 "QStartNoAckMode", "noack", 0);
15225
15226 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
15227 "vKill", "kill", 0);
15228
15229 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
15230 "qAttached", "query-attached", 0);
15231
15232 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
15233 "ConditionalTracepoints",
15234 "conditional-tracepoints", 0);
15235
15236 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
15237 "ConditionalBreakpoints",
15238 "conditional-breakpoints", 0);
15239
15240 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
15241 "BreakpointCommands",
15242 "breakpoint-commands", 0);
15243
15244 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
15245 "FastTracepoints", "fast-tracepoints", 0);
15246
15247 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
15248 "TracepointSource", "TracepointSource", 0);
15249
15250 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
15251 "QAllow", "allow", 0);
15252
15253 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
15254 "StaticTracepoints", "static-tracepoints", 0);
15255
15256 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
15257 "InstallInTrace", "install-in-trace", 0);
15258
15259 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
15260 "qXfer:statictrace:read", "read-sdata-object", 0);
15261
15262 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
15263 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
15264
15265 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
15266 "QDisableRandomization", "disable-randomization", 0);
15267
15268 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
15269 "QAgent", "agent", 0);
15270
15271 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
15272 "QTBuffer:size", "trace-buffer-size", 0);
15273
15274 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
15275 "Qbtrace:off", "disable-btrace", 0);
15276
15277 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
15278 "Qbtrace:bts", "enable-btrace-bts", 0);
15279
15280 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
15281 "Qbtrace:pt", "enable-btrace-pt", 0);
15282
15283 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
15284 "qXfer:btrace", "read-btrace", 0);
15285
15286 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
15287 "qXfer:btrace-conf", "read-btrace-conf", 0);
15288
15289 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
15290 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
15291
15292 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
15293 "multiprocess-feature", "multiprocess-feature", 0);
15294
15295 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
15296 "swbreak-feature", "swbreak-feature", 0);
15297
15298 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
15299 "hwbreak-feature", "hwbreak-feature", 0);
15300
15301 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
15302 "fork-event-feature", "fork-event-feature", 0);
15303
15304 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
15305 "vfork-event-feature", "vfork-event-feature", 0);
15306
15307 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
15308 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
15309
15310 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
15311 "vContSupported", "verbose-resume-supported", 0);
15312
15313 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
15314 "exec-event-feature", "exec-event-feature", 0);
15315
15316 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
15317 "vCtrlC", "ctrl-c", 0);
15318
15319 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
15320 "QThreadEvents", "thread-events", 0);
15321
15322 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
15323 "N stop reply", "no-resumed-stop-reply", 0);
15324
15325 add_packet_config_cmd (&remote_protocol_packets[PACKET_memory_tagging_feature],
15326 "memory-tagging-feature", "memory-tagging-feature", 0);
15327
15328 /* Assert that we've registered "set remote foo-packet" commands
15329 for all packet configs. */
15330 {
15331 int i;
15332
15333 for (i = 0; i < PACKET_MAX; i++)
15334 {
15335 /* Ideally all configs would have a command associated. Some
15336 still don't though. */
15337 int excepted;
15338
15339 switch (i)
15340 {
15341 case PACKET_QNonStop:
15342 case PACKET_EnableDisableTracepoints_feature:
15343 case PACKET_tracenz_feature:
15344 case PACKET_DisconnectedTracing_feature:
15345 case PACKET_augmented_libraries_svr4_read_feature:
15346 case PACKET_qCRC:
15347 /* Additions to this list need to be well justified:
15348 pre-existing packets are OK; new packets are not. */
15349 excepted = 1;
15350 break;
15351 default:
15352 excepted = 0;
15353 break;
15354 }
15355
15356 /* This catches both forgetting to add a config command, and
15357 forgetting to remove a packet from the exception list. */
15358 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
15359 }
15360 }
15361
15362 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15363 Z sub-packet has its own set and show commands, but users may
15364 have sets to this variable in their .gdbinit files (or in their
15365 documentation). */
15366 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
15367 &remote_Z_packet_detect, _("\
15368 Set use of remote protocol `Z' packets."), _("\
15369 Show use of remote protocol `Z' packets."), _("\
15370 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
15371 packets."),
15372 set_remote_protocol_Z_packet_cmd,
15373 show_remote_protocol_Z_packet_cmd,
15374 /* FIXME: i18n: Use of remote protocol
15375 `Z' packets is %s. */
15376 &remote_set_cmdlist, &remote_show_cmdlist);
15377
15378 add_basic_prefix_cmd ("remote", class_files, _("\
15379 Manipulate files on the remote system.\n\
15380 Transfer files to and from the remote target system."),
15381 &remote_cmdlist,
15382 0 /* allow-unknown */, &cmdlist);
15383
15384 add_cmd ("put", class_files, remote_put_command,
15385 _("Copy a local file to the remote system."),
15386 &remote_cmdlist);
15387
15388 add_cmd ("get", class_files, remote_get_command,
15389 _("Copy a remote file to the local system."),
15390 &remote_cmdlist);
15391
15392 add_cmd ("delete", class_files, remote_delete_command,
15393 _("Delete a remote file."),
15394 &remote_cmdlist);
15395
15396 add_setshow_string_noescape_cmd ("exec-file", class_files,
15397 &remote_exec_file_var, _("\
15398 Set the remote pathname for \"run\"."), _("\
15399 Show the remote pathname for \"run\"."), NULL,
15400 set_remote_exec_file,
15401 show_remote_exec_file,
15402 &remote_set_cmdlist,
15403 &remote_show_cmdlist);
15404
15405 add_setshow_boolean_cmd ("range-stepping", class_run,
15406 &use_range_stepping, _("\
15407 Enable or disable range stepping."), _("\
15408 Show whether target-assisted range stepping is enabled."), _("\
15409 If on, and the target supports it, when stepping a source line, GDB\n\
15410 tells the target to step the corresponding range of addresses itself instead\n\
15411 of issuing multiple single-steps. This speeds up source level\n\
15412 stepping. If off, GDB always issues single-steps, even if range\n\
15413 stepping is supported by the target. The default is on."),
15414 set_range_stepping,
15415 show_range_stepping,
15416 &setlist,
15417 &showlist);
15418
15419 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15420 Set watchdog timer."), _("\
15421 Show watchdog timer."), _("\
15422 When non-zero, this timeout is used instead of waiting forever for a target\n\
15423 to finish a low-level step or continue operation. If the specified amount\n\
15424 of time passes without a response from the target, an error occurs."),
15425 NULL,
15426 show_watchdog,
15427 &setlist, &showlist);
15428
15429 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15430 &remote_packet_max_chars, _("\
15431 Set the maximum number of characters to display for each remote packet."), _("\
15432 Show the maximum number of characters to display for each remote packet."), _("\
15433 Specify \"unlimited\" to display all the characters."),
15434 NULL, show_remote_packet_max_chars,
15435 &setdebuglist, &showdebuglist);
15436
15437 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15438 _("Set debugging of remote protocol."),
15439 _("Show debugging of remote protocol."),
15440 _("\
15441 When enabled, each packet sent or received with the remote target\n\
15442 is displayed."),
15443 NULL,
15444 show_remote_debug,
15445 &setdebuglist, &showdebuglist);
15446
15447 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15448 &remote_timeout, _("\
15449 Set timeout limit to wait for target to respond."), _("\
15450 Show timeout limit to wait for target to respond."), _("\
15451 This value is used to set the time limit for gdb to wait for a response\n\
15452 from the target."),
15453 NULL,
15454 show_remote_timeout,
15455 &setlist, &showlist);
15456
15457 /* Eventually initialize fileio. See fileio.c */
15458 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
15459
15460 #if GDB_SELF_TEST
15461 selftests::register_test ("remote_memory_tagging",
15462 selftests::test_memory_tagging_functions);
15463 #endif
15464 }