]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/remote.c
gdbsupport: convert FILEIO_* macros to an enum
[thirdparty/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
4a94e368 3 Copyright (C) 1988-2022 Free Software Foundation, Inc.
c906108c 4
c5aa993b
JM
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
a9762ec7 9 the Free Software Foundation; either version 3 of the License, or
c5aa993b
JM
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
a9762ec7 18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5aa993b 19
23860348 20/* See the GDB User Guide for details of the GDB remote protocol. */
c5aa993b 21
c906108c 22#include "defs.h"
c906108c
SS
23#include <ctype.h>
24#include <fcntl.h>
c906108c 25#include "inferior.h"
45741a9c 26#include "infrun.h"
c906108c
SS
27#include "bfd.h"
28#include "symfile.h"
29#include "target.h"
3b3dac9b 30#include "process-stratum-target.h"
c906108c
SS
31#include "gdbcmd.h"
32#include "objfiles.h"
33#include "gdb-stabs.h"
34#include "gdbthread.h"
c2c6d25f 35#include "remote.h"
722247f1 36#include "remote-notif.h"
4e052eda 37#include "regcache.h"
fd0407d6 38#include "value.h"
76727919 39#include "observable.h"
a77053c2 40#include "solib.h"
37a105a1
DJ
41#include "cli/cli-decode.h"
42#include "cli/cli-setshow.h"
424163ea 43#include "target-descriptions.h"
a4453b7e 44#include "gdb_bfd.h"
268a13a5
TT
45#include "gdbsupport/filestuff.h"
46#include "gdbsupport/rsp-low.h"
6b940e6a 47#include "disasm.h"
f00aae0f 48#include "location.h"
c906108c 49
268a13a5 50#include "gdbsupport/gdb_sys_time.h"
c906108c 51
400b5eca 52#include "gdbsupport/event-loop.h"
c2c6d25f 53#include "event-top.h"
2acceee2 54#include "inf-loop.h"
43ff13b4 55
c906108c
SS
56#include <signal.h>
57#include "serial.h"
58
7e10abd1 59#include "gdbcore.h"
6240bebf 60
449092f6 61#include "remote-fileio.h"
198f946f 62#include "gdbsupport/fileio.h"
53ce3c39 63#include <sys/stat.h>
dc146f7c 64#include "xml-support.h"
449092f6 65
fd79ecee
DJ
66#include "memory-map.h"
67
35b1e5cc
SS
68#include "tracepoint.h"
69#include "ax.h"
70#include "ax-gdb.h"
268a13a5 71#include "gdbsupport/agent.h"
9accd112 72#include "btrace.h"
c0272db5 73#include "record-btrace.h"
325fac50 74#include <algorithm>
268a13a5
TT
75#include "gdbsupport/scoped_restore.h"
76#include "gdbsupport/environ.h"
77#include "gdbsupport/byte-vector.h"
4a72de73 78#include "gdbsupport/search.h"
39ef2f62 79#include <algorithm>
9d6eea31 80#include <unordered_map>
93b54c8e 81#include "async-event.h"
754487e2 82#include "gdbsupport/selftest.h"
35b1e5cc 83
f6ac5f3d
PA
84/* The remote target. */
85
d9f719f1
PA
86static const char remote_doc[] = N_("\
87Use a remote computer via a serial line, using a gdb-specific protocol.\n\
88Specify the serial device it is connected to\n\
89(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
90
cda09ec9
SM
91/* See remote.h */
92
02349803 93bool remote_debug = false;
cda09ec9 94
6b8edb51
PA
95#define OPAQUETHREADBYTES 8
96
97/* a 64 bit opaque identifier */
98typedef unsigned char threadref[OPAQUETHREADBYTES];
99
100struct gdb_ext_thread_info;
101struct threads_listing_context;
102typedef int (*rmt_thread_action) (threadref *ref, void *context);
103struct protocol_feature;
104struct packet_reg;
105
106struct stop_reply;
32603266 107typedef std::unique_ptr<stop_reply> stop_reply_up;
6b8edb51
PA
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
113enum 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
123enum packet_result
124{
125 PACKET_ERROR,
126 PACKET_OK,
127 PACKET_UNKNOWN
128};
129
130struct threads_listing_context;
3c69da40
PA
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
137struct 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
405feb71 152/* About this many threadids fit in a packet. */
3c69da40
PA
153
154#define MAXTHREADLISTRESULTS 32
155
156/* Data for the vFile:pread readahead cache. */
157
158struct 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
191struct 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
203struct 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
231class remote_state
232{
233public:
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
241public: /* 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.
8d64371b 246 The size of the buffer is always at least REMOTE_PACKET_SIZE;
3c69da40
PA
247 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
248 packets. */
8d64371b 249 gdb::char_vector buf;
3c69da40
PA
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
3c69da40
PA
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;
5b6d1e4f
PA
279 /* Whether vCont support was probed already. This is a workaround
280 until packet_support is per-connection. */
281 bool supports_vCont_probed;
3c69da40
PA
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. */
953edf2b 369 std::vector<stop_reply_up> stop_reply_queue;
3c69da40
PA
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
384private:
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};
6b8edb51 391
d9f719f1
PA
392static const target_info remote_target_info = {
393 "remote",
ae9adb36 394 N_("Remote target using gdb-specific protocol"),
d9f719f1
PA
395 remote_doc
396};
397
3b3dac9b 398class remote_target : public process_stratum_target
f6ac5f3d
PA
399{
400public:
3b3dac9b 401 remote_target () = default;
6b8edb51 402 ~remote_target () override;
f6ac5f3d 403
d9f719f1
PA
404 const target_info &info () const override
405 { return remote_target_info; }
f6ac5f3d 406
121b3efd
PA
407 const char *connection_string () override;
408
f6ac5f3d
PA
409 thread_control_capabilities get_thread_control_capabilities () override
410 { return tc_schedlock; }
411
d9f719f1
PA
412 /* Open a remote connection. */
413 static void open (const char *, int);
414
f6ac5f3d
PA
415 void close () override;
416
417 void detach (inferior *, int) override;
418 void disconnect (const char *, int) override;
419
1192f124 420 void commit_resumed () override;
f6ac5f3d 421 void resume (ptid_t, int, enum gdb_signal) override;
b60cea74 422 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
b4b1a226 423 bool has_pending_events () override;
f6ac5f3d
PA
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
f6ac5f3d
PA
429 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
430
431 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
432 enum remove_bp_reason) override;
433
434
57810aa7
PA
435 bool stopped_by_sw_breakpoint () override;
436 bool supports_stopped_by_sw_breakpoint () override;
f6ac5f3d 437
57810aa7 438 bool stopped_by_hw_breakpoint () override;
f6ac5f3d 439
57810aa7 440 bool supports_stopped_by_hw_breakpoint () override;
f6ac5f3d 441
57810aa7 442 bool stopped_by_watchpoint () override;
f6ac5f3d 443
57810aa7 444 bool stopped_data_address (CORE_ADDR *) override;
f6ac5f3d 445
57810aa7 446 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
f6ac5f3d
PA
447
448 int can_use_hw_breakpoint (enum bptype, int, int) override;
449
450 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
451
452 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
453
454 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
455
456 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
457 struct expression *) override;
458
459 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
460 struct expression *) override;
461
462 void kill () override;
463
464 void load (const char *, int) override;
465
466 void mourn_inferior () override;
467
adc6a863 468 void pass_signals (gdb::array_view<const unsigned char>) override;
f6ac5f3d
PA
469
470 int set_syscall_catchpoint (int, bool, int,
471 gdb::array_view<const int>) override;
472
adc6a863 473 void program_signals (gdb::array_view<const unsigned char>) override;
f6ac5f3d 474
57810aa7 475 bool thread_alive (ptid_t ptid) override;
f6ac5f3d
PA
476
477 const char *thread_name (struct thread_info *) override;
478
479 void update_thread_list () override;
480
a068643d 481 std::string pid_to_str (ptid_t) override;
f6ac5f3d
PA
482
483 const char *extra_thread_info (struct thread_info *) override;
484
c80e29db 485 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
f6ac5f3d
PA
486
487 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
488 int handle_len,
489 inferior *inf) override;
490
3d6c6204
KB
491 gdb::byte_vector thread_info_to_thread_handle (struct thread_info *tp)
492 override;
493
f6ac5f3d
PA
494 void stop (ptid_t) override;
495
496 void interrupt () override;
497
498 void pass_ctrlc () override;
499
500 enum target_xfer_status xfer_partial (enum target_object object,
501 const char *annex,
502 gdb_byte *readbuf,
503 const gdb_byte *writebuf,
504 ULONGEST offset, ULONGEST len,
505 ULONGEST *xfered_len) override;
506
507 ULONGEST get_memory_xfer_limit () override;
508
509 void rcmd (const char *command, struct ui_file *output) override;
510
0e90c441 511 const char *pid_to_exec_file (int pid) override;
f6ac5f3d
PA
512
513 void log_command (const char *cmd) override
514 {
515 serial_log_command (this, cmd);
516 }
517
518 CORE_ADDR get_thread_local_address (ptid_t ptid,
519 CORE_ADDR load_module_addr,
520 CORE_ADDR offset) override;
521
57810aa7 522 bool can_execute_reverse () override;
f6ac5f3d
PA
523
524 std::vector<mem_region> memory_map () override;
525
526 void flash_erase (ULONGEST address, LONGEST length) override;
527
528 void flash_done () override;
529
530 const struct target_desc *read_description () override;
531
532 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
533 const gdb_byte *pattern, ULONGEST pattern_len,
534 CORE_ADDR *found_addrp) override;
535
57810aa7 536 bool can_async_p () override;
f6ac5f3d 537
57810aa7 538 bool is_async_p () override;
f6ac5f3d 539
4a570176 540 void async (bool) override;
f6ac5f3d 541
5b6d1e4f
PA
542 int async_wait_fd () override;
543
f6ac5f3d
PA
544 void thread_events (int) override;
545
546 int can_do_single_step () override;
547
548 void terminal_inferior () override;
549
550 void terminal_ours () override;
551
57810aa7 552 bool supports_non_stop () override;
f6ac5f3d 553
57810aa7 554 bool supports_multi_process () override;
f6ac5f3d 555
57810aa7 556 bool supports_disable_randomization () override;
f6ac5f3d 557
57810aa7 558 bool filesystem_is_local () override;
f6ac5f3d
PA
559
560
561 int fileio_open (struct inferior *inf, const char *filename,
562 int flags, int mode, int warn_if_slow,
b872057a 563 fileio_error *target_errno) override;
f6ac5f3d
PA
564
565 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
b872057a 566 ULONGEST offset, fileio_error *target_errno) override;
f6ac5f3d
PA
567
568 int fileio_pread (int fd, gdb_byte *read_buf, int len,
b872057a 569 ULONGEST offset, fileio_error *target_errno) override;
f6ac5f3d 570
b872057a 571 int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
f6ac5f3d 572
b872057a 573 int fileio_close (int fd, fileio_error *target_errno) override;
f6ac5f3d
PA
574
575 int fileio_unlink (struct inferior *inf,
576 const char *filename,
b872057a 577 fileio_error *target_errno) override;
f6ac5f3d
PA
578
579 gdb::optional<std::string>
580 fileio_readlink (struct inferior *inf,
581 const char *filename,
b872057a 582 fileio_error *target_errno) override;
f6ac5f3d 583
57810aa7 584 bool supports_enable_disable_tracepoint () override;
f6ac5f3d 585
57810aa7 586 bool supports_string_tracing () override;
f6ac5f3d 587
57810aa7 588 bool supports_evaluation_of_breakpoint_conditions () override;
f6ac5f3d 589
57810aa7 590 bool can_run_breakpoint_commands () override;
f6ac5f3d
PA
591
592 void trace_init () override;
593
594 void download_tracepoint (struct bp_location *location) override;
595
57810aa7 596 bool can_download_tracepoint () override;
f6ac5f3d
PA
597
598 void download_trace_state_variable (const trace_state_variable &tsv) override;
599
600 void enable_tracepoint (struct bp_location *location) override;
601
602 void disable_tracepoint (struct bp_location *location) override;
603
604 void trace_set_readonly_regions () override;
605
606 void trace_start () override;
607
608 int get_trace_status (struct trace_status *ts) override;
609
610 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
611 override;
612
613 void trace_stop () override;
614
615 int trace_find (enum trace_find_type type, int num,
616 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
617
57810aa7 618 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
f6ac5f3d
PA
619
620 int save_trace_data (const char *filename) override;
621
622 int upload_tracepoints (struct uploaded_tp **utpp) override;
623
624 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
625
626 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
627
628 int get_min_fast_tracepoint_insn_len () override;
629
630 void set_disconnected_tracing (int val) override;
631
632 void set_circular_trace_buffer (int val) override;
633
634 void set_trace_buffer_size (LONGEST val) override;
635
57810aa7
PA
636 bool set_trace_notes (const char *user, const char *notes,
637 const char *stopnotes) override;
f6ac5f3d
PA
638
639 int core_of_thread (ptid_t ptid) override;
640
641 int verify_memory (const gdb_byte *data,
642 CORE_ADDR memaddr, ULONGEST size) override;
643
644
57810aa7 645 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
f6ac5f3d
PA
646
647 void set_permissions () override;
648
649 bool static_tracepoint_marker_at (CORE_ADDR,
650 struct static_tracepoint_marker *marker)
651 override;
652
653 std::vector<static_tracepoint_marker>
654 static_tracepoint_markers_by_strid (const char *id) override;
655
656 traceframe_info_up traceframe_info () override;
657
57810aa7
PA
658 bool use_agent (bool use) override;
659 bool can_use_agent () override;
f6ac5f3d 660
696c0d5e
MM
661 struct btrace_target_info *
662 enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
f6ac5f3d
PA
663
664 void disable_btrace (struct btrace_target_info *tinfo) override;
665
666 void teardown_btrace (struct btrace_target_info *tinfo) override;
667
668 enum btrace_error read_btrace (struct btrace_data *data,
669 struct btrace_target_info *btinfo,
670 enum btrace_read_type type) override;
671
672 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
57810aa7 673 bool augmented_libraries_svr4_read () override;
82d1f134 674 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
294c36eb 675 void follow_exec (inferior *, ptid_t, const char *) override;
f6ac5f3d
PA
676 int insert_fork_catchpoint (int) override;
677 int remove_fork_catchpoint (int) override;
678 int insert_vfork_catchpoint (int) override;
679 int remove_vfork_catchpoint (int) override;
680 int insert_exec_catchpoint (int) override;
681 int remove_exec_catchpoint (int) override;
682 enum exec_direction_kind execution_direction () override;
683
dbe692af
LM
684 bool supports_memory_tagging () override;
685
686 bool fetch_memtags (CORE_ADDR address, size_t len,
687 gdb::byte_vector &tags, int type) override;
688
689 bool store_memtags (CORE_ADDR address, size_t len,
690 const gdb::byte_vector &tags, int type) override;
691
6b8edb51
PA
692public: /* Remote specific methods. */
693
694 void remote_download_command_source (int num, ULONGEST addr,
695 struct command_line *cmds);
696
697 void remote_file_put (const char *local_file, const char *remote_file,
698 int from_tty);
699 void remote_file_get (const char *remote_file, const char *local_file,
700 int from_tty);
701 void remote_file_delete (const char *remote_file, int from_tty);
702
703 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
b872057a 704 ULONGEST offset, fileio_error *remote_errno);
6b8edb51 705 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
b872057a 706 ULONGEST offset, fileio_error *remote_errno);
6b8edb51 707 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
b872057a 708 ULONGEST offset, fileio_error *remote_errno);
6b8edb51
PA
709
710 int remote_hostio_send_command (int command_bytes, int which_packet,
b872057a 711 fileio_error *remote_errno, const char **attachment,
6b8edb51
PA
712 int *attachment_len);
713 int remote_hostio_set_filesystem (struct inferior *inf,
b872057a 714 fileio_error *remote_errno);
6b8edb51
PA
715 /* We should get rid of this and use fileio_open directly. */
716 int remote_hostio_open (struct inferior *inf, const char *filename,
717 int flags, int mode, int warn_if_slow,
b872057a
SM
718 fileio_error *remote_errno);
719 int remote_hostio_close (int fd, fileio_error *remote_errno);
6b8edb51
PA
720
721 int remote_hostio_unlink (inferior *inf, const char *filename,
b872057a 722 fileio_error *remote_errno);
6b8edb51
PA
723
724 struct remote_state *get_remote_state ();
725
726 long get_remote_packet_size (void);
727 long get_memory_packet_size (struct memory_packet_config *config);
728
729 long get_memory_write_packet_size ();
730 long get_memory_read_packet_size ();
731
732 char *append_pending_thread_resumptions (char *p, char *endp,
733 ptid_t ptid);
d9f719f1 734 static void open_1 (const char *name, int from_tty, int extended_p);
f6ac5f3d 735 void start_remote (int from_tty, int extended_p);
00431a78 736 void remote_detach_1 (struct inferior *inf, int from_tty);
6b8edb51
PA
737
738 char *append_resumption (char *p, char *endp,
739 ptid_t ptid, int step, gdb_signal siggnal);
d51926f0 740 int remote_resume_with_vcont (ptid_t scope_ptid, int step,
6b8edb51
PA
741 gdb_signal siggnal);
742
64d38fdd 743 thread_info *add_current_inferior_and_thread (const char *wait_status);
6b8edb51
PA
744
745 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
b60cea74 746 target_wait_flags options);
6b8edb51 747 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
b60cea74 748 target_wait_flags options);
6b8edb51
PA
749
750 ptid_t process_stop_reply (struct stop_reply *stop_reply,
751 target_waitstatus *status);
752
8f66807b 753 ptid_t select_thread_for_ambiguous_stop_reply
c272a98c 754 (const struct target_waitstatus &status);
8f66807b 755
8a82de58 756 void remote_notice_new_inferior (ptid_t currthread, bool executing);
6b8edb51 757
1edb66d8 758 void print_one_stopped_thread (thread_info *thread);
6b8edb51
PA
759 void process_initial_stop_replies (int from_tty);
760
b622494e
AB
761 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
762 bool silent_p);
6b8edb51
PA
763
764 void btrace_sync_conf (const btrace_config *conf);
765
766 void remote_btrace_maybe_reopen ();
767
768 void remove_new_fork_children (threads_listing_context *context);
28561a65 769 void kill_new_fork_children (inferior *inf);
6b8edb51
PA
770 void discard_pending_stop_replies (struct inferior *inf);
771 int stop_reply_queue_length ();
772
773 void check_pending_events_prevent_wildcard_vcont
2f63ec5c 774 (bool *may_global_wildcard_vcont);
6b8edb51
PA
775
776 void discard_pending_stop_replies_in_queue ();
777 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
778 struct stop_reply *queued_stop_reply (ptid_t ptid);
779 int peek_stop_reply (ptid_t ptid);
bb277751 780 void remote_parse_stop_reply (const char *buf, stop_reply *event);
6b8edb51
PA
781
782 void remote_stop_ns (ptid_t ptid);
783 void remote_interrupt_as ();
784 void remote_interrupt_ns ();
785
786 char *remote_get_noisy_reply ();
787 int remote_query_attached (int pid);
9ab8741a 788 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
6b8edb51
PA
789 int try_open_exec);
790
791 ptid_t remote_current_thread (ptid_t oldpid);
e3b2741b 792 ptid_t get_current_thread (const char *wait_status);
6b8edb51
PA
793
794 void set_thread (ptid_t ptid, int gen);
795 void set_general_thread (ptid_t ptid);
796 void set_continue_thread (ptid_t ptid);
797 void set_general_process ();
798
799 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
800
cecb1912 801 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
6b8edb51
PA
802 gdb_ext_thread_info *info);
803 int remote_get_threadinfo (threadref *threadid, int fieldset,
804 gdb_ext_thread_info *info);
805
cecb1912 806 int parse_threadlist_response (const char *pkt, int result_limit,
6b8edb51
PA
807 threadref *original_echo,
808 threadref *resultlist,
809 int *doneflag);
810 int remote_get_threadlist (int startflag, threadref *nextthread,
811 int result_limit, int *done, int *result_count,
812 threadref *threadlist);
813
814 int remote_threadlist_iterator (rmt_thread_action stepfunction,
815 void *context, int looplimit);
816
817 int remote_get_threads_with_ql (threads_listing_context *context);
818 int remote_get_threads_with_qxfer (threads_listing_context *context);
819 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
820
821 void extended_remote_restart ();
822
823 void get_offsets ();
824
825 void remote_check_symbols ();
826
827 void remote_supported_packet (const struct protocol_feature *feature,
828 enum packet_support support,
829 const char *argument);
830
831 void remote_query_supported ();
832
833 void remote_packet_size (const protocol_feature *feature,
834 packet_support support, const char *value);
835
836 void remote_serial_quit_handler ();
837
838 void remote_detach_pid (int pid);
839
840 void remote_vcont_probe ();
841
842 void remote_resume_with_hc (ptid_t ptid, int step,
843 gdb_signal siggnal);
844
845 void send_interrupt_sequence ();
846 void interrupt_query ();
847
848 void remote_notif_get_pending_events (notif_client *nc);
849
850 int fetch_register_using_p (struct regcache *regcache,
851 packet_reg *reg);
852 int send_g_packet ();
853 void process_g_packet (struct regcache *regcache);
854 void fetch_registers_using_g (struct regcache *regcache);
855 int store_register_using_P (const struct regcache *regcache,
856 packet_reg *reg);
857 void store_registers_using_G (const struct regcache *regcache);
858
859 void set_remote_traceframe ();
860
861 void check_binary_download (CORE_ADDR addr);
862
863 target_xfer_status remote_write_bytes_aux (const char *header,
864 CORE_ADDR memaddr,
865 const gdb_byte *myaddr,
866 ULONGEST len_units,
867 int unit_size,
868 ULONGEST *xfered_len_units,
869 char packet_format,
870 int use_length);
871
872 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
873 const gdb_byte *myaddr, ULONGEST len,
874 int unit_size, ULONGEST *xfered_len);
875
876 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
877 ULONGEST len_units,
878 int unit_size, ULONGEST *xfered_len_units);
879
880 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
881 ULONGEST memaddr,
882 ULONGEST len,
883 int unit_size,
884 ULONGEST *xfered_len);
885
886 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
887 gdb_byte *myaddr, ULONGEST len,
888 int unit_size,
889 ULONGEST *xfered_len);
890
891 packet_result remote_send_printf (const char *format, ...)
892 ATTRIBUTE_PRINTF (2, 3);
893
894 target_xfer_status remote_flash_write (ULONGEST address,
895 ULONGEST length, ULONGEST *xfered_len,
896 const gdb_byte *data);
897
898 int readchar (int timeout);
899
900 void remote_serial_write (const char *str, int len);
901
902 int putpkt (const char *buf);
903 int putpkt_binary (const char *buf, int cnt);
904
8d64371b
TT
905 int putpkt (const gdb::char_vector &buf)
906 {
907 return putpkt (buf.data ());
908 }
909
6b8edb51 910 void skip_frame ();
8d64371b
TT
911 long read_frame (gdb::char_vector *buf_p);
912 void getpkt (gdb::char_vector *buf, int forever);
913 int getpkt_or_notif_sane_1 (gdb::char_vector *buf, int forever,
6b8edb51 914 int expecting_notif, int *is_notif);
8d64371b
TT
915 int getpkt_sane (gdb::char_vector *buf, int forever);
916 int getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
6b8edb51
PA
917 int *is_notif);
918 int remote_vkill (int pid);
919 void remote_kill_k ();
920
921 void extended_remote_disable_randomization (int val);
922 int extended_remote_run (const std::string &args);
923
924 void send_environment_packet (const char *action,
925 const char *packet,
926 const char *value);
927
928 void extended_remote_environment_support ();
3c69da40 929 void extended_remote_set_inferior_cwd ();
80152258 930
3c69da40
PA
931 target_xfer_status remote_write_qxfer (const char *object_name,
932 const char *annex,
933 const gdb_byte *writebuf,
934 ULONGEST offset, LONGEST len,
935 ULONGEST *xfered_len,
936 struct packet_config *packet);
43c3a0e4 937
3c69da40
PA
938 target_xfer_status remote_read_qxfer (const char *object_name,
939 const char *annex,
940 gdb_byte *readbuf, ULONGEST offset,
941 LONGEST len,
942 ULONGEST *xfered_len,
943 struct packet_config *packet);
43c3a0e4 944
3c69da40 945 void push_stop_reply (struct stop_reply *new_event);
43c3a0e4 946
3c69da40 947 bool vcont_r_supported ();
43c3a0e4 948
288712bb
AB
949private:
950
951 bool start_remote_1 (int from_tty, int extended_p);
43c3a0e4 952
3c69da40
PA
953 /* The remote state. Don't reference this directly. Use the
954 get_remote_state method instead. */
955 remote_state m_remote_state;
43c3a0e4
PA
956};
957
3c69da40
PA
958static const target_info extended_remote_target_info = {
959 "extended-remote",
ae9adb36 960 N_("Extended remote target using gdb-specific protocol"),
3c69da40
PA
961 remote_doc
962};
ea9c271d 963
3c69da40
PA
964/* Set up the extended remote target by extending the standard remote
965 target and adding to it. */
966
967class extended_remote_target final : public remote_target
ea9c271d 968{
9d6eea31 969public:
3c69da40
PA
970 const target_info &info () const override
971 { return extended_remote_target_info; }
9d6eea31 972
3c69da40
PA
973 /* Open an extended-remote connection. */
974 static void open (const char *, int);
de44f5a7 975
3c69da40
PA
976 bool can_create_inferior () override { return true; }
977 void create_inferior (const char *, const std::string &,
978 char **, int) override;
9d6eea31 979
3c69da40 980 void detach (inferior *, int) override;
9d6eea31 981
3c69da40
PA
982 bool can_attach () override { return true; }
983 void attach (const char *, int) override;
be2a5f71 984
3c69da40
PA
985 void post_attach (int) override;
986 bool supports_disable_randomization () override;
987};
1e51243a 988
a4543480
SM
989struct stop_reply : public notif_event
990{
991 ~stop_reply ();
992
993 /* The identifier of the thread about this event */
994 ptid_t ptid;
995
996 /* The remote state this event is associated with. When the remote
997 connection, represented by a remote_state object, is closed,
998 all the associated stop_reply events should be released. */
999 struct remote_state *rs;
1000
1001 struct target_waitstatus ws;
1002
1003 /* The architecture associated with the expedited registers. */
1004 gdbarch *arch;
1005
1006 /* Expedited registers. This makes remote debugging a bit more
1007 efficient for those targets that provide critical registers as
1008 part of their normal status mechanism (as another roundtrip to
1009 fetch them is avoided). */
1010 std::vector<cached_reg_t> regcache;
1011
1012 enum target_stop_reason stop_reason;
1013
1014 CORE_ADDR watch_data_address;
1015
1016 int core;
1017};
1018
06c7226e
SM
1019/* Return TARGET as a remote_target if it is one, else nullptr. */
1020
1021static remote_target *
1022as_remote_target (process_stratum_target *target)
1023{
1024 return dynamic_cast<remote_target *> (target);
1025}
1026
24b2de7b
AB
1027/* See remote.h. */
1028
1029bool
1030is_remote_target (process_stratum_target *target)
1031{
06c7226e 1032 return as_remote_target (target) != nullptr;
24b2de7b
AB
1033}
1034
3c69da40 1035/* Per-program-space data key. */
08b8a139 1036static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
7b4a314f 1037 remote_pspace_data;
2d717e4f 1038
3c69da40
PA
1039/* The variable registered as the control variable used by the
1040 remote exec-file commands. While the remote exec-file setting is
1041 per-program-space, the set/show machinery uses this as the
1042 location of the remote exec-file value. */
e0700ba4 1043static std::string remote_exec_file_var;
a6f3e723 1044
3c69da40
PA
1045/* The size to align memory write packets, when practical. The protocol
1046 does not guarantee any alignment, and gdb will generate short
1047 writes and unaligned writes, but even as a best-effort attempt this
1048 can improve bulk transfers. For instance, if a write is misaligned
1049 relative to the target's data bus, the stub may need to make an extra
1050 round trip fetching data from the target. This doesn't make a
1051 huge difference, but it's easy to do, so we try to be helpful.
82f73884 1052
3c69da40
PA
1053 The alignment chosen is arbitrary; usually data bus width is
1054 important here, not the possibly larger cache line size. */
1055enum { REMOTE_ALIGN_WRITES = 16 };
82f73884 1056
3c69da40 1057/* Prototypes for local functions. */
74531fed 1058
3c69da40 1059static int hexnumlen (ULONGEST num);
782b2b07 1060
3c69da40 1061static int stubhex (int ch);
5d93a237 1062
3c69da40 1063static int hexnumstr (char *, ULONGEST);
048094ac 1064
3c69da40 1065static int hexnumnstr (char *, ULONGEST, int);
47f8a51d 1066
3c69da40 1067static CORE_ADDR remote_address_masked (CORE_ADDR);
262e1174 1068
cecb1912 1069static int stub_unpack_int (const char *buff, int fieldlength);
5e4a05c4 1070
3c69da40 1071struct packet_config;
b73be471 1072
3c69da40
PA
1073static void show_remote_protocol_packet_cmd (struct ui_file *file,
1074 int from_tty,
1075 struct cmd_list_element *c,
1076 const char *value);
8e88304f 1077
3c69da40 1078static ptid_t read_ptid (const char *buf, const char **obuf);
3a00c802 1079
3c69da40 1080static void remote_async_inferior_event_handler (gdb_client_data);
b80fafe3 1081
eefce37f 1082static bool remote_read_description_p (struct target_ops *target);
88b496c3 1083
05be00a8 1084static void remote_console_output (const char *msg);
5965e028 1085
3c69da40 1086static void remote_btrace_reset (remote_state *rs);
f4abbc16 1087
5b6d1e4f 1088static void remote_unpush_and_throw (remote_target *target);
15a201c8 1089
3c69da40 1090/* For "remote". */
80152258 1091
3c69da40 1092static struct cmd_list_element *remote_cmdlist;
9d6eea31 1093
3c69da40 1094/* For "set remote" and "show remote". */
6b8edb51 1095
3c69da40
PA
1096static struct cmd_list_element *remote_set_cmdlist;
1097static struct cmd_list_element *remote_show_cmdlist;
6b8edb51 1098
3c69da40 1099/* Controls whether GDB is willing to use range stepping. */
6b8edb51 1100
491144b5 1101static bool use_range_stepping = true;
3c69da40 1102
c9d22089
SM
1103/* From the remote target's point of view, each thread is in one of these three
1104 states. */
1105enum class resume_state
1106{
1107 /* Not resumed - we haven't been asked to resume this thread. */
1108 NOT_RESUMED,
1109
1110 /* We have been asked to resume this thread, but haven't sent a vCont action
1111 for it yet. We'll need to consider it next time commit_resume is
1112 called. */
1113 RESUMED_PENDING_VCONT,
1114
1115 /* We have been asked to resume this thread, and we have sent a vCont action
1116 for it. */
1117 RESUMED,
1118};
1119
1120/* Information about a thread's pending vCont-resume. Used when a thread is in
1121 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1122 stores this information which is then picked up by
1123 remote_target::commit_resume to know which is the proper action for this
1124 thread to include in the vCont packet. */
1125struct resumed_pending_vcont_info
1126{
1127 /* True if the last resume call for this thread was a step request, false
1128 if a continue request. */
1129 bool step;
1130
1131 /* The signal specified in the last resume call for this thread. */
1132 gdb_signal sig;
1133};
1134
7aabaf9d
SM
1135/* Private data that we'll store in (struct thread_info)->priv. */
1136struct remote_thread_info : public private_thread_info
dc146f7c 1137{
7aabaf9d
SM
1138 std::string extra;
1139 std::string name;
1140 int core = -1;
799a2abe 1141
f6327dcb
KB
1142 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1143 sequence of bytes. */
7aabaf9d 1144 gdb::byte_vector thread_handle;
f6327dcb 1145
799a2abe 1146 /* Whether the target stopped for a breakpoint/watchpoint. */
7aabaf9d 1147 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
799a2abe
PA
1148
1149 /* This is set to the data address of the access causing the target
1150 to stop for a watchpoint. */
7aabaf9d 1151 CORE_ADDR watch_data_address = 0;
85ad3aaf 1152
c9d22089 1153 /* Get the thread's resume state. */
a6c11cbb 1154 enum resume_state get_resume_state () const
c9d22089
SM
1155 {
1156 return m_resume_state;
1157 }
1158
1159 /* Put the thread in the NOT_RESUMED state. */
1160 void set_not_resumed ()
1161 {
1162 m_resume_state = resume_state::NOT_RESUMED;
1163 }
85ad3aaf 1164
c9d22089
SM
1165 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1166 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1167 {
1168 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1169 m_resumed_pending_vcont_info.step = step;
1170 m_resumed_pending_vcont_info.sig = sig;
1171 }
85ad3aaf 1172
c9d22089 1173 /* Get the information this thread's pending vCont-resumption.
85ad3aaf 1174
c9d22089
SM
1175 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1176 state. */
1177 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1178 {
1179 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1180
1181 return m_resumed_pending_vcont_info;
1182 }
1183
1184 /* Put the thread in the VCONT_RESUMED state. */
1185 void set_resumed ()
1186 {
1187 m_resume_state = resume_state::RESUMED;
1188 }
1189
1190private:
1191 /* Resume state for this thread. This is used to implement vCont action
1192 coalescing (only when the target operates in non-stop mode).
1193
1194 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1195 which notes that this thread must be considered in the next commit_resume
1196 call.
1197
1198 remote_target::commit_resume sends a vCont packet with actions for the
1199 threads in the RESUMED_PENDING_VCONT state and moves them to the
1200 VCONT_RESUMED state.
1201
1202 When reporting a stop to the core for a thread, that thread is moved back
1203 to the NOT_RESUMED state. */
1204 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1205
1206 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1207 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
dc146f7c
VP
1208};
1209
de44f5a7 1210remote_state::remote_state ()
8d64371b 1211 : buf (400)
de44f5a7 1212{
de44f5a7
PA
1213}
1214
1215remote_state::~remote_state ()
1216{
1217 xfree (this->last_pass_packet);
1218 xfree (this->last_program_signals_packet);
de44f5a7
PA
1219 xfree (this->finished_object);
1220 xfree (this->finished_annex);
cf792862
TT
1221}
1222
35b1e5cc
SS
1223/* Utility: generate error from an incoming stub packet. */
1224static void
1225trace_error (char *buf)
1226{
1227 if (*buf++ != 'E')
1228 return; /* not an error msg */
1229 switch (*buf)
1230 {
1231 case '1': /* malformed packet error */
1232 if (*++buf == '0') /* general case: */
1233 error (_("remote.c: error in outgoing packet."));
1234 else
1235 error (_("remote.c: error in outgoing packet at field #%ld."),
1236 strtol (buf, NULL, 16));
35b1e5cc
SS
1237 default:
1238 error (_("Target returns error code '%s'."), buf);
1239 }
1240}
1241
1242/* Utility: wait for reply from stub, while accepting "O" packets. */
b6bb3468 1243
6b8edb51
PA
1244char *
1245remote_target::remote_get_noisy_reply ()
35b1e5cc 1246{
b6bb3468
PA
1247 struct remote_state *rs = get_remote_state ();
1248
35b1e5cc
SS
1249 do /* Loop on reply from remote stub. */
1250 {
1251 char *buf;
a744cf53 1252
0df8b418 1253 QUIT; /* Allow user to bail out with ^C. */
8d64371b
TT
1254 getpkt (&rs->buf, 0);
1255 buf = rs->buf.data ();
ad91cd99 1256 if (buf[0] == 'E')
35b1e5cc 1257 trace_error (buf);
61012eef 1258 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
1259 {
1260 ULONGEST ul;
1261 CORE_ADDR from, to, org_to;
256642e8 1262 const char *p, *pp;
dde08ee1 1263 int adjusted_size = 0;
7556d4a4 1264 int relocated = 0;
dde08ee1
PA
1265
1266 p = buf + strlen ("qRelocInsn:");
1267 pp = unpack_varlen_hex (p, &ul);
1268 if (*pp != ';')
cb91c06a 1269 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
1270 from = ul;
1271
1272 p = pp + 1;
a9cbf802 1273 unpack_varlen_hex (p, &ul);
dde08ee1
PA
1274 to = ul;
1275
1276 org_to = to;
1277
a70b8144 1278 try
dde08ee1 1279 {
f5656ead 1280 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 1281 relocated = 1;
dde08ee1 1282 }
230d2906 1283 catch (const gdb_exception &ex)
7556d4a4
PA
1284 {
1285 if (ex.error == MEMORY_ERROR)
1286 {
1287 /* Propagate memory errors silently back to the
1288 target. The stub may have limited the range of
1289 addresses we can write to, for example. */
1290 }
1291 else
1292 {
1293 /* Something unexpectedly bad happened. Be verbose
1294 so we can tell what, and propagate the error back
1295 to the stub, so it doesn't get stuck waiting for
1296 a response. */
1297 exception_fprintf (gdb_stderr, ex,
1298 _("warning: relocating instruction: "));
1299 }
1300 putpkt ("E01");
1301 }
1302
1303 if (relocated)
dde08ee1
PA
1304 {
1305 adjusted_size = to - org_to;
1306
8d64371b 1307 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
1308 putpkt (buf);
1309 }
dde08ee1 1310 }
ad91cd99 1311 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
1312 remote_console_output (buf + 1); /* 'O' message from stub */
1313 else
0df8b418 1314 return buf; /* Here's the actual reply. */
35b1e5cc
SS
1315 }
1316 while (1);
1317}
3c3bea1c 1318
9d6eea31
PA
1319struct remote_arch_state *
1320remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
d01949b6 1321{
43c3a0e4
PA
1322 remote_arch_state *rsa;
1323
1324 auto it = this->m_arch_states.find (gdbarch);
1325 if (it == this->m_arch_states.end ())
9d6eea31 1326 {
43c3a0e4
PA
1327 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1328 std::forward_as_tuple (gdbarch),
1329 std::forward_as_tuple (gdbarch));
1330 rsa = &p.first->second;
9d6eea31
PA
1331
1332 /* Make sure that the packet buffer is plenty big enough for
1333 this architecture. */
8d64371b
TT
1334 if (this->buf.size () < rsa->remote_packet_size)
1335 this->buf.resize (2 * rsa->remote_packet_size);
9d6eea31 1336 }
43c3a0e4
PA
1337 else
1338 rsa = &it->second;
1339
1340 return rsa;
d01949b6
AC
1341}
1342
0b83947e
DJ
1343/* Fetch the global remote target state. */
1344
6b8edb51
PA
1345remote_state *
1346remote_target::get_remote_state ()
0b83947e
DJ
1347{
1348 /* Make sure that the remote architecture state has been
1349 initialized, because doing so might reallocate rs->buf. Any
1350 function which calls getpkt also needs to be mindful of changes
1351 to rs->buf, but this call limits the number of places which run
1352 into trouble. */
3c69da40 1353 m_remote_state.get_remote_arch_state (target_gdbarch ());
0b83947e 1354
3c69da40 1355 return &m_remote_state;
0b83947e
DJ
1356}
1357
94585166
DB
1358/* Fetch the remote exec-file from the current program space. */
1359
1360static const char *
1361get_remote_exec_file (void)
1362{
1363 char *remote_exec_file;
1364
7b4a314f 1365 remote_exec_file = remote_pspace_data.get (current_program_space);
94585166
DB
1366 if (remote_exec_file == NULL)
1367 return "";
1368
1369 return remote_exec_file;
1370}
1371
1372/* Set the remote exec file for PSPACE. */
1373
1374static void
1375set_pspace_remote_exec_file (struct program_space *pspace,
7b4a314f 1376 const char *remote_exec_file)
94585166 1377{
7b4a314f 1378 char *old_file = remote_pspace_data.get (pspace);
94585166
DB
1379
1380 xfree (old_file);
7b4a314f 1381 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
94585166
DB
1382}
1383
1384/* The "set/show remote exec-file" set command hook. */
1385
1386static void
eb4c3f4a 1387set_remote_exec_file (const char *ignored, int from_tty,
94585166
DB
1388 struct cmd_list_element *c)
1389{
e0700ba4
SM
1390 set_pspace_remote_exec_file (current_program_space,
1391 remote_exec_file_var.c_str ());
94585166
DB
1392}
1393
1394/* The "set/show remote exec-file" show command hook. */
1395
1396static void
1397show_remote_exec_file (struct ui_file *file, int from_tty,
1398 struct cmd_list_element *cmd, const char *value)
1399{
6cb06a8c 1400 gdb_printf (file, "%s\n", get_remote_exec_file ());
94585166
DB
1401}
1402
c21236dc
PA
1403static int
1404map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 1405{
74ca34ce 1406 int regnum, num_remote_regs, offset;
74ca34ce 1407 struct packet_reg **remote_regs;
ea9c271d 1408
4a22f64d 1409 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 1410 {
c21236dc 1411 struct packet_reg *r = &regs[regnum];
baef701f 1412
4a22f64d 1413 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
1414 /* Do not try to fetch zero-sized (placeholder) registers. */
1415 r->pnum = -1;
1416 else
1417 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1418
b323314b 1419 r->regnum = regnum;
74ca34ce
DJ
1420 }
1421
1422 /* Define the g/G packet format as the contents of each register
1423 with a remote protocol number, in order of ascending protocol
1424 number. */
1425
224c3ddb 1426 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 1427 for (num_remote_regs = 0, regnum = 0;
4a22f64d 1428 regnum < gdbarch_num_regs (gdbarch);
f57d151a 1429 regnum++)
c21236dc
PA
1430 if (regs[regnum].pnum != -1)
1431 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 1432
39ef2f62
CB
1433 std::sort (remote_regs, remote_regs + num_remote_regs,
1434 [] (const packet_reg *a, const packet_reg *b)
1435 { return a->pnum < b->pnum; });
74ca34ce
DJ
1436
1437 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1438 {
1439 remote_regs[regnum]->in_g_packet = 1;
1440 remote_regs[regnum]->offset = offset;
4a22f64d 1441 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
1442 }
1443
c21236dc
PA
1444 return offset;
1445}
1446
1447/* Given the architecture described by GDBARCH, return the remote
1448 protocol register's number and the register's offset in the g/G
1449 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1450 If the target does not have a mapping for REGNUM, return false,
1451 otherwise, return true. */
1452
1453int
1454remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1455 int *pnum, int *poffset)
1456{
c21236dc
PA
1457 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1458
b80406ac 1459 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
c21236dc 1460
b80406ac 1461 map_regcache_remote_table (gdbarch, regs.data ());
c21236dc
PA
1462
1463 *pnum = regs[regnum].pnum;
1464 *poffset = regs[regnum].offset;
1465
c21236dc
PA
1466 return *pnum != -1;
1467}
1468
9d6eea31 1469remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
c21236dc 1470{
c21236dc
PA
1471 /* Use the architecture to build a regnum<->pnum table, which will be
1472 1:1 unless a feature set specifies otherwise. */
9d6eea31 1473 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
c21236dc 1474
74ca34ce
DJ
1475 /* Record the maximum possible size of the g packet - it may turn out
1476 to be smaller. */
9d6eea31
PA
1477 this->sizeof_g_packet
1478 = map_regcache_remote_table (gdbarch, this->regs.get ());
74ca34ce 1479
0df8b418 1480 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
1481 remote stubs have a hardwired buffer size of 400 bytes
1482 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1483 as the maximum packet-size to ensure that the packet and an extra
1484 NUL character can always fit in the buffer. This stops GDB
1485 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d 1486 already a full buffer (As of 1999-12-04 that was most stubs). */
9d6eea31 1487 this->remote_packet_size = 400 - 1;
d01949b6 1488
ea9c271d 1489 /* This one is filled in when a ``g'' packet is received. */
9d6eea31 1490 this->actual_register_packet_size = 0;
ea9c271d
DJ
1491
1492 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
1493 default, adjust the size accordingly. Remember that each byte is
1494 encoded as two characters. 32 is the overhead for the packet
1495 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 1496 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 1497 little. */
9d6eea31
PA
1498 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1499 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
ea9c271d
DJ
1500}
1501
6b8edb51
PA
1502/* Get a pointer to the current remote target. If not connected to a
1503 remote target, return NULL. */
1504
1505static remote_target *
1506get_current_remote_target ()
1507{
5b6d1e4f 1508 target_ops *proc_target = current_inferior ()->process_target ();
6b8edb51
PA
1509 return dynamic_cast<remote_target *> (proc_target);
1510}
1511
ea9c271d
DJ
1512/* Return the current allowed size of a remote packet. This is
1513 inferred from the current architecture, and should be used to
1514 limit the length of outgoing packets. */
6b8edb51
PA
1515long
1516remote_target::get_remote_packet_size ()
ea9c271d 1517{
be2a5f71 1518 struct remote_state *rs = get_remote_state ();
9d6eea31 1519 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
ea9c271d 1520
be2a5f71
DJ
1521 if (rs->explicit_packet_size)
1522 return rs->explicit_packet_size;
1523
ea9c271d 1524 return rsa->remote_packet_size;
d01949b6
AC
1525}
1526
ad10f812 1527static struct packet_reg *
5cd63fda
PA
1528packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1529 long regnum)
ad10f812 1530{
5cd63fda 1531 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
b323314b
AC
1532 return NULL;
1533 else
ad10f812 1534 {
ea9c271d 1535 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 1536
b323314b
AC
1537 gdb_assert (r->regnum == regnum);
1538 return r;
ad10f812 1539 }
ad10f812
AC
1540}
1541
1542static struct packet_reg *
5cd63fda
PA
1543packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1544 LONGEST pnum)
ad10f812 1545{
b323314b 1546 int i;
a744cf53 1547
5cd63fda 1548 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
ad10f812 1549 {
ea9c271d 1550 struct packet_reg *r = &rsa->regs[i];
a744cf53 1551
b323314b
AC
1552 if (r->pnum == pnum)
1553 return r;
ad10f812
AC
1554 }
1555 return NULL;
d01949b6
AC
1556}
1557
9a7071a8
JB
1558/* Allow the user to specify what sequence to send to the remote
1559 when he requests a program interruption: Although ^C is usually
1560 what remote systems expect (this is the default, here), it is
1561 sometimes preferable to send a break. On other systems such
1562 as the Linux kernel, a break followed by g, which is Magic SysRq g
1563 is required in order to interrupt the execution. */
1564const char interrupt_sequence_control_c[] = "Ctrl-C";
1565const char interrupt_sequence_break[] = "BREAK";
1566const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 1567static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
1568 {
1569 interrupt_sequence_control_c,
1570 interrupt_sequence_break,
1571 interrupt_sequence_break_g,
1572 NULL
1573 };
1574static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1575
1576static void
1577show_interrupt_sequence (struct ui_file *file, int from_tty,
1578 struct cmd_list_element *c,
1579 const char *value)
1580{
1581 if (interrupt_sequence_mode == interrupt_sequence_control_c)
6cb06a8c
TT
1582 gdb_printf (file,
1583 _("Send the ASCII ETX character (Ctrl-c) "
1584 "to the remote target to interrupt the "
1585 "execution of the program.\n"));
9a7071a8 1586 else if (interrupt_sequence_mode == interrupt_sequence_break)
6cb06a8c
TT
1587 gdb_printf (file,
1588 _("send a break signal to the remote target "
1589 "to interrupt the execution of the program.\n"));
9a7071a8 1590 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
6cb06a8c
TT
1591 gdb_printf (file,
1592 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1593 "the remote target to interrupt the execution "
1594 "of Linux kernel.\n"));
9a7071a8
JB
1595 else
1596 internal_error (__FILE__, __LINE__,
1597 _("Invalid value for interrupt_sequence_mode: %s."),
1598 interrupt_sequence_mode);
1599}
6426a772 1600
9a7071a8
JB
1601/* This boolean variable specifies whether interrupt_sequence is sent
1602 to the remote target when gdb connects to it.
1603 This is mostly needed when you debug the Linux kernel: The Linux kernel
1604 expects BREAK g which is Magic SysRq g for connecting gdb. */
491144b5 1605static bool interrupt_on_connect = false;
c906108c 1606
9a7071a8
JB
1607/* This variable is used to implement the "set/show remotebreak" commands.
1608 Since these commands are now deprecated in favor of "set/show remote
1609 interrupt-sequence", it no longer has any effect on the code. */
491144b5 1610static bool remote_break;
c906108c 1611
9a7071a8 1612static void
eb4c3f4a 1613set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
9a7071a8
JB
1614{
1615 if (remote_break)
1616 interrupt_sequence_mode = interrupt_sequence_break;
1617 else
1618 interrupt_sequence_mode = interrupt_sequence_control_c;
1619}
1620
1621static void
1622show_remotebreak (struct ui_file *file, int from_tty,
1623 struct cmd_list_element *c,
1624 const char *value)
1625{
1626}
1627
c906108c
SS
1628/* This variable sets the number of bits in an address that are to be
1629 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 1630 leading zeros, the entire address would be sent. This variable
c906108c
SS
1631 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1632 initial implementation of remote.c restricted the address sent in
1633 memory packets to ``host::sizeof long'' bytes - (typically 32
1634 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1635 address was never sent. Since fixing this bug may cause a break in
85102364 1636 some remote targets this variable is principally provided to
23860348 1637 facilitate backward compatibility. */
c906108c 1638
883b9c6c 1639static unsigned int remote_address_size;
c906108c 1640
11cf8741 1641\f
11cf8741 1642/* User configurable variables for the number of characters in a
ea9c271d
DJ
1643 memory read/write packet. MIN (rsa->remote_packet_size,
1644 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 1645 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
1646 (speed up transfers). The variables ``preferred_*'' (the user
1647 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 1648 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
1649
1650struct memory_packet_config
1651{
a121b7c1 1652 const char *name;
11cf8741
JM
1653 long size;
1654 int fixed_p;
1655};
1656
cc0be08f
PA
1657/* The default max memory-write-packet-size, when the setting is
1658 "fixed". The 16k is historical. (It came from older GDB's using
1659 alloca for buffers and the knowledge (folklore?) that some hosts
1660 don't cope very well with large alloca calls.) */
1661#define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
a5c0808e
PA
1662
1663/* The minimum remote packet size for memory transfers. Ensures we
1664 can write at least one byte. */
1665#define MIN_MEMORY_PACKET_SIZE 20
1666
cc0be08f
PA
1667/* Get the memory packet size, assuming it is fixed. */
1668
1669static long
1670get_fixed_memory_packet_size (struct memory_packet_config *config)
1671{
1672 gdb_assert (config->fixed_p);
1673
1674 if (config->size <= 0)
1675 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1676 else
1677 return config->size;
1678}
1679
11cf8741
JM
1680/* Compute the current size of a read/write packet. Since this makes
1681 use of ``actual_register_packet_size'' the computation is dynamic. */
1682
6b8edb51
PA
1683long
1684remote_target::get_memory_packet_size (struct memory_packet_config *config)
11cf8741 1685{
d01949b6 1686 struct remote_state *rs = get_remote_state ();
9d6eea31 1687 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
ea9c271d 1688
11cf8741
JM
1689 long what_they_get;
1690 if (config->fixed_p)
cc0be08f 1691 what_they_get = get_fixed_memory_packet_size (config);
11cf8741
JM
1692 else
1693 {
ea9c271d 1694 what_they_get = get_remote_packet_size ();
23860348 1695 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1696 if (config->size > 0
1697 && what_they_get > config->size)
1698 what_they_get = config->size;
be2a5f71
DJ
1699
1700 /* Limit it to the size of the targets ``g'' response unless we have
1701 permission from the stub to use a larger packet size. */
1702 if (rs->explicit_packet_size == 0
1703 && rsa->actual_register_packet_size > 0
1704 && what_they_get > rsa->actual_register_packet_size)
1705 what_they_get = rsa->actual_register_packet_size;
11cf8741 1706 }
a5c0808e
PA
1707 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1708 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1709
1710 /* Make sure there is room in the global buffer for this packet
1711 (including its trailing NUL byte). */
8d64371b
TT
1712 if (rs->buf.size () < what_they_get + 1)
1713 rs->buf.resize (2 * what_they_get);
6d820c5c 1714
11cf8741
JM
1715 return what_they_get;
1716}
1717
0df8b418 1718/* Update the size of a read/write packet. If they user wants
23860348 1719 something really big then do a sanity check. */
11cf8741
JM
1720
1721static void
ac88e2de 1722set_memory_packet_size (const char *args, struct memory_packet_config *config)
11cf8741
JM
1723{
1724 int fixed_p = config->fixed_p;
1725 long size = config->size;
a744cf53 1726
11cf8741 1727 if (args == NULL)
8a3fe4f8 1728 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1729 else if (strcmp (args, "hard") == 0
1730 || strcmp (args, "fixed") == 0)
1731 fixed_p = 1;
1732 else if (strcmp (args, "soft") == 0
1733 || strcmp (args, "limit") == 0)
1734 fixed_p = 0;
1735 else
1736 {
1737 char *end;
a744cf53 1738
11cf8741
JM
1739 size = strtoul (args, &end, 0);
1740 if (args == end)
8a3fe4f8 1741 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1742
1743 /* Instead of explicitly capping the size of a packet to or
1744 disallowing it, the user is allowed to set the size to
1745 something arbitrarily large. */
11cf8741 1746 }
a5c0808e 1747
23860348 1748 /* Extra checks? */
11cf8741
JM
1749 if (fixed_p && !config->fixed_p)
1750 {
cc0be08f
PA
1751 /* So that the query shows the correct value. */
1752 long query_size = (size <= 0
1753 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1754 : size);
1755
e2e0b3e5
AC
1756 if (! query (_("The target may not be able to correctly handle a %s\n"
1757 "of %ld bytes. Change the packet size? "),
cc0be08f 1758 config->name, query_size))
8a3fe4f8 1759 error (_("Packet size not changed."));
11cf8741 1760 }
23860348 1761 /* Update the config. */
11cf8741
JM
1762 config->fixed_p = fixed_p;
1763 config->size = size;
1764}
1765
1766static void
1767show_memory_packet_size (struct memory_packet_config *config)
1768{
cc0be08f 1769 if (config->size == 0)
6cb06a8c 1770 gdb_printf (_("The %s is 0 (default). "), config->name);
cc0be08f 1771 else
6cb06a8c 1772 gdb_printf (_("The %s is %ld. "), config->name, config->size);
11cf8741 1773 if (config->fixed_p)
6cb06a8c
TT
1774 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
1775 get_fixed_memory_packet_size (config));
11cf8741 1776 else
cc0be08f 1777 {
6b8edb51 1778 remote_target *remote = get_current_remote_target ();
cc0be08f 1779
6b8edb51 1780 if (remote != NULL)
6cb06a8c
TT
1781 gdb_printf (_("Packets are limited to %ld bytes.\n"),
1782 remote->get_memory_packet_size (config));
cc0be08f 1783 else
0426ad51
TT
1784 gdb_puts ("The actual limit will be further reduced "
1785 "dependent on the target.\n");
cc0be08f 1786 }
11cf8741
JM
1787}
1788
5b6d1e4f 1789/* FIXME: needs to be per-remote-target. */
11cf8741
JM
1790static struct memory_packet_config memory_write_packet_config =
1791{
1792 "memory-write-packet-size",
1793};
1794
1795static void
ac88e2de 1796set_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1797{
1798 set_memory_packet_size (args, &memory_write_packet_config);
1799}
1800
1801static void
ac88e2de 1802show_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1803{
1804 show_memory_packet_size (&memory_write_packet_config);
1805}
1806
055303e2
AB
1807/* Show the number of hardware watchpoints that can be used. */
1808
1809static void
1810show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
1811 struct cmd_list_element *c,
1812 const char *value)
1813{
6cb06a8c
TT
1814 gdb_printf (file, _("The maximum number of target hardware "
1815 "watchpoints is %s.\n"), value);
055303e2
AB
1816}
1817
1818/* Show the length limit (in bytes) for hardware watchpoints. */
1819
1820static void
1821show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
1822 struct cmd_list_element *c,
1823 const char *value)
1824{
6cb06a8c
TT
1825 gdb_printf (file, _("The maximum length (in bytes) of a target "
1826 "hardware watchpoint is %s.\n"), value);
055303e2
AB
1827}
1828
1829/* Show the number of hardware breakpoints that can be used. */
1830
1831static void
1832show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
1833 struct cmd_list_element *c,
1834 const char *value)
1835{
6cb06a8c
TT
1836 gdb_printf (file, _("The maximum number of target hardware "
1837 "breakpoints is %s.\n"), value);
055303e2
AB
1838}
1839
6cc8564b
LM
1840/* Controls the maximum number of characters to display in the debug output
1841 for each remote packet. The remaining characters are omitted. */
1842
1843static int remote_packet_max_chars = 512;
1844
1845/* Show the maximum number of characters to display for each remote packet
1846 when remote debugging is enabled. */
1847
1848static void
1849show_remote_packet_max_chars (struct ui_file *file, int from_tty,
1850 struct cmd_list_element *c,
1851 const char *value)
1852{
6cb06a8c
TT
1853 gdb_printf (file, _("Number of remote packet characters to "
1854 "display is %s.\n"), value);
6cc8564b
LM
1855}
1856
6b8edb51
PA
1857long
1858remote_target::get_memory_write_packet_size ()
11cf8741
JM
1859{
1860 return get_memory_packet_size (&memory_write_packet_config);
1861}
1862
5b6d1e4f 1863/* FIXME: needs to be per-remote-target. */
11cf8741
JM
1864static struct memory_packet_config memory_read_packet_config =
1865{
1866 "memory-read-packet-size",
1867};
1868
1869static void
ac88e2de 1870set_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1871{
1872 set_memory_packet_size (args, &memory_read_packet_config);
1873}
1874
1875static void
ac88e2de 1876show_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1877{
1878 show_memory_packet_size (&memory_read_packet_config);
1879}
1880
6b8edb51
PA
1881long
1882remote_target::get_memory_read_packet_size ()
11cf8741
JM
1883{
1884 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1885
11cf8741
JM
1886 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1887 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1888 increased beyond this. */
1889 if (size > get_remote_packet_size ())
1890 size = get_remote_packet_size ();
11cf8741
JM
1891 return size;
1892}
1893
11cf8741 1894\f
5a2468f5 1895
5a2468f5
JM
1896struct packet_config
1897 {
bb572ddd
DJ
1898 const char *name;
1899 const char *title;
4082afcc
PA
1900
1901 /* If auto, GDB auto-detects support for this packet or feature,
1902 either through qSupported, or by trying the packet and looking
1903 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1904 packet. If false, the packet is disabled. Configs that don't
1905 have an associated command always have this set to auto. */
7f19b9a2 1906 enum auto_boolean detect;
4082afcc 1907
fcef6471
SM
1908 /* The "show remote foo-packet" command created for this packet. */
1909 cmd_list_element *show_cmd;
1910
4082afcc 1911 /* Does the target support this packet? */
5a2468f5
JM
1912 enum packet_support support;
1913 };
1914
4082afcc
PA
1915static enum packet_support packet_config_support (struct packet_config *config);
1916static enum packet_support packet_support (int packet);
5a2468f5
JM
1917
1918static void
7514a661 1919show_packet_config_cmd (ui_file *file, struct packet_config *config)
5a2468f5 1920{
a121b7c1 1921 const char *support = "internal-error";
a744cf53 1922
4082afcc 1923 switch (packet_config_support (config))
5a2468f5
JM
1924 {
1925 case PACKET_ENABLE:
1926 support = "enabled";
1927 break;
1928 case PACKET_DISABLE:
1929 support = "disabled";
1930 break;
1931 case PACKET_SUPPORT_UNKNOWN:
1932 support = "unknown";
1933 break;
1934 }
1935 switch (config->detect)
1936 {
7f19b9a2 1937 case AUTO_BOOLEAN_AUTO:
6cb06a8c
TT
1938 gdb_printf (file,
1939 _("Support for the `%s' packet "
1940 "is auto-detected, currently %s.\n"),
1941 config->name, support);
5a2468f5 1942 break;
7f19b9a2
AC
1943 case AUTO_BOOLEAN_TRUE:
1944 case AUTO_BOOLEAN_FALSE:
6cb06a8c
TT
1945 gdb_printf (file,
1946 _("Support for the `%s' packet is currently %s.\n"),
1947 config->name, support);
8e248173 1948 break;
5a2468f5
JM
1949 }
1950}
1951
1952static void
bb572ddd
DJ
1953add_packet_config_cmd (struct packet_config *config, const char *name,
1954 const char *title, int legacy)
d471ea57 1955{
5a2468f5
JM
1956 config->name = name;
1957 config->title = title;
8579fd13
AB
1958 gdb::unique_xmalloc_ptr<char> set_doc
1959 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
1960 name, title);
1961 gdb::unique_xmalloc_ptr<char> show_doc
1962 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
1963 name, title);
d471ea57 1964 /* set/show TITLE-packet {auto,on,off} */
8579fd13 1965 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
5e84b7ee 1966 set_show_commands cmds
8579fd13
AB
1967 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
1968 &config->detect, set_doc.get (),
1969 show_doc.get (), NULL, /* help_doc */
5e84b7ee
SM
1970 NULL,
1971 show_remote_protocol_packet_cmd,
1972 &remote_set_cmdlist, &remote_show_cmdlist);
fcef6471 1973 config->show_cmd = cmds.show;
5e84b7ee 1974
23860348 1975 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1976 if (legacy)
1977 {
5f21c7aa
AB
1978 /* It's not clear who should take ownership of the LEGACY_NAME string
1979 created below, so, for now, place the string into a static vector
1980 which ensures the strings is released when GDB exits. */
1981 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
1982 gdb::unique_xmalloc_ptr<char> legacy_name
8579fd13
AB
1983 = xstrprintf ("%s-packet", name);
1984 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
bb572ddd 1985 &remote_set_cmdlist);
8579fd13 1986 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
bb572ddd 1987 &remote_show_cmdlist);
5f21c7aa 1988 legacy_names.emplace_back (std::move (legacy_name));
d471ea57 1989 }
5a2468f5
JM
1990}
1991
d471ea57 1992static enum packet_result
a76d924d 1993packet_check_result (const char *buf)
5a2468f5 1994{
d471ea57 1995 if (buf[0] != '\0')
5a2468f5 1996 {
d471ea57 1997 /* The stub recognized the packet request. Check that the
23860348 1998 operation succeeded. */
a76d924d
DJ
1999 if (buf[0] == 'E'
2000 && isxdigit (buf[1]) && isxdigit (buf[2])
2001 && buf[3] == '\0')
85102364 2002 /* "Enn" - definitely an error. */
a76d924d
DJ
2003 return PACKET_ERROR;
2004
2005 /* Always treat "E." as an error. This will be used for
2006 more verbose error messages, such as E.memtypes. */
2007 if (buf[0] == 'E' && buf[1] == '.')
2008 return PACKET_ERROR;
2009
2010 /* The packet may or may not be OK. Just assume it is. */
2011 return PACKET_OK;
2012 }
2013 else
2014 /* The stub does not support the packet. */
2015 return PACKET_UNKNOWN;
2016}
2017
8d64371b
TT
2018static enum packet_result
2019packet_check_result (const gdb::char_vector &buf)
2020{
2021 return packet_check_result (buf.data ());
2022}
2023
a76d924d
DJ
2024static enum packet_result
2025packet_ok (const char *buf, struct packet_config *config)
2026{
2027 enum packet_result result;
2028
4082afcc
PA
2029 if (config->detect != AUTO_BOOLEAN_TRUE
2030 && config->support == PACKET_DISABLE)
2031 internal_error (__FILE__, __LINE__,
2032 _("packet_ok: attempt to use a disabled packet"));
2033
a76d924d
DJ
2034 result = packet_check_result (buf);
2035 switch (result)
2036 {
2037 case PACKET_OK:
2038 case PACKET_ERROR:
2039 /* The stub recognized the packet request. */
4082afcc 2040 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 2041 {
2189c312
SM
2042 remote_debug_printf ("Packet %s (%s) is supported",
2043 config->name, config->title);
d471ea57 2044 config->support = PACKET_ENABLE;
d471ea57 2045 }
a76d924d
DJ
2046 break;
2047 case PACKET_UNKNOWN:
23860348 2048 /* The stub does not support the packet. */
4082afcc
PA
2049 if (config->detect == AUTO_BOOLEAN_AUTO
2050 && config->support == PACKET_ENABLE)
d471ea57 2051 {
4082afcc
PA
2052 /* If the stub previously indicated that the packet was
2053 supported then there is a protocol error. */
2054 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2055 config->name, config->title);
2056 }
2057 else if (config->detect == AUTO_BOOLEAN_TRUE)
2058 {
2059 /* The user set it wrong. */
2060 error (_("Enabled packet %s (%s) not recognized by stub"),
2061 config->name, config->title);
d471ea57 2062 }
4082afcc 2063
2189c312
SM
2064 remote_debug_printf ("Packet %s (%s) is NOT supported",
2065 config->name, config->title);
4082afcc 2066 config->support = PACKET_DISABLE;
a76d924d 2067 break;
5a2468f5 2068 }
a76d924d
DJ
2069
2070 return result;
5a2468f5
JM
2071}
2072
8d64371b
TT
2073static enum packet_result
2074packet_ok (const gdb::char_vector &buf, struct packet_config *config)
2075{
2076 return packet_ok (buf.data (), config);
2077}
2078
444abaca
DJ
2079enum {
2080 PACKET_vCont = 0,
2081 PACKET_X,
2082 PACKET_qSymbol,
2083 PACKET_P,
2084 PACKET_p,
2085 PACKET_Z0,
2086 PACKET_Z1,
2087 PACKET_Z2,
2088 PACKET_Z3,
2089 PACKET_Z4,
15a201c8 2090 PACKET_vFile_setfs,
a6b151f1
DJ
2091 PACKET_vFile_open,
2092 PACKET_vFile_pread,
2093 PACKET_vFile_pwrite,
2094 PACKET_vFile_close,
2095 PACKET_vFile_unlink,
b9e7b9c3 2096 PACKET_vFile_readlink,
0a93529c 2097 PACKET_vFile_fstat,
0876f84a 2098 PACKET_qXfer_auxv,
23181151 2099 PACKET_qXfer_features,
c78fa86a 2100 PACKET_qXfer_exec_file,
cfa9d6d9 2101 PACKET_qXfer_libraries,
2268b414 2102 PACKET_qXfer_libraries_svr4,
fd79ecee 2103 PACKET_qXfer_memory_map,
07e059b5 2104 PACKET_qXfer_osdata,
dc146f7c 2105 PACKET_qXfer_threads,
0fb4aa4b 2106 PACKET_qXfer_statictrace_read,
b3b9301e 2107 PACKET_qXfer_traceframe_info,
169081d0 2108 PACKET_qXfer_uib,
711e434b 2109 PACKET_qGetTIBAddr,
444abaca 2110 PACKET_qGetTLSAddr,
be2a5f71 2111 PACKET_qSupported,
bd3eecc3 2112 PACKET_qTStatus,
89be2091 2113 PACKET_QPassSignals,
82075af2 2114 PACKET_QCatchSyscalls,
9b224c5e 2115 PACKET_QProgramSignals,
bc3b087d 2116 PACKET_QSetWorkingDir,
aefd8b33 2117 PACKET_QStartupWithShell,
0a2dde4a
SDJ
2118 PACKET_QEnvironmentHexEncoded,
2119 PACKET_QEnvironmentReset,
2120 PACKET_QEnvironmentUnset,
936d2992 2121 PACKET_qCRC,
08388c79 2122 PACKET_qSearch_memory,
2d717e4f
DJ
2123 PACKET_vAttach,
2124 PACKET_vRun,
a6f3e723 2125 PACKET_QStartNoAckMode,
82f73884 2126 PACKET_vKill,
4aa995e1
PA
2127 PACKET_qXfer_siginfo_read,
2128 PACKET_qXfer_siginfo_write,
0b16c5cf 2129 PACKET_qAttached,
4082afcc
PA
2130
2131 /* Support for conditional tracepoints. */
782b2b07 2132 PACKET_ConditionalTracepoints,
4082afcc
PA
2133
2134 /* Support for target-side breakpoint conditions. */
3788aec7 2135 PACKET_ConditionalBreakpoints,
4082afcc
PA
2136
2137 /* Support for target-side breakpoint commands. */
d3ce09f5 2138 PACKET_BreakpointCommands,
4082afcc
PA
2139
2140 /* Support for fast tracepoints. */
7a697b8d 2141 PACKET_FastTracepoints,
4082afcc
PA
2142
2143 /* Support for static tracepoints. */
0fb4aa4b 2144 PACKET_StaticTracepoints,
4082afcc
PA
2145
2146 /* Support for installing tracepoints while a trace experiment is
2147 running. */
1e4d1764 2148 PACKET_InstallInTrace,
4082afcc 2149
40ab02ce
MS
2150 PACKET_bc,
2151 PACKET_bs,
409873ef 2152 PACKET_TracepointSource,
d914c394 2153 PACKET_QAllow,
78d85199 2154 PACKET_qXfer_fdpic,
03583c20 2155 PACKET_QDisableRandomization,
d1feda86 2156 PACKET_QAgent,
f6f899bf 2157 PACKET_QTBuffer_size,
9accd112
MM
2158 PACKET_Qbtrace_off,
2159 PACKET_Qbtrace_bts,
b20a6524 2160 PACKET_Qbtrace_pt,
9accd112 2161 PACKET_qXfer_btrace,
4082afcc
PA
2162
2163 /* Support for the QNonStop packet. */
2164 PACKET_QNonStop,
2165
65706a29
PA
2166 /* Support for the QThreadEvents packet. */
2167 PACKET_QThreadEvents,
2168
4082afcc
PA
2169 /* Support for multi-process extensions. */
2170 PACKET_multiprocess_feature,
2171
2172 /* Support for enabling and disabling tracepoints while a trace
2173 experiment is running. */
2174 PACKET_EnableDisableTracepoints_feature,
2175
2176 /* Support for collecting strings using the tracenz bytecode. */
2177 PACKET_tracenz_feature,
2178
2179 /* Support for continuing to run a trace experiment while GDB is
2180 disconnected. */
2181 PACKET_DisconnectedTracing_feature,
2182
2183 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2184 PACKET_augmented_libraries_svr4_read_feature,
2185
f4abbc16
MM
2186 /* Support for the qXfer:btrace-conf:read packet. */
2187 PACKET_qXfer_btrace_conf,
2188
d33501a5
MM
2189 /* Support for the Qbtrace-conf:bts:size packet. */
2190 PACKET_Qbtrace_conf_bts_size,
2191
f7e6eed5
PA
2192 /* Support for swbreak+ feature. */
2193 PACKET_swbreak_feature,
2194
2195 /* Support for hwbreak+ feature. */
2196 PACKET_hwbreak_feature,
2197
89245bc0
DB
2198 /* Support for fork events. */
2199 PACKET_fork_event_feature,
2200
2201 /* Support for vfork events. */
2202 PACKET_vfork_event_feature,
2203
b20a6524
MM
2204 /* Support for the Qbtrace-conf:pt:size packet. */
2205 PACKET_Qbtrace_conf_pt_size,
2206
94585166
DB
2207 /* Support for exec events. */
2208 PACKET_exec_event_feature,
2209
750ce8d1
YQ
2210 /* Support for query supported vCont actions. */
2211 PACKET_vContSupported,
2212
de979965
PA
2213 /* Support remote CTRL-C. */
2214 PACKET_vCtrlC,
2215
f2faf941
PA
2216 /* Support TARGET_WAITKIND_NO_RESUMED. */
2217 PACKET_no_resumed,
2218
2c2e7f87
LM
2219 /* Support for memory tagging, allocation tag fetch/store
2220 packets and the tag violation stop replies. */
2221 PACKET_memory_tagging_feature,
2222
444abaca
DJ
2223 PACKET_MAX
2224};
506fb367 2225
5b6d1e4f
PA
2226/* FIXME: needs to be per-remote-target. Ignoring this for now,
2227 assuming all remote targets are the same server (thus all support
2228 the same packets). */
444abaca 2229static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 2230
f7e6eed5
PA
2231/* Returns the packet's corresponding "set remote foo-packet" command
2232 state. See struct packet_config for more details. */
2233
2234static enum auto_boolean
2235packet_set_cmd_state (int packet)
2236{
2237 return remote_protocol_packets[packet].detect;
2238}
2239
4082afcc
PA
2240/* Returns whether a given packet or feature is supported. This takes
2241 into account the state of the corresponding "set remote foo-packet"
2242 command, which may be used to bypass auto-detection. */
dc8acb97 2243
4082afcc
PA
2244static enum packet_support
2245packet_config_support (struct packet_config *config)
2246{
2247 switch (config->detect)
444abaca 2248 {
4082afcc
PA
2249 case AUTO_BOOLEAN_TRUE:
2250 return PACKET_ENABLE;
2251 case AUTO_BOOLEAN_FALSE:
2252 return PACKET_DISABLE;
2253 case AUTO_BOOLEAN_AUTO:
2254 return config->support;
2255 default:
557b4d76 2256 gdb_assert_not_reached ("bad switch");
444abaca 2257 }
4082afcc
PA
2258}
2259
2260/* Same as packet_config_support, but takes the packet's enum value as
2261 argument. */
2262
2263static enum packet_support
2264packet_support (int packet)
2265{
2266 struct packet_config *config = &remote_protocol_packets[packet];
2267
2268 return packet_config_support (config);
dc8acb97
MS
2269}
2270
5a2468f5 2271static void
444abaca
DJ
2272show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2273 struct cmd_list_element *c,
2274 const char *value)
5a2468f5 2275{
444abaca 2276 struct packet_config *packet;
1d7fe7f0 2277 gdb_assert (c->var.has_value ());
5a2468f5 2278
444abaca
DJ
2279 for (packet = remote_protocol_packets;
2280 packet < &remote_protocol_packets[PACKET_MAX];
2281 packet++)
2282 {
fcef6471 2283 if (c == packet->show_cmd)
444abaca 2284 {
7514a661 2285 show_packet_config_cmd (file, packet);
444abaca
DJ
2286 return;
2287 }
2288 }
9b20d036 2289 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 2290 c->name);
5a2468f5
JM
2291}
2292
d471ea57
AC
2293/* Should we try one of the 'Z' requests? */
2294
2295enum Z_packet_type
2296{
2297 Z_PACKET_SOFTWARE_BP,
2298 Z_PACKET_HARDWARE_BP,
2299 Z_PACKET_WRITE_WP,
2300 Z_PACKET_READ_WP,
2301 Z_PACKET_ACCESS_WP,
2302 NR_Z_PACKET_TYPES
2303};
96baa820 2304
d471ea57 2305/* For compatibility with older distributions. Provide a ``set remote
23860348 2306 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 2307
7f19b9a2 2308static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
2309
2310static void
eb4c3f4a 2311set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
fba45db2 2312 struct cmd_list_element *c)
96baa820 2313{
d471ea57 2314 int i;
a744cf53 2315
d471ea57 2316 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 2317 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
2318}
2319
2320static void
08546159
AC
2321show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2322 struct cmd_list_element *c,
2323 const char *value)
96baa820 2324{
d471ea57 2325 int i;
a744cf53 2326
d471ea57
AC
2327 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2328 {
7514a661 2329 show_packet_config_cmd (file, &remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 2330 }
96baa820
JM
2331}
2332
4082afcc
PA
2333/* Returns true if the multi-process extensions are in effect. */
2334
2335static int
2336remote_multi_process_p (struct remote_state *rs)
2337{
2338 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2339}
2340
de0d863e
DB
2341/* Returns true if fork events are supported. */
2342
2343static int
2344remote_fork_event_p (struct remote_state *rs)
2345{
2346 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2347}
2348
c269dbdb
DB
2349/* Returns true if vfork events are supported. */
2350
2351static int
2352remote_vfork_event_p (struct remote_state *rs)
2353{
2354 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2355}
2356
d46addbb
DB
2357/* Returns true if exec events are supported. */
2358
2359static int
2360remote_exec_event_p (struct remote_state *rs)
2361{
2362 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2363}
2364
2c2e7f87
LM
2365/* Returns true if memory tagging is supported, false otherwise. */
2366
2367static bool
2368remote_memory_tagging_p ()
2369{
2370 return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE;
2371}
2372
cbb8991c
DB
2373/* Insert fork catchpoint target routine. If fork events are enabled
2374 then return success, nothing more to do. */
2375
f6ac5f3d
PA
2376int
2377remote_target::insert_fork_catchpoint (int pid)
cbb8991c
DB
2378{
2379 struct remote_state *rs = get_remote_state ();
2380
2381 return !remote_fork_event_p (rs);
2382}
2383
2384/* Remove fork catchpoint target routine. Nothing to do, just
2385 return success. */
2386
f6ac5f3d
PA
2387int
2388remote_target::remove_fork_catchpoint (int pid)
cbb8991c
DB
2389{
2390 return 0;
2391}
2392
2393/* Insert vfork catchpoint target routine. If vfork events are enabled
2394 then return success, nothing more to do. */
2395
f6ac5f3d
PA
2396int
2397remote_target::insert_vfork_catchpoint (int pid)
cbb8991c
DB
2398{
2399 struct remote_state *rs = get_remote_state ();
2400
2401 return !remote_vfork_event_p (rs);
2402}
2403
2404/* Remove vfork catchpoint target routine. Nothing to do, just
2405 return success. */
2406
f6ac5f3d
PA
2407int
2408remote_target::remove_vfork_catchpoint (int pid)
cbb8991c
DB
2409{
2410 return 0;
2411}
2412
d46addbb
DB
2413/* Insert exec catchpoint target routine. If exec events are
2414 enabled, just return success. */
2415
f6ac5f3d
PA
2416int
2417remote_target::insert_exec_catchpoint (int pid)
d46addbb
DB
2418{
2419 struct remote_state *rs = get_remote_state ();
2420
2421 return !remote_exec_event_p (rs);
2422}
2423
2424/* Remove exec catchpoint target routine. Nothing to do, just
2425 return success. */
2426
f6ac5f3d
PA
2427int
2428remote_target::remove_exec_catchpoint (int pid)
d46addbb
DB
2429{
2430 return 0;
2431}
2432
c906108c
SS
2433\f
2434
ffdd69cf
TT
2435/* Take advantage of the fact that the TID field is not used, to tag
2436 special ptids with it set to != 0. */
2437static const ptid_t magic_null_ptid (42000, -1, 1);
2438static const ptid_t not_sent_ptid (42000, -2, 1);
2439static const ptid_t any_thread_ptid (42000, 0, 1);
79d7f229 2440
0b16c5cf
PA
2441/* Find out if the stub attached to PID (and hence GDB should offer to
2442 detach instead of killing it when bailing out). */
2443
6b8edb51
PA
2444int
2445remote_target::remote_query_attached (int pid)
0b16c5cf
PA
2446{
2447 struct remote_state *rs = get_remote_state ();
bba74b36 2448 size_t size = get_remote_packet_size ();
0b16c5cf 2449
4082afcc 2450 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
2451 return 0;
2452
2453 if (remote_multi_process_p (rs))
8d64371b 2454 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
0b16c5cf 2455 else
8d64371b 2456 xsnprintf (rs->buf.data (), size, "qAttached");
0b16c5cf
PA
2457
2458 putpkt (rs->buf);
8d64371b 2459 getpkt (&rs->buf, 0);
0b16c5cf
PA
2460
2461 switch (packet_ok (rs->buf,
1554e9be 2462 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
2463 {
2464 case PACKET_OK:
8d64371b 2465 if (strcmp (rs->buf.data (), "1") == 0)
0b16c5cf
PA
2466 return 1;
2467 break;
2468 case PACKET_ERROR:
8d64371b 2469 warning (_("Remote failure reply: %s"), rs->buf.data ());
0b16c5cf
PA
2470 break;
2471 case PACKET_UNKNOWN:
2472 break;
2473 }
2474
2475 return 0;
2476}
2477
49c62f2e
PA
2478/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2479 has been invented by GDB, instead of reported by the target. Since
2480 we can be connected to a remote system before before knowing about
2481 any inferior, mark the target with execution when we find the first
2482 inferior. If ATTACHED is 1, then we had just attached to this
2483 inferior. If it is 0, then we just created this inferior. If it
2484 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
2485 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2486 attempt to open this inferior's executable as the main executable
2487 if no main executable is open already. */
1941c569 2488
6b8edb51 2489inferior *
9ab8741a 2490remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
6b8edb51 2491 int try_open_exec)
1941c569 2492{
1941c569
PA
2493 struct inferior *inf;
2494
0b16c5cf
PA
2495 /* Check whether this process we're learning about is to be
2496 considered attached, or if is to be considered to have been
2497 spawned by the stub. */
2498 if (attached == -1)
2499 attached = remote_query_attached (pid);
2500
f5656ead 2501 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
2502 {
2503 /* If the target shares code across all inferiors, then every
2504 attach adds a new inferior. */
2505 inf = add_inferior (pid);
2506
2507 /* ... and every inferior is bound to the same program space.
2508 However, each inferior may still have its own address
2509 space. */
2510 inf->aspace = maybe_new_address_space ();
2511 inf->pspace = current_program_space;
2512 }
2513 else
2514 {
2515 /* In the traditional debugging scenario, there's a 1-1 match
2516 between program/address spaces. We simply bind the inferior
2517 to the program space's address space. */
2518 inf = current_inferior ();
78f2c40a
PA
2519
2520 /* However, if the current inferior is already bound to a
2521 process, find some other empty inferior. */
2522 if (inf->pid != 0)
2523 {
2524 inf = nullptr;
2525 for (inferior *it : all_inferiors ())
2526 if (it->pid == 0)
2527 {
2528 inf = it;
2529 break;
2530 }
2531 }
2532 if (inf == nullptr)
2533 {
2534 /* Since all inferiors were already bound to a process, add
2535 a new inferior. */
2536 inf = add_inferior_with_spaces ();
2537 }
2538 switch_to_inferior_no_thread (inf);
02980c56 2539 inf->push_target (this);
6c95b8df
PA
2540 inferior_appeared (inf, pid);
2541 }
1941c569 2542
0b16c5cf 2543 inf->attach_flag = attached;
49c62f2e 2544 inf->fake_pid_p = fake_pid_p;
0b16c5cf 2545
1b6e6f5c
GB
2546 /* If no main executable is currently open then attempt to
2547 open the file that was executed to create this inferior. */
835205d0 2548 if (try_open_exec && get_exec_file (0) == NULL)
bb805577 2549 exec_file_locate_attach (pid, 0, 1);
1b6e6f5c 2550
a2fedca9
PW
2551 /* Check for exec file mismatch, and let the user solve it. */
2552 validate_exec_file (1);
2553
1941c569
PA
2554 return inf;
2555}
2556
7aabaf9d 2557static remote_thread_info *get_remote_thread_info (thread_info *thread);
5b6d1e4f
PA
2558static remote_thread_info *get_remote_thread_info (remote_target *target,
2559 ptid_t ptid);
85ad3aaf 2560
1941c569 2561/* Add thread PTID to GDB's thread list. Tag it as executing/running
b622494e
AB
2562 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2563 remote_state::starting_up flag) is true then the new thread is added
2564 silently, otherwise the new thread will be announced to the user. */
1941c569 2565
00431a78 2566thread_info *
b622494e
AB
2567remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2568 bool silent_p)
c906108c 2569{
b7ea362b 2570 struct remote_state *rs = get_remote_state ();
85ad3aaf 2571 struct thread_info *thread;
b7ea362b
PA
2572
2573 /* GDB historically didn't pull threads in the initial connection
2574 setup. If the remote target doesn't even have a concept of
2575 threads (e.g., a bare-metal target), even if internally we
2576 consider that a single-threaded target, mentioning a new thread
2577 might be confusing to the user. Be silent then, preserving the
2578 age old behavior. */
b622494e 2579 if (rs->starting_up || silent_p)
5b6d1e4f 2580 thread = add_thread_silent (this, ptid);
b7ea362b 2581 else
5b6d1e4f 2582 thread = add_thread (this, ptid);
1941c569 2583
c9d22089
SM
2584 /* We start by assuming threads are resumed. That state then gets updated
2585 when we process a matching stop reply. */
2586 get_remote_thread_info (thread)->set_resumed ();
2587
5b6d1e4f
PA
2588 set_executing (this, ptid, executing);
2589 set_running (this, ptid, running);
00431a78
PA
2590
2591 return thread;
1941c569
PA
2592}
2593
2594/* Come here when we learn about a thread id from the remote target.
2595 It may be the first time we hear about such thread, so take the
2596 opportunity to add it to GDB's thread list. In case this is the
2597 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
2598 GDB's inferior list as well. EXECUTING indicates whether the
2599 thread is (internally) executing or stopped. */
1941c569 2600
6b8edb51 2601void
8a82de58 2602remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
1941c569 2603{
0d5b594f
PA
2604 /* In non-stop mode, we assume new found threads are (externally)
2605 running until proven otherwise with a stop reply. In all-stop,
2606 we can only get here if all threads are stopped. */
8a82de58 2607 bool running = target_is_non_stop_p ();
0d5b594f 2608
c906108c
SS
2609 /* If this is a new thread, add it to GDB's thread list.
2610 If we leave it up to WFI to do this, bad things will happen. */
82f73884 2611
5b6d1e4f 2612 thread_info *tp = find_thread_ptid (this, currthread);
00431a78 2613 if (tp != NULL && tp->state == THREAD_EXITED)
82f73884
PA
2614 {
2615 /* We're seeing an event on a thread id we knew had exited.
2616 This has to be a new thread reusing the old id. Add it. */
b622494e 2617 remote_add_thread (currthread, running, executing, false);
82f73884
PA
2618 return;
2619 }
2620
5b6d1e4f 2621 if (!in_thread_list (this, currthread))
c0a2216e 2622 {
1941c569 2623 struct inferior *inf = NULL;
e99b03dc 2624 int pid = currthread.pid ();
1941c569 2625
0e998d96 2626 if (inferior_ptid.is_pid ()
e99b03dc 2627 && pid == inferior_ptid.pid ())
c0a2216e
PA
2628 {
2629 /* inferior_ptid has no thread member yet. This can happen
2630 with the vAttach -> remote_wait,"TAAthread:" path if the
2631 stub doesn't support qC. This is the first stop reported
2632 after an attach, so this is the main thread. Update the
2633 ptid in the thread list. */
5b6d1e4f
PA
2634 if (in_thread_list (this, ptid_t (pid)))
2635 thread_change_ptid (this, inferior_ptid, currthread);
bad34192
PA
2636 else
2637 {
0ac55310 2638 thread_info *thr
b622494e 2639 = remote_add_thread (currthread, running, executing, false);
0ac55310 2640 switch_to_thread (thr);
bad34192 2641 }
dc146f7c 2642 return;
c0a2216e 2643 }
82f73884 2644
d7e15655 2645 if (magic_null_ptid == inferior_ptid)
c0a2216e
PA
2646 {
2647 /* inferior_ptid is not set yet. This can happen with the
2648 vRun -> remote_wait,"TAAthread:" path if the stub
2649 doesn't support qC. This is the first stop reported
2650 after an attach, so this is the main thread. Update the
2651 ptid in the thread list. */
5b6d1e4f 2652 thread_change_ptid (this, inferior_ptid, currthread);
82f73884 2653 return;
c0a2216e 2654 }
82f73884 2655
29c87f7f
PA
2656 /* When connecting to a target remote, or to a target
2657 extended-remote which already was debugging an inferior, we
2658 may not know about it yet. Add it before adding its child
2659 thread, so notifications are emitted in a sensible order. */
5b6d1e4f 2660 if (find_inferior_pid (this, currthread.pid ()) == NULL)
49c62f2e
PA
2661 {
2662 struct remote_state *rs = get_remote_state ();
9ab8741a 2663 bool fake_pid_p = !remote_multi_process_p (rs);
49c62f2e
PA
2664
2665 inf = remote_add_inferior (fake_pid_p,
e99b03dc 2666 currthread.pid (), -1, 1);
49c62f2e 2667 }
29c87f7f 2668
82f73884 2669 /* This is really a new thread. Add it. */
00431a78 2670 thread_info *new_thr
b622494e 2671 = remote_add_thread (currthread, running, executing, false);
1941c569
PA
2672
2673 /* If we found a new inferior, let the common code do whatever
2674 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
2675 breakpoints), unless we're just setting up an all-stop
2676 connection. */
1941c569 2677 if (inf != NULL)
b7ea362b
PA
2678 {
2679 struct remote_state *rs = get_remote_state ();
2680
6efcd9a8 2681 if (!rs->starting_up)
00431a78 2682 notice_new_inferior (new_thr, executing, 0);
b7ea362b 2683 }
c0a2216e 2684 }
c906108c
SS
2685}
2686
85ad3aaf 2687/* Return THREAD's private thread data, creating it if necessary. */
dc146f7c 2688
7aabaf9d
SM
2689static remote_thread_info *
2690get_remote_thread_info (thread_info *thread)
dc146f7c 2691{
85ad3aaf 2692 gdb_assert (thread != NULL);
dc146f7c 2693
85ad3aaf 2694 if (thread->priv == NULL)
7aabaf9d 2695 thread->priv.reset (new remote_thread_info);
dc146f7c 2696
7aabaf9d 2697 return static_cast<remote_thread_info *> (thread->priv.get ());
85ad3aaf
PA
2698}
2699
5b6d1e4f
PA
2700/* Return PTID's private thread data, creating it if necessary. */
2701
7aabaf9d 2702static remote_thread_info *
5b6d1e4f 2703get_remote_thread_info (remote_target *target, ptid_t ptid)
85ad3aaf 2704{
5b6d1e4f 2705 thread_info *thr = find_thread_ptid (target, ptid);
00431a78 2706 return get_remote_thread_info (thr);
dc146f7c
VP
2707}
2708
74531fed
PA
2709/* Call this function as a result of
2710 1) A halt indication (T packet) containing a thread id
2711 2) A direct query of currthread
0df8b418 2712 3) Successful execution of set thread */
74531fed
PA
2713
2714static void
47f8a51d 2715record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 2716{
47f8a51d 2717 rs->general_thread = currthread;
74531fed
PA
2718}
2719
89be2091
DJ
2720/* If 'QPassSignals' is supported, tell the remote stub what signals
2721 it can simply pass through to the inferior without reporting. */
2722
f6ac5f3d 2723void
adc6a863 2724remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
89be2091 2725{
4082afcc 2726 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
2727 {
2728 char *pass_packet, *p;
adc6a863 2729 int count = 0;
747dc59d 2730 struct remote_state *rs = get_remote_state ();
89be2091 2731
adc6a863
PA
2732 gdb_assert (pass_signals.size () < 256);
2733 for (size_t i = 0; i < pass_signals.size (); i++)
89be2091 2734 {
2455069d 2735 if (pass_signals[i])
89be2091
DJ
2736 count++;
2737 }
224c3ddb 2738 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
2739 strcpy (pass_packet, "QPassSignals:");
2740 p = pass_packet + strlen (pass_packet);
adc6a863 2741 for (size_t i = 0; i < pass_signals.size (); i++)
89be2091 2742 {
2455069d 2743 if (pass_signals[i])
89be2091
DJ
2744 {
2745 if (i >= 16)
2746 *p++ = tohex (i >> 4);
2747 *p++ = tohex (i & 15);
2748 if (count)
2749 *p++ = ';';
2750 else
2751 break;
2752 count--;
2753 }
2754 }
2755 *p = 0;
747dc59d 2756 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 2757 {
89be2091 2758 putpkt (pass_packet);
8d64371b 2759 getpkt (&rs->buf, 0);
8dc5b319 2760 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
84d53fa9 2761 xfree (rs->last_pass_packet);
747dc59d 2762 rs->last_pass_packet = pass_packet;
89be2091
DJ
2763 }
2764 else
2765 xfree (pass_packet);
2766 }
2767}
2768
82075af2
JS
2769/* If 'QCatchSyscalls' is supported, tell the remote stub
2770 to report syscalls to GDB. */
2771
f6ac5f3d
PA
2772int
2773remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2774 gdb::array_view<const int> syscall_counts)
82075af2 2775{
b80406ac 2776 const char *catch_packet;
82075af2
JS
2777 enum packet_result result;
2778 int n_sysno = 0;
2779
2780 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2781 {
2782 /* Not supported. */
2783 return 1;
2784 }
2785
649a140c 2786 if (needed && any_count == 0)
82075af2 2787 {
649a140c
PA
2788 /* Count how many syscalls are to be caught. */
2789 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2790 {
649a140c 2791 if (syscall_counts[i] != 0)
82075af2
JS
2792 n_sysno++;
2793 }
2794 }
2795
2189c312
SM
2796 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
2797 pid, needed, any_count, n_sysno);
82075af2 2798
1b81856f 2799 std::string built_packet;
82075af2
JS
2800 if (needed)
2801 {
2802 /* Prepare a packet with the sysno list, assuming max 8+1
2803 characters for a sysno. If the resulting packet size is too
2804 big, fallback on the non-selective packet. */
2805 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
1b81856f
PA
2806 built_packet.reserve (maxpktsz);
2807 built_packet = "QCatchSyscalls:1";
649a140c 2808 if (any_count == 0)
82075af2 2809 {
649a140c
PA
2810 /* Add in each syscall to be caught. */
2811 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2812 {
649a140c
PA
2813 if (syscall_counts[i] != 0)
2814 string_appendf (built_packet, ";%zx", i);
82075af2
JS
2815 }
2816 }
1b81856f 2817 if (built_packet.size () > get_remote_packet_size ())
82075af2
JS
2818 {
2819 /* catch_packet too big. Fallback to less efficient
2820 non selective mode, with GDB doing the filtering. */
b80406ac 2821 catch_packet = "QCatchSyscalls:1";
82075af2 2822 }
b80406ac 2823 else
1b81856f 2824 catch_packet = built_packet.c_str ();
82075af2
JS
2825 }
2826 else
b80406ac 2827 catch_packet = "QCatchSyscalls:0";
82075af2 2828
b80406ac 2829 struct remote_state *rs = get_remote_state ();
82075af2 2830
b80406ac 2831 putpkt (catch_packet);
8d64371b 2832 getpkt (&rs->buf, 0);
b80406ac
TT
2833 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2834 if (result == PACKET_OK)
2835 return 0;
2836 else
2837 return -1;
82075af2
JS
2838}
2839
9b224c5e
PA
2840/* If 'QProgramSignals' is supported, tell the remote stub what
2841 signals it should pass through to the inferior when detaching. */
2842
f6ac5f3d 2843void
adc6a863 2844remote_target::program_signals (gdb::array_view<const unsigned char> signals)
9b224c5e 2845{
4082afcc 2846 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
2847 {
2848 char *packet, *p;
adc6a863 2849 int count = 0;
5e4a05c4 2850 struct remote_state *rs = get_remote_state ();
9b224c5e 2851
adc6a863
PA
2852 gdb_assert (signals.size () < 256);
2853 for (size_t i = 0; i < signals.size (); i++)
9b224c5e
PA
2854 {
2855 if (signals[i])
2856 count++;
2857 }
224c3ddb 2858 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2859 strcpy (packet, "QProgramSignals:");
2860 p = packet + strlen (packet);
adc6a863 2861 for (size_t i = 0; i < signals.size (); i++)
9b224c5e
PA
2862 {
2863 if (signal_pass_state (i))
2864 {
2865 if (i >= 16)
2866 *p++ = tohex (i >> 4);
2867 *p++ = tohex (i & 15);
2868 if (count)
2869 *p++ = ';';
2870 else
2871 break;
2872 count--;
2873 }
2874 }
2875 *p = 0;
5e4a05c4
TT
2876 if (!rs->last_program_signals_packet
2877 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2878 {
9b224c5e 2879 putpkt (packet);
8d64371b 2880 getpkt (&rs->buf, 0);
8dc5b319 2881 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2882 xfree (rs->last_program_signals_packet);
2883 rs->last_program_signals_packet = packet;
9b224c5e
PA
2884 }
2885 else
2886 xfree (packet);
2887 }
2888}
2889
79d7f229
PA
2890/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2891 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2892 thread. If GEN is set, set the general thread, if not, then set
2893 the step/continue thread. */
6b8edb51
PA
2894void
2895remote_target::set_thread (ptid_t ptid, int gen)
c906108c 2896{
d01949b6 2897 struct remote_state *rs = get_remote_state ();
47f8a51d 2898 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
8d64371b
TT
2899 char *buf = rs->buf.data ();
2900 char *endbuf = buf + get_remote_packet_size ();
c906108c 2901
d7e15655 2902 if (state == ptid)
c906108c
SS
2903 return;
2904
79d7f229
PA
2905 *buf++ = 'H';
2906 *buf++ = gen ? 'g' : 'c';
d7e15655 2907 if (ptid == magic_null_ptid)
79d7f229 2908 xsnprintf (buf, endbuf - buf, "0");
d7e15655 2909 else if (ptid == any_thread_ptid)
79d7f229 2910 xsnprintf (buf, endbuf - buf, "0");
d7e15655 2911 else if (ptid == minus_one_ptid)
79d7f229
PA
2912 xsnprintf (buf, endbuf - buf, "-1");
2913 else
82f73884 2914 write_ptid (buf, endbuf, ptid);
79d7f229 2915 putpkt (rs->buf);
8d64371b 2916 getpkt (&rs->buf, 0);
c906108c 2917 if (gen)
47f8a51d 2918 rs->general_thread = ptid;
c906108c 2919 else
47f8a51d 2920 rs->continue_thread = ptid;
c906108c 2921}
79d7f229 2922
6b8edb51
PA
2923void
2924remote_target::set_general_thread (ptid_t ptid)
79d7f229
PA
2925{
2926 set_thread (ptid, 1);
2927}
2928
6b8edb51
PA
2929void
2930remote_target::set_continue_thread (ptid_t ptid)
79d7f229
PA
2931{
2932 set_thread (ptid, 0);
2933}
2934
3c9c4b83
PA
2935/* Change the remote current process. Which thread within the process
2936 ends up selected isn't important, as long as it is the same process
2937 as what INFERIOR_PTID points to.
2938
2939 This comes from that fact that there is no explicit notion of
2940 "selected process" in the protocol. The selected process for
2941 general operations is the process the selected general thread
2942 belongs to. */
2943
6b8edb51
PA
2944void
2945remote_target::set_general_process ()
3c9c4b83
PA
2946{
2947 struct remote_state *rs = get_remote_state ();
2948
2949 /* If the remote can't handle multiple processes, don't bother. */
8020350c 2950 if (!remote_multi_process_p (rs))
3c9c4b83
PA
2951 return;
2952
2953 /* We only need to change the remote current thread if it's pointing
2954 at some other process. */
e99b03dc 2955 if (rs->general_thread.pid () != inferior_ptid.pid ())
3c9c4b83
PA
2956 set_general_thread (inferior_ptid);
2957}
2958
c906108c 2959\f
7d1a114c
PA
2960/* Return nonzero if this is the main thread that we made up ourselves
2961 to model non-threaded targets as single-threaded. */
c906108c
SS
2962
2963static int
f6ac5f3d 2964remote_thread_always_alive (ptid_t ptid)
c906108c 2965{
d7e15655 2966 if (ptid == magic_null_ptid)
c0a2216e
PA
2967 /* The main thread is always alive. */
2968 return 1;
2969
e38504b3 2970 if (ptid.pid () != 0 && ptid.lwp () == 0)
c0a2216e
PA
2971 /* The main thread is always alive. This can happen after a
2972 vAttach, if the remote side doesn't support
2973 multi-threading. */
2974 return 1;
2975
7d1a114c
PA
2976 return 0;
2977}
2978
2979/* Return nonzero if the thread PTID is still alive on the remote
2980 system. */
2981
57810aa7 2982bool
f6ac5f3d 2983remote_target::thread_alive (ptid_t ptid)
7d1a114c
PA
2984{
2985 struct remote_state *rs = get_remote_state ();
2986 char *p, *endp;
2987
2988 /* Check if this is a thread that we made up ourselves to model
2989 non-threaded targets as single-threaded. */
f6ac5f3d 2990 if (remote_thread_always_alive (ptid))
7d1a114c
PA
2991 return 1;
2992
8d64371b
TT
2993 p = rs->buf.data ();
2994 endp = p + get_remote_packet_size ();
82f73884
PA
2995
2996 *p++ = 'T';
2997 write_ptid (p, endp, ptid);
2998
2e9f7625 2999 putpkt (rs->buf);
8d64371b 3000 getpkt (&rs->buf, 0);
2e9f7625 3001 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
3002}
3003
79efa585
SM
3004/* Return a pointer to a thread name if we know it and NULL otherwise.
3005 The thread_info object owns the memory for the name. */
3006
f6ac5f3d
PA
3007const char *
3008remote_target::thread_name (struct thread_info *info)
79efa585
SM
3009{
3010 if (info->priv != NULL)
a9334058
SM
3011 {
3012 const std::string &name = get_remote_thread_info (info)->name;
3013 return !name.empty () ? name.c_str () : NULL;
3014 }
79efa585
SM
3015
3016 return NULL;
3017}
3018
c906108c
SS
3019/* About these extended threadlist and threadinfo packets. They are
3020 variable length packets but, the fields within them are often fixed
30baf67b 3021 length. They are redundant enough to send over UDP as is the
c906108c
SS
3022 remote protocol in general. There is a matching unit test module
3023 in libstub. */
3024
23860348 3025/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 3026 libstub protocol encoding, and remote.c. It is not particularly
23860348 3027 changable. */
cce74817
JM
3028
3029/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 3030 Plan to fix this. */
cce74817 3031
23860348 3032typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 3033
9d1f7ab2 3034/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 3035 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
3036
3037struct gdb_ext_thread_info
c5aa993b 3038 {
23860348 3039 threadref threadid; /* External form of thread reference. */
2bc416ba 3040 int active; /* Has state interesting to GDB?
23860348 3041 regs, stack. */
2bc416ba 3042 char display[256]; /* Brief state display, name,
cedea757 3043 blocked/suspended. */
23860348 3044 char shortname[32]; /* To be used to name threads. */
2bc416ba 3045 char more_display[256]; /* Long info, statistics, queue depth,
23860348 3046 whatever. */
c5aa993b 3047 };
cce74817
JM
3048
3049/* The volume of remote transfers can be limited by submitting
3050 a mask containing bits specifying the desired information.
3051 Use a union of these values as the 'selection' parameter to
0df8b418 3052 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
3053
3054#define TAG_THREADID 1
3055#define TAG_EXISTS 2
3056#define TAG_DISPLAY 4
3057#define TAG_THREADNAME 8
c5aa993b 3058#define TAG_MOREDISPLAY 16
cce74817 3059
23860348 3060#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 3061
cecb1912 3062static const char *unpack_nibble (const char *buf, int *val);
cce74817 3063
cecb1912 3064static const char *unpack_byte (const char *buf, int *value);
cce74817 3065
a14ed312 3066static char *pack_int (char *buf, int value);
cce74817 3067
cecb1912 3068static const char *unpack_int (const char *buf, int *value);
cce74817 3069
cecb1912 3070static const char *unpack_string (const char *src, char *dest, int length);
cce74817 3071
23860348 3072static char *pack_threadid (char *pkt, threadref *id);
cce74817 3073
cecb1912 3074static const char *unpack_threadid (const char *inbuf, threadref *id);
cce74817 3075
23860348 3076void int_to_threadref (threadref *id, int value);
cce74817 3077
23860348 3078static int threadref_to_int (threadref *ref);
cce74817 3079
23860348 3080static void copy_threadref (threadref *dest, threadref *src);
cce74817 3081
23860348 3082static int threadmatch (threadref *dest, threadref *src);
cce74817 3083
2bc416ba 3084static char *pack_threadinfo_request (char *pkt, int mode,
23860348 3085 threadref *id);
cce74817 3086
a14ed312
KB
3087static char *pack_threadlist_request (char *pkt, int startflag,
3088 int threadcount,
23860348 3089 threadref *nextthread);
cce74817 3090
23860348 3091static int remote_newthread_step (threadref *ref, void *context);
cce74817 3092
82f73884
PA
3093
3094/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3095 buffer we're allowed to write to. Returns
3096 BUF+CHARACTERS_WRITTEN. */
3097
6b8edb51
PA
3098char *
3099remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
82f73884
PA
3100{
3101 int pid, tid;
3102 struct remote_state *rs = get_remote_state ();
3103
3104 if (remote_multi_process_p (rs))
3105 {
e99b03dc 3106 pid = ptid.pid ();
82f73884
PA
3107 if (pid < 0)
3108 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3109 else
3110 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3111 }
e38504b3 3112 tid = ptid.lwp ();
82f73884
PA
3113 if (tid < 0)
3114 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3115 else
3116 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3117
3118 return buf;
3119}
3120
256642e8
PA
3121/* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3122 last parsed char. Returns null_ptid if no thread id is found, and
3123 throws an error if the thread id has an invalid format. */
82f73884
PA
3124
3125static ptid_t
256642e8 3126read_ptid (const char *buf, const char **obuf)
82f73884 3127{
256642e8
PA
3128 const char *p = buf;
3129 const char *pp;
82f73884 3130 ULONGEST pid = 0, tid = 0;
82f73884
PA
3131
3132 if (*p == 'p')
3133 {
3134 /* Multi-process ptid. */
3135 pp = unpack_varlen_hex (p + 1, &pid);
3136 if (*pp != '.')
b37520b6 3137 error (_("invalid remote ptid: %s"), p);
82f73884
PA
3138
3139 p = pp;
3140 pp = unpack_varlen_hex (p + 1, &tid);
3141 if (obuf)
3142 *obuf = pp;
184ea2f7 3143 return ptid_t (pid, tid);
82f73884
PA
3144 }
3145
3146 /* No multi-process. Just a tid. */
3147 pp = unpack_varlen_hex (p, &tid);
3148
c9f35b34
KB
3149 /* Return null_ptid when no thread id is found. */
3150 if (p == pp)
3151 {
3152 if (obuf)
3153 *obuf = pp;
3154 return null_ptid;
3155 }
3156
2f761de2
TBA
3157 /* Since the stub is not sending a process id, default to what's
3158 current_inferior, unless it doesn't have a PID yet. If so,
ca19bf23
PA
3159 then since there's no way to know the pid of the reported
3160 threads, use the magic number. */
2f761de2
TBA
3161 inferior *inf = current_inferior ();
3162 if (inf->pid == 0)
e99b03dc 3163 pid = magic_null_ptid.pid ();
ca19bf23 3164 else
2f761de2 3165 pid = inf->pid;
82f73884
PA
3166
3167 if (obuf)
3168 *obuf = pp;
184ea2f7 3169 return ptid_t (pid, tid);
82f73884
PA
3170}
3171
c906108c 3172static int
fba45db2 3173stubhex (int ch)
c906108c
SS
3174{
3175 if (ch >= 'a' && ch <= 'f')
3176 return ch - 'a' + 10;
3177 if (ch >= '0' && ch <= '9')
3178 return ch - '0';
3179 if (ch >= 'A' && ch <= 'F')
3180 return ch - 'A' + 10;
3181 return -1;
3182}
3183
3184static int
cecb1912 3185stub_unpack_int (const char *buff, int fieldlength)
c906108c
SS
3186{
3187 int nibble;
3188 int retval = 0;
3189
3190 while (fieldlength)
3191 {
3192 nibble = stubhex (*buff++);
3193 retval |= nibble;
3194 fieldlength--;
3195 if (fieldlength)
3196 retval = retval << 4;
3197 }
3198 return retval;
3199}
3200
cecb1912
SM
3201static const char *
3202unpack_nibble (const char *buf, int *val)
c906108c 3203{
b7589f7d 3204 *val = fromhex (*buf++);
c906108c
SS
3205 return buf;
3206}
3207
cecb1912
SM
3208static const char *
3209unpack_byte (const char *buf, int *value)
c906108c
SS
3210{
3211 *value = stub_unpack_int (buf, 2);
3212 return buf + 2;
3213}
3214
3215static char *
fba45db2 3216pack_int (char *buf, int value)
c906108c
SS
3217{
3218 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3219 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3220 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3221 buf = pack_hex_byte (buf, (value & 0xff));
3222 return buf;
3223}
3224
cecb1912
SM
3225static const char *
3226unpack_int (const char *buf, int *value)
c906108c
SS
3227{
3228 *value = stub_unpack_int (buf, 8);
3229 return buf + 8;
3230}
3231
23860348 3232#if 0 /* Currently unused, uncomment when needed. */
a14ed312 3233static char *pack_string (char *pkt, char *string);
c906108c
SS
3234
3235static char *
fba45db2 3236pack_string (char *pkt, char *string)
c906108c
SS
3237{
3238 char ch;
3239 int len;
3240
3241 len = strlen (string);
3242 if (len > 200)
23860348 3243 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
3244 pkt = pack_hex_byte (pkt, len);
3245 while (len-- > 0)
3246 {
3247 ch = *string++;
3248 if ((ch == '\0') || (ch == '#'))
23860348 3249 ch = '*'; /* Protect encapsulation. */
c906108c
SS
3250 *pkt++ = ch;
3251 }
3252 return pkt;
3253}
3254#endif /* 0 (unused) */
3255
cecb1912
SM
3256static const char *
3257unpack_string (const char *src, char *dest, int length)
c906108c
SS
3258{
3259 while (length--)
3260 *dest++ = *src++;
3261 *dest = '\0';
3262 return src;
3263}
3264
3265static char *
fba45db2 3266pack_threadid (char *pkt, threadref *id)
c906108c
SS
3267{
3268 char *limit;
3269 unsigned char *altid;
3270
3271 altid = (unsigned char *) id;
3272 limit = pkt + BUF_THREAD_ID_SIZE;
3273 while (pkt < limit)
3274 pkt = pack_hex_byte (pkt, *altid++);
3275 return pkt;
3276}
3277
3278
cecb1912
SM
3279static const char *
3280unpack_threadid (const char *inbuf, threadref *id)
c906108c
SS
3281{
3282 char *altref;
cecb1912 3283 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
c906108c
SS
3284 int x, y;
3285
3286 altref = (char *) id;
3287
3288 while (inbuf < limit)
3289 {
3290 x = stubhex (*inbuf++);
3291 y = stubhex (*inbuf++);
3292 *altref++ = (x << 4) | y;
3293 }
3294 return inbuf;
3295}
3296
3297/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 3298 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
3299 to use 64bit thread references internally. This is an adapter
3300 function. */
3301
3302void
fba45db2 3303int_to_threadref (threadref *id, int value)
c906108c
SS
3304{
3305 unsigned char *scan;
3306
3307 scan = (unsigned char *) id;
3308 {
3309 int i = 4;
3310 while (i--)
3311 *scan++ = 0;
3312 }
3313 *scan++ = (value >> 24) & 0xff;
3314 *scan++ = (value >> 16) & 0xff;
3315 *scan++ = (value >> 8) & 0xff;
3316 *scan++ = (value & 0xff);
3317}
3318
3319static int
fba45db2 3320threadref_to_int (threadref *ref)
c906108c
SS
3321{
3322 int i, value = 0;
3323 unsigned char *scan;
3324
cfd77fa1 3325 scan = *ref;
c906108c
SS
3326 scan += 4;
3327 i = 4;
3328 while (i-- > 0)
3329 value = (value << 8) | ((*scan++) & 0xff);
3330 return value;
3331}
3332
3333static void
fba45db2 3334copy_threadref (threadref *dest, threadref *src)
c906108c
SS
3335{
3336 int i;
3337 unsigned char *csrc, *cdest;
3338
3339 csrc = (unsigned char *) src;
3340 cdest = (unsigned char *) dest;
3341 i = 8;
3342 while (i--)
3343 *cdest++ = *csrc++;
3344}
3345
3346static int
fba45db2 3347threadmatch (threadref *dest, threadref *src)
c906108c 3348{
23860348 3349 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
3350#if 0
3351 unsigned char *srcp, *destp;
3352 int i, result;
3353 srcp = (char *) src;
3354 destp = (char *) dest;
3355
3356 result = 1;
3357 while (i-- > 0)
3358 result &= (*srcp++ == *destp++) ? 1 : 0;
3359 return result;
3360#endif
3361 return 1;
3362}
3363
3364/*
c5aa993b
JM
3365 threadid:1, # always request threadid
3366 context_exists:2,
3367 display:4,
3368 unique_name:8,
3369 more_display:16
3370 */
c906108c
SS
3371
3372/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3373
3374static char *
fba45db2 3375pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 3376{
23860348
MS
3377 *pkt++ = 'q'; /* Info Query */
3378 *pkt++ = 'P'; /* process or thread info */
3379 pkt = pack_int (pkt, mode); /* mode */
c906108c 3380 pkt = pack_threadid (pkt, id); /* threadid */
23860348 3381 *pkt = '\0'; /* terminate */
c906108c
SS
3382 return pkt;
3383}
3384
23860348 3385/* These values tag the fields in a thread info response packet. */
c906108c 3386/* Tagging the fields allows us to request specific fields and to
23860348 3387 add more fields as time goes by. */
c906108c 3388
23860348 3389#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 3390#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 3391 fetch registers and its stack? */
c5aa993b 3392#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 3393#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 3394#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 3395 the process. */
c906108c 3396
6b8edb51 3397int
cecb1912 3398remote_target::remote_unpack_thread_info_response (const char *pkt,
6b8edb51
PA
3399 threadref *expectedref,
3400 gdb_ext_thread_info *info)
c906108c 3401{
d01949b6 3402 struct remote_state *rs = get_remote_state ();
c906108c 3403 int mask, length;
cfd77fa1 3404 int tag;
c906108c 3405 threadref ref;
cecb1912 3406 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
c906108c
SS
3407 int retval = 1;
3408
23860348 3409 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
3410 info->active = 0;
3411 info->display[0] = '\0';
3412 info->shortname[0] = '\0';
3413 info->more_display[0] = '\0';
3414
23860348
MS
3415 /* Assume the characters indicating the packet type have been
3416 stripped. */
c906108c
SS
3417 pkt = unpack_int (pkt, &mask); /* arg mask */
3418 pkt = unpack_threadid (pkt, &ref);
3419
3420 if (mask == 0)
8a3fe4f8 3421 warning (_("Incomplete response to threadinfo request."));
c906108c 3422 if (!threadmatch (&ref, expectedref))
23860348 3423 { /* This is an answer to a different request. */
8a3fe4f8 3424 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
3425 return 0;
3426 }
3427 copy_threadref (&info->threadid, &ref);
3428
405feb71 3429 /* Loop on tagged fields , try to bail if something goes wrong. */
c906108c 3430
23860348
MS
3431 /* Packets are terminated with nulls. */
3432 while ((pkt < limit) && mask && *pkt)
c906108c
SS
3433 {
3434 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
3435 pkt = unpack_byte (pkt, &length); /* length */
3436 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 3437 {
8a3fe4f8 3438 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
3439 retval = 0;
3440 break;
3441 }
3442 if (tag == TAG_THREADID)
3443 {
3444 if (length != 16)
3445 {
8a3fe4f8 3446 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
3447 retval = 0;
3448 break;
3449 }
3450 pkt = unpack_threadid (pkt, &ref);
3451 mask = mask & ~TAG_THREADID;
3452 continue;
3453 }
3454 if (tag == TAG_EXISTS)
3455 {
3456 info->active = stub_unpack_int (pkt, length);
3457 pkt += length;
3458 mask = mask & ~(TAG_EXISTS);
3459 if (length > 8)
3460 {
8a3fe4f8 3461 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
3462 retval = 0;
3463 break;
3464 }
3465 continue;
3466 }
3467 if (tag == TAG_THREADNAME)
3468 {
3469 pkt = unpack_string (pkt, &info->shortname[0], length);
3470 mask = mask & ~TAG_THREADNAME;
3471 continue;
3472 }
3473 if (tag == TAG_DISPLAY)
3474 {
3475 pkt = unpack_string (pkt, &info->display[0], length);
3476 mask = mask & ~TAG_DISPLAY;
3477 continue;
3478 }
3479 if (tag == TAG_MOREDISPLAY)
3480 {
3481 pkt = unpack_string (pkt, &info->more_display[0], length);
3482 mask = mask & ~TAG_MOREDISPLAY;
3483 continue;
3484 }
8a3fe4f8 3485 warning (_("ERROR RMT: unknown thread info tag."));
23860348 3486 break; /* Not a tag we know about. */
c906108c
SS
3487 }
3488 return retval;
3489}
3490
6b8edb51
PA
3491int
3492remote_target::remote_get_threadinfo (threadref *threadid,
3493 int fieldset,
3494 gdb_ext_thread_info *info)
c906108c 3495{
d01949b6 3496 struct remote_state *rs = get_remote_state ();
c906108c 3497 int result;
c906108c 3498
8d64371b 3499 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
2e9f7625 3500 putpkt (rs->buf);
8d64371b 3501 getpkt (&rs->buf, 0);
3084dd77
PA
3502
3503 if (rs->buf[0] == '\0')
3504 return 0;
3505
8d64371b 3506 result = remote_unpack_thread_info_response (&rs->buf[2],
23860348 3507 threadid, info);
c906108c
SS
3508 return result;
3509}
3510
c906108c
SS
3511/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3512
3513static char *
fba45db2
KB
3514pack_threadlist_request (char *pkt, int startflag, int threadcount,
3515 threadref *nextthread)
c906108c
SS
3516{
3517 *pkt++ = 'q'; /* info query packet */
3518 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 3519 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
3520 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3521 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3522 *pkt = '\0';
3523 return pkt;
3524}
3525
3526/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3527
6b8edb51 3528int
cecb1912 3529remote_target::parse_threadlist_response (const char *pkt, int result_limit,
6b8edb51
PA
3530 threadref *original_echo,
3531 threadref *resultlist,
3532 int *doneflag)
c906108c 3533{
d01949b6 3534 struct remote_state *rs = get_remote_state ();
c906108c
SS
3535 int count, resultcount, done;
3536
3537 resultcount = 0;
3538 /* Assume the 'q' and 'M chars have been stripped. */
cecb1912 3539 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
23860348 3540 /* done parse past here */
c906108c
SS
3541 pkt = unpack_byte (pkt, &count); /* count field */
3542 pkt = unpack_nibble (pkt, &done);
3543 /* The first threadid is the argument threadid. */
3544 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3545 while ((count-- > 0) && (pkt < limit))
3546 {
3547 pkt = unpack_threadid (pkt, resultlist++);
3548 if (resultcount++ >= result_limit)
3549 break;
3550 }
3551 if (doneflag)
3552 *doneflag = done;
3553 return resultcount;
3554}
3555
6dc54d91
PA
3556/* Fetch the next batch of threads from the remote. Returns -1 if the
3557 qL packet is not supported, 0 on error and 1 on success. */
3558
6b8edb51
PA
3559int
3560remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3561 int result_limit, int *done, int *result_count,
3562 threadref *threadlist)
c906108c 3563{
d01949b6 3564 struct remote_state *rs = get_remote_state ();
c906108c
SS
3565 int result = 1;
3566
405feb71 3567 /* Truncate result limit to be smaller than the packet size. */
3e43a32a
MS
3568 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3569 >= get_remote_packet_size ())
ea9c271d 3570 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 3571
8d64371b
TT
3572 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3573 nextthread);
6d820c5c 3574 putpkt (rs->buf);
8d64371b
TT
3575 getpkt (&rs->buf, 0);
3576 if (rs->buf[0] == '\0')
6dc54d91
PA
3577 {
3578 /* Packet not supported. */
3579 return -1;
3580 }
3581
3582 *result_count =
8d64371b 3583 parse_threadlist_response (&rs->buf[2], result_limit,
6dc54d91 3584 &rs->echo_nextthread, threadlist, done);
c906108c 3585
0d031856 3586 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 3587 {
23860348 3588 /* FIXME: This is a good reason to drop the packet. */
405feb71
TV
3589 /* Possibly, there is a duplicate response. */
3590 /* Possibilities :
dda83cd7
SM
3591 retransmit immediatly - race conditions
3592 retransmit after timeout - yes
3593 exit
3594 wait for packet, then exit
c906108c 3595 */
8a3fe4f8 3596 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 3597 return 0; /* I choose simply exiting. */
c906108c
SS
3598 }
3599 if (*result_count <= 0)
3600 {
3601 if (*done != 1)
3602 {
8a3fe4f8 3603 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
3604 result = 0;
3605 }
3606 return result; /* break; */
3607 }
3608 if (*result_count > result_limit)
3609 {
3610 *result_count = 0;
8a3fe4f8 3611 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
3612 return 0;
3613 }
3614 return result;
3615}
3616
6dc54d91
PA
3617/* Fetch the list of remote threads, with the qL packet, and call
3618 STEPFUNCTION for each thread found. Stops iterating and returns 1
3619 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3620 STEPFUNCTION returns false. If the packet is not supported,
3621 returns -1. */
c906108c 3622
6b8edb51
PA
3623int
3624remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3625 void *context, int looplimit)
c906108c 3626{
0d031856 3627 struct remote_state *rs = get_remote_state ();
c906108c
SS
3628 int done, i, result_count;
3629 int startflag = 1;
3630 int result = 1;
3631 int loopcount = 0;
c906108c
SS
3632
3633 done = 0;
3634 while (!done)
3635 {
3636 if (loopcount++ > looplimit)
3637 {
3638 result = 0;
8a3fe4f8 3639 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
3640 break;
3641 }
6dc54d91
PA
3642 result = remote_get_threadlist (startflag, &rs->nextthread,
3643 MAXTHREADLISTRESULTS,
3644 &done, &result_count,
3645 rs->resultthreadlist);
3646 if (result <= 0)
3647 break;
23860348 3648 /* Clear for later iterations. */
c906108c
SS
3649 startflag = 0;
3650 /* Setup to resume next batch of thread references, set nextthread. */
3651 if (result_count >= 1)
0d031856
TT
3652 copy_threadref (&rs->nextthread,
3653 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
3654 i = 0;
3655 while (result_count--)
6dc54d91
PA
3656 {
3657 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3658 {
3659 result = 0;
3660 break;
3661 }
3662 }
c906108c
SS
3663 }
3664 return result;
3665}
3666
6dc54d91
PA
3667/* A thread found on the remote target. */
3668
21fe1c75 3669struct thread_item
6dc54d91 3670{
21fe1c75
SM
3671 explicit thread_item (ptid_t ptid_)
3672 : ptid (ptid_)
3673 {}
3674
3675 thread_item (thread_item &&other) = default;
3676 thread_item &operator= (thread_item &&other) = default;
3677
3678 DISABLE_COPY_AND_ASSIGN (thread_item);
3679
6dc54d91
PA
3680 /* The thread's PTID. */
3681 ptid_t ptid;
3682
21fe1c75
SM
3683 /* The thread's extra info. */
3684 std::string extra;
6dc54d91 3685
21fe1c75
SM
3686 /* The thread's name. */
3687 std::string name;
79efa585 3688
6dc54d91 3689 /* The core the thread was running on. -1 if not known. */
21fe1c75 3690 int core = -1;
f6327dcb
KB
3691
3692 /* The thread handle associated with the thread. */
21fe1c75 3693 gdb::byte_vector thread_handle;
21fe1c75 3694};
6dc54d91
PA
3695
3696/* Context passed around to the various methods listing remote
3697 threads. As new threads are found, they're added to the ITEMS
3698 vector. */
3699
3700struct threads_listing_context
3701{
21fe1c75
SM
3702 /* Return true if this object contains an entry for a thread with ptid
3703 PTID. */
6dc54d91 3704
21fe1c75
SM
3705 bool contains_thread (ptid_t ptid) const
3706 {
3707 auto match_ptid = [&] (const thread_item &item)
3708 {
3709 return item.ptid == ptid;
3710 };
80134cf5 3711
21fe1c75
SM
3712 auto it = std::find_if (this->items.begin (),
3713 this->items.end (),
3714 match_ptid);
80134cf5 3715
21fe1c75
SM
3716 return it != this->items.end ();
3717 }
80134cf5 3718
21fe1c75 3719 /* Remove the thread with ptid PTID. */
80134cf5 3720
21fe1c75
SM
3721 void remove_thread (ptid_t ptid)
3722 {
3723 auto match_ptid = [&] (const thread_item &item)
3724 {
dda83cd7 3725 return item.ptid == ptid;
21fe1c75 3726 };
cbb8991c 3727
21fe1c75
SM
3728 auto it = std::remove_if (this->items.begin (),
3729 this->items.end (),
3730 match_ptid);
cbb8991c 3731
21fe1c75
SM
3732 if (it != this->items.end ())
3733 this->items.erase (it);
3734 }
3735
3736 /* The threads found on the remote target. */
3737 std::vector<thread_item> items;
3738};
cbb8991c 3739
c906108c 3740static int
6dc54d91 3741remote_newthread_step (threadref *ref, void *data)
c906108c 3742{
19ba03f4
SM
3743 struct threads_listing_context *context
3744 = (struct threads_listing_context *) data;
21fe1c75
SM
3745 int pid = inferior_ptid.pid ();
3746 int lwp = threadref_to_int (ref);
3747 ptid_t ptid (pid, lwp);
6dc54d91 3748
21fe1c75 3749 context->items.emplace_back (ptid);
6dc54d91 3750
c906108c
SS
3751 return 1; /* continue iterator */
3752}
3753
3754#define CRAZY_MAX_THREADS 1000
3755
6b8edb51
PA
3756ptid_t
3757remote_target::remote_current_thread (ptid_t oldpid)
c906108c 3758{
d01949b6 3759 struct remote_state *rs = get_remote_state ();
c906108c
SS
3760
3761 putpkt ("qC");
8d64371b 3762 getpkt (&rs->buf, 0);
2e9f7625 3763 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34 3764 {
256642e8 3765 const char *obuf;
c9f35b34
KB
3766 ptid_t result;
3767
3768 result = read_ptid (&rs->buf[2], &obuf);
2189c312
SM
3769 if (*obuf != '\0')
3770 remote_debug_printf ("warning: garbage in qC reply");
c9f35b34
KB
3771
3772 return result;
3773 }
c906108c
SS
3774 else
3775 return oldpid;
3776}
3777
6dc54d91 3778/* List remote threads using the deprecated qL packet. */
cce74817 3779
6b8edb51
PA
3780int
3781remote_target::remote_get_threads_with_ql (threads_listing_context *context)
c906108c 3782{
6dc54d91
PA
3783 if (remote_threadlist_iterator (remote_newthread_step, context,
3784 CRAZY_MAX_THREADS) >= 0)
3785 return 1;
3786
3787 return 0;
c906108c
SS
3788}
3789
dc146f7c
VP
3790#if defined(HAVE_LIBEXPAT)
3791
dc146f7c
VP
3792static void
3793start_thread (struct gdb_xml_parser *parser,
3794 const struct gdb_xml_element *element,
4d0fdd9b
SM
3795 void *user_data,
3796 std::vector<gdb_xml_value> &attributes)
dc146f7c 3797{
19ba03f4
SM
3798 struct threads_listing_context *data
3799 = (struct threads_listing_context *) user_data;
3d2c1d41 3800 struct gdb_xml_value *attr;
dc146f7c 3801
4d0fdd9b 3802 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
21fe1c75
SM
3803 ptid_t ptid = read_ptid (id, NULL);
3804
3805 data->items.emplace_back (ptid);
3806 thread_item &item = data->items.back ();
dc146f7c 3807
3d2c1d41
PA
3808 attr = xml_find_attribute (attributes, "core");
3809 if (attr != NULL)
4d0fdd9b 3810 item.core = *(ULONGEST *) attr->value.get ();
dc146f7c 3811
79efa585 3812 attr = xml_find_attribute (attributes, "name");
21fe1c75 3813 if (attr != NULL)
4d0fdd9b 3814 item.name = (const char *) attr->value.get ();
79efa585 3815
f6327dcb
KB
3816 attr = xml_find_attribute (attributes, "handle");
3817 if (attr != NULL)
4d0fdd9b 3818 item.thread_handle = hex2bin ((const char *) attr->value.get ());
dc146f7c
VP
3819}
3820
3821static void
3822end_thread (struct gdb_xml_parser *parser,
3823 const struct gdb_xml_element *element,
3824 void *user_data, const char *body_text)
3825{
19ba03f4
SM
3826 struct threads_listing_context *data
3827 = (struct threads_listing_context *) user_data;
dc146f7c 3828
21fe1c75
SM
3829 if (body_text != NULL && *body_text != '\0')
3830 data->items.back ().extra = body_text;
dc146f7c
VP
3831}
3832
3833const struct gdb_xml_attribute thread_attributes[] = {
3834 { "id", GDB_XML_AF_NONE, NULL, NULL },
3835 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3836 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
f6327dcb 3837 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3838 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3839};
3840
3841const struct gdb_xml_element thread_children[] = {
3842 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3843};
3844
3845const struct gdb_xml_element threads_children[] = {
3846 { "thread", thread_attributes, thread_children,
3847 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3848 start_thread, end_thread },
3849 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3850};
3851
3852const struct gdb_xml_element threads_elements[] = {
3853 { "threads", NULL, threads_children,
3854 GDB_XML_EF_NONE, NULL, NULL },
3855 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3856};
3857
3858#endif
3859
6dc54d91 3860/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3861
6b8edb51
PA
3862int
3863remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
0f71a2f6 3864{
dc146f7c 3865#if defined(HAVE_LIBEXPAT)
4082afcc 3866 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3867 {
9018be22 3868 gdb::optional<gdb::char_vector> xml
6b8edb51 3869 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
efc0eabd 3870
9018be22 3871 if (xml && (*xml)[0] != '\0')
dc146f7c 3872 {
6dc54d91 3873 gdb_xml_parse_quick (_("threads"), "threads.dtd",
9018be22 3874 threads_elements, xml->data (), context);
dc146f7c
VP
3875 }
3876
6dc54d91 3877 return 1;
dc146f7c
VP
3878 }
3879#endif
3880
6dc54d91
PA
3881 return 0;
3882}
3883
3884/* List remote threads using qfThreadInfo/qsThreadInfo. */
3885
6b8edb51
PA
3886int
3887remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
6dc54d91
PA
3888{
3889 struct remote_state *rs = get_remote_state ();
3890
b80fafe3 3891 if (rs->use_threadinfo_query)
9d1f7ab2 3892 {
256642e8 3893 const char *bufp;
6dc54d91 3894
9d1f7ab2 3895 putpkt ("qfThreadInfo");
8d64371b
TT
3896 getpkt (&rs->buf, 0);
3897 bufp = rs->buf.data ();
9d1f7ab2 3898 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3899 {
9d1f7ab2
MS
3900 while (*bufp++ == 'm') /* reply contains one or more TID */
3901 {
3902 do
3903 {
21fe1c75
SM
3904 ptid_t ptid = read_ptid (bufp, &bufp);
3905 context->items.emplace_back (ptid);
9d1f7ab2
MS
3906 }
3907 while (*bufp++ == ','); /* comma-separated list */
3908 putpkt ("qsThreadInfo");
8d64371b
TT
3909 getpkt (&rs->buf, 0);
3910 bufp = rs->buf.data ();
9d1f7ab2 3911 }
6dc54d91
PA
3912 return 1;
3913 }
3914 else
3915 {
3916 /* Packet not recognized. */
3917 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3918 }
3919 }
3920
6dc54d91
PA
3921 return 0;
3922}
3923
a05575d3
TBA
3924/* Return true if INF only has one non-exited thread. */
3925
3926static bool
3927has_single_non_exited_thread (inferior *inf)
3928{
3929 int count = 0;
3930 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
3931 if (++count > 1)
3932 break;
3933 return count == 1;
3934}
3935
e8032dde 3936/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3937 targets. */
3938
f6ac5f3d
PA
3939void
3940remote_target::update_thread_list ()
6dc54d91 3941{
6dc54d91 3942 struct threads_listing_context context;
ab970af1 3943 int got_list = 0;
e8032dde 3944
6dc54d91
PA
3945 /* We have a few different mechanisms to fetch the thread list. Try
3946 them all, starting with the most preferred one first, falling
3947 back to older methods. */
6b8edb51
PA
3948 if (remote_get_threads_with_qxfer (&context)
3949 || remote_get_threads_with_qthreadinfo (&context)
3950 || remote_get_threads_with_ql (&context))
6dc54d91 3951 {
ab970af1
PA
3952 got_list = 1;
3953
21fe1c75 3954 if (context.items.empty ()
f6ac5f3d 3955 && remote_thread_always_alive (inferior_ptid))
7d1a114c
PA
3956 {
3957 /* Some targets don't really support threads, but still
3958 reply an (empty) thread list in response to the thread
3959 listing packets, instead of replying "packet not
3960 supported". Exit early so we don't delete the main
3961 thread. */
7d1a114c
PA
3962 return;
3963 }
3964
ab970af1
PA
3965 /* CONTEXT now holds the current thread list on the remote
3966 target end. Delete GDB-side threads no longer found on the
3967 target. */
08036331 3968 for (thread_info *tp : all_threads_safe ())
cbb8991c 3969 {
5b6d1e4f
PA
3970 if (tp->inf->process_target () != this)
3971 continue;
3972
21fe1c75 3973 if (!context.contains_thread (tp->ptid))
ab970af1 3974 {
a05575d3
TBA
3975 /* Do not remove the thread if it is the last thread in
3976 the inferior. This situation happens when we have a
3977 pending exit process status to process. Otherwise we
3978 may end up with a seemingly live inferior (i.e. pid
3979 != 0) that has no threads. */
3980 if (has_single_non_exited_thread (tp->inf))
3981 continue;
3982
ab970af1 3983 /* Not found. */
00431a78 3984 delete_thread (tp);
ab970af1 3985 }
cbb8991c
DB
3986 }
3987
3988 /* Remove any unreported fork child threads from CONTEXT so
3989 that we don't interfere with follow fork, which is where
3990 creation of such threads is handled. */
3991 remove_new_fork_children (&context);
74531fed 3992
ab970af1 3993 /* And now add threads we don't know about yet to our list. */
21fe1c75 3994 for (thread_item &item : context.items)
6dc54d91 3995 {
21fe1c75 3996 if (item.ptid != null_ptid)
6dc54d91 3997 {
6dc54d91 3998 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
3999 executing until proven otherwise with a stop reply.
4000 In all-stop, we can only get here if all threads are
6dc54d91 4001 stopped. */
8a82de58 4002 bool executing = target_is_non_stop_p ();
6dc54d91 4003
21fe1c75 4004 remote_notice_new_inferior (item.ptid, executing);
6dc54d91 4005
5b6d1e4f 4006 thread_info *tp = find_thread_ptid (this, item.ptid);
00431a78 4007 remote_thread_info *info = get_remote_thread_info (tp);
21fe1c75 4008 info->core = item.core;
7aabaf9d
SM
4009 info->extra = std::move (item.extra);
4010 info->name = std::move (item.name);
4011 info->thread_handle = std::move (item.thread_handle);
6dc54d91
PA
4012 }
4013 }
4014 }
4015
ab970af1
PA
4016 if (!got_list)
4017 {
4018 /* If no thread listing method is supported, then query whether
4019 each known thread is alive, one by one, with the T packet.
4020 If the target doesn't support threads at all, then this is a
4021 no-op. See remote_thread_alive. */
4022 prune_threads ();
4023 }
9d1f7ab2
MS
4024}
4025
802188a7 4026/*
9d1f7ab2
MS
4027 * Collect a descriptive string about the given thread.
4028 * The target may say anything it wants to about the thread
4029 * (typically info about its blocked / runnable state, name, etc.).
4030 * This string will appear in the info threads display.
802188a7 4031 *
9d1f7ab2
MS
4032 * Optional: targets are not required to implement this function.
4033 */
4034
f6ac5f3d
PA
4035const char *
4036remote_target::extra_thread_info (thread_info *tp)
9d1f7ab2 4037{
d01949b6 4038 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
4039 int set;
4040 threadref id;
4041 struct gdb_ext_thread_info threadinfo;
9d1f7ab2 4042
5d93a237 4043 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 4044 internal_error (__FILE__, __LINE__,
e2e0b3e5 4045 _("remote_threads_extra_info"));
9d1f7ab2 4046
d7e15655 4047 if (tp->ptid == magic_null_ptid
e38504b3 4048 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
60e569b9
PA
4049 /* This is the main thread which was added by GDB. The remote
4050 server doesn't know about it. */
4051 return NULL;
4052
c76a8ea3
PA
4053 std::string &extra = get_remote_thread_info (tp)->extra;
4054
4055 /* If already have cached info, use it. */
4056 if (!extra.empty ())
4057 return extra.c_str ();
4058
4082afcc 4059 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 4060 {
c76a8ea3
PA
4061 /* If we're using qXfer:threads:read, then the extra info is
4062 included in the XML. So if we didn't have anything cached,
4063 it's because there's really no extra info. */
4064 return NULL;
dc146f7c
VP
4065 }
4066
b80fafe3 4067 if (rs->use_threadextra_query)
9d1f7ab2 4068 {
8d64371b
TT
4069 char *b = rs->buf.data ();
4070 char *endb = b + get_remote_packet_size ();
82f73884
PA
4071
4072 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4073 b += strlen (b);
4074 write_ptid (b, endb, tp->ptid);
4075
2e9f7625 4076 putpkt (rs->buf);
8d64371b 4077 getpkt (&rs->buf, 0);
2e9f7625 4078 if (rs->buf[0] != 0)
9d1f7ab2 4079 {
8d64371b
TT
4080 extra.resize (strlen (rs->buf.data ()) / 2);
4081 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
c76a8ea3 4082 return extra.c_str ();
9d1f7ab2 4083 }
0f71a2f6 4084 }
9d1f7ab2
MS
4085
4086 /* If the above query fails, fall back to the old method. */
b80fafe3 4087 rs->use_threadextra_query = 0;
9d1f7ab2
MS
4088 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4089 | TAG_MOREDISPLAY | TAG_DISPLAY;
e38504b3 4090 int_to_threadref (&id, tp->ptid.lwp ());
9d1f7ab2
MS
4091 if (remote_get_threadinfo (&id, set, &threadinfo))
4092 if (threadinfo.active)
0f71a2f6 4093 {
9d1f7ab2 4094 if (*threadinfo.shortname)
c76a8ea3 4095 string_appendf (extra, " Name: %s", threadinfo.shortname);
9d1f7ab2 4096 if (*threadinfo.display)
c76a8ea3
PA
4097 {
4098 if (!extra.empty ())
4099 extra += ',';
4100 string_appendf (extra, " State: %s", threadinfo.display);
4101 }
9d1f7ab2 4102 if (*threadinfo.more_display)
c5aa993b 4103 {
c76a8ea3
PA
4104 if (!extra.empty ())
4105 extra += ',';
4106 string_appendf (extra, " Priority: %s", threadinfo.more_display);
c5aa993b 4107 }
c76a8ea3 4108 return extra.c_str ();
0f71a2f6 4109 }
9d1f7ab2 4110 return NULL;
0f71a2f6 4111}
c906108c 4112\f
c5aa993b 4113
f6ac5f3d
PA
4114bool
4115remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4116 struct static_tracepoint_marker *marker)
0fb4aa4b
PA
4117{
4118 struct remote_state *rs = get_remote_state ();
8d64371b 4119 char *p = rs->buf.data ();
0fb4aa4b 4120
bba74b36 4121 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
4122 p += strlen (p);
4123 p += hexnumstr (p, addr);
4124 putpkt (rs->buf);
8d64371b
TT
4125 getpkt (&rs->buf, 0);
4126 p = rs->buf.data ();
0fb4aa4b
PA
4127
4128 if (*p == 'E')
4129 error (_("Remote failure reply: %s"), p);
4130
4131 if (*p++ == 'm')
4132 {
256642e8 4133 parse_static_tracepoint_marker_definition (p, NULL, marker);
5d9310c4 4134 return true;
0fb4aa4b
PA
4135 }
4136
5d9310c4 4137 return false;
0fb4aa4b
PA
4138}
4139
f6ac5f3d
PA
4140std::vector<static_tracepoint_marker>
4141remote_target::static_tracepoint_markers_by_strid (const char *strid)
0fb4aa4b
PA
4142{
4143 struct remote_state *rs = get_remote_state ();
5d9310c4 4144 std::vector<static_tracepoint_marker> markers;
256642e8 4145 const char *p;
5d9310c4 4146 static_tracepoint_marker marker;
0fb4aa4b
PA
4147
4148 /* Ask for a first packet of static tracepoint marker
4149 definition. */
4150 putpkt ("qTfSTM");
8d64371b
TT
4151 getpkt (&rs->buf, 0);
4152 p = rs->buf.data ();
0fb4aa4b
PA
4153 if (*p == 'E')
4154 error (_("Remote failure reply: %s"), p);
4155
0fb4aa4b
PA
4156 while (*p++ == 'm')
4157 {
0fb4aa4b
PA
4158 do
4159 {
5d9310c4 4160 parse_static_tracepoint_marker_definition (p, &p, &marker);
0fb4aa4b 4161
5d9310c4
SM
4162 if (strid == NULL || marker.str_id == strid)
4163 markers.push_back (std::move (marker));
0fb4aa4b
PA
4164 }
4165 while (*p++ == ','); /* comma-separated list */
4166 /* Ask for another packet of static tracepoint definition. */
4167 putpkt ("qTsSTM");
8d64371b
TT
4168 getpkt (&rs->buf, 0);
4169 p = rs->buf.data ();
0fb4aa4b
PA
4170 }
4171
0fb4aa4b
PA
4172 return markers;
4173}
4174
4175\f
10760264
JB
4176/* Implement the to_get_ada_task_ptid function for the remote targets. */
4177
f6ac5f3d 4178ptid_t
c80e29db 4179remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
10760264 4180{
184ea2f7 4181 return ptid_t (inferior_ptid.pid (), lwp);
10760264
JB
4182}
4183\f
4184
24b06219 4185/* Restart the remote side; this is an extended protocol operation. */
c906108c 4186
6b8edb51
PA
4187void
4188remote_target::extended_remote_restart ()
c906108c 4189{
d01949b6 4190 struct remote_state *rs = get_remote_state ();
c906108c
SS
4191
4192 /* Send the restart command; for reasons I don't understand the
4193 remote side really expects a number after the "R". */
8d64371b 4194 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
6d820c5c 4195 putpkt (rs->buf);
c906108c 4196
ad9a8f3f 4197 remote_fileio_reset ();
c906108c
SS
4198}
4199\f
4200/* Clean up connection to a remote debugger. */
4201
f6ac5f3d
PA
4202void
4203remote_target::close ()
c906108c 4204{
048094ac 4205 /* Make sure we leave stdin registered in the event loop. */
f6ac5f3d 4206 terminal_ours ();
ce5ce7ed 4207
6b8edb51
PA
4208 trace_reset_local_state ();
4209
4210 delete this;
4211}
4212
4213remote_target::~remote_target ()
4214{
4215 struct remote_state *rs = get_remote_state ();
4216
4217 /* Check for NULL because we may get here with a partially
4218 constructed target/connection. */
4219 if (rs->remote_desc == nullptr)
4220 return;
4221
4222 serial_close (rs->remote_desc);
4223
4224 /* We are destroying the remote target, so we should discard
f48ff2a7 4225 everything of this target. */
6b8edb51 4226 discard_pending_stop_replies_in_queue ();
74531fed 4227
6b8edb51
PA
4228 if (rs->remote_async_inferior_event_token)
4229 delete_async_event_handler (&rs->remote_async_inferior_event_token);
722247f1 4230
97dfbadd 4231 delete rs->notif_state;
c906108c
SS
4232}
4233
23860348 4234/* Query the remote side for the text, data and bss offsets. */
c906108c 4235
6b8edb51
PA
4236void
4237remote_target::get_offsets ()
c906108c 4238{
d01949b6 4239 struct remote_state *rs = get_remote_state ();
2e9f7625 4240 char *buf;
085dd6e6 4241 char *ptr;
31d99776
DJ
4242 int lose, num_segments = 0, do_sections, do_segments;
4243 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
31d99776 4244
a42d7dd8 4245 if (current_program_space->symfile_object_file == NULL)
31d99776 4246 return;
c906108c
SS
4247
4248 putpkt ("qOffsets");
8d64371b
TT
4249 getpkt (&rs->buf, 0);
4250 buf = rs->buf.data ();
c906108c
SS
4251
4252 if (buf[0] == '\000')
4253 return; /* Return silently. Stub doesn't support
23860348 4254 this command. */
c906108c
SS
4255 if (buf[0] == 'E')
4256 {
8a3fe4f8 4257 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
4258 return;
4259 }
4260
4261 /* Pick up each field in turn. This used to be done with scanf, but
4262 scanf will make trouble if CORE_ADDR size doesn't match
4263 conversion directives correctly. The following code will work
4264 with any size of CORE_ADDR. */
4265 text_addr = data_addr = bss_addr = 0;
4266 ptr = buf;
4267 lose = 0;
4268
61012eef 4269 if (startswith (ptr, "Text="))
c906108c
SS
4270 {
4271 ptr += 5;
4272 /* Don't use strtol, could lose on big values. */
4273 while (*ptr && *ptr != ';')
4274 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 4275
61012eef 4276 if (startswith (ptr, ";Data="))
31d99776
DJ
4277 {
4278 ptr += 6;
4279 while (*ptr && *ptr != ';')
4280 data_addr = (data_addr << 4) + fromhex (*ptr++);
4281 }
4282 else
4283 lose = 1;
4284
61012eef 4285 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
4286 {
4287 ptr += 5;
4288 while (*ptr && *ptr != ';')
4289 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 4290
31d99776
DJ
4291 if (bss_addr != data_addr)
4292 warning (_("Target reported unsupported offsets: %s"), buf);
4293 }
4294 else
4295 lose = 1;
4296 }
61012eef 4297 else if (startswith (ptr, "TextSeg="))
c906108c 4298 {
31d99776
DJ
4299 ptr += 8;
4300 /* Don't use strtol, could lose on big values. */
c906108c 4301 while (*ptr && *ptr != ';')
31d99776
DJ
4302 text_addr = (text_addr << 4) + fromhex (*ptr++);
4303 num_segments = 1;
4304
61012eef 4305 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
4306 {
4307 ptr += 9;
4308 while (*ptr && *ptr != ';')
4309 data_addr = (data_addr << 4) + fromhex (*ptr++);
4310 num_segments++;
4311 }
c906108c
SS
4312 }
4313 else
4314 lose = 1;
4315
4316 if (lose)
8a3fe4f8 4317 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
4318 else if (*ptr != '\0')
4319 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 4320
a42d7dd8
TT
4321 objfile *objf = current_program_space->symfile_object_file;
4322 section_offsets offs = objf->section_offsets;
c906108c 4323
98badbfd 4324 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
31d99776
DJ
4325 do_segments = (data != NULL);
4326 do_sections = num_segments == 0;
c906108c 4327
28c32713 4328 if (num_segments > 0)
31d99776 4329 {
31d99776
DJ
4330 segments[0] = text_addr;
4331 segments[1] = data_addr;
4332 }
28c32713
JB
4333 /* If we have two segments, we can still try to relocate everything
4334 by assuming that the .text and .data offsets apply to the whole
4335 text and data segments. Convert the offsets given in the packet
4336 to base addresses for symfile_map_offsets_to_segments. */
68b888ff 4337 else if (data != nullptr && data->segments.size () == 2)
28c32713 4338 {
68b888ff
SM
4339 segments[0] = data->segments[0].base + text_addr;
4340 segments[1] = data->segments[1].base + data_addr;
28c32713
JB
4341 num_segments = 2;
4342 }
8d385431
DJ
4343 /* If the object file has only one segment, assume that it is text
4344 rather than data; main programs with no writable data are rare,
4345 but programs with no code are useless. Of course the code might
4346 have ended up in the data segment... to detect that we would need
4347 the permissions here. */
68b888ff 4348 else if (data && data->segments.size () == 1)
8d385431 4349 {
68b888ff 4350 segments[0] = data->segments[0].base + text_addr;
8d385431
DJ
4351 num_segments = 1;
4352 }
28c32713
JB
4353 /* There's no way to relocate by segment. */
4354 else
4355 do_segments = 0;
31d99776
DJ
4356
4357 if (do_segments)
4358 {
98badbfd 4359 int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
62982abd
SM
4360 data.get (), offs,
4361 num_segments, segments);
31d99776
DJ
4362
4363 if (ret == 0 && !do_sections)
3e43a32a
MS
4364 error (_("Can not handle qOffsets TextSeg "
4365 "response with this symbol file"));
31d99776
DJ
4366
4367 if (ret > 0)
4368 do_sections = 0;
4369 }
c906108c 4370
31d99776
DJ
4371 if (do_sections)
4372 {
a42d7dd8 4373 offs[SECT_OFF_TEXT (objf)] = text_addr;
31d99776 4374
3e43a32a
MS
4375 /* This is a temporary kludge to force data and bss to use the
4376 same offsets because that's what nlmconv does now. The real
4377 solution requires changes to the stub and remote.c that I
4378 don't have time to do right now. */
31d99776 4379
a42d7dd8
TT
4380 offs[SECT_OFF_DATA (objf)] = data_addr;
4381 offs[SECT_OFF_BSS (objf)] = data_addr;
31d99776 4382 }
c906108c 4383
a42d7dd8 4384 objfile_relocate (objf, offs);
c906108c
SS
4385}
4386
9a7071a8 4387/* Send interrupt_sequence to remote target. */
6b8edb51
PA
4388
4389void
4390remote_target::send_interrupt_sequence ()
9a7071a8 4391{
5d93a237
TT
4392 struct remote_state *rs = get_remote_state ();
4393
9a7071a8 4394 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 4395 remote_serial_write ("\x03", 1);
9a7071a8 4396 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 4397 serial_send_break (rs->remote_desc);
9a7071a8
JB
4398 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4399 {
5d93a237 4400 serial_send_break (rs->remote_desc);
c33e31fd 4401 remote_serial_write ("g", 1);
9a7071a8
JB
4402 }
4403 else
4404 internal_error (__FILE__, __LINE__,
4405 _("Invalid value for interrupt_sequence_mode: %s."),
4406 interrupt_sequence_mode);
4407}
4408
3405876a
PA
4409
4410/* If STOP_REPLY is a T stop reply, look for the "thread" register,
4411 and extract the PTID. Returns NULL_PTID if not found. */
4412
4413static ptid_t
e3b2741b 4414stop_reply_extract_thread (const char *stop_reply)
3405876a
PA
4415{
4416 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4417 {
256642e8 4418 const char *p;
3405876a
PA
4419
4420 /* Txx r:val ; r:val (...) */
4421 p = &stop_reply[3];
4422
4423 /* Look for "register" named "thread". */
4424 while (*p != '\0')
4425 {
256642e8 4426 const char *p1;
3405876a
PA
4427
4428 p1 = strchr (p, ':');
4429 if (p1 == NULL)
4430 return null_ptid;
4431
4432 if (strncmp (p, "thread", p1 - p) == 0)
4433 return read_ptid (++p1, &p);
4434
4435 p1 = strchr (p, ';');
4436 if (p1 == NULL)
4437 return null_ptid;
4438 p1++;
4439
4440 p = p1;
4441 }
4442 }
4443
4444 return null_ptid;
4445}
4446
b7ea362b
PA
4447/* Determine the remote side's current thread. If we have a stop
4448 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4449 "thread" register we can extract the current thread from. If not,
4450 ask the remote which is the current thread with qC. The former
4451 method avoids a roundtrip. */
4452
6b8edb51 4453ptid_t
e3b2741b 4454remote_target::get_current_thread (const char *wait_status)
b7ea362b 4455{
6a49a997 4456 ptid_t ptid = null_ptid;
b7ea362b
PA
4457
4458 /* Note we don't use remote_parse_stop_reply as that makes use of
4459 the target architecture, which we haven't yet fully determined at
4460 this point. */
4461 if (wait_status != NULL)
4462 ptid = stop_reply_extract_thread (wait_status);
d7e15655 4463 if (ptid == null_ptid)
b7ea362b
PA
4464 ptid = remote_current_thread (inferior_ptid);
4465
4466 return ptid;
4467}
4468
49c62f2e
PA
4469/* Query the remote target for which is the current thread/process,
4470 add it to our tables, and update INFERIOR_PTID. The caller is
4471 responsible for setting the state such that the remote end is ready
3405876a
PA
4472 to return the current thread.
4473
4474 This function is called after handling the '?' or 'vRun' packets,
4475 whose response is a stop reply from which we can also try
4476 extracting the thread. If the target doesn't support the explicit
4477 qC query, we infer the current thread from that stop reply, passed
64d38fdd 4478 in in WAIT_STATUS, which may be NULL.
49c62f2e 4479
64d38fdd
JM
4480 The function returns pointer to the main thread of the inferior. */
4481
4482thread_info *
e3b2741b 4483remote_target::add_current_inferior_and_thread (const char *wait_status)
49c62f2e
PA
4484{
4485 struct remote_state *rs = get_remote_state ();
9ab8741a 4486 bool fake_pid_p = false;
49c62f2e 4487
0ac55310 4488 switch_to_no_thread ();
49c62f2e 4489
0ac55310
PA
4490 /* Now, if we have thread information, update the current thread's
4491 ptid. */
87215ad1 4492 ptid_t curr_ptid = get_current_thread (wait_status);
3405876a 4493
87215ad1 4494 if (curr_ptid != null_ptid)
49c62f2e
PA
4495 {
4496 if (!remote_multi_process_p (rs))
9ab8741a 4497 fake_pid_p = true;
49c62f2e
PA
4498 }
4499 else
4500 {
4501 /* Without this, some commands which require an active target
4502 (such as kill) won't work. This variable serves (at least)
4503 double duty as both the pid of the target process (if it has
4504 such), and as a flag indicating that a target is active. */
87215ad1 4505 curr_ptid = magic_null_ptid;
9ab8741a 4506 fake_pid_p = true;
49c62f2e
PA
4507 }
4508
e99b03dc 4509 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
49c62f2e 4510
87215ad1
SDJ
4511 /* Add the main thread and switch to it. Don't try reading
4512 registers yet, since we haven't fetched the target description
4513 yet. */
5b6d1e4f 4514 thread_info *tp = add_thread_silent (this, curr_ptid);
87215ad1 4515 switch_to_thread_no_regs (tp);
64d38fdd
JM
4516
4517 return tp;
49c62f2e
PA
4518}
4519
6efcd9a8
PA
4520/* Print info about a thread that was found already stopped on
4521 connection. */
4522
1edb66d8
SM
4523void
4524remote_target::print_one_stopped_thread (thread_info *thread)
6efcd9a8 4525{
1edb66d8
SM
4526 target_waitstatus ws;
4527
4528 /* If there is a pending waitstatus, use it. If there isn't it's because
4529 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4530 and process_initial_stop_replies decided it wasn't interesting to save
4531 and report to the core. */
4532 if (thread->has_pending_waitstatus ())
4533 {
4534 ws = thread->pending_waitstatus ();
4535 thread->clear_pending_waitstatus ();
4536 }
4537 else
4538 {
183be222 4539 ws.set_stopped (GDB_SIGNAL_0);
1edb66d8 4540 }
6efcd9a8 4541
00431a78 4542 switch_to_thread (thread);
1edb66d8 4543 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
6efcd9a8
PA
4544 set_current_sal_from_frame (get_current_frame ());
4545
1edb66d8
SM
4546 /* For "info program". */
4547 set_last_target_status (this, thread->ptid, ws);
6efcd9a8 4548
183be222 4549 if (ws.kind () == TARGET_WAITKIND_STOPPED)
6efcd9a8 4550 {
183be222 4551 enum gdb_signal sig = ws.sig ();
6efcd9a8
PA
4552
4553 if (signal_print_state (sig))
76727919 4554 gdb::observers::signal_received.notify (sig);
6efcd9a8 4555 }
76727919 4556 gdb::observers::normal_stop.notify (NULL, 1);
6efcd9a8
PA
4557}
4558
221e1a37
PA
4559/* Process all initial stop replies the remote side sent in response
4560 to the ? packet. These indicate threads that were already stopped
4561 on initial connection. We mark these threads as stopped and print
4562 their current frame before giving the user the prompt. */
4563
6b8edb51
PA
4564void
4565remote_target::process_initial_stop_replies (int from_tty)
221e1a37
PA
4566{
4567 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
4568 struct thread_info *selected = NULL;
4569 struct thread_info *lowest_stopped = NULL;
4570 struct thread_info *first = NULL;
221e1a37 4571
1edb66d8
SM
4572 /* This is only used when the target is non-stop. */
4573 gdb_assert (target_is_non_stop_p ());
4574
221e1a37
PA
4575 /* Consume the initial pending events. */
4576 while (pending_stop_replies-- > 0)
4577 {
4578 ptid_t waiton_ptid = minus_one_ptid;
4579 ptid_t event_ptid;
4580 struct target_waitstatus ws;
4581 int ignore_event = 0;
4582
221e1a37
PA
4583 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4584 if (remote_debug)
c272a98c 4585 print_target_wait_results (waiton_ptid, event_ptid, ws);
221e1a37 4586
183be222 4587 switch (ws.kind ())
221e1a37
PA
4588 {
4589 case TARGET_WAITKIND_IGNORE:
4590 case TARGET_WAITKIND_NO_RESUMED:
4591 case TARGET_WAITKIND_SIGNALLED:
4592 case TARGET_WAITKIND_EXITED:
4593 /* We shouldn't see these, but if we do, just ignore. */
2189c312 4594 remote_debug_printf ("event ignored");
221e1a37
PA
4595 ignore_event = 1;
4596 break;
4597
221e1a37
PA
4598 default:
4599 break;
4600 }
4601
4602 if (ignore_event)
4603 continue;
4604
5b6d1e4f 4605 thread_info *evthread = find_thread_ptid (this, event_ptid);
221e1a37 4606
183be222 4607 if (ws.kind () == TARGET_WAITKIND_STOPPED)
221e1a37 4608 {
183be222 4609 enum gdb_signal sig = ws.sig ();
221e1a37
PA
4610
4611 /* Stubs traditionally report SIGTRAP as initial signal,
4612 instead of signal 0. Suppress it. */
4613 if (sig == GDB_SIGNAL_TRAP)
4614 sig = GDB_SIGNAL_0;
1edb66d8 4615 evthread->set_stop_signal (sig);
183be222 4616 ws.set_stopped (sig);
6efcd9a8 4617 }
221e1a37 4618
183be222
SM
4619 if (ws.kind () != TARGET_WAITKIND_STOPPED
4620 || ws.sig () != GDB_SIGNAL_0)
1edb66d8 4621 evthread->set_pending_waitstatus (ws);
6efcd9a8 4622
719546c4
SM
4623 set_executing (this, event_ptid, false);
4624 set_running (this, event_ptid, false);
c9d22089 4625 get_remote_thread_info (evthread)->set_not_resumed ();
6efcd9a8
PA
4626 }
4627
4628 /* "Notice" the new inferiors before anything related to
4629 registers/memory. */
5b6d1e4f 4630 for (inferior *inf : all_non_exited_inferiors (this))
6efcd9a8 4631 {
6efcd9a8
PA
4632 inf->needs_setup = 1;
4633
4634 if (non_stop)
4635 {
08036331 4636 thread_info *thread = any_live_thread_of_inferior (inf);
00431a78 4637 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
6efcd9a8
PA
4638 from_tty);
4639 }
4640 }
4641
4642 /* If all-stop on top of non-stop, pause all threads. Note this
4643 records the threads' stop pc, so must be done after "noticing"
4644 the inferiors. */
4645 if (!non_stop)
4646 {
abe8cab7
SM
4647 {
4648 /* At this point, the remote target is not async. It needs to be for
4649 the poll in stop_all_threads to consider events from it, so enable
4650 it temporarily. */
4651 gdb_assert (!this->is_async_p ());
4a570176
TT
4652 SCOPE_EXIT { target_async (false); };
4653 target_async (true);
4f5539f0 4654 stop_all_threads ("remote connect in all-stop");
abe8cab7 4655 }
6efcd9a8
PA
4656
4657 /* If all threads of an inferior were already stopped, we
4658 haven't setup the inferior yet. */
5b6d1e4f 4659 for (inferior *inf : all_non_exited_inferiors (this))
6efcd9a8 4660 {
6efcd9a8
PA
4661 if (inf->needs_setup)
4662 {
08036331 4663 thread_info *thread = any_live_thread_of_inferior (inf);
6efcd9a8
PA
4664 switch_to_thread_no_regs (thread);
4665 setup_inferior (0);
4666 }
4667 }
221e1a37 4668 }
6efcd9a8
PA
4669
4670 /* Now go over all threads that are stopped, and print their current
4671 frame. If all-stop, then if there's a signalled thread, pick
4672 that as current. */
5b6d1e4f 4673 for (thread_info *thread : all_non_exited_threads (this))
6efcd9a8 4674 {
6efcd9a8
PA
4675 if (first == NULL)
4676 first = thread;
4677
4678 if (!non_stop)
00431a78 4679 thread->set_running (false);
6efcd9a8
PA
4680 else if (thread->state != THREAD_STOPPED)
4681 continue;
4682
1edb66d8 4683 if (selected == nullptr && thread->has_pending_waitstatus ())
6efcd9a8
PA
4684 selected = thread;
4685
5d5658a1
PA
4686 if (lowest_stopped == NULL
4687 || thread->inf->num < lowest_stopped->inf->num
4688 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
4689 lowest_stopped = thread;
4690
4691 if (non_stop)
4692 print_one_stopped_thread (thread);
4693 }
4694
4695 /* In all-stop, we only print the status of one thread, and leave
4696 others with their status pending. */
4697 if (!non_stop)
4698 {
08036331 4699 thread_info *thread = selected;
6efcd9a8
PA
4700 if (thread == NULL)
4701 thread = lowest_stopped;
4702 if (thread == NULL)
4703 thread = first;
4704
4705 print_one_stopped_thread (thread);
4706 }
221e1a37
PA
4707}
4708
7a34f66b
AB
4709/* Mark a remote_target as marking (by setting the starting_up flag within
4710 its remote_state) for the lifetime of this object. The reference count
4711 on the remote target is temporarily incremented, to prevent the target
4712 being deleted under our feet. */
4713
4714struct scoped_mark_target_starting
4715{
4716 /* Constructor, TARGET is the target to be marked as starting, its
4717 reference count will be incremented. */
4718 scoped_mark_target_starting (remote_target *target)
4719 : m_remote_target (target)
4720 {
4721 m_remote_target->incref ();
4722 remote_state *rs = m_remote_target->get_remote_state ();
4723 rs->starting_up = true;
4724 }
4725
4726 /* Destructor, mark the target being worked on as no longer starting, and
4727 decrement the reference count. */
4728 ~scoped_mark_target_starting ()
4729 {
4730 remote_state *rs = m_remote_target->get_remote_state ();
4731 rs->starting_up = false;
4732 decref_target (m_remote_target);
4733 }
4734
4735private:
4736
4737 /* The target on which we are operating. */
4738 remote_target *m_remote_target;
4739};
4740
288712bb
AB
4741/* Helper for remote_target::start_remote, start the remote connection and
4742 sync state. Return true if everything goes OK, otherwise, return false.
4743 This function exists so that the scoped_restore created within it will
4744 expire before we return to remote_target::start_remote. */
048094ac 4745
288712bb
AB
4746bool
4747remote_target::start_remote_1 (int from_tty, int extended_p)
c906108c 4748{
2189c312
SM
4749 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4750
c8d104ad
PA
4751 struct remote_state *rs = get_remote_state ();
4752 struct packet_config *noack_config;
8621d6a9 4753
048094ac
PA
4754 /* Signal other parts that we're going through the initial setup,
4755 and so things may not be stable yet. E.g., we don't try to
4756 install tracepoints until we've relocated symbols. Also, a
4757 Ctrl-C before we're connected and synced up can't interrupt the
4758 target. Instead, it offers to drop the (potentially wedged)
4759 connection. */
7a34f66b 4760 scoped_mark_target_starting target_is_starting (this);
048094ac 4761
522002f9 4762 QUIT;
c906108c 4763
9a7071a8
JB
4764 if (interrupt_on_connect)
4765 send_interrupt_sequence ();
4766
57e12211 4767 /* Ack any packet which the remote side has already sent. */
048094ac 4768 remote_serial_write ("+", 1);
1e51243a 4769
c8d104ad
PA
4770 /* The first packet we send to the target is the optional "supported
4771 packets" request. If the target can answer this, it will tell us
4772 which later probes to skip. */
4773 remote_query_supported ();
4774
d914c394 4775 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 4776 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
f6ac5f3d 4777 set_permissions ();
d914c394 4778
57809e5e
JK
4779 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4780 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4781 as a reply to known packet. For packet "vFile:setfs:" it is an
4782 invalid reply and GDB would return error in
4783 remote_hostio_set_filesystem, making remote files access impossible.
4784 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4785 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4786 {
4787 const char v_mustreplyempty[] = "vMustReplyEmpty";
4788
4789 putpkt (v_mustreplyempty);
8d64371b
TT
4790 getpkt (&rs->buf, 0);
4791 if (strcmp (rs->buf.data (), "OK") == 0)
57809e5e 4792 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
8d64371b 4793 else if (strcmp (rs->buf.data (), "") != 0)
57809e5e 4794 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
8d64371b 4795 rs->buf.data ());
57809e5e
JK
4796 }
4797
c8d104ad
PA
4798 /* Next, we possibly activate noack mode.
4799
4800 If the QStartNoAckMode packet configuration is set to AUTO,
4801 enable noack mode if the stub reported a wish for it with
4802 qSupported.
4803
4804 If set to TRUE, then enable noack mode even if the stub didn't
4805 report it in qSupported. If the stub doesn't reply OK, the
4806 session ends with an error.
4807
4808 If FALSE, then don't activate noack mode, regardless of what the
4809 stub claimed should be the default with qSupported. */
4810
4811 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 4812 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
4813 {
4814 putpkt ("QStartNoAckMode");
8d64371b 4815 getpkt (&rs->buf, 0);
c8d104ad
PA
4816 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4817 rs->noack_mode = 1;
4818 }
4819
04bd08de 4820 if (extended_p)
5fe04517
PA
4821 {
4822 /* Tell the remote that we are using the extended protocol. */
4823 putpkt ("!");
8d64371b 4824 getpkt (&rs->buf, 0);
5fe04517
PA
4825 }
4826
9b224c5e
PA
4827 /* Let the target know which signals it is allowed to pass down to
4828 the program. */
4829 update_signals_program_target ();
4830
d962ef82
DJ
4831 /* Next, if the target can specify a description, read it. We do
4832 this before anything involving memory or registers. */
4833 target_find_description ();
4834
6c95b8df
PA
4835 /* Next, now that we know something about the target, update the
4836 address spaces in the program spaces. */
4837 update_address_spaces ();
4838
50c71eaf
PA
4839 /* On OSs where the list of libraries is global to all
4840 processes, we fetch them early. */
f5656ead 4841 if (gdbarch_has_global_solist (target_gdbarch ()))
e696b3ad 4842 solib_add (NULL, from_tty, auto_solib_add);
50c71eaf 4843
6efcd9a8 4844 if (target_is_non_stop_p ())
74531fed 4845 {
4082afcc 4846 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
4847 error (_("Non-stop mode requested, but remote "
4848 "does not support non-stop"));
74531fed
PA
4849
4850 putpkt ("QNonStop:1");
8d64371b 4851 getpkt (&rs->buf, 0);
74531fed 4852
8d64371b
TT
4853 if (strcmp (rs->buf.data (), "OK") != 0)
4854 error (_("Remote refused setting non-stop mode with: %s"),
4855 rs->buf.data ());
74531fed
PA
4856
4857 /* Find about threads and processes the stub is already
4858 controlling. We default to adding them in the running state.
4859 The '?' query below will then tell us about which threads are
4860 stopped. */
f6ac5f3d 4861 this->update_thread_list ();
74531fed 4862 }
4082afcc 4863 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4864 {
4865 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4866 Request it explicitly. */
74531fed 4867 putpkt ("QNonStop:0");
8d64371b 4868 getpkt (&rs->buf, 0);
74531fed 4869
8d64371b
TT
4870 if (strcmp (rs->buf.data (), "OK") != 0)
4871 error (_("Remote refused setting all-stop mode with: %s"),
4872 rs->buf.data ());
74531fed
PA
4873 }
4874
a0743c90
YQ
4875 /* Upload TSVs regardless of whether the target is running or not. The
4876 remote stub, such as GDBserver, may have some predefined or builtin
4877 TSVs, even if the target is not running. */
f6ac5f3d 4878 if (get_trace_status (current_trace_status ()) != -1)
a0743c90
YQ
4879 {
4880 struct uploaded_tsv *uploaded_tsvs = NULL;
4881
f6ac5f3d 4882 upload_trace_state_variables (&uploaded_tsvs);
a0743c90
YQ
4883 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4884 }
4885
2d717e4f
DJ
4886 /* Check whether the target is running now. */
4887 putpkt ("?");
8d64371b 4888 getpkt (&rs->buf, 0);
2d717e4f 4889
6efcd9a8 4890 if (!target_is_non_stop_p ())
2d717e4f 4891 {
b5c8f22d
SM
4892 char *wait_status = NULL;
4893
74531fed 4894 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4895 {
04bd08de 4896 if (!extended_p)
74531fed 4897 error (_("The target is not running (try extended-remote?)"));
288712bb 4898 return false;
2d717e4f
DJ
4899 }
4900 else
74531fed 4901 {
74531fed 4902 /* Save the reply for later. */
8d64371b
TT
4903 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
4904 strcpy (wait_status, rs->buf.data ());
74531fed
PA
4905 }
4906
b7ea362b 4907 /* Fetch thread list. */
e8032dde 4908 target_update_thread_list ();
b7ea362b 4909
74531fed
PA
4910 /* Let the stub know that we want it to return the thread. */
4911 set_continue_thread (minus_one_ptid);
4912
5b6d1e4f 4913 if (thread_count (this) == 0)
b7ea362b
PA
4914 {
4915 /* Target has no concept of threads at all. GDB treats
4916 non-threaded target as single-threaded; add a main
4917 thread. */
64d38fdd
JM
4918 thread_info *tp = add_current_inferior_and_thread (wait_status);
4919 get_remote_thread_info (tp)->set_resumed ();
b7ea362b
PA
4920 }
4921 else
4922 {
4923 /* We have thread information; select the thread the target
4924 says should be current. If we're reconnecting to a
4925 multi-threaded program, this will ideally be the thread
4926 that last reported an event before GDB disconnected. */
75c6c844
PA
4927 ptid_t curr_thread = get_current_thread (wait_status);
4928 if (curr_thread == null_ptid)
b7ea362b
PA
4929 {
4930 /* Odd... The target was able to list threads, but not
4931 tell us which thread was current (no "thread"
4932 register in T stop reply?). Just pick the first
4933 thread in the thread list then. */
2189c312
SM
4934
4935 remote_debug_printf ("warning: couldn't determine remote "
4936 "current thread; picking first in list.");
c9f35b34 4937
5b6d1e4f
PA
4938 for (thread_info *tp : all_non_exited_threads (this,
4939 minus_one_ptid))
75c6c844
PA
4940 {
4941 switch_to_thread (tp);
4942 break;
4943 }
b7ea362b 4944 }
75c6c844 4945 else
5b6d1e4f 4946 switch_to_thread (find_thread_ptid (this, curr_thread));
b7ea362b 4947 }
74531fed 4948
6e586cc5
YQ
4949 /* init_wait_for_inferior should be called before get_offsets in order
4950 to manage `inserted' flag in bp loc in a correct state.
4951 breakpoint_init_inferior, called from init_wait_for_inferior, set
4952 `inserted' flag to 0, while before breakpoint_re_set, called from
4953 start_remote, set `inserted' flag to 1. In the initialization of
4954 inferior, breakpoint_init_inferior should be called first, and then
4955 breakpoint_re_set can be called. If this order is broken, state of
4956 `inserted' flag is wrong, and cause some problems on breakpoint
4957 manipulation. */
4958 init_wait_for_inferior ();
4959
74531fed
PA
4960 get_offsets (); /* Get text, data & bss offsets. */
4961
d962ef82
DJ
4962 /* If we could not find a description using qXfer, and we know
4963 how to do it some other way, try again. This is not
4964 supported for non-stop; it could be, but it is tricky if
4965 there are no stopped threads when we connect. */
f6ac5f3d 4966 if (remote_read_description_p (this)
f5656ead 4967 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4968 {
4969 target_clear_description ();
4970 target_find_description ();
4971 }
4972
74531fed
PA
4973 /* Use the previously fetched status. */
4974 gdb_assert (wait_status != NULL);
4f626cad
AB
4975 struct notif_event *reply
4976 = remote_notif_parse (this, &notif_client_stop, wait_status);
4977 push_stop_reply ((struct stop_reply *) reply);
74531fed 4978
f6ac5f3d 4979 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4980 }
4981 else
4982 {
68c97600
PA
4983 /* Clear WFI global state. Do this before finding about new
4984 threads and inferiors, and setting the current inferior.
4985 Otherwise we would clear the proceed status of the current
4986 inferior when we want its stop_soon state to be preserved
4987 (see notice_new_inferior). */
4988 init_wait_for_inferior ();
4989
74531fed
PA
4990 /* In non-stop, we will either get an "OK", meaning that there
4991 are no stopped threads at this time; or, a regular stop
4992 reply. In the latter case, there may be more than one thread
4993 stopped --- we pull them all out using the vStopped
4994 mechanism. */
8d64371b 4995 if (strcmp (rs->buf.data (), "OK") != 0)
74531fed 4996 {
722247f1 4997 struct notif_client *notif = &notif_client_stop;
2d717e4f 4998
722247f1
YQ
4999 /* remote_notif_get_pending_replies acks this one, and gets
5000 the rest out. */
f48ff2a7 5001 rs->notif_state->pending_event[notif_client_stop.id]
8d64371b 5002 = remote_notif_parse (this, notif, rs->buf.data ());
722247f1 5003 remote_notif_get_pending_events (notif);
74531fed 5004 }
2d717e4f 5005
5b6d1e4f 5006 if (thread_count (this) == 0)
74531fed 5007 {
04bd08de 5008 if (!extended_p)
74531fed 5009 error (_("The target is not running (try extended-remote?)"));
288712bb 5010 return false;
c35b1492 5011 }
74531fed 5012
2455069d 5013 /* Report all signals during attach/startup. */
adc6a863 5014 pass_signals ({});
221e1a37
PA
5015
5016 /* If there are already stopped threads, mark them stopped and
5017 report their stops before giving the prompt to the user. */
6efcd9a8 5018 process_initial_stop_replies (from_tty);
221e1a37
PA
5019
5020 if (target_can_async_p ())
4a570176 5021 target_async (true);
74531fed 5022 }
c8d104ad 5023
901e4e8d
SM
5024 /* Give the target a chance to look up symbols. */
5025 for (inferior *inf : all_inferiors (this))
c8d104ad 5026 {
901e4e8d
SM
5027 /* The inferiors that exist at this point were created from what
5028 was found already running on the remote side, so we know they
5029 have execution. */
5030 gdb_assert (this->has_execution (inf));
5031
a42d7dd8 5032 /* No use without a symbol-file. */
901e4e8d
SM
5033 if (inf->pspace->symfile_object_file == nullptr)
5034 continue;
5035
5036 /* Need to switch to a specific thread, because remote_check_symbols
5037 uses INFERIOR_PTID to set the general thread. */
5038 scoped_restore_current_thread restore_thread;
5039 thread_info *thread = any_thread_of_inferior (inf);
5040 switch_to_thread (thread);
5041 this->remote_check_symbols ();
c8d104ad 5042 }
50c71eaf 5043
d5551862
SS
5044 /* Possibly the target has been engaged in a trace run started
5045 previously; find out where things are at. */
f6ac5f3d 5046 if (get_trace_status (current_trace_status ()) != -1)
d5551862 5047 {
00bf0b85 5048 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 5049
00bf0b85 5050 if (current_trace_status ()->running)
6cb06a8c 5051 gdb_printf (_("Trace is already running on the target.\n"));
00bf0b85 5052
f6ac5f3d 5053 upload_tracepoints (&uploaded_tps);
00bf0b85
SS
5054
5055 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
5056 }
5057
c0272db5
TW
5058 /* Possibly the target has been engaged in a btrace record started
5059 previously; find out where things are at. */
5060 remote_btrace_maybe_reopen ();
5061
288712bb
AB
5062 return true;
5063}
5064
5065/* Start the remote connection and sync state. */
1e51243a 5066
288712bb
AB
5067void
5068remote_target::start_remote (int from_tty, int extended_p)
5069{
5070 if (start_remote_1 (from_tty, extended_p)
5071 && breakpoints_should_be_inserted_now ())
50c71eaf 5072 insert_breakpoints ();
c906108c
SS
5073}
5074
121b3efd
PA
5075const char *
5076remote_target::connection_string ()
5077{
5078 remote_state *rs = get_remote_state ();
5079
5080 if (rs->remote_desc->name != NULL)
5081 return rs->remote_desc->name;
5082 else
5083 return NULL;
5084}
5085
c906108c
SS
5086/* Open a connection to a remote debugger.
5087 NAME is the filename used for communication. */
5088
f6ac5f3d
PA
5089void
5090remote_target::open (const char *name, int from_tty)
c906108c 5091{
f6ac5f3d 5092 open_1 (name, from_tty, 0);
43ff13b4
JM
5093}
5094
c906108c
SS
5095/* Open a connection to a remote debugger using the extended
5096 remote gdb protocol. NAME is the filename used for communication. */
5097
f6ac5f3d
PA
5098void
5099extended_remote_target::open (const char *name, int from_tty)
c906108c 5100{
f6ac5f3d 5101 open_1 (name, from_tty, 1 /*extended_p */);
43ff13b4
JM
5102}
5103
ca4f7f8b
PA
5104/* Reset all packets back to "unknown support". Called when opening a
5105 new connection to a remote target. */
c906108c 5106
d471ea57 5107static void
ca4f7f8b 5108reset_all_packet_configs_support (void)
d471ea57
AC
5109{
5110 int i;
a744cf53 5111
444abaca 5112 for (i = 0; i < PACKET_MAX; i++)
4082afcc 5113 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
5114}
5115
ca4f7f8b
PA
5116/* Initialize all packet configs. */
5117
5118static void
5119init_all_packet_configs (void)
5120{
5121 int i;
5122
5123 for (i = 0; i < PACKET_MAX; i++)
5124 {
5125 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5126 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5127 }
5128}
5129
23860348 5130/* Symbol look-up. */
dc8acb97 5131
6b8edb51
PA
5132void
5133remote_target::remote_check_symbols ()
dc8acb97 5134{
8d64371b 5135 char *tmp;
dc8acb97
MS
5136 int end;
5137
06c7226e
SM
5138 /* It doesn't make sense to send a qSymbol packet for an inferior that
5139 doesn't have execution, because the remote side doesn't know about
5140 inferiors without execution. */
5141 gdb_assert (target_has_execution ());
63154eca 5142
4082afcc 5143 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
5144 return;
5145
63154eca
PA
5146 /* Make sure the remote is pointing at the right process. Note
5147 there's no way to select "no process". */
3c9c4b83
PA
5148 set_general_process ();
5149
6d820c5c
DJ
5150 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5151 because we need both at the same time. */
66644cd3 5152 gdb::char_vector msg (get_remote_packet_size ());
8d64371b 5153 gdb::char_vector reply (get_remote_packet_size ());
6d820c5c 5154
23860348 5155 /* Invite target to request symbol lookups. */
dc8acb97
MS
5156
5157 putpkt ("qSymbol::");
8d64371b 5158 getpkt (&reply, 0);
28170b88 5159 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
dc8acb97 5160
8d64371b 5161 while (startswith (reply.data (), "qSymbol:"))
dc8acb97 5162 {
77e371c0
TT
5163 struct bound_minimal_symbol sym;
5164
dc8acb97 5165 tmp = &reply[8];
66644cd3
AB
5166 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5167 strlen (tmp) / 2);
dc8acb97 5168 msg[end] = '\0';
66644cd3 5169 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
3b7344d5 5170 if (sym.minsym == NULL)
66644cd3
AB
5171 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5172 &reply[8]);
dc8acb97 5173 else
2bbe3cc1 5174 {
f5656ead 5175 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4aeddc50 5176 CORE_ADDR sym_addr = sym.value_address ();
2bbe3cc1
DJ
5177
5178 /* If this is a function address, return the start of code
5179 instead of any data function descriptor. */
328d42d8
SM
5180 sym_addr = gdbarch_convert_from_func_ptr_addr
5181 (target_gdbarch (), sym_addr, current_inferior ()->top_target ());
2bbe3cc1 5182
66644cd3 5183 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 5184 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1 5185 }
66644cd3
AB
5186
5187 putpkt (msg.data ());
8d64371b 5188 getpkt (&reply, 0);
dc8acb97
MS
5189 }
5190}
5191
9db8d71f 5192static struct serial *
baa336ce 5193remote_serial_open (const char *name)
9db8d71f
DJ
5194{
5195 static int udp_warning = 0;
5196
5197 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5198 of in ser-tcp.c, because it is the remote protocol assuming that the
5199 serial connection is reliable and not the serial connection promising
5200 to be. */
61012eef 5201 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 5202 {
3e43a32a
MS
5203 warning (_("The remote protocol may be unreliable over UDP.\n"
5204 "Some events may be lost, rendering further debugging "
5205 "impossible."));
9db8d71f
DJ
5206 udp_warning = 1;
5207 }
5208
5209 return serial_open (name);
5210}
5211
d914c394
SS
5212/* Inform the target of our permission settings. The permission flags
5213 work without this, but if the target knows the settings, it can do
5214 a couple things. First, it can add its own check, to catch cases
5215 that somehow manage to get by the permissions checks in target
5216 methods. Second, if the target is wired to disallow particular
5217 settings (for instance, a system in the field that is not set up to
5218 be able to stop at a breakpoint), it can object to any unavailable
5219 permissions. */
5220
5221void
f6ac5f3d 5222remote_target::set_permissions ()
d914c394
SS
5223{
5224 struct remote_state *rs = get_remote_state ();
5225
8d64371b 5226 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
bba74b36
YQ
5227 "WriteReg:%x;WriteMem:%x;"
5228 "InsertBreak:%x;InsertTrace:%x;"
5229 "InsertFastTrace:%x;Stop:%x",
5230 may_write_registers, may_write_memory,
5231 may_insert_breakpoints, may_insert_tracepoints,
5232 may_insert_fast_tracepoints, may_stop);
d914c394 5233 putpkt (rs->buf);
8d64371b 5234 getpkt (&rs->buf, 0);
d914c394
SS
5235
5236 /* If the target didn't like the packet, warn the user. Do not try
5237 to undo the user's settings, that would just be maddening. */
8d64371b
TT
5238 if (strcmp (rs->buf.data (), "OK") != 0)
5239 warning (_("Remote refused setting permissions with: %s"),
5240 rs->buf.data ());
d914c394
SS
5241}
5242
be2a5f71
DJ
5243/* This type describes each known response to the qSupported
5244 packet. */
5245struct protocol_feature
5246{
5247 /* The name of this protocol feature. */
5248 const char *name;
5249
5250 /* The default for this protocol feature. */
5251 enum packet_support default_support;
5252
5253 /* The function to call when this feature is reported, or after
5254 qSupported processing if the feature is not supported.
5255 The first argument points to this structure. The second
5256 argument indicates whether the packet requested support be
5257 enabled, disabled, or probed (or the default, if this function
5258 is being called at the end of processing and this feature was
5259 not reported). The third argument may be NULL; if not NULL, it
5260 is a NUL-terminated string taken from the packet following
5261 this feature's name and an equals sign. */
6b8edb51
PA
5262 void (*func) (remote_target *remote, const struct protocol_feature *,
5263 enum packet_support, const char *);
be2a5f71
DJ
5264
5265 /* The corresponding packet for this feature. Only used if
5266 FUNC is remote_supported_packet. */
5267 int packet;
5268};
5269
be2a5f71 5270static void
6b8edb51
PA
5271remote_supported_packet (remote_target *remote,
5272 const struct protocol_feature *feature,
be2a5f71
DJ
5273 enum packet_support support,
5274 const char *argument)
5275{
5276 if (argument)
5277 {
5278 warning (_("Remote qSupported response supplied an unexpected value for"
5279 " \"%s\"."), feature->name);
5280 return;
5281 }
5282
4082afcc 5283 remote_protocol_packets[feature->packet].support = support;
be2a5f71 5284}
be2a5f71 5285
6b8edb51
PA
5286void
5287remote_target::remote_packet_size (const protocol_feature *feature,
5288 enum packet_support support, const char *value)
be2a5f71
DJ
5289{
5290 struct remote_state *rs = get_remote_state ();
5291
5292 int packet_size;
5293 char *value_end;
5294
5295 if (support != PACKET_ENABLE)
5296 return;
5297
5298 if (value == NULL || *value == '\0')
5299 {
5300 warning (_("Remote target reported \"%s\" without a size."),
5301 feature->name);
5302 return;
5303 }
5304
5305 errno = 0;
5306 packet_size = strtol (value, &value_end, 16);
5307 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5308 {
5309 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5310 feature->name, value);
5311 return;
5312 }
5313
be2a5f71
DJ
5314 /* Record the new maximum packet size. */
5315 rs->explicit_packet_size = packet_size;
5316}
5317
cb8c24b6 5318static void
6b8edb51
PA
5319remote_packet_size (remote_target *remote, const protocol_feature *feature,
5320 enum packet_support support, const char *value)
5321{
5322 remote->remote_packet_size (feature, support, value);
5323}
5324
dc473cfb 5325static const struct protocol_feature remote_protocol_features[] = {
0876f84a 5326 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 5327 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 5328 PACKET_qXfer_auxv },
c78fa86a
GB
5329 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5330 PACKET_qXfer_exec_file },
23181151
DJ
5331 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5332 PACKET_qXfer_features },
cfa9d6d9
DJ
5333 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5334 PACKET_qXfer_libraries },
2268b414
JK
5335 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5336 PACKET_qXfer_libraries_svr4 },
ced63ec0 5337 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 5338 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 5339 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 5340 PACKET_qXfer_memory_map },
07e059b5
VP
5341 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5342 PACKET_qXfer_osdata },
dc146f7c
VP
5343 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5344 PACKET_qXfer_threads },
b3b9301e
PA
5345 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5346 PACKET_qXfer_traceframe_info },
89be2091
DJ
5347 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5348 PACKET_QPassSignals },
82075af2
JS
5349 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5350 PACKET_QCatchSyscalls },
9b224c5e
PA
5351 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5352 PACKET_QProgramSignals },
bc3b087d
SDJ
5353 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5354 PACKET_QSetWorkingDir },
aefd8b33
SDJ
5355 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5356 PACKET_QStartupWithShell },
0a2dde4a
SDJ
5357 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5358 PACKET_QEnvironmentHexEncoded },
5359 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5360 PACKET_QEnvironmentReset },
5361 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5362 PACKET_QEnvironmentUnset },
a6f3e723
SL
5363 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5364 PACKET_QStartNoAckMode },
4082afcc
PA
5365 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5366 PACKET_multiprocess_feature },
5367 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
5368 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5369 PACKET_qXfer_siginfo_read },
5370 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5371 PACKET_qXfer_siginfo_write },
4082afcc 5372 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 5373 PACKET_ConditionalTracepoints },
4082afcc 5374 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 5375 PACKET_ConditionalBreakpoints },
4082afcc 5376 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 5377 PACKET_BreakpointCommands },
4082afcc 5378 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 5379 PACKET_FastTracepoints },
4082afcc 5380 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 5381 PACKET_StaticTracepoints },
4082afcc 5382 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 5383 PACKET_InstallInTrace},
4082afcc
PA
5384 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5385 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
5386 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5387 PACKET_bc },
5388 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5389 PACKET_bs },
409873ef
SS
5390 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5391 PACKET_TracepointSource },
d914c394
SS
5392 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5393 PACKET_QAllow },
4082afcc
PA
5394 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5395 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
5396 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5397 PACKET_qXfer_fdpic },
169081d0
TG
5398 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5399 PACKET_qXfer_uib },
03583c20
UW
5400 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5401 PACKET_QDisableRandomization },
d1feda86 5402 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
5403 { "QTBuffer:size", PACKET_DISABLE,
5404 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 5405 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
5406 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5407 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 5408 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 5409 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
5410 PACKET_qXfer_btrace },
5411 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
5412 PACKET_qXfer_btrace_conf },
5413 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
5414 PACKET_Qbtrace_conf_bts_size },
5415 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 5416 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
5417 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5418 PACKET_fork_event_feature },
5419 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5420 PACKET_vfork_event_feature },
94585166
DB
5421 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5422 PACKET_exec_event_feature },
b20a6524 5423 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 5424 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
5425 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5426 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 5427 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
2c2e7f87
LM
5428 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5429 PACKET_memory_tagging_feature },
be2a5f71
DJ
5430};
5431
c8d5aac9
L
5432static char *remote_support_xml;
5433
5434/* Register string appended to "xmlRegisters=" in qSupported query. */
5435
5436void
6e39997a 5437register_remote_support_xml (const char *xml)
c8d5aac9
L
5438{
5439#if defined(HAVE_LIBEXPAT)
5440 if (remote_support_xml == NULL)
c4f7c687 5441 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
5442 else
5443 {
5444 char *copy = xstrdup (remote_support_xml + 13);
ca3a04f6
CB
5445 char *saveptr;
5446 char *p = strtok_r (copy, ",", &saveptr);
c8d5aac9
L
5447
5448 do
5449 {
5450 if (strcmp (p, xml) == 0)
5451 {
5452 /* already there */
5453 xfree (copy);
5454 return;
5455 }
5456 }
ca3a04f6 5457 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
c8d5aac9
L
5458 xfree (copy);
5459
94b0dee1
PA
5460 remote_support_xml = reconcat (remote_support_xml,
5461 remote_support_xml, ",", xml,
5462 (char *) NULL);
c8d5aac9
L
5463 }
5464#endif
5465}
5466
69b6ecb0
TT
5467static void
5468remote_query_supported_append (std::string *msg, const char *append)
c8d5aac9 5469{
69b6ecb0
TT
5470 if (!msg->empty ())
5471 msg->append (";");
5472 msg->append (append);
c8d5aac9
L
5473}
5474
6b8edb51
PA
5475void
5476remote_target::remote_query_supported ()
be2a5f71
DJ
5477{
5478 struct remote_state *rs = get_remote_state ();
5479 char *next;
5480 int i;
5481 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5482
5483 /* The packet support flags are handled differently for this packet
5484 than for most others. We treat an error, a disabled packet, and
5485 an empty response identically: any features which must be reported
5486 to be used will be automatically disabled. An empty buffer
5487 accomplishes this, since that is also the representation for a list
5488 containing no features. */
5489
5490 rs->buf[0] = 0;
4082afcc 5491 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 5492 {
69b6ecb0 5493 std::string q;
c8d5aac9 5494
73b8c1fd 5495 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5496 remote_query_supported_append (&q, "multiprocess+");
c8d5aac9 5497
f7e6eed5 5498 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5499 remote_query_supported_append (&q, "swbreak+");
f7e6eed5 5500 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5501 remote_query_supported_append (&q, "hwbreak+");
f7e6eed5 5502
69b6ecb0 5503 remote_query_supported_append (&q, "qRelocInsn+");
dde08ee1 5504
8020350c
DB
5505 if (packet_set_cmd_state (PACKET_fork_event_feature)
5506 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5507 remote_query_supported_append (&q, "fork-events+");
8020350c
DB
5508 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5509 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5510 remote_query_supported_append (&q, "vfork-events+");
8020350c
DB
5511 if (packet_set_cmd_state (PACKET_exec_event_feature)
5512 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5513 remote_query_supported_append (&q, "exec-events+");
89245bc0 5514
750ce8d1 5515 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5516 remote_query_supported_append (&q, "vContSupported+");
750ce8d1 5517
65706a29 5518 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5519 remote_query_supported_append (&q, "QThreadEvents+");
65706a29 5520
f2faf941 5521 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5522 remote_query_supported_append (&q, "no-resumed+");
f2faf941 5523
2c2e7f87
LM
5524 if (packet_set_cmd_state (PACKET_memory_tagging_feature)
5525 != AUTO_BOOLEAN_FALSE)
5526 remote_query_supported_append (&q, "memory-tagging+");
5527
b35d5edb
PA
5528 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5529 the qSupported:xmlRegisters=i386 handling. */
7cc244de
PA
5530 if (remote_support_xml != NULL
5531 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
69b6ecb0 5532 remote_query_supported_append (&q, remote_support_xml);
82f73884 5533
69b6ecb0
TT
5534 q = "qSupported:" + q;
5535 putpkt (q.c_str ());
94b0dee1 5536
8d64371b 5537 getpkt (&rs->buf, 0);
be2a5f71
DJ
5538
5539 /* If an error occured, warn, but do not return - just reset the
5540 buffer to empty and go on to disable features. */
5541 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5542 == PACKET_ERROR)
5543 {
8d64371b 5544 warning (_("Remote failure reply: %s"), rs->buf.data ());
be2a5f71
DJ
5545 rs->buf[0] = 0;
5546 }
5547 }
5548
5549 memset (seen, 0, sizeof (seen));
5550
8d64371b 5551 next = rs->buf.data ();
be2a5f71
DJ
5552 while (*next)
5553 {
5554 enum packet_support is_supported;
5555 char *p, *end, *name_end, *value;
5556
5557 /* First separate out this item from the rest of the packet. If
5558 there's another item after this, we overwrite the separator
5559 (terminated strings are much easier to work with). */
5560 p = next;
5561 end = strchr (p, ';');
5562 if (end == NULL)
5563 {
5564 end = p + strlen (p);
5565 next = end;
5566 }
5567 else
5568 {
89be2091
DJ
5569 *end = '\0';
5570 next = end + 1;
5571
be2a5f71
DJ
5572 if (end == p)
5573 {
5574 warning (_("empty item in \"qSupported\" response"));
5575 continue;
5576 }
be2a5f71
DJ
5577 }
5578
5579 name_end = strchr (p, '=');
5580 if (name_end)
5581 {
5582 /* This is a name=value entry. */
5583 is_supported = PACKET_ENABLE;
5584 value = name_end + 1;
5585 *name_end = '\0';
5586 }
5587 else
5588 {
5589 value = NULL;
5590 switch (end[-1])
5591 {
5592 case '+':
5593 is_supported = PACKET_ENABLE;
5594 break;
5595
5596 case '-':
5597 is_supported = PACKET_DISABLE;
5598 break;
5599
5600 case '?':
5601 is_supported = PACKET_SUPPORT_UNKNOWN;
5602 break;
5603
5604 default:
3e43a32a
MS
5605 warning (_("unrecognized item \"%s\" "
5606 "in \"qSupported\" response"), p);
be2a5f71
DJ
5607 continue;
5608 }
5609 end[-1] = '\0';
5610 }
5611
5612 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5613 if (strcmp (remote_protocol_features[i].name, p) == 0)
5614 {
5615 const struct protocol_feature *feature;
5616
5617 seen[i] = 1;
5618 feature = &remote_protocol_features[i];
6b8edb51 5619 feature->func (this, feature, is_supported, value);
be2a5f71
DJ
5620 break;
5621 }
5622 }
5623
5624 /* If we increased the packet size, make sure to increase the global
5625 buffer size also. We delay this until after parsing the entire
5626 qSupported packet, because this is the same buffer we were
5627 parsing. */
8d64371b
TT
5628 if (rs->buf.size () < rs->explicit_packet_size)
5629 rs->buf.resize (rs->explicit_packet_size);
be2a5f71
DJ
5630
5631 /* Handle the defaults for unmentioned features. */
5632 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5633 if (!seen[i])
5634 {
5635 const struct protocol_feature *feature;
5636
5637 feature = &remote_protocol_features[i];
6b8edb51 5638 feature->func (this, feature, feature->default_support, NULL);
be2a5f71
DJ
5639 }
5640}
5641
048094ac
PA
5642/* Serial QUIT handler for the remote serial descriptor.
5643
5644 Defers handling a Ctrl-C until we're done with the current
5645 command/response packet sequence, unless:
5646
5647 - We're setting up the connection. Don't send a remote interrupt
5648 request, as we're not fully synced yet. Quit immediately
5649 instead.
5650
5651 - The target has been resumed in the foreground
223ffa71 5652 (target_terminal::is_ours is false) with a synchronous resume
048094ac
PA
5653 packet, and we're blocked waiting for the stop reply, thus a
5654 Ctrl-C should be immediately sent to the target.
5655
5656 - We get a second Ctrl-C while still within the same serial read or
5657 write. In that case the serial is seemingly wedged --- offer to
5658 quit/disconnect.
5659
5660 - We see a second Ctrl-C without target response, after having
5661 previously interrupted the target. In that case the target/stub
5662 is probably wedged --- offer to quit/disconnect.
5663*/
5664
6b8edb51
PA
5665void
5666remote_target::remote_serial_quit_handler ()
048094ac
PA
5667{
5668 struct remote_state *rs = get_remote_state ();
5669
5670 if (check_quit_flag ())
5671 {
5672 /* If we're starting up, we're not fully synced yet. Quit
5673 immediately. */
5674 if (rs->starting_up)
5675 quit ();
5676 else if (rs->got_ctrlc_during_io)
5677 {
5678 if (query (_("The target is not responding to GDB commands.\n"
5679 "Stop debugging it? ")))
5b6d1e4f 5680 remote_unpush_and_throw (this);
048094ac
PA
5681 }
5682 /* If ^C has already been sent once, offer to disconnect. */
223ffa71 5683 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
048094ac
PA
5684 interrupt_query ();
5685 /* All-stop protocol, and blocked waiting for stop reply. Send
5686 an interrupt request. */
223ffa71 5687 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
e671cd59 5688 target_interrupt ();
048094ac
PA
5689 else
5690 rs->got_ctrlc_during_io = 1;
5691 }
5692}
5693
6b8edb51
PA
5694/* The remote_target that is current while the quit handler is
5695 overridden with remote_serial_quit_handler. */
5696static remote_target *curr_quit_handler_target;
5697
5698static void
5699remote_serial_quit_handler ()
5700{
5701 curr_quit_handler_target->remote_serial_quit_handler ();
5702}
5703
5b6d1e4f
PA
5704/* Remove the remote target from the target stack of each inferior
5705 that is using it. Upper targets depend on it so remove them
5706 first. */
78a095c3
JK
5707
5708static void
5b6d1e4f 5709remote_unpush_target (remote_target *target)
78a095c3 5710{
5b6d1e4f
PA
5711 /* We have to unpush the target from all inferiors, even those that
5712 aren't running. */
5713 scoped_restore_current_inferior restore_current_inferior;
5714
5715 for (inferior *inf : all_inferiors (target))
5716 {
5717 switch_to_inferior_no_thread (inf);
5718 pop_all_targets_at_and_above (process_stratum);
5719 generic_mourn_inferior ();
5720 }
d7cb0ef3
PA
5721
5722 /* Don't rely on target_close doing this when the target is popped
5723 from the last remote inferior above, because something may be
5724 holding a reference to the target higher up on the stack, meaning
5725 target_close won't be called yet. We lost the connection to the
5726 target, so clear these now, otherwise we may later throw
5727 TARGET_CLOSE_ERROR while trying to tell the remote target to
5728 close the file. */
5729 fileio_handles_invalidate_target (target);
78a095c3 5730}
be2a5f71 5731
048094ac 5732static void
5b6d1e4f 5733remote_unpush_and_throw (remote_target *target)
048094ac 5734{
5b6d1e4f 5735 remote_unpush_target (target);
048094ac
PA
5736 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5737}
5738
f6ac5f3d
PA
5739void
5740remote_target::open_1 (const char *name, int from_tty, int extended_p)
c906108c 5741{
6b8edb51 5742 remote_target *curr_remote = get_current_remote_target ();
a6f3e723 5743
c906108c 5744 if (name == 0)
8a3fe4f8 5745 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 5746 "serial device is attached to the remote system\n"
8a3fe4f8 5747 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 5748
2d717e4f 5749 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
5750 Ask this question first, before target_preopen has a chance to kill
5751 anything. */
55f6301a 5752 if (curr_remote != NULL && !target_has_execution ())
2d717e4f 5753 {
78a095c3
JK
5754 if (from_tty
5755 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
5756 error (_("Still connected."));
5757 }
5758
78a095c3 5759 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
5760 target_preopen (from_tty);
5761
ad9a8f3f 5762 remote_fileio_reset ();
1dd41f16 5763 reopen_exec_file ();
9dec38d3 5764 reread_symbols (from_tty);
1dd41f16 5765
6b8edb51
PA
5766 remote_target *remote
5767 = (extended_p ? new extended_remote_target () : new remote_target ());
5768 target_ops_up target_holder (remote);
5769
5770 remote_state *rs = remote->get_remote_state ();
5771
5772 /* See FIXME above. */
5773 if (!target_async_permitted)
5774 rs->wait_forever_enabled_p = 1;
5775
5d93a237
TT
5776 rs->remote_desc = remote_serial_open (name);
5777 if (!rs->remote_desc)
c906108c
SS
5778 perror_with_name (name);
5779
5780 if (baud_rate != -1)
5781 {
5d93a237 5782 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 5783 {
9b74d5d3
KB
5784 /* The requested speed could not be set. Error out to
5785 top level after closing remote_desc. Take care to
5786 set remote_desc to NULL to avoid closing remote_desc
5787 more than once. */
5d93a237
TT
5788 serial_close (rs->remote_desc);
5789 rs->remote_desc = NULL;
c906108c
SS
5790 perror_with_name (name);
5791 }
5792 }
5793
236af5e3 5794 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 5795 serial_raw (rs->remote_desc);
c906108c
SS
5796
5797 /* If there is something sitting in the buffer we might take it as a
5798 response to a command, which would be bad. */
5d93a237 5799 serial_flush_input (rs->remote_desc);
c906108c
SS
5800
5801 if (from_tty)
5802 {
0426ad51
TT
5803 gdb_puts ("Remote debugging using ");
5804 gdb_puts (name);
5805 gdb_puts ("\n");
c906108c 5806 }
d9f719f1 5807
6b8edb51 5808 /* Switch to using the remote target now. */
02980c56 5809 current_inferior ()->push_target (std::move (target_holder));
c906108c 5810
74531fed 5811 /* Register extra event sources in the event loop. */
6b8edb51 5812 rs->remote_async_inferior_event_token
baa8575b 5813 = create_async_event_handler (remote_async_inferior_event_handler, nullptr,
db20ebdf 5814 "remote");
6b8edb51 5815 rs->notif_state = remote_notif_state_allocate (remote);
74531fed 5816
be2a5f71
DJ
5817 /* Reset the target state; these things will be queried either by
5818 remote_query_supported or as they are needed. */
ca4f7f8b 5819 reset_all_packet_configs_support ();
be2a5f71 5820 rs->explicit_packet_size = 0;
a6f3e723 5821 rs->noack_mode = 0;
82f73884 5822 rs->extended = extended_p;
e24a49d8 5823 rs->waiting_for_stop_reply = 0;
3a29589a 5824 rs->ctrlc_pending_p = 0;
048094ac 5825 rs->got_ctrlc_during_io = 0;
802188a7 5826
47f8a51d
TT
5827 rs->general_thread = not_sent_ptid;
5828 rs->continue_thread = not_sent_ptid;
262e1174 5829 rs->remote_traceframe_number = -1;
c906108c 5830
3a00c802
PA
5831 rs->last_resume_exec_dir = EXEC_FORWARD;
5832
9d1f7ab2 5833 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
5834 rs->use_threadinfo_query = 1;
5835 rs->use_threadextra_query = 1;
9d1f7ab2 5836
dd194f6b 5837 rs->readahead_cache.invalidate ();
80152258 5838
c6ebd6cf 5839 if (target_async_permitted)
92d1e331 5840 {
92d1e331
DJ
5841 /* FIXME: cagney/1999-09-23: During the initial connection it is
5842 assumed that the target is already ready and able to respond to
0df8b418 5843 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 5844 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 5845 around this. Eventually a mechanism that allows
92d1e331 5846 wait_for_inferior() to expect/get timeouts will be
23860348 5847 implemented. */
6b8edb51 5848 rs->wait_forever_enabled_p = 0;
92d1e331
DJ
5849 }
5850
23860348 5851 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 5852 no_shared_libraries (NULL, 0);
f78f6cf1 5853
36918e70 5854 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
5855 target (we'd otherwise be in an inconsistent state) and then
5856 propogate the error on up the exception chain. This ensures that
5857 the caller doesn't stumble along blindly assuming that the
5858 function succeeded. The CLI doesn't have this problem but other
5859 UI's, such as MI do.
36918e70
AC
5860
5861 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5862 this function should return an error indication letting the
ce2826aa 5863 caller restore the previous state. Unfortunately the command
36918e70
AC
5864 ``target remote'' is directly wired to this function making that
5865 impossible. On a positive note, the CLI side of this problem has
5866 been fixed - the function set_cmd_context() makes it possible for
5867 all the ``target ....'' commands to share a common callback
5868 function. See cli-dump.c. */
109c3e39 5869 {
2d717e4f 5870
a70b8144 5871 try
04bd08de 5872 {
6b8edb51 5873 remote->start_remote (from_tty, extended_p);
04bd08de 5874 }
230d2906 5875 catch (const gdb_exception &ex)
109c3e39 5876 {
c8d104ad
PA
5877 /* Pop the partially set up target - unless something else did
5878 already before throwing the exception. */
6b8edb51 5879 if (ex.error != TARGET_CLOSE_ERROR)
5b6d1e4f 5880 remote_unpush_target (remote);
eedc3f4f 5881 throw;
109c3e39
AC
5882 }
5883 }
c906108c 5884
6b8edb51 5885 remote_btrace_reset (rs);
f4abbc16 5886
c6ebd6cf 5887 if (target_async_permitted)
6b8edb51 5888 rs->wait_forever_enabled_p = 1;
43ff13b4
JM
5889}
5890
28561a65 5891/* Determine if WS represents a fork status. */
a4543480 5892
28561a65
SM
5893static bool
5894is_fork_status (target_waitkind kind)
a4543480 5895{
28561a65
SM
5896 return (kind == TARGET_WAITKIND_FORKED
5897 || kind == TARGET_WAITKIND_VFORKED);
a4543480
SM
5898}
5899
28561a65
SM
5900/* Return THREAD's pending status if it is a pending fork parent, else
5901 return nullptr. */
a4543480 5902
28561a65 5903static const target_waitstatus *
a4543480
SM
5904thread_pending_fork_status (struct thread_info *thread)
5905{
28561a65
SM
5906 const target_waitstatus &ws
5907 = (thread->has_pending_waitstatus ()
5908 ? thread->pending_waitstatus ()
5909 : thread->pending_follow);
a4543480 5910
28561a65
SM
5911 if (!is_fork_status (ws.kind ()))
5912 return nullptr;
a4543480 5913
28561a65 5914 return &ws;
a4543480
SM
5915}
5916
de0d863e
DB
5917/* Detach the specified process. */
5918
6b8edb51
PA
5919void
5920remote_target::remote_detach_pid (int pid)
de0d863e
DB
5921{
5922 struct remote_state *rs = get_remote_state ();
5923
4c7333b3
PA
5924 /* This should not be necessary, but the handling for D;PID in
5925 GDBserver versions prior to 8.2 incorrectly assumes that the
5926 selected process points to the same process we're detaching,
5927 leading to misbehavior (and possibly GDBserver crashing) when it
5928 does not. Since it's easy and cheap, work around it by forcing
5929 GDBserver to select GDB's current process. */
5930 set_general_process ();
5931
de0d863e 5932 if (remote_multi_process_p (rs))
8d64371b 5933 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
de0d863e 5934 else
8d64371b 5935 strcpy (rs->buf.data (), "D");
de0d863e
DB
5936
5937 putpkt (rs->buf);
8d64371b 5938 getpkt (&rs->buf, 0);
de0d863e
DB
5939
5940 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5941 ;
5942 else if (rs->buf[0] == '\0')
5943 error (_("Remote doesn't know how to detach"));
5944 else
5945 error (_("Can't detach process."));
5946}
5947
5948/* This detaches a program to which we previously attached, using
5949 inferior_ptid to identify the process. After this is done, GDB
5950 can be used to debug some other program. We better not have left
5951 any breakpoints in the target program or it'll die when it hits
5952 one. */
c906108c 5953
6b8edb51 5954void
00431a78 5955remote_target::remote_detach_1 (inferior *inf, int from_tty)
c906108c 5956{
e99b03dc 5957 int pid = inferior_ptid.pid ();
d01949b6 5958 struct remote_state *rs = get_remote_state ();
de0d863e 5959 int is_fork_parent;
c906108c 5960
55f6301a 5961 if (!target_has_execution ())
2d717e4f
DJ
5962 error (_("No process to detach from."));
5963
0f48b757 5964 target_announce_detach (from_tty);
7cee1e54 5965
e87f0fe8
PA
5966 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
5967 {
5968 /* If we're in breakpoints-always-inserted mode, or the inferior
5969 is running, we have to remove breakpoints before detaching.
5970 We don't do this in common code instead because not all
5971 targets support removing breakpoints while the target is
5972 running. The remote target / gdbserver does, though. */
5973 remove_breakpoints_inf (current_inferior ());
5974 }
5975
c906108c 5976 /* Tell the remote target to detach. */
de0d863e 5977 remote_detach_pid (pid);
82f73884 5978
8020350c 5979 /* Exit only if this is the only active inferior. */
5b6d1e4f 5980 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
0426ad51 5981 gdb_puts (_("Ending remote debugging.\n"));
82f73884 5982
df5ad102
SM
5983 /* See if any thread of the inferior we are detaching has a pending fork
5984 status. In that case, we must detach from the child resulting from
5985 that fork. */
5986 for (thread_info *thread : inf->non_exited_threads ())
5987 {
5988 const target_waitstatus *ws = thread_pending_fork_status (thread);
5989
5990 if (ws == nullptr)
5991 continue;
5992
5993 remote_detach_pid (ws->child_ptid ().pid ());
5994 }
5995
5996 /* Check also for any pending fork events in the stop reply queue. */
5997 remote_notif_get_pending_events (&notif_client_stop);
5998 for (stop_reply_up &reply : rs->stop_reply_queue)
5999 {
6000 if (reply->ptid.pid () != pid)
6001 continue;
6002
6003 if (!is_fork_status (reply->ws.kind ()))
6004 continue;
6005
6006 remote_detach_pid (reply->ws.child_ptid ().pid ());
6007 }
6008
5b6d1e4f 6009 thread_info *tp = find_thread_ptid (this, inferior_ptid);
00431a78 6010
de0d863e
DB
6011 /* Check to see if we are detaching a fork parent. Note that if we
6012 are detaching a fork child, tp == NULL. */
6013 is_fork_parent = (tp != NULL
183be222 6014 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
de0d863e
DB
6015
6016 /* If doing detach-on-fork, we don't mourn, because that will delete
6017 breakpoints that should be available for the followed inferior. */
6018 if (!is_fork_parent)
f67c0c91 6019 {
249b5733
PA
6020 /* Save the pid as a string before mourning, since that will
6021 unpush the remote target, and we need the string after. */
f2907e49 6022 std::string infpid = target_pid_to_str (ptid_t (pid));
f67c0c91
SDJ
6023
6024 target_mourn_inferior (inferior_ptid);
6025 if (print_inferior_events)
6cb06a8c
TT
6026 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6027 inf->num, infpid.c_str ());
f67c0c91 6028 }
de0d863e
DB
6029 else
6030 {
0ac55310 6031 switch_to_no_thread ();
00431a78 6032 detach_inferior (current_inferior ());
de0d863e 6033 }
2d717e4f
DJ
6034}
6035
f6ac5f3d
PA
6036void
6037remote_target::detach (inferior *inf, int from_tty)
2d717e4f 6038{
00431a78 6039 remote_detach_1 (inf, from_tty);
2d717e4f
DJ
6040}
6041
f6ac5f3d
PA
6042void
6043extended_remote_target::detach (inferior *inf, int from_tty)
2d717e4f 6044{
00431a78 6045 remote_detach_1 (inf, from_tty);
de0d863e
DB
6046}
6047
6048/* Target follow-fork function for remote targets. On entry, and
6049 at return, the current inferior is the fork parent.
6050
6051 Note that although this is currently only used for extended-remote,
6052 it is named remote_follow_fork in anticipation of using it for the
6053 remote target as well. */
6054
e97007b6 6055void
82d1f134
SM
6056remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6057 target_waitkind fork_kind, bool follow_child,
6058 bool detach_fork)
de0d863e 6059{
82d1f134
SM
6060 process_stratum_target::follow_fork (child_inf, child_ptid,
6061 fork_kind, follow_child, detach_fork);
6062
de0d863e
DB
6063 struct remote_state *rs = get_remote_state ();
6064
3a849a34
SM
6065 if ((fork_kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
6066 || (fork_kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
6067 {
6068 /* When following the parent and detaching the child, we detach
6069 the child here. For the case of following the child and
6070 detaching the parent, the detach is done in the target-
6071 independent follow fork code in infrun.c. We can't use
6072 target_detach when detaching an unfollowed child because
6073 the client side doesn't know anything about the child. */
6074 if (detach_fork && !follow_child)
6075 {
6076 /* Detach the fork child. */
3a849a34 6077 remote_detach_pid (child_ptid.pid ());
de0d863e
DB
6078 }
6079 }
c906108c
SS
6080}
6081
94585166 6082/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
294c36eb 6083 in the program space of the new inferior. */
94585166 6084
f6ac5f3d 6085void
294c36eb
SM
6086remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6087 const char *execd_pathname)
94585166 6088{
294c36eb
SM
6089 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6090
94585166
DB
6091 /* We know that this is a target file name, so if it has the "target:"
6092 prefix we strip it off before saving it in the program space. */
6093 if (is_target_filename (execd_pathname))
6094 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6095
294c36eb 6096 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
94585166
DB
6097}
6098
6ad8ae5c
DJ
6099/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6100
f6ac5f3d
PA
6101void
6102remote_target::disconnect (const char *args, int from_tty)
43ff13b4 6103{
43ff13b4 6104 if (args)
2d717e4f 6105 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 6106
8020350c 6107 /* Make sure we unpush even the extended remote targets. Calling
5b6d1e4f
PA
6108 target_mourn_inferior won't unpush, and
6109 remote_target::mourn_inferior won't unpush if there is more than
6110 one inferior left. */
6111 remote_unpush_target (this);
2d717e4f 6112
43ff13b4 6113 if (from_tty)
0426ad51 6114 gdb_puts ("Ending remote debugging.\n");
43ff13b4
JM
6115}
6116
2d717e4f
DJ
6117/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6118 be chatty about it. */
6119
f6ac5f3d
PA
6120void
6121extended_remote_target::attach (const char *args, int from_tty)
2d717e4f
DJ
6122{
6123 struct remote_state *rs = get_remote_state ();
be86555c 6124 int pid;
96ef3384 6125 char *wait_status = NULL;
2d717e4f 6126
74164c56 6127 pid = parse_pid_to_attach (args);
2d717e4f 6128
74164c56
JK
6129 /* Remote PID can be freely equal to getpid, do not check it here the same
6130 way as in other targets. */
2d717e4f 6131
4082afcc 6132 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
6133 error (_("This target does not support attaching to a process"));
6134
bc521517 6135 target_announce_attach (from_tty, pid);
7cee1e54 6136
8d64371b 6137 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f 6138 putpkt (rs->buf);
8d64371b 6139 getpkt (&rs->buf, 0);
2d717e4f 6140
4082afcc
PA
6141 switch (packet_ok (rs->buf,
6142 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 6143 {
4082afcc 6144 case PACKET_OK:
6efcd9a8 6145 if (!target_is_non_stop_p ())
74531fed
PA
6146 {
6147 /* Save the reply for later. */
8d64371b
TT
6148 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6149 strcpy (wait_status, rs->buf.data ());
74531fed 6150 }
8d64371b 6151 else if (strcmp (rs->buf.data (), "OK") != 0)
74531fed 6152 error (_("Attaching to %s failed with: %s"),
a068643d 6153 target_pid_to_str (ptid_t (pid)).c_str (),
8d64371b 6154 rs->buf.data ());
4082afcc
PA
6155 break;
6156 case PACKET_UNKNOWN:
6157 error (_("This target does not support attaching to a process"));
6158 default:
50fa3001
SDJ
6159 error (_("Attaching to %s failed"),
6160 target_pid_to_str (ptid_t (pid)).c_str ());
2d717e4f 6161 }
2d717e4f 6162
0ac55310 6163 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
bad34192 6164
f2907e49 6165 inferior_ptid = ptid_t (pid);
79d7f229 6166
6efcd9a8 6167 if (target_is_non_stop_p ())
bad34192 6168 {
bad34192 6169 /* Get list of threads. */
f6ac5f3d 6170 update_thread_list ();
82f73884 6171
0ac55310
PA
6172 thread_info *thread = first_thread_of_inferior (current_inferior ());
6173 if (thread != nullptr)
6174 switch_to_thread (thread);
bad34192
PA
6175
6176 /* Invalidate our notion of the remote current thread. */
47f8a51d 6177 record_currthread (rs, minus_one_ptid);
bad34192 6178 }
74531fed 6179 else
bad34192 6180 {
0ac55310
PA
6181 /* Now, if we have thread information, update the main thread's
6182 ptid. */
6183 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
bad34192 6184
b622494e
AB
6185 /* Add the main thread to the thread list. We add the thread
6186 silently in this case (the final true parameter). */
6187 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
0ac55310
PA
6188
6189 switch_to_thread (thr);
bad34192 6190 }
c0a2216e 6191
96ef3384
UW
6192 /* Next, if the target can specify a description, read it. We do
6193 this before anything involving memory or registers. */
6194 target_find_description ();
6195
6efcd9a8 6196 if (!target_is_non_stop_p ())
74531fed
PA
6197 {
6198 /* Use the previously fetched status. */
6199 gdb_assert (wait_status != NULL);
6200
4f626cad
AB
6201 struct notif_event *reply
6202 = remote_notif_parse (this, &notif_client_stop, wait_status);
74531fed 6203
4f626cad 6204 push_stop_reply ((struct stop_reply *) reply);
74531fed
PA
6205 }
6206 else
621cc310
PA
6207 {
6208 gdb_assert (wait_status == NULL);
6209
6210 gdb_assert (target_can_async_p ());
621cc310 6211 }
2d717e4f
DJ
6212}
6213
b9c1d481
AS
6214/* Implementation of the to_post_attach method. */
6215
f6ac5f3d
PA
6216void
6217extended_remote_target::post_attach (int pid)
b9c1d481 6218{
6efcd9a8
PA
6219 /* Get text, data & bss offsets. */
6220 get_offsets ();
6221
b9c1d481
AS
6222 /* In certain cases GDB might not have had the chance to start
6223 symbol lookup up until now. This could happen if the debugged
6224 binary is not using shared libraries, the vsyscall page is not
6225 present (on Linux) and the binary itself hadn't changed since the
6226 debugging process was started. */
a42d7dd8 6227 if (current_program_space->symfile_object_file != NULL)
b9c1d481
AS
6228 remote_check_symbols();
6229}
6230
c906108c 6231\f
506fb367
DJ
6232/* Check for the availability of vCont. This function should also check
6233 the response. */
c906108c 6234
6b8edb51
PA
6235void
6236remote_target::remote_vcont_probe ()
c906108c 6237{
6b8edb51 6238 remote_state *rs = get_remote_state ();
2e9f7625 6239 char *buf;
6d820c5c 6240
8d64371b 6241 strcpy (rs->buf.data (), "vCont?");
2e9f7625 6242 putpkt (rs->buf);
8d64371b
TT
6243 getpkt (&rs->buf, 0);
6244 buf = rs->buf.data ();
c906108c 6245
506fb367 6246 /* Make sure that the features we assume are supported. */
61012eef 6247 if (startswith (buf, "vCont"))
506fb367
DJ
6248 {
6249 char *p = &buf[5];
750ce8d1 6250 int support_c, support_C;
506fb367 6251
750ce8d1
YQ
6252 rs->supports_vCont.s = 0;
6253 rs->supports_vCont.S = 0;
506fb367
DJ
6254 support_c = 0;
6255 support_C = 0;
d458bd84 6256 rs->supports_vCont.t = 0;
c1e36e3e 6257 rs->supports_vCont.r = 0;
506fb367
DJ
6258 while (p && *p == ';')
6259 {
6260 p++;
6261 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 6262 rs->supports_vCont.s = 1;
506fb367 6263 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 6264 rs->supports_vCont.S = 1;
506fb367
DJ
6265 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6266 support_c = 1;
6267 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6268 support_C = 1;
74531fed 6269 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 6270 rs->supports_vCont.t = 1;
c1e36e3e
PA
6271 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6272 rs->supports_vCont.r = 1;
506fb367
DJ
6273
6274 p = strchr (p, ';');
6275 }
c906108c 6276
750ce8d1
YQ
6277 /* If c, and C are not all supported, we can't use vCont. Clearing
6278 BUF will make packet_ok disable the packet. */
6279 if (!support_c || !support_C)
506fb367
DJ
6280 buf[0] = 0;
6281 }
c906108c 6282
8d64371b 6283 packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCont]);
5b6d1e4f 6284 rs->supports_vCont_probed = true;
506fb367 6285}
c906108c 6286
0d8f58ca
PA
6287/* Helper function for building "vCont" resumptions. Write a
6288 resumption to P. ENDP points to one-passed-the-end of the buffer
6289 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6290 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6291 resumed thread should be single-stepped and/or signalled. If PTID
6292 equals minus_one_ptid, then all threads are resumed; if PTID
d51926f0
PA
6293 represents a process, then all threads of the process are
6294 resumed. */
0d8f58ca 6295
6b8edb51
PA
6296char *
6297remote_target::append_resumption (char *p, char *endp,
6298 ptid_t ptid, int step, gdb_signal siggnal)
0d8f58ca
PA
6299{
6300 struct remote_state *rs = get_remote_state ();
6301
a493e3e2 6302 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 6303 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
6304 else if (step
6305 /* GDB is willing to range step. */
6306 && use_range_stepping
6307 /* Target supports range stepping. */
6308 && rs->supports_vCont.r
6309 /* We don't currently support range stepping multiple
6310 threads with a wildcard (though the protocol allows it,
6311 so stubs shouldn't make an active effort to forbid
6312 it). */
0e998d96 6313 && !(remote_multi_process_p (rs) && ptid.is_pid ()))
c1e36e3e
PA
6314 {
6315 struct thread_info *tp;
6316
d7e15655 6317 if (ptid == minus_one_ptid)
c1e36e3e
PA
6318 {
6319 /* If we don't know about the target thread's tid, then
6320 we're resuming magic_null_ptid (see caller). */
5b6d1e4f 6321 tp = find_thread_ptid (this, magic_null_ptid);
c1e36e3e
PA
6322 }
6323 else
5b6d1e4f 6324 tp = find_thread_ptid (this, ptid);
c1e36e3e
PA
6325 gdb_assert (tp != NULL);
6326
6327 if (tp->control.may_range_step)
6328 {
6329 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6330
6331 p += xsnprintf (p, endp - p, ";r%s,%s",
6332 phex_nz (tp->control.step_range_start,
6333 addr_size),
6334 phex_nz (tp->control.step_range_end,
6335 addr_size));
6336 }
6337 else
6338 p += xsnprintf (p, endp - p, ";s");
6339 }
0d8f58ca
PA
6340 else if (step)
6341 p += xsnprintf (p, endp - p, ";s");
a493e3e2 6342 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
6343 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6344 else
6345 p += xsnprintf (p, endp - p, ";c");
6346
0e998d96 6347 if (remote_multi_process_p (rs) && ptid.is_pid ())
0d8f58ca
PA
6348 {
6349 ptid_t nptid;
6350
6351 /* All (-1) threads of process. */
184ea2f7 6352 nptid = ptid_t (ptid.pid (), -1);
0d8f58ca
PA
6353
6354 p += xsnprintf (p, endp - p, ":");
6355 p = write_ptid (p, endp, nptid);
6356 }
d7e15655 6357 else if (ptid != minus_one_ptid)
0d8f58ca
PA
6358 {
6359 p += xsnprintf (p, endp - p, ":");
6360 p = write_ptid (p, endp, ptid);
6361 }
6362
6363 return p;
6364}
6365
799a2abe
PA
6366/* Clear the thread's private info on resume. */
6367
6368static void
6369resume_clear_thread_private_info (struct thread_info *thread)
6370{
6371 if (thread->priv != NULL)
6372 {
7aabaf9d
SM
6373 remote_thread_info *priv = get_remote_thread_info (thread);
6374
6375 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6376 priv->watch_data_address = 0;
799a2abe
PA
6377 }
6378}
6379
e5ef252a
PA
6380/* Append a vCont continue-with-signal action for threads that have a
6381 non-zero stop signal. */
6382
6b8edb51
PA
6383char *
6384remote_target::append_pending_thread_resumptions (char *p, char *endp,
6385 ptid_t ptid)
e5ef252a 6386{
5b6d1e4f 6387 for (thread_info *thread : all_non_exited_threads (this, ptid))
08036331 6388 if (inferior_ptid != thread->ptid
1edb66d8 6389 && thread->stop_signal () != GDB_SIGNAL_0)
e5ef252a
PA
6390 {
6391 p = append_resumption (p, endp, thread->ptid,
1edb66d8
SM
6392 0, thread->stop_signal ());
6393 thread->set_stop_signal (GDB_SIGNAL_0);
799a2abe 6394 resume_clear_thread_private_info (thread);
e5ef252a
PA
6395 }
6396
6397 return p;
6398}
6399
7b68ffbb
PA
6400/* Set the target running, using the packets that use Hc
6401 (c/s/C/S). */
6402
6b8edb51
PA
6403void
6404remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6405 gdb_signal siggnal)
7b68ffbb
PA
6406{
6407 struct remote_state *rs = get_remote_state ();
7b68ffbb
PA
6408 char *buf;
6409
6410 rs->last_sent_signal = siggnal;
6411 rs->last_sent_step = step;
6412
6413 /* The c/s/C/S resume packets use Hc, so set the continue
6414 thread. */
d7e15655 6415 if (ptid == minus_one_ptid)
7b68ffbb
PA
6416 set_continue_thread (any_thread_ptid);
6417 else
6418 set_continue_thread (ptid);
6419
5b6d1e4f 6420 for (thread_info *thread : all_non_exited_threads (this))
7b68ffbb
PA
6421 resume_clear_thread_private_info (thread);
6422
8d64371b 6423 buf = rs->buf.data ();
6b8edb51 6424 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6425 {
6426 /* We don't pass signals to the target in reverse exec mode. */
6427 if (info_verbose && siggnal != GDB_SIGNAL_0)
6428 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6429 siggnal);
6430
6431 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6432 error (_("Remote reverse-step not supported."));
6433 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6434 error (_("Remote reverse-continue not supported."));
6435
6436 strcpy (buf, step ? "bs" : "bc");
6437 }
6438 else if (siggnal != GDB_SIGNAL_0)
6439 {
6440 buf[0] = step ? 'S' : 'C';
6441 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6442 buf[2] = tohex (((int) siggnal) & 0xf);
6443 buf[3] = '\0';
6444 }
6445 else
6446 strcpy (buf, step ? "s" : "c");
6447
6448 putpkt (buf);
6449}
6450
d51926f0
PA
6451/* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6452 STEP, and SIGGNAL have the same meaning as in target_resume. This
6453 function returns non-zero iff it resumes the inferior.
44eaed12 6454
7b68ffbb
PA
6455 This function issues a strict subset of all possible vCont commands
6456 at the moment. */
44eaed12 6457
6b8edb51 6458int
d51926f0 6459remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6b8edb51 6460 enum gdb_signal siggnal)
506fb367
DJ
6461{
6462 struct remote_state *rs = get_remote_state ();
82f73884
PA
6463 char *p;
6464 char *endp;
44eaed12 6465
7b68ffbb 6466 /* No reverse execution actions defined for vCont. */
6b8edb51 6467 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6468 return 0;
6469
4082afcc 6470 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 6471 remote_vcont_probe ();
44eaed12 6472
4082afcc 6473 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 6474 return 0;
44eaed12 6475
8d64371b
TT
6476 p = rs->buf.data ();
6477 endp = p + get_remote_packet_size ();
82f73884 6478
506fb367
DJ
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
0d8f58ca
PA
6483 p += xsnprintf (p, endp - p, "vCont");
6484
d51926f0 6485 if (scope_ptid == magic_null_ptid)
c906108c 6486 {
79d7f229
PA
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. */
a9cbf802 6491 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 6492 }
d51926f0 6493 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
506fb367 6494 {
0d8f58ca
PA
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. */
a493e3e2 6499 if (step || siggnal != GDB_SIGNAL_0)
82f73884 6500 {
0d8f58ca
PA
6501 /* Step inferior_ptid, with or without signal. */
6502 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 6503 }
0d8f58ca 6504
e5ef252a
PA
6505 /* Also pass down any pending signaled resumption for other
6506 threads not the current. */
d51926f0 6507 p = append_pending_thread_resumptions (p, endp, scope_ptid);
e5ef252a 6508
0d8f58ca 6509 /* And continue others without a signal. */
d51926f0 6510 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
6511 }
6512 else
506fb367 6513 {
d51926f0
PA
6514 /* Scheduler locking; resume only SCOPE_PTID. */
6515 append_resumption (p, endp, scope_ptid, step, siggnal);
506fb367 6516 }
c906108c 6517
8d64371b 6518 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
82f73884 6519 putpkt (rs->buf);
506fb367 6520
6efcd9a8 6521 if (target_is_non_stop_p ())
74531fed
PA
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. */
8d64371b
TT
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 ());
74531fed
PA
6530 }
6531
506fb367 6532 return 1;
c906108c 6533}
43ff13b4 6534
506fb367
DJ
6535/* Tell the remote machine to resume. */
6536
f6ac5f3d 6537void
d51926f0 6538remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
43ff13b4 6539{
d01949b6 6540 struct remote_state *rs = get_remote_state ();
43ff13b4 6541
85ad3aaf
PA
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
c9d22089
SM
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. */
f6ac5f3d 6549 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
85ad3aaf 6550 {
d51926f0
PA
6551 remote_thread_info *remote_thr
6552 = get_remote_thread_info (inferior_thread ());
7aabaf9d 6553
c9d22089
SM
6554 /* We don't expect the core to ask to resume an already resumed (from
6555 its point of view) thread. */
a6c11cbb 6556 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
c9d22089
SM
6557
6558 remote_thr->set_resumed_pending_vcont (step, siggnal);
d51926f0
PA
6559
6560 /* There's actually nothing that says that the core can't
6561 request a wildcard resume in non-stop mode, though. It's
6562 just that we know it doesn't currently, so we don't bother
6563 with it. */
6564 gdb_assert (scope_ptid == inferior_ptid);
85ad3aaf
PA
6565 return;
6566 }
6567
722247f1
YQ
6568 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6569 (explained in remote-notif.c:handle_notification) so
6570 remote_notif_process is not called. We need find a place where
6571 it is safe to start a 'vNotif' sequence. It is good to do it
6572 before resuming inferior, because inferior was stopped and no RSP
6573 traffic at that moment. */
6efcd9a8 6574 if (!target_is_non_stop_p ())
5965e028 6575 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 6576
f6ac5f3d 6577 rs->last_resume_exec_dir = ::execution_direction;
3a00c802 6578
7b68ffbb 6579 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
d51926f0
PA
6580 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
6581 remote_resume_with_hc (scope_ptid, step, siggnal);
43ff13b4 6582
c9d22089 6583 /* Update resumed state tracked by the remote target. */
d51926f0 6584 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
c9d22089
SM
6585 get_remote_thread_info (tp)->set_resumed ();
6586
e24a49d8
PA
6587 /* We've just told the target to resume. The remote server will
6588 wait for the inferior to stop, and then send a stop reply. In
6589 the mean time, we can't start another command/query ourselves
74531fed
PA
6590 because the stub wouldn't be ready to process it. This applies
6591 only to the base all-stop protocol, however. In non-stop (which
6592 only supports vCont), the stub replies with an "OK", and is
6593 immediate able to process further serial input. */
6efcd9a8 6594 if (!target_is_non_stop_p ())
74531fed 6595 rs->waiting_for_stop_reply = 1;
43ff13b4 6596}
85ad3aaf 6597
85ad3aaf
PA
6598/* Private per-inferior info for target remote processes. */
6599
089354bb 6600struct remote_inferior : public private_inferior
85ad3aaf
PA
6601{
6602 /* Whether we can send a wildcard vCont for this process. */
089354bb 6603 bool may_wildcard_vcont = true;
85ad3aaf
PA
6604};
6605
089354bb
SM
6606/* Get the remote private inferior data associated to INF. */
6607
6608static remote_inferior *
6609get_remote_inferior (inferior *inf)
6610{
6611 if (inf->priv == NULL)
6612 inf->priv.reset (new remote_inferior);
6613
6614 return static_cast<remote_inferior *> (inf->priv.get ());
6615}
6616
f5db4863 6617/* Class used to track the construction of a vCont packet in the
85ad3aaf
PA
6618 outgoing packet buffer. This is used to send multiple vCont
6619 packets if we have more actions than would fit a single packet. */
6620
f5db4863 6621class vcont_builder
85ad3aaf 6622{
f5db4863 6623public:
6b8edb51
PA
6624 explicit vcont_builder (remote_target *remote)
6625 : m_remote (remote)
f5db4863
PA
6626 {
6627 restart ();
6628 }
6629
6630 void flush ();
6631 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6632
6633private:
6634 void restart ();
6635
6b8edb51
PA
6636 /* The remote target. */
6637 remote_target *m_remote;
6638
85ad3aaf
PA
6639 /* Pointer to the first action. P points here if no action has been
6640 appended yet. */
f5db4863 6641 char *m_first_action;
85ad3aaf
PA
6642
6643 /* Where the next action will be appended. */
f5db4863 6644 char *m_p;
85ad3aaf
PA
6645
6646 /* The end of the buffer. Must never write past this. */
f5db4863 6647 char *m_endp;
85ad3aaf
PA
6648};
6649
6650/* Prepare the outgoing buffer for a new vCont packet. */
6651
f5db4863
PA
6652void
6653vcont_builder::restart ()
85ad3aaf 6654{
6b8edb51 6655 struct remote_state *rs = m_remote->get_remote_state ();
85ad3aaf 6656
8d64371b
TT
6657 m_p = rs->buf.data ();
6658 m_endp = m_p + m_remote->get_remote_packet_size ();
f5db4863
PA
6659 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6660 m_first_action = m_p;
85ad3aaf
PA
6661}
6662
6663/* If the vCont packet being built has any action, send it to the
6664 remote end. */
6665
f5db4863
PA
6666void
6667vcont_builder::flush ()
85ad3aaf
PA
6668{
6669 struct remote_state *rs;
6670
f5db4863 6671 if (m_p == m_first_action)
85ad3aaf
PA
6672 return;
6673
6b8edb51
PA
6674 rs = m_remote->get_remote_state ();
6675 m_remote->putpkt (rs->buf);
8d64371b
TT
6676 m_remote->getpkt (&rs->buf, 0);
6677 if (strcmp (rs->buf.data (), "OK") != 0)
6678 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
85ad3aaf
PA
6679}
6680
6681/* The largest action is range-stepping, with its two addresses. This
6682 is more than sufficient. If a new, bigger action is created, it'll
6683 quickly trigger a failed assertion in append_resumption (and we'll
6684 just bump this). */
6685#define MAX_ACTION_SIZE 200
6686
6687/* Append a new vCont action in the outgoing packet being built. If
6688 the action doesn't fit the packet along with previous actions, push
6689 what we've got so far to the remote end and start over a new vCont
6690 packet (with the new action). */
6691
f5db4863
PA
6692void
6693vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
85ad3aaf
PA
6694{
6695 char buf[MAX_ACTION_SIZE + 1];
85ad3aaf 6696
6b8edb51
PA
6697 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6698 ptid, step, siggnal);
85ad3aaf
PA
6699
6700 /* Check whether this new action would fit in the vCont packet along
6701 with previous actions. If not, send what we've got so far and
6702 start a new vCont packet. */
f5db4863
PA
6703 size_t rsize = endp - buf;
6704 if (rsize > m_endp - m_p)
85ad3aaf 6705 {
f5db4863
PA
6706 flush ();
6707 restart ();
85ad3aaf
PA
6708
6709 /* Should now fit. */
f5db4863 6710 gdb_assert (rsize <= m_endp - m_p);
85ad3aaf
PA
6711 }
6712
f5db4863
PA
6713 memcpy (m_p, buf, rsize);
6714 m_p += rsize;
6715 *m_p = '\0';
85ad3aaf
PA
6716}
6717
6718/* to_commit_resume implementation. */
6719
f6ac5f3d 6720void
1192f124 6721remote_target::commit_resumed ()
85ad3aaf 6722{
85ad3aaf
PA
6723 /* If connected in all-stop mode, we'd send the remote resume
6724 request directly from remote_resume. Likewise if
6725 reverse-debugging, as there are no defined vCont actions for
6726 reverse execution. */
f6ac5f3d 6727 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
85ad3aaf
PA
6728 return;
6729
6730 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6731 instead of resuming all threads of each process individually.
6732 However, if any thread of a process must remain halted, we can't
6733 send wildcard resumes and must send one action per thread.
6734
6735 Care must be taken to not resume threads/processes the server
6736 side already told us are stopped, but the core doesn't know about
6737 yet, because the events are still in the vStopped notification
6738 queue. For example:
6739
6740 #1 => vCont s:p1.1;c
6741 #2 <= OK
6742 #3 <= %Stopped T05 p1.1
6743 #4 => vStopped
6744 #5 <= T05 p1.2
6745 #6 => vStopped
6746 #7 <= OK
6747 #8 (infrun handles the stop for p1.1 and continues stepping)
6748 #9 => vCont s:p1.1;c
6749
6750 The last vCont above would resume thread p1.2 by mistake, because
6751 the server has no idea that the event for p1.2 had not been
6752 handled yet.
6753
6754 The server side must similarly ignore resume actions for the
6755 thread that has a pending %Stopped notification (and any other
6756 threads with events pending), until GDB acks the notification
6757 with vStopped. Otherwise, e.g., the following case is
6758 mishandled:
6759
6760 #1 => g (or any other packet)
6761 #2 <= [registers]
6762 #3 <= %Stopped T05 p1.2
6763 #4 => vCont s:p1.1;c
6764 #5 <= OK
6765
6766 Above, the server must not resume thread p1.2. GDB can't know
6767 that p1.2 stopped until it acks the %Stopped notification, and
6768 since from GDB's perspective all threads should be running, it
6769 sends a "c" action.
6770
6771 Finally, special care must also be given to handling fork/vfork
6772 events. A (v)fork event actually tells us that two processes
6773 stopped -- the parent and the child. Until we follow the fork,
6774 we must not resume the child. Therefore, if we have a pending
6775 fork follow, we must not send a global wildcard resume action
6776 (vCont;c). We can still send process-wide wildcards though. */
6777
6778 /* Start by assuming a global wildcard (vCont;c) is possible. */
2f63ec5c 6779 bool may_global_wildcard_vcont = true;
85ad3aaf
PA
6780
6781 /* And assume every process is individually wildcard-able too. */
5b6d1e4f 6782 for (inferior *inf : all_non_exited_inferiors (this))
85ad3aaf 6783 {
089354bb
SM
6784 remote_inferior *priv = get_remote_inferior (inf);
6785
6786 priv->may_wildcard_vcont = true;
85ad3aaf
PA
6787 }
6788
6789 /* Check for any pending events (not reported or processed yet) and
6790 disable process and global wildcard resumes appropriately. */
6791 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6792
1192f124
SM
6793 bool any_pending_vcont_resume = false;
6794
5b6d1e4f 6795 for (thread_info *tp : all_non_exited_threads (this))
85ad3aaf 6796 {
c9d22089
SM
6797 remote_thread_info *priv = get_remote_thread_info (tp);
6798
85ad3aaf
PA
6799 /* If a thread of a process is not meant to be resumed, then we
6800 can't wildcard that process. */
a6c11cbb 6801 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
85ad3aaf 6802 {
089354bb 6803 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
85ad3aaf
PA
6804
6805 /* And if we can't wildcard a process, we can't wildcard
6806 everything either. */
2f63ec5c 6807 may_global_wildcard_vcont = false;
85ad3aaf
PA
6808 continue;
6809 }
6810
1192f124
SM
6811 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
6812 any_pending_vcont_resume = true;
6813
85ad3aaf
PA
6814 /* If a thread is the parent of an unfollowed fork, then we
6815 can't do a global wildcard, as that would resume the fork
6816 child. */
28561a65 6817 if (thread_pending_fork_status (tp) != nullptr)
2f63ec5c 6818 may_global_wildcard_vcont = false;
85ad3aaf
PA
6819 }
6820
1192f124
SM
6821 /* We didn't have any resumed thread pending a vCont resume, so nothing to
6822 do. */
6823 if (!any_pending_vcont_resume)
6824 return;
6825
85ad3aaf
PA
6826 /* Now let's build the vCont packet(s). Actions must be appended
6827 from narrower to wider scopes (thread -> process -> global). If
6828 we end up with too many actions for a single packet vcont_builder
6829 flushes the current vCont packet to the remote side and starts a
6830 new one. */
6b8edb51 6831 struct vcont_builder vcont_builder (this);
85ad3aaf
PA
6832
6833 /* Threads first. */
5b6d1e4f 6834 for (thread_info *tp : all_non_exited_threads (this))
85ad3aaf 6835 {
7aabaf9d 6836 remote_thread_info *remote_thr = get_remote_thread_info (tp);
85ad3aaf 6837
c9d22089
SM
6838 /* If the thread was previously vCont-resumed, no need to send a specific
6839 action for it. If we didn't receive a resume request for it, don't
6840 send an action for it either. */
a6c11cbb 6841 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
85ad3aaf
PA
6842 continue;
6843
6844 gdb_assert (!thread_is_in_step_over_chain (tp));
6845
1192f124
SM
6846 /* We should never be commit-resuming a thread that has a stop reply.
6847 Otherwise, we would end up reporting a stop event for a thread while
6848 it is running on the remote target. */
6849 remote_state *rs = get_remote_state ();
6850 for (const auto &stop_reply : rs->stop_reply_queue)
6851 gdb_assert (stop_reply->ptid != tp->ptid);
6852
c9d22089
SM
6853 const resumed_pending_vcont_info &info
6854 = remote_thr->resumed_pending_vcont_info ();
85ad3aaf 6855
c9d22089
SM
6856 /* Check if we need to send a specific action for this thread. If not,
6857 it will be included in a wildcard resume instead. */
6858 if (info.step || info.sig != GDB_SIGNAL_0
6859 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
6860 vcont_builder.push_action (tp->ptid, info.step, info.sig);
6861
6862 remote_thr->set_resumed ();
85ad3aaf
PA
6863 }
6864
6865 /* Now check whether we can send any process-wide wildcard. This is
6866 to avoid sending a global wildcard in the case nothing is
6867 supposed to be resumed. */
2f63ec5c 6868 bool any_process_wildcard = false;
85ad3aaf 6869
5b6d1e4f 6870 for (inferior *inf : all_non_exited_inferiors (this))
85ad3aaf 6871 {
089354bb 6872 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf 6873 {
2f63ec5c 6874 any_process_wildcard = true;
85ad3aaf
PA
6875 break;
6876 }
6877 }
6878
6879 if (any_process_wildcard)
6880 {
6881 /* If all processes are wildcard-able, then send a single "c"
6882 action, otherwise, send an "all (-1) threads of process"
6883 continue action for each running process, if any. */
6884 if (may_global_wildcard_vcont)
6885 {
f5db4863
PA
6886 vcont_builder.push_action (minus_one_ptid,
6887 false, GDB_SIGNAL_0);
85ad3aaf
PA
6888 }
6889 else
6890 {
5b6d1e4f 6891 for (inferior *inf : all_non_exited_inferiors (this))
85ad3aaf 6892 {
089354bb 6893 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf 6894 {
f2907e49 6895 vcont_builder.push_action (ptid_t (inf->pid),
f5db4863 6896 false, GDB_SIGNAL_0);
85ad3aaf
PA
6897 }
6898 }
6899 }
6900 }
6901
f5db4863 6902 vcont_builder.flush ();
85ad3aaf
PA
6903}
6904
b4b1a226
SM
6905/* Implementation of target_has_pending_events. */
6906
6907bool
6908remote_target::has_pending_events ()
6909{
6910 if (target_can_async_p ())
6911 {
6912 remote_state *rs = get_remote_state ();
6913
6914 if (async_event_handler_marked (rs->remote_async_inferior_event_token))
6915 return true;
6916
6917 /* Note that BUFCNT can be negative, indicating sticky
6918 error. */
6919 if (rs->remote_desc->bufcnt != 0)
6920 return true;
6921 }
6922 return false;
6923}
6924
c906108c 6925\f
43ff13b4 6926
74531fed
PA
6927/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6928 thread, all threads of a remote process, or all threads of all
6929 processes. */
6930
6b8edb51
PA
6931void
6932remote_target::remote_stop_ns (ptid_t ptid)
74531fed
PA
6933{
6934 struct remote_state *rs = get_remote_state ();
8d64371b
TT
6935 char *p = rs->buf.data ();
6936 char *endp = p + get_remote_packet_size ();
74531fed 6937
1192f124
SM
6938 /* If any thread that needs to stop was resumed but pending a vCont
6939 resume, generate a phony stop_reply. However, first check
6940 whether the thread wasn't resumed with a signal. Generating a
6941 phony stop in that case would result in losing the signal. */
6942 bool needs_commit = false;
6943 for (thread_info *tp : all_non_exited_threads (this, ptid))
6944 {
6945 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6946
6947 if (remote_thr->get_resume_state ()
6948 == resume_state::RESUMED_PENDING_VCONT)
6949 {
6950 const resumed_pending_vcont_info &info
6951 = remote_thr->resumed_pending_vcont_info ();
6952 if (info.sig != GDB_SIGNAL_0)
6953 {
6954 /* This signal must be forwarded to the inferior. We
6955 could commit-resume just this thread, but its simpler
6956 to just commit-resume everything. */
6957 needs_commit = true;
6958 break;
6959 }
6960 }
6961 }
6962
6963 if (needs_commit)
6964 commit_resumed ();
6965 else
6966 for (thread_info *tp : all_non_exited_threads (this, ptid))
6967 {
6968 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6969
6970 if (remote_thr->get_resume_state ()
6971 == resume_state::RESUMED_PENDING_VCONT)
6972 {
6973 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
96bbe3ef
TT
6974 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
6975 tp->ptid.lwp (),
6976 pulongest (tp->ptid.tid ()));
1192f124
SM
6977
6978 /* Check that the thread wasn't resumed with a signal.
6979 Generating a phony stop would result in losing the
6980 signal. */
6981 const resumed_pending_vcont_info &info
6982 = remote_thr->resumed_pending_vcont_info ();
6983 gdb_assert (info.sig == GDB_SIGNAL_0);
6984
6985 stop_reply *sr = new stop_reply ();
6986 sr->ptid = tp->ptid;
6987 sr->rs = rs;
183be222 6988 sr->ws.set_stopped (GDB_SIGNAL_0);
1192f124
SM
6989 sr->arch = tp->inf->gdbarch;
6990 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6991 sr->watch_data_address = 0;
6992 sr->core = 0;
6993 this->push_stop_reply (sr);
6994
6995 /* Pretend that this thread was actually resumed on the
6996 remote target, then stopped. If we leave it in the
6997 RESUMED_PENDING_VCONT state and the commit_resumed
6998 method is called while the stop reply is still in the
6999 queue, we'll end up reporting a stop event to the core
7000 for that thread while it is running on the remote
7001 target... that would be bad. */
7002 remote_thr->set_resumed ();
7003 }
7004 }
7005
5b6d1e4f
PA
7006 /* FIXME: This supports_vCont_probed check is a workaround until
7007 packet_support is per-connection. */
7008 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN
7009 || !rs->supports_vCont_probed)
6b8edb51 7010 remote_vcont_probe ();
74531fed 7011
d458bd84 7012 if (!rs->supports_vCont.t)
74531fed
PA
7013 error (_("Remote server does not support stopping threads"));
7014
d7e15655 7015 if (ptid == minus_one_ptid
0e998d96 7016 || (!remote_multi_process_p (rs) && ptid.is_pid ()))
74531fed
PA
7017 p += xsnprintf (p, endp - p, "vCont;t");
7018 else
7019 {
7020 ptid_t nptid;
7021
74531fed
PA
7022 p += xsnprintf (p, endp - p, "vCont;t:");
7023
0e998d96 7024 if (ptid.is_pid ())
74531fed 7025 /* All (-1) threads of process. */
184ea2f7 7026 nptid = ptid_t (ptid.pid (), -1);
74531fed
PA
7027 else
7028 {
7029 /* Small optimization: if we already have a stop reply for
7030 this thread, no use in telling the stub we want this
7031 stopped. */
7032 if (peek_stop_reply (ptid))
7033 return;
7034
7035 nptid = ptid;
7036 }
7037
a9cbf802 7038 write_ptid (p, endp, nptid);
74531fed
PA
7039 }
7040
7041 /* In non-stop, we get an immediate OK reply. The stop reply will
7042 come in asynchronously by notification. */
7043 putpkt (rs->buf);
8d64371b
TT
7044 getpkt (&rs->buf, 0);
7045 if (strcmp (rs->buf.data (), "OK") != 0)
a068643d 7046 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
8d64371b 7047 rs->buf.data ());
74531fed
PA
7048}
7049
bfedc46a
PA
7050/* All-stop version of target_interrupt. Sends a break or a ^C to
7051 interrupt the remote target. It is undefined which thread of which
7052 process reports the interrupt. */
74531fed 7053
6b8edb51
PA
7054void
7055remote_target::remote_interrupt_as ()
74531fed
PA
7056{
7057 struct remote_state *rs = get_remote_state ();
7058
3a29589a
DJ
7059 rs->ctrlc_pending_p = 1;
7060
74531fed 7061 /* If the inferior is stopped already, but the core didn't know
4f626cad 7062 about it yet, just ignore the request. The pending stop events
74531fed 7063 will be collected in remote_wait. */
4f626cad 7064 if (stop_reply_queue_length () > 0)
74531fed
PA
7065 return;
7066
9a7071a8
JB
7067 /* Send interrupt_sequence to remote target. */
7068 send_interrupt_sequence ();
74531fed
PA
7069}
7070
de979965
PA
7071/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7072 the remote target. It is undefined which thread of which process
e42de8c7
PA
7073 reports the interrupt. Throws an error if the packet is not
7074 supported by the server. */
de979965 7075
6b8edb51
PA
7076void
7077remote_target::remote_interrupt_ns ()
de979965
PA
7078{
7079 struct remote_state *rs = get_remote_state ();
8d64371b
TT
7080 char *p = rs->buf.data ();
7081 char *endp = p + get_remote_packet_size ();
de979965
PA
7082
7083 xsnprintf (p, endp - p, "vCtrlC");
7084
7085 /* In non-stop, we get an immediate OK reply. The stop reply will
7086 come in asynchronously by notification. */
7087 putpkt (rs->buf);
8d64371b 7088 getpkt (&rs->buf, 0);
de979965
PA
7089
7090 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
7091 {
7092 case PACKET_OK:
7093 break;
7094 case PACKET_UNKNOWN:
e42de8c7 7095 error (_("No support for interrupting the remote target."));
de979965 7096 case PACKET_ERROR:
8d64371b 7097 error (_("Interrupting target failed: %s"), rs->buf.data ());
de979965 7098 }
de979965
PA
7099}
7100
bfedc46a 7101/* Implement the to_stop function for the remote targets. */
74531fed 7102
f6ac5f3d
PA
7103void
7104remote_target::stop (ptid_t ptid)
c906108c 7105{
2189c312 7106 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
c906108c 7107
6efcd9a8 7108 if (target_is_non_stop_p ())
74531fed 7109 remote_stop_ns (ptid);
c906108c 7110 else
bfedc46a
PA
7111 {
7112 /* We don't currently have a way to transparently pause the
7113 remote target in all-stop mode. Interrupt it instead. */
de979965 7114 remote_interrupt_as ();
bfedc46a
PA
7115 }
7116}
7117
7118/* Implement the to_interrupt function for the remote targets. */
7119
f6ac5f3d
PA
7120void
7121remote_target::interrupt ()
bfedc46a 7122{
2189c312 7123 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
bfedc46a 7124
e42de8c7
PA
7125 if (target_is_non_stop_p ())
7126 remote_interrupt_ns ();
bfedc46a 7127 else
e42de8c7 7128 remote_interrupt_as ();
c906108c
SS
7129}
7130
93692b58
PA
7131/* Implement the to_pass_ctrlc function for the remote targets. */
7132
f6ac5f3d
PA
7133void
7134remote_target::pass_ctrlc ()
93692b58 7135{
2189c312 7136 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
93692b58 7137
2189c312 7138 struct remote_state *rs = get_remote_state ();
93692b58
PA
7139
7140 /* If we're starting up, we're not fully synced yet. Quit
7141 immediately. */
7142 if (rs->starting_up)
7143 quit ();
7144 /* If ^C has already been sent once, offer to disconnect. */
7145 else if (rs->ctrlc_pending_p)
7146 interrupt_query ();
7147 else
e671cd59 7148 target_interrupt ();
93692b58
PA
7149}
7150
c906108c
SS
7151/* Ask the user what to do when an interrupt is received. */
7152
6b8edb51
PA
7153void
7154remote_target::interrupt_query ()
c906108c 7155{
abc56d60 7156 struct remote_state *rs = get_remote_state ();
c906108c 7157
abc56d60 7158 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 7159 {
abc56d60
PA
7160 if (query (_("The target is not responding to interrupt requests.\n"
7161 "Stop debugging it? ")))
74531fed 7162 {
5b6d1e4f 7163 remote_unpush_target (this);
abc56d60 7164 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
7165 }
7166 }
abc56d60
PA
7167 else
7168 {
7169 if (query (_("Interrupted while waiting for the program.\n"
7170 "Give up waiting? ")))
7171 quit ();
7172 }
c906108c
SS
7173}
7174
6426a772
JM
7175/* Enable/disable target terminal ownership. Most targets can use
7176 terminal groups to control terminal ownership. Remote targets are
7177 different in that explicit transfer of ownership to/from GDB/target
23860348 7178 is required. */
6426a772 7179
f6ac5f3d
PA
7180void
7181remote_target::terminal_inferior ()
6426a772 7182{
6426a772
JM
7183 /* NOTE: At this point we could also register our selves as the
7184 recipient of all input. Any characters typed could then be
23860348 7185 passed on down to the target. */
6426a772
JM
7186}
7187
f6ac5f3d
PA
7188void
7189remote_target::terminal_ours ()
6426a772 7190{
6426a772
JM
7191}
7192
176a6961 7193static void
05be00a8 7194remote_console_output (const char *msg)
c906108c 7195{
05be00a8 7196 const char *p;
c906108c 7197
c5aa993b 7198 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
7199 {
7200 char tb[2];
7201 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 7202
c906108c
SS
7203 tb[0] = c;
7204 tb[1] = 0;
da5bd37e 7205 gdb_stdtarg->puts (tb);
c906108c 7206 }
da5bd37e 7207 gdb_stdtarg->flush ();
00db5b94 7208}
74531fed 7209
221e1a37
PA
7210/* Return the length of the stop reply queue. */
7211
6b8edb51
PA
7212int
7213remote_target::stop_reply_queue_length ()
221e1a37 7214{
6b8edb51 7215 remote_state *rs = get_remote_state ();
953edf2b 7216 return rs->stop_reply_queue.size ();
221e1a37
PA
7217}
7218
cb8c24b6 7219static void
6b8edb51 7220remote_notif_stop_parse (remote_target *remote,
bb277751 7221 struct notif_client *self, const char *buf,
722247f1
YQ
7222 struct notif_event *event)
7223{
6b8edb51 7224 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
722247f1
YQ
7225}
7226
7227static void
6b8edb51 7228remote_notif_stop_ack (remote_target *remote,
bb277751 7229 struct notif_client *self, const char *buf,
722247f1
YQ
7230 struct notif_event *event)
7231{
7232 struct stop_reply *stop_reply = (struct stop_reply *) event;
7233
7234 /* acknowledge */
6b8edb51 7235 putpkt (remote, self->ack_command);
722247f1 7236
b0083dd7
PA
7237 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7238 the notification. It was left in the queue because we need to
7239 acknowledge it and pull the rest of the notifications out. */
183be222 7240 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
b0083dd7 7241 remote->push_stop_reply (stop_reply);
722247f1
YQ
7242}
7243
7244static int
6b8edb51
PA
7245remote_notif_stop_can_get_pending_events (remote_target *remote,
7246 struct notif_client *self)
722247f1
YQ
7247{
7248 /* We can't get pending events in remote_notif_process for
7249 notification stop, and we have to do this in remote_wait_ns
7250 instead. If we fetch all queued events from stub, remote stub
7251 may exit and we have no chance to process them back in
7252 remote_wait_ns. */
6b8edb51
PA
7253 remote_state *rs = remote->get_remote_state ();
7254 mark_async_event_handler (rs->remote_async_inferior_event_token);
722247f1
YQ
7255 return 0;
7256}
7257
32603266 7258stop_reply::~stop_reply ()
722247f1 7259{
32603266
TT
7260 for (cached_reg_t &reg : regcache)
7261 xfree (reg.data);
722247f1
YQ
7262}
7263
32603266
TT
7264static notif_event_up
7265remote_notif_stop_alloc_reply ()
722247f1 7266{
32603266 7267 return notif_event_up (new struct stop_reply ());
722247f1
YQ
7268}
7269
7270/* A client of notification Stop. */
7271
7272struct notif_client notif_client_stop =
7273{
7274 "Stop",
7275 "vStopped",
7276 remote_notif_stop_parse,
7277 remote_notif_stop_ack,
7278 remote_notif_stop_can_get_pending_events,
7279 remote_notif_stop_alloc_reply,
f48ff2a7 7280 REMOTE_NOTIF_STOP,
722247f1
YQ
7281};
7282
cbb8991c
DB
7283/* If CONTEXT contains any fork child threads that have not been
7284 reported yet, remove them from the CONTEXT list. If such a
7285 thread exists it is because we are stopped at a fork catchpoint
7286 and have not yet called follow_fork, which will set up the
7287 host-side data structures for the new process. */
7288
6b8edb51
PA
7289void
7290remote_target::remove_new_fork_children (threads_listing_context *context)
cbb8991c 7291{
cbb8991c 7292 struct notif_client *notif = &notif_client_stop;
cbb8991c
DB
7293
7294 /* For any threads stopped at a fork event, remove the corresponding
7295 fork child threads from the CONTEXT list. */
5b6d1e4f 7296 for (thread_info *thread : all_non_exited_threads (this))
cbb8991c 7297 {
28561a65
SM
7298 const target_waitstatus *ws = thread_pending_fork_status (thread);
7299
7300 if (ws == nullptr)
7301 continue;
cbb8991c 7302
28561a65 7303 context->remove_thread (ws->child_ptid ());
cbb8991c
DB
7304 }
7305
7306 /* Check for any pending fork events (not reported or processed yet)
7307 in process PID and remove those fork child threads from the
7308 CONTEXT list as well. */
7309 remote_notif_get_pending_events (notif);
953edf2b 7310 for (auto &event : get_remote_state ()->stop_reply_queue)
183be222 7311 if (event->ws.kind () == TARGET_WAITKIND_FORKED
3890f02a 7312 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
183be222 7313 context->remove_thread (event->ws.child_ptid ());
3890f02a
SM
7314 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7315 context->remove_thread (event->ptid);
85ad3aaf
PA
7316}
7317
2f63ec5c
AB
7318/* Check whether any event pending in the vStopped queue would prevent a
7319 global or process wildcard vCont action. Set *may_global_wildcard to
7320 false if we can't do a global wildcard (vCont;c), and clear the event
7321 inferior's may_wildcard_vcont flag if we can't do a process-wide
7322 wildcard resume (vCont;c:pPID.-1). */
85ad3aaf 7323
6b8edb51
PA
7324void
7325remote_target::check_pending_events_prevent_wildcard_vcont
2f63ec5c 7326 (bool *may_global_wildcard)
85ad3aaf
PA
7327{
7328 struct notif_client *notif = &notif_client_stop;
7329
7330 remote_notif_get_pending_events (notif);
953edf2b
TT
7331 for (auto &event : get_remote_state ()->stop_reply_queue)
7332 {
183be222
SM
7333 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7334 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
953edf2b 7335 continue;
85ad3aaf 7336
183be222
SM
7337 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7338 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
2f63ec5c 7339 *may_global_wildcard = false;
722247f1 7340
953edf2b
TT
7341 /* This may be the first time we heard about this process.
7342 Regardless, we must not do a global wildcard resume, otherwise
7343 we'd resume this process too. */
2f63ec5c 7344 *may_global_wildcard = false;
323fd5b9
PA
7345 if (event->ptid != null_ptid)
7346 {
7347 inferior *inf = find_inferior_ptid (this, event->ptid);
7348 if (inf != NULL)
7349 get_remote_inferior (inf)->may_wildcard_vcont = false;
7350 }
722247f1 7351 }
722247f1
YQ
7352}
7353
f48ff2a7 7354/* Discard all pending stop replies of inferior INF. */
c906108c 7355
6b8edb51
PA
7356void
7357remote_target::discard_pending_stop_replies (struct inferior *inf)
c906108c 7358{
f48ff2a7
YQ
7359 struct stop_reply *reply;
7360 struct remote_state *rs = get_remote_state ();
7361 struct remote_notif_state *rns = rs->notif_state;
7362
7363 /* This function can be notified when an inferior exists. When the
7364 target is not remote, the notification state is NULL. */
7365 if (rs->remote_desc == NULL)
7366 return;
7367
7368 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 7369
74531fed 7370 /* Discard the in-flight notification. */
e99b03dc 7371 if (reply != NULL && reply->ptid.pid () == inf->pid)
74531fed 7372 {
b0083dd7
PA
7373 /* Leave the notification pending, since the server expects that
7374 we acknowledge it with vStopped. But clear its contents, so
7375 that later on when we acknowledge it, we also discard it. */
df5ad102
SM
7376 remote_debug_printf
7377 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7378 reply->ptid.to_string().c_str(),
7379 reply->ws.to_string ().c_str ());
183be222 7380 reply->ws.set_ignore ();
74531fed 7381 }
c906108c 7382
74531fed
PA
7383 /* Discard the stop replies we have already pulled with
7384 vStopped. */
953edf2b
TT
7385 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7386 rs->stop_reply_queue.end (),
7387 [=] (const stop_reply_up &event)
7388 {
7389 return event->ptid.pid () == inf->pid;
7390 });
df5ad102
SM
7391 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7392 remote_debug_printf
7393 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7394 reply->ptid.to_string().c_str(),
7395 reply->ws.to_string ().c_str ());
953edf2b 7396 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
bcc75809
YQ
7397}
7398
7399/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7 7400
6b8edb51
PA
7401void
7402remote_target::discard_pending_stop_replies_in_queue ()
f48ff2a7 7403{
6b8edb51 7404 remote_state *rs = get_remote_state ();
f48ff2a7 7405
f48ff2a7
YQ
7406 /* Discard the stop replies we have already pulled with
7407 vStopped. */
953edf2b
TT
7408 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7409 rs->stop_reply_queue.end (),
7410 [=] (const stop_reply_up &event)
7411 {
7412 return event->rs == rs;
7413 });
7414 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
74531fed 7415}
43ff13b4 7416
722247f1
YQ
7417/* Remove the first reply in 'stop_reply_queue' which matches
7418 PTID. */
2e9f7625 7419
6b8edb51
PA
7420struct stop_reply *
7421remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 7422{
953edf2b 7423 remote_state *rs = get_remote_state ();
722247f1 7424
953edf2b
TT
7425 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7426 rs->stop_reply_queue.end (),
7427 [=] (const stop_reply_up &event)
7428 {
7429 return event->ptid.matches (ptid);
7430 });
7431 struct stop_reply *result;
7432 if (iter == rs->stop_reply_queue.end ())
7433 result = nullptr;
7434 else
7435 {
7436 result = iter->release ();
7437 rs->stop_reply_queue.erase (iter);
7438 }
722247f1 7439
722247f1 7440 if (notif_debug)
6cb06a8c
TT
7441 gdb_printf (gdb_stdlog,
7442 "notif: discard queued event: 'Stop' in %s\n",
7443 ptid.to_string ().c_str ());
a744cf53 7444
953edf2b 7445 return result;
74531fed 7446}
75c99385 7447
74531fed
PA
7448/* Look for a queued stop reply belonging to PTID. If one is found,
7449 remove it from the queue, and return it. Returns NULL if none is
7450 found. If there are still queued events left to process, tell the
7451 event loop to get back to target_wait soon. */
e24a49d8 7452
6b8edb51
PA
7453struct stop_reply *
7454remote_target::queued_stop_reply (ptid_t ptid)
74531fed 7455{
953edf2b 7456 remote_state *rs = get_remote_state ();
722247f1 7457 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 7458
4f626cad 7459 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
6b8edb51 7460 {
6b8edb51
PA
7461 /* There's still at least an event left. */
7462 mark_async_event_handler (rs->remote_async_inferior_event_token);
7463 }
74531fed 7464
722247f1 7465 return r;
74531fed
PA
7466}
7467
7468/* Push a fully parsed stop reply in the stop reply queue. Since we
7469 know that we now have at least one queued event left to pass to the
7470 core side, tell the event loop to get back to target_wait soon. */
7471
6b8edb51
PA
7472void
7473remote_target::push_stop_reply (struct stop_reply *new_event)
74531fed 7474{
6b8edb51 7475 remote_state *rs = get_remote_state ();
953edf2b 7476 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
74531fed 7477
722247f1 7478 if (notif_debug)
6cb06a8c
TT
7479 gdb_printf (gdb_stdlog,
7480 "notif: push 'Stop' %s to queue %d\n",
7481 new_event->ptid.to_string ().c_str (),
7482 int (rs->stop_reply_queue.size ()));
74531fed 7483
4f626cad
AB
7484 /* Mark the pending event queue only if async mode is currently enabled.
7485 If async mode is not currently enabled, then, if it later becomes
7486 enabled, and there are events in this queue, we will mark the event
7487 token at that point, see remote_target::async. */
7488 if (target_is_async_p ())
7489 mark_async_event_handler (rs->remote_async_inferior_event_token);
74531fed
PA
7490}
7491
7492/* Returns true if we have a stop reply for PTID. */
7493
6b8edb51
PA
7494int
7495remote_target::peek_stop_reply (ptid_t ptid)
74531fed 7496{
6b8edb51 7497 remote_state *rs = get_remote_state ();
953edf2b
TT
7498 for (auto &event : rs->stop_reply_queue)
7499 if (ptid == event->ptid
183be222 7500 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
953edf2b
TT
7501 return 1;
7502 return 0;
74531fed
PA
7503}
7504
26d56a93
SL
7505/* Helper for remote_parse_stop_reply. Return nonzero if the substring
7506 starting with P and ending with PEND matches PREFIX. */
7507
7508static int
7509strprefix (const char *p, const char *pend, const char *prefix)
7510{
7511 for ( ; p < pend; p++, prefix++)
7512 if (*p != *prefix)
7513 return 0;
7514 return *prefix == '\0';
7515}
7516
74531fed
PA
7517/* Parse the stop reply in BUF. Either the function succeeds, and the
7518 result is stored in EVENT, or throws an error. */
7519
6b8edb51 7520void
bb277751 7521remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
74531fed 7522{
5cd63fda 7523 remote_arch_state *rsa = NULL;
74531fed 7524 ULONGEST addr;
256642e8 7525 const char *p;
94585166 7526 int skipregs = 0;
74531fed
PA
7527
7528 event->ptid = null_ptid;
bcc75809 7529 event->rs = get_remote_state ();
183be222 7530 event->ws.set_ignore ();
f7e6eed5 7531 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
32603266 7532 event->regcache.clear ();
dc146f7c 7533 event->core = -1;
74531fed
PA
7534
7535 switch (buf[0])
7536 {
7537 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
7538 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7539 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7540 ss = signal number
7541 n... = register number
7542 r... = register contents
7543 */
7544
7545 p = &buf[3]; /* after Txx */
7546 while (*p)
7547 {
256642e8 7548 const char *p1;
cea39f65 7549 int fieldsize;
43ff13b4 7550
1f10ba14
PA
7551 p1 = strchr (p, ':');
7552 if (p1 == NULL)
7553 error (_("Malformed packet(a) (missing colon): %s\n\
7554Packet: '%s'\n"),
7555 p, buf);
7556 if (p == p1)
7557 error (_("Malformed packet(a) (missing register number): %s\n\
7558Packet: '%s'\n"),
7559 p, buf);
3c3bea1c 7560
1f10ba14
PA
7561 /* Some "registers" are actually extended stop information.
7562 Note if you're adding a new entry here: GDB 7.9 and
7563 earlier assume that all register "numbers" that start
7564 with an hex digit are real register numbers. Make sure
7565 the server only sends such a packet if it knows the
7566 client understands it. */
c8e38a49 7567
26d56a93 7568 if (strprefix (p, p1, "thread"))
1f10ba14 7569 event->ptid = read_ptid (++p1, &p);
82075af2
JS
7570 else if (strprefix (p, p1, "syscall_entry"))
7571 {
7572 ULONGEST sysno;
7573
82075af2 7574 p = unpack_varlen_hex (++p1, &sysno);
183be222 7575 event->ws.set_syscall_entry ((int) sysno);
82075af2
JS
7576 }
7577 else if (strprefix (p, p1, "syscall_return"))
7578 {
7579 ULONGEST sysno;
7580
82075af2 7581 p = unpack_varlen_hex (++p1, &sysno);
183be222 7582 event->ws.set_syscall_return ((int) sysno);
82075af2 7583 }
26d56a93
SL
7584 else if (strprefix (p, p1, "watch")
7585 || strprefix (p, p1, "rwatch")
7586 || strprefix (p, p1, "awatch"))
cea39f65 7587 {
f7e6eed5 7588 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
7589 p = unpack_varlen_hex (++p1, &addr);
7590 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 7591 }
26d56a93 7592 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
7593 {
7594 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7595
7596 /* Make sure the stub doesn't forget to indicate support
7597 with qSupported. */
7598 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7599 error (_("Unexpected swbreak stop reason"));
7600
7601 /* The value part is documented as "must be empty",
7602 though we ignore it, in case we ever decide to make
7603 use of it in a backward compatible way. */
8424cc97 7604 p = strchrnul (p1 + 1, ';');
f7e6eed5 7605 }
26d56a93 7606 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
7607 {
7608 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7609
7610 /* Make sure the stub doesn't forget to indicate support
7611 with qSupported. */
7612 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7613 error (_("Unexpected hwbreak stop reason"));
7614
7615 /* See above. */
8424cc97 7616 p = strchrnul (p1 + 1, ';');
f7e6eed5 7617 }
26d56a93 7618 else if (strprefix (p, p1, "library"))
cea39f65 7619 {
183be222 7620 event->ws.set_loaded ();
8424cc97 7621 p = strchrnul (p1 + 1, ';');
1f10ba14 7622 }
26d56a93 7623 else if (strprefix (p, p1, "replaylog"))
1f10ba14 7624 {
183be222 7625 event->ws.set_no_history ();
1f10ba14
PA
7626 /* p1 will indicate "begin" or "end", but it makes
7627 no difference for now, so ignore it. */
8424cc97 7628 p = strchrnul (p1 + 1, ';');
1f10ba14 7629 }
26d56a93 7630 else if (strprefix (p, p1, "core"))
1f10ba14
PA
7631 {
7632 ULONGEST c;
a744cf53 7633
1f10ba14
PA
7634 p = unpack_varlen_hex (++p1, &c);
7635 event->core = c;
cea39f65 7636 }
26d56a93 7637 else if (strprefix (p, p1, "fork"))
183be222 7638 event->ws.set_forked (read_ptid (++p1, &p));
26d56a93 7639 else if (strprefix (p, p1, "vfork"))
183be222 7640 event->ws.set_vforked (read_ptid (++p1, &p));
26d56a93 7641 else if (strprefix (p, p1, "vforkdone"))
c269dbdb 7642 {
183be222 7643 event->ws.set_vfork_done ();
8424cc97 7644 p = strchrnul (p1 + 1, ';');
c269dbdb 7645 }
6ab24463 7646 else if (strprefix (p, p1, "exec"))
94585166
DB
7647 {
7648 ULONGEST ignored;
94585166
DB
7649 int pathlen;
7650
7651 /* Determine the length of the execd pathname. */
7652 p = unpack_varlen_hex (++p1, &ignored);
7653 pathlen = (p - p1) / 2;
7654
7655 /* Save the pathname for event reporting and for
7656 the next run command. */
183be222 7657 gdb::unique_xmalloc_ptr<char> pathname
c6321f19
TT
7658 ((char *) xmalloc (pathlen + 1));
7659 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
183be222 7660 pathname.get ()[pathlen] = '\0';
94585166
DB
7661
7662 /* This is freed during event handling. */
183be222 7663 event->ws.set_execd (std::move (pathname));
94585166
DB
7664
7665 /* Skip the registers included in this packet, since
7666 they may be for an architecture different from the
7667 one used by the original program. */
7668 skipregs = 1;
7669 }
65706a29
PA
7670 else if (strprefix (p, p1, "create"))
7671 {
183be222 7672 event->ws.set_thread_created ();
8424cc97 7673 p = strchrnul (p1 + 1, ';');
65706a29 7674 }
cea39f65
MS
7675 else
7676 {
1f10ba14 7677 ULONGEST pnum;
256642e8 7678 const char *p_temp;
1f10ba14 7679
94585166
DB
7680 if (skipregs)
7681 {
8424cc97 7682 p = strchrnul (p1 + 1, ';');
94585166
DB
7683 p++;
7684 continue;
7685 }
7686
1f10ba14
PA
7687 /* Maybe a real ``P'' register number. */
7688 p_temp = unpack_varlen_hex (p, &pnum);
7689 /* If the first invalid character is the colon, we got a
7690 register number. Otherwise, it's an unknown stop
7691 reason. */
7692 if (p_temp == p1)
7693 {
5cd63fda
PA
7694 /* If we haven't parsed the event's thread yet, find
7695 it now, in order to find the architecture of the
7696 reported expedited registers. */
7697 if (event->ptid == null_ptid)
7698 {
24ed6739
AB
7699 /* If there is no thread-id information then leave
7700 the event->ptid as null_ptid. Later in
7701 process_stop_reply we will pick a suitable
7702 thread. */
5cd63fda
PA
7703 const char *thr = strstr (p1 + 1, ";thread:");
7704 if (thr != NULL)
7705 event->ptid = read_ptid (thr + strlen (";thread:"),
7706 NULL);
5cd63fda
PA
7707 }
7708
7709 if (rsa == NULL)
7710 {
5b6d1e4f
PA
7711 inferior *inf
7712 = (event->ptid == null_ptid
7713 ? NULL
7714 : find_inferior_ptid (this, event->ptid));
5cd63fda
PA
7715 /* If this is the first time we learn anything
7716 about this process, skip the registers
7717 included in this packet, since we don't yet
7718 know which architecture to use to parse them.
7719 We'll determine the architecture later when
7720 we process the stop reply and retrieve the
7721 target description, via
7722 remote_notice_new_inferior ->
7723 post_create_inferior. */
7724 if (inf == NULL)
7725 {
7726 p = strchrnul (p1 + 1, ';');
7727 p++;
7728 continue;
7729 }
7730
7731 event->arch = inf->gdbarch;
9d6eea31 7732 rsa = event->rs->get_remote_arch_state (event->arch);
5cd63fda
PA
7733 }
7734
7735 packet_reg *reg
7736 = packet_reg_from_pnum (event->arch, rsa, pnum);
1f10ba14 7737 cached_reg_t cached_reg;
43ff13b4 7738
1f10ba14
PA
7739 if (reg == NULL)
7740 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 7741Packet: '%s'\n"),
1f10ba14 7742 hex_string (pnum), p, buf);
c8e38a49 7743
1f10ba14 7744 cached_reg.num = reg->regnum;
d1dff226 7745 cached_reg.data = (gdb_byte *)
5cd63fda 7746 xmalloc (register_size (event->arch, reg->regnum));
4100683b 7747
1f10ba14
PA
7748 p = p1 + 1;
7749 fieldsize = hex2bin (p, cached_reg.data,
5cd63fda 7750 register_size (event->arch, reg->regnum));
1f10ba14 7751 p += 2 * fieldsize;
5cd63fda 7752 if (fieldsize < register_size (event->arch, reg->regnum))
1f10ba14 7753 warning (_("Remote reply is too short: %s"), buf);
74531fed 7754
32603266 7755 event->regcache.push_back (cached_reg);
1f10ba14
PA
7756 }
7757 else
7758 {
7759 /* Not a number. Silently skip unknown optional
7760 info. */
8424cc97 7761 p = strchrnul (p1 + 1, ';');
1f10ba14 7762 }
cea39f65 7763 }
c8e38a49 7764
cea39f65
MS
7765 if (*p != ';')
7766 error (_("Remote register badly formatted: %s\nhere: %s"),
7767 buf, p);
7768 ++p;
7769 }
5b5596ff 7770
183be222 7771 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
5b5596ff
PA
7772 break;
7773
c8e38a49
PA
7774 /* fall through */
7775 case 'S': /* Old style status, just signal only. */
3a09da41
PA
7776 {
7777 int sig;
7778
3a09da41
PA
7779 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7780 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
183be222 7781 event->ws.set_stopped ((enum gdb_signal) sig);
3a09da41 7782 else
183be222 7783 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
3a09da41 7784 }
c8e38a49 7785 break;
65706a29
PA
7786 case 'w': /* Thread exited. */
7787 {
65706a29
PA
7788 ULONGEST value;
7789
65706a29 7790 p = unpack_varlen_hex (&buf[1], &value);
183be222 7791 event->ws.set_thread_exited (value);
65706a29
PA
7792 if (*p != ';')
7793 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 7794 event->ptid = read_ptid (++p, NULL);
65706a29
PA
7795 break;
7796 }
c8e38a49
PA
7797 case 'W': /* Target exited. */
7798 case 'X':
7799 {
c8e38a49 7800 ULONGEST value;
82f73884 7801
c8e38a49
PA
7802 /* GDB used to accept only 2 hex chars here. Stubs should
7803 only send more if they detect GDB supports multi-process
7804 support. */
7805 p = unpack_varlen_hex (&buf[1], &value);
82f73884 7806
c8e38a49
PA
7807 if (buf[0] == 'W')
7808 {
7809 /* The remote process exited. */
183be222 7810 event->ws.set_exited (value);
c8e38a49
PA
7811 }
7812 else
7813 {
7814 /* The remote process exited with a signal. */
3a09da41 7815 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
183be222 7816 event->ws.set_signalled ((enum gdb_signal) value);
3a09da41 7817 else
183be222 7818 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
c8e38a49 7819 }
82f73884 7820
e7af6c70
TBA
7821 /* If no process is specified, return null_ptid, and let the
7822 caller figure out the right process to use. */
7823 int pid = 0;
c8e38a49
PA
7824 if (*p == '\0')
7825 ;
7826 else if (*p == ';')
7827 {
7828 p++;
7829
0b24eb2d 7830 if (*p == '\0')
82f73884 7831 ;
61012eef 7832 else if (startswith (p, "process:"))
82f73884 7833 {
c8e38a49 7834 ULONGEST upid;
a744cf53 7835
c8e38a49
PA
7836 p += sizeof ("process:") - 1;
7837 unpack_varlen_hex (p, &upid);
7838 pid = upid;
82f73884
PA
7839 }
7840 else
7841 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 7842 }
c8e38a49
PA
7843 else
7844 error (_("unknown stop reply packet: %s"), buf);
f2907e49 7845 event->ptid = ptid_t (pid);
74531fed
PA
7846 }
7847 break;
f2faf941 7848 case 'N':
183be222 7849 event->ws.set_no_resumed ();
f2faf941
PA
7850 event->ptid = minus_one_ptid;
7851 break;
74531fed 7852 }
74531fed
PA
7853}
7854
722247f1
YQ
7855/* When the stub wants to tell GDB about a new notification reply, it
7856 sends a notification (%Stop, for example). Those can come it at
7857 any time, hence, we have to make sure that any pending
7858 putpkt/getpkt sequence we're making is finished, before querying
7859 the stub for more events with the corresponding ack command
7860 (vStopped, for example). E.g., if we started a vStopped sequence
7861 immediately upon receiving the notification, something like this
7862 could happen:
74531fed
PA
7863
7864 1.1) --> Hg 1
7865 1.2) <-- OK
7866 1.3) --> g
7867 1.4) <-- %Stop
7868 1.5) --> vStopped
7869 1.6) <-- (registers reply to step #1.3)
7870
7871 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7872 query.
7873
796cb314 7874 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
7875 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7876 doing whatever we were doing:
7877
7878 2.1) --> Hg 1
7879 2.2) <-- OK
7880 2.3) --> g
7881 2.4) <-- %Stop
7882 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7883 2.5) <-- (registers reply to step #2.3)
7884
85102364 7885 Eventually after step #2.5, we return to the event loop, which
74531fed
PA
7886 notices there's an event on the
7887 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7888 associated callback --- the function below. At this point, we're
7889 always safe to start a vStopped sequence. :
7890
7891 2.6) --> vStopped
7892 2.7) <-- T05 thread:2
7893 2.8) --> vStopped
7894 2.9) --> OK
7895*/
7896
722247f1 7897void
6b8edb51 7898remote_target::remote_notif_get_pending_events (notif_client *nc)
74531fed
PA
7899{
7900 struct remote_state *rs = get_remote_state ();
74531fed 7901
f48ff2a7 7902 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 7903 {
722247f1 7904 if (notif_debug)
6cb06a8c
TT
7905 gdb_printf (gdb_stdlog,
7906 "notif: process: '%s' ack pending event\n",
7907 nc->name);
74531fed 7908
722247f1 7909 /* acknowledge */
8d64371b
TT
7910 nc->ack (this, nc, rs->buf.data (),
7911 rs->notif_state->pending_event[nc->id]);
f48ff2a7 7912 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
7913
7914 while (1)
7915 {
8d64371b
TT
7916 getpkt (&rs->buf, 0);
7917 if (strcmp (rs->buf.data (), "OK") == 0)
74531fed
PA
7918 break;
7919 else
8d64371b 7920 remote_notif_ack (this, nc, rs->buf.data ());
74531fed
PA
7921 }
7922 }
722247f1
YQ
7923 else
7924 {
7925 if (notif_debug)
6cb06a8c
TT
7926 gdb_printf (gdb_stdlog,
7927 "notif: process: '%s' no pending reply\n",
7928 nc->name);
722247f1 7929 }
74531fed
PA
7930}
7931
6b8edb51
PA
7932/* Wrapper around remote_target::remote_notif_get_pending_events to
7933 avoid having to export the whole remote_target class. */
7934
7935void
7936remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7937{
7938 remote->remote_notif_get_pending_events (nc);
7939}
7940
8f66807b
AB
7941/* Called from process_stop_reply when the stop packet we are responding
7942 to didn't include a process-id or thread-id. STATUS is the stop event
7943 we are responding to.
7944
7945 It is the task of this function to select a suitable thread (or process)
7946 and return its ptid, this is the thread (or process) we will assume the
7947 stop event came from.
7948
7949 In some cases there isn't really any choice about which thread (or
7950 process) is selected, a basic remote with a single process containing a
7951 single thread might choose not to send any process-id or thread-id in
7952 its stop packets, this function will select and return the one and only
7953 thread.
7954
7955 However, if a target supports multiple threads (or processes) and still
7956 doesn't include a thread-id (or process-id) in its stop packet then
7957 first, this is a badly behaving target, and second, we're going to have
7958 to select a thread (or process) at random and use that. This function
7959 will print a warning to the user if it detects that there is the
7960 possibility that GDB is guessing which thread (or process) to
7961 report.
7962
7963 Note that this is called before GDB fetches the updated thread list from the
7964 target. So it's possible for the stop reply to be ambiguous and for GDB to
7965 not realize it. For example, if there's initially one thread, the target
7966 spawns a second thread, and then sends a stop reply without an id that
7967 concerns the first thread. GDB will assume the stop reply is about the
7968 first thread - the only thread it knows about - without printing a warning.
7969 Anyway, if the remote meant for the stop reply to be about the second thread,
7970 then it would be really broken, because GDB doesn't know about that thread
7971 yet. */
74531fed 7972
6b8edb51 7973ptid_t
8f66807b 7974remote_target::select_thread_for_ambiguous_stop_reply
c272a98c 7975 (const target_waitstatus &status)
74531fed 7976{
4351271e
AB
7977 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7978
8f66807b
AB
7979 /* Some stop events apply to all threads in an inferior, while others
7980 only apply to a single thread. */
7981 bool process_wide_stop
c272a98c
SM
7982 = (status.kind () == TARGET_WAITKIND_EXITED
7983 || status.kind () == TARGET_WAITKIND_SIGNALLED);
74531fed 7984
4351271e
AB
7985 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
7986
8f66807b
AB
7987 thread_info *first_resumed_thread = nullptr;
7988 bool ambiguous = false;
74531fed 7989
8f66807b
AB
7990 /* Consider all non-exited threads of the target, find the first resumed
7991 one. */
7992 for (thread_info *thr : all_non_exited_threads (this))
24ed6739 7993 {
8f66807b 7994 remote_thread_info *remote_thr = get_remote_thread_info (thr);
cada5fc9 7995
a6c11cbb 7996 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8f66807b 7997 continue;
24ed6739 7998
8f66807b
AB
7999 if (first_resumed_thread == nullptr)
8000 first_resumed_thread = thr;
8001 else if (!process_wide_stop
8002 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8003 ambiguous = true;
8004 }
8005
b622494e
AB
8006 gdb_assert (first_resumed_thread != nullptr);
8007
4351271e
AB
8008 remote_debug_printf ("first resumed thread is %s",
8009 pid_to_str (first_resumed_thread->ptid).c_str ());
8010 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8011
8f66807b
AB
8012 /* Warn if the remote target is sending ambiguous stop replies. */
8013 if (ambiguous)
8014 {
8015 static bool warned = false;
8016
8017 if (!warned)
8018 {
8019 /* If you are seeing this warning then the remote target has
8020 stopped without specifying a thread-id, but the target
8021 does have multiple threads (or inferiors), and so GDB is
8022 having to guess which thread stopped.
8023
8024 Examples of what might cause this are the target sending
8025 and 'S' stop packet, or a 'T' stop packet and not
8026 including a thread-id.
8027
8028 Additionally, the target might send a 'W' or 'X packet
8029 without including a process-id, when the target has
8030 multiple running inferiors. */
8031 if (process_wide_stop)
8032 warning (_("multi-inferior target stopped without "
8033 "sending a process-id, using first "
8034 "non-exited inferior"));
cada5fc9 8035 else
8f66807b
AB
8036 warning (_("multi-threaded target stopped without "
8037 "sending a thread-id, using first "
8038 "non-exited thread"));
8039 warned = true;
24ed6739 8040 }
24ed6739 8041 }
74531fed 8042
8f66807b
AB
8043 /* If this is a stop for all threads then don't use a particular threads
8044 ptid, instead create a new ptid where only the pid field is set. */
8045 if (process_wide_stop)
8046 return ptid_t (first_resumed_thread->ptid.pid ());
8047 else
8048 return first_resumed_thread->ptid;
8049}
8050
8051/* Called when it is decided that STOP_REPLY holds the info of the
8052 event that is to be returned to the core. This function always
8053 destroys STOP_REPLY. */
8054
8055ptid_t
8056remote_target::process_stop_reply (struct stop_reply *stop_reply,
8057 struct target_waitstatus *status)
8058{
8059 *status = stop_reply->ws;
8060 ptid_t ptid = stop_reply->ptid;
8061
8062 /* If no thread/process was reported by the stub then select a suitable
8063 thread/process. */
8064 if (ptid == null_ptid)
c272a98c 8065 ptid = select_thread_for_ambiguous_stop_reply (*status);
8f66807b
AB
8066 gdb_assert (ptid != null_ptid);
8067
183be222
SM
8068 if (status->kind () != TARGET_WAITKIND_EXITED
8069 && status->kind () != TARGET_WAITKIND_SIGNALLED
8070 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
74531fed 8071 {
5f3563ea 8072 /* Expedited registers. */
32603266 8073 if (!stop_reply->regcache.empty ())
5f3563ea 8074 {
217f1f79 8075 struct regcache *regcache
5b6d1e4f 8076 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
5f3563ea 8077
32603266
TT
8078 for (cached_reg_t &reg : stop_reply->regcache)
8079 {
8080 regcache->raw_supply (reg.num, reg.data);
8081 xfree (reg.data);
8082 }
d1dff226 8083
32603266 8084 stop_reply->regcache.clear ();
5f3563ea 8085 }
74531fed 8086
8a82de58 8087 remote_notice_new_inferior (ptid, false);
5b6d1e4f 8088 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
799a2abe
PA
8089 remote_thr->core = stop_reply->core;
8090 remote_thr->stop_reason = stop_reply->stop_reason;
8091 remote_thr->watch_data_address = stop_reply->watch_data_address;
c9d22089
SM
8092
8093 if (target_is_non_stop_p ())
8094 {
8095 /* If the target works in non-stop mode, a stop-reply indicates that
8096 only this thread stopped. */
8097 remote_thr->set_not_resumed ();
8098 }
8099 else
8100 {
8101 /* If the target works in all-stop mode, a stop-reply indicates that
8102 all the target's threads stopped. */
8103 for (thread_info *tp : all_non_exited_threads (this))
8104 get_remote_thread_info (tp)->set_not_resumed ();
8105 }
74531fed
PA
8106 }
8107
32603266 8108 delete stop_reply;
74531fed
PA
8109 return ptid;
8110}
8111
8112/* The non-stop mode version of target_wait. */
8113
6b8edb51 8114ptid_t
b60cea74
TT
8115remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8116 target_wait_flags options)
74531fed
PA
8117{
8118 struct remote_state *rs = get_remote_state ();
74531fed
PA
8119 struct stop_reply *stop_reply;
8120 int ret;
fee9eda9 8121 int is_notif = 0;
74531fed
PA
8122
8123 /* If in non-stop mode, get out of getpkt even if a
8124 notification is received. */
8125
8d64371b 8126 ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
74531fed
PA
8127 while (1)
8128 {
fee9eda9 8129 if (ret != -1 && !is_notif)
74531fed
PA
8130 switch (rs->buf[0])
8131 {
8132 case 'E': /* Error of some sort. */
8133 /* We're out of sync with the target now. Did it continue
8134 or not? We can't tell which thread it was in non-stop,
8135 so just ignore this. */
8d64371b 8136 warning (_("Remote failure reply: %s"), rs->buf.data ());
74531fed
PA
8137 break;
8138 case 'O': /* Console output. */
8d64371b 8139 remote_console_output (&rs->buf[1]);
74531fed
PA
8140 break;
8141 default:
8d64371b 8142 warning (_("Invalid remote reply: %s"), rs->buf.data ());
74531fed
PA
8143 break;
8144 }
8145
8146 /* Acknowledge a pending stop reply that may have arrived in the
8147 mean time. */
f48ff2a7 8148 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 8149 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
8150
8151 /* If indeed we noticed a stop reply, we're done. */
8152 stop_reply = queued_stop_reply (ptid);
8153 if (stop_reply != NULL)
8154 return process_stop_reply (stop_reply, status);
8155
47608cb1 8156 /* Still no event. If we're just polling for an event, then
74531fed 8157 return to the event loop. */
47608cb1 8158 if (options & TARGET_WNOHANG)
74531fed 8159 {
183be222 8160 status->set_ignore ();
74531fed
PA
8161 return minus_one_ptid;
8162 }
8163
47608cb1 8164 /* Otherwise do a blocking wait. */
8d64371b 8165 ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
74531fed
PA
8166 }
8167}
8168
31ba933e
PA
8169/* Return the first resumed thread. */
8170
8171static ptid_t
5b6d1e4f 8172first_remote_resumed_thread (remote_target *target)
31ba933e 8173{
5b6d1e4f 8174 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
7846f3aa 8175 if (tp->resumed ())
31ba933e
PA
8176 return tp->ptid;
8177 return null_ptid;
8178}
8179
74531fed
PA
8180/* Wait until the remote machine stops, then return, storing status in
8181 STATUS just as `wait' would. */
8182
6b8edb51 8183ptid_t
b60cea74
TT
8184remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8185 target_wait_flags options)
74531fed
PA
8186{
8187 struct remote_state *rs = get_remote_state ();
74531fed 8188 ptid_t event_ptid = null_ptid;
cea39f65 8189 char *buf;
74531fed
PA
8190 struct stop_reply *stop_reply;
8191
47608cb1
PA
8192 again:
8193
183be222 8194 status->set_ignore ();
74531fed
PA
8195
8196 stop_reply = queued_stop_reply (ptid);
8197 if (stop_reply != NULL)
4f626cad
AB
8198 {
8199 /* None of the paths that push a stop reply onto the queue should
8200 have set the waiting_for_stop_reply flag. */
8201 gdb_assert (!rs->waiting_for_stop_reply);
8202 event_ptid = process_stop_reply (stop_reply, status);
8203 }
74531fed
PA
8204 else
8205 {
567420d1 8206 int forever = ((options & TARGET_WNOHANG) == 0
6b8edb51 8207 && rs->wait_forever_enabled_p);
567420d1
PA
8208
8209 if (!rs->waiting_for_stop_reply)
8210 {
183be222 8211 status->set_no_resumed ();
567420d1
PA
8212 return minus_one_ptid;
8213 }
74531fed 8214
74531fed
PA
8215 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8216 _never_ wait for ever -> test on target_is_async_p().
8217 However, before we do that we need to ensure that the caller
8218 knows how to take the target into/out of async mode. */
4f626cad
AB
8219 int is_notif;
8220 int ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
722247f1
YQ
8221
8222 /* GDB gets a notification. Return to core as this event is
8223 not interesting. */
8224 if (ret != -1 && is_notif)
8225 return minus_one_ptid;
567420d1
PA
8226
8227 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8228 return minus_one_ptid;
74531fed 8229
4f626cad 8230 buf = rs->buf.data ();
74531fed 8231
4f626cad
AB
8232 /* Assume that the target has acknowledged Ctrl-C unless we receive
8233 an 'F' or 'O' packet. */
8234 if (buf[0] != 'F' && buf[0] != 'O')
8235 rs->ctrlc_pending_p = 0;
3a29589a 8236
4f626cad
AB
8237 switch (buf[0])
8238 {
8239 case 'E': /* Error of some sort. */
8240 /* We're out of sync with the target now. Did it continue or
8241 not? Not is more likely, so report a stop. */
8242 rs->waiting_for_stop_reply = 0;
29090fb6 8243
4f626cad
AB
8244 warning (_("Remote failure reply: %s"), buf);
8245 status->set_stopped (GDB_SIGNAL_0);
8246 break;
8247 case 'F': /* File-I/O request. */
8248 /* GDB may access the inferior memory while handling the File-I/O
8249 request, but we don't want GDB accessing memory while waiting
8250 for a stop reply. See the comments in putpkt_binary. Set
8251 waiting_for_stop_reply to 0 temporarily. */
8252 rs->waiting_for_stop_reply = 0;
8253 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8254 rs->ctrlc_pending_p = 0;
8255 /* GDB handled the File-I/O request, and the target is running
8256 again. Keep waiting for events. */
8257 rs->waiting_for_stop_reply = 1;
8258 break;
8259 case 'N': case 'T': case 'S': case 'X': case 'W':
8260 {
8261 /* There is a stop reply to handle. */
8262 rs->waiting_for_stop_reply = 0;
29090fb6 8263
4f626cad
AB
8264 stop_reply
8265 = (struct stop_reply *) remote_notif_parse (this,
8266 &notif_client_stop,
8267 rs->buf.data ());
74531fed 8268
4f626cad
AB
8269 event_ptid = process_stop_reply (stop_reply, status);
8270 break;
8271 }
8272 case 'O': /* Console output. */
8273 remote_console_output (buf + 1);
8274 break;
8275 case '\0':
8276 if (rs->last_sent_signal != GDB_SIGNAL_0)
8277 {
8278 /* Zero length reply means that we tried 'S' or 'C' and the
8279 remote system doesn't support it. */
8280 target_terminal::ours_for_output ();
6cb06a8c 8281 gdb_printf
4f626cad
AB
8282 ("Can't send signals to this remote system. %s not sent.\n",
8283 gdb_signal_to_name (rs->last_sent_signal));
8284 rs->last_sent_signal = GDB_SIGNAL_0;
8285 target_terminal::inferior ();
8286
8287 strcpy (buf, rs->last_sent_step ? "s" : "c");
8288 putpkt (buf);
8289 break;
8290 }
8291 /* fallthrough */
8292 default:
8293 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 8294 break;
43ff13b4
JM
8295 }
8296 }
c8e38a49 8297
183be222 8298 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
f2faf941 8299 return minus_one_ptid;
183be222 8300 else if (status->kind () == TARGET_WAITKIND_IGNORE)
47608cb1
PA
8301 {
8302 /* Nothing interesting happened. If we're doing a non-blocking
8303 poll, we're done. Otherwise, go back to waiting. */
8304 if (options & TARGET_WNOHANG)
8305 return minus_one_ptid;
8306 else
8307 goto again;
8308 }
183be222
SM
8309 else if (status->kind () != TARGET_WAITKIND_EXITED
8310 && status->kind () != TARGET_WAITKIND_SIGNALLED)
82f73884 8311 {
d7e15655 8312 if (event_ptid != null_ptid)
47f8a51d 8313 record_currthread (rs, event_ptid);
82f73884 8314 else
5b6d1e4f 8315 event_ptid = first_remote_resumed_thread (this);
43ff13b4 8316 }
74531fed 8317 else
e7af6c70
TBA
8318 {
8319 /* A process exit. Invalidate our notion of current thread. */
8320 record_currthread (rs, minus_one_ptid);
8321 /* It's possible that the packet did not include a pid. */
8322 if (event_ptid == null_ptid)
5b6d1e4f 8323 event_ptid = first_remote_resumed_thread (this);
e7af6c70
TBA
8324 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8325 if (event_ptid == null_ptid)
8326 event_ptid = magic_null_ptid;
8327 }
79d7f229 8328
82f73884 8329 return event_ptid;
43ff13b4
JM
8330}
8331
74531fed
PA
8332/* Wait until the remote machine stops, then return, storing status in
8333 STATUS just as `wait' would. */
8334
f6ac5f3d 8335ptid_t
b60cea74
TT
8336remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8337 target_wait_flags options)
c8e38a49 8338{
2189c312
SM
8339 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8340
baa8575b
SM
8341 remote_state *rs = get_remote_state ();
8342
8343 /* Start by clearing the flag that asks for our wait method to be called,
8d34471f
AB
8344 we'll mark it again at the end if needed. If the target is not in
8345 async mode then the async token should not be marked. */
baa8575b
SM
8346 if (target_is_async_p ())
8347 clear_async_event_handler (rs->remote_async_inferior_event_token);
8d34471f
AB
8348 else
8349 gdb_assert (!async_event_handler_marked
8350 (rs->remote_async_inferior_event_token));
baa8575b 8351
c8e38a49
PA
8352 ptid_t event_ptid;
8353
6efcd9a8 8354 if (target_is_non_stop_p ())
6b8edb51 8355 event_ptid = wait_ns (ptid, status, options);
74531fed 8356 else
6b8edb51 8357 event_ptid = wait_as (ptid, status, options);
c8e38a49 8358
d9d41e78 8359 if (target_is_async_p ())
c8e38a49 8360 {
baa8575b
SM
8361 /* If there are events left in the queue, or unacknowledged
8362 notifications, then tell the event loop to call us again. */
8363 if (!rs->stop_reply_queue.empty ()
8364 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
6b8edb51 8365 mark_async_event_handler (rs->remote_async_inferior_event_token);
c8e38a49 8366 }
c8e38a49
PA
8367
8368 return event_ptid;
8369}
8370
74ca34ce 8371/* Fetch a single register using a 'p' packet. */
c906108c 8372
6b8edb51
PA
8373int
8374remote_target::fetch_register_using_p (struct regcache *regcache,
8375 packet_reg *reg)
b96ec7ac 8376{
ac7936df 8377 struct gdbarch *gdbarch = regcache->arch ();
b96ec7ac 8378 struct remote_state *rs = get_remote_state ();
2e9f7625 8379 char *buf, *p;
9890e433 8380 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
b96ec7ac
AC
8381 int i;
8382
4082afcc 8383 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
8384 return 0;
8385
8386 if (reg->pnum == -1)
8387 return 0;
8388
8d64371b 8389 p = rs->buf.data ();
fcad0fa4 8390 *p++ = 'p';
74ca34ce 8391 p += hexnumstr (p, reg->pnum);
fcad0fa4 8392 *p++ = '\0';
1f4437a4 8393 putpkt (rs->buf);
8d64371b 8394 getpkt (&rs->buf, 0);
3f9a994c 8395
8d64371b 8396 buf = rs->buf.data ();
2e9f7625 8397
8d64371b 8398 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_p]))
74ca34ce
DJ
8399 {
8400 case PACKET_OK:
8401 break;
8402 case PACKET_UNKNOWN:
8403 return 0;
8404 case PACKET_ERROR:
27a9c0bf 8405 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
ac7936df 8406 gdbarch_register_name (regcache->arch (),
27a9c0bf
MS
8407 reg->regnum),
8408 buf);
74ca34ce 8409 }
3f9a994c
JB
8410
8411 /* If this register is unfetchable, tell the regcache. */
8412 if (buf[0] == 'x')
8480adf2 8413 {
73e1c03f 8414 regcache->raw_supply (reg->regnum, NULL);
8480adf2 8415 return 1;
b96ec7ac 8416 }
b96ec7ac 8417
3f9a994c
JB
8418 /* Otherwise, parse and supply the value. */
8419 p = buf;
8420 i = 0;
8421 while (p[0] != 0)
8422 {
8423 if (p[1] == 0)
74ca34ce 8424 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
8425
8426 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8427 p += 2;
8428 }
73e1c03f 8429 regcache->raw_supply (reg->regnum, regp);
3f9a994c 8430 return 1;
b96ec7ac
AC
8431}
8432
74ca34ce
DJ
8433/* Fetch the registers included in the target's 'g' packet. */
8434
6b8edb51
PA
8435int
8436remote_target::send_g_packet ()
c906108c 8437{
d01949b6 8438 struct remote_state *rs = get_remote_state ();
cea39f65 8439 int buf_len;
c906108c 8440
8d64371b 8441 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
b75abf5b 8442 putpkt (rs->buf);
8d64371b 8443 getpkt (&rs->buf, 0);
b75abf5b
AK
8444 if (packet_check_result (rs->buf) == PACKET_ERROR)
8445 error (_("Could not read registers; remote failure reply '%s'"),
dda83cd7 8446 rs->buf.data ());
c906108c 8447
29709017
DJ
8448 /* We can get out of synch in various cases. If the first character
8449 in the buffer is not a hex character, assume that has happened
8450 and try to fetch another packet to read. */
8451 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8452 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8453 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8454 && rs->buf[0] != 'x') /* New: unavailable register value. */
8455 {
2189c312 8456 remote_debug_printf ("Bad register packet; fetching a new packet");
8d64371b 8457 getpkt (&rs->buf, 0);
29709017
DJ
8458 }
8459
8d64371b 8460 buf_len = strlen (rs->buf.data ());
74ca34ce
DJ
8461
8462 /* Sanity check the received packet. */
8463 if (buf_len % 2 != 0)
8d64371b 8464 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
29709017
DJ
8465
8466 return buf_len / 2;
8467}
8468
6b8edb51
PA
8469void
8470remote_target::process_g_packet (struct regcache *regcache)
29709017 8471{
ac7936df 8472 struct gdbarch *gdbarch = regcache->arch ();
29709017 8473 struct remote_state *rs = get_remote_state ();
9d6eea31 8474 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
29709017
DJ
8475 int i, buf_len;
8476 char *p;
8477 char *regs;
8478
8d64371b 8479 buf_len = strlen (rs->buf.data ());
29709017
DJ
8480
8481 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce 8482 if (buf_len > 2 * rsa->sizeof_g_packet)
fc809827 8483 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8d64371b
TT
8484 "bytes): %s"),
8485 rsa->sizeof_g_packet, buf_len / 2,
8486 rs->buf.data ());
74ca34ce
DJ
8487
8488 /* Save the size of the packet sent to us by the target. It is used
8489 as a heuristic when determining the max size of packets that the
8490 target can safely receive. */
8491 if (rsa->actual_register_packet_size == 0)
8492 rsa->actual_register_packet_size = buf_len;
8493
8494 /* If this is smaller than we guessed the 'g' packet would be,
8495 update our records. A 'g' reply that doesn't include a register's
8496 value implies either that the register is not available, or that
8497 the 'p' packet must be used. */
8498 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 8499 {
9dc193c3 8500 long sizeof_g_packet = buf_len / 2;
74ca34ce 8501
4a22f64d 8502 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 8503 {
9dc193c3
LF
8504 long offset = rsa->regs[i].offset;
8505 long reg_size = register_size (gdbarch, i);
8506
74ca34ce
DJ
8507 if (rsa->regs[i].pnum == -1)
8508 continue;
8509
9dc193c3 8510 if (offset >= sizeof_g_packet)
74ca34ce 8511 rsa->regs[i].in_g_packet = 0;
9dc193c3
LF
8512 else if (offset + reg_size > sizeof_g_packet)
8513 error (_("Truncated register %d in remote 'g' packet"), i);
b96ec7ac 8514 else
74ca34ce 8515 rsa->regs[i].in_g_packet = 1;
b96ec7ac 8516 }
9dc193c3
LF
8517
8518 /* Looks valid enough, we can assume this is the correct length
dda83cd7
SM
8519 for a 'g' packet. It's important not to adjust
8520 rsa->sizeof_g_packet if we have truncated registers otherwise
8521 this "if" won't be run the next time the method is called
8522 with a packet of the same size and one of the internal errors
8523 below will trigger instead. */
9dc193c3 8524 rsa->sizeof_g_packet = sizeof_g_packet;
74ca34ce 8525 }
b323314b 8526
224c3ddb 8527 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
8528
8529 /* Unimplemented registers read as all bits zero. */
ea9c271d 8530 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 8531
c906108c
SS
8532 /* Reply describes registers byte by byte, each byte encoded as two
8533 hex characters. Suck them all up, then supply them to the
8534 register cacheing/storage mechanism. */
8535
8d64371b 8536 p = rs->buf.data ();
ea9c271d 8537 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 8538 {
74ca34ce
DJ
8539 if (p[0] == 0 || p[1] == 0)
8540 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8541 internal_error (__FILE__, __LINE__,
9b20d036 8542 _("unexpected end of 'g' packet reply"));
74ca34ce 8543
c906108c 8544 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 8545 regs[i] = 0; /* 'x' */
c906108c
SS
8546 else
8547 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8548 p += 2;
8549 }
8550
a744cf53
MS
8551 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8552 {
8553 struct packet_reg *r = &rsa->regs[i];
9dc193c3 8554 long reg_size = register_size (gdbarch, i);
a744cf53
MS
8555
8556 if (r->in_g_packet)
8557 {
8d64371b 8558 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
a744cf53
MS
8559 /* This shouldn't happen - we adjusted in_g_packet above. */
8560 internal_error (__FILE__, __LINE__,
9b20d036 8561 _("unexpected end of 'g' packet reply"));
a744cf53
MS
8562 else if (rs->buf[r->offset * 2] == 'x')
8563 {
8d64371b 8564 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
a744cf53
MS
8565 /* The register isn't available, mark it as such (at
8566 the same time setting the value to zero). */
73e1c03f 8567 regcache->raw_supply (r->regnum, NULL);
a744cf53
MS
8568 }
8569 else
73e1c03f 8570 regcache->raw_supply (r->regnum, regs + r->offset);
a744cf53
MS
8571 }
8572 }
c906108c
SS
8573}
8574
6b8edb51
PA
8575void
8576remote_target::fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
8577{
8578 send_g_packet ();
56be3814 8579 process_g_packet (regcache);
29709017
DJ
8580}
8581
e6e4e701
PA
8582/* Make the remote selected traceframe match GDB's selected
8583 traceframe. */
8584
6b8edb51
PA
8585void
8586remote_target::set_remote_traceframe ()
e6e4e701
PA
8587{
8588 int newnum;
262e1174 8589 struct remote_state *rs = get_remote_state ();
e6e4e701 8590
262e1174 8591 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
8592 return;
8593
8594 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 8595 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
8596
8597 newnum = target_trace_find (tfind_number,
8598 get_traceframe_number (), 0, 0, NULL);
8599
8600 /* Should not happen. If it does, all bets are off. */
8601 if (newnum != get_traceframe_number ())
8602 warning (_("could not set remote traceframe"));
8603}
8604
f6ac5f3d
PA
8605void
8606remote_target::fetch_registers (struct regcache *regcache, int regnum)
74ca34ce 8607{
ac7936df 8608 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8609 struct remote_state *rs = get_remote_state ();
8610 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8611 int i;
8612
e6e4e701 8613 set_remote_traceframe ();
222312d3 8614 set_general_thread (regcache->ptid ());
74ca34ce
DJ
8615
8616 if (regnum >= 0)
8617 {
5cd63fda 8618 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8619
74ca34ce
DJ
8620 gdb_assert (reg != NULL);
8621
8622 /* If this register might be in the 'g' packet, try that first -
8623 we are likely to read more than one register. If this is the
8624 first 'g' packet, we might be overly optimistic about its
8625 contents, so fall back to 'p'. */
8626 if (reg->in_g_packet)
8627 {
56be3814 8628 fetch_registers_using_g (regcache);
74ca34ce
DJ
8629 if (reg->in_g_packet)
8630 return;
8631 }
8632
56be3814 8633 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
8634 return;
8635
8636 /* This register is not available. */
73e1c03f 8637 regcache->raw_supply (reg->regnum, NULL);
74ca34ce
DJ
8638
8639 return;
8640 }
8641
56be3814 8642 fetch_registers_using_g (regcache);
74ca34ce 8643
5cd63fda 8644 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8645 if (!rsa->regs[i].in_g_packet)
56be3814 8646 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
8647 {
8648 /* This register is not available. */
73e1c03f 8649 regcache->raw_supply (i, NULL);
74ca34ce
DJ
8650 }
8651}
8652
c906108c
SS
8653/* Prepare to store registers. Since we may send them all (using a
8654 'G' request), we have to read out the ones we don't want to change
8655 first. */
8656
f6ac5f3d
PA
8657void
8658remote_target::prepare_to_store (struct regcache *regcache)
c906108c 8659{
9d6eea31
PA
8660 struct remote_state *rs = get_remote_state ();
8661 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cf0e1e0d 8662 int i;
cf0e1e0d 8663
c906108c 8664 /* Make sure the entire registers array is valid. */
4082afcc 8665 switch (packet_support (PACKET_P))
5a2468f5
JM
8666 {
8667 case PACKET_DISABLE:
8668 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 8669 /* Make sure all the necessary registers are cached. */
ac7936df 8670 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
ea9c271d 8671 if (rsa->regs[i].in_g_packet)
0b47d985 8672 regcache->raw_update (rsa->regs[i].regnum);
5a2468f5
JM
8673 break;
8674 case PACKET_ENABLE:
8675 break;
8676 }
8677}
8678
ad10f812 8679/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 8680 packet was not recognized. */
5a2468f5 8681
6b8edb51
PA
8682int
8683remote_target::store_register_using_P (const struct regcache *regcache,
8684 packet_reg *reg)
5a2468f5 8685{
ac7936df 8686 struct gdbarch *gdbarch = regcache->arch ();
d01949b6 8687 struct remote_state *rs = get_remote_state ();
5a2468f5 8688 /* Try storing a single register. */
8d64371b 8689 char *buf = rs->buf.data ();
9890e433 8690 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
5a2468f5 8691 char *p;
5a2468f5 8692
4082afcc 8693 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
8694 return 0;
8695
8696 if (reg->pnum == -1)
8697 return 0;
8698
ea9c271d 8699 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 8700 p = buf + strlen (buf);
34a79281 8701 regcache->raw_collect (reg->regnum, regp);
4a22f64d 8702 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4 8703 putpkt (rs->buf);
8d64371b 8704 getpkt (&rs->buf, 0);
5a2468f5 8705
74ca34ce
DJ
8706 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8707 {
8708 case PACKET_OK:
8709 return 1;
8710 case PACKET_ERROR:
27a9c0bf 8711 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8d64371b 8712 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
74ca34ce
DJ
8713 case PACKET_UNKNOWN:
8714 return 0;
8715 default:
8716 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8717 }
c906108c
SS
8718}
8719
23860348
MS
8720/* Store register REGNUM, or all registers if REGNUM == -1, from the
8721 contents of the register cache buffer. FIXME: ignores errors. */
c906108c 8722
6b8edb51
PA
8723void
8724remote_target::store_registers_using_G (const struct regcache *regcache)
c906108c 8725{
d01949b6 8726 struct remote_state *rs = get_remote_state ();
9d6eea31 8727 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cfd77fa1 8728 gdb_byte *regs;
c906108c
SS
8729 char *p;
8730
193cb69f
AC
8731 /* Extract all the registers in the regcache copying them into a
8732 local buffer. */
8733 {
b323314b 8734 int i;
a744cf53 8735
224c3ddb 8736 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 8737 memset (regs, 0, rsa->sizeof_g_packet);
ac7936df 8738 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
193cb69f 8739 {
ea9c271d 8740 struct packet_reg *r = &rsa->regs[i];
a744cf53 8741
b323314b 8742 if (r->in_g_packet)
34a79281 8743 regcache->raw_collect (r->regnum, regs + r->offset);
193cb69f
AC
8744 }
8745 }
c906108c
SS
8746
8747 /* Command describes registers byte by byte,
8748 each byte encoded as two hex characters. */
8d64371b 8749 p = rs->buf.data ();
193cb69f 8750 *p++ = 'G';
74ca34ce 8751 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4 8752 putpkt (rs->buf);
8d64371b 8753 getpkt (&rs->buf, 0);
1f4437a4 8754 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf 8755 error (_("Could not write registers; remote failure reply '%s'"),
8d64371b 8756 rs->buf.data ());
c906108c 8757}
74ca34ce
DJ
8758
8759/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8760 of the register cache buffer. FIXME: ignores errors. */
8761
f6ac5f3d
PA
8762void
8763remote_target::store_registers (struct regcache *regcache, int regnum)
74ca34ce 8764{
5cd63fda 8765 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8766 struct remote_state *rs = get_remote_state ();
8767 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8768 int i;
8769
e6e4e701 8770 set_remote_traceframe ();
222312d3 8771 set_general_thread (regcache->ptid ());
74ca34ce
DJ
8772
8773 if (regnum >= 0)
8774 {
5cd63fda 8775 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8776
74ca34ce
DJ
8777 gdb_assert (reg != NULL);
8778
8779 /* Always prefer to store registers using the 'P' packet if
8780 possible; we often change only a small number of registers.
8781 Sometimes we change a larger number; we'd need help from a
8782 higher layer to know to use 'G'. */
56be3814 8783 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
8784 return;
8785
8786 /* For now, don't complain if we have no way to write the
8787 register. GDB loses track of unavailable registers too
8788 easily. Some day, this may be an error. We don't have
0df8b418 8789 any way to read the register, either... */
74ca34ce
DJ
8790 if (!reg->in_g_packet)
8791 return;
8792
56be3814 8793 store_registers_using_G (regcache);
74ca34ce
DJ
8794 return;
8795 }
8796
56be3814 8797 store_registers_using_G (regcache);
74ca34ce 8798
5cd63fda 8799 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8800 if (!rsa->regs[i].in_g_packet)
56be3814 8801 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
8802 /* See above for why we do not issue an error here. */
8803 continue;
8804}
c906108c
SS
8805\f
8806
8807/* Return the number of hex digits in num. */
8808
8809static int
fba45db2 8810hexnumlen (ULONGEST num)
c906108c
SS
8811{
8812 int i;
8813
8814 for (i = 0; num != 0; i++)
8815 num >>= 4;
8816
325fac50 8817 return std::max (i, 1);
c906108c
SS
8818}
8819
2df3850c 8820/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
8821
8822static int
fba45db2 8823hexnumstr (char *buf, ULONGEST num)
c906108c 8824{
c906108c 8825 int len = hexnumlen (num);
a744cf53 8826
2df3850c
JM
8827 return hexnumnstr (buf, num, len);
8828}
8829
c906108c 8830
2df3850c 8831/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 8832
2df3850c 8833static int
fba45db2 8834hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
8835{
8836 int i;
8837
8838 buf[width] = '\0';
8839
8840 for (i = width - 1; i >= 0; i--)
c906108c 8841 {
c5aa993b 8842 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
8843 num >>= 4;
8844 }
8845
2df3850c 8846 return width;
c906108c
SS
8847}
8848
23860348 8849/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
8850
8851static CORE_ADDR
fba45db2 8852remote_address_masked (CORE_ADDR addr)
c906108c 8853{
883b9c6c 8854 unsigned int address_size = remote_address_size;
a744cf53 8855
911c95a5
UW
8856 /* If "remoteaddresssize" was not set, default to target address size. */
8857 if (!address_size)
f5656ead 8858 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
8859
8860 if (address_size > 0
8861 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
8862 {
8863 /* Only create a mask when that mask can safely be constructed
dda83cd7 8864 in a ULONGEST variable. */
c906108c 8865 ULONGEST mask = 1;
a744cf53 8866
911c95a5 8867 mask = (mask << address_size) - 1;
c906108c
SS
8868 addr &= mask;
8869 }
8870 return addr;
8871}
8872
8873/* Determine whether the remote target supports binary downloading.
8874 This is accomplished by sending a no-op memory write of zero length
8875 to the target at the specified address. It does not suffice to send
23860348
MS
8876 the whole packet, since many stubs strip the eighth bit and
8877 subsequently compute a wrong checksum, which causes real havoc with
8878 remote_write_bytes.
7a292a7a 8879
96baa820 8880 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 8881 clean. In cases like this, the user should clear "remote
23860348 8882 X-packet". */
96baa820 8883
6b8edb51
PA
8884void
8885remote_target::check_binary_download (CORE_ADDR addr)
c906108c 8886{
d01949b6 8887 struct remote_state *rs = get_remote_state ();
24b06219 8888
4082afcc 8889 switch (packet_support (PACKET_X))
c906108c 8890 {
96baa820
JM
8891 case PACKET_DISABLE:
8892 break;
8893 case PACKET_ENABLE:
8894 break;
8895 case PACKET_SUPPORT_UNKNOWN:
8896 {
96baa820 8897 char *p;
802188a7 8898
8d64371b 8899 p = rs->buf.data ();
96baa820
JM
8900 *p++ = 'X';
8901 p += hexnumstr (p, (ULONGEST) addr);
8902 *p++ = ',';
8903 p += hexnumstr (p, (ULONGEST) 0);
8904 *p++ = ':';
8905 *p = '\0';
802188a7 8906
8d64371b
TT
8907 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
8908 getpkt (&rs->buf, 0);
c906108c 8909
2e9f7625 8910 if (rs->buf[0] == '\0')
96baa820 8911 {
2189c312 8912 remote_debug_printf ("binary downloading NOT supported by target");
444abaca 8913 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
8914 }
8915 else
8916 {
2189c312 8917 remote_debug_printf ("binary downloading supported by target");
444abaca 8918 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
8919 }
8920 break;
8921 }
c906108c
SS
8922 }
8923}
8924
124e13d9
SM
8925/* Helper function to resize the payload in order to try to get a good
8926 alignment. We try to write an amount of data such that the next write will
8927 start on an address aligned on REMOTE_ALIGN_WRITES. */
8928
8929static int
8930align_for_efficient_write (int todo, CORE_ADDR memaddr)
8931{
8932 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8933}
8934
c906108c
SS
8935/* Write memory data directly to the remote machine.
8936 This does not inform the data cache; the data cache uses this.
a76d924d 8937 HEADER is the starting part of the packet.
c906108c
SS
8938 MEMADDR is the address in the remote memory space.
8939 MYADDR is the address of the buffer in our space.
124e13d9
SM
8940 LEN_UNITS is the number of addressable units to write.
8941 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
8942 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8943 should send data as binary ('X'), or hex-encoded ('M').
8944
8945 The function creates packet of the form
8946 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8947
124e13d9 8948 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
8949
8950 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8951 are omitted.
8952
9b409511 8953 Return the transferred status, error or OK (an
124e13d9
SM
8954 'enum target_xfer_status' value). Save the number of addressable units
8955 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8956
8957 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8958 exchange between gdb and the stub could look like (?? in place of the
8959 checksum):
8960
8961 -> $m1000,4#??
8962 <- aaaabbbbccccdddd
8963
8964 -> $M1000,3:eeeeffffeeee#??
8965 <- OK
8966
8967 -> $m1000,4#??
8968 <- eeeeffffeeeedddd */
c906108c 8969
6b8edb51
PA
8970target_xfer_status
8971remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8972 const gdb_byte *myaddr,
8973 ULONGEST len_units,
8974 int unit_size,
8975 ULONGEST *xfered_len_units,
8976 char packet_format, int use_length)
c906108c 8977{
6d820c5c 8978 struct remote_state *rs = get_remote_state ();
cfd77fa1 8979 char *p;
a76d924d
DJ
8980 char *plen = NULL;
8981 int plenlen = 0;
124e13d9
SM
8982 int todo_units;
8983 int units_written;
8984 int payload_capacity_bytes;
8985 int payload_length_bytes;
a76d924d
DJ
8986
8987 if (packet_format != 'X' && packet_format != 'M')
8988 internal_error (__FILE__, __LINE__,
9b20d036 8989 _("remote_write_bytes_aux: bad packet format"));
c906108c 8990
124e13d9 8991 if (len_units == 0)
9b409511 8992 return TARGET_XFER_EOF;
b2182ed2 8993
124e13d9 8994 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 8995
6d820c5c
DJ
8996 /* The packet buffer will be large enough for the payload;
8997 get_memory_packet_size ensures this. */
a76d924d 8998 rs->buf[0] = '\0';
c906108c 8999
a257b5bb 9000 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
9001 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9002
124e13d9 9003 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 9004 if (!use_length)
0df8b418 9005 /* The comma won't be used. */
124e13d9
SM
9006 payload_capacity_bytes += 1;
9007 payload_capacity_bytes -= strlen (header);
9008 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 9009
a76d924d 9010 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 9011
8d64371b
TT
9012 strcat (rs->buf.data (), header);
9013 p = rs->buf.data () + strlen (header);
a76d924d
DJ
9014
9015 /* Compute a best guess of the number of bytes actually transfered. */
9016 if (packet_format == 'X')
c906108c 9017 {
23860348 9018 /* Best guess at number of bytes that will fit. */
325fac50
PA
9019 todo_units = std::min (len_units,
9020 (ULONGEST) payload_capacity_bytes / unit_size);
a76d924d 9021 if (use_length)
124e13d9 9022 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50 9023 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
9024 }
9025 else
9026 {
124e13d9 9027 /* Number of bytes that will fit. */
325fac50
PA
9028 todo_units
9029 = std::min (len_units,
9030 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
a76d924d 9031 if (use_length)
124e13d9 9032 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50
PA
9033 todo_units = std::min (todo_units,
9034 (payload_capacity_bytes / unit_size) / 2);
917317f4 9035 }
a76d924d 9036
124e13d9 9037 if (todo_units <= 0)
3de11b2e 9038 internal_error (__FILE__, __LINE__,
405f8e94 9039 _("minimum packet size too small to write data"));
802188a7 9040
6765f3e5
DJ
9041 /* If we already need another packet, then try to align the end
9042 of this packet to a useful boundary. */
124e13d9
SM
9043 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9044 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 9045
a257b5bb 9046 /* Append "<memaddr>". */
917317f4
JM
9047 memaddr = remote_address_masked (memaddr);
9048 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 9049
a76d924d
DJ
9050 if (use_length)
9051 {
9052 /* Append ",". */
9053 *p++ = ',';
802188a7 9054
124e13d9 9055 /* Append the length and retain its location and size. It may need to be
dda83cd7 9056 adjusted once the packet body has been created. */
a76d924d 9057 plen = p;
124e13d9 9058 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
9059 p += plenlen;
9060 }
a257b5bb
AC
9061
9062 /* Append ":". */
917317f4
JM
9063 *p++ = ':';
9064 *p = '\0';
802188a7 9065
a257b5bb 9066 /* Append the packet body. */
a76d924d 9067 if (packet_format == 'X')
917317f4 9068 {
917317f4
JM
9069 /* Binary mode. Send target system values byte by byte, in
9070 increasing byte addresses. Only escape certain critical
9071 characters. */
124e13d9
SM
9072 payload_length_bytes =
9073 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9074 &units_written, payload_capacity_bytes);
6765f3e5 9075
124e13d9 9076 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
9077 a second try to keep the end of the packet aligned. Don't do
9078 this if the packet is tiny. */
124e13d9 9079 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 9080 {
124e13d9
SM
9081 int new_todo_units;
9082
9083 new_todo_units = align_for_efficient_write (units_written, memaddr);
9084
9085 if (new_todo_units != units_written)
9086 payload_length_bytes =
9087 remote_escape_output (myaddr, new_todo_units, unit_size,
9088 (gdb_byte *) p, &units_written,
9089 payload_capacity_bytes);
6765f3e5
DJ
9090 }
9091
124e13d9
SM
9092 p += payload_length_bytes;
9093 if (use_length && units_written < todo_units)
c906108c 9094 {
802188a7 9095 /* Escape chars have filled up the buffer prematurely,
124e13d9 9096 and we have actually sent fewer units than planned.
917317f4
JM
9097 Fix-up the length field of the packet. Use the same
9098 number of characters as before. */
124e13d9
SM
9099 plen += hexnumnstr (plen, (ULONGEST) units_written,
9100 plenlen);
917317f4 9101 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 9102 }
a76d924d
DJ
9103 }
9104 else
9105 {
917317f4
JM
9106 /* Normal mode: Send target system values byte by byte, in
9107 increasing byte addresses. Each byte is encoded as a two hex
9108 value. */
124e13d9
SM
9109 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9110 units_written = todo_units;
c906108c 9111 }
802188a7 9112
8d64371b
TT
9113 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9114 getpkt (&rs->buf, 0);
802188a7 9115
2e9f7625 9116 if (rs->buf[0] == 'E')
00d84524 9117 return TARGET_XFER_E_IO;
802188a7 9118
124e13d9
SM
9119 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9120 send fewer units than we'd planned. */
9121 *xfered_len_units = (ULONGEST) units_written;
92ffd475 9122 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
9123}
9124
a76d924d
DJ
9125/* Write memory data directly to the remote machine.
9126 This does not inform the data cache; the data cache uses this.
9127 MEMADDR is the address in the remote memory space.
9128 MYADDR is the address of the buffer in our space.
9129 LEN is the number of bytes.
9130
9b409511
YQ
9131 Return the transferred status, error or OK (an
9132 'enum target_xfer_status' value). Save the number of bytes
9133 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 9134
6b8edb51
PA
9135target_xfer_status
9136remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9137 ULONGEST len, int unit_size,
9138 ULONGEST *xfered_len)
a76d924d 9139{
a121b7c1 9140 const char *packet_format = NULL;
a76d924d
DJ
9141
9142 /* Check whether the target supports binary download. */
9143 check_binary_download (memaddr);
9144
4082afcc 9145 switch (packet_support (PACKET_X))
a76d924d
DJ
9146 {
9147 case PACKET_ENABLE:
9148 packet_format = "X";
9149 break;
9150 case PACKET_DISABLE:
9151 packet_format = "M";
9152 break;
9153 case PACKET_SUPPORT_UNKNOWN:
9154 internal_error (__FILE__, __LINE__,
9155 _("remote_write_bytes: bad internal state"));
9156 default:
9157 internal_error (__FILE__, __LINE__, _("bad switch"));
9158 }
9159
9160 return remote_write_bytes_aux (packet_format,
124e13d9 9161 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 9162 packet_format[0], 1);
a76d924d
DJ
9163}
9164
9217e74e
YQ
9165/* Read memory data directly from the remote machine.
9166 This does not use the data cache; the data cache uses this.
9167 MEMADDR is the address in the remote memory space.
9168 MYADDR is the address of the buffer in our space.
124e13d9
SM
9169 LEN_UNITS is the number of addressable memory units to read..
9170 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
9171
9172 Return the transferred status, error or OK (an
9173 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
9174 transferred in *XFERED_LEN_UNITS.
9175
9176 See the comment of remote_write_bytes_aux for an example of
9177 memory read/write exchange between gdb and the stub. */
9217e74e 9178
6b8edb51
PA
9179target_xfer_status
9180remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9181 ULONGEST len_units,
9182 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
9183{
9184 struct remote_state *rs = get_remote_state ();
124e13d9 9185 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 9186 char *p;
124e13d9
SM
9187 int todo_units;
9188 int decoded_bytes;
9217e74e 9189
124e13d9 9190 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
9191 /* The packet buffer will be large enough for the payload;
9192 get_memory_packet_size ensures this. */
9193
124e13d9 9194 /* Number of units that will fit. */
325fac50
PA
9195 todo_units = std::min (len_units,
9196 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
9197
9198 /* Construct "m"<memaddr>","<len>". */
9199 memaddr = remote_address_masked (memaddr);
8d64371b 9200 p = rs->buf.data ();
9217e74e
YQ
9201 *p++ = 'm';
9202 p += hexnumstr (p, (ULONGEST) memaddr);
9203 *p++ = ',';
124e13d9 9204 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
9205 *p = '\0';
9206 putpkt (rs->buf);
8d64371b 9207 getpkt (&rs->buf, 0);
9217e74e
YQ
9208 if (rs->buf[0] == 'E'
9209 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9210 && rs->buf[3] == '\0')
9211 return TARGET_XFER_E_IO;
9212 /* Reply describes memory byte by byte, each byte encoded as two hex
9213 characters. */
8d64371b 9214 p = rs->buf.data ();
124e13d9 9215 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 9216 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 9217 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
92ffd475 9218 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9217e74e
YQ
9219}
9220
b55fbac4
YQ
9221/* Using the set of read-only target sections of remote, read live
9222 read-only memory.
8acf9577
YQ
9223
9224 For interface/parameters/return description see target.h,
9225 to_xfer_partial. */
9226
6b8edb51
PA
9227target_xfer_status
9228remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9229 ULONGEST memaddr,
9230 ULONGEST len,
9231 int unit_size,
9232 ULONGEST *xfered_len)
8acf9577 9233{
19cf757a 9234 const struct target_section *secp;
8acf9577 9235
6b8edb51 9236 secp = target_section_by_addr (this, memaddr);
8acf9577 9237 if (secp != NULL
fd361982 9238 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
8acf9577 9239 {
8acf9577
YQ
9240 ULONGEST memend = memaddr + len;
9241
19cf757a
AB
9242 const target_section_table *table = target_get_section_table (this);
9243 for (const target_section &p : *table)
8acf9577 9244 {
bb2a6777 9245 if (memaddr >= p.addr)
8acf9577 9246 {
bb2a6777 9247 if (memend <= p.endaddr)
8acf9577
YQ
9248 {
9249 /* Entire transfer is within this section. */
124e13d9 9250 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 9251 xfered_len);
8acf9577 9252 }
bb2a6777 9253 else if (memaddr >= p.endaddr)
8acf9577
YQ
9254 {
9255 /* This section ends before the transfer starts. */
9256 continue;
9257 }
9258 else
9259 {
9260 /* This section overlaps the transfer. Just do half. */
bb2a6777 9261 len = p.endaddr - memaddr;
124e13d9 9262 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 9263 xfered_len);
8acf9577
YQ
9264 }
9265 }
9266 }
9267 }
9268
9269 return TARGET_XFER_EOF;
9270}
9271
9217e74e
YQ
9272/* Similar to remote_read_bytes_1, but it reads from the remote stub
9273 first if the requested memory is unavailable in traceframe.
9274 Otherwise, fall back to remote_read_bytes_1. */
c906108c 9275
6b8edb51
PA
9276target_xfer_status
9277remote_target::remote_read_bytes (CORE_ADDR memaddr,
9278 gdb_byte *myaddr, ULONGEST len, int unit_size,
9279 ULONGEST *xfered_len)
c906108c 9280{
6b6aa828 9281 if (len == 0)
96c4f946 9282 return TARGET_XFER_EOF;
b2182ed2 9283
8acf9577
YQ
9284 if (get_traceframe_number () != -1)
9285 {
a79b1bc6 9286 std::vector<mem_range> available;
8acf9577
YQ
9287
9288 /* If we fail to get the set of available memory, then the
9289 target does not support querying traceframe info, and so we
9290 attempt reading from the traceframe anyway (assuming the
9291 target implements the old QTro packet then). */
9292 if (traceframe_available_memory (&available, memaddr, len))
9293 {
a79b1bc6 9294 if (available.empty () || available[0].start != memaddr)
8acf9577
YQ
9295 {
9296 enum target_xfer_status res;
9297
9298 /* Don't read into the traceframe's available
9299 memory. */
a79b1bc6 9300 if (!available.empty ())
8acf9577
YQ
9301 {
9302 LONGEST oldlen = len;
9303
a79b1bc6 9304 len = available[0].start - memaddr;
8acf9577
YQ
9305 gdb_assert (len <= oldlen);
9306 }
9307
8acf9577 9308 /* This goes through the topmost target again. */
6b8edb51 9309 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
124e13d9 9310 len, unit_size, xfered_len);
8acf9577
YQ
9311 if (res == TARGET_XFER_OK)
9312 return TARGET_XFER_OK;
9313 else
9314 {
9315 /* No use trying further, we know some memory starting
9316 at MEMADDR isn't available. */
9317 *xfered_len = len;
92ffd475
PC
9318 return (*xfered_len != 0) ?
9319 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8acf9577
YQ
9320 }
9321 }
9322
9323 /* Don't try to read more than how much is available, in
9324 case the target implements the deprecated QTro packet to
9325 cater for older GDBs (the target's knowledge of read-only
9326 sections may be outdated by now). */
a79b1bc6 9327 len = available[0].length;
8acf9577
YQ
9328 }
9329 }
9330
124e13d9 9331 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 9332}
74531fed 9333
c906108c 9334\f
c906108c 9335
a76d924d
DJ
9336/* Sends a packet with content determined by the printf format string
9337 FORMAT and the remaining arguments, then gets the reply. Returns
9338 whether the packet was a success, a failure, or unknown. */
9339
6b8edb51
PA
9340packet_result
9341remote_target::remote_send_printf (const char *format, ...)
a76d924d
DJ
9342{
9343 struct remote_state *rs = get_remote_state ();
9344 int max_size = get_remote_packet_size ();
a76d924d 9345 va_list ap;
a744cf53 9346
a76d924d
DJ
9347 va_start (ap, format);
9348
9349 rs->buf[0] = '\0';
8d64371b 9350 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
33b031ce
GB
9351
9352 va_end (ap);
9353
9354 if (size >= max_size)
9b20d036 9355 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
9356
9357 if (putpkt (rs->buf) < 0)
9358 error (_("Communication problem with target."));
9359
9360 rs->buf[0] = '\0';
8d64371b 9361 getpkt (&rs->buf, 0);
a76d924d
DJ
9362
9363 return packet_check_result (rs->buf);
9364}
9365
a76d924d
DJ
9366/* Flash writing can take quite some time. We'll set
9367 effectively infinite timeout for flash operations.
9368 In future, we'll need to decide on a better approach. */
9369static const int remote_flash_timeout = 1000;
9370
f6ac5f3d
PA
9371void
9372remote_target::flash_erase (ULONGEST address, LONGEST length)
a76d924d 9373{
f5656ead 9374 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d 9375 enum packet_result ret;
2ec845e7
TT
9376 scoped_restore restore_timeout
9377 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
a76d924d
DJ
9378
9379 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 9380 phex (address, addr_size),
a76d924d
DJ
9381 phex (length, 4));
9382 switch (ret)
9383 {
9384 case PACKET_UNKNOWN:
9385 error (_("Remote target does not support flash erase"));
9386 case PACKET_ERROR:
9387 error (_("Error erasing flash with vFlashErase packet"));
9388 default:
9389 break;
9390 }
a76d924d
DJ
9391}
9392
6b8edb51
PA
9393target_xfer_status
9394remote_target::remote_flash_write (ULONGEST address,
9395 ULONGEST length, ULONGEST *xfered_len,
9396 const gdb_byte *data)
a76d924d 9397{
2ec845e7
TT
9398 scoped_restore restore_timeout
9399 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9400 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9401 xfered_len,'X', 0);
a76d924d
DJ
9402}
9403
f6ac5f3d
PA
9404void
9405remote_target::flash_done ()
a76d924d 9406{
a76d924d 9407 int ret;
a76d924d 9408
2ec845e7
TT
9409 scoped_restore restore_timeout
9410 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9411
a76d924d 9412 ret = remote_send_printf ("vFlashDone");
a76d924d
DJ
9413
9414 switch (ret)
9415 {
9416 case PACKET_UNKNOWN:
9417 error (_("Remote target does not support vFlashDone"));
9418 case PACKET_ERROR:
9419 error (_("Error finishing flash operation"));
9420 default:
9421 break;
9422 }
9423}
9424
c906108c
SS
9425\f
9426/* Stuff for dealing with the packets which are part of this protocol.
9427 See comment at top of file for details. */
9428
1927e618
PA
9429/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9430 error to higher layers. Called when a serial error is detected.
9431 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
9432 the system error message for errno at function entry and final dot
9433 for output compatibility with throw_perror_with_name. */
1927e618
PA
9434
9435static void
5b6d1e4f 9436unpush_and_perror (remote_target *target, const char *string)
1927e618 9437{
d6cb50a2 9438 int saved_errno = errno;
1927e618 9439
5b6d1e4f 9440 remote_unpush_target (target);
d6cb50a2
JK
9441 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9442 safe_strerror (saved_errno));
1927e618
PA
9443}
9444
048094ac
PA
9445/* Read a single character from the remote end. The current quit
9446 handler is overridden to avoid quitting in the middle of packet
9447 sequence, as that would break communication with the remote server.
9448 See remote_serial_quit_handler for more detail. */
c906108c 9449
6b8edb51
PA
9450int
9451remote_target::readchar (int timeout)
c906108c
SS
9452{
9453 int ch;
5d93a237 9454 struct remote_state *rs = get_remote_state ();
048094ac 9455
2ec845e7 9456 {
6b8edb51
PA
9457 scoped_restore restore_quit_target
9458 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9459 scoped_restore restore_quit
6b8edb51 9460 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
c906108c 9461
2ec845e7 9462 rs->got_ctrlc_during_io = 0;
c906108c 9463
2ec845e7 9464 ch = serial_readchar (rs->remote_desc, timeout);
048094ac 9465
2ec845e7
TT
9466 if (rs->got_ctrlc_during_io)
9467 set_quit_flag ();
9468 }
048094ac 9469
2acceee2 9470 if (ch >= 0)
0876f84a 9471 return ch;
2acceee2
JM
9472
9473 switch ((enum serial_rc) ch)
c906108c
SS
9474 {
9475 case SERIAL_EOF:
5b6d1e4f 9476 remote_unpush_target (this);
598d3636 9477 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 9478 /* no return */
c906108c 9479 case SERIAL_ERROR:
5b6d1e4f
PA
9480 unpush_and_perror (this, _("Remote communication error. "
9481 "Target disconnected."));
2acceee2 9482 /* no return */
c906108c 9483 case SERIAL_TIMEOUT:
2acceee2 9484 break;
c906108c 9485 }
2acceee2 9486 return ch;
c906108c
SS
9487}
9488
c33e31fd 9489/* Wrapper for serial_write that closes the target and throws if
048094ac
PA
9490 writing fails. The current quit handler is overridden to avoid
9491 quitting in the middle of packet sequence, as that would break
9492 communication with the remote server. See
9493 remote_serial_quit_handler for more detail. */
c33e31fd 9494
6b8edb51
PA
9495void
9496remote_target::remote_serial_write (const char *str, int len)
c33e31fd 9497{
5d93a237 9498 struct remote_state *rs = get_remote_state ();
048094ac 9499
6b8edb51
PA
9500 scoped_restore restore_quit_target
9501 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9502 scoped_restore restore_quit
6b8edb51 9503 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
048094ac
PA
9504
9505 rs->got_ctrlc_during_io = 0;
5d93a237
TT
9506
9507 if (serial_write (rs->remote_desc, str, len))
c33e31fd 9508 {
5b6d1e4f
PA
9509 unpush_and_perror (this, _("Remote communication error. "
9510 "Target disconnected."));
c33e31fd 9511 }
048094ac
PA
9512
9513 if (rs->got_ctrlc_during_io)
9514 set_quit_flag ();
c33e31fd
PA
9515}
9516
b3ced9ba
PA
9517/* Return a string representing an escaped version of BUF, of len N.
9518 E.g. \n is converted to \\n, \t to \\t, etc. */
6e5abd65 9519
b3ced9ba 9520static std::string
6e5abd65
PA
9521escape_buffer (const char *buf, int n)
9522{
d7e74731 9523 string_file stb;
6e5abd65 9524
d7e74731 9525 stb.putstrn (buf, n, '\\');
5d10a204 9526 return stb.release ();
6e5abd65
PA
9527}
9528
c906108c 9529int
6b8edb51 9530remote_target::putpkt (const char *buf)
c906108c
SS
9531{
9532 return putpkt_binary (buf, strlen (buf));
9533}
9534
6b8edb51
PA
9535/* Wrapper around remote_target::putpkt to avoid exporting
9536 remote_target. */
9537
9538int
9539putpkt (remote_target *remote, const char *buf)
9540{
9541 return remote->putpkt (buf);
9542}
9543
c906108c 9544/* Send a packet to the remote machine, with error checking. The data
23860348 9545 of the packet is in BUF. The string in BUF can be at most
ea9c271d 9546 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
9547 and for a possible /0 if we are debugging (remote_debug) and want
9548 to print the sent packet as a string. */
c906108c 9549
6b8edb51
PA
9550int
9551remote_target::putpkt_binary (const char *buf, int cnt)
c906108c 9552{
2d717e4f 9553 struct remote_state *rs = get_remote_state ();
c906108c
SS
9554 int i;
9555 unsigned char csum = 0;
b80406ac
TT
9556 gdb::def_vector<char> data (cnt + 6);
9557 char *buf2 = data.data ();
085dd6e6 9558
c906108c
SS
9559 int ch;
9560 int tcount = 0;
9561 char *p;
9562
e24a49d8
PA
9563 /* Catch cases like trying to read memory or listing threads while
9564 we're waiting for a stop reply. The remote server wouldn't be
9565 ready to handle this request, so we'd hang and timeout. We don't
9566 have to worry about this in synchronous mode, because in that
9567 case it's not possible to issue a command while the target is
74531fed
PA
9568 running. This is not a problem in non-stop mode, because in that
9569 case, the stub is always ready to process serial input. */
6efcd9a8
PA
9570 if (!target_is_non_stop_p ()
9571 && target_is_async_p ()
9572 && rs->waiting_for_stop_reply)
9597b22a
DE
9573 {
9574 error (_("Cannot execute this command while the target is running.\n"
9575 "Use the \"interrupt\" command to stop the target\n"
9576 "and then try again."));
9577 }
e24a49d8 9578
c906108c
SS
9579 /* Copy the packet into buffer BUF2, encapsulating it
9580 and giving it a checksum. */
9581
c906108c
SS
9582 p = buf2;
9583 *p++ = '$';
9584
9585 for (i = 0; i < cnt; i++)
9586 {
9587 csum += buf[i];
9588 *p++ = buf[i];
9589 }
9590 *p++ = '#';
9591 *p++ = tohex ((csum >> 4) & 0xf);
9592 *p++ = tohex (csum & 0xf);
9593
9594 /* Send it over and over until we get a positive ack. */
9595
9596 while (1)
9597 {
c906108c
SS
9598 if (remote_debug)
9599 {
9600 *p = '\0';
b3ced9ba 9601
6f8976bf 9602 int len = (int) (p - buf2);
6cc8564b
LM
9603 int max_chars;
9604
9605 if (remote_packet_max_chars < 0)
9606 max_chars = len;
9607 else
9608 max_chars = remote_packet_max_chars;
6f8976bf
YQ
9609
9610 std::string str
6cc8564b 9611 = escape_buffer (buf2, std::min (len, max_chars));
6f8976bf 9612
6cc8564b 9613 if (len > max_chars)
2189c312
SM
9614 remote_debug_printf_nofunc
9615 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9616 len - max_chars);
9617 else
9618 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
c906108c 9619 }
c33e31fd 9620 remote_serial_write (buf2, p - buf2);
c906108c 9621
a6f3e723
SL
9622 /* If this is a no acks version of the remote protocol, send the
9623 packet and move on. */
9624 if (rs->noack_mode)
dda83cd7 9625 break;
a6f3e723 9626
74531fed
PA
9627 /* Read until either a timeout occurs (-2) or '+' is read.
9628 Handle any notification that arrives in the mean time. */
c906108c
SS
9629 while (1)
9630 {
9631 ch = readchar (remote_timeout);
9632
c906108c
SS
9633 switch (ch)
9634 {
9635 case '+':
2189c312 9636 remote_debug_printf_nofunc ("Received Ack");
c906108c 9637 return 1;
1216fa2c 9638 case '-':
2189c312 9639 remote_debug_printf_nofunc ("Received Nak");
a17d146e 9640 /* FALLTHROUGH */
c906108c 9641 case SERIAL_TIMEOUT:
c5aa993b 9642 tcount++;
c906108c 9643 if (tcount > 3)
b80406ac 9644 return 0;
23860348 9645 break; /* Retransmit buffer. */
c906108c
SS
9646 case '$':
9647 {
2189c312 9648 remote_debug_printf ("Packet instead of Ack, ignoring it");
d6f7abdf
AC
9649 /* It's probably an old response sent because an ACK
9650 was lost. Gobble up the packet and ack it so it
9651 doesn't get retransmitted when we resend this
9652 packet. */
6d820c5c 9653 skip_frame ();
c33e31fd 9654 remote_serial_write ("+", 1);
23860348 9655 continue; /* Now, go look for +. */
c906108c 9656 }
74531fed
PA
9657
9658 case '%':
9659 {
9660 int val;
9661
9662 /* If we got a notification, handle it, and go back to looking
9663 for an ack. */
9664 /* We've found the start of a notification. Now
9665 collect the data. */
8d64371b 9666 val = read_frame (&rs->buf);
74531fed
PA
9667 if (val >= 0)
9668 {
2189c312
SM
9669 remote_debug_printf_nofunc
9670 (" Notification received: %s",
9671 escape_buffer (rs->buf.data (), val).c_str ());
6e5abd65 9672
8d64371b 9673 handle_notification (rs->notif_state, rs->buf.data ());
74531fed
PA
9674 /* We're in sync now, rewait for the ack. */
9675 tcount = 0;
9676 }
9677 else
2189c312
SM
9678 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9679 rs->buf.data ());
74531fed
PA
9680 continue;
9681 }
9682 /* fall-through */
c906108c 9683 default:
2189c312
SM
9684 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9685 rs->buf.data ());
c906108c
SS
9686 continue;
9687 }
23860348 9688 break; /* Here to retransmit. */
c906108c
SS
9689 }
9690
9691#if 0
9692 /* This is wrong. If doing a long backtrace, the user should be
dda83cd7
SM
9693 able to get out next time we call QUIT, without anything as
9694 violent as interrupt_query. If we want to provide a way out of
9695 here without getting to the next QUIT, it should be based on
9696 hitting ^C twice as in remote_wait. */
c906108c
SS
9697 if (quit_flag)
9698 {
9699 quit_flag = 0;
9700 interrupt_query ();
9701 }
9702#endif
9703 }
a5c0808e 9704
a6f3e723 9705 return 0;
c906108c
SS
9706}
9707
6d820c5c
DJ
9708/* Come here after finding the start of a frame when we expected an
9709 ack. Do our best to discard the rest of this packet. */
9710
6b8edb51
PA
9711void
9712remote_target::skip_frame ()
6d820c5c
DJ
9713{
9714 int c;
9715
9716 while (1)
9717 {
9718 c = readchar (remote_timeout);
9719 switch (c)
9720 {
9721 case SERIAL_TIMEOUT:
9722 /* Nothing we can do. */
9723 return;
9724 case '#':
9725 /* Discard the two bytes of checksum and stop. */
9726 c = readchar (remote_timeout);
9727 if (c >= 0)
9728 c = readchar (remote_timeout);
9729
9730 return;
9731 case '*': /* Run length encoding. */
9732 /* Discard the repeat count. */
9733 c = readchar (remote_timeout);
9734 if (c < 0)
9735 return;
9736 break;
9737 default:
9738 /* A regular character. */
9739 break;
9740 }
9741 }
9742}
9743
c906108c 9744/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
9745 into *BUF, verifying the checksum, length, and handling run-length
9746 compression. NUL terminate the buffer. If there is not enough room,
8d64371b 9747 expand *BUF.
c906108c 9748
c2d11a7d
JM
9749 Returns -1 on error, number of characters in buffer (ignoring the
9750 trailing NULL) on success. (could be extended to return one of the
23860348 9751 SERIAL status indications). */
c2d11a7d 9752
6b8edb51 9753long
8d64371b 9754remote_target::read_frame (gdb::char_vector *buf_p)
c906108c
SS
9755{
9756 unsigned char csum;
c2d11a7d 9757 long bc;
c906108c 9758 int c;
8d64371b 9759 char *buf = buf_p->data ();
a6f3e723 9760 struct remote_state *rs = get_remote_state ();
c906108c
SS
9761
9762 csum = 0;
c2d11a7d 9763 bc = 0;
c906108c
SS
9764
9765 while (1)
9766 {
9767 c = readchar (remote_timeout);
c906108c
SS
9768 switch (c)
9769 {
9770 case SERIAL_TIMEOUT:
2189c312 9771 remote_debug_printf ("Timeout in mid-packet, retrying");
c2d11a7d 9772 return -1;
2189c312 9773
c906108c 9774 case '$':
2189c312 9775 remote_debug_printf ("Saw new packet start in middle of old one");
23860348 9776 return -1; /* Start a new packet, count retries. */
2189c312 9777
c906108c
SS
9778 case '#':
9779 {
9780 unsigned char pktcsum;
e1b09194
AC
9781 int check_0 = 0;
9782 int check_1 = 0;
c906108c 9783
c2d11a7d 9784 buf[bc] = '\0';
c906108c 9785
e1b09194
AC
9786 check_0 = readchar (remote_timeout);
9787 if (check_0 >= 0)
9788 check_1 = readchar (remote_timeout);
802188a7 9789
e1b09194
AC
9790 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9791 {
2189c312 9792 remote_debug_printf ("Timeout in checksum, retrying");
e1b09194
AC
9793 return -1;
9794 }
9795 else if (check_0 < 0 || check_1 < 0)
40e3f985 9796 {
2189c312 9797 remote_debug_printf ("Communication error in checksum");
40e3f985
FN
9798 return -1;
9799 }
c906108c 9800
a6f3e723
SL
9801 /* Don't recompute the checksum; with no ack packets we
9802 don't have any way to indicate a packet retransmission
9803 is necessary. */
9804 if (rs->noack_mode)
9805 return bc;
9806
e1b09194 9807 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 9808 if (csum == pktcsum)
dda83cd7 9809 return bc;
c906108c 9810
2189c312
SM
9811 remote_debug_printf
9812 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
9813 pktcsum, csum, escape_buffer (buf, bc).c_str ());
6e5abd65 9814
c2d11a7d 9815 /* Number of characters in buffer ignoring trailing
dda83cd7 9816 NULL. */
c2d11a7d 9817 return -1;
c906108c 9818 }
23860348 9819 case '*': /* Run length encoding. */
dda83cd7 9820 {
c2c6d25f 9821 int repeat;
c906108c 9822
24b21115 9823 csum += c;
b4501125
AC
9824 c = readchar (remote_timeout);
9825 csum += c;
23860348 9826 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 9827
23860348 9828 /* The character before ``*'' is repeated. */
c2d11a7d 9829
6d820c5c 9830 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 9831 {
8d64371b 9832 if (bc + repeat - 1 >= buf_p->size () - 1)
6d820c5c
DJ
9833 {
9834 /* Make some more room in the buffer. */
8d64371b
TT
9835 buf_p->resize (buf_p->size () + repeat);
9836 buf = buf_p->data ();
6d820c5c
DJ
9837 }
9838
c2d11a7d
JM
9839 memset (&buf[bc], buf[bc - 1], repeat);
9840 bc += repeat;
c2c6d25f
JM
9841 continue;
9842 }
9843
c2d11a7d 9844 buf[bc] = '\0';
6cb06a8c 9845 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 9846 return -1;
c2c6d25f 9847 }
c906108c 9848 default:
8d64371b 9849 if (bc >= buf_p->size () - 1)
c906108c 9850 {
6d820c5c 9851 /* Make some more room in the buffer. */
8d64371b
TT
9852 buf_p->resize (buf_p->size () * 2);
9853 buf = buf_p->data ();
c906108c
SS
9854 }
9855
6d820c5c
DJ
9856 buf[bc++] = c;
9857 csum += c;
9858 continue;
c906108c
SS
9859 }
9860 }
9861}
9862
ed2b7c17
TT
9863/* Set this to the maximum number of seconds to wait instead of waiting forever
9864 in target_wait(). If this timer times out, then it generates an error and
9865 the command is aborted. This replaces most of the need for timeouts in the
9866 GDB test suite, and makes it possible to distinguish between a hung target
9867 and one with slow communications. */
9868
9869static int watchdog = 0;
9870static void
9871show_watchdog (struct ui_file *file, int from_tty,
9872 struct cmd_list_element *c, const char *value)
9873{
6cb06a8c 9874 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
ed2b7c17
TT
9875}
9876
c906108c 9877/* Read a packet from the remote machine, with error checking, and
8d64371b
TT
9878 store it in *BUF. Resize *BUF if necessary to hold the result. If
9879 FOREVER, wait forever rather than timing out; this is used (in
9880 synchronous mode) to wait for a target that is is executing user
9881 code to stop. */
d9fcf2fb
JM
9882/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9883 don't have to change all the calls to getpkt to deal with the
9884 return value, because at the moment I don't know what the right
23860348 9885 thing to do it for those. */
6b8edb51 9886
c906108c 9887void
8d64371b 9888remote_target::getpkt (gdb::char_vector *buf, int forever)
d9fcf2fb 9889{
8d64371b 9890 getpkt_sane (buf, forever);
d9fcf2fb
JM
9891}
9892
9893
9894/* Read a packet from the remote machine, with error checking, and
8d64371b
TT
9895 store it in *BUF. Resize *BUF if necessary to hold the result. If
9896 FOREVER, wait forever rather than timing out; this is used (in
9897 synchronous mode) to wait for a target that is is executing user
9898 code to stop. If FOREVER == 0, this function is allowed to time
9899 out gracefully and return an indication of this to the caller.
9900 Otherwise return the number of bytes read. If EXPECTING_NOTIF,
9901 consider receiving a notification enough reason to return to the
9902 caller. *IS_NOTIF is an output boolean that indicates whether *BUF
9903 holds a notification or not (a regular packet). */
74531fed 9904
6b8edb51 9905int
8d64371b 9906remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
6b8edb51
PA
9907 int forever, int expecting_notif,
9908 int *is_notif)
c906108c 9909{
2d717e4f 9910 struct remote_state *rs = get_remote_state ();
c906108c
SS
9911 int c;
9912 int tries;
9913 int timeout;
df4b58fe 9914 int val = -1;
c906108c 9915
8d64371b 9916 strcpy (buf->data (), "timeout");
c906108c
SS
9917
9918 if (forever)
74531fed
PA
9919 timeout = watchdog > 0 ? watchdog : -1;
9920 else if (expecting_notif)
9921 timeout = 0; /* There should already be a char in the buffer. If
9922 not, bail out. */
c906108c
SS
9923 else
9924 timeout = remote_timeout;
9925
9926#define MAX_TRIES 3
9927
74531fed
PA
9928 /* Process any number of notifications, and then return when
9929 we get a packet. */
9930 for (;;)
c906108c 9931 {
d9c43928 9932 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
9933 times. */
9934 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 9935 {
74531fed
PA
9936 /* This can loop forever if the remote side sends us
9937 characters continuously, but if it pauses, we'll get
9938 SERIAL_TIMEOUT from readchar because of timeout. Then
9939 we'll count that as a retry.
9940
9941 Note that even when forever is set, we will only wait
9942 forever prior to the start of a packet. After that, we
9943 expect characters to arrive at a brisk pace. They should
9944 show up within remote_timeout intervals. */
9945 do
9946 c = readchar (timeout);
9947 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
9948
9949 if (c == SERIAL_TIMEOUT)
9950 {
74531fed
PA
9951 if (expecting_notif)
9952 return -1; /* Don't complain, it's normal to not get
9953 anything in this case. */
9954
23860348 9955 if (forever) /* Watchdog went off? Kill the target. */
c906108c 9956 {
5b6d1e4f 9957 remote_unpush_target (this);
598d3636
JK
9958 throw_error (TARGET_CLOSE_ERROR,
9959 _("Watchdog timeout has expired. "
9960 "Target detached."));
c906108c 9961 }
2189c312
SM
9962
9963 remote_debug_printf ("Timed out.");
c906108c 9964 }
74531fed
PA
9965 else
9966 {
9967 /* We've found the start of a packet or notification.
9968 Now collect the data. */
8d64371b 9969 val = read_frame (buf);
74531fed
PA
9970 if (val >= 0)
9971 break;
9972 }
9973
c33e31fd 9974 remote_serial_write ("-", 1);
c906108c 9975 }
c906108c 9976
74531fed
PA
9977 if (tries > MAX_TRIES)
9978 {
9979 /* We have tried hard enough, and just can't receive the
9980 packet/notification. Give up. */
6cb06a8c 9981 gdb_printf (_("Ignoring packet error, continuing...\n"));
c906108c 9982
74531fed
PA
9983 /* Skip the ack char if we're in no-ack mode. */
9984 if (!rs->noack_mode)
c33e31fd 9985 remote_serial_write ("+", 1);
74531fed
PA
9986 return -1;
9987 }
c906108c 9988
74531fed
PA
9989 /* If we got an ordinary packet, return that to our caller. */
9990 if (c == '$')
c906108c
SS
9991 {
9992 if (remote_debug)
43e526b9 9993 {
6cc8564b
LM
9994 int max_chars;
9995
9996 if (remote_packet_max_chars < 0)
9997 max_chars = val;
9998 else
9999 max_chars = remote_packet_max_chars;
10000
6f8976bf 10001 std::string str
8d64371b 10002 = escape_buffer (buf->data (),
6cc8564b 10003 std::min (val, max_chars));
6f8976bf 10004
6cc8564b 10005 if (val > max_chars)
2189c312
SM
10006 remote_debug_printf_nofunc
10007 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10008 val - max_chars);
10009 else
10010 remote_debug_printf_nofunc ("Packet received: %s",
10011 str.c_str ());
43e526b9 10012 }
a6f3e723
SL
10013
10014 /* Skip the ack char if we're in no-ack mode. */
10015 if (!rs->noack_mode)
c33e31fd 10016 remote_serial_write ("+", 1);
fee9eda9
YQ
10017 if (is_notif != NULL)
10018 *is_notif = 0;
0876f84a 10019 return val;
c906108c
SS
10020 }
10021
74531fed
PA
10022 /* If we got a notification, handle it, and go back to looking
10023 for a packet. */
10024 else
10025 {
10026 gdb_assert (c == '%');
10027
2189c312
SM
10028 remote_debug_printf_nofunc
10029 (" Notification received: %s",
10030 escape_buffer (buf->data (), val).c_str ());
6e5abd65 10031
fee9eda9
YQ
10032 if (is_notif != NULL)
10033 *is_notif = 1;
c906108c 10034
8d64371b 10035 handle_notification (rs->notif_state, buf->data ());
c906108c 10036
74531fed 10037 /* Notifications require no acknowledgement. */
a6f3e723 10038
74531fed 10039 if (expecting_notif)
fee9eda9 10040 return val;
74531fed
PA
10041 }
10042 }
10043}
10044
6b8edb51 10045int
8d64371b 10046remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
74531fed 10047{
8d64371b 10048 return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
74531fed
PA
10049}
10050
6b8edb51 10051int
8d64371b 10052remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
6b8edb51 10053 int *is_notif)
74531fed 10054{
8d64371b 10055 return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
c906108c 10056}
74531fed 10057
28561a65 10058/* Kill any new fork children of inferior INF that haven't been
cbb8991c
DB
10059 processed by follow_fork. */
10060
6b8edb51 10061void
28561a65 10062remote_target::kill_new_fork_children (inferior *inf)
cbb8991c 10063{
6b8edb51 10064 remote_state *rs = get_remote_state ();
cbb8991c 10065 struct notif_client *notif = &notif_client_stop;
cbb8991c 10066
28561a65
SM
10067 /* Kill the fork child threads of any threads in inferior INF that are stopped
10068 at a fork event. */
10069 for (thread_info *thread : inf->non_exited_threads ())
cbb8991c 10070 {
28561a65 10071 const target_waitstatus *ws = thread_pending_fork_status (thread);
cbb8991c 10072
28561a65
SM
10073 if (ws == nullptr)
10074 continue;
cbb8991c 10075
28561a65
SM
10076 int child_pid = ws->child_ptid ().pid ();
10077 int res = remote_vkill (child_pid);
10078
10079 if (res != 0)
10080 error (_("Can't kill fork child process %d"), child_pid);
cbb8991c
DB
10081 }
10082
10083 /* Check for any pending fork events (not reported or processed yet)
28561a65 10084 in inferior INF and kill those fork child threads as well. */
cbb8991c 10085 remote_notif_get_pending_events (notif);
953edf2b 10086 for (auto &event : rs->stop_reply_queue)
28561a65
SM
10087 {
10088 if (event->ptid.pid () != inf->pid)
10089 continue;
953edf2b 10090
28561a65
SM
10091 if (!is_fork_status (event->ws.kind ()))
10092 continue;
10093
10094 int child_pid = event->ws.child_ptid ().pid ();
10095 int res = remote_vkill (child_pid);
10096
10097 if (res != 0)
10098 error (_("Can't kill fork child process %d"), child_pid);
10099 }
cbb8991c
DB
10100}
10101
c906108c 10102\f
8020350c
DB
10103/* Target hook to kill the current inferior. */
10104
f6ac5f3d
PA
10105void
10106remote_target::kill ()
43ff13b4 10107{
8020350c 10108 int res = -1;
28561a65 10109 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
8020350c 10110 struct remote_state *rs = get_remote_state ();
0fdf84ca 10111
28561a65
SM
10112 gdb_assert (inf != nullptr);
10113
8020350c 10114 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 10115 {
8020350c
DB
10116 /* If we're stopped while forking and we haven't followed yet,
10117 kill the child task. We need to do this before killing the
10118 parent task because if this is a vfork then the parent will
10119 be sleeping. */
28561a65 10120 kill_new_fork_children (inf);
8020350c 10121
28561a65 10122 res = remote_vkill (inf->pid);
8020350c 10123 if (res == 0)
0fdf84ca 10124 {
bc1e6c81 10125 target_mourn_inferior (inferior_ptid);
0fdf84ca
PA
10126 return;
10127 }
8020350c 10128 }
0fdf84ca 10129
8020350c
DB
10130 /* If we are in 'target remote' mode and we are killing the only
10131 inferior, then we will tell gdbserver to exit and unpush the
10132 target. */
10133 if (res == -1 && !remote_multi_process_p (rs)
5b6d1e4f 10134 && number_of_live_inferiors (this) == 1)
8020350c
DB
10135 {
10136 remote_kill_k ();
10137
10138 /* We've killed the remote end, we get to mourn it. If we are
10139 not in extended mode, mourning the inferior also unpushes
10140 remote_ops from the target stack, which closes the remote
10141 connection. */
bc1e6c81 10142 target_mourn_inferior (inferior_ptid);
8020350c
DB
10143
10144 return;
0fdf84ca 10145 }
43ff13b4 10146
8020350c 10147 error (_("Can't kill process"));
43ff13b4
JM
10148}
10149
8020350c
DB
10150/* Send a kill request to the target using the 'vKill' packet. */
10151
6b8edb51
PA
10152int
10153remote_target::remote_vkill (int pid)
82f73884 10154{
4082afcc 10155 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
10156 return -1;
10157
6b8edb51
PA
10158 remote_state *rs = get_remote_state ();
10159
82f73884 10160 /* Tell the remote target to detach. */
8d64371b 10161 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
82f73884 10162 putpkt (rs->buf);
8d64371b 10163 getpkt (&rs->buf, 0);
82f73884 10164
4082afcc
PA
10165 switch (packet_ok (rs->buf,
10166 &remote_protocol_packets[PACKET_vKill]))
10167 {
10168 case PACKET_OK:
10169 return 0;
10170 case PACKET_ERROR:
10171 return 1;
10172 case PACKET_UNKNOWN:
10173 return -1;
10174 default:
10175 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
10176 }
82f73884
PA
10177}
10178
8020350c
DB
10179/* Send a kill request to the target using the 'k' packet. */
10180
6b8edb51
PA
10181void
10182remote_target::remote_kill_k ()
82f73884 10183{
8020350c
DB
10184 /* Catch errors so the user can quit from gdb even when we
10185 aren't on speaking terms with the remote system. */
a70b8144 10186 try
82f73884 10187 {
82f73884 10188 putpkt ("k");
82f73884 10189 }
230d2906 10190 catch (const gdb_exception_error &ex)
8020350c
DB
10191 {
10192 if (ex.error == TARGET_CLOSE_ERROR)
10193 {
10194 /* If we got an (EOF) error that caused the target
10195 to go away, then we're done, that's what we wanted.
10196 "k" is susceptible to cause a premature EOF, given
10197 that the remote server isn't actually required to
10198 reply to "k", and it can happen that it doesn't
10199 even get to reply ACK to the "k". */
10200 return;
10201 }
82f73884 10202
8020350c
DB
10203 /* Otherwise, something went wrong. We didn't actually kill
10204 the target. Just propagate the exception, and let the
10205 user or higher layers decide what to do. */
eedc3f4f 10206 throw;
8020350c 10207 }
82f73884
PA
10208}
10209
f6ac5f3d
PA
10210void
10211remote_target::mourn_inferior ()
c906108c 10212{
8020350c 10213 struct remote_state *rs = get_remote_state ();
ce5ce7ed 10214
9607784a
PA
10215 /* We're no longer interested in notification events of an inferior
10216 that exited or was killed/detached. */
10217 discard_pending_stop_replies (current_inferior ());
10218
8020350c 10219 /* In 'target remote' mode with one inferior, we close the connection. */
5b6d1e4f 10220 if (!rs->extended && number_of_live_inferiors (this) <= 1)
8020350c 10221 {
5b6d1e4f 10222 remote_unpush_target (this);
8020350c
DB
10223 return;
10224 }
c906108c 10225
e24a49d8
PA
10226 /* In case we got here due to an error, but we're going to stay
10227 connected. */
10228 rs->waiting_for_stop_reply = 0;
10229
dc1981d7
PA
10230 /* If the current general thread belonged to the process we just
10231 detached from or has exited, the remote side current general
10232 thread becomes undefined. Considering a case like this:
10233
10234 - We just got here due to a detach.
10235 - The process that we're detaching from happens to immediately
10236 report a global breakpoint being hit in non-stop mode, in the
10237 same thread we had selected before.
10238 - GDB attaches to this process again.
10239 - This event happens to be the next event we handle.
10240
10241 GDB would consider that the current general thread didn't need to
10242 be set on the stub side (with Hg), since for all it knew,
10243 GENERAL_THREAD hadn't changed.
10244
10245 Notice that although in all-stop mode, the remote server always
10246 sets the current thread to the thread reporting the stop event,
10247 that doesn't happen in non-stop mode; in non-stop, the stub *must
10248 not* change the current thread when reporting a breakpoint hit,
10249 due to the decoupling of event reporting and event handling.
10250
10251 To keep things simple, we always invalidate our notion of the
10252 current thread. */
47f8a51d 10253 record_currthread (rs, minus_one_ptid);
dc1981d7 10254
8020350c 10255 /* Call common code to mark the inferior as not running. */
48aa3c27 10256 generic_mourn_inferior ();
2d717e4f 10257}
c906108c 10258
57810aa7 10259bool
f6ac5f3d 10260extended_remote_target::supports_disable_randomization ()
03583c20 10261{
4082afcc 10262 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
10263}
10264
6b8edb51
PA
10265void
10266remote_target::extended_remote_disable_randomization (int val)
03583c20
UW
10267{
10268 struct remote_state *rs = get_remote_state ();
10269 char *reply;
10270
8d64371b
TT
10271 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10272 "QDisableRandomization:%x", val);
03583c20 10273 putpkt (rs->buf);
b6bb3468 10274 reply = remote_get_noisy_reply ();
03583c20
UW
10275 if (*reply == '\0')
10276 error (_("Target does not support QDisableRandomization."));
10277 if (strcmp (reply, "OK") != 0)
10278 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10279}
10280
6b8edb51
PA
10281int
10282remote_target::extended_remote_run (const std::string &args)
2d717e4f
DJ
10283{
10284 struct remote_state *rs = get_remote_state ();
2d717e4f 10285 int len;
94585166 10286 const char *remote_exec_file = get_remote_exec_file ();
c906108c 10287
2d717e4f
DJ
10288 /* If the user has disabled vRun support, or we have detected that
10289 support is not available, do not try it. */
4082afcc 10290 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 10291 return -1;
424163ea 10292
8d64371b
TT
10293 strcpy (rs->buf.data (), "vRun;");
10294 len = strlen (rs->buf.data ());
c906108c 10295
2d717e4f
DJ
10296 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10297 error (_("Remote file name too long for run packet"));
8d64371b 10298 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
9f1b45b0 10299 strlen (remote_exec_file));
2d717e4f 10300
7c5ded6a 10301 if (!args.empty ())
2d717e4f 10302 {
2d717e4f 10303 int i;
2d717e4f 10304
773a1edc 10305 gdb_argv argv (args.c_str ());
2d717e4f
DJ
10306 for (i = 0; argv[i] != NULL; i++)
10307 {
10308 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10309 error (_("Argument list too long for run packet"));
10310 rs->buf[len++] = ';';
8d64371b 10311 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
9f1b45b0 10312 strlen (argv[i]));
2d717e4f 10313 }
2d717e4f
DJ
10314 }
10315
10316 rs->buf[len++] = '\0';
10317
10318 putpkt (rs->buf);
8d64371b 10319 getpkt (&rs->buf, 0);
2d717e4f 10320
4082afcc 10321 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 10322 {
4082afcc 10323 case PACKET_OK:
3405876a 10324 /* We have a wait response. All is well. */
2d717e4f 10325 return 0;
4082afcc
PA
10326 case PACKET_UNKNOWN:
10327 return -1;
10328 case PACKET_ERROR:
2d717e4f
DJ
10329 if (remote_exec_file[0] == '\0')
10330 error (_("Running the default executable on the remote target failed; "
10331 "try \"set remote exec-file\"?"));
10332 else
10333 error (_("Running \"%s\" on the remote target failed"),
10334 remote_exec_file);
4082afcc 10335 default:
557b4d76 10336 gdb_assert_not_reached ("bad switch");
2d717e4f 10337 }
c906108c
SS
10338}
10339
0a2dde4a
SDJ
10340/* Helper function to send set/unset environment packets. ACTION is
10341 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10342 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10343 sent. */
10344
6b8edb51
PA
10345void
10346remote_target::send_environment_packet (const char *action,
10347 const char *packet,
10348 const char *value)
0a2dde4a 10349{
6b8edb51
PA
10350 remote_state *rs = get_remote_state ();
10351
0a2dde4a
SDJ
10352 /* Convert the environment variable to an hex string, which
10353 is the best format to be transmitted over the wire. */
10354 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10355 strlen (value));
10356
8d64371b 10357 xsnprintf (rs->buf.data (), get_remote_packet_size (),
0a2dde4a
SDJ
10358 "%s:%s", packet, encoded_value.c_str ());
10359
10360 putpkt (rs->buf);
8d64371b
TT
10361 getpkt (&rs->buf, 0);
10362 if (strcmp (rs->buf.data (), "OK") != 0)
0a2dde4a
SDJ
10363 warning (_("Unable to %s environment variable '%s' on remote."),
10364 action, value);
10365}
10366
10367/* Helper function to handle the QEnvironment* packets. */
10368
6b8edb51
PA
10369void
10370remote_target::extended_remote_environment_support ()
0a2dde4a 10371{
6b8edb51
PA
10372 remote_state *rs = get_remote_state ();
10373
0a2dde4a
SDJ
10374 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10375 {
10376 putpkt ("QEnvironmentReset");
8d64371b
TT
10377 getpkt (&rs->buf, 0);
10378 if (strcmp (rs->buf.data (), "OK") != 0)
0a2dde4a
SDJ
10379 warning (_("Unable to reset environment on remote."));
10380 }
10381
10382 gdb_environ *e = &current_inferior ()->environment;
10383
10384 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10385 for (const std::string &el : e->user_set_env ())
6b8edb51 10386 send_environment_packet ("set", "QEnvironmentHexEncoded",
0a2dde4a
SDJ
10387 el.c_str ());
10388
10389 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10390 for (const std::string &el : e->user_unset_env ())
6b8edb51 10391 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
0a2dde4a
SDJ
10392}
10393
bc3b087d
SDJ
10394/* Helper function to set the current working directory for the
10395 inferior in the remote target. */
10396
6b8edb51
PA
10397void
10398remote_target::extended_remote_set_inferior_cwd ()
bc3b087d
SDJ
10399{
10400 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10401 {
11bd012e 10402 const std::string &inferior_cwd = current_inferior ()->cwd ();
6b8edb51 10403 remote_state *rs = get_remote_state ();
bc3b087d 10404
11bd012e 10405 if (!inferior_cwd.empty ())
bc3b087d 10406 {
11bd012e
SM
10407 std::string hexpath
10408 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10409 inferior_cwd.size ());
bc3b087d 10410
8d64371b 10411 xsnprintf (rs->buf.data (), get_remote_packet_size (),
bc3b087d
SDJ
10412 "QSetWorkingDir:%s", hexpath.c_str ());
10413 }
10414 else
10415 {
10416 /* An empty inferior_cwd means that the user wants us to
10417 reset the remote server's inferior's cwd. */
8d64371b 10418 xsnprintf (rs->buf.data (), get_remote_packet_size (),
bc3b087d
SDJ
10419 "QSetWorkingDir:");
10420 }
10421
10422 putpkt (rs->buf);
8d64371b 10423 getpkt (&rs->buf, 0);
bc3b087d
SDJ
10424 if (packet_ok (rs->buf,
10425 &remote_protocol_packets[PACKET_QSetWorkingDir])
10426 != PACKET_OK)
10427 error (_("\
10428Remote replied unexpectedly while setting the inferior's working\n\
10429directory: %s"),
8d64371b 10430 rs->buf.data ());
bc3b087d
SDJ
10431
10432 }
10433}
10434
2d717e4f
DJ
10435/* In the extended protocol we want to be able to do things like
10436 "run" and have them basically work as expected. So we need
10437 a special create_inferior function. We support changing the
10438 executable file and the command line arguments, but not the
10439 environment. */
10440
f6ac5f3d
PA
10441void
10442extended_remote_target::create_inferior (const char *exec_file,
10443 const std::string &args,
10444 char **env, int from_tty)
43ff13b4 10445{
3405876a
PA
10446 int run_worked;
10447 char *stop_reply;
10448 struct remote_state *rs = get_remote_state ();
94585166 10449 const char *remote_exec_file = get_remote_exec_file ();
3405876a 10450
43ff13b4 10451 /* If running asynchronously, register the target file descriptor
23860348 10452 with the event loop. */
75c99385 10453 if (target_can_async_p ())
4a570176 10454 target_async (true);
43ff13b4 10455
03583c20 10456 /* Disable address space randomization if requested (and supported). */
f6ac5f3d 10457 if (supports_disable_randomization ())
03583c20
UW
10458 extended_remote_disable_randomization (disable_randomization);
10459
aefd8b33
SDJ
10460 /* If startup-with-shell is on, we inform gdbserver to start the
10461 remote inferior using a shell. */
10462 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10463 {
8d64371b 10464 xsnprintf (rs->buf.data (), get_remote_packet_size (),
aefd8b33
SDJ
10465 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10466 putpkt (rs->buf);
8d64371b
TT
10467 getpkt (&rs->buf, 0);
10468 if (strcmp (rs->buf.data (), "OK") != 0)
aefd8b33
SDJ
10469 error (_("\
10470Remote replied unexpectedly while setting startup-with-shell: %s"),
8d64371b 10471 rs->buf.data ());
aefd8b33
SDJ
10472 }
10473
6b8edb51 10474 extended_remote_environment_support ();
0a2dde4a 10475
6b8edb51 10476 extended_remote_set_inferior_cwd ();
bc3b087d 10477
43ff13b4 10478 /* Now restart the remote server. */
3405876a
PA
10479 run_worked = extended_remote_run (args) != -1;
10480 if (!run_worked)
2d717e4f
DJ
10481 {
10482 /* vRun was not supported. Fail if we need it to do what the
10483 user requested. */
10484 if (remote_exec_file[0])
10485 error (_("Remote target does not support \"set remote exec-file\""));
7c5ded6a 10486 if (!args.empty ())
65e65158 10487 error (_("Remote target does not support \"set args\" or run ARGS"));
43ff13b4 10488
2d717e4f
DJ
10489 /* Fall back to "R". */
10490 extended_remote_restart ();
10491 }
424163ea 10492
3405876a 10493 /* vRun's success return is a stop reply. */
8d64371b 10494 stop_reply = run_worked ? rs->buf.data () : NULL;
3405876a 10495 add_current_inferior_and_thread (stop_reply);
c0a2216e 10496
2d717e4f
DJ
10497 /* Get updated offsets, if the stub uses qOffsets. */
10498 get_offsets ();
2d717e4f 10499}
c906108c 10500\f
c5aa993b 10501
b775012e
LM
10502/* Given a location's target info BP_TGT and the packet buffer BUF, output
10503 the list of conditions (in agent expression bytecode format), if any, the
10504 target needs to evaluate. The output is placed into the packet buffer
bba74b36 10505 started from BUF and ended at BUF_END. */
b775012e
LM
10506
10507static int
10508remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
10509 struct bp_target_info *bp_tgt, char *buf,
10510 char *buf_end)
b775012e 10511{
3cde5c42 10512 if (bp_tgt->conditions.empty ())
b775012e
LM
10513 return 0;
10514
10515 buf += strlen (buf);
bba74b36 10516 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
10517 buf++;
10518
83621223 10519 /* Send conditions to the target. */
d538e36d 10520 for (agent_expr *aexpr : bp_tgt->conditions)
b775012e 10521 {
bba74b36 10522 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e 10523 buf += strlen (buf);
3cde5c42 10524 for (int i = 0; i < aexpr->len; ++i)
b775012e
LM
10525 buf = pack_hex_byte (buf, aexpr->buf[i]);
10526 *buf = '\0';
10527 }
b775012e
LM
10528 return 0;
10529}
10530
d3ce09f5
SS
10531static void
10532remote_add_target_side_commands (struct gdbarch *gdbarch,
10533 struct bp_target_info *bp_tgt, char *buf)
10534{
3cde5c42 10535 if (bp_tgt->tcommands.empty ())
d3ce09f5
SS
10536 return;
10537
10538 buf += strlen (buf);
10539
10540 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10541 buf += strlen (buf);
10542
10543 /* Concatenate all the agent expressions that are commands into the
10544 cmds parameter. */
df97be55 10545 for (agent_expr *aexpr : bp_tgt->tcommands)
d3ce09f5
SS
10546 {
10547 sprintf (buf, "X%x,", aexpr->len);
10548 buf += strlen (buf);
3cde5c42 10549 for (int i = 0; i < aexpr->len; ++i)
d3ce09f5
SS
10550 buf = pack_hex_byte (buf, aexpr->buf[i]);
10551 *buf = '\0';
10552 }
d3ce09f5
SS
10553}
10554
8181d85f
DJ
10555/* Insert a breakpoint. On targets that have software breakpoint
10556 support, we ask the remote target to do the work; on targets
10557 which don't, we insert a traditional memory breakpoint. */
c906108c 10558
f6ac5f3d
PA
10559int
10560remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10561 struct bp_target_info *bp_tgt)
c906108c 10562{
d471ea57
AC
10563 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10564 If it succeeds, then set the support to PACKET_ENABLE. If it
10565 fails, and the user has explicitly requested the Z support then
23860348 10566 report an error, otherwise, mark it disabled and go on. */
802188a7 10567
4082afcc 10568 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10569 {
0d5ed153 10570 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10571 struct remote_state *rs;
bba74b36 10572 char *p, *endbuf;
4fff2411 10573
28439a30
PA
10574 /* Make sure the remote is pointing at the right process, if
10575 necessary. */
10576 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10577 set_general_process ();
10578
4fff2411 10579 rs = get_remote_state ();
8d64371b
TT
10580 p = rs->buf.data ();
10581 endbuf = p + get_remote_packet_size ();
802188a7 10582
96baa820
JM
10583 *(p++) = 'Z';
10584 *(p++) = '0';
10585 *(p++) = ',';
7c0f6dcc 10586 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 10587 p += hexnumstr (p, addr);
579c6ad9 10588 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10589
f6ac5f3d 10590 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10591 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10592
f6ac5f3d 10593 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10594 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10595
6d820c5c 10596 putpkt (rs->buf);
8d64371b 10597 getpkt (&rs->buf, 0);
96baa820 10598
6d820c5c 10599 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 10600 {
d471ea57
AC
10601 case PACKET_ERROR:
10602 return -1;
10603 case PACKET_OK:
10604 return 0;
10605 case PACKET_UNKNOWN:
10606 break;
96baa820
JM
10607 }
10608 }
c906108c 10609
0000e5cc
PA
10610 /* If this breakpoint has target-side commands but this stub doesn't
10611 support Z0 packets, throw error. */
3cde5c42 10612 if (!bp_tgt->tcommands.empty ())
0000e5cc
PA
10613 throw_error (NOT_SUPPORTED_ERROR, _("\
10614Target doesn't support breakpoints that have target side commands."));
10615
f6ac5f3d 10616 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
c906108c
SS
10617}
10618
f6ac5f3d
PA
10619int
10620remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10621 struct bp_target_info *bp_tgt,
10622 enum remove_bp_reason reason)
c906108c 10623{
8181d85f 10624 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 10625 struct remote_state *rs = get_remote_state ();
96baa820 10626
4082afcc 10627 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10628 {
8d64371b
TT
10629 char *p = rs->buf.data ();
10630 char *endbuf = p + get_remote_packet_size ();
802188a7 10631
28439a30
PA
10632 /* Make sure the remote is pointing at the right process, if
10633 necessary. */
10634 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10635 set_general_process ();
10636
96baa820
JM
10637 *(p++) = 'z';
10638 *(p++) = '0';
10639 *(p++) = ',';
10640
8181d85f
DJ
10641 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10642 p += hexnumstr (p, addr);
579c6ad9 10643 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10644
6d820c5c 10645 putpkt (rs->buf);
8d64371b 10646 getpkt (&rs->buf, 0);
96baa820 10647
6d820c5c 10648 return (rs->buf[0] == 'E');
96baa820
JM
10649 }
10650
f6ac5f3d 10651 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
c906108c
SS
10652}
10653
f486487f 10654static enum Z_packet_type
d471ea57
AC
10655watchpoint_to_Z_packet (int type)
10656{
10657 switch (type)
10658 {
10659 case hw_write:
bb858e6a 10660 return Z_PACKET_WRITE_WP;
d471ea57
AC
10661 break;
10662 case hw_read:
bb858e6a 10663 return Z_PACKET_READ_WP;
d471ea57
AC
10664 break;
10665 case hw_access:
bb858e6a 10666 return Z_PACKET_ACCESS_WP;
d471ea57
AC
10667 break;
10668 default:
8e65ff28 10669 internal_error (__FILE__, __LINE__,
e2e0b3e5 10670 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
10671 }
10672}
10673
f6ac5f3d
PA
10674int
10675remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10676 enum target_hw_bp_type type, struct expression *cond)
96baa820 10677{
d01949b6 10678 struct remote_state *rs = get_remote_state ();
8d64371b 10679 char *endbuf = rs->buf.data () + get_remote_packet_size ();
e514a9d6 10680 char *p;
d471ea57 10681 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 10682
4082afcc 10683 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 10684 return 1;
802188a7 10685
28439a30
PA
10686 /* Make sure the remote is pointing at the right process, if
10687 necessary. */
10688 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10689 set_general_process ();
10690
8d64371b
TT
10691 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10692 p = strchr (rs->buf.data (), '\0');
96baa820
JM
10693 addr = remote_address_masked (addr);
10694 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10695 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 10696
6d820c5c 10697 putpkt (rs->buf);
8d64371b 10698 getpkt (&rs->buf, 0);
96baa820 10699
6d820c5c 10700 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10701 {
10702 case PACKET_ERROR:
d471ea57 10703 return -1;
85d721b8
PA
10704 case PACKET_UNKNOWN:
10705 return 1;
d471ea57
AC
10706 case PACKET_OK:
10707 return 0;
10708 }
8e65ff28 10709 internal_error (__FILE__, __LINE__,
e2e0b3e5 10710 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
10711}
10712
57810aa7 10713bool
f6ac5f3d
PA
10714remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10715 CORE_ADDR start, int length)
283002cf
MR
10716{
10717 CORE_ADDR diff = remote_address_masked (addr - start);
10718
10719 return diff < length;
10720}
10721
d471ea57 10722
f6ac5f3d
PA
10723int
10724remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10725 enum target_hw_bp_type type, struct expression *cond)
96baa820 10726{
d01949b6 10727 struct remote_state *rs = get_remote_state ();
8d64371b 10728 char *endbuf = rs->buf.data () + get_remote_packet_size ();
e514a9d6 10729 char *p;
d471ea57
AC
10730 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10731
4082afcc 10732 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 10733 return -1;
802188a7 10734
28439a30
PA
10735 /* Make sure the remote is pointing at the right process, if
10736 necessary. */
10737 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10738 set_general_process ();
10739
8d64371b
TT
10740 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10741 p = strchr (rs->buf.data (), '\0');
96baa820
JM
10742 addr = remote_address_masked (addr);
10743 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10744 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c 10745 putpkt (rs->buf);
8d64371b 10746 getpkt (&rs->buf, 0);
96baa820 10747
6d820c5c 10748 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10749 {
10750 case PACKET_ERROR:
10751 case PACKET_UNKNOWN:
10752 return -1;
10753 case PACKET_OK:
10754 return 0;
10755 }
8e65ff28 10756 internal_error (__FILE__, __LINE__,
e2e0b3e5 10757 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
10758}
10759
3c3bea1c 10760
60fcc1c3
TT
10761static int remote_hw_watchpoint_limit = -1;
10762static int remote_hw_watchpoint_length_limit = -1;
10763static int remote_hw_breakpoint_limit = -1;
d471ea57 10764
f6ac5f3d
PA
10765int
10766remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
480a3f21
PW
10767{
10768 if (remote_hw_watchpoint_length_limit == 0)
10769 return 0;
10770 else if (remote_hw_watchpoint_length_limit < 0)
10771 return 1;
10772 else if (len <= remote_hw_watchpoint_length_limit)
10773 return 1;
10774 else
10775 return 0;
10776}
10777
f6ac5f3d
PA
10778int
10779remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
96baa820 10780{
3c3bea1c
GS
10781 if (type == bp_hardware_breakpoint)
10782 {
10783 if (remote_hw_breakpoint_limit == 0)
10784 return 0;
501eef12
AC
10785 else if (remote_hw_breakpoint_limit < 0)
10786 return 1;
3c3bea1c
GS
10787 else if (cnt <= remote_hw_breakpoint_limit)
10788 return 1;
10789 }
10790 else
10791 {
10792 if (remote_hw_watchpoint_limit == 0)
10793 return 0;
501eef12
AC
10794 else if (remote_hw_watchpoint_limit < 0)
10795 return 1;
3c3bea1c
GS
10796 else if (ot)
10797 return -1;
10798 else if (cnt <= remote_hw_watchpoint_limit)
10799 return 1;
10800 }
10801 return -1;
10802}
10803
f7e6eed5
PA
10804/* The to_stopped_by_sw_breakpoint method of target remote. */
10805
57810aa7 10806bool
f6ac5f3d 10807remote_target::stopped_by_sw_breakpoint ()
f7e6eed5 10808{
799a2abe 10809 struct thread_info *thread = inferior_thread ();
f7e6eed5 10810
799a2abe 10811 return (thread->priv != NULL
7aabaf9d
SM
10812 && (get_remote_thread_info (thread)->stop_reason
10813 == TARGET_STOPPED_BY_SW_BREAKPOINT));
f7e6eed5
PA
10814}
10815
10816/* The to_supports_stopped_by_sw_breakpoint method of target
10817 remote. */
10818
57810aa7 10819bool
f6ac5f3d 10820remote_target::supports_stopped_by_sw_breakpoint ()
f7e6eed5 10821{
f7e6eed5
PA
10822 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10823}
10824
10825/* The to_stopped_by_hw_breakpoint method of target remote. */
10826
57810aa7 10827bool
f6ac5f3d 10828remote_target::stopped_by_hw_breakpoint ()
f7e6eed5 10829{
799a2abe 10830 struct thread_info *thread = inferior_thread ();
f7e6eed5 10831
799a2abe 10832 return (thread->priv != NULL
7aabaf9d
SM
10833 && (get_remote_thread_info (thread)->stop_reason
10834 == TARGET_STOPPED_BY_HW_BREAKPOINT));
f7e6eed5
PA
10835}
10836
10837/* The to_supports_stopped_by_hw_breakpoint method of target
10838 remote. */
10839
57810aa7 10840bool
f6ac5f3d 10841remote_target::supports_stopped_by_hw_breakpoint ()
f7e6eed5 10842{
f7e6eed5
PA
10843 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10844}
10845
57810aa7 10846bool
f6ac5f3d 10847remote_target::stopped_by_watchpoint ()
3c3bea1c 10848{
799a2abe 10849 struct thread_info *thread = inferior_thread ();
ee154bee 10850
799a2abe 10851 return (thread->priv != NULL
7aabaf9d
SM
10852 && (get_remote_thread_info (thread)->stop_reason
10853 == TARGET_STOPPED_BY_WATCHPOINT));
3c3bea1c
GS
10854}
10855
57810aa7 10856bool
f6ac5f3d 10857remote_target::stopped_data_address (CORE_ADDR *addr_p)
3c3bea1c 10858{
799a2abe 10859 struct thread_info *thread = inferior_thread ();
a744cf53 10860
799a2abe 10861 if (thread->priv != NULL
7aabaf9d
SM
10862 && (get_remote_thread_info (thread)->stop_reason
10863 == TARGET_STOPPED_BY_WATCHPOINT))
4aa7a7f5 10864 {
7aabaf9d 10865 *addr_p = get_remote_thread_info (thread)->watch_data_address;
57810aa7 10866 return true;
4aa7a7f5
JJ
10867 }
10868
57810aa7 10869 return false;
3c3bea1c
GS
10870}
10871
10872
f6ac5f3d
PA
10873int
10874remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10875 struct bp_target_info *bp_tgt)
3c3bea1c 10876{
0d5ed153 10877 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10878 struct remote_state *rs;
bba74b36 10879 char *p, *endbuf;
dd61ec5c 10880 char *message;
3c3bea1c 10881
4082afcc 10882 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10883 return -1;
2bc416ba 10884
28439a30
PA
10885 /* Make sure the remote is pointing at the right process, if
10886 necessary. */
10887 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10888 set_general_process ();
10889
4fff2411 10890 rs = get_remote_state ();
8d64371b
TT
10891 p = rs->buf.data ();
10892 endbuf = p + get_remote_packet_size ();
4fff2411 10893
96baa820
JM
10894 *(p++) = 'Z';
10895 *(p++) = '1';
10896 *(p++) = ',';
802188a7 10897
0d5ed153 10898 addr = remote_address_masked (addr);
96baa820 10899 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10900 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10901
f6ac5f3d 10902 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10903 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10904
f6ac5f3d 10905 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10906 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10907
6d820c5c 10908 putpkt (rs->buf);
8d64371b 10909 getpkt (&rs->buf, 0);
96baa820 10910
6d820c5c 10911 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10912 {
10913 case PACKET_ERROR:
dd61ec5c 10914 if (rs->buf[1] == '.')
dda83cd7
SM
10915 {
10916 message = strchr (&rs->buf[2], '.');
10917 if (message)
10918 error (_("Remote failure reply: %s"), message + 1);
10919 }
dd61ec5c 10920 return -1;
d471ea57
AC
10921 case PACKET_UNKNOWN:
10922 return -1;
10923 case PACKET_OK:
10924 return 0;
10925 }
8e65ff28 10926 internal_error (__FILE__, __LINE__,
e2e0b3e5 10927 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
10928}
10929
d471ea57 10930
f6ac5f3d
PA
10931int
10932remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10933 struct bp_target_info *bp_tgt)
96baa820 10934{
8181d85f 10935 CORE_ADDR addr;
d01949b6 10936 struct remote_state *rs = get_remote_state ();
8d64371b
TT
10937 char *p = rs->buf.data ();
10938 char *endbuf = p + get_remote_packet_size ();
c8189ed1 10939
4082afcc 10940 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10941 return -1;
802188a7 10942
28439a30
PA
10943 /* Make sure the remote is pointing at the right process, if
10944 necessary. */
10945 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10946 set_general_process ();
10947
96baa820
JM
10948 *(p++) = 'z';
10949 *(p++) = '1';
10950 *(p++) = ',';
802188a7 10951
8181d85f 10952 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 10953 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10954 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10955
6d820c5c 10956 putpkt (rs->buf);
8d64371b 10957 getpkt (&rs->buf, 0);
802188a7 10958
6d820c5c 10959 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10960 {
10961 case PACKET_ERROR:
10962 case PACKET_UNKNOWN:
10963 return -1;
10964 case PACKET_OK:
10965 return 0;
10966 }
8e65ff28 10967 internal_error (__FILE__, __LINE__,
e2e0b3e5 10968 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 10969}
96baa820 10970
4a5e7a5b
PA
10971/* Verify memory using the "qCRC:" request. */
10972
f6ac5f3d
PA
10973int
10974remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
4a5e7a5b
PA
10975{
10976 struct remote_state *rs = get_remote_state ();
10977 unsigned long host_crc, target_crc;
10978 char *tmp;
10979
936d2992
PA
10980 /* It doesn't make sense to use qCRC if the remote target is
10981 connected but not running. */
55f6301a
TT
10982 if (target_has_execution ()
10983 && packet_support (PACKET_qCRC) != PACKET_DISABLE)
936d2992
PA
10984 {
10985 enum packet_result result;
28439a30 10986
936d2992
PA
10987 /* Make sure the remote is pointing at the right process. */
10988 set_general_process ();
4a5e7a5b 10989
936d2992 10990 /* FIXME: assumes lma can fit into long. */
8d64371b 10991 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
936d2992
PA
10992 (long) lma, (long) size);
10993 putpkt (rs->buf);
4a5e7a5b 10994
936d2992
PA
10995 /* Be clever; compute the host_crc before waiting for target
10996 reply. */
10997 host_crc = xcrc32 (data, size, 0xffffffff);
10998
8d64371b 10999 getpkt (&rs->buf, 0);
4a5e7a5b 11000
936d2992
PA
11001 result = packet_ok (rs->buf,
11002 &remote_protocol_packets[PACKET_qCRC]);
11003 if (result == PACKET_ERROR)
11004 return -1;
11005 else if (result == PACKET_OK)
11006 {
11007 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11008 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 11009
936d2992
PA
11010 return (host_crc == target_crc);
11011 }
11012 }
4a5e7a5b 11013
f6ac5f3d 11014 return simple_verify_memory (this, data, lma, size);
4a5e7a5b
PA
11015}
11016
c906108c
SS
11017/* compare-sections command
11018
11019 With no arguments, compares each loadable section in the exec bfd
11020 with the same memory range on the target, and reports mismatches.
4a5e7a5b 11021 Useful for verifying the image on the target against the exec file. */
e514a9d6 11022
c906108c 11023static void
ac88e2de 11024compare_sections_command (const char *args, int from_tty)
c906108c
SS
11025{
11026 asection *s;
ce359b09 11027 const char *sectname;
c906108c
SS
11028 bfd_size_type size;
11029 bfd_vma lma;
11030 int matched = 0;
11031 int mismatched = 0;
4a5e7a5b 11032 int res;
95cf3b38 11033 int read_only = 0;
c906108c 11034
7e10abd1 11035 if (!current_program_space->exec_bfd ())
8a3fe4f8 11036 error (_("command cannot be used without an exec file"));
c906108c 11037
95cf3b38
DT
11038 if (args != NULL && strcmp (args, "-r") == 0)
11039 {
11040 read_only = 1;
11041 args = NULL;
11042 }
11043
7e10abd1 11044 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
c906108c
SS
11045 {
11046 if (!(s->flags & SEC_LOAD))
0df8b418 11047 continue; /* Skip non-loadable section. */
c906108c 11048
95cf3b38
DT
11049 if (read_only && (s->flags & SEC_READONLY) == 0)
11050 continue; /* Skip writeable sections */
11051
fd361982 11052 size = bfd_section_size (s);
c906108c 11053 if (size == 0)
0df8b418 11054 continue; /* Skip zero-length section. */
c906108c 11055
fd361982 11056 sectname = bfd_section_name (s);
c906108c 11057 if (args && strcmp (args, sectname) != 0)
0df8b418 11058 continue; /* Not the section selected by user. */
c906108c 11059
0df8b418 11060 matched = 1; /* Do this section. */
c906108c 11061 lma = s->lma;
c906108c 11062
b80406ac 11063 gdb::byte_vector sectdata (size);
7e10abd1
TT
11064 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11065 sectdata.data (), 0, size);
c906108c 11066
b80406ac 11067 res = target_verify_memory (sectdata.data (), lma, size);
4a5e7a5b
PA
11068
11069 if (res == -1)
5af949e3 11070 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
11071 paddress (target_gdbarch (), lma),
11072 paddress (target_gdbarch (), lma + size));
c906108c 11073
6cb06a8c
TT
11074 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11075 paddress (target_gdbarch (), lma),
11076 paddress (target_gdbarch (), lma + size));
4a5e7a5b 11077 if (res)
6cb06a8c 11078 gdb_printf ("matched.\n");
c906108c 11079 else
c5aa993b 11080 {
6cb06a8c 11081 gdb_printf ("MIS-MATCHED!\n");
c5aa993b
JM
11082 mismatched++;
11083 }
c906108c
SS
11084 }
11085 if (mismatched > 0)
936d2992 11086 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 11087the loaded file\n"));
c906108c 11088 if (args && !matched)
6cb06a8c 11089 gdb_printf (_("No loaded section named '%s'.\n"), args);
c906108c
SS
11090}
11091
0e7f50da
UW
11092/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11093 into remote target. The number of bytes written to the remote
11094 target is returned, or -1 for error. */
11095
6b8edb51
PA
11096target_xfer_status
11097remote_target::remote_write_qxfer (const char *object_name,
11098 const char *annex, const gdb_byte *writebuf,
11099 ULONGEST offset, LONGEST len,
11100 ULONGEST *xfered_len,
11101 struct packet_config *packet)
0e7f50da
UW
11102{
11103 int i, buf_len;
11104 ULONGEST n;
0e7f50da
UW
11105 struct remote_state *rs = get_remote_state ();
11106 int max_size = get_memory_write_packet_size ();
11107
7cc244de 11108 if (packet_config_support (packet) == PACKET_DISABLE)
2ed4b548 11109 return TARGET_XFER_E_IO;
0e7f50da
UW
11110
11111 /* Insert header. */
8d64371b 11112 i = snprintf (rs->buf.data (), max_size,
0e7f50da
UW
11113 "qXfer:%s:write:%s:%s:",
11114 object_name, annex ? annex : "",
11115 phex_nz (offset, sizeof offset));
11116 max_size -= (i + 1);
11117
11118 /* Escape as much data as fits into rs->buf. */
11119 buf_len = remote_escape_output
8d64371b 11120 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
0e7f50da 11121
8d64371b
TT
11122 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11123 || getpkt_sane (&rs->buf, 0) < 0
0e7f50da 11124 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 11125 return TARGET_XFER_E_IO;
0e7f50da 11126
8d64371b 11127 unpack_varlen_hex (rs->buf.data (), &n);
9b409511
YQ
11128
11129 *xfered_len = n;
92ffd475 11130 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
0e7f50da
UW
11131}
11132
0876f84a
DJ
11133/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11134 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11135 number of bytes read is returned, or 0 for EOF, or -1 for error.
11136 The number of bytes read may be less than LEN without indicating an
11137 EOF. PACKET is checked and updated to indicate whether the remote
11138 target supports this object. */
11139
6b8edb51
PA
11140target_xfer_status
11141remote_target::remote_read_qxfer (const char *object_name,
11142 const char *annex,
11143 gdb_byte *readbuf, ULONGEST offset,
11144 LONGEST len,
11145 ULONGEST *xfered_len,
11146 struct packet_config *packet)
0876f84a 11147{
0876f84a 11148 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
11149 LONGEST i, n, packet_len;
11150
7cc244de 11151 if (packet_config_support (packet) == PACKET_DISABLE)
2ed4b548 11152 return TARGET_XFER_E_IO;
0876f84a
DJ
11153
11154 /* Check whether we've cached an end-of-object packet that matches
11155 this request. */
8e88304f 11156 if (rs->finished_object)
0876f84a 11157 {
8e88304f
TT
11158 if (strcmp (object_name, rs->finished_object) == 0
11159 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11160 && offset == rs->finished_offset)
9b409511
YQ
11161 return TARGET_XFER_EOF;
11162
0876f84a
DJ
11163
11164 /* Otherwise, we're now reading something different. Discard
11165 the cache. */
8e88304f
TT
11166 xfree (rs->finished_object);
11167 xfree (rs->finished_annex);
11168 rs->finished_object = NULL;
11169 rs->finished_annex = NULL;
0876f84a
DJ
11170 }
11171
11172 /* Request only enough to fit in a single packet. The actual data
11173 may not, since we don't know how much of it will need to be escaped;
11174 the target is free to respond with slightly less data. We subtract
11175 five to account for the response type and the protocol frame. */
768adc05 11176 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
8d64371b
TT
11177 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11178 "qXfer:%s:read:%s:%s,%s",
0876f84a
DJ
11179 object_name, annex ? annex : "",
11180 phex_nz (offset, sizeof offset),
11181 phex_nz (n, sizeof n));
11182 i = putpkt (rs->buf);
11183 if (i < 0)
2ed4b548 11184 return TARGET_XFER_E_IO;
0876f84a
DJ
11185
11186 rs->buf[0] = '\0';
8d64371b 11187 packet_len = getpkt_sane (&rs->buf, 0);
0876f84a 11188 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 11189 return TARGET_XFER_E_IO;
0876f84a
DJ
11190
11191 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8d64371b 11192 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
0876f84a
DJ
11193
11194 /* 'm' means there is (or at least might be) more data after this
11195 batch. That does not make sense unless there's at least one byte
11196 of data in this reply. */
11197 if (rs->buf[0] == 'm' && packet_len == 1)
11198 error (_("Remote qXfer reply contained no data."));
11199
11200 /* Got some data. */
8d64371b 11201 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
bc20a4af 11202 packet_len - 1, readbuf, n);
0876f84a
DJ
11203
11204 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
11205 or possibly empty. If we have the final block of a non-empty
11206 object, record this fact to bypass a subsequent partial read. */
11207 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 11208 {
8e88304f
TT
11209 rs->finished_object = xstrdup (object_name);
11210 rs->finished_annex = xstrdup (annex ? annex : "");
11211 rs->finished_offset = offset + i;
0876f84a
DJ
11212 }
11213
9b409511
YQ
11214 if (i == 0)
11215 return TARGET_XFER_EOF;
11216 else
11217 {
11218 *xfered_len = i;
11219 return TARGET_XFER_OK;
11220 }
0876f84a
DJ
11221}
11222
f6ac5f3d
PA
11223enum target_xfer_status
11224remote_target::xfer_partial (enum target_object object,
11225 const char *annex, gdb_byte *readbuf,
11226 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11227 ULONGEST *xfered_len)
c906108c 11228{
82f73884 11229 struct remote_state *rs;
c906108c 11230 int i;
6d820c5c 11231 char *p2;
1e3ff5ad 11232 char query_type;
124e13d9 11233 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 11234
e6e4e701 11235 set_remote_traceframe ();
82f73884
PA
11236 set_general_thread (inferior_ptid);
11237
11238 rs = get_remote_state ();
11239
b2182ed2 11240 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
11241 if (object == TARGET_OBJECT_MEMORY)
11242 {
2d717e4f
DJ
11243 /* If the remote target is connected but not running, we should
11244 pass this request down to a lower stratum (e.g. the executable
11245 file). */
55f6301a 11246 if (!target_has_execution ())
9b409511 11247 return TARGET_XFER_EOF;
2d717e4f 11248
21e3b9b9 11249 if (writebuf != NULL)
124e13d9
SM
11250 return remote_write_bytes (offset, writebuf, len, unit_size,
11251 xfered_len);
21e3b9b9 11252 else
6b8edb51 11253 return remote_read_bytes (offset, readbuf, len, unit_size,
124e13d9 11254 xfered_len);
21e3b9b9
DJ
11255 }
11256
4aa995e1
PA
11257 /* Handle extra signal info using qxfer packets. */
11258 if (object == TARGET_OBJECT_SIGNAL_INFO)
11259 {
11260 if (readbuf)
f6ac5f3d 11261 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
9b409511 11262 xfered_len, &remote_protocol_packets
4aa995e1
PA
11263 [PACKET_qXfer_siginfo_read]);
11264 else
f6ac5f3d 11265 return remote_write_qxfer ("siginfo", annex,
9b409511 11266 writebuf, offset, len, xfered_len,
4aa995e1
PA
11267 &remote_protocol_packets
11268 [PACKET_qXfer_siginfo_write]);
11269 }
11270
0fb4aa4b
PA
11271 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11272 {
11273 if (readbuf)
f6ac5f3d 11274 return remote_read_qxfer ("statictrace", annex,
9b409511 11275 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
11276 &remote_protocol_packets
11277 [PACKET_qXfer_statictrace_read]);
11278 else
2ed4b548 11279 return TARGET_XFER_E_IO;
0fb4aa4b
PA
11280 }
11281
a76d924d
DJ
11282 /* Only handle flash writes. */
11283 if (writebuf != NULL)
11284 {
a76d924d
DJ
11285 switch (object)
11286 {
11287 case TARGET_OBJECT_FLASH:
6b8edb51 11288 return remote_flash_write (offset, len, xfered_len,
9b409511 11289 writebuf);
a76d924d
DJ
11290
11291 default:
2ed4b548 11292 return TARGET_XFER_E_IO;
a76d924d
DJ
11293 }
11294 }
4b8a223f 11295
1e3ff5ad
AC
11296 /* Map pre-existing objects onto letters. DO NOT do this for new
11297 objects!!! Instead specify new query packets. */
11298 switch (object)
c906108c 11299 {
1e3ff5ad
AC
11300 case TARGET_OBJECT_AVR:
11301 query_type = 'R';
11302 break;
802188a7
RM
11303
11304 case TARGET_OBJECT_AUXV:
0876f84a 11305 gdb_assert (annex == NULL);
f6ac5f3d 11306 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
9b409511 11307 xfered_len,
0876f84a 11308 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 11309
23181151
DJ
11310 case TARGET_OBJECT_AVAILABLE_FEATURES:
11311 return remote_read_qxfer
f6ac5f3d 11312 ("features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
11313 &remote_protocol_packets[PACKET_qXfer_features]);
11314
cfa9d6d9
DJ
11315 case TARGET_OBJECT_LIBRARIES:
11316 return remote_read_qxfer
f6ac5f3d 11317 ("libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
11318 &remote_protocol_packets[PACKET_qXfer_libraries]);
11319
2268b414
JK
11320 case TARGET_OBJECT_LIBRARIES_SVR4:
11321 return remote_read_qxfer
f6ac5f3d 11322 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
11323 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
11324
fd79ecee
DJ
11325 case TARGET_OBJECT_MEMORY_MAP:
11326 gdb_assert (annex == NULL);
f6ac5f3d 11327 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
9b409511 11328 xfered_len,
fd79ecee
DJ
11329 &remote_protocol_packets[PACKET_qXfer_memory_map]);
11330
07e059b5
VP
11331 case TARGET_OBJECT_OSDATA:
11332 /* Should only get here if we're connected. */
5d93a237 11333 gdb_assert (rs->remote_desc);
07e059b5 11334 return remote_read_qxfer
f6ac5f3d 11335 ("osdata", annex, readbuf, offset, len, xfered_len,
dda83cd7 11336 &remote_protocol_packets[PACKET_qXfer_osdata]);
07e059b5 11337
dc146f7c
VP
11338 case TARGET_OBJECT_THREADS:
11339 gdb_assert (annex == NULL);
f6ac5f3d 11340 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
9b409511 11341 xfered_len,
dc146f7c
VP
11342 &remote_protocol_packets[PACKET_qXfer_threads]);
11343
b3b9301e
PA
11344 case TARGET_OBJECT_TRACEFRAME_INFO:
11345 gdb_assert (annex == NULL);
11346 return remote_read_qxfer
f6ac5f3d 11347 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 11348 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
11349
11350 case TARGET_OBJECT_FDPIC:
f6ac5f3d 11351 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
9b409511 11352 xfered_len,
78d85199 11353 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
11354
11355 case TARGET_OBJECT_OPENVMS_UIB:
f6ac5f3d 11356 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
9b409511 11357 xfered_len,
169081d0
TG
11358 &remote_protocol_packets[PACKET_qXfer_uib]);
11359
9accd112 11360 case TARGET_OBJECT_BTRACE:
f6ac5f3d 11361 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
9b409511 11362 xfered_len,
dda83cd7 11363 &remote_protocol_packets[PACKET_qXfer_btrace]);
9accd112 11364
f4abbc16 11365 case TARGET_OBJECT_BTRACE_CONF:
f6ac5f3d 11366 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
f4abbc16
MM
11367 len, xfered_len,
11368 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11369
c78fa86a 11370 case TARGET_OBJECT_EXEC_FILE:
f6ac5f3d 11371 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
c78fa86a
GB
11372 len, xfered_len,
11373 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11374
1e3ff5ad 11375 default:
2ed4b548 11376 return TARGET_XFER_E_IO;
c906108c
SS
11377 }
11378
0df8b418 11379 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 11380 large enough let the caller deal with it. */
ea9c271d 11381 if (len < get_remote_packet_size ())
2ed4b548 11382 return TARGET_XFER_E_IO;
ea9c271d 11383 len = get_remote_packet_size ();
1e3ff5ad 11384
23860348 11385 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 11386 if (!rs->remote_desc)
8a3fe4f8 11387 error (_("remote query is only available after target open"));
c906108c 11388
1e3ff5ad 11389 gdb_assert (annex != NULL);
4b8a223f 11390 gdb_assert (readbuf != NULL);
c906108c 11391
8d64371b 11392 p2 = rs->buf.data ();
c906108c
SS
11393 *p2++ = 'q';
11394 *p2++ = query_type;
11395
23860348
MS
11396 /* We used one buffer char for the remote protocol q command and
11397 another for the query type. As the remote protocol encapsulation
11398 uses 4 chars plus one extra in case we are debugging
11399 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11400 string. */
c906108c 11401 i = 0;
ea9c271d 11402 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 11403 {
1e3ff5ad
AC
11404 /* Bad caller may have sent forbidden characters. */
11405 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11406 *p2++ = annex[i];
c906108c
SS
11407 i++;
11408 }
1e3ff5ad
AC
11409 *p2 = '\0';
11410 gdb_assert (annex[i] == '\0');
c906108c 11411
6d820c5c 11412 i = putpkt (rs->buf);
c5aa993b 11413 if (i < 0)
2ed4b548 11414 return TARGET_XFER_E_IO;
c906108c 11415
8d64371b
TT
11416 getpkt (&rs->buf, 0);
11417 strcpy ((char *) readbuf, rs->buf.data ());
c906108c 11418
9b409511 11419 *xfered_len = strlen ((char *) readbuf);
92ffd475 11420 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
11421}
11422
09c98b44
DB
11423/* Implementation of to_get_memory_xfer_limit. */
11424
f6ac5f3d
PA
11425ULONGEST
11426remote_target::get_memory_xfer_limit ()
09c98b44
DB
11427{
11428 return get_memory_write_packet_size ();
11429}
11430
f6ac5f3d
PA
11431int
11432remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11433 const gdb_byte *pattern, ULONGEST pattern_len,
11434 CORE_ADDR *found_addrp)
08388c79 11435{
f5656ead 11436 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
11437 struct remote_state *rs = get_remote_state ();
11438 int max_size = get_memory_write_packet_size ();
11439 struct packet_config *packet =
11440 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
11441 /* Number of packet bytes used to encode the pattern;
11442 this could be more than PATTERN_LEN due to escape characters. */
08388c79 11443 int escaped_pattern_len;
0df8b418 11444 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
11445 int used_pattern_len;
11446 int i;
11447 int found;
11448 ULONGEST found_addr;
11449
4a72de73
TT
11450 auto read_memory = [=] (CORE_ADDR addr, gdb_byte *result, size_t len)
11451 {
11452 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11453 == len);
11454 };
11455
7cc244de
PA
11456 /* Don't go to the target if we don't have to. This is done before
11457 checking packet_config_support to avoid the possibility that a
11458 success for this edge case means the facility works in
11459 general. */
08388c79
DE
11460 if (pattern_len > search_space_len)
11461 return 0;
11462 if (pattern_len == 0)
11463 {
11464 *found_addrp = start_addr;
11465 return 1;
11466 }
11467
11468 /* If we already know the packet isn't supported, fall back to the simple
11469 way of searching memory. */
11470
4082afcc 11471 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
11472 {
11473 /* Target doesn't provided special support, fall back and use the
11474 standard support (copy memory and do the search here). */
4a72de73 11475 return simple_search_memory (read_memory, start_addr, search_space_len,
08388c79
DE
11476 pattern, pattern_len, found_addrp);
11477 }
11478
28439a30
PA
11479 /* Make sure the remote is pointing at the right process. */
11480 set_general_process ();
11481
08388c79 11482 /* Insert header. */
8d64371b 11483 i = snprintf (rs->buf.data (), max_size,
08388c79 11484 "qSearch:memory:%s;%s;",
5af949e3 11485 phex_nz (start_addr, addr_size),
08388c79
DE
11486 phex_nz (search_space_len, sizeof (search_space_len)));
11487 max_size -= (i + 1);
11488
11489 /* Escape as much data as fits into rs->buf. */
11490 escaped_pattern_len =
8d64371b
TT
11491 remote_escape_output (pattern, pattern_len, 1,
11492 (gdb_byte *) rs->buf.data () + i,
08388c79
DE
11493 &used_pattern_len, max_size);
11494
11495 /* Bail if the pattern is too large. */
11496 if (used_pattern_len != pattern_len)
9b20d036 11497 error (_("Pattern is too large to transmit to remote target."));
08388c79 11498
8d64371b
TT
11499 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11500 || getpkt_sane (&rs->buf, 0) < 0
08388c79
DE
11501 || packet_ok (rs->buf, packet) != PACKET_OK)
11502 {
11503 /* The request may not have worked because the command is not
11504 supported. If so, fall back to the simple way. */
7cc244de 11505 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79 11506 {
4a72de73 11507 return simple_search_memory (read_memory, start_addr, search_space_len,
08388c79
DE
11508 pattern, pattern_len, found_addrp);
11509 }
11510 return -1;
11511 }
11512
11513 if (rs->buf[0] == '0')
11514 found = 0;
11515 else if (rs->buf[0] == '1')
11516 {
11517 found = 1;
11518 if (rs->buf[1] != ',')
8d64371b
TT
11519 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11520 unpack_varlen_hex (&rs->buf[2], &found_addr);
08388c79
DE
11521 *found_addrp = found_addr;
11522 }
11523 else
8d64371b 11524 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
08388c79
DE
11525
11526 return found;
11527}
11528
f6ac5f3d
PA
11529void
11530remote_target::rcmd (const char *command, struct ui_file *outbuf)
96baa820 11531{
d01949b6 11532 struct remote_state *rs = get_remote_state ();
8d64371b 11533 char *p = rs->buf.data ();
96baa820 11534
5d93a237 11535 if (!rs->remote_desc)
8a3fe4f8 11536 error (_("remote rcmd is only available after target open"));
96baa820 11537
23860348 11538 /* Send a NULL command across as an empty command. */
7be570e7
JM
11539 if (command == NULL)
11540 command = "";
11541
23860348 11542 /* The query prefix. */
8d64371b
TT
11543 strcpy (rs->buf.data (), "qRcmd,");
11544 p = strchr (rs->buf.data (), '\0');
96baa820 11545
8d64371b 11546 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
3e43a32a 11547 > get_remote_packet_size ())
8a3fe4f8 11548 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 11549
23860348 11550 /* Encode the actual command. */
a30bf1f1 11551 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 11552
6d820c5c 11553 if (putpkt (rs->buf) < 0)
8a3fe4f8 11554 error (_("Communication problem with target."));
96baa820
JM
11555
11556 /* get/display the response */
11557 while (1)
11558 {
2e9f7625
DJ
11559 char *buf;
11560
00bf0b85 11561 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 11562 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 11563 rs->buf[0] = '\0';
8d64371b 11564 if (getpkt_sane (&rs->buf, 0) == -1)
dda83cd7
SM
11565 {
11566 /* Timeout. Continue to (try to) read responses.
11567 This is better than stopping with an error, assuming the stub
11568 is still executing the (long) monitor command.
11569 If needed, the user can interrupt gdb using C-c, obtaining
11570 an effect similar to stop on timeout. */
11571 continue;
11572 }
8d64371b 11573 buf = rs->buf.data ();
96baa820 11574 if (buf[0] == '\0')
8a3fe4f8 11575 error (_("Target does not support this command."));
96baa820
JM
11576 if (buf[0] == 'O' && buf[1] != 'K')
11577 {
23860348 11578 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
11579 continue;
11580 }
11581 if (strcmp (buf, "OK") == 0)
11582 break;
7be570e7 11583 if (strlen (buf) == 3 && buf[0] == 'E'
d5ce6f2d 11584 && isxdigit (buf[1]) && isxdigit (buf[2]))
7be570e7 11585 {
8a3fe4f8 11586 error (_("Protocol error with Rcmd"));
7be570e7 11587 }
96baa820
JM
11588 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11589 {
11590 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 11591
a11ac3b3 11592 gdb_putc (c, outbuf);
96baa820
JM
11593 }
11594 break;
11595 }
11596}
11597
f6ac5f3d
PA
11598std::vector<mem_region>
11599remote_target::memory_map ()
fd79ecee 11600{
a664f67e 11601 std::vector<mem_region> result;
9018be22 11602 gdb::optional<gdb::char_vector> text
328d42d8
SM
11603 = target_read_stralloc (current_inferior ()->top_target (),
11604 TARGET_OBJECT_MEMORY_MAP, NULL);
fd79ecee
DJ
11605
11606 if (text)
9018be22 11607 result = parse_memory_map (text->data ());
fd79ecee
DJ
11608
11609 return result;
11610}
11611
e5b176f2
AB
11612/* Set of callbacks used to implement the 'maint packet' command. */
11613
11614struct cli_packet_command_callbacks : public send_remote_packet_callbacks
c906108c 11615{
e5b176f2
AB
11616 /* Called before the packet is sent. BUF is the packet content before
11617 the protocol specific prefix, suffix, and escaping is added. */
c906108c 11618
e5b176f2
AB
11619 void sending (gdb::array_view<const char> &buf) override
11620 {
0426ad51 11621 gdb_puts ("sending: ");
e5b176f2 11622 print_packet (buf);
0426ad51 11623 gdb_puts ("\n");
e5b176f2 11624 }
c906108c 11625
e5b176f2
AB
11626 /* Called with BUF, the reply from the remote target. */
11627
11628 void received (gdb::array_view<const char> &buf) override
11629 {
0426ad51 11630 gdb_puts ("received: \"");
e5b176f2 11631 print_packet (buf);
0426ad51 11632 gdb_puts ("\"\n");
e5b176f2
AB
11633 }
11634
11635private:
11636
11637 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11638 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11639
11640 static void
11641 print_packet (gdb::array_view<const char> &buf)
11642 {
11643 string_file stb;
11644
11645 for (int i = 0; i < buf.size (); ++i)
11646 {
11647 gdb_byte c = buf[i];
11648 if (isprint (c))
a11ac3b3 11649 gdb_putc (c, &stb);
e5b176f2 11650 else
6cb06a8c 11651 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
e5b176f2
AB
11652 }
11653
0426ad51 11654 gdb_puts (stb.string ().c_str ());
e5b176f2
AB
11655 }
11656};
11657
11658/* See remote.h. */
6b8edb51
PA
11659
11660void
e5b176f2
AB
11661send_remote_packet (gdb::array_view<const char> &buf,
11662 send_remote_packet_callbacks *callbacks)
6b8edb51 11663{
e5b176f2
AB
11664 if (buf.size () == 0 || buf.data ()[0] == '\0')
11665 error (_("a remote packet must not be empty"));
c906108c 11666
e5b176f2
AB
11667 remote_target *remote = get_current_remote_target ();
11668 if (remote == nullptr)
11669 error (_("packets can only be sent to a remote target"));
c906108c 11670
e5b176f2 11671 callbacks->sending (buf);
6b8edb51 11672
e5b176f2
AB
11673 remote->putpkt_binary (buf.data (), buf.size ());
11674 remote_state *rs = remote->get_remote_state ();
11675 int bytes = remote->getpkt_sane (&rs->buf, 0);
11676
11677 if (bytes < 0)
11678 error (_("error while fetching packet from remote target"));
11679
11680 gdb::array_view<const char> view (&rs->buf[0], bytes);
11681 callbacks->received (view);
11682}
11683
11684/* Entry point for the 'maint packet' command. */
11685
11686static void
11687cli_packet_command (const char *args, int from_tty)
11688{
11689 cli_packet_command_callbacks cb;
11690 gdb::array_view<const char> view
11691 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11692 send_remote_packet (view, &cb);
c906108c
SS
11693}
11694
11695#if 0
23860348 11696/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 11697
a14ed312 11698static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 11699
a14ed312 11700static void threadset_test_cmd (char *cmd, int tty);
c906108c 11701
a14ed312 11702static void threadalive_test (char *cmd, int tty);
c906108c 11703
a14ed312 11704static void threadlist_test_cmd (char *cmd, int tty);
c906108c 11705
23860348 11706int get_and_display_threadinfo (threadref *ref);
c906108c 11707
a14ed312 11708static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 11709
23860348 11710static int thread_display_step (threadref *ref, void *context);
c906108c 11711
a14ed312 11712static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 11713
a14ed312 11714static void init_remote_threadtests (void);
c906108c 11715
23860348 11716#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
11717
11718static void
0b39b52e 11719threadset_test_cmd (const char *cmd, int tty)
c906108c
SS
11720{
11721 int sample_thread = SAMPLE_THREAD;
11722
6cb06a8c 11723 gdb_printf (_("Remote threadset test\n"));
79d7f229 11724 set_general_thread (sample_thread);
c906108c
SS
11725}
11726
11727
11728static void
0b39b52e 11729threadalive_test (const char *cmd, int tty)
c906108c
SS
11730{
11731 int sample_thread = SAMPLE_THREAD;
e99b03dc 11732 int pid = inferior_ptid.pid ();
fd79271b 11733 ptid_t ptid = ptid_t (pid, sample_thread, 0);
c906108c 11734
79d7f229 11735 if (remote_thread_alive (ptid))
6cb06a8c 11736 gdb_printf ("PASS: Thread alive test\n");
c906108c 11737 else
6cb06a8c 11738 gdb_printf ("FAIL: Thread alive test\n");
c906108c
SS
11739}
11740
23860348 11741void output_threadid (char *title, threadref *ref);
c906108c
SS
11742
11743void
fba45db2 11744output_threadid (char *title, threadref *ref)
c906108c
SS
11745{
11746 char hexid[20];
11747
405feb71 11748 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
c906108c 11749 hexid[16] = 0;
6cb06a8c 11750 gdb_printf ("%s %s\n", title, (&hexid[0]));
c906108c
SS
11751}
11752
11753static void
0b39b52e 11754threadlist_test_cmd (const char *cmd, int tty)
c906108c
SS
11755{
11756 int startflag = 1;
11757 threadref nextthread;
11758 int done, result_count;
11759 threadref threadlist[3];
11760
6cb06a8c 11761 gdb_printf ("Remote Threadlist test\n");
c906108c
SS
11762 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11763 &result_count, &threadlist[0]))
6cb06a8c 11764 gdb_printf ("FAIL: threadlist test\n");
c906108c
SS
11765 else
11766 {
11767 threadref *scan = threadlist;
11768 threadref *limit = scan + result_count;
11769
11770 while (scan < limit)
11771 output_threadid (" thread ", scan++);
11772 }
11773}
11774
11775void
fba45db2 11776display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
11777{
11778 output_threadid ("Threadid: ", &info->threadid);
6cb06a8c
TT
11779 gdb_printf ("Name: %s\n ", info->shortname);
11780 gdb_printf ("State: %s\n", info->display);
11781 gdb_printf ("other: %s\n\n", info->more_display);
c906108c
SS
11782}
11783
11784int
fba45db2 11785get_and_display_threadinfo (threadref *ref)
c906108c
SS
11786{
11787 int result;
11788 int set;
11789 struct gdb_ext_thread_info threadinfo;
11790
11791 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11792 | TAG_MOREDISPLAY | TAG_DISPLAY;
11793 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11794 display_thread_info (&threadinfo);
11795 return result;
11796}
11797
11798static void
0b39b52e 11799threadinfo_test_cmd (const char *cmd, int tty)
c906108c
SS
11800{
11801 int athread = SAMPLE_THREAD;
11802 threadref thread;
11803 int set;
11804
11805 int_to_threadref (&thread, athread);
6cb06a8c 11806 gdb_printf ("Remote Threadinfo test\n");
c906108c 11807 if (!get_and_display_threadinfo (&thread))
6cb06a8c 11808 gdb_printf ("FAIL cannot get thread info\n");
c906108c
SS
11809}
11810
11811static int
fba45db2 11812thread_display_step (threadref *ref, void *context)
c906108c
SS
11813{
11814 /* output_threadid(" threadstep ",ref); *//* simple test */
11815 return get_and_display_threadinfo (ref);
11816}
11817
11818static void
0b39b52e 11819threadlist_update_test_cmd (const char *cmd, int tty)
c906108c 11820{
6cb06a8c 11821 gdb_printf ("Remote Threadlist update test\n");
c906108c
SS
11822 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11823}
11824
11825static void
11826init_remote_threadtests (void)
11827{
3e43a32a
MS
11828 add_com ("tlist", class_obscure, threadlist_test_cmd,
11829 _("Fetch and print the remote list of "
590042fc 11830 "thread identifiers, one pkt only."));
c906108c 11831 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
590042fc 11832 _("Fetch and display info about one thread."));
c906108c 11833 add_com ("tset", class_obscure, threadset_test_cmd,
590042fc 11834 _("Test setting to a different thread."));
c906108c 11835 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
590042fc 11836 _("Iterate through updating all remote thread info."));
c906108c 11837 add_com ("talive", class_obscure, threadalive_test,
590042fc 11838 _("Remote thread alive test."));
c906108c
SS
11839}
11840
11841#endif /* 0 */
11842
a068643d 11843/* Convert a thread ID to a string. */
f3fb8c85 11844
a068643d 11845std::string
f6ac5f3d 11846remote_target::pid_to_str (ptid_t ptid)
f3fb8c85 11847{
82f73884 11848 struct remote_state *rs = get_remote_state ();
f3fb8c85 11849
d7e15655 11850 if (ptid == null_ptid)
7cee1e54 11851 return normal_pid_to_str (ptid);
0e998d96 11852 else if (ptid.is_pid ())
ecd0ada5
PA
11853 {
11854 /* Printing an inferior target id. */
11855
11856 /* When multi-process extensions are off, there's no way in the
11857 remote protocol to know the remote process id, if there's any
11858 at all. There's one exception --- when we're connected with
11859 target extended-remote, and we manually attached to a process
11860 with "attach PID". We don't record anywhere a flag that
11861 allows us to distinguish that case from the case of
11862 connecting with extended-remote and the stub already being
11863 attached to a process, and reporting yes to qAttached, hence
11864 no smart special casing here. */
11865 if (!remote_multi_process_p (rs))
a068643d 11866 return "Remote target";
ecd0ada5
PA
11867
11868 return normal_pid_to_str (ptid);
82f73884 11869 }
ecd0ada5 11870 else
79d7f229 11871 {
d7e15655 11872 if (magic_null_ptid == ptid)
a068643d 11873 return "Thread <main>";
8020350c 11874 else if (remote_multi_process_p (rs))
e38504b3 11875 if (ptid.lwp () == 0)
de0d863e
DB
11876 return normal_pid_to_str (ptid);
11877 else
a068643d
TT
11878 return string_printf ("Thread %d.%ld",
11879 ptid.pid (), ptid.lwp ());
ecd0ada5 11880 else
a068643d 11881 return string_printf ("Thread %ld", ptid.lwp ());
79d7f229 11882 }
f3fb8c85
MS
11883}
11884
38691318
KB
11885/* Get the address of the thread local variable in OBJFILE which is
11886 stored at OFFSET within the thread local storage for thread PTID. */
11887
f6ac5f3d
PA
11888CORE_ADDR
11889remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11890 CORE_ADDR offset)
38691318 11891{
4082afcc 11892 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
11893 {
11894 struct remote_state *rs = get_remote_state ();
8d64371b
TT
11895 char *p = rs->buf.data ();
11896 char *endp = p + get_remote_packet_size ();
571dd617 11897 enum packet_result result;
38691318
KB
11898
11899 strcpy (p, "qGetTLSAddr:");
11900 p += strlen (p);
82f73884 11901 p = write_ptid (p, endp, ptid);
38691318
KB
11902 *p++ = ',';
11903 p += hexnumstr (p, offset);
11904 *p++ = ',';
11905 p += hexnumstr (p, lm);
11906 *p++ = '\0';
11907
6d820c5c 11908 putpkt (rs->buf);
8d64371b 11909 getpkt (&rs->buf, 0);
3e43a32a
MS
11910 result = packet_ok (rs->buf,
11911 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 11912 if (result == PACKET_OK)
38691318 11913 {
b926417a 11914 ULONGEST addr;
38691318 11915
8d64371b 11916 unpack_varlen_hex (rs->buf.data (), &addr);
b926417a 11917 return addr;
38691318 11918 }
571dd617 11919 else if (result == PACKET_UNKNOWN)
109c3e39
AC
11920 throw_error (TLS_GENERIC_ERROR,
11921 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 11922 else
109c3e39
AC
11923 throw_error (TLS_GENERIC_ERROR,
11924 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
11925 }
11926 else
109c3e39
AC
11927 throw_error (TLS_GENERIC_ERROR,
11928 _("TLS not supported or disabled on this target"));
38691318
KB
11929 /* Not reached. */
11930 return 0;
11931}
11932
711e434b
PM
11933/* Provide thread local base, i.e. Thread Information Block address.
11934 Returns 1 if ptid is found and thread_local_base is non zero. */
11935
57810aa7 11936bool
f6ac5f3d 11937remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
711e434b 11938{
4082afcc 11939 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
11940 {
11941 struct remote_state *rs = get_remote_state ();
8d64371b
TT
11942 char *p = rs->buf.data ();
11943 char *endp = p + get_remote_packet_size ();
711e434b
PM
11944 enum packet_result result;
11945
11946 strcpy (p, "qGetTIBAddr:");
11947 p += strlen (p);
11948 p = write_ptid (p, endp, ptid);
11949 *p++ = '\0';
11950
11951 putpkt (rs->buf);
8d64371b 11952 getpkt (&rs->buf, 0);
711e434b
PM
11953 result = packet_ok (rs->buf,
11954 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11955 if (result == PACKET_OK)
11956 {
b926417a 11957 ULONGEST val;
8d64371b 11958 unpack_varlen_hex (rs->buf.data (), &val);
711e434b 11959 if (addr)
b926417a 11960 *addr = (CORE_ADDR) val;
57810aa7 11961 return true;
711e434b
PM
11962 }
11963 else if (result == PACKET_UNKNOWN)
11964 error (_("Remote target doesn't support qGetTIBAddr packet"));
11965 else
11966 error (_("Remote target failed to process qGetTIBAddr request"));
11967 }
11968 else
11969 error (_("qGetTIBAddr not supported or disabled on this target"));
11970 /* Not reached. */
57810aa7 11971 return false;
711e434b
PM
11972}
11973
29709017
DJ
11974/* Support for inferring a target description based on the current
11975 architecture and the size of a 'g' packet. While the 'g' packet
11976 can have any size (since optional registers can be left off the
11977 end), some sizes are easily recognizable given knowledge of the
11978 approximate architecture. */
11979
11980struct remote_g_packet_guess
11981{
eefce37f
TT
11982 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
11983 : bytes (bytes_),
11984 tdesc (tdesc_)
11985 {
11986 }
11987
29709017
DJ
11988 int bytes;
11989 const struct target_desc *tdesc;
11990};
29709017 11991
cb275538 11992struct remote_g_packet_data
29709017 11993{
eefce37f 11994 std::vector<remote_g_packet_guess> guesses;
29709017
DJ
11995};
11996
cb275538
TT
11997static const registry<gdbarch>::key<struct remote_g_packet_data>
11998 remote_g_packet_data_handle;
29709017 11999
cb275538
TT
12000static struct remote_g_packet_data *
12001get_g_packet_data (struct gdbarch *gdbarch)
29709017 12002{
cb275538
TT
12003 struct remote_g_packet_data *data
12004 = remote_g_packet_data_handle.get (gdbarch);
12005 if (data == nullptr)
12006 data = remote_g_packet_data_handle.emplace (gdbarch);
12007 return data;
29709017
DJ
12008}
12009
12010void
12011register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12012 const struct target_desc *tdesc)
12013{
cb275538 12014 struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
29709017
DJ
12015
12016 gdb_assert (tdesc != NULL);
12017
eefce37f
TT
12018 for (const remote_g_packet_guess &guess : data->guesses)
12019 if (guess.bytes == bytes)
29709017 12020 internal_error (__FILE__, __LINE__,
9b20d036 12021 _("Duplicate g packet description added for size %d"),
29709017
DJ
12022 bytes);
12023
eefce37f 12024 data->guesses.emplace_back (bytes, tdesc);
29709017
DJ
12025}
12026
eefce37f
TT
12027/* Return true if remote_read_description would do anything on this target
12028 and architecture, false otherwise. */
d962ef82 12029
eefce37f 12030static bool
d962ef82
DJ
12031remote_read_description_p (struct target_ops *target)
12032{
cb275538 12033 struct remote_g_packet_data *data = get_g_packet_data (target_gdbarch ());
d962ef82 12034
eefce37f 12035 return !data->guesses.empty ();
d962ef82
DJ
12036}
12037
f6ac5f3d
PA
12038const struct target_desc *
12039remote_target::read_description ()
29709017 12040{
cb275538 12041 struct remote_g_packet_data *data = get_g_packet_data (target_gdbarch ());
29709017 12042
d962ef82
DJ
12043 /* Do not try this during initial connection, when we do not know
12044 whether there is a running but stopped thread. */
55f6301a 12045 if (!target_has_execution () || inferior_ptid == null_ptid)
b6a8c27b 12046 return beneath ()->read_description ();
d962ef82 12047
eefce37f 12048 if (!data->guesses.empty ())
29709017 12049 {
29709017
DJ
12050 int bytes = send_g_packet ();
12051
eefce37f
TT
12052 for (const remote_g_packet_guess &guess : data->guesses)
12053 if (guess.bytes == bytes)
12054 return guess.tdesc;
29709017
DJ
12055
12056 /* We discard the g packet. A minor optimization would be to
12057 hold on to it, and fill the register cache once we have selected
12058 an architecture, but it's too tricky to do safely. */
12059 }
12060
b6a8c27b 12061 return beneath ()->read_description ();
29709017
DJ
12062}
12063
a6b151f1
DJ
12064/* Remote file transfer support. This is host-initiated I/O, not
12065 target-initiated; for target-initiated, see remote-fileio.c. */
12066
12067/* If *LEFT is at least the length of STRING, copy STRING to
12068 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12069 decrease *LEFT. Otherwise raise an error. */
12070
12071static void
a121b7c1 12072remote_buffer_add_string (char **buffer, int *left, const char *string)
a6b151f1
DJ
12073{
12074 int len = strlen (string);
12075
12076 if (len > *left)
12077 error (_("Packet too long for target."));
12078
12079 memcpy (*buffer, string, len);
12080 *buffer += len;
12081 *left -= len;
12082
12083 /* NUL-terminate the buffer as a convenience, if there is
12084 room. */
12085 if (*left)
12086 **buffer = '\0';
12087}
12088
12089/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12090 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12091 decrease *LEFT. Otherwise raise an error. */
12092
12093static void
12094remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12095 int len)
12096{
12097 if (2 * len > *left)
12098 error (_("Packet too long for target."));
12099
12100 bin2hex (bytes, *buffer, len);
12101 *buffer += 2 * len;
12102 *left -= 2 * len;
12103
12104 /* NUL-terminate the buffer as a convenience, if there is
12105 room. */
12106 if (*left)
12107 **buffer = '\0';
12108}
12109
12110/* If *LEFT is large enough, convert VALUE to hex and add it to
12111 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12112 decrease *LEFT. Otherwise raise an error. */
12113
12114static void
12115remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12116{
12117 int len = hexnumlen (value);
12118
12119 if (len > *left)
12120 error (_("Packet too long for target."));
12121
12122 hexnumstr (*buffer, value);
12123 *buffer += len;
12124 *left -= len;
12125
12126 /* NUL-terminate the buffer as a convenience, if there is
12127 room. */
12128 if (*left)
12129 **buffer = '\0';
12130}
12131
12132/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
b872057a 12133 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
a6b151f1
DJ
12134 was included, and *ATTACHMENT to point to the start of the annex
12135 if any. The length of the packet isn't needed here; there may
12136 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12137
12138 Return 0 if the packet could be parsed, -1 if it could not. If
12139 -1 is returned, the other variables may not be initialized. */
12140
12141static int
aa2838cc 12142remote_hostio_parse_result (const char *buffer, int *retcode,
b872057a 12143 fileio_error *remote_errno, const char **attachment)
a6b151f1
DJ
12144{
12145 char *p, *p2;
12146
b872057a 12147 *remote_errno = FILEIO_SUCCESS;
a6b151f1
DJ
12148 *attachment = NULL;
12149
12150 if (buffer[0] != 'F')
12151 return -1;
12152
12153 errno = 0;
12154 *retcode = strtol (&buffer[1], &p, 16);
12155 if (errno != 0 || p == &buffer[1])
12156 return -1;
12157
12158 /* Check for ",errno". */
12159 if (*p == ',')
12160 {
12161 errno = 0;
b872057a 12162 *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
a6b151f1
DJ
12163 if (errno != 0 || p + 1 == p2)
12164 return -1;
12165 p = p2;
12166 }
12167
12168 /* Check for ";attachment". If there is no attachment, the
12169 packet should end here. */
12170 if (*p == ';')
12171 {
12172 *attachment = p + 1;
12173 return 0;
12174 }
12175 else if (*p == '\0')
12176 return 0;
12177 else
12178 return -1;
12179}
12180
12181/* Send a prepared I/O packet to the target and read its response.
12182 The prepared packet is in the global RS->BUF before this function
12183 is called, and the answer is there when we return.
12184
12185 COMMAND_BYTES is the length of the request to send, which may include
12186 binary data. WHICH_PACKET is the packet configuration to check
12187 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12188 is set to the error number and -1 is returned. Otherwise the value
12189 returned by the function is returned.
12190
12191 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12192 attachment is expected; an error will be reported if there's a
12193 mismatch. If one is found, *ATTACHMENT will be set to point into
12194 the packet buffer and *ATTACHMENT_LEN will be set to the
12195 attachment's length. */
12196
6b8edb51
PA
12197int
12198remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
b872057a 12199 fileio_error *remote_errno, const char **attachment,
6b8edb51 12200 int *attachment_len)
a6b151f1
DJ
12201{
12202 struct remote_state *rs = get_remote_state ();
12203 int ret, bytes_read;
aa2838cc 12204 const char *attachment_tmp;
a6b151f1 12205
20db9c52 12206 if (packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
12207 {
12208 *remote_errno = FILEIO_ENOSYS;
12209 return -1;
12210 }
12211
8d64371b
TT
12212 putpkt_binary (rs->buf.data (), command_bytes);
12213 bytes_read = getpkt_sane (&rs->buf, 0);
a6b151f1
DJ
12214
12215 /* If it timed out, something is wrong. Don't try to parse the
12216 buffer. */
12217 if (bytes_read < 0)
12218 {
12219 *remote_errno = FILEIO_EINVAL;
12220 return -1;
12221 }
12222
12223 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
12224 {
12225 case PACKET_ERROR:
12226 *remote_errno = FILEIO_EINVAL;
12227 return -1;
12228 case PACKET_UNKNOWN:
12229 *remote_errno = FILEIO_ENOSYS;
12230 return -1;
12231 case PACKET_OK:
12232 break;
12233 }
12234
8d64371b 12235 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
a6b151f1
DJ
12236 &attachment_tmp))
12237 {
12238 *remote_errno = FILEIO_EINVAL;
12239 return -1;
12240 }
12241
12242 /* Make sure we saw an attachment if and only if we expected one. */
12243 if ((attachment_tmp == NULL && attachment != NULL)
12244 || (attachment_tmp != NULL && attachment == NULL))
12245 {
12246 *remote_errno = FILEIO_EINVAL;
12247 return -1;
12248 }
12249
12250 /* If an attachment was found, it must point into the packet buffer;
12251 work out how many bytes there were. */
12252 if (attachment_tmp != NULL)
12253 {
12254 *attachment = attachment_tmp;
8d64371b 12255 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
a6b151f1
DJ
12256 }
12257
12258 return ret;
12259}
12260
dd194f6b 12261/* See declaration.h. */
80152258 12262
dd194f6b
PA
12263void
12264readahead_cache::invalidate ()
80152258 12265{
dd194f6b 12266 this->fd = -1;
80152258
PA
12267}
12268
dd194f6b 12269/* See declaration.h. */
80152258 12270
dd194f6b
PA
12271void
12272readahead_cache::invalidate_fd (int fd)
80152258 12273{
dd194f6b
PA
12274 if (this->fd == fd)
12275 this->fd = -1;
80152258
PA
12276}
12277
15a201c8
GB
12278/* Set the filesystem remote_hostio functions that take FILENAME
12279 arguments will use. Return 0 on success, or -1 if an error
12280 occurs (and set *REMOTE_ERRNO). */
12281
6b8edb51
PA
12282int
12283remote_target::remote_hostio_set_filesystem (struct inferior *inf,
b872057a 12284 fileio_error *remote_errno)
15a201c8
GB
12285{
12286 struct remote_state *rs = get_remote_state ();
12287 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
8d64371b 12288 char *p = rs->buf.data ();
15a201c8
GB
12289 int left = get_remote_packet_size () - 1;
12290 char arg[9];
12291 int ret;
12292
12293 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12294 return 0;
12295
12296 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12297 return 0;
12298
12299 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12300
12301 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12302 remote_buffer_add_string (&p, &left, arg);
12303
8d64371b 12304 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
15a201c8
GB
12305 remote_errno, NULL, NULL);
12306
12307 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12308 return 0;
12309
12310 if (ret == 0)
12311 rs->fs_pid = required_pid;
12312
12313 return ret;
12314}
12315
12e2a5fd 12316/* Implementation of to_fileio_open. */
a6b151f1 12317
6b8edb51
PA
12318int
12319remote_target::remote_hostio_open (inferior *inf, const char *filename,
12320 int flags, int mode, int warn_if_slow,
b872057a 12321 fileio_error *remote_errno)
a6b151f1
DJ
12322{
12323 struct remote_state *rs = get_remote_state ();
8d64371b 12324 char *p = rs->buf.data ();
a6b151f1
DJ
12325 int left = get_remote_packet_size () - 1;
12326
4313b8c0
GB
12327 if (warn_if_slow)
12328 {
12329 static int warning_issued = 0;
12330
6cb06a8c
TT
12331 gdb_printf (_("Reading %s from remote target...\n"),
12332 filename);
4313b8c0
GB
12333
12334 if (!warning_issued)
12335 {
12336 warning (_("File transfers from remote targets can be slow."
12337 " Use \"set sysroot\" to access files locally"
12338 " instead."));
12339 warning_issued = 1;
12340 }
12341 }
12342
15a201c8
GB
12343 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12344 return -1;
12345
a6b151f1
DJ
12346 remote_buffer_add_string (&p, &left, "vFile:open:");
12347
12348 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12349 strlen (filename));
12350 remote_buffer_add_string (&p, &left, ",");
12351
12352 remote_buffer_add_int (&p, &left, flags);
12353 remote_buffer_add_string (&p, &left, ",");
12354
12355 remote_buffer_add_int (&p, &left, mode);
12356
8d64371b 12357 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
a6b151f1
DJ
12358 remote_errno, NULL, NULL);
12359}
12360
f6ac5f3d
PA
12361int
12362remote_target::fileio_open (struct inferior *inf, const char *filename,
12363 int flags, int mode, int warn_if_slow,
b872057a 12364 fileio_error *remote_errno)
f6ac5f3d 12365{
6b8edb51 12366 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
f6ac5f3d
PA
12367 remote_errno);
12368}
12369
12e2a5fd 12370/* Implementation of to_fileio_pwrite. */
a6b151f1 12371
6b8edb51
PA
12372int
12373remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
b872057a 12374 ULONGEST offset, fileio_error *remote_errno)
a6b151f1
DJ
12375{
12376 struct remote_state *rs = get_remote_state ();
8d64371b 12377 char *p = rs->buf.data ();
a6b151f1
DJ
12378 int left = get_remote_packet_size ();
12379 int out_len;
12380
dd194f6b 12381 rs->readahead_cache.invalidate_fd (fd);
80152258 12382
a6b151f1
DJ
12383 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12384
12385 remote_buffer_add_int (&p, &left, fd);
12386 remote_buffer_add_string (&p, &left, ",");
12387
12388 remote_buffer_add_int (&p, &left, offset);
12389 remote_buffer_add_string (&p, &left, ",");
12390
124e13d9 12391 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
8d64371b
TT
12392 (get_remote_packet_size ()
12393 - (p - rs->buf.data ())));
a6b151f1 12394
8d64371b 12395 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
a6b151f1
DJ
12396 remote_errno, NULL, NULL);
12397}
12398
f6ac5f3d
PA
12399int
12400remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
b872057a 12401 ULONGEST offset, fileio_error *remote_errno)
f6ac5f3d 12402{
6b8edb51 12403 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
f6ac5f3d
PA
12404}
12405
80152258
PA
12406/* Helper for the implementation of to_fileio_pread. Read the file
12407 from the remote side with vFile:pread. */
a6b151f1 12408
6b8edb51
PA
12409int
12410remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
b872057a 12411 ULONGEST offset, fileio_error *remote_errno)
a6b151f1
DJ
12412{
12413 struct remote_state *rs = get_remote_state ();
8d64371b 12414 char *p = rs->buf.data ();
aa2838cc 12415 const char *attachment;
a6b151f1
DJ
12416 int left = get_remote_packet_size ();
12417 int ret, attachment_len;
12418 int read_len;
12419
12420 remote_buffer_add_string (&p, &left, "vFile:pread:");
12421
12422 remote_buffer_add_int (&p, &left, fd);
12423 remote_buffer_add_string (&p, &left, ",");
12424
12425 remote_buffer_add_int (&p, &left, len);
12426 remote_buffer_add_string (&p, &left, ",");
12427
12428 remote_buffer_add_int (&p, &left, offset);
12429
8d64371b 12430 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
a6b151f1
DJ
12431 remote_errno, &attachment,
12432 &attachment_len);
12433
12434 if (ret < 0)
12435 return ret;
12436
bc20a4af 12437 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
12438 read_buf, len);
12439 if (read_len != ret)
12440 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12441
12442 return ret;
12443}
12444
dd194f6b 12445/* See declaration.h. */
80152258 12446
dd194f6b
PA
12447int
12448readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12449 ULONGEST offset)
80152258 12450{
dd194f6b
PA
12451 if (this->fd == fd
12452 && this->offset <= offset
12453 && offset < this->offset + this->bufsize)
80152258 12454 {
dd194f6b 12455 ULONGEST max = this->offset + this->bufsize;
80152258
PA
12456
12457 if (offset + len > max)
12458 len = max - offset;
12459
dd194f6b 12460 memcpy (read_buf, this->buf + offset - this->offset, len);
80152258
PA
12461 return len;
12462 }
12463
12464 return 0;
12465}
12466
12467/* Implementation of to_fileio_pread. */
12468
6b8edb51
PA
12469int
12470remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
b872057a 12471 ULONGEST offset, fileio_error *remote_errno)
80152258
PA
12472{
12473 int ret;
12474 struct remote_state *rs = get_remote_state ();
dd194f6b 12475 readahead_cache *cache = &rs->readahead_cache;
80152258 12476
dd194f6b 12477 ret = cache->pread (fd, read_buf, len, offset);
80152258
PA
12478 if (ret > 0)
12479 {
12480 cache->hit_count++;
12481
2189c312
SM
12482 remote_debug_printf ("readahead cache hit %s",
12483 pulongest (cache->hit_count));
80152258
PA
12484 return ret;
12485 }
12486
12487 cache->miss_count++;
2189c312
SM
12488
12489 remote_debug_printf ("readahead cache miss %s",
12490 pulongest (cache->miss_count));
80152258
PA
12491
12492 cache->fd = fd;
12493 cache->offset = offset;
12494 cache->bufsize = get_remote_packet_size ();
224c3ddb 12495 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258 12496
6b8edb51 12497 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
80152258
PA
12498 cache->offset, remote_errno);
12499 if (ret <= 0)
12500 {
dd194f6b 12501 cache->invalidate_fd (fd);
80152258
PA
12502 return ret;
12503 }
12504
12505 cache->bufsize = ret;
dd194f6b 12506 return cache->pread (fd, read_buf, len, offset);
80152258
PA
12507}
12508
f6ac5f3d
PA
12509int
12510remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
b872057a 12511 ULONGEST offset, fileio_error *remote_errno)
f6ac5f3d 12512{
6b8edb51 12513 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
f6ac5f3d
PA
12514}
12515
12e2a5fd 12516/* Implementation of to_fileio_close. */
a6b151f1 12517
6b8edb51 12518int
b872057a 12519remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
a6b151f1
DJ
12520{
12521 struct remote_state *rs = get_remote_state ();
8d64371b 12522 char *p = rs->buf.data ();
a6b151f1
DJ
12523 int left = get_remote_packet_size () - 1;
12524
dd194f6b 12525 rs->readahead_cache.invalidate_fd (fd);
80152258 12526
a6b151f1
DJ
12527 remote_buffer_add_string (&p, &left, "vFile:close:");
12528
12529 remote_buffer_add_int (&p, &left, fd);
12530
8d64371b 12531 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
a6b151f1
DJ
12532 remote_errno, NULL, NULL);
12533}
12534
f6ac5f3d 12535int
b872057a 12536remote_target::fileio_close (int fd, fileio_error *remote_errno)
f6ac5f3d 12537{
6b8edb51 12538 return remote_hostio_close (fd, remote_errno);
f6ac5f3d
PA
12539}
12540
12e2a5fd 12541/* Implementation of to_fileio_unlink. */
a6b151f1 12542
6b8edb51
PA
12543int
12544remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
b872057a 12545 fileio_error *remote_errno)
a6b151f1
DJ
12546{
12547 struct remote_state *rs = get_remote_state ();
8d64371b 12548 char *p = rs->buf.data ();
a6b151f1
DJ
12549 int left = get_remote_packet_size () - 1;
12550
15a201c8
GB
12551 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12552 return -1;
12553
a6b151f1
DJ
12554 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12555
12556 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12557 strlen (filename));
12558
8d64371b 12559 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
a6b151f1
DJ
12560 remote_errno, NULL, NULL);
12561}
12562
f6ac5f3d
PA
12563int
12564remote_target::fileio_unlink (struct inferior *inf, const char *filename,
b872057a 12565 fileio_error *remote_errno)
f6ac5f3d 12566{
6b8edb51 12567 return remote_hostio_unlink (inf, filename, remote_errno);
f6ac5f3d
PA
12568}
12569
12e2a5fd 12570/* Implementation of to_fileio_readlink. */
b9e7b9c3 12571
f6ac5f3d
PA
12572gdb::optional<std::string>
12573remote_target::fileio_readlink (struct inferior *inf, const char *filename,
b872057a 12574 fileio_error *remote_errno)
b9e7b9c3
UW
12575{
12576 struct remote_state *rs = get_remote_state ();
8d64371b 12577 char *p = rs->buf.data ();
aa2838cc 12578 const char *attachment;
b9e7b9c3
UW
12579 int left = get_remote_packet_size ();
12580 int len, attachment_len;
12581 int read_len;
b9e7b9c3 12582
15a201c8 12583 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
e0d3522b 12584 return {};
15a201c8 12585
b9e7b9c3
UW
12586 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12587
12588 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12589 strlen (filename));
12590
8d64371b 12591 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
b9e7b9c3
UW
12592 remote_errno, &attachment,
12593 &attachment_len);
12594
12595 if (len < 0)
e0d3522b 12596 return {};
b9e7b9c3 12597
e0d3522b 12598 std::string ret (len, '\0');
b9e7b9c3 12599
bc20a4af 12600 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
e0d3522b 12601 (gdb_byte *) &ret[0], len);
b9e7b9c3
UW
12602 if (read_len != len)
12603 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12604
b9e7b9c3
UW
12605 return ret;
12606}
12607
12e2a5fd 12608/* Implementation of to_fileio_fstat. */
0a93529c 12609
f6ac5f3d 12610int
b872057a 12611remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
0a93529c
GB
12612{
12613 struct remote_state *rs = get_remote_state ();
8d64371b 12614 char *p = rs->buf.data ();
0a93529c
GB
12615 int left = get_remote_packet_size ();
12616 int attachment_len, ret;
aa2838cc 12617 const char *attachment;
0a93529c
GB
12618 struct fio_stat fst;
12619 int read_len;
12620
464b0089
GB
12621 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12622
12623 remote_buffer_add_int (&p, &left, fd);
12624
8d64371b 12625 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
464b0089
GB
12626 remote_errno, &attachment,
12627 &attachment_len);
12628 if (ret < 0)
0a93529c 12629 {
464b0089
GB
12630 if (*remote_errno != FILEIO_ENOSYS)
12631 return ret;
12632
0a93529c
GB
12633 /* Strictly we should return -1, ENOSYS here, but when
12634 "set sysroot remote:" was implemented in August 2008
12635 BFD's need for a stat function was sidestepped with
12636 this hack. This was not remedied until March 2015
12637 so we retain the previous behavior to avoid breaking
12638 compatibility.
12639
12640 Note that the memset is a March 2015 addition; older
12641 GDBs set st_size *and nothing else* so the structure
12642 would have garbage in all other fields. This might
12643 break something but retaining the previous behavior
12644 here would be just too wrong. */
12645
12646 memset (st, 0, sizeof (struct stat));
12647 st->st_size = INT_MAX;
12648 return 0;
12649 }
12650
0a93529c
GB
12651 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12652 (gdb_byte *) &fst, sizeof (fst));
12653
12654 if (read_len != ret)
12655 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12656
12657 if (read_len != sizeof (fst))
12658 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12659 read_len, (int) sizeof (fst));
12660
12661 remote_fileio_to_host_stat (&fst, st);
12662
12663 return 0;
12664}
12665
12e2a5fd 12666/* Implementation of to_filesystem_is_local. */
e3dd7556 12667
57810aa7 12668bool
f6ac5f3d 12669remote_target::filesystem_is_local ()
e3dd7556
GB
12670{
12671 /* Valgrind GDB presents itself as a remote target but works
12672 on the local filesystem: it does not implement remote get
12673 and users are not expected to set a sysroot. To handle
12674 this case we treat the remote filesystem as local if the
12675 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12676 does not support vFile:open. */
e0700ba4 12677 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
e3dd7556
GB
12678 {
12679 enum packet_support ps = packet_support (PACKET_vFile_open);
12680
12681 if (ps == PACKET_SUPPORT_UNKNOWN)
12682 {
b872057a
SM
12683 int fd;
12684 fileio_error remote_errno;
e3dd7556
GB
12685
12686 /* Try opening a file to probe support. The supplied
12687 filename is irrelevant, we only care about whether
12688 the stub recognizes the packet or not. */
6b8edb51 12689 fd = remote_hostio_open (NULL, "just probing",
4313b8c0 12690 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
12691 &remote_errno);
12692
12693 if (fd >= 0)
6b8edb51 12694 remote_hostio_close (fd, &remote_errno);
e3dd7556
GB
12695
12696 ps = packet_support (PACKET_vFile_open);
12697 }
12698
12699 if (ps == PACKET_DISABLE)
12700 {
12701 static int warning_issued = 0;
12702
12703 if (!warning_issued)
12704 {
12705 warning (_("remote target does not support file"
12706 " transfer, attempting to access files"
12707 " from local filesystem."));
12708 warning_issued = 1;
12709 }
12710
57810aa7 12711 return true;
e3dd7556
GB
12712 }
12713 }
12714
57810aa7 12715 return false;
e3dd7556
GB
12716}
12717
a6b151f1 12718static int
b872057a 12719remote_fileio_errno_to_host (fileio_error errnum)
a6b151f1
DJ
12720{
12721 switch (errnum)
12722 {
12723 case FILEIO_EPERM:
dda83cd7 12724 return EPERM;
a6b151f1 12725 case FILEIO_ENOENT:
dda83cd7 12726 return ENOENT;
a6b151f1 12727 case FILEIO_EINTR:
dda83cd7 12728 return EINTR;
a6b151f1 12729 case FILEIO_EIO:
dda83cd7 12730 return EIO;
a6b151f1 12731 case FILEIO_EBADF:
dda83cd7 12732 return EBADF;
a6b151f1 12733 case FILEIO_EACCES:
dda83cd7 12734 return EACCES;
a6b151f1 12735 case FILEIO_EFAULT:
dda83cd7 12736 return EFAULT;
a6b151f1 12737 case FILEIO_EBUSY:
dda83cd7 12738 return EBUSY;
a6b151f1 12739 case FILEIO_EEXIST:
dda83cd7 12740 return EEXIST;
a6b151f1 12741 case FILEIO_ENODEV:
dda83cd7 12742 return ENODEV;
a6b151f1 12743 case FILEIO_ENOTDIR:
dda83cd7 12744 return ENOTDIR;
a6b151f1 12745 case FILEIO_EISDIR:
dda83cd7 12746 return EISDIR;
a6b151f1 12747 case FILEIO_EINVAL:
dda83cd7 12748 return EINVAL;
a6b151f1 12749 case FILEIO_ENFILE:
dda83cd7 12750 return ENFILE;
a6b151f1 12751 case FILEIO_EMFILE:
dda83cd7 12752 return EMFILE;
a6b151f1 12753 case FILEIO_EFBIG:
dda83cd7 12754 return EFBIG;
a6b151f1 12755 case FILEIO_ENOSPC:
dda83cd7 12756 return ENOSPC;
a6b151f1 12757 case FILEIO_ESPIPE:
dda83cd7 12758 return ESPIPE;
a6b151f1 12759 case FILEIO_EROFS:
dda83cd7 12760 return EROFS;
a6b151f1 12761 case FILEIO_ENOSYS:
dda83cd7 12762 return ENOSYS;
a6b151f1 12763 case FILEIO_ENAMETOOLONG:
dda83cd7 12764 return ENAMETOOLONG;
a6b151f1
DJ
12765 }
12766 return -1;
12767}
12768
12769static char *
b872057a 12770remote_hostio_error (fileio_error errnum)
a6b151f1
DJ
12771{
12772 int host_error = remote_fileio_errno_to_host (errnum);
12773
12774 if (host_error == -1)
12775 error (_("Unknown remote I/O error %d"), errnum);
12776 else
12777 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12778}
12779
440b7aec
PA
12780/* A RAII wrapper around a remote file descriptor. */
12781
12782class scoped_remote_fd
a6b151f1 12783{
440b7aec 12784public:
6b8edb51
PA
12785 scoped_remote_fd (remote_target *remote, int fd)
12786 : m_remote (remote), m_fd (fd)
440b7aec
PA
12787 {
12788 }
a6b151f1 12789
440b7aec
PA
12790 ~scoped_remote_fd ()
12791 {
12792 if (m_fd != -1)
12793 {
12794 try
12795 {
b872057a 12796 fileio_error remote_errno;
6b8edb51 12797 m_remote->remote_hostio_close (m_fd, &remote_errno);
440b7aec
PA
12798 }
12799 catch (...)
12800 {
12801 /* Swallow exception before it escapes the dtor. If
12802 something goes wrong, likely the connection is gone,
12803 and there's nothing else that can be done. */
12804 }
12805 }
12806 }
12807
12808 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12809
12810 /* Release ownership of the file descriptor, and return it. */
88a774b9 12811 ATTRIBUTE_UNUSED_RESULT int release () noexcept
440b7aec
PA
12812 {
12813 int fd = m_fd;
12814 m_fd = -1;
12815 return fd;
12816 }
12817
12818 /* Return the owned file descriptor. */
12819 int get () const noexcept
12820 {
12821 return m_fd;
12822 }
12823
12824private:
6b8edb51
PA
12825 /* The remote target. */
12826 remote_target *m_remote;
12827
440b7aec
PA
12828 /* The owned remote I/O file descriptor. */
12829 int m_fd;
12830};
a6b151f1
DJ
12831
12832void
12833remote_file_put (const char *local_file, const char *remote_file, int from_tty)
6b8edb51
PA
12834{
12835 remote_target *remote = get_current_remote_target ();
12836
12837 if (remote == nullptr)
12838 error (_("command can only be used with remote target"));
12839
12840 remote->remote_file_put (local_file, remote_file, from_tty);
12841}
12842
12843void
12844remote_target::remote_file_put (const char *local_file, const char *remote_file,
12845 int from_tty)
a6b151f1 12846{
b872057a
SM
12847 int retcode, bytes, io_size;
12848 fileio_error remote_errno;
a6b151f1
DJ
12849 int bytes_in_buffer;
12850 int saw_eof;
12851 ULONGEST offset;
a6b151f1 12852
d419f42d 12853 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
12854 if (file == NULL)
12855 perror_with_name (local_file);
a6b151f1 12856
440b7aec 12857 scoped_remote_fd fd
6b8edb51
PA
12858 (this, remote_hostio_open (NULL,
12859 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12860 | FILEIO_O_TRUNC),
12861 0700, 0, &remote_errno));
440b7aec 12862 if (fd.get () == -1)
a6b151f1
DJ
12863 remote_hostio_error (remote_errno);
12864
12865 /* Send up to this many bytes at once. They won't all fit in the
12866 remote packet limit, so we'll transfer slightly fewer. */
12867 io_size = get_remote_packet_size ();
5ca3b260 12868 gdb::byte_vector buffer (io_size);
a6b151f1 12869
a6b151f1
DJ
12870 bytes_in_buffer = 0;
12871 saw_eof = 0;
12872 offset = 0;
12873 while (bytes_in_buffer || !saw_eof)
12874 {
12875 if (!saw_eof)
12876 {
5ca3b260 12877 bytes = fread (buffer.data () + bytes_in_buffer, 1,
3e43a32a 12878 io_size - bytes_in_buffer,
d419f42d 12879 file.get ());
a6b151f1
DJ
12880 if (bytes == 0)
12881 {
d419f42d 12882 if (ferror (file.get ()))
a6b151f1
DJ
12883 error (_("Error reading %s."), local_file);
12884 else
12885 {
12886 /* EOF. Unless there is something still in the
12887 buffer from the last iteration, we are done. */
12888 saw_eof = 1;
12889 if (bytes_in_buffer == 0)
12890 break;
12891 }
12892 }
12893 }
12894 else
12895 bytes = 0;
12896
12897 bytes += bytes_in_buffer;
12898 bytes_in_buffer = 0;
12899
5ca3b260 12900 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
3e43a32a 12901 offset, &remote_errno);
a6b151f1
DJ
12902
12903 if (retcode < 0)
12904 remote_hostio_error (remote_errno);
12905 else if (retcode == 0)
12906 error (_("Remote write of %d bytes returned 0!"), bytes);
12907 else if (retcode < bytes)
12908 {
12909 /* Short write. Save the rest of the read data for the next
12910 write. */
12911 bytes_in_buffer = bytes - retcode;
5ca3b260 12912 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
a6b151f1
DJ
12913 }
12914
12915 offset += retcode;
12916 }
12917
6b8edb51 12918 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
12919 remote_hostio_error (remote_errno);
12920
12921 if (from_tty)
6cb06a8c 12922 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
a6b151f1
DJ
12923}
12924
12925void
12926remote_file_get (const char *remote_file, const char *local_file, int from_tty)
6b8edb51
PA
12927{
12928 remote_target *remote = get_current_remote_target ();
12929
12930 if (remote == nullptr)
12931 error (_("command can only be used with remote target"));
12932
12933 remote->remote_file_get (remote_file, local_file, from_tty);
12934}
12935
12936void
12937remote_target::remote_file_get (const char *remote_file, const char *local_file,
12938 int from_tty)
a6b151f1 12939{
b872057a
SM
12940 fileio_error remote_errno;
12941 int bytes, io_size;
a6b151f1 12942 ULONGEST offset;
a6b151f1 12943
440b7aec 12944 scoped_remote_fd fd
6b8edb51
PA
12945 (this, remote_hostio_open (NULL,
12946 remote_file, FILEIO_O_RDONLY, 0, 0,
12947 &remote_errno));
440b7aec 12948 if (fd.get () == -1)
a6b151f1
DJ
12949 remote_hostio_error (remote_errno);
12950
d419f42d 12951 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
12952 if (file == NULL)
12953 perror_with_name (local_file);
a6b151f1
DJ
12954
12955 /* Send up to this many bytes at once. They won't all fit in the
12956 remote packet limit, so we'll transfer slightly fewer. */
12957 io_size = get_remote_packet_size ();
5ca3b260 12958 gdb::byte_vector buffer (io_size);
a6b151f1 12959
a6b151f1
DJ
12960 offset = 0;
12961 while (1)
12962 {
5ca3b260 12963 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
440b7aec 12964 &remote_errno);
a6b151f1
DJ
12965 if (bytes == 0)
12966 /* Success, but no bytes, means end-of-file. */
12967 break;
12968 if (bytes == -1)
12969 remote_hostio_error (remote_errno);
12970
12971 offset += bytes;
12972
5ca3b260 12973 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
a6b151f1
DJ
12974 if (bytes == 0)
12975 perror_with_name (local_file);
12976 }
12977
6b8edb51 12978 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
12979 remote_hostio_error (remote_errno);
12980
12981 if (from_tty)
6cb06a8c 12982 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
a6b151f1
DJ
12983}
12984
12985void
12986remote_file_delete (const char *remote_file, int from_tty)
12987{
6b8edb51 12988 remote_target *remote = get_current_remote_target ();
a6b151f1 12989
6b8edb51 12990 if (remote == nullptr)
a6b151f1
DJ
12991 error (_("command can only be used with remote target"));
12992
6b8edb51
PA
12993 remote->remote_file_delete (remote_file, from_tty);
12994}
12995
12996void
12997remote_target::remote_file_delete (const char *remote_file, int from_tty)
12998{
b872057a
SM
12999 int retcode;
13000 fileio_error remote_errno;
6b8edb51
PA
13001
13002 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
a6b151f1
DJ
13003 if (retcode == -1)
13004 remote_hostio_error (remote_errno);
13005
13006 if (from_tty)
6cb06a8c 13007 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
a6b151f1
DJ
13008}
13009
13010static void
ac88e2de 13011remote_put_command (const char *args, int from_tty)
a6b151f1 13012{
d1a41061
PP
13013 if (args == NULL)
13014 error_no_arg (_("file to put"));
13015
773a1edc 13016 gdb_argv argv (args);
a6b151f1
DJ
13017 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13018 error (_("Invalid parameters to remote put"));
13019
13020 remote_file_put (argv[0], argv[1], from_tty);
a6b151f1
DJ
13021}
13022
13023static void
ac88e2de 13024remote_get_command (const char *args, int from_tty)
a6b151f1 13025{
d1a41061
PP
13026 if (args == NULL)
13027 error_no_arg (_("file to get"));
13028
773a1edc 13029 gdb_argv argv (args);
a6b151f1
DJ
13030 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13031 error (_("Invalid parameters to remote get"));
13032
13033 remote_file_get (argv[0], argv[1], from_tty);
a6b151f1
DJ
13034}
13035
13036static void
ac88e2de 13037remote_delete_command (const char *args, int from_tty)
a6b151f1 13038{
d1a41061
PP
13039 if (args == NULL)
13040 error_no_arg (_("file to delete"));
13041
773a1edc 13042 gdb_argv argv (args);
a6b151f1
DJ
13043 if (argv[0] == NULL || argv[1] != NULL)
13044 error (_("Invalid parameters to remote delete"));
13045
13046 remote_file_delete (argv[0], from_tty);
a6b151f1
DJ
13047}
13048
57810aa7 13049bool
f6ac5f3d 13050remote_target::can_execute_reverse ()
b2175913 13051{
4082afcc
PA
13052 if (packet_support (PACKET_bs) == PACKET_ENABLE
13053 || packet_support (PACKET_bc) == PACKET_ENABLE)
57810aa7 13054 return true;
40ab02ce 13055 else
57810aa7 13056 return false;
b2175913
MS
13057}
13058
57810aa7 13059bool
f6ac5f3d 13060remote_target::supports_non_stop ()
74531fed 13061{
57810aa7 13062 return true;
74531fed
PA
13063}
13064
57810aa7 13065bool
f6ac5f3d 13066remote_target::supports_disable_randomization ()
03583c20
UW
13067{
13068 /* Only supported in extended mode. */
57810aa7 13069 return false;
03583c20
UW
13070}
13071
57810aa7 13072bool
f6ac5f3d 13073remote_target::supports_multi_process ()
8a305172
PA
13074{
13075 struct remote_state *rs = get_remote_state ();
a744cf53 13076
8020350c 13077 return remote_multi_process_p (rs);
8a305172
PA
13078}
13079
70221824 13080static int
f6ac5f3d 13081remote_supports_cond_tracepoints ()
782b2b07 13082{
4082afcc 13083 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
13084}
13085
57810aa7 13086bool
f6ac5f3d 13087remote_target::supports_evaluation_of_breakpoint_conditions ()
3788aec7 13088{
4082afcc 13089 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
13090}
13091
70221824 13092static int
f6ac5f3d 13093remote_supports_fast_tracepoints ()
7a697b8d 13094{
4082afcc 13095 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
13096}
13097
0fb4aa4b 13098static int
f6ac5f3d 13099remote_supports_static_tracepoints ()
0fb4aa4b 13100{
4082afcc 13101 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
13102}
13103
1e4d1764 13104static int
f6ac5f3d 13105remote_supports_install_in_trace ()
1e4d1764 13106{
4082afcc 13107 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
13108}
13109
57810aa7 13110bool
f6ac5f3d 13111remote_target::supports_enable_disable_tracepoint ()
d248b706 13112{
4082afcc
PA
13113 return (packet_support (PACKET_EnableDisableTracepoints_feature)
13114 == PACKET_ENABLE);
d248b706
KY
13115}
13116
57810aa7 13117bool
f6ac5f3d 13118remote_target::supports_string_tracing ()
3065dfb6 13119{
4082afcc 13120 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
13121}
13122
57810aa7 13123bool
f6ac5f3d 13124remote_target::can_run_breakpoint_commands ()
d3ce09f5 13125{
4082afcc 13126 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
13127}
13128
f6ac5f3d
PA
13129void
13130remote_target::trace_init ()
35b1e5cc 13131{
b6bb3468
PA
13132 struct remote_state *rs = get_remote_state ();
13133
35b1e5cc 13134 putpkt ("QTinit");
b6bb3468 13135 remote_get_noisy_reply ();
8d64371b 13136 if (strcmp (rs->buf.data (), "OK") != 0)
35b1e5cc
SS
13137 error (_("Target does not support this command."));
13138}
13139
409873ef
SS
13140/* Recursive routine to walk through command list including loops, and
13141 download packets for each command. */
13142
6b8edb51
PA
13143void
13144remote_target::remote_download_command_source (int num, ULONGEST addr,
13145 struct command_line *cmds)
409873ef
SS
13146{
13147 struct remote_state *rs = get_remote_state ();
13148 struct command_line *cmd;
13149
13150 for (cmd = cmds; cmd; cmd = cmd->next)
13151 {
0df8b418 13152 QUIT; /* Allow user to bail out with ^C. */
8d64371b 13153 strcpy (rs->buf.data (), "QTDPsrc:");
409873ef 13154 encode_source_string (num, addr, "cmd", cmd->line,
8d64371b
TT
13155 rs->buf.data () + strlen (rs->buf.data ()),
13156 rs->buf.size () - strlen (rs->buf.data ()));
409873ef 13157 putpkt (rs->buf);
b6bb3468 13158 remote_get_noisy_reply ();
8d64371b 13159 if (strcmp (rs->buf.data (), "OK"))
409873ef
SS
13160 warning (_("Target does not support source download."));
13161
13162 if (cmd->control_type == while_control
13163 || cmd->control_type == while_stepping_control)
13164 {
12973681 13165 remote_download_command_source (num, addr, cmd->body_list_0.get ());
409873ef 13166
0df8b418 13167 QUIT; /* Allow user to bail out with ^C. */
8d64371b 13168 strcpy (rs->buf.data (), "QTDPsrc:");
409873ef 13169 encode_source_string (num, addr, "cmd", "end",
8d64371b
TT
13170 rs->buf.data () + strlen (rs->buf.data ()),
13171 rs->buf.size () - strlen (rs->buf.data ()));
409873ef 13172 putpkt (rs->buf);
b6bb3468 13173 remote_get_noisy_reply ();
8d64371b 13174 if (strcmp (rs->buf.data (), "OK"))
409873ef
SS
13175 warning (_("Target does not support source download."));
13176 }
13177 }
13178}
13179
f6ac5f3d
PA
13180void
13181remote_target::download_tracepoint (struct bp_location *loc)
35b1e5cc
SS
13182{
13183 CORE_ADDR tpaddr;
409873ef 13184 char addrbuf[40];
b44ec619
SM
13185 std::vector<std::string> tdp_actions;
13186 std::vector<std::string> stepping_actions;
35b1e5cc 13187 char *pkt;
e8ba3115 13188 struct breakpoint *b = loc->owner;
d9b3f62e 13189 struct tracepoint *t = (struct tracepoint *) b;
b6bb3468 13190 struct remote_state *rs = get_remote_state ();
3df3a985 13191 int ret;
ff36536c 13192 const char *err_msg = _("Tracepoint packet too large for target.");
3df3a985
PFC
13193 size_t size_left;
13194
13195 /* We use a buffer other than rs->buf because we'll build strings
13196 across multiple statements, and other statements in between could
13197 modify rs->buf. */
13198 gdb::char_vector buf (get_remote_packet_size ());
35b1e5cc 13199
dc673c81 13200 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
13201
13202 tpaddr = loc->address;
53807e9f 13203 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
3df3a985
PFC
13204 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13205 b->number, addrbuf, /* address */
13206 (b->enable_state == bp_enabled ? 'E' : 'D'),
13207 t->step_count, t->pass_count);
13208
13209 if (ret < 0 || ret >= buf.size ())
a7f25a84 13210 error ("%s", err_msg);
3df3a985 13211
e8ba3115
YQ
13212 /* Fast tracepoints are mostly handled by the target, but we can
13213 tell the target how big of an instruction block should be moved
13214 around. */
13215 if (b->type == bp_fast_tracepoint)
13216 {
13217 /* Only test for support at download time; we may not know
13218 target capabilities at definition time. */
13219 if (remote_supports_fast_tracepoints ())
35b1e5cc 13220 {
6b940e6a
PL
13221 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13222 NULL))
3df3a985
PFC
13223 {
13224 size_left = buf.size () - strlen (buf.data ());
13225 ret = snprintf (buf.data () + strlen (buf.data ()),
13226 size_left, ":F%x",
13227 gdb_insn_length (loc->gdbarch, tpaddr));
13228
13229 if (ret < 0 || ret >= size_left)
a7f25a84 13230 error ("%s", err_msg);
3df3a985 13231 }
35b1e5cc 13232 else
e8ba3115
YQ
13233 /* If it passed validation at definition but fails now,
13234 something is very wrong. */
13235 internal_error (__FILE__, __LINE__,
13236 _("Fast tracepoint not "
13237 "valid during download"));
35b1e5cc 13238 }
e8ba3115
YQ
13239 else
13240 /* Fast tracepoints are functionally identical to regular
13241 tracepoints, so don't take lack of support as a reason to
13242 give up on the trace run. */
13243 warning (_("Target does not support fast tracepoints, "
13244 "downloading %d as regular tracepoint"), b->number);
13245 }
7b572efb
TT
13246 else if (b->type == bp_static_tracepoint
13247 || b->type == bp_static_marker_tracepoint)
e8ba3115
YQ
13248 {
13249 /* Only test for support at download time; we may not know
13250 target capabilities at definition time. */
13251 if (remote_supports_static_tracepoints ())
0fb4aa4b 13252 {
e8ba3115 13253 struct static_tracepoint_marker marker;
0fb4aa4b 13254
e8ba3115 13255 if (target_static_tracepoint_marker_at (tpaddr, &marker))
3df3a985
PFC
13256 {
13257 size_left = buf.size () - strlen (buf.data ());
13258 ret = snprintf (buf.data () + strlen (buf.data ()),
13259 size_left, ":S");
13260
13261 if (ret < 0 || ret >= size_left)
a7f25a84 13262 error ("%s", err_msg);
3df3a985 13263 }
0fb4aa4b 13264 else
e8ba3115 13265 error (_("Static tracepoint not valid during download"));
0fb4aa4b 13266 }
e8ba3115
YQ
13267 else
13268 /* Fast tracepoints are functionally identical to regular
13269 tracepoints, so don't take lack of support as a reason
13270 to give up on the trace run. */
13271 error (_("Target does not support static tracepoints"));
13272 }
13273 /* If the tracepoint has a conditional, make it into an agent
13274 expression and append to the definition. */
13275 if (loc->cond)
13276 {
13277 /* Only test support at download time, we may not know target
13278 capabilities at definition time. */
13279 if (remote_supports_cond_tracepoints ())
35b1e5cc 13280 {
3df3a985
PFC
13281 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13282 loc->cond.get ());
13283
13284 size_left = buf.size () - strlen (buf.data ());
13285
13286 ret = snprintf (buf.data () + strlen (buf.data ()),
13287 size_left, ":X%x,", aexpr->len);
13288
13289 if (ret < 0 || ret >= size_left)
a7f25a84 13290 error ("%s", err_msg);
3df3a985
PFC
13291
13292 size_left = buf.size () - strlen (buf.data ());
13293
13294 /* Two bytes to encode each aexpr byte, plus the terminating
13295 null byte. */
13296 if (aexpr->len * 2 + 1 > size_left)
a7f25a84 13297 error ("%s", err_msg);
3df3a985
PFC
13298
13299 pkt = buf.data () + strlen (buf.data ());
13300
b44ec619 13301 for (int ndx = 0; ndx < aexpr->len; ++ndx)
e8ba3115
YQ
13302 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13303 *pkt = '\0';
35b1e5cc 13304 }
e8ba3115
YQ
13305 else
13306 warning (_("Target does not support conditional tracepoints, "
13307 "ignoring tp %d cond"), b->number);
13308 }
35b1e5cc 13309
e0700ba4 13310 if (b->commands || !default_collect.empty ())
3df3a985
PFC
13311 {
13312 size_left = buf.size () - strlen (buf.data ());
13313
13314 ret = snprintf (buf.data () + strlen (buf.data ()),
13315 size_left, "-");
13316
13317 if (ret < 0 || ret >= size_left)
a7f25a84 13318 error ("%s", err_msg);
3df3a985
PFC
13319 }
13320
13321 putpkt (buf.data ());
b6bb3468 13322 remote_get_noisy_reply ();
8d64371b 13323 if (strcmp (rs->buf.data (), "OK"))
e8ba3115 13324 error (_("Target does not support tracepoints."));
35b1e5cc 13325
e8ba3115 13326 /* do_single_steps (t); */
b44ec619
SM
13327 for (auto action_it = tdp_actions.begin ();
13328 action_it != tdp_actions.end (); action_it++)
e8ba3115 13329 {
b44ec619
SM
13330 QUIT; /* Allow user to bail out with ^C. */
13331
aa6f3694 13332 bool has_more = ((action_it + 1) != tdp_actions.end ()
b44ec619
SM
13333 || !stepping_actions.empty ());
13334
3df3a985
PFC
13335 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13336 b->number, addrbuf, /* address */
13337 action_it->c_str (),
13338 has_more ? '-' : 0);
13339
13340 if (ret < 0 || ret >= buf.size ())
a7f25a84 13341 error ("%s", err_msg);
3df3a985
PFC
13342
13343 putpkt (buf.data ());
b44ec619 13344 remote_get_noisy_reply ();
8d64371b 13345 if (strcmp (rs->buf.data (), "OK"))
b44ec619 13346 error (_("Error on target while setting tracepoints."));
e8ba3115 13347 }
409873ef 13348
05abfc39
PFC
13349 for (auto action_it = stepping_actions.begin ();
13350 action_it != stepping_actions.end (); action_it++)
13351 {
13352 QUIT; /* Allow user to bail out with ^C. */
13353
13354 bool is_first = action_it == stepping_actions.begin ();
aa6f3694 13355 bool has_more = (action_it + 1) != stepping_actions.end ();
05abfc39 13356
3df3a985
PFC
13357 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13358 b->number, addrbuf, /* address */
13359 is_first ? "S" : "",
13360 action_it->c_str (),
13361 has_more ? "-" : "");
13362
13363 if (ret < 0 || ret >= buf.size ())
a7f25a84 13364 error ("%s", err_msg);
3df3a985
PFC
13365
13366 putpkt (buf.data ());
05abfc39 13367 remote_get_noisy_reply ();
8d64371b 13368 if (strcmp (rs->buf.data (), "OK"))
05abfc39
PFC
13369 error (_("Error on target while setting tracepoints."));
13370 }
b44ec619 13371
4082afcc 13372 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 13373 {
264f9890 13374 if (b->locspec != nullptr)
409873ef 13375 {
3df3a985
PFC
13376 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13377
13378 if (ret < 0 || ret >= buf.size ())
a7f25a84 13379 error ("%s", err_msg);
3df3a985 13380
709438c7 13381 const char *str = b->locspec->to_string ();
264f9890 13382 encode_source_string (b->number, loc->address, "at", str,
3df3a985
PFC
13383 buf.data () + strlen (buf.data ()),
13384 buf.size () - strlen (buf.data ()));
13385 putpkt (buf.data ());
b6bb3468 13386 remote_get_noisy_reply ();
8d64371b 13387 if (strcmp (rs->buf.data (), "OK"))
e8ba3115 13388 warning (_("Target does not support source download."));
409873ef 13389 }
e8ba3115
YQ
13390 if (b->cond_string)
13391 {
3df3a985
PFC
13392 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13393
13394 if (ret < 0 || ret >= buf.size ())
a7f25a84 13395 error ("%s", err_msg);
3df3a985 13396
e8ba3115 13397 encode_source_string (b->number, loc->address,
6f781ee3 13398 "cond", b->cond_string.get (),
3df3a985
PFC
13399 buf.data () + strlen (buf.data ()),
13400 buf.size () - strlen (buf.data ()));
13401 putpkt (buf.data ());
b6bb3468 13402 remote_get_noisy_reply ();
8d64371b 13403 if (strcmp (rs->buf.data (), "OK"))
e8ba3115
YQ
13404 warning (_("Target does not support source download."));
13405 }
13406 remote_download_command_source (b->number, loc->address,
13407 breakpoint_commands (b));
35b1e5cc 13408 }
35b1e5cc
SS
13409}
13410
57810aa7 13411bool
f6ac5f3d 13412remote_target::can_download_tracepoint ()
1e4d1764 13413{
1e51243a
PA
13414 struct remote_state *rs = get_remote_state ();
13415 struct trace_status *ts;
13416 int status;
13417
13418 /* Don't try to install tracepoints until we've relocated our
13419 symbols, and fetched and merged the target's tracepoint list with
13420 ours. */
13421 if (rs->starting_up)
57810aa7 13422 return false;
1e51243a
PA
13423
13424 ts = current_trace_status ();
f6ac5f3d 13425 status = get_trace_status (ts);
1e4d1764
YQ
13426
13427 if (status == -1 || !ts->running_known || !ts->running)
57810aa7 13428 return false;
1e4d1764
YQ
13429
13430 /* If we are in a tracing experiment, but remote stub doesn't support
13431 installing tracepoint in trace, we have to return. */
13432 if (!remote_supports_install_in_trace ())
57810aa7 13433 return false;
1e4d1764 13434
57810aa7 13435 return true;
1e4d1764
YQ
13436}
13437
13438
f6ac5f3d
PA
13439void
13440remote_target::download_trace_state_variable (const trace_state_variable &tsv)
35b1e5cc
SS
13441{
13442 struct remote_state *rs = get_remote_state ();
00bf0b85 13443 char *p;
35b1e5cc 13444
8d64371b 13445 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
c252925c
SM
13446 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13447 tsv.builtin);
8d64371b
TT
13448 p = rs->buf.data () + strlen (rs->buf.data ());
13449 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13450 >= get_remote_packet_size ())
00bf0b85 13451 error (_("Trace state variable name too long for tsv definition packet"));
c252925c 13452 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
00bf0b85 13453 *p++ = '\0';
35b1e5cc 13454 putpkt (rs->buf);
b6bb3468 13455 remote_get_noisy_reply ();
8d64371b 13456 if (rs->buf[0] == '\0')
ad91cd99 13457 error (_("Target does not support this command."));
8d64371b 13458 if (strcmp (rs->buf.data (), "OK") != 0)
ad91cd99 13459 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
13460}
13461
f6ac5f3d
PA
13462void
13463remote_target::enable_tracepoint (struct bp_location *location)
d248b706
KY
13464{
13465 struct remote_state *rs = get_remote_state ();
d248b706 13466
8d64371b 13467 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
53807e9f
TT
13468 location->owner->number,
13469 phex (location->address, sizeof (CORE_ADDR)));
d248b706 13470 putpkt (rs->buf);
b6bb3468 13471 remote_get_noisy_reply ();
8d64371b 13472 if (rs->buf[0] == '\0')
d248b706 13473 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
8d64371b 13474 if (strcmp (rs->buf.data (), "OK") != 0)
d248b706
KY
13475 error (_("Error on target while enabling tracepoint."));
13476}
13477
f6ac5f3d
PA
13478void
13479remote_target::disable_tracepoint (struct bp_location *location)
d248b706
KY
13480{
13481 struct remote_state *rs = get_remote_state ();
d248b706 13482
8d64371b 13483 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
53807e9f
TT
13484 location->owner->number,
13485 phex (location->address, sizeof (CORE_ADDR)));
d248b706 13486 putpkt (rs->buf);
b6bb3468 13487 remote_get_noisy_reply ();
8d64371b 13488 if (rs->buf[0] == '\0')
d248b706 13489 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
8d64371b 13490 if (strcmp (rs->buf.data (), "OK") != 0)
d248b706
KY
13491 error (_("Error on target while disabling tracepoint."));
13492}
13493
f6ac5f3d
PA
13494void
13495remote_target::trace_set_readonly_regions ()
35b1e5cc
SS
13496{
13497 asection *s;
13498 bfd_size_type size;
608bcef2 13499 bfd_vma vma;
35b1e5cc 13500 int anysecs = 0;
c2fa21f1 13501 int offset = 0;
f493c217 13502 bfd *abfd = current_program_space->exec_bfd ();
35b1e5cc 13503
f493c217 13504 if (!abfd)
35b1e5cc
SS
13505 return; /* No information to give. */
13506
b6bb3468
PA
13507 struct remote_state *rs = get_remote_state ();
13508
8d64371b
TT
13509 strcpy (rs->buf.data (), "QTro");
13510 offset = strlen (rs->buf.data ());
f493c217 13511 for (s = abfd->sections; s; s = s->next)
35b1e5cc
SS
13512 {
13513 char tmp1[40], tmp2[40];
c2fa21f1 13514 int sec_length;
35b1e5cc 13515
f493c217
AM
13516 if ((s->flags & SEC_LOAD) == 0
13517 /* || (s->flags & SEC_CODE) == 0 */
13518 || (s->flags & SEC_READONLY) == 0)
35b1e5cc
SS
13519 continue;
13520
13521 anysecs = 1;
fd361982
AM
13522 vma = bfd_section_vma (s);
13523 size = bfd_section_size (s);
f493c217
AM
13524 bfd_sprintf_vma (abfd, tmp1, vma);
13525 bfd_sprintf_vma (abfd, tmp2, vma + size);
c2fa21f1 13526 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
8d64371b 13527 if (offset + sec_length + 1 > rs->buf.size ())
c2fa21f1 13528 {
4082afcc 13529 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 13530 warning (_("\
c2fa21f1
HZ
13531Too many sections for read-only sections definition packet."));
13532 break;
13533 }
8d64371b 13534 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
bba74b36 13535 tmp1, tmp2);
c2fa21f1 13536 offset += sec_length;
35b1e5cc
SS
13537 }
13538 if (anysecs)
13539 {
b6bb3468 13540 putpkt (rs->buf);
8d64371b 13541 getpkt (&rs->buf, 0);
35b1e5cc
SS
13542 }
13543}
13544
f6ac5f3d
PA
13545void
13546remote_target::trace_start ()
35b1e5cc 13547{
b6bb3468
PA
13548 struct remote_state *rs = get_remote_state ();
13549
35b1e5cc 13550 putpkt ("QTStart");
b6bb3468 13551 remote_get_noisy_reply ();
8d64371b 13552 if (rs->buf[0] == '\0')
ad91cd99 13553 error (_("Target does not support this command."));
8d64371b
TT
13554 if (strcmp (rs->buf.data (), "OK") != 0)
13555 error (_("Bogus reply from target: %s"), rs->buf.data ());
35b1e5cc
SS
13556}
13557
f6ac5f3d
PA
13558int
13559remote_target::get_trace_status (struct trace_status *ts)
35b1e5cc 13560{
953b98d1 13561 /* Initialize it just to avoid a GCC false warning. */
f652de6f 13562 char *p = NULL;
bd3eecc3 13563 enum packet_result result;
b6bb3468 13564 struct remote_state *rs = get_remote_state ();
bd3eecc3 13565
4082afcc 13566 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 13567 return -1;
a744cf53 13568
7b9a15e1 13569 /* FIXME we need to get register block size some other way. */
5cd63fda 13570 trace_regblock_size
9d6eea31 13571 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
00bf0b85 13572
049dc89b
JK
13573 putpkt ("qTStatus");
13574
a70b8144 13575 try
67f41397 13576 {
b6bb3468 13577 p = remote_get_noisy_reply ();
67f41397 13578 }
230d2906 13579 catch (const gdb_exception_error &ex)
67f41397 13580 {
598d3636
JK
13581 if (ex.error != TARGET_CLOSE_ERROR)
13582 {
13583 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13584 return -1;
13585 }
eedc3f4f 13586 throw;
67f41397 13587 }
00bf0b85 13588
bd3eecc3
PA
13589 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13590
00bf0b85 13591 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 13592 if (result == PACKET_UNKNOWN)
00bf0b85 13593 return -1;
35b1e5cc 13594
00bf0b85 13595 /* We're working with a live target. */
f5911ea1 13596 ts->filename = NULL;
00bf0b85 13597
00bf0b85 13598 if (*p++ != 'T')
8d64371b 13599 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
35b1e5cc 13600
84cebc4a
YQ
13601 /* Function 'parse_trace_status' sets default value of each field of
13602 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
13603 parse_trace_status (p, ts);
13604
13605 return ts->running;
35b1e5cc
SS
13606}
13607
f6ac5f3d
PA
13608void
13609remote_target::get_tracepoint_status (struct breakpoint *bp,
13610 struct uploaded_tp *utp)
f196051f
SS
13611{
13612 struct remote_state *rs = get_remote_state ();
f196051f 13613 char *reply;
f196051f 13614 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 13615 size_t size = get_remote_packet_size ();
f196051f
SS
13616
13617 if (tp)
13618 {
c1fc2657 13619 tp->hit_count = 0;
f196051f 13620 tp->traceframe_usage = 0;
40cb8ca5 13621 for (bp_location *loc : tp->locations ())
f196051f
SS
13622 {
13623 /* If the tracepoint was never downloaded, don't go asking for
13624 any status. */
13625 if (tp->number_on_target == 0)
13626 continue;
8d64371b 13627 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
bba74b36 13628 phex_nz (loc->address, 0));
f196051f 13629 putpkt (rs->buf);
b6bb3468 13630 reply = remote_get_noisy_reply ();
f196051f
SS
13631 if (reply && *reply)
13632 {
13633 if (*reply == 'V')
13634 parse_tracepoint_status (reply + 1, bp, utp);
13635 }
13636 }
13637 }
13638 else if (utp)
13639 {
13640 utp->hit_count = 0;
13641 utp->traceframe_usage = 0;
8d64371b 13642 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
bba74b36 13643 phex_nz (utp->addr, 0));
f196051f 13644 putpkt (rs->buf);
b6bb3468 13645 reply = remote_get_noisy_reply ();
f196051f
SS
13646 if (reply && *reply)
13647 {
13648 if (*reply == 'V')
13649 parse_tracepoint_status (reply + 1, bp, utp);
13650 }
13651 }
13652}
13653
f6ac5f3d
PA
13654void
13655remote_target::trace_stop ()
35b1e5cc 13656{
b6bb3468
PA
13657 struct remote_state *rs = get_remote_state ();
13658
35b1e5cc 13659 putpkt ("QTStop");
b6bb3468 13660 remote_get_noisy_reply ();
8d64371b 13661 if (rs->buf[0] == '\0')
ad91cd99 13662 error (_("Target does not support this command."));
8d64371b
TT
13663 if (strcmp (rs->buf.data (), "OK") != 0)
13664 error (_("Bogus reply from target: %s"), rs->buf.data ());
35b1e5cc
SS
13665}
13666
f6ac5f3d
PA
13667int
13668remote_target::trace_find (enum trace_find_type type, int num,
13669 CORE_ADDR addr1, CORE_ADDR addr2,
13670 int *tpp)
35b1e5cc
SS
13671{
13672 struct remote_state *rs = get_remote_state ();
8d64371b 13673 char *endbuf = rs->buf.data () + get_remote_packet_size ();
35b1e5cc
SS
13674 char *p, *reply;
13675 int target_frameno = -1, target_tracept = -1;
13676
e6e4e701
PA
13677 /* Lookups other than by absolute frame number depend on the current
13678 trace selected, so make sure it is correct on the remote end
13679 first. */
13680 if (type != tfind_number)
13681 set_remote_traceframe ();
13682
8d64371b 13683 p = rs->buf.data ();
35b1e5cc
SS
13684 strcpy (p, "QTFrame:");
13685 p = strchr (p, '\0');
13686 switch (type)
13687 {
13688 case tfind_number:
bba74b36 13689 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
13690 break;
13691 case tfind_pc:
bba74b36 13692 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
13693 break;
13694 case tfind_tp:
bba74b36 13695 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
13696 break;
13697 case tfind_range:
bba74b36
YQ
13698 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13699 phex_nz (addr2, 0));
35b1e5cc
SS
13700 break;
13701 case tfind_outside:
bba74b36
YQ
13702 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13703 phex_nz (addr2, 0));
35b1e5cc
SS
13704 break;
13705 default:
9b20d036 13706 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
13707 }
13708
13709 putpkt (rs->buf);
b6bb3468 13710 reply = remote_get_noisy_reply ();
ad91cd99
PA
13711 if (*reply == '\0')
13712 error (_("Target does not support this command."));
35b1e5cc
SS
13713
13714 while (reply && *reply)
13715 switch (*reply)
13716 {
13717 case 'F':
f197e0f1
VP
13718 p = ++reply;
13719 target_frameno = (int) strtol (p, &reply, 16);
13720 if (reply == p)
13721 error (_("Unable to parse trace frame number"));
e6e4e701
PA
13722 /* Don't update our remote traceframe number cache on failure
13723 to select a remote traceframe. */
f197e0f1
VP
13724 if (target_frameno == -1)
13725 return -1;
35b1e5cc
SS
13726 break;
13727 case 'T':
f197e0f1
VP
13728 p = ++reply;
13729 target_tracept = (int) strtol (p, &reply, 16);
13730 if (reply == p)
13731 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
13732 break;
13733 case 'O': /* "OK"? */
13734 if (reply[1] == 'K' && reply[2] == '\0')
13735 reply += 2;
13736 else
13737 error (_("Bogus reply from target: %s"), reply);
13738 break;
13739 default:
13740 error (_("Bogus reply from target: %s"), reply);
13741 }
13742 if (tpp)
13743 *tpp = target_tracept;
e6e4e701 13744
262e1174 13745 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
13746 return target_frameno;
13747}
13748
57810aa7 13749bool
f6ac5f3d 13750remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
35b1e5cc
SS
13751{
13752 struct remote_state *rs = get_remote_state ();
13753 char *reply;
13754 ULONGEST uval;
13755
e6e4e701
PA
13756 set_remote_traceframe ();
13757
8d64371b 13758 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc 13759 putpkt (rs->buf);
b6bb3468 13760 reply = remote_get_noisy_reply ();
35b1e5cc
SS
13761 if (reply && *reply)
13762 {
13763 if (*reply == 'V')
13764 {
13765 unpack_varlen_hex (reply + 1, &uval);
13766 *val = (LONGEST) uval;
57810aa7 13767 return true;
35b1e5cc
SS
13768 }
13769 }
57810aa7 13770 return false;
35b1e5cc
SS
13771}
13772
f6ac5f3d
PA
13773int
13774remote_target::save_trace_data (const char *filename)
00bf0b85
SS
13775{
13776 struct remote_state *rs = get_remote_state ();
13777 char *p, *reply;
13778
8d64371b 13779 p = rs->buf.data ();
00bf0b85
SS
13780 strcpy (p, "QTSave:");
13781 p += strlen (p);
8d64371b
TT
13782 if ((p - rs->buf.data ()) + strlen (filename) * 2
13783 >= get_remote_packet_size ())
00bf0b85 13784 error (_("Remote file name too long for trace save packet"));
9f1b45b0 13785 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
13786 *p++ = '\0';
13787 putpkt (rs->buf);
b6bb3468 13788 reply = remote_get_noisy_reply ();
d6c5869f 13789 if (*reply == '\0')
ad91cd99
PA
13790 error (_("Target does not support this command."));
13791 if (strcmp (reply, "OK") != 0)
13792 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
13793 return 0;
13794}
13795
13796/* This is basically a memory transfer, but needs to be its own packet
13797 because we don't know how the target actually organizes its trace
13798 memory, plus we want to be able to ask for as much as possible, but
13799 not be unhappy if we don't get as much as we ask for. */
13800
f6ac5f3d
PA
13801LONGEST
13802remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
13803{
13804 struct remote_state *rs = get_remote_state ();
13805 char *reply;
13806 char *p;
13807 int rslt;
13808
8d64371b 13809 p = rs->buf.data ();
00bf0b85
SS
13810 strcpy (p, "qTBuffer:");
13811 p += strlen (p);
13812 p += hexnumstr (p, offset);
13813 *p++ = ',';
13814 p += hexnumstr (p, len);
13815 *p++ = '\0';
13816
13817 putpkt (rs->buf);
b6bb3468 13818 reply = remote_get_noisy_reply ();
00bf0b85
SS
13819 if (reply && *reply)
13820 {
13821 /* 'l' by itself means we're at the end of the buffer and
13822 there is nothing more to get. */
13823 if (*reply == 'l')
13824 return 0;
13825
13826 /* Convert the reply into binary. Limit the number of bytes to
13827 convert according to our passed-in buffer size, rather than
13828 what was returned in the packet; if the target is
13829 unexpectedly generous and gives us a bigger reply than we
13830 asked for, we don't want to crash. */
b6bb3468 13831 rslt = hex2bin (reply, buf, len);
00bf0b85
SS
13832 return rslt;
13833 }
13834
13835 /* Something went wrong, flag as an error. */
13836 return -1;
13837}
13838
f6ac5f3d
PA
13839void
13840remote_target::set_disconnected_tracing (int val)
35b1e5cc
SS
13841{
13842 struct remote_state *rs = get_remote_state ();
13843
4082afcc 13844 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 13845 {
ad91cd99
PA
13846 char *reply;
13847
8d64371b
TT
13848 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13849 "QTDisconnected:%x", val);
33da3f1c 13850 putpkt (rs->buf);
b6bb3468 13851 reply = remote_get_noisy_reply ();
ad91cd99 13852 if (*reply == '\0')
33da3f1c 13853 error (_("Target does not support this command."));
ad91cd99 13854 if (strcmp (reply, "OK") != 0)
dda83cd7 13855 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
13856 }
13857 else if (val)
13858 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
13859}
13860
f6ac5f3d
PA
13861int
13862remote_target::core_of_thread (ptid_t ptid)
dc146f7c 13863{
5b6d1e4f 13864 thread_info *info = find_thread_ptid (this, ptid);
a744cf53 13865
7aabaf9d
SM
13866 if (info != NULL && info->priv != NULL)
13867 return get_remote_thread_info (info)->core;
13868
dc146f7c
VP
13869 return -1;
13870}
13871
f6ac5f3d
PA
13872void
13873remote_target::set_circular_trace_buffer (int val)
4daf5ac0
SS
13874{
13875 struct remote_state *rs = get_remote_state ();
ad91cd99 13876 char *reply;
4daf5ac0 13877
8d64371b
TT
13878 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13879 "QTBuffer:circular:%x", val);
4daf5ac0 13880 putpkt (rs->buf);
b6bb3468 13881 reply = remote_get_noisy_reply ();
ad91cd99 13882 if (*reply == '\0')
4daf5ac0 13883 error (_("Target does not support this command."));
ad91cd99
PA
13884 if (strcmp (reply, "OK") != 0)
13885 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
13886}
13887
f6ac5f3d
PA
13888traceframe_info_up
13889remote_target::traceframe_info ()
b3b9301e 13890{
9018be22 13891 gdb::optional<gdb::char_vector> text
328d42d8
SM
13892 = target_read_stralloc (current_inferior ()->top_target (),
13893 TARGET_OBJECT_TRACEFRAME_INFO,
b7b030ad 13894 NULL);
9018be22
SM
13895 if (text)
13896 return parse_traceframe_info (text->data ());
b3b9301e
PA
13897
13898 return NULL;
13899}
13900
405f8e94
SS
13901/* Handle the qTMinFTPILen packet. Returns the minimum length of
13902 instruction on which a fast tracepoint may be placed. Returns -1
13903 if the packet is not supported, and 0 if the minimum instruction
13904 length is unknown. */
13905
f6ac5f3d
PA
13906int
13907remote_target::get_min_fast_tracepoint_insn_len ()
405f8e94
SS
13908{
13909 struct remote_state *rs = get_remote_state ();
13910 char *reply;
13911
e886a173
PA
13912 /* If we're not debugging a process yet, the IPA can't be
13913 loaded. */
55f6301a 13914 if (!target_has_execution ())
e886a173
PA
13915 return 0;
13916
13917 /* Make sure the remote is pointing at the right process. */
13918 set_general_process ();
13919
8d64371b 13920 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
405f8e94 13921 putpkt (rs->buf);
b6bb3468 13922 reply = remote_get_noisy_reply ();
405f8e94
SS
13923 if (*reply == '\0')
13924 return -1;
13925 else
13926 {
13927 ULONGEST min_insn_len;
13928
13929 unpack_varlen_hex (reply, &min_insn_len);
13930
13931 return (int) min_insn_len;
13932 }
13933}
13934
f6ac5f3d
PA
13935void
13936remote_target::set_trace_buffer_size (LONGEST val)
f6f899bf 13937{
4082afcc 13938 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
13939 {
13940 struct remote_state *rs = get_remote_state ();
8d64371b
TT
13941 char *buf = rs->buf.data ();
13942 char *endbuf = buf + get_remote_packet_size ();
f6f899bf
HAQ
13943 enum packet_result result;
13944
13945 gdb_assert (val >= 0 || val == -1);
13946 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13947 /* Send -1 as literal "-1" to avoid host size dependency. */
13948 if (val < 0)
13949 {
13950 *buf++ = '-';
dda83cd7 13951 buf += hexnumstr (buf, (ULONGEST) -val);
f6f899bf
HAQ
13952 }
13953 else
13954 buf += hexnumstr (buf, (ULONGEST) val);
13955
13956 putpkt (rs->buf);
b6bb3468 13957 remote_get_noisy_reply ();
f6f899bf
HAQ
13958 result = packet_ok (rs->buf,
13959 &remote_protocol_packets[PACKET_QTBuffer_size]);
13960
13961 if (result != PACKET_OK)
8d64371b 13962 warning (_("Bogus reply from target: %s"), rs->buf.data ());
f6f899bf
HAQ
13963 }
13964}
13965
57810aa7 13966bool
f6ac5f3d
PA
13967remote_target::set_trace_notes (const char *user, const char *notes,
13968 const char *stop_notes)
f196051f
SS
13969{
13970 struct remote_state *rs = get_remote_state ();
13971 char *reply;
8d64371b
TT
13972 char *buf = rs->buf.data ();
13973 char *endbuf = buf + get_remote_packet_size ();
f196051f
SS
13974 int nbytes;
13975
13976 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13977 if (user)
13978 {
13979 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 13980 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
13981 buf += 2 * nbytes;
13982 *buf++ = ';';
13983 }
13984 if (notes)
13985 {
13986 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 13987 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
13988 buf += 2 * nbytes;
13989 *buf++ = ';';
13990 }
13991 if (stop_notes)
13992 {
13993 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 13994 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
13995 buf += 2 * nbytes;
13996 *buf++ = ';';
13997 }
13998 /* Ensure the buffer is terminated. */
13999 *buf = '\0';
14000
14001 putpkt (rs->buf);
b6bb3468 14002 reply = remote_get_noisy_reply ();
f196051f 14003 if (*reply == '\0')
57810aa7 14004 return false;
f196051f
SS
14005
14006 if (strcmp (reply, "OK") != 0)
14007 error (_("Bogus reply from target: %s"), reply);
14008
57810aa7 14009 return true;
f196051f
SS
14010}
14011
57810aa7
PA
14012bool
14013remote_target::use_agent (bool use)
d1feda86 14014{
4082afcc 14015 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
14016 {
14017 struct remote_state *rs = get_remote_state ();
14018
14019 /* If the stub supports QAgent. */
8d64371b 14020 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
d1feda86 14021 putpkt (rs->buf);
8d64371b 14022 getpkt (&rs->buf, 0);
d1feda86 14023
8d64371b 14024 if (strcmp (rs->buf.data (), "OK") == 0)
d1feda86 14025 {
f6ac5f3d 14026 ::use_agent = use;
57810aa7 14027 return true;
d1feda86
YQ
14028 }
14029 }
14030
57810aa7 14031 return false;
d1feda86
YQ
14032}
14033
57810aa7 14034bool
f6ac5f3d 14035remote_target::can_use_agent ()
d1feda86 14036{
4082afcc 14037 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
14038}
14039
9accd112
MM
14040struct btrace_target_info
14041{
14042 /* The ptid of the traced thread. */
14043 ptid_t ptid;
f4abbc16
MM
14044
14045 /* The obtained branch trace configuration. */
14046 struct btrace_config conf;
9accd112
MM
14047};
14048
f4abbc16
MM
14049/* Reset our idea of our target's btrace configuration. */
14050
14051static void
6b8edb51 14052remote_btrace_reset (remote_state *rs)
f4abbc16 14053{
f4abbc16
MM
14054 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14055}
14056
f4abbc16
MM
14057/* Synchronize the configuration with the target. */
14058
6b8edb51
PA
14059void
14060remote_target::btrace_sync_conf (const btrace_config *conf)
f4abbc16 14061{
d33501a5
MM
14062 struct packet_config *packet;
14063 struct remote_state *rs;
14064 char *buf, *pos, *endbuf;
14065
14066 rs = get_remote_state ();
8d64371b 14067 buf = rs->buf.data ();
d33501a5
MM
14068 endbuf = buf + get_remote_packet_size ();
14069
14070 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
14071 if (packet_config_support (packet) == PACKET_ENABLE
14072 && conf->bts.size != rs->btrace_config.bts.size)
14073 {
14074 pos = buf;
14075 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
dda83cd7 14076 conf->bts.size);
d33501a5
MM
14077
14078 putpkt (buf);
8d64371b 14079 getpkt (&rs->buf, 0);
d33501a5
MM
14080
14081 if (packet_ok (buf, packet) == PACKET_ERROR)
14082 {
14083 if (buf[0] == 'E' && buf[1] == '.')
14084 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14085 else
14086 error (_("Failed to configure the BTS buffer size."));
14087 }
14088
14089 rs->btrace_config.bts.size = conf->bts.size;
14090 }
b20a6524
MM
14091
14092 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
14093 if (packet_config_support (packet) == PACKET_ENABLE
14094 && conf->pt.size != rs->btrace_config.pt.size)
14095 {
14096 pos = buf;
14097 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
dda83cd7 14098 conf->pt.size);
b20a6524
MM
14099
14100 putpkt (buf);
8d64371b 14101 getpkt (&rs->buf, 0);
b20a6524
MM
14102
14103 if (packet_ok (buf, packet) == PACKET_ERROR)
14104 {
14105 if (buf[0] == 'E' && buf[1] == '.')
14106 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14107 else
14108 error (_("Failed to configure the trace buffer size."));
14109 }
14110
14111 rs->btrace_config.pt.size = conf->pt.size;
14112 }
f4abbc16
MM
14113}
14114
0d8cbc5f 14115/* Read TP's btrace configuration from the target and store it into CONF. */
f4abbc16
MM
14116
14117static void
0d8cbc5f 14118btrace_read_config (thread_info *tp, struct btrace_config *conf)
f4abbc16 14119{
0d8cbc5f
MM
14120 /* target_read_stralloc relies on INFERIOR_PTID. */
14121 scoped_restore_current_thread restore_thread;
14122 switch_to_thread (tp);
14123
9018be22 14124 gdb::optional<gdb::char_vector> xml
328d42d8
SM
14125 = target_read_stralloc (current_inferior ()->top_target (),
14126 TARGET_OBJECT_BTRACE_CONF, "");
9018be22
SM
14127 if (xml)
14128 parse_xml_btrace_conf (conf, xml->data ());
f4abbc16
MM
14129}
14130
c0272db5
TW
14131/* Maybe reopen target btrace. */
14132
6b8edb51
PA
14133void
14134remote_target::remote_btrace_maybe_reopen ()
c0272db5
TW
14135{
14136 struct remote_state *rs = get_remote_state ();
c0272db5 14137 int btrace_target_pushed = 0;
15766370 14138#if !defined (HAVE_LIBIPT)
c0272db5 14139 int warned = 0;
15766370 14140#endif
c0272db5 14141
aedbe3bb
CM
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
5b6d1e4f 14147 for (thread_info *tp : all_non_exited_threads (this))
c0272db5 14148 {
c0272db5 14149 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
0d8cbc5f 14150 btrace_read_config (tp, &rs->btrace_config);
c0272db5
TW
14151
14152 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14153 continue;
14154
14155#if !defined (HAVE_LIBIPT)
14156 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14157 {
14158 if (!warned)
14159 {
14160 warned = 1;
c4e12631
MM
14161 warning (_("Target is recording using Intel Processor Trace "
14162 "but support was disabled at compile time."));
c0272db5
TW
14163 }
14164
14165 continue;
14166 }
14167#endif /* !defined (HAVE_LIBIPT) */
14168
14169 /* Push target, once, but before anything else happens. This way our
14170 changes to the threads will be cleaned up by unpushing the target
14171 in case btrace_read_config () throws. */
14172 if (!btrace_target_pushed)
14173 {
14174 btrace_target_pushed = 1;
14175 record_btrace_push_target ();
6cb06a8c
TT
14176 gdb_printf (_("Target is recording using %s.\n"),
14177 btrace_format_string (rs->btrace_config.format));
c0272db5
TW
14178 }
14179
14180 tp->btrace.target = XCNEW (struct btrace_target_info);
14181 tp->btrace.target->ptid = tp->ptid;
14182 tp->btrace.target->conf = rs->btrace_config;
14183 }
c0272db5
TW
14184}
14185
9accd112
MM
14186/* Enable branch tracing. */
14187
f6ac5f3d 14188struct btrace_target_info *
696c0d5e
MM
14189remote_target::enable_btrace (thread_info *tp,
14190 const struct btrace_config *conf)
9accd112
MM
14191{
14192 struct btrace_target_info *tinfo = NULL;
b20a6524 14193 struct packet_config *packet = NULL;
9accd112 14194 struct remote_state *rs = get_remote_state ();
8d64371b
TT
14195 char *buf = rs->buf.data ();
14196 char *endbuf = buf + get_remote_packet_size ();
9accd112 14197
b20a6524
MM
14198 switch (conf->format)
14199 {
14200 case BTRACE_FORMAT_BTS:
14201 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
14202 break;
14203
14204 case BTRACE_FORMAT_PT:
14205 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
14206 break;
14207 }
14208
14209 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
14210 error (_("Target does not support branch tracing."));
14211
f4abbc16
MM
14212 btrace_sync_conf (conf);
14213
696c0d5e 14214 ptid_t ptid = tp->ptid;
9accd112
MM
14215 set_general_thread (ptid);
14216
14217 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14218 putpkt (rs->buf);
8d64371b 14219 getpkt (&rs->buf, 0);
9accd112
MM
14220
14221 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14222 {
14223 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14224 error (_("Could not enable branch tracing for %s: %s"),
a068643d 14225 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
9accd112
MM
14226 else
14227 error (_("Could not enable branch tracing for %s."),
a068643d 14228 target_pid_to_str (ptid).c_str ());
9accd112
MM
14229 }
14230
8d749320 14231 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
14232 tinfo->ptid = ptid;
14233
f4abbc16
MM
14234 /* If we fail to read the configuration, we lose some information, but the
14235 tracing itself is not impacted. */
a70b8144 14236 try
492d29ea 14237 {
0d8cbc5f 14238 btrace_read_config (tp, &tinfo->conf);
492d29ea 14239 }
230d2906 14240 catch (const gdb_exception_error &err)
492d29ea
PA
14241 {
14242 if (err.message != NULL)
3d6e9d23 14243 warning ("%s", err.what ());
492d29ea 14244 }
f4abbc16 14245
9accd112
MM
14246 return tinfo;
14247}
14248
14249/* Disable branch tracing. */
14250
f6ac5f3d
PA
14251void
14252remote_target::disable_btrace (struct btrace_target_info *tinfo)
9accd112
MM
14253{
14254 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
14255 struct remote_state *rs = get_remote_state ();
8d64371b
TT
14256 char *buf = rs->buf.data ();
14257 char *endbuf = buf + get_remote_packet_size ();
9accd112 14258
4082afcc 14259 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
14260 error (_("Target does not support branch tracing."));
14261
14262 set_general_thread (tinfo->ptid);
14263
14264 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14265 putpkt (rs->buf);
8d64371b 14266 getpkt (&rs->buf, 0);
9accd112
MM
14267
14268 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14269 {
14270 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14271 error (_("Could not disable branch tracing for %s: %s"),
a068643d 14272 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
9accd112
MM
14273 else
14274 error (_("Could not disable branch tracing for %s."),
a068643d 14275 target_pid_to_str (tinfo->ptid).c_str ());
9accd112
MM
14276 }
14277
14278 xfree (tinfo);
14279}
14280
14281/* Teardown branch tracing. */
14282
f6ac5f3d
PA
14283void
14284remote_target::teardown_btrace (struct btrace_target_info *tinfo)
9accd112
MM
14285{
14286 /* We must not talk to the target during teardown. */
14287 xfree (tinfo);
14288}
14289
14290/* Read the branch trace. */
14291
f6ac5f3d
PA
14292enum btrace_error
14293remote_target::read_btrace (struct btrace_data *btrace,
14294 struct btrace_target_info *tinfo,
14295 enum btrace_read_type type)
9accd112
MM
14296{
14297 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
9accd112 14298 const char *annex;
9accd112 14299
4082afcc 14300 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
14301 error (_("Target does not support branch tracing."));
14302
14303#if !defined(HAVE_LIBEXPAT)
14304 error (_("Cannot process branch tracing result. XML parsing not supported."));
14305#endif
14306
14307 switch (type)
14308 {
864089d2 14309 case BTRACE_READ_ALL:
9accd112
MM
14310 annex = "all";
14311 break;
864089d2 14312 case BTRACE_READ_NEW:
9accd112
MM
14313 annex = "new";
14314 break;
969c39fb
MM
14315 case BTRACE_READ_DELTA:
14316 annex = "delta";
14317 break;
9accd112
MM
14318 default:
14319 internal_error (__FILE__, __LINE__,
14320 _("Bad branch tracing read type: %u."),
14321 (unsigned int) type);
14322 }
14323
9018be22 14324 gdb::optional<gdb::char_vector> xml
328d42d8
SM
14325 = target_read_stralloc (current_inferior ()->top_target (),
14326 TARGET_OBJECT_BTRACE, annex);
9018be22 14327 if (!xml)
969c39fb 14328 return BTRACE_ERR_UNKNOWN;
9accd112 14329
9018be22 14330 parse_xml_btrace (btrace, xml->data ());
9accd112 14331
969c39fb 14332 return BTRACE_ERR_NONE;
9accd112
MM
14333}
14334
f6ac5f3d
PA
14335const struct btrace_config *
14336remote_target::btrace_conf (const struct btrace_target_info *tinfo)
f4abbc16
MM
14337{
14338 return &tinfo->conf;
14339}
14340
57810aa7 14341bool
f6ac5f3d 14342remote_target::augmented_libraries_svr4_read ()
ced63ec0 14343{
4082afcc
PA
14344 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
14345 == PACKET_ENABLE);
ced63ec0
GB
14346}
14347
9dd130a0
TT
14348/* Implementation of to_load. */
14349
f6ac5f3d
PA
14350void
14351remote_target::load (const char *name, int from_tty)
9dd130a0
TT
14352{
14353 generic_load (name, from_tty);
14354}
14355
c78fa86a
GB
14356/* Accepts an integer PID; returns a string representing a file that
14357 can be opened on the remote side to get the symbols for the child
14358 process. Returns NULL if the operation is not supported. */
14359
0e90c441 14360const char *
f6ac5f3d 14361remote_target::pid_to_exec_file (int pid)
c78fa86a 14362{
9018be22 14363 static gdb::optional<gdb::char_vector> filename;
835205d0 14364 char *annex = NULL;
c78fa86a
GB
14365
14366 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14367 return NULL;
14368
5b6d1e4f 14369 inferior *inf = find_inferior_pid (this, pid);
835205d0
GB
14370 if (inf == NULL)
14371 internal_error (__FILE__, __LINE__,
14372 _("not currently attached to process %d"), pid);
14373
14374 if (!inf->fake_pid_p)
14375 {
14376 const int annex_size = 9;
14377
224c3ddb 14378 annex = (char *) alloca (annex_size);
835205d0
GB
14379 xsnprintf (annex, annex_size, "%x", pid);
14380 }
14381
328d42d8 14382 filename = target_read_stralloc (current_inferior ()->top_target (),
c78fa86a
GB
14383 TARGET_OBJECT_EXEC_FILE, annex);
14384
9018be22 14385 return filename ? filename->data () : nullptr;
c78fa86a
GB
14386}
14387
750ce8d1
YQ
14388/* Implement the to_can_do_single_step target_ops method. */
14389
f6ac5f3d
PA
14390int
14391remote_target::can_do_single_step ()
750ce8d1
YQ
14392{
14393 /* We can only tell whether target supports single step or not by
14394 supported s and S vCont actions if the stub supports vContSupported
14395 feature. If the stub doesn't support vContSupported feature,
14396 we have conservatively to think target doesn't supports single
14397 step. */
14398 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14399 {
14400 struct remote_state *rs = get_remote_state ();
14401
14402 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 14403 remote_vcont_probe ();
750ce8d1
YQ
14404
14405 return rs->supports_vCont.s && rs->supports_vCont.S;
14406 }
14407 else
14408 return 0;
14409}
14410
3a00c802
PA
14411/* Implementation of the to_execution_direction method for the remote
14412 target. */
14413
f6ac5f3d
PA
14414enum exec_direction_kind
14415remote_target::execution_direction ()
3a00c802
PA
14416{
14417 struct remote_state *rs = get_remote_state ();
14418
14419 return rs->last_resume_exec_dir;
14420}
14421
f6327dcb
KB
14422/* Return pointer to the thread_info struct which corresponds to
14423 THREAD_HANDLE (having length HANDLE_LEN). */
14424
f6ac5f3d
PA
14425thread_info *
14426remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14427 int handle_len,
14428 inferior *inf)
f6327dcb 14429{
5b6d1e4f 14430 for (thread_info *tp : all_non_exited_threads (this))
f6327dcb 14431 {
7aabaf9d 14432 remote_thread_info *priv = get_remote_thread_info (tp);
f6327dcb
KB
14433
14434 if (tp->inf == inf && priv != NULL)
dda83cd7 14435 {
7aabaf9d 14436 if (handle_len != priv->thread_handle.size ())
f6327dcb 14437 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
dda83cd7 14438 handle_len, priv->thread_handle.size ());
7aabaf9d 14439 if (memcmp (thread_handle, priv->thread_handle.data (),
dda83cd7 14440 handle_len) == 0)
f6327dcb
KB
14441 return tp;
14442 }
14443 }
14444
14445 return NULL;
14446}
14447
3d6c6204
KB
14448gdb::byte_vector
14449remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14450{
14451 remote_thread_info *priv = get_remote_thread_info (tp);
14452 return priv->thread_handle;
14453}
14454
57810aa7 14455bool
f6ac5f3d 14456remote_target::can_async_p ()
6426a772 14457{
fce6cd34
AB
14458 /* This flag should be checked in the common target.c code. */
14459 gdb_assert (target_async_permitted);
75c99385 14460
fce6cd34
AB
14461 /* We're async whenever the serial device can. */
14462 struct remote_state *rs = get_remote_state ();
5d93a237 14463 return serial_can_async_p (rs->remote_desc);
6426a772
JM
14464}
14465
57810aa7 14466bool
f6ac5f3d 14467remote_target::is_async_p ()
6426a772 14468{
23860348 14469 /* We're async whenever the serial device is. */
7054fa5b 14470 struct remote_state *rs = get_remote_state ();
5d93a237 14471 return serial_is_async_p (rs->remote_desc);
6426a772
JM
14472}
14473
2acceee2
JM
14474/* Pass the SERIAL event on and up to the client. One day this code
14475 will be able to delay notifying the client of an event until the
23860348 14476 point where an entire packet has been received. */
2acceee2 14477
2acceee2
JM
14478static serial_event_ftype remote_async_serial_handler;
14479
6426a772 14480static void
819cc324 14481remote_async_serial_handler (struct serial *scb, void *context)
6426a772 14482{
2acceee2
JM
14483 /* Don't propogate error information up to the client. Instead let
14484 the client find out about the error by querying the target. */
b1a35af2 14485 inferior_event_handler (INF_REG_EVENT);
2acceee2
JM
14486}
14487
74531fed
PA
14488static void
14489remote_async_inferior_event_handler (gdb_client_data data)
14490{
6b36ddeb 14491 inferior_event_handler (INF_REG_EVENT);
74531fed
PA
14492}
14493
5b6d1e4f
PA
14494int
14495remote_target::async_wait_fd ()
14496{
14497 struct remote_state *rs = get_remote_state ();
14498 return rs->remote_desc->fd;
14499}
14500
f6ac5f3d 14501void
4a570176 14502remote_target::async (bool enable)
2acceee2 14503{
5d93a237
TT
14504 struct remote_state *rs = get_remote_state ();
14505
6a3753b3 14506 if (enable)
2acceee2 14507 {
88b496c3 14508 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
14509
14510 /* If there are pending events in the stop reply queue tell the
14511 event loop to process them. */
953edf2b 14512 if (!rs->stop_reply_queue.empty ())
6b8edb51 14513 mark_async_event_handler (rs->remote_async_inferior_event_token);
6efcd9a8
PA
14514 /* For simplicity, below we clear the pending events token
14515 without remembering whether it is marked, so here we always
14516 mark it. If there's actually no pending notification to
14517 process, this ends up being a no-op (other than a spurious
14518 event-loop wakeup). */
14519 if (target_is_non_stop_p ())
14520 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
14521 }
14522 else
b7d2e916
PA
14523 {
14524 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
14525 /* If the core is disabling async, it doesn't want to be
14526 disturbed with target events. Clear all async event sources
14527 too. */
6b8edb51 14528 clear_async_event_handler (rs->remote_async_inferior_event_token);
6efcd9a8
PA
14529 if (target_is_non_stop_p ())
14530 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 14531 }
6426a772
JM
14532}
14533
65706a29
PA
14534/* Implementation of the to_thread_events method. */
14535
f6ac5f3d
PA
14536void
14537remote_target::thread_events (int enable)
65706a29
PA
14538{
14539 struct remote_state *rs = get_remote_state ();
14540 size_t size = get_remote_packet_size ();
65706a29
PA
14541
14542 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14543 return;
14544
8d64371b 14545 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
65706a29 14546 putpkt (rs->buf);
8d64371b 14547 getpkt (&rs->buf, 0);
65706a29
PA
14548
14549 switch (packet_ok (rs->buf,
14550 &remote_protocol_packets[PACKET_QThreadEvents]))
14551 {
14552 case PACKET_OK:
8d64371b
TT
14553 if (strcmp (rs->buf.data (), "OK") != 0)
14554 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
65706a29
PA
14555 break;
14556 case PACKET_ERROR:
8d64371b 14557 warning (_("Remote failure reply: %s"), rs->buf.data ());
65706a29
PA
14558 break;
14559 case PACKET_UNKNOWN:
14560 break;
14561 }
14562}
14563
d471ea57 14564static void
981a3fb3 14565show_remote_cmd (const char *args, int from_tty)
d471ea57 14566{
37a105a1 14567 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 14568 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1 14569 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 14570 struct ui_out *uiout = current_uiout;
37a105a1 14571
2e783024 14572 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
37a105a1
DJ
14573 for (; list != NULL; list = list->next)
14574 if (strcmp (list->name, "Z-packet") == 0)
14575 continue;
427c3a89
DJ
14576 else if (list->type == not_set_cmd)
14577 /* Alias commands are exactly like the original, except they
14578 don't have the normal type. */
14579 continue;
14580 else
37a105a1 14581 {
2e783024 14582 ui_out_emit_tuple option_emitter (uiout, "option");
a744cf53 14583
112e8700
SM
14584 uiout->field_string ("name", list->name);
14585 uiout->text (": ");
427c3a89 14586 if (list->type == show_cmd)
f5c4fcd9 14587 do_show_command (NULL, from_tty, list);
427c3a89
DJ
14588 else
14589 cmd_func (list, NULL, from_tty);
37a105a1 14590 }
d471ea57 14591}
5a2468f5 14592
0f71a2f6 14593
23860348 14594/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
14595static void
14596remote_new_objfile (struct objfile *objfile)
14597{
06c7226e
SM
14598 /* The objfile change happened in that program space. */
14599 program_space *pspace = current_program_space;
5d93a237 14600
06c7226e
SM
14601 /* The affected program space is possibly shared by multiple inferiors.
14602 Consider sending a qSymbol packet for each of the inferiors using that
14603 program space. */
14604 for (inferior *inf : all_inferiors ())
14605 {
14606 if (inf->pspace != pspace)
14607 continue;
122373f7 14608
06c7226e
SM
14609 /* Check whether the inferior's process target is a remote target. */
14610 remote_target *remote = as_remote_target (inf->process_target ());
14611 if (remote == nullptr)
14612 continue;
14613
14614 /* When we are attaching or handling a fork child and the shared library
14615 subsystem reads the list of loaded libraries, we receive new objfile
14616 events in between each found library. The libraries are read in an
14617 undefined order, so if we gave the remote side a chance to look up
14618 symbols between each objfile, we might give it an inconsistent picture
14619 of the inferior. It could appear that a library A appears loaded but
14620 a library B does not, even though library A requires library B. That
14621 would present a state that couldn't normally exist in the inferior.
14622
14623 So, skip these events, we'll give the remote a chance to look up
14624 symbols once all the loaded libraries and their symbols are known to
14625 GDB. */
14626 if (inf->in_initial_library_scan)
14627 continue;
14628
14629 if (!remote->has_execution (inf))
14630 continue;
14631
14632 /* Need to switch to a specific thread, because remote_check_symbols will
14633 set the general thread using INFERIOR_PTID.
122373f7 14634
06c7226e
SM
14635 It's possible to have inferiors with no thread here, because we are
14636 called very early in the connection process, while the inferior is
14637 being set up, before threads are added. Just skip it, start_remote_1
14638 also calls remote_check_symbols when it's done setting things up. */
14639 thread_info *thread = any_thread_of_inferior (inf);
14640 if (thread != nullptr)
14641 {
14642 scoped_restore_current_thread restore_thread;
14643 switch_to_thread (thread);
14644 remote->remote_check_symbols ();
14645 }
14646 }
dc8acb97
MS
14647}
14648
00bf0b85
SS
14649/* Pull all the tracepoints defined on the target and create local
14650 data structures representing them. We don't want to create real
14651 tracepoints yet, we don't want to mess up the user's existing
14652 collection. */
14653
f6ac5f3d
PA
14654int
14655remote_target::upload_tracepoints (struct uploaded_tp **utpp)
d5551862 14656{
00bf0b85
SS
14657 struct remote_state *rs = get_remote_state ();
14658 char *p;
d5551862 14659
00bf0b85
SS
14660 /* Ask for a first packet of tracepoint definition. */
14661 putpkt ("qTfP");
8d64371b
TT
14662 getpkt (&rs->buf, 0);
14663 p = rs->buf.data ();
00bf0b85 14664 while (*p && *p != 'l')
d5551862 14665 {
00bf0b85
SS
14666 parse_tracepoint_definition (p, utpp);
14667 /* Ask for another packet of tracepoint definition. */
14668 putpkt ("qTsP");
8d64371b
TT
14669 getpkt (&rs->buf, 0);
14670 p = rs->buf.data ();
d5551862 14671 }
00bf0b85 14672 return 0;
d5551862
SS
14673}
14674
f6ac5f3d
PA
14675int
14676remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
d5551862 14677{
00bf0b85 14678 struct remote_state *rs = get_remote_state ();
d5551862 14679 char *p;
d5551862 14680
00bf0b85
SS
14681 /* Ask for a first packet of variable definition. */
14682 putpkt ("qTfV");
8d64371b
TT
14683 getpkt (&rs->buf, 0);
14684 p = rs->buf.data ();
00bf0b85 14685 while (*p && *p != 'l')
d5551862 14686 {
00bf0b85
SS
14687 parse_tsv_definition (p, utsvp);
14688 /* Ask for another packet of variable definition. */
14689 putpkt ("qTsV");
8d64371b
TT
14690 getpkt (&rs->buf, 0);
14691 p = rs->buf.data ();
d5551862 14692 }
00bf0b85 14693 return 0;
d5551862
SS
14694}
14695
c1e36e3e
PA
14696/* The "set/show range-stepping" show hook. */
14697
14698static void
14699show_range_stepping (struct ui_file *file, int from_tty,
14700 struct cmd_list_element *c,
14701 const char *value)
14702{
6cb06a8c
TT
14703 gdb_printf (file,
14704 _("Debugger's willingness to use range stepping "
14705 "is %s.\n"), value);
c1e36e3e
PA
14706}
14707
6b8edb51
PA
14708/* Return true if the vCont;r action is supported by the remote
14709 stub. */
14710
14711bool
14712remote_target::vcont_r_supported ()
14713{
14714 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14715 remote_vcont_probe ();
14716
14717 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14718 && get_remote_state ()->supports_vCont.r);
14719}
14720
c1e36e3e
PA
14721/* The "set/show range-stepping" set hook. */
14722
14723static void
eb4c3f4a 14724set_range_stepping (const char *ignore_args, int from_tty,
c1e36e3e
PA
14725 struct cmd_list_element *c)
14726{
6b8edb51
PA
14727 /* When enabling, check whether range stepping is actually supported
14728 by the target, and warn if not. */
c1e36e3e
PA
14729 if (use_range_stepping)
14730 {
6b8edb51
PA
14731 remote_target *remote = get_current_remote_target ();
14732 if (remote == NULL
14733 || !remote->vcont_r_supported ())
14734 warning (_("Range stepping is not supported by the current target"));
c1e36e3e
PA
14735 }
14736}
14737
baf2b57f
SM
14738static void
14739show_remote_debug (struct ui_file *file, int from_tty,
14740 struct cmd_list_element *c, const char *value)
14741{
6cb06a8c
TT
14742 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
14743 value);
baf2b57f
SM
14744}
14745
14746static void
14747show_remote_timeout (struct ui_file *file, int from_tty,
14748 struct cmd_list_element *c, const char *value)
14749{
6cb06a8c
TT
14750 gdb_printf (file,
14751 _("Timeout limit to wait for target to respond is %s.\n"),
14752 value);
baf2b57f
SM
14753}
14754
dbe692af
LM
14755/* Implement the "supports_memory_tagging" target_ops method. */
14756
14757bool
14758remote_target::supports_memory_tagging ()
14759{
2c2e7f87
LM
14760 return remote_memory_tagging_p ();
14761}
14762
14763/* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
14764
14765static void
14766create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14767 size_t len, int type)
14768{
14769 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14770
14771 std::string request = string_printf ("qMemTags:%s,%s:%s",
14772 phex_nz (address, addr_size),
14773 phex_nz (len, sizeof (len)),
14774 phex_nz (type, sizeof (type)));
14775
14776 strcpy (packet.data (), request.c_str ());
14777}
14778
14779/* Parse the qMemTags packet reply into TAGS.
14780
14781 Return true if successful, false otherwise. */
14782
14783static bool
14784parse_fetch_memtags_reply (const gdb::char_vector &reply,
14785 gdb::byte_vector &tags)
14786{
14787 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
14788 return false;
14789
14790 /* Copy the tag data. */
14791 tags = hex2bin (reply.data () + 1);
14792
14793 return true;
14794}
14795
14796/* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
14797
14798static void
14799create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14800 size_t len, int type,
14801 const gdb::byte_vector &tags)
14802{
14803 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14804
14805 /* Put together the main packet, address and length. */
14806 std::string request = string_printf ("QMemTags:%s,%s:%s:",
14807 phex_nz (address, addr_size),
14808 phex_nz (len, sizeof (len)),
14809 phex_nz (type, sizeof (type)));
14810 request += bin2hex (tags.data (), tags.size ());
14811
14812 /* Check if we have exceeded the maximum packet size. */
14813 if (packet.size () < request.length ())
14814 error (_("Contents too big for packet QMemTags."));
14815
14816 strcpy (packet.data (), request.c_str ());
dbe692af
LM
14817}
14818
14819/* Implement the "fetch_memtags" target_ops method. */
14820
14821bool
14822remote_target::fetch_memtags (CORE_ADDR address, size_t len,
14823 gdb::byte_vector &tags, int type)
14824{
2c2e7f87
LM
14825 /* Make sure the qMemTags packet is supported. */
14826 if (!remote_memory_tagging_p ())
14827 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
14828
14829 struct remote_state *rs = get_remote_state ();
14830
14831 create_fetch_memtags_request (rs->buf, address, len, type);
14832
14833 putpkt (rs->buf);
14834 getpkt (&rs->buf, 0);
14835
14836 return parse_fetch_memtags_reply (rs->buf, tags);
dbe692af
LM
14837}
14838
14839/* Implement the "store_memtags" target_ops method. */
14840
14841bool
14842remote_target::store_memtags (CORE_ADDR address, size_t len,
14843 const gdb::byte_vector &tags, int type)
14844{
2c2e7f87
LM
14845 /* Make sure the QMemTags packet is supported. */
14846 if (!remote_memory_tagging_p ())
14847 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
14848
14849 struct remote_state *rs = get_remote_state ();
14850
14851 create_store_memtags_request (rs->buf, address, len, type, tags);
14852
14853 putpkt (rs->buf);
14854 getpkt (&rs->buf, 0);
14855
14856 /* Verify if the request was successful. */
14857 return packet_check_result (rs->buf.data ()) == PACKET_OK;
dbe692af
LM
14858}
14859
c39ebbf4
TV
14860/* Return true if remote target T is non-stop. */
14861
14862bool
14863remote_target_is_non_stop_p (remote_target *t)
14864{
14865 scoped_restore_current_thread restore_thread;
14866 switch_to_target_no_thread (t);
14867
14868 return target_is_non_stop_p ();
14869}
14870
754487e2
LM
14871#if GDB_SELF_TEST
14872
14873namespace selftests {
14874
14875static void
14876test_memory_tagging_functions ()
14877{
14878 remote_target remote;
14879
14880 struct packet_config *config
14881 = &remote_protocol_packets[PACKET_memory_tagging_feature];
14882
14883 scoped_restore restore_memtag_support_
14884 = make_scoped_restore (&config->support);
14885
14886 /* Test memory tagging packet support. */
14887 config->support = PACKET_SUPPORT_UNKNOWN;
14888 SELF_CHECK (remote.supports_memory_tagging () == false);
14889 config->support = PACKET_DISABLE;
14890 SELF_CHECK (remote.supports_memory_tagging () == false);
14891 config->support = PACKET_ENABLE;
14892 SELF_CHECK (remote.supports_memory_tagging () == true);
14893
14894 /* Setup testing. */
14895 gdb::char_vector packet;
14896 gdb::byte_vector tags, bv;
14897 std::string expected, reply;
14898 packet.resize (32000);
14899
14900 /* Test creating a qMemTags request. */
14901
14902 expected = "qMemTags:0,0:0";
14903 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
14904 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14905
14906 expected = "qMemTags:deadbeef,10:1";
14907 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
14908 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14909
14910 /* Test parsing a qMemTags reply. */
14911
14912 /* Error reply, tags vector unmodified. */
14913 reply = "E00";
14914 strcpy (packet.data (), reply.c_str ());
14915 tags.resize (0);
14916 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
14917 SELF_CHECK (tags.size () == 0);
14918
14919 /* Valid reply, tags vector updated. */
14920 tags.resize (0);
14921 bv.resize (0);
14922
14923 for (int i = 0; i < 5; i++)
14924 bv.push_back (i);
14925
14926 reply = "m" + bin2hex (bv.data (), bv.size ());
14927 strcpy (packet.data (), reply.c_str ());
14928
14929 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
14930 SELF_CHECK (tags.size () == 5);
14931
14932 for (int i = 0; i < 5; i++)
14933 SELF_CHECK (tags[i] == i);
14934
14935 /* Test creating a QMemTags request. */
14936
14937 /* Empty tag data. */
14938 tags.resize (0);
14939 expected = "QMemTags:0,0:0:";
14940 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
14941 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14942 expected.length ()) == 0);
14943
14944 /* Non-empty tag data. */
14945 tags.resize (0);
14946 for (int i = 0; i < 5; i++)
14947 tags.push_back (i);
14948 expected = "QMemTags:deadbeef,ff:1:0001020304";
14949 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
14950 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14951 expected.length ()) == 0);
14952}
14953
14954} // namespace selftests
14955#endif /* GDB_SELF_TEST */
14956
6c265988 14957void _initialize_remote ();
c906108c 14958void
6c265988 14959_initialize_remote ()
c906108c 14960{
d9f719f1
PA
14961 add_target (remote_target_info, remote_target::open);
14962 add_target (extended_remote_target_info, extended_remote_target::open);
cce74817 14963
dc8acb97 14964 /* Hook into new objfile notification. */
c90e7d63 14965 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
dc8acb97 14966
c906108c
SS
14967#if 0
14968 init_remote_threadtests ();
14969#endif
14970
23860348 14971 /* set/show remote ... */
d471ea57 14972
0743fc83 14973 add_basic_prefix_cmd ("remote", class_maintenance, _("\
590042fc 14974Remote protocol specific variables.\n\
5a2468f5 14975Configure various remote-protocol specific variables such as\n\
590042fc 14976the packets being used."),
2f822da5 14977 &remote_set_cmdlist,
0743fc83 14978 0 /* allow-unknown */, &setlist);
1bedd215 14979 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
590042fc 14980Remote protocol specific variables.\n\
5a2468f5 14981Configure various remote-protocol specific variables such as\n\
590042fc 14982the packets being used."),
2f822da5 14983 &remote_show_cmdlist,
23860348 14984 0 /* allow-unknown */, &showlist);
5a2468f5 14985
1a966eab
AC
14986 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14987Compare section data on target to the exec file.\n\
95cf3b38
DT
14988Argument is a single section name (default: all loaded sections).\n\
14989To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
14990 &cmdlist);
14991
e5b176f2 14992 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
1a966eab 14993Send an arbitrary packet to a remote target.\n\
c906108c
SS
14994 maintenance packet TEXT\n\
14995If GDB is talking to an inferior via the GDB serial protocol, then\n\
14996this command sends the string TEXT to the inferior, and displays the\n\
14997response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 14998terminating `#' character and checksum."),
c906108c
SS
14999 &maintenancelist);
15000
9f260536
SM
15001 set_show_commands remotebreak_cmds
15002 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
7915a72c
AC
15003Set whether to send break if interrupted."), _("\
15004Show whether to send break if interrupted."), _("\
15005If set, a break, instead of a cntrl-c, is sent to the remote target."),
9f260536
SM
15006 set_remotebreak, show_remotebreak,
15007 &setlist, &showlist);
15008 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
15009 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
9a7071a8
JB
15010
15011 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
15012 interrupt_sequence_modes, &interrupt_sequence_mode,
15013 _("\
9a7071a8
JB
15014Set interrupt sequence to remote target."), _("\
15015Show interrupt sequence to remote target."), _("\
15016Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
15017 NULL, show_interrupt_sequence,
15018 &remote_set_cmdlist,
15019 &remote_show_cmdlist);
15020
15021 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
15022 &interrupt_on_connect, _("\
590042fc
PW
15023Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15024Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
9a7071a8
JB
15025If set, interrupt sequence is sent to remote target."),
15026 NULL, NULL,
15027 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 15028
23860348 15029 /* Install commands for configuring memory read/write packets. */
11cf8741 15030
1a966eab
AC
15031 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
15032Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 15033 &setlist);
1a966eab
AC
15034 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
15035Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
15036 &showlist);
15037 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
15038 set_memory_write_packet_size, _("\
15039Set the maximum number of bytes per memory-write packet.\n\
15040Specify the number of bytes in a packet or 0 (zero) for the\n\
15041default packet size. The actual limit is further reduced\n\
15042dependent on the target. Specify ``fixed'' to disable the\n\
15043further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
15044 &remote_set_cmdlist);
15045 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
15046 set_memory_read_packet_size, _("\
15047Set the maximum number of bytes per memory-read packet.\n\
15048Specify the number of bytes in a packet or 0 (zero) for the\n\
15049default packet size. The actual limit is further reduced\n\
15050dependent on the target. Specify ``fixed'' to disable the\n\
15051further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
15052 &remote_set_cmdlist);
15053 add_cmd ("memory-write-packet-size", no_class,
15054 show_memory_write_packet_size,
1a966eab 15055 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
15056 &remote_show_cmdlist);
15057 add_cmd ("memory-read-packet-size", no_class,
15058 show_memory_read_packet_size,
1a966eab 15059 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 15060 &remote_show_cmdlist);
c906108c 15061
055303e2 15062 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
15063 &remote_hw_watchpoint_limit, _("\
15064Set the maximum number of target hardware watchpoints."), _("\
15065Show the maximum number of target hardware watchpoints."), _("\
055303e2
AB
15066Specify \"unlimited\" for unlimited hardware watchpoints."),
15067 NULL, show_hardware_watchpoint_limit,
15068 &remote_set_cmdlist,
15069 &remote_show_cmdlist);
15070 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15071 no_class,
480a3f21
PW
15072 &remote_hw_watchpoint_length_limit, _("\
15073Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15074Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
055303e2
AB
15075Specify \"unlimited\" to allow watchpoints of unlimited size."),
15076 NULL, show_hardware_watchpoint_length_limit,
480a3f21 15077 &remote_set_cmdlist, &remote_show_cmdlist);
055303e2 15078 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
15079 &remote_hw_breakpoint_limit, _("\
15080Set the maximum number of target hardware breakpoints."), _("\
15081Show the maximum number of target hardware breakpoints."), _("\
055303e2
AB
15082Specify \"unlimited\" for unlimited hardware breakpoints."),
15083 NULL, show_hardware_breakpoint_limit,
b3f42336 15084 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 15085
1b493192
PA
15086 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15087 &remote_address_size, _("\
4d28ad1e
AC
15088Set the maximum size of the address (in bits) in a memory packet."), _("\
15089Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
15090 NULL,
15091 NULL, /* FIXME: i18n: */
15092 &setlist, &showlist);
c906108c 15093
ca4f7f8b
PA
15094 init_all_packet_configs ();
15095
444abaca 15096 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 15097 "X", "binary-download", 1);
0f71a2f6 15098
444abaca 15099 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 15100 "vCont", "verbose-resume", 0);
506fb367 15101
89be2091
DJ
15102 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
15103 "QPassSignals", "pass-signals", 0);
15104
82075af2
JS
15105 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
15106 "QCatchSyscalls", "catch-syscalls", 0);
15107
9b224c5e
PA
15108 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
15109 "QProgramSignals", "program-signals", 0);
15110
bc3b087d
SDJ
15111 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
15112 "QSetWorkingDir", "set-working-dir", 0);
15113
aefd8b33
SDJ
15114 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
15115 "QStartupWithShell", "startup-with-shell", 0);
15116
0a2dde4a
SDJ
15117 add_packet_config_cmd (&remote_protocol_packets
15118 [PACKET_QEnvironmentHexEncoded],
15119 "QEnvironmentHexEncoded", "environment-hex-encoded",
15120 0);
15121
15122 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
15123 "QEnvironmentReset", "environment-reset",
15124 0);
15125
15126 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
15127 "QEnvironmentUnset", "environment-unset",
15128 0);
15129
444abaca 15130 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 15131 "qSymbol", "symbol-lookup", 0);
dc8acb97 15132
444abaca 15133 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 15134 "P", "set-register", 1);
d471ea57 15135
444abaca 15136 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 15137 "p", "fetch-register", 1);
b96ec7ac 15138
444abaca 15139 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 15140 "Z0", "software-breakpoint", 0);
d471ea57 15141
444abaca 15142 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 15143 "Z1", "hardware-breakpoint", 0);
d471ea57 15144
444abaca 15145 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 15146 "Z2", "write-watchpoint", 0);
d471ea57 15147
444abaca 15148 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 15149 "Z3", "read-watchpoint", 0);
d471ea57 15150
444abaca 15151 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 15152 "Z4", "access-watchpoint", 0);
d471ea57 15153
0876f84a
DJ
15154 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
15155 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 15156
c78fa86a
GB
15157 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
15158 "qXfer:exec-file:read", "pid-to-exec-file", 0);
15159
23181151
DJ
15160 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
15161 "qXfer:features:read", "target-features", 0);
15162
cfa9d6d9
DJ
15163 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
15164 "qXfer:libraries:read", "library-info", 0);
15165
2268b414
JK
15166 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
15167 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15168
fd79ecee
DJ
15169 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
15170 "qXfer:memory-map:read", "memory-map", 0);
15171
07e059b5 15172 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
dda83cd7 15173 "qXfer:osdata:read", "osdata", 0);
07e059b5 15174
dc146f7c
VP
15175 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
15176 "qXfer:threads:read", "threads", 0);
15177
4aa995e1 15178 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
dda83cd7 15179 "qXfer:siginfo:read", "read-siginfo-object", 0);
4aa995e1
PA
15180
15181 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
dda83cd7 15182 "qXfer:siginfo:write", "write-siginfo-object", 0);
4aa995e1 15183
b3b9301e
PA
15184 add_packet_config_cmd
15185 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 15186 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 15187
169081d0
TG
15188 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
15189 "qXfer:uib:read", "unwind-info-block", 0);
15190
444abaca 15191 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 15192 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
15193 0);
15194
711e434b
PM
15195 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
15196 "qGetTIBAddr", "get-thread-information-block-address",
15197 0);
15198
40ab02ce
MS
15199 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
15200 "bc", "reverse-continue", 0);
15201
15202 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
15203 "bs", "reverse-step", 0);
15204
be2a5f71
DJ
15205 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
15206 "qSupported", "supported-packets", 0);
15207
08388c79
DE
15208 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
15209 "qSearch:memory", "search-memory", 0);
15210
bd3eecc3
PA
15211 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
15212 "qTStatus", "trace-status", 0);
15213
15a201c8
GB
15214 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
15215 "vFile:setfs", "hostio-setfs", 0);
15216
a6b151f1
DJ
15217 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
15218 "vFile:open", "hostio-open", 0);
15219
15220 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
15221 "vFile:pread", "hostio-pread", 0);
15222
15223 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
15224 "vFile:pwrite", "hostio-pwrite", 0);
15225
15226 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
15227 "vFile:close", "hostio-close", 0);
15228
15229 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
15230 "vFile:unlink", "hostio-unlink", 0);
15231
b9e7b9c3
UW
15232 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
15233 "vFile:readlink", "hostio-readlink", 0);
15234
0a93529c
GB
15235 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
15236 "vFile:fstat", "hostio-fstat", 0);
15237
2d717e4f
DJ
15238 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
15239 "vAttach", "attach", 0);
15240
15241 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
15242 "vRun", "run", 0);
15243
a6f3e723
SL
15244 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
15245 "QStartNoAckMode", "noack", 0);
15246
82f73884
PA
15247 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
15248 "vKill", "kill", 0);
15249
0b16c5cf
PA
15250 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
15251 "qAttached", "query-attached", 0);
15252
782b2b07 15253 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
15254 "ConditionalTracepoints",
15255 "conditional-tracepoints", 0);
3788aec7
LM
15256
15257 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
15258 "ConditionalBreakpoints",
15259 "conditional-breakpoints", 0);
15260
d3ce09f5
SS
15261 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
15262 "BreakpointCommands",
15263 "breakpoint-commands", 0);
15264
7a697b8d
SS
15265 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
15266 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 15267
409873ef
SS
15268 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
15269 "TracepointSource", "TracepointSource", 0);
15270
d914c394
SS
15271 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
15272 "QAllow", "allow", 0);
15273
0fb4aa4b
PA
15274 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
15275 "StaticTracepoints", "static-tracepoints", 0);
15276
1e4d1764
YQ
15277 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
15278 "InstallInTrace", "install-in-trace", 0);
15279
0fb4aa4b 15280 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
dda83cd7 15281 "qXfer:statictrace:read", "read-sdata-object", 0);
0fb4aa4b 15282
78d85199
YQ
15283 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
15284 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
15285
03583c20
UW
15286 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
15287 "QDisableRandomization", "disable-randomization", 0);
15288
d1feda86
YQ
15289 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
15290 "QAgent", "agent", 0);
15291
f6f899bf
HAQ
15292 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
15293 "QTBuffer:size", "trace-buffer-size", 0);
15294
9accd112
MM
15295 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
15296 "Qbtrace:off", "disable-btrace", 0);
15297
15298 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
15299 "Qbtrace:bts", "enable-btrace-bts", 0);
15300
15301 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
15302 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
15303
15304 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
15305 "qXfer:btrace", "read-btrace", 0);
15306
f4abbc16
MM
15307 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
15308 "qXfer:btrace-conf", "read-btrace-conf", 0);
15309
d33501a5
MM
15310 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
15311 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
15312
73b8c1fd
PA
15313 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
15314 "multiprocess-feature", "multiprocess-feature", 0);
15315
f7e6eed5 15316 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
dda83cd7 15317 "swbreak-feature", "swbreak-feature", 0);
f7e6eed5
PA
15318
15319 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
dda83cd7 15320 "hwbreak-feature", "hwbreak-feature", 0);
f7e6eed5 15321
89245bc0
DB
15322 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
15323 "fork-event-feature", "fork-event-feature", 0);
15324
15325 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
15326 "vfork-event-feature", "vfork-event-feature", 0);
15327
b20a6524
MM
15328 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
15329 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
15330
750ce8d1
YQ
15331 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
15332 "vContSupported", "verbose-resume-supported", 0);
15333
94585166
DB
15334 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
15335 "exec-event-feature", "exec-event-feature", 0);
15336
de979965
PA
15337 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
15338 "vCtrlC", "ctrl-c", 0);
15339
65706a29
PA
15340 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
15341 "QThreadEvents", "thread-events", 0);
15342
f2faf941
PA
15343 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
15344 "N stop reply", "no-resumed-stop-reply", 0);
15345
2c2e7f87
LM
15346 add_packet_config_cmd (&remote_protocol_packets[PACKET_memory_tagging_feature],
15347 "memory-tagging-feature", "memory-tagging-feature", 0);
15348
0b736949
DB
15349 /* Assert that we've registered "set remote foo-packet" commands
15350 for all packet configs. */
ca4f7f8b
PA
15351 {
15352 int i;
15353
15354 for (i = 0; i < PACKET_MAX; i++)
15355 {
15356 /* Ideally all configs would have a command associated. Some
15357 still don't though. */
15358 int excepted;
15359
15360 switch (i)
15361 {
15362 case PACKET_QNonStop:
ca4f7f8b
PA
15363 case PACKET_EnableDisableTracepoints_feature:
15364 case PACKET_tracenz_feature:
15365 case PACKET_DisconnectedTracing_feature:
15366 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
15367 case PACKET_qCRC:
15368 /* Additions to this list need to be well justified:
15369 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
15370 excepted = 1;
15371 break;
15372 default:
15373 excepted = 0;
15374 break;
15375 }
15376
15377 /* This catches both forgetting to add a config command, and
15378 forgetting to remove a packet from the exception list. */
15379 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
15380 }
15381 }
15382
37a105a1
DJ
15383 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15384 Z sub-packet has its own set and show commands, but users may
15385 have sets to this variable in their .gdbinit files (or in their
15386 documentation). */
e9e68a56 15387 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c 15388 &remote_Z_packet_detect, _("\
590042fc
PW
15389Set use of remote protocol `Z' packets."), _("\
15390Show use of remote protocol `Z' packets."), _("\
3b64bf98 15391When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 15392packets."),
e9e68a56 15393 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
15394 show_remote_protocol_Z_packet_cmd,
15395 /* FIXME: i18n: Use of remote protocol
15396 `Z' packets is %s. */
e9e68a56 15397 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 15398
0743fc83 15399 add_basic_prefix_cmd ("remote", class_files, _("\
590042fc 15400Manipulate files on the remote system.\n\
a6b151f1 15401Transfer files to and from the remote target system."),
2f822da5 15402 &remote_cmdlist,
0743fc83 15403 0 /* allow-unknown */, &cmdlist);
a6b151f1
DJ
15404
15405 add_cmd ("put", class_files, remote_put_command,
15406 _("Copy a local file to the remote system."),
15407 &remote_cmdlist);
15408
15409 add_cmd ("get", class_files, remote_get_command,
15410 _("Copy a remote file to the local system."),
15411 &remote_cmdlist);
15412
15413 add_cmd ("delete", class_files, remote_delete_command,
15414 _("Delete a remote file."),
15415 &remote_cmdlist);
15416
2d717e4f 15417 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 15418 &remote_exec_file_var, _("\
590042fc
PW
15419Set the remote pathname for \"run\"."), _("\
15420Show the remote pathname for \"run\"."), NULL,
94585166
DB
15421 set_remote_exec_file,
15422 show_remote_exec_file,
15423 &remote_set_cmdlist,
15424 &remote_show_cmdlist);
2d717e4f 15425
c1e36e3e
PA
15426 add_setshow_boolean_cmd ("range-stepping", class_run,
15427 &use_range_stepping, _("\
15428Enable or disable range stepping."), _("\
15429Show whether target-assisted range stepping is enabled."), _("\
15430If on, and the target supports it, when stepping a source line, GDB\n\
15431tells the target to step the corresponding range of addresses itself instead\n\
15432of issuing multiple single-steps. This speeds up source level\n\
15433stepping. If off, GDB always issues single-steps, even if range\n\
15434stepping is supported by the target. The default is on."),
15435 set_range_stepping,
15436 show_range_stepping,
15437 &setlist,
15438 &showlist);
15439
ed2b7c17
TT
15440 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15441Set watchdog timer."), _("\
15442Show watchdog timer."), _("\
15443When non-zero, this timeout is used instead of waiting forever for a target\n\
15444to finish a low-level step or continue operation. If the specified amount\n\
15445of time passes without a response from the target, an error occurs."),
15446 NULL,
15447 show_watchdog,
15448 &setlist, &showlist);
15449
6cc8564b
LM
15450 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15451 &remote_packet_max_chars, _("\
15452Set the maximum number of characters to display for each remote packet."), _("\
15453Show the maximum number of characters to display for each remote packet."), _("\
15454Specify \"unlimited\" to display all the characters."),
15455 NULL, show_remote_packet_max_chars,
15456 &setdebuglist, &showdebuglist);
15457
02349803
SM
15458 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15459 _("Set debugging of remote protocol."),
15460 _("Show debugging of remote protocol."),
15461 _("\
baf2b57f
SM
15462When enabled, each packet sent or received with the remote target\n\
15463is displayed."),
02349803
SM
15464 NULL,
15465 show_remote_debug,
15466 &setdebuglist, &showdebuglist);
baf2b57f
SM
15467
15468 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15469 &remote_timeout, _("\
15470Set timeout limit to wait for target to respond."), _("\
15471Show timeout limit to wait for target to respond."), _("\
15472This value is used to set the time limit for gdb to wait for a response\n\
15473from the target."),
15474 NULL,
15475 show_remote_timeout,
15476 &setlist, &showlist);
15477
449092f6 15478 /* Eventually initialize fileio. See fileio.c */
3f4d92eb 15479 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
754487e2
LM
15480
15481#if GDB_SELF_TEST
15482 selftests::register_test ("remote_memory_tagging",
15483 selftests::test_memory_tagging_functions);
15484#endif
c906108c 15485}