]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/remote.c
Convert ranged breakpoints to vtable ops
[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"
a6b151f1 62#include "gdb/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
511 char *pid_to_exec_file (int pid) override;
512
513 void log_command (const char *cmd) override
514 {
515 serial_log_command (this, cmd);
516 }
517
518 CORE_ADDR get_thread_local_address (ptid_t ptid,
519 CORE_ADDR load_module_addr,
520 CORE_ADDR offset) override;
521
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
PA
539
540 void async (int) override;
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,
563 int *target_errno) override;
564
565 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
566 ULONGEST offset, int *target_errno) override;
567
568 int fileio_pread (int fd, gdb_byte *read_buf, int len,
569 ULONGEST offset, int *target_errno) override;
570
571 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
572
573 int fileio_close (int fd, int *target_errno) override;
574
575 int fileio_unlink (struct inferior *inf,
576 const char *filename,
577 int *target_errno) override;
578
579 gdb::optional<std::string>
580 fileio_readlink (struct inferior *inf,
581 const char *filename,
582 int *target_errno) override;
583
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,
704 ULONGEST offset, int *remote_errno);
705 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
706 ULONGEST offset, int *remote_errno);
707 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
708 ULONGEST offset, int *remote_errno);
709
710 int remote_hostio_send_command (int command_bytes, int which_packet,
aa2838cc 711 int *remote_errno, const char **attachment,
6b8edb51
PA
712 int *attachment_len);
713 int remote_hostio_set_filesystem (struct inferior *inf,
714 int *remote_errno);
715 /* We should get rid of this and use fileio_open directly. */
716 int remote_hostio_open (struct inferior *inf, const char *filename,
717 int flags, int mode, int warn_if_slow,
718 int *remote_errno);
719 int remote_hostio_close (int fd, int *remote_errno);
720
721 int remote_hostio_unlink (inferior *inf, const char *filename,
722 int *remote_errno);
723
724 struct remote_state *get_remote_state ();
725
726 long get_remote_packet_size (void);
727 long get_memory_packet_size (struct memory_packet_config *config);
728
729 long get_memory_write_packet_size ();
730 long get_memory_read_packet_size ();
731
732 char *append_pending_thread_resumptions (char *p, char *endp,
733 ptid_t ptid);
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
24b2de7b
AB
1019/* See remote.h. */
1020
1021bool
1022is_remote_target (process_stratum_target *target)
1023{
1024 remote_target *rt = dynamic_cast<remote_target *> (target);
1025 return rt != nullptr;
1026}
1027
3c69da40 1028/* Per-program-space data key. */
7b4a314f
TT
1029static const struct program_space_key<char, gdb::xfree_deleter<char>>
1030 remote_pspace_data;
2d717e4f 1031
3c69da40
PA
1032/* The variable registered as the control variable used by the
1033 remote exec-file commands. While the remote exec-file setting is
1034 per-program-space, the set/show machinery uses this as the
1035 location of the remote exec-file value. */
e0700ba4 1036static std::string remote_exec_file_var;
a6f3e723 1037
3c69da40
PA
1038/* The size to align memory write packets, when practical. The protocol
1039 does not guarantee any alignment, and gdb will generate short
1040 writes and unaligned writes, but even as a best-effort attempt this
1041 can improve bulk transfers. For instance, if a write is misaligned
1042 relative to the target's data bus, the stub may need to make an extra
1043 round trip fetching data from the target. This doesn't make a
1044 huge difference, but it's easy to do, so we try to be helpful.
82f73884 1045
3c69da40
PA
1046 The alignment chosen is arbitrary; usually data bus width is
1047 important here, not the possibly larger cache line size. */
1048enum { REMOTE_ALIGN_WRITES = 16 };
82f73884 1049
3c69da40 1050/* Prototypes for local functions. */
74531fed 1051
3c69da40 1052static int hexnumlen (ULONGEST num);
782b2b07 1053
3c69da40 1054static int stubhex (int ch);
5d93a237 1055
3c69da40 1056static int hexnumstr (char *, ULONGEST);
048094ac 1057
3c69da40 1058static int hexnumnstr (char *, ULONGEST, int);
47f8a51d 1059
3c69da40 1060static CORE_ADDR remote_address_masked (CORE_ADDR);
262e1174 1061
cecb1912 1062static int stub_unpack_int (const char *buff, int fieldlength);
5e4a05c4 1063
3c69da40 1064struct packet_config;
b73be471 1065
3c69da40
PA
1066static void show_remote_protocol_packet_cmd (struct ui_file *file,
1067 int from_tty,
1068 struct cmd_list_element *c,
1069 const char *value);
8e88304f 1070
3c69da40 1071static ptid_t read_ptid (const char *buf, const char **obuf);
3a00c802 1072
3c69da40 1073static void remote_async_inferior_event_handler (gdb_client_data);
b80fafe3 1074
eefce37f 1075static bool remote_read_description_p (struct target_ops *target);
88b496c3 1076
05be00a8 1077static void remote_console_output (const char *msg);
5965e028 1078
3c69da40 1079static void remote_btrace_reset (remote_state *rs);
f4abbc16 1080
5b6d1e4f 1081static void remote_unpush_and_throw (remote_target *target);
15a201c8 1082
3c69da40 1083/* For "remote". */
80152258 1084
3c69da40 1085static struct cmd_list_element *remote_cmdlist;
9d6eea31 1086
3c69da40 1087/* For "set remote" and "show remote". */
6b8edb51 1088
3c69da40
PA
1089static struct cmd_list_element *remote_set_cmdlist;
1090static struct cmd_list_element *remote_show_cmdlist;
6b8edb51 1091
3c69da40 1092/* Controls whether GDB is willing to use range stepping. */
6b8edb51 1093
491144b5 1094static bool use_range_stepping = true;
3c69da40 1095
c9d22089
SM
1096/* From the remote target's point of view, each thread is in one of these three
1097 states. */
1098enum class resume_state
1099{
1100 /* Not resumed - we haven't been asked to resume this thread. */
1101 NOT_RESUMED,
1102
1103 /* We have been asked to resume this thread, but haven't sent a vCont action
1104 for it yet. We'll need to consider it next time commit_resume is
1105 called. */
1106 RESUMED_PENDING_VCONT,
1107
1108 /* We have been asked to resume this thread, and we have sent a vCont action
1109 for it. */
1110 RESUMED,
1111};
1112
1113/* Information about a thread's pending vCont-resume. Used when a thread is in
1114 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1115 stores this information which is then picked up by
1116 remote_target::commit_resume to know which is the proper action for this
1117 thread to include in the vCont packet. */
1118struct resumed_pending_vcont_info
1119{
1120 /* True if the last resume call for this thread was a step request, false
1121 if a continue request. */
1122 bool step;
1123
1124 /* The signal specified in the last resume call for this thread. */
1125 gdb_signal sig;
1126};
1127
7aabaf9d
SM
1128/* Private data that we'll store in (struct thread_info)->priv. */
1129struct remote_thread_info : public private_thread_info
dc146f7c 1130{
7aabaf9d
SM
1131 std::string extra;
1132 std::string name;
1133 int core = -1;
799a2abe 1134
f6327dcb
KB
1135 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1136 sequence of bytes. */
7aabaf9d 1137 gdb::byte_vector thread_handle;
f6327dcb 1138
799a2abe 1139 /* Whether the target stopped for a breakpoint/watchpoint. */
7aabaf9d 1140 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
799a2abe
PA
1141
1142 /* This is set to the data address of the access causing the target
1143 to stop for a watchpoint. */
7aabaf9d 1144 CORE_ADDR watch_data_address = 0;
85ad3aaf 1145
c9d22089 1146 /* Get the thread's resume state. */
a6c11cbb 1147 enum resume_state get_resume_state () const
c9d22089
SM
1148 {
1149 return m_resume_state;
1150 }
1151
1152 /* Put the thread in the NOT_RESUMED state. */
1153 void set_not_resumed ()
1154 {
1155 m_resume_state = resume_state::NOT_RESUMED;
1156 }
85ad3aaf 1157
c9d22089
SM
1158 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1159 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1160 {
1161 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1162 m_resumed_pending_vcont_info.step = step;
1163 m_resumed_pending_vcont_info.sig = sig;
1164 }
85ad3aaf 1165
c9d22089 1166 /* Get the information this thread's pending vCont-resumption.
85ad3aaf 1167
c9d22089
SM
1168 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1169 state. */
1170 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1171 {
1172 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1173
1174 return m_resumed_pending_vcont_info;
1175 }
1176
1177 /* Put the thread in the VCONT_RESUMED state. */
1178 void set_resumed ()
1179 {
1180 m_resume_state = resume_state::RESUMED;
1181 }
1182
1183private:
1184 /* Resume state for this thread. This is used to implement vCont action
1185 coalescing (only when the target operates in non-stop mode).
1186
1187 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1188 which notes that this thread must be considered in the next commit_resume
1189 call.
1190
1191 remote_target::commit_resume sends a vCont packet with actions for the
1192 threads in the RESUMED_PENDING_VCONT state and moves them to the
1193 VCONT_RESUMED state.
1194
1195 When reporting a stop to the core for a thread, that thread is moved back
1196 to the NOT_RESUMED state. */
1197 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1198
1199 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1200 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
dc146f7c
VP
1201};
1202
de44f5a7 1203remote_state::remote_state ()
8d64371b 1204 : buf (400)
de44f5a7 1205{
de44f5a7
PA
1206}
1207
1208remote_state::~remote_state ()
1209{
1210 xfree (this->last_pass_packet);
1211 xfree (this->last_program_signals_packet);
de44f5a7
PA
1212 xfree (this->finished_object);
1213 xfree (this->finished_annex);
cf792862
TT
1214}
1215
35b1e5cc
SS
1216/* Utility: generate error from an incoming stub packet. */
1217static void
1218trace_error (char *buf)
1219{
1220 if (*buf++ != 'E')
1221 return; /* not an error msg */
1222 switch (*buf)
1223 {
1224 case '1': /* malformed packet error */
1225 if (*++buf == '0') /* general case: */
1226 error (_("remote.c: error in outgoing packet."));
1227 else
1228 error (_("remote.c: error in outgoing packet at field #%ld."),
1229 strtol (buf, NULL, 16));
35b1e5cc
SS
1230 default:
1231 error (_("Target returns error code '%s'."), buf);
1232 }
1233}
1234
1235/* Utility: wait for reply from stub, while accepting "O" packets. */
b6bb3468 1236
6b8edb51
PA
1237char *
1238remote_target::remote_get_noisy_reply ()
35b1e5cc 1239{
b6bb3468
PA
1240 struct remote_state *rs = get_remote_state ();
1241
35b1e5cc
SS
1242 do /* Loop on reply from remote stub. */
1243 {
1244 char *buf;
a744cf53 1245
0df8b418 1246 QUIT; /* Allow user to bail out with ^C. */
8d64371b
TT
1247 getpkt (&rs->buf, 0);
1248 buf = rs->buf.data ();
ad91cd99 1249 if (buf[0] == 'E')
35b1e5cc 1250 trace_error (buf);
61012eef 1251 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
1252 {
1253 ULONGEST ul;
1254 CORE_ADDR from, to, org_to;
256642e8 1255 const char *p, *pp;
dde08ee1 1256 int adjusted_size = 0;
7556d4a4 1257 int relocated = 0;
dde08ee1
PA
1258
1259 p = buf + strlen ("qRelocInsn:");
1260 pp = unpack_varlen_hex (p, &ul);
1261 if (*pp != ';')
cb91c06a 1262 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
1263 from = ul;
1264
1265 p = pp + 1;
a9cbf802 1266 unpack_varlen_hex (p, &ul);
dde08ee1
PA
1267 to = ul;
1268
1269 org_to = to;
1270
a70b8144 1271 try
dde08ee1 1272 {
f5656ead 1273 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 1274 relocated = 1;
dde08ee1 1275 }
230d2906 1276 catch (const gdb_exception &ex)
7556d4a4
PA
1277 {
1278 if (ex.error == MEMORY_ERROR)
1279 {
1280 /* Propagate memory errors silently back to the
1281 target. The stub may have limited the range of
1282 addresses we can write to, for example. */
1283 }
1284 else
1285 {
1286 /* Something unexpectedly bad happened. Be verbose
1287 so we can tell what, and propagate the error back
1288 to the stub, so it doesn't get stuck waiting for
1289 a response. */
1290 exception_fprintf (gdb_stderr, ex,
1291 _("warning: relocating instruction: "));
1292 }
1293 putpkt ("E01");
1294 }
1295
1296 if (relocated)
dde08ee1
PA
1297 {
1298 adjusted_size = to - org_to;
1299
8d64371b 1300 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
1301 putpkt (buf);
1302 }
dde08ee1 1303 }
ad91cd99 1304 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
1305 remote_console_output (buf + 1); /* 'O' message from stub */
1306 else
0df8b418 1307 return buf; /* Here's the actual reply. */
35b1e5cc
SS
1308 }
1309 while (1);
1310}
3c3bea1c 1311
9d6eea31
PA
1312struct remote_arch_state *
1313remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
d01949b6 1314{
43c3a0e4
PA
1315 remote_arch_state *rsa;
1316
1317 auto it = this->m_arch_states.find (gdbarch);
1318 if (it == this->m_arch_states.end ())
9d6eea31 1319 {
43c3a0e4
PA
1320 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1321 std::forward_as_tuple (gdbarch),
1322 std::forward_as_tuple (gdbarch));
1323 rsa = &p.first->second;
9d6eea31
PA
1324
1325 /* Make sure that the packet buffer is plenty big enough for
1326 this architecture. */
8d64371b
TT
1327 if (this->buf.size () < rsa->remote_packet_size)
1328 this->buf.resize (2 * rsa->remote_packet_size);
9d6eea31 1329 }
43c3a0e4
PA
1330 else
1331 rsa = &it->second;
1332
1333 return rsa;
d01949b6
AC
1334}
1335
0b83947e
DJ
1336/* Fetch the global remote target state. */
1337
6b8edb51
PA
1338remote_state *
1339remote_target::get_remote_state ()
0b83947e
DJ
1340{
1341 /* Make sure that the remote architecture state has been
1342 initialized, because doing so might reallocate rs->buf. Any
1343 function which calls getpkt also needs to be mindful of changes
1344 to rs->buf, but this call limits the number of places which run
1345 into trouble. */
3c69da40 1346 m_remote_state.get_remote_arch_state (target_gdbarch ());
0b83947e 1347
3c69da40 1348 return &m_remote_state;
0b83947e
DJ
1349}
1350
94585166
DB
1351/* Fetch the remote exec-file from the current program space. */
1352
1353static const char *
1354get_remote_exec_file (void)
1355{
1356 char *remote_exec_file;
1357
7b4a314f 1358 remote_exec_file = remote_pspace_data.get (current_program_space);
94585166
DB
1359 if (remote_exec_file == NULL)
1360 return "";
1361
1362 return remote_exec_file;
1363}
1364
1365/* Set the remote exec file for PSPACE. */
1366
1367static void
1368set_pspace_remote_exec_file (struct program_space *pspace,
7b4a314f 1369 const char *remote_exec_file)
94585166 1370{
7b4a314f 1371 char *old_file = remote_pspace_data.get (pspace);
94585166
DB
1372
1373 xfree (old_file);
7b4a314f 1374 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
94585166
DB
1375}
1376
1377/* The "set/show remote exec-file" set command hook. */
1378
1379static void
eb4c3f4a 1380set_remote_exec_file (const char *ignored, int from_tty,
94585166
DB
1381 struct cmd_list_element *c)
1382{
e0700ba4
SM
1383 set_pspace_remote_exec_file (current_program_space,
1384 remote_exec_file_var.c_str ());
94585166
DB
1385}
1386
1387/* The "set/show remote exec-file" show command hook. */
1388
1389static void
1390show_remote_exec_file (struct ui_file *file, int from_tty,
1391 struct cmd_list_element *cmd, const char *value)
1392{
6cb06a8c 1393 gdb_printf (file, "%s\n", get_remote_exec_file ());
94585166
DB
1394}
1395
c21236dc
PA
1396static int
1397map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 1398{
74ca34ce 1399 int regnum, num_remote_regs, offset;
74ca34ce 1400 struct packet_reg **remote_regs;
ea9c271d 1401
4a22f64d 1402 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 1403 {
c21236dc 1404 struct packet_reg *r = &regs[regnum];
baef701f 1405
4a22f64d 1406 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
1407 /* Do not try to fetch zero-sized (placeholder) registers. */
1408 r->pnum = -1;
1409 else
1410 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1411
b323314b 1412 r->regnum = regnum;
74ca34ce
DJ
1413 }
1414
1415 /* Define the g/G packet format as the contents of each register
1416 with a remote protocol number, in order of ascending protocol
1417 number. */
1418
224c3ddb 1419 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 1420 for (num_remote_regs = 0, regnum = 0;
4a22f64d 1421 regnum < gdbarch_num_regs (gdbarch);
f57d151a 1422 regnum++)
c21236dc
PA
1423 if (regs[regnum].pnum != -1)
1424 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 1425
39ef2f62
CB
1426 std::sort (remote_regs, remote_regs + num_remote_regs,
1427 [] (const packet_reg *a, const packet_reg *b)
1428 { return a->pnum < b->pnum; });
74ca34ce
DJ
1429
1430 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1431 {
1432 remote_regs[regnum]->in_g_packet = 1;
1433 remote_regs[regnum]->offset = offset;
4a22f64d 1434 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
1435 }
1436
c21236dc
PA
1437 return offset;
1438}
1439
1440/* Given the architecture described by GDBARCH, return the remote
1441 protocol register's number and the register's offset in the g/G
1442 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1443 If the target does not have a mapping for REGNUM, return false,
1444 otherwise, return true. */
1445
1446int
1447remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1448 int *pnum, int *poffset)
1449{
c21236dc
PA
1450 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1451
b80406ac 1452 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
c21236dc 1453
b80406ac 1454 map_regcache_remote_table (gdbarch, regs.data ());
c21236dc
PA
1455
1456 *pnum = regs[regnum].pnum;
1457 *poffset = regs[regnum].offset;
1458
c21236dc
PA
1459 return *pnum != -1;
1460}
1461
9d6eea31 1462remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
c21236dc 1463{
c21236dc
PA
1464 /* Use the architecture to build a regnum<->pnum table, which will be
1465 1:1 unless a feature set specifies otherwise. */
9d6eea31 1466 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
c21236dc 1467
74ca34ce
DJ
1468 /* Record the maximum possible size of the g packet - it may turn out
1469 to be smaller. */
9d6eea31
PA
1470 this->sizeof_g_packet
1471 = map_regcache_remote_table (gdbarch, this->regs.get ());
74ca34ce 1472
0df8b418 1473 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
1474 remote stubs have a hardwired buffer size of 400 bytes
1475 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1476 as the maximum packet-size to ensure that the packet and an extra
1477 NUL character can always fit in the buffer. This stops GDB
1478 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d 1479 already a full buffer (As of 1999-12-04 that was most stubs). */
9d6eea31 1480 this->remote_packet_size = 400 - 1;
d01949b6 1481
ea9c271d 1482 /* This one is filled in when a ``g'' packet is received. */
9d6eea31 1483 this->actual_register_packet_size = 0;
ea9c271d
DJ
1484
1485 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
1486 default, adjust the size accordingly. Remember that each byte is
1487 encoded as two characters. 32 is the overhead for the packet
1488 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 1489 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 1490 little. */
9d6eea31
PA
1491 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1492 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
ea9c271d
DJ
1493}
1494
6b8edb51
PA
1495/* Get a pointer to the current remote target. If not connected to a
1496 remote target, return NULL. */
1497
1498static remote_target *
1499get_current_remote_target ()
1500{
5b6d1e4f 1501 target_ops *proc_target = current_inferior ()->process_target ();
6b8edb51
PA
1502 return dynamic_cast<remote_target *> (proc_target);
1503}
1504
ea9c271d
DJ
1505/* Return the current allowed size of a remote packet. This is
1506 inferred from the current architecture, and should be used to
1507 limit the length of outgoing packets. */
6b8edb51
PA
1508long
1509remote_target::get_remote_packet_size ()
ea9c271d 1510{
be2a5f71 1511 struct remote_state *rs = get_remote_state ();
9d6eea31 1512 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
ea9c271d 1513
be2a5f71
DJ
1514 if (rs->explicit_packet_size)
1515 return rs->explicit_packet_size;
1516
ea9c271d 1517 return rsa->remote_packet_size;
d01949b6
AC
1518}
1519
ad10f812 1520static struct packet_reg *
5cd63fda
PA
1521packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1522 long regnum)
ad10f812 1523{
5cd63fda 1524 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
b323314b
AC
1525 return NULL;
1526 else
ad10f812 1527 {
ea9c271d 1528 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 1529
b323314b
AC
1530 gdb_assert (r->regnum == regnum);
1531 return r;
ad10f812 1532 }
ad10f812
AC
1533}
1534
1535static struct packet_reg *
5cd63fda
PA
1536packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1537 LONGEST pnum)
ad10f812 1538{
b323314b 1539 int i;
a744cf53 1540
5cd63fda 1541 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
ad10f812 1542 {
ea9c271d 1543 struct packet_reg *r = &rsa->regs[i];
a744cf53 1544
b323314b
AC
1545 if (r->pnum == pnum)
1546 return r;
ad10f812
AC
1547 }
1548 return NULL;
d01949b6
AC
1549}
1550
9a7071a8
JB
1551/* Allow the user to specify what sequence to send to the remote
1552 when he requests a program interruption: Although ^C is usually
1553 what remote systems expect (this is the default, here), it is
1554 sometimes preferable to send a break. On other systems such
1555 as the Linux kernel, a break followed by g, which is Magic SysRq g
1556 is required in order to interrupt the execution. */
1557const char interrupt_sequence_control_c[] = "Ctrl-C";
1558const char interrupt_sequence_break[] = "BREAK";
1559const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 1560static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
1561 {
1562 interrupt_sequence_control_c,
1563 interrupt_sequence_break,
1564 interrupt_sequence_break_g,
1565 NULL
1566 };
1567static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1568
1569static void
1570show_interrupt_sequence (struct ui_file *file, int from_tty,
1571 struct cmd_list_element *c,
1572 const char *value)
1573{
1574 if (interrupt_sequence_mode == interrupt_sequence_control_c)
6cb06a8c
TT
1575 gdb_printf (file,
1576 _("Send the ASCII ETX character (Ctrl-c) "
1577 "to the remote target to interrupt the "
1578 "execution of the program.\n"));
9a7071a8 1579 else if (interrupt_sequence_mode == interrupt_sequence_break)
6cb06a8c
TT
1580 gdb_printf (file,
1581 _("send a break signal to the remote target "
1582 "to interrupt the execution of the program.\n"));
9a7071a8 1583 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
6cb06a8c
TT
1584 gdb_printf (file,
1585 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1586 "the remote target to interrupt the execution "
1587 "of Linux kernel.\n"));
9a7071a8
JB
1588 else
1589 internal_error (__FILE__, __LINE__,
1590 _("Invalid value for interrupt_sequence_mode: %s."),
1591 interrupt_sequence_mode);
1592}
6426a772 1593
9a7071a8
JB
1594/* This boolean variable specifies whether interrupt_sequence is sent
1595 to the remote target when gdb connects to it.
1596 This is mostly needed when you debug the Linux kernel: The Linux kernel
1597 expects BREAK g which is Magic SysRq g for connecting gdb. */
491144b5 1598static bool interrupt_on_connect = false;
c906108c 1599
9a7071a8
JB
1600/* This variable is used to implement the "set/show remotebreak" commands.
1601 Since these commands are now deprecated in favor of "set/show remote
1602 interrupt-sequence", it no longer has any effect on the code. */
491144b5 1603static bool remote_break;
c906108c 1604
9a7071a8 1605static void
eb4c3f4a 1606set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
9a7071a8
JB
1607{
1608 if (remote_break)
1609 interrupt_sequence_mode = interrupt_sequence_break;
1610 else
1611 interrupt_sequence_mode = interrupt_sequence_control_c;
1612}
1613
1614static void
1615show_remotebreak (struct ui_file *file, int from_tty,
1616 struct cmd_list_element *c,
1617 const char *value)
1618{
1619}
1620
c906108c
SS
1621/* This variable sets the number of bits in an address that are to be
1622 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 1623 leading zeros, the entire address would be sent. This variable
c906108c
SS
1624 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1625 initial implementation of remote.c restricted the address sent in
1626 memory packets to ``host::sizeof long'' bytes - (typically 32
1627 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1628 address was never sent. Since fixing this bug may cause a break in
85102364 1629 some remote targets this variable is principally provided to
23860348 1630 facilitate backward compatibility. */
c906108c 1631
883b9c6c 1632static unsigned int remote_address_size;
c906108c 1633
11cf8741 1634\f
11cf8741 1635/* User configurable variables for the number of characters in a
ea9c271d
DJ
1636 memory read/write packet. MIN (rsa->remote_packet_size,
1637 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 1638 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
1639 (speed up transfers). The variables ``preferred_*'' (the user
1640 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 1641 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
1642
1643struct memory_packet_config
1644{
a121b7c1 1645 const char *name;
11cf8741
JM
1646 long size;
1647 int fixed_p;
1648};
1649
cc0be08f
PA
1650/* The default max memory-write-packet-size, when the setting is
1651 "fixed". The 16k is historical. (It came from older GDB's using
1652 alloca for buffers and the knowledge (folklore?) that some hosts
1653 don't cope very well with large alloca calls.) */
1654#define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
a5c0808e
PA
1655
1656/* The minimum remote packet size for memory transfers. Ensures we
1657 can write at least one byte. */
1658#define MIN_MEMORY_PACKET_SIZE 20
1659
cc0be08f
PA
1660/* Get the memory packet size, assuming it is fixed. */
1661
1662static long
1663get_fixed_memory_packet_size (struct memory_packet_config *config)
1664{
1665 gdb_assert (config->fixed_p);
1666
1667 if (config->size <= 0)
1668 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1669 else
1670 return config->size;
1671}
1672
11cf8741
JM
1673/* Compute the current size of a read/write packet. Since this makes
1674 use of ``actual_register_packet_size'' the computation is dynamic. */
1675
6b8edb51
PA
1676long
1677remote_target::get_memory_packet_size (struct memory_packet_config *config)
11cf8741 1678{
d01949b6 1679 struct remote_state *rs = get_remote_state ();
9d6eea31 1680 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
ea9c271d 1681
11cf8741
JM
1682 long what_they_get;
1683 if (config->fixed_p)
cc0be08f 1684 what_they_get = get_fixed_memory_packet_size (config);
11cf8741
JM
1685 else
1686 {
ea9c271d 1687 what_they_get = get_remote_packet_size ();
23860348 1688 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1689 if (config->size > 0
1690 && what_they_get > config->size)
1691 what_they_get = config->size;
be2a5f71
DJ
1692
1693 /* Limit it to the size of the targets ``g'' response unless we have
1694 permission from the stub to use a larger packet size. */
1695 if (rs->explicit_packet_size == 0
1696 && rsa->actual_register_packet_size > 0
1697 && what_they_get > rsa->actual_register_packet_size)
1698 what_they_get = rsa->actual_register_packet_size;
11cf8741 1699 }
a5c0808e
PA
1700 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1701 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1702
1703 /* Make sure there is room in the global buffer for this packet
1704 (including its trailing NUL byte). */
8d64371b
TT
1705 if (rs->buf.size () < what_they_get + 1)
1706 rs->buf.resize (2 * what_they_get);
6d820c5c 1707
11cf8741
JM
1708 return what_they_get;
1709}
1710
0df8b418 1711/* Update the size of a read/write packet. If they user wants
23860348 1712 something really big then do a sanity check. */
11cf8741
JM
1713
1714static void
ac88e2de 1715set_memory_packet_size (const char *args, struct memory_packet_config *config)
11cf8741
JM
1716{
1717 int fixed_p = config->fixed_p;
1718 long size = config->size;
a744cf53 1719
11cf8741 1720 if (args == NULL)
8a3fe4f8 1721 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1722 else if (strcmp (args, "hard") == 0
1723 || strcmp (args, "fixed") == 0)
1724 fixed_p = 1;
1725 else if (strcmp (args, "soft") == 0
1726 || strcmp (args, "limit") == 0)
1727 fixed_p = 0;
1728 else
1729 {
1730 char *end;
a744cf53 1731
11cf8741
JM
1732 size = strtoul (args, &end, 0);
1733 if (args == end)
8a3fe4f8 1734 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1735
1736 /* Instead of explicitly capping the size of a packet to or
1737 disallowing it, the user is allowed to set the size to
1738 something arbitrarily large. */
11cf8741 1739 }
a5c0808e 1740
23860348 1741 /* Extra checks? */
11cf8741
JM
1742 if (fixed_p && !config->fixed_p)
1743 {
cc0be08f
PA
1744 /* So that the query shows the correct value. */
1745 long query_size = (size <= 0
1746 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1747 : size);
1748
e2e0b3e5
AC
1749 if (! query (_("The target may not be able to correctly handle a %s\n"
1750 "of %ld bytes. Change the packet size? "),
cc0be08f 1751 config->name, query_size))
8a3fe4f8 1752 error (_("Packet size not changed."));
11cf8741 1753 }
23860348 1754 /* Update the config. */
11cf8741
JM
1755 config->fixed_p = fixed_p;
1756 config->size = size;
1757}
1758
1759static void
1760show_memory_packet_size (struct memory_packet_config *config)
1761{
cc0be08f 1762 if (config->size == 0)
6cb06a8c 1763 gdb_printf (_("The %s is 0 (default). "), config->name);
cc0be08f 1764 else
6cb06a8c 1765 gdb_printf (_("The %s is %ld. "), config->name, config->size);
11cf8741 1766 if (config->fixed_p)
6cb06a8c
TT
1767 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
1768 get_fixed_memory_packet_size (config));
11cf8741 1769 else
cc0be08f 1770 {
6b8edb51 1771 remote_target *remote = get_current_remote_target ();
cc0be08f 1772
6b8edb51 1773 if (remote != NULL)
6cb06a8c
TT
1774 gdb_printf (_("Packets are limited to %ld bytes.\n"),
1775 remote->get_memory_packet_size (config));
cc0be08f 1776 else
0426ad51
TT
1777 gdb_puts ("The actual limit will be further reduced "
1778 "dependent on the target.\n");
cc0be08f 1779 }
11cf8741
JM
1780}
1781
5b6d1e4f 1782/* FIXME: needs to be per-remote-target. */
11cf8741
JM
1783static struct memory_packet_config memory_write_packet_config =
1784{
1785 "memory-write-packet-size",
1786};
1787
1788static void
ac88e2de 1789set_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1790{
1791 set_memory_packet_size (args, &memory_write_packet_config);
1792}
1793
1794static void
ac88e2de 1795show_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1796{
1797 show_memory_packet_size (&memory_write_packet_config);
1798}
1799
055303e2
AB
1800/* Show the number of hardware watchpoints that can be used. */
1801
1802static void
1803show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
1804 struct cmd_list_element *c,
1805 const char *value)
1806{
6cb06a8c
TT
1807 gdb_printf (file, _("The maximum number of target hardware "
1808 "watchpoints is %s.\n"), value);
055303e2
AB
1809}
1810
1811/* Show the length limit (in bytes) for hardware watchpoints. */
1812
1813static void
1814show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
1815 struct cmd_list_element *c,
1816 const char *value)
1817{
6cb06a8c
TT
1818 gdb_printf (file, _("The maximum length (in bytes) of a target "
1819 "hardware watchpoint is %s.\n"), value);
055303e2
AB
1820}
1821
1822/* Show the number of hardware breakpoints that can be used. */
1823
1824static void
1825show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
1826 struct cmd_list_element *c,
1827 const char *value)
1828{
6cb06a8c
TT
1829 gdb_printf (file, _("The maximum number of target hardware "
1830 "breakpoints is %s.\n"), value);
055303e2
AB
1831}
1832
6cc8564b
LM
1833/* Controls the maximum number of characters to display in the debug output
1834 for each remote packet. The remaining characters are omitted. */
1835
1836static int remote_packet_max_chars = 512;
1837
1838/* Show the maximum number of characters to display for each remote packet
1839 when remote debugging is enabled. */
1840
1841static void
1842show_remote_packet_max_chars (struct ui_file *file, int from_tty,
1843 struct cmd_list_element *c,
1844 const char *value)
1845{
6cb06a8c
TT
1846 gdb_printf (file, _("Number of remote packet characters to "
1847 "display is %s.\n"), value);
6cc8564b
LM
1848}
1849
6b8edb51
PA
1850long
1851remote_target::get_memory_write_packet_size ()
11cf8741
JM
1852{
1853 return get_memory_packet_size (&memory_write_packet_config);
1854}
1855
5b6d1e4f 1856/* FIXME: needs to be per-remote-target. */
11cf8741
JM
1857static struct memory_packet_config memory_read_packet_config =
1858{
1859 "memory-read-packet-size",
1860};
1861
1862static void
ac88e2de 1863set_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1864{
1865 set_memory_packet_size (args, &memory_read_packet_config);
1866}
1867
1868static void
ac88e2de 1869show_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1870{
1871 show_memory_packet_size (&memory_read_packet_config);
1872}
1873
6b8edb51
PA
1874long
1875remote_target::get_memory_read_packet_size ()
11cf8741
JM
1876{
1877 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1878
11cf8741
JM
1879 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1880 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1881 increased beyond this. */
1882 if (size > get_remote_packet_size ())
1883 size = get_remote_packet_size ();
11cf8741
JM
1884 return size;
1885}
1886
11cf8741 1887\f
5a2468f5 1888
5a2468f5
JM
1889struct packet_config
1890 {
bb572ddd
DJ
1891 const char *name;
1892 const char *title;
4082afcc
PA
1893
1894 /* If auto, GDB auto-detects support for this packet or feature,
1895 either through qSupported, or by trying the packet and looking
1896 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1897 packet. If false, the packet is disabled. Configs that don't
1898 have an associated command always have this set to auto. */
7f19b9a2 1899 enum auto_boolean detect;
4082afcc 1900
fcef6471
SM
1901 /* The "show remote foo-packet" command created for this packet. */
1902 cmd_list_element *show_cmd;
1903
4082afcc 1904 /* Does the target support this packet? */
5a2468f5
JM
1905 enum packet_support support;
1906 };
1907
4082afcc
PA
1908static enum packet_support packet_config_support (struct packet_config *config);
1909static enum packet_support packet_support (int packet);
5a2468f5
JM
1910
1911static void
7514a661 1912show_packet_config_cmd (ui_file *file, struct packet_config *config)
5a2468f5 1913{
a121b7c1 1914 const char *support = "internal-error";
a744cf53 1915
4082afcc 1916 switch (packet_config_support (config))
5a2468f5
JM
1917 {
1918 case PACKET_ENABLE:
1919 support = "enabled";
1920 break;
1921 case PACKET_DISABLE:
1922 support = "disabled";
1923 break;
1924 case PACKET_SUPPORT_UNKNOWN:
1925 support = "unknown";
1926 break;
1927 }
1928 switch (config->detect)
1929 {
7f19b9a2 1930 case AUTO_BOOLEAN_AUTO:
6cb06a8c
TT
1931 gdb_printf (file,
1932 _("Support for the `%s' packet "
1933 "is auto-detected, currently %s.\n"),
1934 config->name, support);
5a2468f5 1935 break;
7f19b9a2
AC
1936 case AUTO_BOOLEAN_TRUE:
1937 case AUTO_BOOLEAN_FALSE:
6cb06a8c
TT
1938 gdb_printf (file,
1939 _("Support for the `%s' packet is currently %s.\n"),
1940 config->name, support);
8e248173 1941 break;
5a2468f5
JM
1942 }
1943}
1944
1945static void
bb572ddd
DJ
1946add_packet_config_cmd (struct packet_config *config, const char *name,
1947 const char *title, int legacy)
d471ea57 1948{
5a2468f5
JM
1949 config->name = name;
1950 config->title = title;
8579fd13
AB
1951 gdb::unique_xmalloc_ptr<char> set_doc
1952 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
1953 name, title);
1954 gdb::unique_xmalloc_ptr<char> show_doc
1955 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
1956 name, title);
d471ea57 1957 /* set/show TITLE-packet {auto,on,off} */
8579fd13 1958 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
5e84b7ee 1959 set_show_commands cmds
8579fd13
AB
1960 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
1961 &config->detect, set_doc.get (),
1962 show_doc.get (), NULL, /* help_doc */
5e84b7ee
SM
1963 NULL,
1964 show_remote_protocol_packet_cmd,
1965 &remote_set_cmdlist, &remote_show_cmdlist);
fcef6471 1966 config->show_cmd = cmds.show;
5e84b7ee 1967
23860348 1968 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1969 if (legacy)
1970 {
5f21c7aa
AB
1971 /* It's not clear who should take ownership of the LEGACY_NAME string
1972 created below, so, for now, place the string into a static vector
1973 which ensures the strings is released when GDB exits. */
1974 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
1975 gdb::unique_xmalloc_ptr<char> legacy_name
8579fd13
AB
1976 = xstrprintf ("%s-packet", name);
1977 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
bb572ddd 1978 &remote_set_cmdlist);
8579fd13 1979 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
bb572ddd 1980 &remote_show_cmdlist);
5f21c7aa 1981 legacy_names.emplace_back (std::move (legacy_name));
d471ea57 1982 }
5a2468f5
JM
1983}
1984
d471ea57 1985static enum packet_result
a76d924d 1986packet_check_result (const char *buf)
5a2468f5 1987{
d471ea57 1988 if (buf[0] != '\0')
5a2468f5 1989 {
d471ea57 1990 /* The stub recognized the packet request. Check that the
23860348 1991 operation succeeded. */
a76d924d
DJ
1992 if (buf[0] == 'E'
1993 && isxdigit (buf[1]) && isxdigit (buf[2])
1994 && buf[3] == '\0')
85102364 1995 /* "Enn" - definitely an error. */
a76d924d
DJ
1996 return PACKET_ERROR;
1997
1998 /* Always treat "E." as an error. This will be used for
1999 more verbose error messages, such as E.memtypes. */
2000 if (buf[0] == 'E' && buf[1] == '.')
2001 return PACKET_ERROR;
2002
2003 /* The packet may or may not be OK. Just assume it is. */
2004 return PACKET_OK;
2005 }
2006 else
2007 /* The stub does not support the packet. */
2008 return PACKET_UNKNOWN;
2009}
2010
8d64371b
TT
2011static enum packet_result
2012packet_check_result (const gdb::char_vector &buf)
2013{
2014 return packet_check_result (buf.data ());
2015}
2016
a76d924d
DJ
2017static enum packet_result
2018packet_ok (const char *buf, struct packet_config *config)
2019{
2020 enum packet_result result;
2021
4082afcc
PA
2022 if (config->detect != AUTO_BOOLEAN_TRUE
2023 && config->support == PACKET_DISABLE)
2024 internal_error (__FILE__, __LINE__,
2025 _("packet_ok: attempt to use a disabled packet"));
2026
a76d924d
DJ
2027 result = packet_check_result (buf);
2028 switch (result)
2029 {
2030 case PACKET_OK:
2031 case PACKET_ERROR:
2032 /* The stub recognized the packet request. */
4082afcc 2033 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 2034 {
2189c312
SM
2035 remote_debug_printf ("Packet %s (%s) is supported",
2036 config->name, config->title);
d471ea57 2037 config->support = PACKET_ENABLE;
d471ea57 2038 }
a76d924d
DJ
2039 break;
2040 case PACKET_UNKNOWN:
23860348 2041 /* The stub does not support the packet. */
4082afcc
PA
2042 if (config->detect == AUTO_BOOLEAN_AUTO
2043 && config->support == PACKET_ENABLE)
d471ea57 2044 {
4082afcc
PA
2045 /* If the stub previously indicated that the packet was
2046 supported then there is a protocol error. */
2047 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2048 config->name, config->title);
2049 }
2050 else if (config->detect == AUTO_BOOLEAN_TRUE)
2051 {
2052 /* The user set it wrong. */
2053 error (_("Enabled packet %s (%s) not recognized by stub"),
2054 config->name, config->title);
d471ea57 2055 }
4082afcc 2056
2189c312
SM
2057 remote_debug_printf ("Packet %s (%s) is NOT supported",
2058 config->name, config->title);
4082afcc 2059 config->support = PACKET_DISABLE;
a76d924d 2060 break;
5a2468f5 2061 }
a76d924d
DJ
2062
2063 return result;
5a2468f5
JM
2064}
2065
8d64371b
TT
2066static enum packet_result
2067packet_ok (const gdb::char_vector &buf, struct packet_config *config)
2068{
2069 return packet_ok (buf.data (), config);
2070}
2071
444abaca
DJ
2072enum {
2073 PACKET_vCont = 0,
2074 PACKET_X,
2075 PACKET_qSymbol,
2076 PACKET_P,
2077 PACKET_p,
2078 PACKET_Z0,
2079 PACKET_Z1,
2080 PACKET_Z2,
2081 PACKET_Z3,
2082 PACKET_Z4,
15a201c8 2083 PACKET_vFile_setfs,
a6b151f1
DJ
2084 PACKET_vFile_open,
2085 PACKET_vFile_pread,
2086 PACKET_vFile_pwrite,
2087 PACKET_vFile_close,
2088 PACKET_vFile_unlink,
b9e7b9c3 2089 PACKET_vFile_readlink,
0a93529c 2090 PACKET_vFile_fstat,
0876f84a 2091 PACKET_qXfer_auxv,
23181151 2092 PACKET_qXfer_features,
c78fa86a 2093 PACKET_qXfer_exec_file,
cfa9d6d9 2094 PACKET_qXfer_libraries,
2268b414 2095 PACKET_qXfer_libraries_svr4,
fd79ecee 2096 PACKET_qXfer_memory_map,
07e059b5 2097 PACKET_qXfer_osdata,
dc146f7c 2098 PACKET_qXfer_threads,
0fb4aa4b 2099 PACKET_qXfer_statictrace_read,
b3b9301e 2100 PACKET_qXfer_traceframe_info,
169081d0 2101 PACKET_qXfer_uib,
711e434b 2102 PACKET_qGetTIBAddr,
444abaca 2103 PACKET_qGetTLSAddr,
be2a5f71 2104 PACKET_qSupported,
bd3eecc3 2105 PACKET_qTStatus,
89be2091 2106 PACKET_QPassSignals,
82075af2 2107 PACKET_QCatchSyscalls,
9b224c5e 2108 PACKET_QProgramSignals,
bc3b087d 2109 PACKET_QSetWorkingDir,
aefd8b33 2110 PACKET_QStartupWithShell,
0a2dde4a
SDJ
2111 PACKET_QEnvironmentHexEncoded,
2112 PACKET_QEnvironmentReset,
2113 PACKET_QEnvironmentUnset,
936d2992 2114 PACKET_qCRC,
08388c79 2115 PACKET_qSearch_memory,
2d717e4f
DJ
2116 PACKET_vAttach,
2117 PACKET_vRun,
a6f3e723 2118 PACKET_QStartNoAckMode,
82f73884 2119 PACKET_vKill,
4aa995e1
PA
2120 PACKET_qXfer_siginfo_read,
2121 PACKET_qXfer_siginfo_write,
0b16c5cf 2122 PACKET_qAttached,
4082afcc
PA
2123
2124 /* Support for conditional tracepoints. */
782b2b07 2125 PACKET_ConditionalTracepoints,
4082afcc
PA
2126
2127 /* Support for target-side breakpoint conditions. */
3788aec7 2128 PACKET_ConditionalBreakpoints,
4082afcc
PA
2129
2130 /* Support for target-side breakpoint commands. */
d3ce09f5 2131 PACKET_BreakpointCommands,
4082afcc
PA
2132
2133 /* Support for fast tracepoints. */
7a697b8d 2134 PACKET_FastTracepoints,
4082afcc
PA
2135
2136 /* Support for static tracepoints. */
0fb4aa4b 2137 PACKET_StaticTracepoints,
4082afcc
PA
2138
2139 /* Support for installing tracepoints while a trace experiment is
2140 running. */
1e4d1764 2141 PACKET_InstallInTrace,
4082afcc 2142
40ab02ce
MS
2143 PACKET_bc,
2144 PACKET_bs,
409873ef 2145 PACKET_TracepointSource,
d914c394 2146 PACKET_QAllow,
78d85199 2147 PACKET_qXfer_fdpic,
03583c20 2148 PACKET_QDisableRandomization,
d1feda86 2149 PACKET_QAgent,
f6f899bf 2150 PACKET_QTBuffer_size,
9accd112
MM
2151 PACKET_Qbtrace_off,
2152 PACKET_Qbtrace_bts,
b20a6524 2153 PACKET_Qbtrace_pt,
9accd112 2154 PACKET_qXfer_btrace,
4082afcc
PA
2155
2156 /* Support for the QNonStop packet. */
2157 PACKET_QNonStop,
2158
65706a29
PA
2159 /* Support for the QThreadEvents packet. */
2160 PACKET_QThreadEvents,
2161
4082afcc
PA
2162 /* Support for multi-process extensions. */
2163 PACKET_multiprocess_feature,
2164
2165 /* Support for enabling and disabling tracepoints while a trace
2166 experiment is running. */
2167 PACKET_EnableDisableTracepoints_feature,
2168
2169 /* Support for collecting strings using the tracenz bytecode. */
2170 PACKET_tracenz_feature,
2171
2172 /* Support for continuing to run a trace experiment while GDB is
2173 disconnected. */
2174 PACKET_DisconnectedTracing_feature,
2175
2176 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2177 PACKET_augmented_libraries_svr4_read_feature,
2178
f4abbc16
MM
2179 /* Support for the qXfer:btrace-conf:read packet. */
2180 PACKET_qXfer_btrace_conf,
2181
d33501a5
MM
2182 /* Support for the Qbtrace-conf:bts:size packet. */
2183 PACKET_Qbtrace_conf_bts_size,
2184
f7e6eed5
PA
2185 /* Support for swbreak+ feature. */
2186 PACKET_swbreak_feature,
2187
2188 /* Support for hwbreak+ feature. */
2189 PACKET_hwbreak_feature,
2190
89245bc0
DB
2191 /* Support for fork events. */
2192 PACKET_fork_event_feature,
2193
2194 /* Support for vfork events. */
2195 PACKET_vfork_event_feature,
2196
b20a6524
MM
2197 /* Support for the Qbtrace-conf:pt:size packet. */
2198 PACKET_Qbtrace_conf_pt_size,
2199
94585166
DB
2200 /* Support for exec events. */
2201 PACKET_exec_event_feature,
2202
750ce8d1
YQ
2203 /* Support for query supported vCont actions. */
2204 PACKET_vContSupported,
2205
de979965
PA
2206 /* Support remote CTRL-C. */
2207 PACKET_vCtrlC,
2208
f2faf941
PA
2209 /* Support TARGET_WAITKIND_NO_RESUMED. */
2210 PACKET_no_resumed,
2211
2c2e7f87
LM
2212 /* Support for memory tagging, allocation tag fetch/store
2213 packets and the tag violation stop replies. */
2214 PACKET_memory_tagging_feature,
2215
444abaca
DJ
2216 PACKET_MAX
2217};
506fb367 2218
5b6d1e4f
PA
2219/* FIXME: needs to be per-remote-target. Ignoring this for now,
2220 assuming all remote targets are the same server (thus all support
2221 the same packets). */
444abaca 2222static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 2223
f7e6eed5
PA
2224/* Returns the packet's corresponding "set remote foo-packet" command
2225 state. See struct packet_config for more details. */
2226
2227static enum auto_boolean
2228packet_set_cmd_state (int packet)
2229{
2230 return remote_protocol_packets[packet].detect;
2231}
2232
4082afcc
PA
2233/* Returns whether a given packet or feature is supported. This takes
2234 into account the state of the corresponding "set remote foo-packet"
2235 command, which may be used to bypass auto-detection. */
dc8acb97 2236
4082afcc
PA
2237static enum packet_support
2238packet_config_support (struct packet_config *config)
2239{
2240 switch (config->detect)
444abaca 2241 {
4082afcc
PA
2242 case AUTO_BOOLEAN_TRUE:
2243 return PACKET_ENABLE;
2244 case AUTO_BOOLEAN_FALSE:
2245 return PACKET_DISABLE;
2246 case AUTO_BOOLEAN_AUTO:
2247 return config->support;
2248 default:
557b4d76 2249 gdb_assert_not_reached ("bad switch");
444abaca 2250 }
4082afcc
PA
2251}
2252
2253/* Same as packet_config_support, but takes the packet's enum value as
2254 argument. */
2255
2256static enum packet_support
2257packet_support (int packet)
2258{
2259 struct packet_config *config = &remote_protocol_packets[packet];
2260
2261 return packet_config_support (config);
dc8acb97
MS
2262}
2263
5a2468f5 2264static void
444abaca
DJ
2265show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2266 struct cmd_list_element *c,
2267 const char *value)
5a2468f5 2268{
444abaca 2269 struct packet_config *packet;
1d7fe7f0 2270 gdb_assert (c->var.has_value ());
5a2468f5 2271
444abaca
DJ
2272 for (packet = remote_protocol_packets;
2273 packet < &remote_protocol_packets[PACKET_MAX];
2274 packet++)
2275 {
fcef6471 2276 if (c == packet->show_cmd)
444abaca 2277 {
7514a661 2278 show_packet_config_cmd (file, packet);
444abaca
DJ
2279 return;
2280 }
2281 }
9b20d036 2282 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 2283 c->name);
5a2468f5
JM
2284}
2285
d471ea57
AC
2286/* Should we try one of the 'Z' requests? */
2287
2288enum Z_packet_type
2289{
2290 Z_PACKET_SOFTWARE_BP,
2291 Z_PACKET_HARDWARE_BP,
2292 Z_PACKET_WRITE_WP,
2293 Z_PACKET_READ_WP,
2294 Z_PACKET_ACCESS_WP,
2295 NR_Z_PACKET_TYPES
2296};
96baa820 2297
d471ea57 2298/* For compatibility with older distributions. Provide a ``set remote
23860348 2299 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 2300
7f19b9a2 2301static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
2302
2303static void
eb4c3f4a 2304set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
fba45db2 2305 struct cmd_list_element *c)
96baa820 2306{
d471ea57 2307 int i;
a744cf53 2308
d471ea57 2309 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 2310 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
2311}
2312
2313static void
08546159
AC
2314show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2315 struct cmd_list_element *c,
2316 const char *value)
96baa820 2317{
d471ea57 2318 int i;
a744cf53 2319
d471ea57
AC
2320 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2321 {
7514a661 2322 show_packet_config_cmd (file, &remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 2323 }
96baa820
JM
2324}
2325
4082afcc
PA
2326/* Returns true if the multi-process extensions are in effect. */
2327
2328static int
2329remote_multi_process_p (struct remote_state *rs)
2330{
2331 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2332}
2333
de0d863e
DB
2334/* Returns true if fork events are supported. */
2335
2336static int
2337remote_fork_event_p (struct remote_state *rs)
2338{
2339 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2340}
2341
c269dbdb
DB
2342/* Returns true if vfork events are supported. */
2343
2344static int
2345remote_vfork_event_p (struct remote_state *rs)
2346{
2347 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2348}
2349
d46addbb
DB
2350/* Returns true if exec events are supported. */
2351
2352static int
2353remote_exec_event_p (struct remote_state *rs)
2354{
2355 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2356}
2357
2c2e7f87
LM
2358/* Returns true if memory tagging is supported, false otherwise. */
2359
2360static bool
2361remote_memory_tagging_p ()
2362{
2363 return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE;
2364}
2365
cbb8991c
DB
2366/* Insert fork catchpoint target routine. If fork events are enabled
2367 then return success, nothing more to do. */
2368
f6ac5f3d
PA
2369int
2370remote_target::insert_fork_catchpoint (int pid)
cbb8991c
DB
2371{
2372 struct remote_state *rs = get_remote_state ();
2373
2374 return !remote_fork_event_p (rs);
2375}
2376
2377/* Remove fork catchpoint target routine. Nothing to do, just
2378 return success. */
2379
f6ac5f3d
PA
2380int
2381remote_target::remove_fork_catchpoint (int pid)
cbb8991c
DB
2382{
2383 return 0;
2384}
2385
2386/* Insert vfork catchpoint target routine. If vfork events are enabled
2387 then return success, nothing more to do. */
2388
f6ac5f3d
PA
2389int
2390remote_target::insert_vfork_catchpoint (int pid)
cbb8991c
DB
2391{
2392 struct remote_state *rs = get_remote_state ();
2393
2394 return !remote_vfork_event_p (rs);
2395}
2396
2397/* Remove vfork catchpoint target routine. Nothing to do, just
2398 return success. */
2399
f6ac5f3d
PA
2400int
2401remote_target::remove_vfork_catchpoint (int pid)
cbb8991c
DB
2402{
2403 return 0;
2404}
2405
d46addbb
DB
2406/* Insert exec catchpoint target routine. If exec events are
2407 enabled, just return success. */
2408
f6ac5f3d
PA
2409int
2410remote_target::insert_exec_catchpoint (int pid)
d46addbb
DB
2411{
2412 struct remote_state *rs = get_remote_state ();
2413
2414 return !remote_exec_event_p (rs);
2415}
2416
2417/* Remove exec catchpoint target routine. Nothing to do, just
2418 return success. */
2419
f6ac5f3d
PA
2420int
2421remote_target::remove_exec_catchpoint (int pid)
d46addbb
DB
2422{
2423 return 0;
2424}
2425
c906108c
SS
2426\f
2427
ffdd69cf
TT
2428/* Take advantage of the fact that the TID field is not used, to tag
2429 special ptids with it set to != 0. */
2430static const ptid_t magic_null_ptid (42000, -1, 1);
2431static const ptid_t not_sent_ptid (42000, -2, 1);
2432static const ptid_t any_thread_ptid (42000, 0, 1);
79d7f229 2433
0b16c5cf
PA
2434/* Find out if the stub attached to PID (and hence GDB should offer to
2435 detach instead of killing it when bailing out). */
2436
6b8edb51
PA
2437int
2438remote_target::remote_query_attached (int pid)
0b16c5cf
PA
2439{
2440 struct remote_state *rs = get_remote_state ();
bba74b36 2441 size_t size = get_remote_packet_size ();
0b16c5cf 2442
4082afcc 2443 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
2444 return 0;
2445
2446 if (remote_multi_process_p (rs))
8d64371b 2447 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
0b16c5cf 2448 else
8d64371b 2449 xsnprintf (rs->buf.data (), size, "qAttached");
0b16c5cf
PA
2450
2451 putpkt (rs->buf);
8d64371b 2452 getpkt (&rs->buf, 0);
0b16c5cf
PA
2453
2454 switch (packet_ok (rs->buf,
1554e9be 2455 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
2456 {
2457 case PACKET_OK:
8d64371b 2458 if (strcmp (rs->buf.data (), "1") == 0)
0b16c5cf
PA
2459 return 1;
2460 break;
2461 case PACKET_ERROR:
8d64371b 2462 warning (_("Remote failure reply: %s"), rs->buf.data ());
0b16c5cf
PA
2463 break;
2464 case PACKET_UNKNOWN:
2465 break;
2466 }
2467
2468 return 0;
2469}
2470
49c62f2e
PA
2471/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2472 has been invented by GDB, instead of reported by the target. Since
2473 we can be connected to a remote system before before knowing about
2474 any inferior, mark the target with execution when we find the first
2475 inferior. If ATTACHED is 1, then we had just attached to this
2476 inferior. If it is 0, then we just created this inferior. If it
2477 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
2478 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2479 attempt to open this inferior's executable as the main executable
2480 if no main executable is open already. */
1941c569 2481
6b8edb51 2482inferior *
9ab8741a 2483remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
6b8edb51 2484 int try_open_exec)
1941c569 2485{
1941c569
PA
2486 struct inferior *inf;
2487
0b16c5cf
PA
2488 /* Check whether this process we're learning about is to be
2489 considered attached, or if is to be considered to have been
2490 spawned by the stub. */
2491 if (attached == -1)
2492 attached = remote_query_attached (pid);
2493
f5656ead 2494 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
2495 {
2496 /* If the target shares code across all inferiors, then every
2497 attach adds a new inferior. */
2498 inf = add_inferior (pid);
2499
2500 /* ... and every inferior is bound to the same program space.
2501 However, each inferior may still have its own address
2502 space. */
2503 inf->aspace = maybe_new_address_space ();
2504 inf->pspace = current_program_space;
2505 }
2506 else
2507 {
2508 /* In the traditional debugging scenario, there's a 1-1 match
2509 between program/address spaces. We simply bind the inferior
2510 to the program space's address space. */
2511 inf = current_inferior ();
78f2c40a
PA
2512
2513 /* However, if the current inferior is already bound to a
2514 process, find some other empty inferior. */
2515 if (inf->pid != 0)
2516 {
2517 inf = nullptr;
2518 for (inferior *it : all_inferiors ())
2519 if (it->pid == 0)
2520 {
2521 inf = it;
2522 break;
2523 }
2524 }
2525 if (inf == nullptr)
2526 {
2527 /* Since all inferiors were already bound to a process, add
2528 a new inferior. */
2529 inf = add_inferior_with_spaces ();
2530 }
2531 switch_to_inferior_no_thread (inf);
02980c56 2532 inf->push_target (this);
6c95b8df
PA
2533 inferior_appeared (inf, pid);
2534 }
1941c569 2535
0b16c5cf 2536 inf->attach_flag = attached;
49c62f2e 2537 inf->fake_pid_p = fake_pid_p;
0b16c5cf 2538
1b6e6f5c
GB
2539 /* If no main executable is currently open then attempt to
2540 open the file that was executed to create this inferior. */
835205d0 2541 if (try_open_exec && get_exec_file (0) == NULL)
bb805577 2542 exec_file_locate_attach (pid, 0, 1);
1b6e6f5c 2543
a2fedca9
PW
2544 /* Check for exec file mismatch, and let the user solve it. */
2545 validate_exec_file (1);
2546
1941c569
PA
2547 return inf;
2548}
2549
7aabaf9d 2550static remote_thread_info *get_remote_thread_info (thread_info *thread);
5b6d1e4f
PA
2551static remote_thread_info *get_remote_thread_info (remote_target *target,
2552 ptid_t ptid);
85ad3aaf 2553
1941c569 2554/* Add thread PTID to GDB's thread list. Tag it as executing/running
b622494e
AB
2555 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2556 remote_state::starting_up flag) is true then the new thread is added
2557 silently, otherwise the new thread will be announced to the user. */
1941c569 2558
00431a78 2559thread_info *
b622494e
AB
2560remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2561 bool silent_p)
c906108c 2562{
b7ea362b 2563 struct remote_state *rs = get_remote_state ();
85ad3aaf 2564 struct thread_info *thread;
b7ea362b
PA
2565
2566 /* GDB historically didn't pull threads in the initial connection
2567 setup. If the remote target doesn't even have a concept of
2568 threads (e.g., a bare-metal target), even if internally we
2569 consider that a single-threaded target, mentioning a new thread
2570 might be confusing to the user. Be silent then, preserving the
2571 age old behavior. */
b622494e 2572 if (rs->starting_up || silent_p)
5b6d1e4f 2573 thread = add_thread_silent (this, ptid);
b7ea362b 2574 else
5b6d1e4f 2575 thread = add_thread (this, ptid);
1941c569 2576
c9d22089
SM
2577 /* We start by assuming threads are resumed. That state then gets updated
2578 when we process a matching stop reply. */
2579 get_remote_thread_info (thread)->set_resumed ();
2580
5b6d1e4f
PA
2581 set_executing (this, ptid, executing);
2582 set_running (this, ptid, running);
00431a78
PA
2583
2584 return thread;
1941c569
PA
2585}
2586
2587/* Come here when we learn about a thread id from the remote target.
2588 It may be the first time we hear about such thread, so take the
2589 opportunity to add it to GDB's thread list. In case this is the
2590 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
2591 GDB's inferior list as well. EXECUTING indicates whether the
2592 thread is (internally) executing or stopped. */
1941c569 2593
6b8edb51 2594void
8a82de58 2595remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
1941c569 2596{
0d5b594f
PA
2597 /* In non-stop mode, we assume new found threads are (externally)
2598 running until proven otherwise with a stop reply. In all-stop,
2599 we can only get here if all threads are stopped. */
8a82de58 2600 bool running = target_is_non_stop_p ();
0d5b594f 2601
c906108c
SS
2602 /* If this is a new thread, add it to GDB's thread list.
2603 If we leave it up to WFI to do this, bad things will happen. */
82f73884 2604
5b6d1e4f 2605 thread_info *tp = find_thread_ptid (this, currthread);
00431a78 2606 if (tp != NULL && tp->state == THREAD_EXITED)
82f73884
PA
2607 {
2608 /* We're seeing an event on a thread id we knew had exited.
2609 This has to be a new thread reusing the old id. Add it. */
b622494e 2610 remote_add_thread (currthread, running, executing, false);
82f73884
PA
2611 return;
2612 }
2613
5b6d1e4f 2614 if (!in_thread_list (this, currthread))
c0a2216e 2615 {
1941c569 2616 struct inferior *inf = NULL;
e99b03dc 2617 int pid = currthread.pid ();
1941c569 2618
0e998d96 2619 if (inferior_ptid.is_pid ()
e99b03dc 2620 && pid == inferior_ptid.pid ())
c0a2216e
PA
2621 {
2622 /* inferior_ptid has no thread member yet. This can happen
2623 with the vAttach -> remote_wait,"TAAthread:" path if the
2624 stub doesn't support qC. This is the first stop reported
2625 after an attach, so this is the main thread. Update the
2626 ptid in the thread list. */
5b6d1e4f
PA
2627 if (in_thread_list (this, ptid_t (pid)))
2628 thread_change_ptid (this, inferior_ptid, currthread);
bad34192
PA
2629 else
2630 {
0ac55310 2631 thread_info *thr
b622494e 2632 = remote_add_thread (currthread, running, executing, false);
0ac55310 2633 switch_to_thread (thr);
bad34192 2634 }
dc146f7c 2635 return;
c0a2216e 2636 }
82f73884 2637
d7e15655 2638 if (magic_null_ptid == inferior_ptid)
c0a2216e
PA
2639 {
2640 /* inferior_ptid is not set yet. This can happen with the
2641 vRun -> remote_wait,"TAAthread:" path if the stub
2642 doesn't support qC. This is the first stop reported
2643 after an attach, so this is the main thread. Update the
2644 ptid in the thread list. */
5b6d1e4f 2645 thread_change_ptid (this, inferior_ptid, currthread);
82f73884 2646 return;
c0a2216e 2647 }
82f73884 2648
29c87f7f
PA
2649 /* When connecting to a target remote, or to a target
2650 extended-remote which already was debugging an inferior, we
2651 may not know about it yet. Add it before adding its child
2652 thread, so notifications are emitted in a sensible order. */
5b6d1e4f 2653 if (find_inferior_pid (this, currthread.pid ()) == NULL)
49c62f2e
PA
2654 {
2655 struct remote_state *rs = get_remote_state ();
9ab8741a 2656 bool fake_pid_p = !remote_multi_process_p (rs);
49c62f2e
PA
2657
2658 inf = remote_add_inferior (fake_pid_p,
e99b03dc 2659 currthread.pid (), -1, 1);
49c62f2e 2660 }
29c87f7f 2661
82f73884 2662 /* This is really a new thread. Add it. */
00431a78 2663 thread_info *new_thr
b622494e 2664 = remote_add_thread (currthread, running, executing, false);
1941c569
PA
2665
2666 /* If we found a new inferior, let the common code do whatever
2667 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
2668 breakpoints), unless we're just setting up an all-stop
2669 connection. */
1941c569 2670 if (inf != NULL)
b7ea362b
PA
2671 {
2672 struct remote_state *rs = get_remote_state ();
2673
6efcd9a8 2674 if (!rs->starting_up)
00431a78 2675 notice_new_inferior (new_thr, executing, 0);
b7ea362b 2676 }
c0a2216e 2677 }
c906108c
SS
2678}
2679
85ad3aaf 2680/* Return THREAD's private thread data, creating it if necessary. */
dc146f7c 2681
7aabaf9d
SM
2682static remote_thread_info *
2683get_remote_thread_info (thread_info *thread)
dc146f7c 2684{
85ad3aaf 2685 gdb_assert (thread != NULL);
dc146f7c 2686
85ad3aaf 2687 if (thread->priv == NULL)
7aabaf9d 2688 thread->priv.reset (new remote_thread_info);
dc146f7c 2689
7aabaf9d 2690 return static_cast<remote_thread_info *> (thread->priv.get ());
85ad3aaf
PA
2691}
2692
5b6d1e4f
PA
2693/* Return PTID's private thread data, creating it if necessary. */
2694
7aabaf9d 2695static remote_thread_info *
5b6d1e4f 2696get_remote_thread_info (remote_target *target, ptid_t ptid)
85ad3aaf 2697{
5b6d1e4f 2698 thread_info *thr = find_thread_ptid (target, ptid);
00431a78 2699 return get_remote_thread_info (thr);
dc146f7c
VP
2700}
2701
74531fed
PA
2702/* Call this function as a result of
2703 1) A halt indication (T packet) containing a thread id
2704 2) A direct query of currthread
0df8b418 2705 3) Successful execution of set thread */
74531fed
PA
2706
2707static void
47f8a51d 2708record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 2709{
47f8a51d 2710 rs->general_thread = currthread;
74531fed
PA
2711}
2712
89be2091
DJ
2713/* If 'QPassSignals' is supported, tell the remote stub what signals
2714 it can simply pass through to the inferior without reporting. */
2715
f6ac5f3d 2716void
adc6a863 2717remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
89be2091 2718{
4082afcc 2719 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
2720 {
2721 char *pass_packet, *p;
adc6a863 2722 int count = 0;
747dc59d 2723 struct remote_state *rs = get_remote_state ();
89be2091 2724
adc6a863
PA
2725 gdb_assert (pass_signals.size () < 256);
2726 for (size_t i = 0; i < pass_signals.size (); i++)
89be2091 2727 {
2455069d 2728 if (pass_signals[i])
89be2091
DJ
2729 count++;
2730 }
224c3ddb 2731 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
2732 strcpy (pass_packet, "QPassSignals:");
2733 p = pass_packet + strlen (pass_packet);
adc6a863 2734 for (size_t i = 0; i < pass_signals.size (); i++)
89be2091 2735 {
2455069d 2736 if (pass_signals[i])
89be2091
DJ
2737 {
2738 if (i >= 16)
2739 *p++ = tohex (i >> 4);
2740 *p++ = tohex (i & 15);
2741 if (count)
2742 *p++ = ';';
2743 else
2744 break;
2745 count--;
2746 }
2747 }
2748 *p = 0;
747dc59d 2749 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 2750 {
89be2091 2751 putpkt (pass_packet);
8d64371b 2752 getpkt (&rs->buf, 0);
8dc5b319 2753 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
84d53fa9 2754 xfree (rs->last_pass_packet);
747dc59d 2755 rs->last_pass_packet = pass_packet;
89be2091
DJ
2756 }
2757 else
2758 xfree (pass_packet);
2759 }
2760}
2761
82075af2
JS
2762/* If 'QCatchSyscalls' is supported, tell the remote stub
2763 to report syscalls to GDB. */
2764
f6ac5f3d
PA
2765int
2766remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2767 gdb::array_view<const int> syscall_counts)
82075af2 2768{
b80406ac 2769 const char *catch_packet;
82075af2
JS
2770 enum packet_result result;
2771 int n_sysno = 0;
2772
2773 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2774 {
2775 /* Not supported. */
2776 return 1;
2777 }
2778
649a140c 2779 if (needed && any_count == 0)
82075af2 2780 {
649a140c
PA
2781 /* Count how many syscalls are to be caught. */
2782 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2783 {
649a140c 2784 if (syscall_counts[i] != 0)
82075af2
JS
2785 n_sysno++;
2786 }
2787 }
2788
2189c312
SM
2789 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
2790 pid, needed, any_count, n_sysno);
82075af2 2791
1b81856f 2792 std::string built_packet;
82075af2
JS
2793 if (needed)
2794 {
2795 /* Prepare a packet with the sysno list, assuming max 8+1
2796 characters for a sysno. If the resulting packet size is too
2797 big, fallback on the non-selective packet. */
2798 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
1b81856f
PA
2799 built_packet.reserve (maxpktsz);
2800 built_packet = "QCatchSyscalls:1";
649a140c 2801 if (any_count == 0)
82075af2 2802 {
649a140c
PA
2803 /* Add in each syscall to be caught. */
2804 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2805 {
649a140c
PA
2806 if (syscall_counts[i] != 0)
2807 string_appendf (built_packet, ";%zx", i);
82075af2
JS
2808 }
2809 }
1b81856f 2810 if (built_packet.size () > get_remote_packet_size ())
82075af2
JS
2811 {
2812 /* catch_packet too big. Fallback to less efficient
2813 non selective mode, with GDB doing the filtering. */
b80406ac 2814 catch_packet = "QCatchSyscalls:1";
82075af2 2815 }
b80406ac 2816 else
1b81856f 2817 catch_packet = built_packet.c_str ();
82075af2
JS
2818 }
2819 else
b80406ac 2820 catch_packet = "QCatchSyscalls:0";
82075af2 2821
b80406ac 2822 struct remote_state *rs = get_remote_state ();
82075af2 2823
b80406ac 2824 putpkt (catch_packet);
8d64371b 2825 getpkt (&rs->buf, 0);
b80406ac
TT
2826 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2827 if (result == PACKET_OK)
2828 return 0;
2829 else
2830 return -1;
82075af2
JS
2831}
2832
9b224c5e
PA
2833/* If 'QProgramSignals' is supported, tell the remote stub what
2834 signals it should pass through to the inferior when detaching. */
2835
f6ac5f3d 2836void
adc6a863 2837remote_target::program_signals (gdb::array_view<const unsigned char> signals)
9b224c5e 2838{
4082afcc 2839 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
2840 {
2841 char *packet, *p;
adc6a863 2842 int count = 0;
5e4a05c4 2843 struct remote_state *rs = get_remote_state ();
9b224c5e 2844
adc6a863
PA
2845 gdb_assert (signals.size () < 256);
2846 for (size_t i = 0; i < signals.size (); i++)
9b224c5e
PA
2847 {
2848 if (signals[i])
2849 count++;
2850 }
224c3ddb 2851 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2852 strcpy (packet, "QProgramSignals:");
2853 p = packet + strlen (packet);
adc6a863 2854 for (size_t i = 0; i < signals.size (); i++)
9b224c5e
PA
2855 {
2856 if (signal_pass_state (i))
2857 {
2858 if (i >= 16)
2859 *p++ = tohex (i >> 4);
2860 *p++ = tohex (i & 15);
2861 if (count)
2862 *p++ = ';';
2863 else
2864 break;
2865 count--;
2866 }
2867 }
2868 *p = 0;
5e4a05c4
TT
2869 if (!rs->last_program_signals_packet
2870 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2871 {
9b224c5e 2872 putpkt (packet);
8d64371b 2873 getpkt (&rs->buf, 0);
8dc5b319 2874 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2875 xfree (rs->last_program_signals_packet);
2876 rs->last_program_signals_packet = packet;
9b224c5e
PA
2877 }
2878 else
2879 xfree (packet);
2880 }
2881}
2882
79d7f229
PA
2883/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2884 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2885 thread. If GEN is set, set the general thread, if not, then set
2886 the step/continue thread. */
6b8edb51
PA
2887void
2888remote_target::set_thread (ptid_t ptid, int gen)
c906108c 2889{
d01949b6 2890 struct remote_state *rs = get_remote_state ();
47f8a51d 2891 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
8d64371b
TT
2892 char *buf = rs->buf.data ();
2893 char *endbuf = buf + get_remote_packet_size ();
c906108c 2894
d7e15655 2895 if (state == ptid)
c906108c
SS
2896 return;
2897
79d7f229
PA
2898 *buf++ = 'H';
2899 *buf++ = gen ? 'g' : 'c';
d7e15655 2900 if (ptid == magic_null_ptid)
79d7f229 2901 xsnprintf (buf, endbuf - buf, "0");
d7e15655 2902 else if (ptid == any_thread_ptid)
79d7f229 2903 xsnprintf (buf, endbuf - buf, "0");
d7e15655 2904 else if (ptid == minus_one_ptid)
79d7f229
PA
2905 xsnprintf (buf, endbuf - buf, "-1");
2906 else
82f73884 2907 write_ptid (buf, endbuf, ptid);
79d7f229 2908 putpkt (rs->buf);
8d64371b 2909 getpkt (&rs->buf, 0);
c906108c 2910 if (gen)
47f8a51d 2911 rs->general_thread = ptid;
c906108c 2912 else
47f8a51d 2913 rs->continue_thread = ptid;
c906108c 2914}
79d7f229 2915
6b8edb51
PA
2916void
2917remote_target::set_general_thread (ptid_t ptid)
79d7f229
PA
2918{
2919 set_thread (ptid, 1);
2920}
2921
6b8edb51
PA
2922void
2923remote_target::set_continue_thread (ptid_t ptid)
79d7f229
PA
2924{
2925 set_thread (ptid, 0);
2926}
2927
3c9c4b83
PA
2928/* Change the remote current process. Which thread within the process
2929 ends up selected isn't important, as long as it is the same process
2930 as what INFERIOR_PTID points to.
2931
2932 This comes from that fact that there is no explicit notion of
2933 "selected process" in the protocol. The selected process for
2934 general operations is the process the selected general thread
2935 belongs to. */
2936
6b8edb51
PA
2937void
2938remote_target::set_general_process ()
3c9c4b83
PA
2939{
2940 struct remote_state *rs = get_remote_state ();
2941
2942 /* If the remote can't handle multiple processes, don't bother. */
8020350c 2943 if (!remote_multi_process_p (rs))
3c9c4b83
PA
2944 return;
2945
2946 /* We only need to change the remote current thread if it's pointing
2947 at some other process. */
e99b03dc 2948 if (rs->general_thread.pid () != inferior_ptid.pid ())
3c9c4b83
PA
2949 set_general_thread (inferior_ptid);
2950}
2951
c906108c 2952\f
7d1a114c
PA
2953/* Return nonzero if this is the main thread that we made up ourselves
2954 to model non-threaded targets as single-threaded. */
c906108c
SS
2955
2956static int
f6ac5f3d 2957remote_thread_always_alive (ptid_t ptid)
c906108c 2958{
d7e15655 2959 if (ptid == magic_null_ptid)
c0a2216e
PA
2960 /* The main thread is always alive. */
2961 return 1;
2962
e38504b3 2963 if (ptid.pid () != 0 && ptid.lwp () == 0)
c0a2216e
PA
2964 /* The main thread is always alive. This can happen after a
2965 vAttach, if the remote side doesn't support
2966 multi-threading. */
2967 return 1;
2968
7d1a114c
PA
2969 return 0;
2970}
2971
2972/* Return nonzero if the thread PTID is still alive on the remote
2973 system. */
2974
57810aa7 2975bool
f6ac5f3d 2976remote_target::thread_alive (ptid_t ptid)
7d1a114c
PA
2977{
2978 struct remote_state *rs = get_remote_state ();
2979 char *p, *endp;
2980
2981 /* Check if this is a thread that we made up ourselves to model
2982 non-threaded targets as single-threaded. */
f6ac5f3d 2983 if (remote_thread_always_alive (ptid))
7d1a114c
PA
2984 return 1;
2985
8d64371b
TT
2986 p = rs->buf.data ();
2987 endp = p + get_remote_packet_size ();
82f73884
PA
2988
2989 *p++ = 'T';
2990 write_ptid (p, endp, ptid);
2991
2e9f7625 2992 putpkt (rs->buf);
8d64371b 2993 getpkt (&rs->buf, 0);
2e9f7625 2994 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2995}
2996
79efa585
SM
2997/* Return a pointer to a thread name if we know it and NULL otherwise.
2998 The thread_info object owns the memory for the name. */
2999
f6ac5f3d
PA
3000const char *
3001remote_target::thread_name (struct thread_info *info)
79efa585
SM
3002{
3003 if (info->priv != NULL)
a9334058
SM
3004 {
3005 const std::string &name = get_remote_thread_info (info)->name;
3006 return !name.empty () ? name.c_str () : NULL;
3007 }
79efa585
SM
3008
3009 return NULL;
3010}
3011
c906108c
SS
3012/* About these extended threadlist and threadinfo packets. They are
3013 variable length packets but, the fields within them are often fixed
30baf67b 3014 length. They are redundant enough to send over UDP as is the
c906108c
SS
3015 remote protocol in general. There is a matching unit test module
3016 in libstub. */
3017
23860348 3018/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 3019 libstub protocol encoding, and remote.c. It is not particularly
23860348 3020 changable. */
cce74817
JM
3021
3022/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 3023 Plan to fix this. */
cce74817 3024
23860348 3025typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 3026
9d1f7ab2 3027/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 3028 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
3029
3030struct gdb_ext_thread_info
c5aa993b 3031 {
23860348 3032 threadref threadid; /* External form of thread reference. */
2bc416ba 3033 int active; /* Has state interesting to GDB?
23860348 3034 regs, stack. */
2bc416ba 3035 char display[256]; /* Brief state display, name,
cedea757 3036 blocked/suspended. */
23860348 3037 char shortname[32]; /* To be used to name threads. */
2bc416ba 3038 char more_display[256]; /* Long info, statistics, queue depth,
23860348 3039 whatever. */
c5aa993b 3040 };
cce74817
JM
3041
3042/* The volume of remote transfers can be limited by submitting
3043 a mask containing bits specifying the desired information.
3044 Use a union of these values as the 'selection' parameter to
0df8b418 3045 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
3046
3047#define TAG_THREADID 1
3048#define TAG_EXISTS 2
3049#define TAG_DISPLAY 4
3050#define TAG_THREADNAME 8
c5aa993b 3051#define TAG_MOREDISPLAY 16
cce74817 3052
23860348 3053#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 3054
cecb1912 3055static const char *unpack_nibble (const char *buf, int *val);
cce74817 3056
cecb1912 3057static const char *unpack_byte (const char *buf, int *value);
cce74817 3058
a14ed312 3059static char *pack_int (char *buf, int value);
cce74817 3060
cecb1912 3061static const char *unpack_int (const char *buf, int *value);
cce74817 3062
cecb1912 3063static const char *unpack_string (const char *src, char *dest, int length);
cce74817 3064
23860348 3065static char *pack_threadid (char *pkt, threadref *id);
cce74817 3066
cecb1912 3067static const char *unpack_threadid (const char *inbuf, threadref *id);
cce74817 3068
23860348 3069void int_to_threadref (threadref *id, int value);
cce74817 3070
23860348 3071static int threadref_to_int (threadref *ref);
cce74817 3072
23860348 3073static void copy_threadref (threadref *dest, threadref *src);
cce74817 3074
23860348 3075static int threadmatch (threadref *dest, threadref *src);
cce74817 3076
2bc416ba 3077static char *pack_threadinfo_request (char *pkt, int mode,
23860348 3078 threadref *id);
cce74817 3079
a14ed312
KB
3080static char *pack_threadlist_request (char *pkt, int startflag,
3081 int threadcount,
23860348 3082 threadref *nextthread);
cce74817 3083
23860348 3084static int remote_newthread_step (threadref *ref, void *context);
cce74817 3085
82f73884
PA
3086
3087/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3088 buffer we're allowed to write to. Returns
3089 BUF+CHARACTERS_WRITTEN. */
3090
6b8edb51
PA
3091char *
3092remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
82f73884
PA
3093{
3094 int pid, tid;
3095 struct remote_state *rs = get_remote_state ();
3096
3097 if (remote_multi_process_p (rs))
3098 {
e99b03dc 3099 pid = ptid.pid ();
82f73884
PA
3100 if (pid < 0)
3101 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3102 else
3103 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3104 }
e38504b3 3105 tid = ptid.lwp ();
82f73884
PA
3106 if (tid < 0)
3107 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3108 else
3109 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3110
3111 return buf;
3112}
3113
256642e8
PA
3114/* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3115 last parsed char. Returns null_ptid if no thread id is found, and
3116 throws an error if the thread id has an invalid format. */
82f73884
PA
3117
3118static ptid_t
256642e8 3119read_ptid (const char *buf, const char **obuf)
82f73884 3120{
256642e8
PA
3121 const char *p = buf;
3122 const char *pp;
82f73884 3123 ULONGEST pid = 0, tid = 0;
82f73884
PA
3124
3125 if (*p == 'p')
3126 {
3127 /* Multi-process ptid. */
3128 pp = unpack_varlen_hex (p + 1, &pid);
3129 if (*pp != '.')
b37520b6 3130 error (_("invalid remote ptid: %s"), p);
82f73884
PA
3131
3132 p = pp;
3133 pp = unpack_varlen_hex (p + 1, &tid);
3134 if (obuf)
3135 *obuf = pp;
184ea2f7 3136 return ptid_t (pid, tid);
82f73884
PA
3137 }
3138
3139 /* No multi-process. Just a tid. */
3140 pp = unpack_varlen_hex (p, &tid);
3141
c9f35b34
KB
3142 /* Return null_ptid when no thread id is found. */
3143 if (p == pp)
3144 {
3145 if (obuf)
3146 *obuf = pp;
3147 return null_ptid;
3148 }
3149
2f761de2
TBA
3150 /* Since the stub is not sending a process id, default to what's
3151 current_inferior, unless it doesn't have a PID yet. If so,
ca19bf23
PA
3152 then since there's no way to know the pid of the reported
3153 threads, use the magic number. */
2f761de2
TBA
3154 inferior *inf = current_inferior ();
3155 if (inf->pid == 0)
e99b03dc 3156 pid = magic_null_ptid.pid ();
ca19bf23 3157 else
2f761de2 3158 pid = inf->pid;
82f73884
PA
3159
3160 if (obuf)
3161 *obuf = pp;
184ea2f7 3162 return ptid_t (pid, tid);
82f73884
PA
3163}
3164
c906108c 3165static int
fba45db2 3166stubhex (int ch)
c906108c
SS
3167{
3168 if (ch >= 'a' && ch <= 'f')
3169 return ch - 'a' + 10;
3170 if (ch >= '0' && ch <= '9')
3171 return ch - '0';
3172 if (ch >= 'A' && ch <= 'F')
3173 return ch - 'A' + 10;
3174 return -1;
3175}
3176
3177static int
cecb1912 3178stub_unpack_int (const char *buff, int fieldlength)
c906108c
SS
3179{
3180 int nibble;
3181 int retval = 0;
3182
3183 while (fieldlength)
3184 {
3185 nibble = stubhex (*buff++);
3186 retval |= nibble;
3187 fieldlength--;
3188 if (fieldlength)
3189 retval = retval << 4;
3190 }
3191 return retval;
3192}
3193
cecb1912
SM
3194static const char *
3195unpack_nibble (const char *buf, int *val)
c906108c 3196{
b7589f7d 3197 *val = fromhex (*buf++);
c906108c
SS
3198 return buf;
3199}
3200
cecb1912
SM
3201static const char *
3202unpack_byte (const char *buf, int *value)
c906108c
SS
3203{
3204 *value = stub_unpack_int (buf, 2);
3205 return buf + 2;
3206}
3207
3208static char *
fba45db2 3209pack_int (char *buf, int value)
c906108c
SS
3210{
3211 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3212 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3213 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3214 buf = pack_hex_byte (buf, (value & 0xff));
3215 return buf;
3216}
3217
cecb1912
SM
3218static const char *
3219unpack_int (const char *buf, int *value)
c906108c
SS
3220{
3221 *value = stub_unpack_int (buf, 8);
3222 return buf + 8;
3223}
3224
23860348 3225#if 0 /* Currently unused, uncomment when needed. */
a14ed312 3226static char *pack_string (char *pkt, char *string);
c906108c
SS
3227
3228static char *
fba45db2 3229pack_string (char *pkt, char *string)
c906108c
SS
3230{
3231 char ch;
3232 int len;
3233
3234 len = strlen (string);
3235 if (len > 200)
23860348 3236 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
3237 pkt = pack_hex_byte (pkt, len);
3238 while (len-- > 0)
3239 {
3240 ch = *string++;
3241 if ((ch == '\0') || (ch == '#'))
23860348 3242 ch = '*'; /* Protect encapsulation. */
c906108c
SS
3243 *pkt++ = ch;
3244 }
3245 return pkt;
3246}
3247#endif /* 0 (unused) */
3248
cecb1912
SM
3249static const char *
3250unpack_string (const char *src, char *dest, int length)
c906108c
SS
3251{
3252 while (length--)
3253 *dest++ = *src++;
3254 *dest = '\0';
3255 return src;
3256}
3257
3258static char *
fba45db2 3259pack_threadid (char *pkt, threadref *id)
c906108c
SS
3260{
3261 char *limit;
3262 unsigned char *altid;
3263
3264 altid = (unsigned char *) id;
3265 limit = pkt + BUF_THREAD_ID_SIZE;
3266 while (pkt < limit)
3267 pkt = pack_hex_byte (pkt, *altid++);
3268 return pkt;
3269}
3270
3271
cecb1912
SM
3272static const char *
3273unpack_threadid (const char *inbuf, threadref *id)
c906108c
SS
3274{
3275 char *altref;
cecb1912 3276 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
c906108c
SS
3277 int x, y;
3278
3279 altref = (char *) id;
3280
3281 while (inbuf < limit)
3282 {
3283 x = stubhex (*inbuf++);
3284 y = stubhex (*inbuf++);
3285 *altref++ = (x << 4) | y;
3286 }
3287 return inbuf;
3288}
3289
3290/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 3291 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
3292 to use 64bit thread references internally. This is an adapter
3293 function. */
3294
3295void
fba45db2 3296int_to_threadref (threadref *id, int value)
c906108c
SS
3297{
3298 unsigned char *scan;
3299
3300 scan = (unsigned char *) id;
3301 {
3302 int i = 4;
3303 while (i--)
3304 *scan++ = 0;
3305 }
3306 *scan++ = (value >> 24) & 0xff;
3307 *scan++ = (value >> 16) & 0xff;
3308 *scan++ = (value >> 8) & 0xff;
3309 *scan++ = (value & 0xff);
3310}
3311
3312static int
fba45db2 3313threadref_to_int (threadref *ref)
c906108c
SS
3314{
3315 int i, value = 0;
3316 unsigned char *scan;
3317
cfd77fa1 3318 scan = *ref;
c906108c
SS
3319 scan += 4;
3320 i = 4;
3321 while (i-- > 0)
3322 value = (value << 8) | ((*scan++) & 0xff);
3323 return value;
3324}
3325
3326static void
fba45db2 3327copy_threadref (threadref *dest, threadref *src)
c906108c
SS
3328{
3329 int i;
3330 unsigned char *csrc, *cdest;
3331
3332 csrc = (unsigned char *) src;
3333 cdest = (unsigned char *) dest;
3334 i = 8;
3335 while (i--)
3336 *cdest++ = *csrc++;
3337}
3338
3339static int
fba45db2 3340threadmatch (threadref *dest, threadref *src)
c906108c 3341{
23860348 3342 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
3343#if 0
3344 unsigned char *srcp, *destp;
3345 int i, result;
3346 srcp = (char *) src;
3347 destp = (char *) dest;
3348
3349 result = 1;
3350 while (i-- > 0)
3351 result &= (*srcp++ == *destp++) ? 1 : 0;
3352 return result;
3353#endif
3354 return 1;
3355}
3356
3357/*
c5aa993b
JM
3358 threadid:1, # always request threadid
3359 context_exists:2,
3360 display:4,
3361 unique_name:8,
3362 more_display:16
3363 */
c906108c
SS
3364
3365/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3366
3367static char *
fba45db2 3368pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 3369{
23860348
MS
3370 *pkt++ = 'q'; /* Info Query */
3371 *pkt++ = 'P'; /* process or thread info */
3372 pkt = pack_int (pkt, mode); /* mode */
c906108c 3373 pkt = pack_threadid (pkt, id); /* threadid */
23860348 3374 *pkt = '\0'; /* terminate */
c906108c
SS
3375 return pkt;
3376}
3377
23860348 3378/* These values tag the fields in a thread info response packet. */
c906108c 3379/* Tagging the fields allows us to request specific fields and to
23860348 3380 add more fields as time goes by. */
c906108c 3381
23860348 3382#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 3383#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 3384 fetch registers and its stack? */
c5aa993b 3385#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 3386#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 3387#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 3388 the process. */
c906108c 3389
6b8edb51 3390int
cecb1912 3391remote_target::remote_unpack_thread_info_response (const char *pkt,
6b8edb51
PA
3392 threadref *expectedref,
3393 gdb_ext_thread_info *info)
c906108c 3394{
d01949b6 3395 struct remote_state *rs = get_remote_state ();
c906108c 3396 int mask, length;
cfd77fa1 3397 int tag;
c906108c 3398 threadref ref;
cecb1912 3399 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
c906108c
SS
3400 int retval = 1;
3401
23860348 3402 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
3403 info->active = 0;
3404 info->display[0] = '\0';
3405 info->shortname[0] = '\0';
3406 info->more_display[0] = '\0';
3407
23860348
MS
3408 /* Assume the characters indicating the packet type have been
3409 stripped. */
c906108c
SS
3410 pkt = unpack_int (pkt, &mask); /* arg mask */
3411 pkt = unpack_threadid (pkt, &ref);
3412
3413 if (mask == 0)
8a3fe4f8 3414 warning (_("Incomplete response to threadinfo request."));
c906108c 3415 if (!threadmatch (&ref, expectedref))
23860348 3416 { /* This is an answer to a different request. */
8a3fe4f8 3417 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
3418 return 0;
3419 }
3420 copy_threadref (&info->threadid, &ref);
3421
405feb71 3422 /* Loop on tagged fields , try to bail if something goes wrong. */
c906108c 3423
23860348
MS
3424 /* Packets are terminated with nulls. */
3425 while ((pkt < limit) && mask && *pkt)
c906108c
SS
3426 {
3427 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
3428 pkt = unpack_byte (pkt, &length); /* length */
3429 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 3430 {
8a3fe4f8 3431 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
3432 retval = 0;
3433 break;
3434 }
3435 if (tag == TAG_THREADID)
3436 {
3437 if (length != 16)
3438 {
8a3fe4f8 3439 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
3440 retval = 0;
3441 break;
3442 }
3443 pkt = unpack_threadid (pkt, &ref);
3444 mask = mask & ~TAG_THREADID;
3445 continue;
3446 }
3447 if (tag == TAG_EXISTS)
3448 {
3449 info->active = stub_unpack_int (pkt, length);
3450 pkt += length;
3451 mask = mask & ~(TAG_EXISTS);
3452 if (length > 8)
3453 {
8a3fe4f8 3454 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
3455 retval = 0;
3456 break;
3457 }
3458 continue;
3459 }
3460 if (tag == TAG_THREADNAME)
3461 {
3462 pkt = unpack_string (pkt, &info->shortname[0], length);
3463 mask = mask & ~TAG_THREADNAME;
3464 continue;
3465 }
3466 if (tag == TAG_DISPLAY)
3467 {
3468 pkt = unpack_string (pkt, &info->display[0], length);
3469 mask = mask & ~TAG_DISPLAY;
3470 continue;
3471 }
3472 if (tag == TAG_MOREDISPLAY)
3473 {
3474 pkt = unpack_string (pkt, &info->more_display[0], length);
3475 mask = mask & ~TAG_MOREDISPLAY;
3476 continue;
3477 }
8a3fe4f8 3478 warning (_("ERROR RMT: unknown thread info tag."));
23860348 3479 break; /* Not a tag we know about. */
c906108c
SS
3480 }
3481 return retval;
3482}
3483
6b8edb51
PA
3484int
3485remote_target::remote_get_threadinfo (threadref *threadid,
3486 int fieldset,
3487 gdb_ext_thread_info *info)
c906108c 3488{
d01949b6 3489 struct remote_state *rs = get_remote_state ();
c906108c 3490 int result;
c906108c 3491
8d64371b 3492 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
2e9f7625 3493 putpkt (rs->buf);
8d64371b 3494 getpkt (&rs->buf, 0);
3084dd77
PA
3495
3496 if (rs->buf[0] == '\0')
3497 return 0;
3498
8d64371b 3499 result = remote_unpack_thread_info_response (&rs->buf[2],
23860348 3500 threadid, info);
c906108c
SS
3501 return result;
3502}
3503
c906108c
SS
3504/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3505
3506static char *
fba45db2
KB
3507pack_threadlist_request (char *pkt, int startflag, int threadcount,
3508 threadref *nextthread)
c906108c
SS
3509{
3510 *pkt++ = 'q'; /* info query packet */
3511 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 3512 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
3513 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3514 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3515 *pkt = '\0';
3516 return pkt;
3517}
3518
3519/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3520
6b8edb51 3521int
cecb1912 3522remote_target::parse_threadlist_response (const char *pkt, int result_limit,
6b8edb51
PA
3523 threadref *original_echo,
3524 threadref *resultlist,
3525 int *doneflag)
c906108c 3526{
d01949b6 3527 struct remote_state *rs = get_remote_state ();
c906108c
SS
3528 int count, resultcount, done;
3529
3530 resultcount = 0;
3531 /* Assume the 'q' and 'M chars have been stripped. */
cecb1912 3532 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
23860348 3533 /* done parse past here */
c906108c
SS
3534 pkt = unpack_byte (pkt, &count); /* count field */
3535 pkt = unpack_nibble (pkt, &done);
3536 /* The first threadid is the argument threadid. */
3537 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3538 while ((count-- > 0) && (pkt < limit))
3539 {
3540 pkt = unpack_threadid (pkt, resultlist++);
3541 if (resultcount++ >= result_limit)
3542 break;
3543 }
3544 if (doneflag)
3545 *doneflag = done;
3546 return resultcount;
3547}
3548
6dc54d91
PA
3549/* Fetch the next batch of threads from the remote. Returns -1 if the
3550 qL packet is not supported, 0 on error and 1 on success. */
3551
6b8edb51
PA
3552int
3553remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3554 int result_limit, int *done, int *result_count,
3555 threadref *threadlist)
c906108c 3556{
d01949b6 3557 struct remote_state *rs = get_remote_state ();
c906108c
SS
3558 int result = 1;
3559
405feb71 3560 /* Truncate result limit to be smaller than the packet size. */
3e43a32a
MS
3561 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3562 >= get_remote_packet_size ())
ea9c271d 3563 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 3564
8d64371b
TT
3565 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3566 nextthread);
6d820c5c 3567 putpkt (rs->buf);
8d64371b
TT
3568 getpkt (&rs->buf, 0);
3569 if (rs->buf[0] == '\0')
6dc54d91
PA
3570 {
3571 /* Packet not supported. */
3572 return -1;
3573 }
3574
3575 *result_count =
8d64371b 3576 parse_threadlist_response (&rs->buf[2], result_limit,
6dc54d91 3577 &rs->echo_nextthread, threadlist, done);
c906108c 3578
0d031856 3579 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 3580 {
23860348 3581 /* FIXME: This is a good reason to drop the packet. */
405feb71
TV
3582 /* Possibly, there is a duplicate response. */
3583 /* Possibilities :
dda83cd7
SM
3584 retransmit immediatly - race conditions
3585 retransmit after timeout - yes
3586 exit
3587 wait for packet, then exit
c906108c 3588 */
8a3fe4f8 3589 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 3590 return 0; /* I choose simply exiting. */
c906108c
SS
3591 }
3592 if (*result_count <= 0)
3593 {
3594 if (*done != 1)
3595 {
8a3fe4f8 3596 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
3597 result = 0;
3598 }
3599 return result; /* break; */
3600 }
3601 if (*result_count > result_limit)
3602 {
3603 *result_count = 0;
8a3fe4f8 3604 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
3605 return 0;
3606 }
3607 return result;
3608}
3609
6dc54d91
PA
3610/* Fetch the list of remote threads, with the qL packet, and call
3611 STEPFUNCTION for each thread found. Stops iterating and returns 1
3612 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3613 STEPFUNCTION returns false. If the packet is not supported,
3614 returns -1. */
c906108c 3615
6b8edb51
PA
3616int
3617remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3618 void *context, int looplimit)
c906108c 3619{
0d031856 3620 struct remote_state *rs = get_remote_state ();
c906108c
SS
3621 int done, i, result_count;
3622 int startflag = 1;
3623 int result = 1;
3624 int loopcount = 0;
c906108c
SS
3625
3626 done = 0;
3627 while (!done)
3628 {
3629 if (loopcount++ > looplimit)
3630 {
3631 result = 0;
8a3fe4f8 3632 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
3633 break;
3634 }
6dc54d91
PA
3635 result = remote_get_threadlist (startflag, &rs->nextthread,
3636 MAXTHREADLISTRESULTS,
3637 &done, &result_count,
3638 rs->resultthreadlist);
3639 if (result <= 0)
3640 break;
23860348 3641 /* Clear for later iterations. */
c906108c
SS
3642 startflag = 0;
3643 /* Setup to resume next batch of thread references, set nextthread. */
3644 if (result_count >= 1)
0d031856
TT
3645 copy_threadref (&rs->nextthread,
3646 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
3647 i = 0;
3648 while (result_count--)
6dc54d91
PA
3649 {
3650 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3651 {
3652 result = 0;
3653 break;
3654 }
3655 }
c906108c
SS
3656 }
3657 return result;
3658}
3659
6dc54d91
PA
3660/* A thread found on the remote target. */
3661
21fe1c75 3662struct thread_item
6dc54d91 3663{
21fe1c75
SM
3664 explicit thread_item (ptid_t ptid_)
3665 : ptid (ptid_)
3666 {}
3667
3668 thread_item (thread_item &&other) = default;
3669 thread_item &operator= (thread_item &&other) = default;
3670
3671 DISABLE_COPY_AND_ASSIGN (thread_item);
3672
6dc54d91
PA
3673 /* The thread's PTID. */
3674 ptid_t ptid;
3675
21fe1c75
SM
3676 /* The thread's extra info. */
3677 std::string extra;
6dc54d91 3678
21fe1c75
SM
3679 /* The thread's name. */
3680 std::string name;
79efa585 3681
6dc54d91 3682 /* The core the thread was running on. -1 if not known. */
21fe1c75 3683 int core = -1;
f6327dcb
KB
3684
3685 /* The thread handle associated with the thread. */
21fe1c75 3686 gdb::byte_vector thread_handle;
21fe1c75 3687};
6dc54d91
PA
3688
3689/* Context passed around to the various methods listing remote
3690 threads. As new threads are found, they're added to the ITEMS
3691 vector. */
3692
3693struct threads_listing_context
3694{
21fe1c75
SM
3695 /* Return true if this object contains an entry for a thread with ptid
3696 PTID. */
6dc54d91 3697
21fe1c75
SM
3698 bool contains_thread (ptid_t ptid) const
3699 {
3700 auto match_ptid = [&] (const thread_item &item)
3701 {
3702 return item.ptid == ptid;
3703 };
80134cf5 3704
21fe1c75
SM
3705 auto it = std::find_if (this->items.begin (),
3706 this->items.end (),
3707 match_ptid);
80134cf5 3708
21fe1c75
SM
3709 return it != this->items.end ();
3710 }
80134cf5 3711
21fe1c75 3712 /* Remove the thread with ptid PTID. */
80134cf5 3713
21fe1c75
SM
3714 void remove_thread (ptid_t ptid)
3715 {
3716 auto match_ptid = [&] (const thread_item &item)
3717 {
dda83cd7 3718 return item.ptid == ptid;
21fe1c75 3719 };
cbb8991c 3720
21fe1c75
SM
3721 auto it = std::remove_if (this->items.begin (),
3722 this->items.end (),
3723 match_ptid);
cbb8991c 3724
21fe1c75
SM
3725 if (it != this->items.end ())
3726 this->items.erase (it);
3727 }
3728
3729 /* The threads found on the remote target. */
3730 std::vector<thread_item> items;
3731};
cbb8991c 3732
c906108c 3733static int
6dc54d91 3734remote_newthread_step (threadref *ref, void *data)
c906108c 3735{
19ba03f4
SM
3736 struct threads_listing_context *context
3737 = (struct threads_listing_context *) data;
21fe1c75
SM
3738 int pid = inferior_ptid.pid ();
3739 int lwp = threadref_to_int (ref);
3740 ptid_t ptid (pid, lwp);
6dc54d91 3741
21fe1c75 3742 context->items.emplace_back (ptid);
6dc54d91 3743
c906108c
SS
3744 return 1; /* continue iterator */
3745}
3746
3747#define CRAZY_MAX_THREADS 1000
3748
6b8edb51
PA
3749ptid_t
3750remote_target::remote_current_thread (ptid_t oldpid)
c906108c 3751{
d01949b6 3752 struct remote_state *rs = get_remote_state ();
c906108c
SS
3753
3754 putpkt ("qC");
8d64371b 3755 getpkt (&rs->buf, 0);
2e9f7625 3756 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34 3757 {
256642e8 3758 const char *obuf;
c9f35b34
KB
3759 ptid_t result;
3760
3761 result = read_ptid (&rs->buf[2], &obuf);
2189c312
SM
3762 if (*obuf != '\0')
3763 remote_debug_printf ("warning: garbage in qC reply");
c9f35b34
KB
3764
3765 return result;
3766 }
c906108c
SS
3767 else
3768 return oldpid;
3769}
3770
6dc54d91 3771/* List remote threads using the deprecated qL packet. */
cce74817 3772
6b8edb51
PA
3773int
3774remote_target::remote_get_threads_with_ql (threads_listing_context *context)
c906108c 3775{
6dc54d91
PA
3776 if (remote_threadlist_iterator (remote_newthread_step, context,
3777 CRAZY_MAX_THREADS) >= 0)
3778 return 1;
3779
3780 return 0;
c906108c
SS
3781}
3782
dc146f7c
VP
3783#if defined(HAVE_LIBEXPAT)
3784
dc146f7c
VP
3785static void
3786start_thread (struct gdb_xml_parser *parser,
3787 const struct gdb_xml_element *element,
4d0fdd9b
SM
3788 void *user_data,
3789 std::vector<gdb_xml_value> &attributes)
dc146f7c 3790{
19ba03f4
SM
3791 struct threads_listing_context *data
3792 = (struct threads_listing_context *) user_data;
3d2c1d41 3793 struct gdb_xml_value *attr;
dc146f7c 3794
4d0fdd9b 3795 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
21fe1c75
SM
3796 ptid_t ptid = read_ptid (id, NULL);
3797
3798 data->items.emplace_back (ptid);
3799 thread_item &item = data->items.back ();
dc146f7c 3800
3d2c1d41
PA
3801 attr = xml_find_attribute (attributes, "core");
3802 if (attr != NULL)
4d0fdd9b 3803 item.core = *(ULONGEST *) attr->value.get ();
dc146f7c 3804
79efa585 3805 attr = xml_find_attribute (attributes, "name");
21fe1c75 3806 if (attr != NULL)
4d0fdd9b 3807 item.name = (const char *) attr->value.get ();
79efa585 3808
f6327dcb
KB
3809 attr = xml_find_attribute (attributes, "handle");
3810 if (attr != NULL)
4d0fdd9b 3811 item.thread_handle = hex2bin ((const char *) attr->value.get ());
dc146f7c
VP
3812}
3813
3814static void
3815end_thread (struct gdb_xml_parser *parser,
3816 const struct gdb_xml_element *element,
3817 void *user_data, const char *body_text)
3818{
19ba03f4
SM
3819 struct threads_listing_context *data
3820 = (struct threads_listing_context *) user_data;
dc146f7c 3821
21fe1c75
SM
3822 if (body_text != NULL && *body_text != '\0')
3823 data->items.back ().extra = body_text;
dc146f7c
VP
3824}
3825
3826const struct gdb_xml_attribute thread_attributes[] = {
3827 { "id", GDB_XML_AF_NONE, NULL, NULL },
3828 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3829 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
f6327dcb 3830 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3831 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3832};
3833
3834const struct gdb_xml_element thread_children[] = {
3835 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3836};
3837
3838const struct gdb_xml_element threads_children[] = {
3839 { "thread", thread_attributes, thread_children,
3840 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3841 start_thread, end_thread },
3842 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3843};
3844
3845const struct gdb_xml_element threads_elements[] = {
3846 { "threads", NULL, threads_children,
3847 GDB_XML_EF_NONE, NULL, NULL },
3848 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3849};
3850
3851#endif
3852
6dc54d91 3853/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3854
6b8edb51
PA
3855int
3856remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
0f71a2f6 3857{
dc146f7c 3858#if defined(HAVE_LIBEXPAT)
4082afcc 3859 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3860 {
9018be22 3861 gdb::optional<gdb::char_vector> xml
6b8edb51 3862 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
efc0eabd 3863
9018be22 3864 if (xml && (*xml)[0] != '\0')
dc146f7c 3865 {
6dc54d91 3866 gdb_xml_parse_quick (_("threads"), "threads.dtd",
9018be22 3867 threads_elements, xml->data (), context);
dc146f7c
VP
3868 }
3869
6dc54d91 3870 return 1;
dc146f7c
VP
3871 }
3872#endif
3873
6dc54d91
PA
3874 return 0;
3875}
3876
3877/* List remote threads using qfThreadInfo/qsThreadInfo. */
3878
6b8edb51
PA
3879int
3880remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
6dc54d91
PA
3881{
3882 struct remote_state *rs = get_remote_state ();
3883
b80fafe3 3884 if (rs->use_threadinfo_query)
9d1f7ab2 3885 {
256642e8 3886 const char *bufp;
6dc54d91 3887
9d1f7ab2 3888 putpkt ("qfThreadInfo");
8d64371b
TT
3889 getpkt (&rs->buf, 0);
3890 bufp = rs->buf.data ();
9d1f7ab2 3891 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3892 {
9d1f7ab2
MS
3893 while (*bufp++ == 'm') /* reply contains one or more TID */
3894 {
3895 do
3896 {
21fe1c75
SM
3897 ptid_t ptid = read_ptid (bufp, &bufp);
3898 context->items.emplace_back (ptid);
9d1f7ab2
MS
3899 }
3900 while (*bufp++ == ','); /* comma-separated list */
3901 putpkt ("qsThreadInfo");
8d64371b
TT
3902 getpkt (&rs->buf, 0);
3903 bufp = rs->buf.data ();
9d1f7ab2 3904 }
6dc54d91
PA
3905 return 1;
3906 }
3907 else
3908 {
3909 /* Packet not recognized. */
3910 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3911 }
3912 }
3913
6dc54d91
PA
3914 return 0;
3915}
3916
a05575d3
TBA
3917/* Return true if INF only has one non-exited thread. */
3918
3919static bool
3920has_single_non_exited_thread (inferior *inf)
3921{
3922 int count = 0;
3923 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
3924 if (++count > 1)
3925 break;
3926 return count == 1;
3927}
3928
e8032dde 3929/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3930 targets. */
3931
f6ac5f3d
PA
3932void
3933remote_target::update_thread_list ()
6dc54d91 3934{
6dc54d91 3935 struct threads_listing_context context;
ab970af1 3936 int got_list = 0;
e8032dde 3937
6dc54d91
PA
3938 /* We have a few different mechanisms to fetch the thread list. Try
3939 them all, starting with the most preferred one first, falling
3940 back to older methods. */
6b8edb51
PA
3941 if (remote_get_threads_with_qxfer (&context)
3942 || remote_get_threads_with_qthreadinfo (&context)
3943 || remote_get_threads_with_ql (&context))
6dc54d91 3944 {
ab970af1
PA
3945 got_list = 1;
3946
21fe1c75 3947 if (context.items.empty ()
f6ac5f3d 3948 && remote_thread_always_alive (inferior_ptid))
7d1a114c
PA
3949 {
3950 /* Some targets don't really support threads, but still
3951 reply an (empty) thread list in response to the thread
3952 listing packets, instead of replying "packet not
3953 supported". Exit early so we don't delete the main
3954 thread. */
7d1a114c
PA
3955 return;
3956 }
3957
ab970af1
PA
3958 /* CONTEXT now holds the current thread list on the remote
3959 target end. Delete GDB-side threads no longer found on the
3960 target. */
08036331 3961 for (thread_info *tp : all_threads_safe ())
cbb8991c 3962 {
5b6d1e4f
PA
3963 if (tp->inf->process_target () != this)
3964 continue;
3965
21fe1c75 3966 if (!context.contains_thread (tp->ptid))
ab970af1 3967 {
a05575d3
TBA
3968 /* Do not remove the thread if it is the last thread in
3969 the inferior. This situation happens when we have a
3970 pending exit process status to process. Otherwise we
3971 may end up with a seemingly live inferior (i.e. pid
3972 != 0) that has no threads. */
3973 if (has_single_non_exited_thread (tp->inf))
3974 continue;
3975
ab970af1 3976 /* Not found. */
00431a78 3977 delete_thread (tp);
ab970af1 3978 }
cbb8991c
DB
3979 }
3980
3981 /* Remove any unreported fork child threads from CONTEXT so
3982 that we don't interfere with follow fork, which is where
3983 creation of such threads is handled. */
3984 remove_new_fork_children (&context);
74531fed 3985
ab970af1 3986 /* And now add threads we don't know about yet to our list. */
21fe1c75 3987 for (thread_item &item : context.items)
6dc54d91 3988 {
21fe1c75 3989 if (item.ptid != null_ptid)
6dc54d91 3990 {
6dc54d91 3991 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
3992 executing until proven otherwise with a stop reply.
3993 In all-stop, we can only get here if all threads are
6dc54d91 3994 stopped. */
8a82de58 3995 bool executing = target_is_non_stop_p ();
6dc54d91 3996
21fe1c75 3997 remote_notice_new_inferior (item.ptid, executing);
6dc54d91 3998
5b6d1e4f 3999 thread_info *tp = find_thread_ptid (this, item.ptid);
00431a78 4000 remote_thread_info *info = get_remote_thread_info (tp);
21fe1c75 4001 info->core = item.core;
7aabaf9d
SM
4002 info->extra = std::move (item.extra);
4003 info->name = std::move (item.name);
4004 info->thread_handle = std::move (item.thread_handle);
6dc54d91
PA
4005 }
4006 }
4007 }
4008
ab970af1
PA
4009 if (!got_list)
4010 {
4011 /* If no thread listing method is supported, then query whether
4012 each known thread is alive, one by one, with the T packet.
4013 If the target doesn't support threads at all, then this is a
4014 no-op. See remote_thread_alive. */
4015 prune_threads ();
4016 }
9d1f7ab2
MS
4017}
4018
802188a7 4019/*
9d1f7ab2
MS
4020 * Collect a descriptive string about the given thread.
4021 * The target may say anything it wants to about the thread
4022 * (typically info about its blocked / runnable state, name, etc.).
4023 * This string will appear in the info threads display.
802188a7 4024 *
9d1f7ab2
MS
4025 * Optional: targets are not required to implement this function.
4026 */
4027
f6ac5f3d
PA
4028const char *
4029remote_target::extra_thread_info (thread_info *tp)
9d1f7ab2 4030{
d01949b6 4031 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
4032 int set;
4033 threadref id;
4034 struct gdb_ext_thread_info threadinfo;
9d1f7ab2 4035
5d93a237 4036 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 4037 internal_error (__FILE__, __LINE__,
e2e0b3e5 4038 _("remote_threads_extra_info"));
9d1f7ab2 4039
d7e15655 4040 if (tp->ptid == magic_null_ptid
e38504b3 4041 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
60e569b9
PA
4042 /* This is the main thread which was added by GDB. The remote
4043 server doesn't know about it. */
4044 return NULL;
4045
c76a8ea3
PA
4046 std::string &extra = get_remote_thread_info (tp)->extra;
4047
4048 /* If already have cached info, use it. */
4049 if (!extra.empty ())
4050 return extra.c_str ();
4051
4082afcc 4052 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 4053 {
c76a8ea3
PA
4054 /* If we're using qXfer:threads:read, then the extra info is
4055 included in the XML. So if we didn't have anything cached,
4056 it's because there's really no extra info. */
4057 return NULL;
dc146f7c
VP
4058 }
4059
b80fafe3 4060 if (rs->use_threadextra_query)
9d1f7ab2 4061 {
8d64371b
TT
4062 char *b = rs->buf.data ();
4063 char *endb = b + get_remote_packet_size ();
82f73884
PA
4064
4065 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4066 b += strlen (b);
4067 write_ptid (b, endb, tp->ptid);
4068
2e9f7625 4069 putpkt (rs->buf);
8d64371b 4070 getpkt (&rs->buf, 0);
2e9f7625 4071 if (rs->buf[0] != 0)
9d1f7ab2 4072 {
8d64371b
TT
4073 extra.resize (strlen (rs->buf.data ()) / 2);
4074 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
c76a8ea3 4075 return extra.c_str ();
9d1f7ab2 4076 }
0f71a2f6 4077 }
9d1f7ab2
MS
4078
4079 /* If the above query fails, fall back to the old method. */
b80fafe3 4080 rs->use_threadextra_query = 0;
9d1f7ab2
MS
4081 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4082 | TAG_MOREDISPLAY | TAG_DISPLAY;
e38504b3 4083 int_to_threadref (&id, tp->ptid.lwp ());
9d1f7ab2
MS
4084 if (remote_get_threadinfo (&id, set, &threadinfo))
4085 if (threadinfo.active)
0f71a2f6 4086 {
9d1f7ab2 4087 if (*threadinfo.shortname)
c76a8ea3 4088 string_appendf (extra, " Name: %s", threadinfo.shortname);
9d1f7ab2 4089 if (*threadinfo.display)
c76a8ea3
PA
4090 {
4091 if (!extra.empty ())
4092 extra += ',';
4093 string_appendf (extra, " State: %s", threadinfo.display);
4094 }
9d1f7ab2 4095 if (*threadinfo.more_display)
c5aa993b 4096 {
c76a8ea3
PA
4097 if (!extra.empty ())
4098 extra += ',';
4099 string_appendf (extra, " Priority: %s", threadinfo.more_display);
c5aa993b 4100 }
c76a8ea3 4101 return extra.c_str ();
0f71a2f6 4102 }
9d1f7ab2 4103 return NULL;
0f71a2f6 4104}
c906108c 4105\f
c5aa993b 4106
f6ac5f3d
PA
4107bool
4108remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4109 struct static_tracepoint_marker *marker)
0fb4aa4b
PA
4110{
4111 struct remote_state *rs = get_remote_state ();
8d64371b 4112 char *p = rs->buf.data ();
0fb4aa4b 4113
bba74b36 4114 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
4115 p += strlen (p);
4116 p += hexnumstr (p, addr);
4117 putpkt (rs->buf);
8d64371b
TT
4118 getpkt (&rs->buf, 0);
4119 p = rs->buf.data ();
0fb4aa4b
PA
4120
4121 if (*p == 'E')
4122 error (_("Remote failure reply: %s"), p);
4123
4124 if (*p++ == 'm')
4125 {
256642e8 4126 parse_static_tracepoint_marker_definition (p, NULL, marker);
5d9310c4 4127 return true;
0fb4aa4b
PA
4128 }
4129
5d9310c4 4130 return false;
0fb4aa4b
PA
4131}
4132
f6ac5f3d
PA
4133std::vector<static_tracepoint_marker>
4134remote_target::static_tracepoint_markers_by_strid (const char *strid)
0fb4aa4b
PA
4135{
4136 struct remote_state *rs = get_remote_state ();
5d9310c4 4137 std::vector<static_tracepoint_marker> markers;
256642e8 4138 const char *p;
5d9310c4 4139 static_tracepoint_marker marker;
0fb4aa4b
PA
4140
4141 /* Ask for a first packet of static tracepoint marker
4142 definition. */
4143 putpkt ("qTfSTM");
8d64371b
TT
4144 getpkt (&rs->buf, 0);
4145 p = rs->buf.data ();
0fb4aa4b
PA
4146 if (*p == 'E')
4147 error (_("Remote failure reply: %s"), p);
4148
0fb4aa4b
PA
4149 while (*p++ == 'm')
4150 {
0fb4aa4b
PA
4151 do
4152 {
5d9310c4 4153 parse_static_tracepoint_marker_definition (p, &p, &marker);
0fb4aa4b 4154
5d9310c4
SM
4155 if (strid == NULL || marker.str_id == strid)
4156 markers.push_back (std::move (marker));
0fb4aa4b
PA
4157 }
4158 while (*p++ == ','); /* comma-separated list */
4159 /* Ask for another packet of static tracepoint definition. */
4160 putpkt ("qTsSTM");
8d64371b
TT
4161 getpkt (&rs->buf, 0);
4162 p = rs->buf.data ();
0fb4aa4b
PA
4163 }
4164
0fb4aa4b
PA
4165 return markers;
4166}
4167
4168\f
10760264
JB
4169/* Implement the to_get_ada_task_ptid function for the remote targets. */
4170
f6ac5f3d 4171ptid_t
c80e29db 4172remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
10760264 4173{
184ea2f7 4174 return ptid_t (inferior_ptid.pid (), lwp);
10760264
JB
4175}
4176\f
4177
24b06219 4178/* Restart the remote side; this is an extended protocol operation. */
c906108c 4179
6b8edb51
PA
4180void
4181remote_target::extended_remote_restart ()
c906108c 4182{
d01949b6 4183 struct remote_state *rs = get_remote_state ();
c906108c
SS
4184
4185 /* Send the restart command; for reasons I don't understand the
4186 remote side really expects a number after the "R". */
8d64371b 4187 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
6d820c5c 4188 putpkt (rs->buf);
c906108c 4189
ad9a8f3f 4190 remote_fileio_reset ();
c906108c
SS
4191}
4192\f
4193/* Clean up connection to a remote debugger. */
4194
f6ac5f3d
PA
4195void
4196remote_target::close ()
c906108c 4197{
048094ac 4198 /* Make sure we leave stdin registered in the event loop. */
f6ac5f3d 4199 terminal_ours ();
ce5ce7ed 4200
6b8edb51
PA
4201 trace_reset_local_state ();
4202
4203 delete this;
4204}
4205
4206remote_target::~remote_target ()
4207{
4208 struct remote_state *rs = get_remote_state ();
4209
4210 /* Check for NULL because we may get here with a partially
4211 constructed target/connection. */
4212 if (rs->remote_desc == nullptr)
4213 return;
4214
4215 serial_close (rs->remote_desc);
4216
4217 /* We are destroying the remote target, so we should discard
f48ff2a7 4218 everything of this target. */
6b8edb51 4219 discard_pending_stop_replies_in_queue ();
74531fed 4220
6b8edb51
PA
4221 if (rs->remote_async_inferior_event_token)
4222 delete_async_event_handler (&rs->remote_async_inferior_event_token);
722247f1 4223
97dfbadd 4224 delete rs->notif_state;
c906108c
SS
4225}
4226
23860348 4227/* Query the remote side for the text, data and bss offsets. */
c906108c 4228
6b8edb51
PA
4229void
4230remote_target::get_offsets ()
c906108c 4231{
d01949b6 4232 struct remote_state *rs = get_remote_state ();
2e9f7625 4233 char *buf;
085dd6e6 4234 char *ptr;
31d99776
DJ
4235 int lose, num_segments = 0, do_sections, do_segments;
4236 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
31d99776 4237
a42d7dd8 4238 if (current_program_space->symfile_object_file == NULL)
31d99776 4239 return;
c906108c
SS
4240
4241 putpkt ("qOffsets");
8d64371b
TT
4242 getpkt (&rs->buf, 0);
4243 buf = rs->buf.data ();
c906108c
SS
4244
4245 if (buf[0] == '\000')
4246 return; /* Return silently. Stub doesn't support
23860348 4247 this command. */
c906108c
SS
4248 if (buf[0] == 'E')
4249 {
8a3fe4f8 4250 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
4251 return;
4252 }
4253
4254 /* Pick up each field in turn. This used to be done with scanf, but
4255 scanf will make trouble if CORE_ADDR size doesn't match
4256 conversion directives correctly. The following code will work
4257 with any size of CORE_ADDR. */
4258 text_addr = data_addr = bss_addr = 0;
4259 ptr = buf;
4260 lose = 0;
4261
61012eef 4262 if (startswith (ptr, "Text="))
c906108c
SS
4263 {
4264 ptr += 5;
4265 /* Don't use strtol, could lose on big values. */
4266 while (*ptr && *ptr != ';')
4267 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 4268
61012eef 4269 if (startswith (ptr, ";Data="))
31d99776
DJ
4270 {
4271 ptr += 6;
4272 while (*ptr && *ptr != ';')
4273 data_addr = (data_addr << 4) + fromhex (*ptr++);
4274 }
4275 else
4276 lose = 1;
4277
61012eef 4278 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
4279 {
4280 ptr += 5;
4281 while (*ptr && *ptr != ';')
4282 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 4283
31d99776
DJ
4284 if (bss_addr != data_addr)
4285 warning (_("Target reported unsupported offsets: %s"), buf);
4286 }
4287 else
4288 lose = 1;
4289 }
61012eef 4290 else if (startswith (ptr, "TextSeg="))
c906108c 4291 {
31d99776
DJ
4292 ptr += 8;
4293 /* Don't use strtol, could lose on big values. */
c906108c 4294 while (*ptr && *ptr != ';')
31d99776
DJ
4295 text_addr = (text_addr << 4) + fromhex (*ptr++);
4296 num_segments = 1;
4297
61012eef 4298 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
4299 {
4300 ptr += 9;
4301 while (*ptr && *ptr != ';')
4302 data_addr = (data_addr << 4) + fromhex (*ptr++);
4303 num_segments++;
4304 }
c906108c
SS
4305 }
4306 else
4307 lose = 1;
4308
4309 if (lose)
8a3fe4f8 4310 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
4311 else if (*ptr != '\0')
4312 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 4313
a42d7dd8
TT
4314 objfile *objf = current_program_space->symfile_object_file;
4315 section_offsets offs = objf->section_offsets;
c906108c 4316
a42d7dd8 4317 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd);
31d99776
DJ
4318 do_segments = (data != NULL);
4319 do_sections = num_segments == 0;
c906108c 4320
28c32713 4321 if (num_segments > 0)
31d99776 4322 {
31d99776
DJ
4323 segments[0] = text_addr;
4324 segments[1] = data_addr;
4325 }
28c32713
JB
4326 /* If we have two segments, we can still try to relocate everything
4327 by assuming that the .text and .data offsets apply to the whole
4328 text and data segments. Convert the offsets given in the packet
4329 to base addresses for symfile_map_offsets_to_segments. */
68b888ff 4330 else if (data != nullptr && data->segments.size () == 2)
28c32713 4331 {
68b888ff
SM
4332 segments[0] = data->segments[0].base + text_addr;
4333 segments[1] = data->segments[1].base + data_addr;
28c32713
JB
4334 num_segments = 2;
4335 }
8d385431
DJ
4336 /* If the object file has only one segment, assume that it is text
4337 rather than data; main programs with no writable data are rare,
4338 but programs with no code are useless. Of course the code might
4339 have ended up in the data segment... to detect that we would need
4340 the permissions here. */
68b888ff 4341 else if (data && data->segments.size () == 1)
8d385431 4342 {
68b888ff 4343 segments[0] = data->segments[0].base + text_addr;
8d385431
DJ
4344 num_segments = 1;
4345 }
28c32713
JB
4346 /* There's no way to relocate by segment. */
4347 else
4348 do_segments = 0;
31d99776
DJ
4349
4350 if (do_segments)
4351 {
a42d7dd8 4352 int ret = symfile_map_offsets_to_segments (objf->obfd,
62982abd
SM
4353 data.get (), offs,
4354 num_segments, segments);
31d99776
DJ
4355
4356 if (ret == 0 && !do_sections)
3e43a32a
MS
4357 error (_("Can not handle qOffsets TextSeg "
4358 "response with this symbol file"));
31d99776
DJ
4359
4360 if (ret > 0)
4361 do_sections = 0;
4362 }
c906108c 4363
31d99776
DJ
4364 if (do_sections)
4365 {
a42d7dd8 4366 offs[SECT_OFF_TEXT (objf)] = text_addr;
31d99776 4367
3e43a32a
MS
4368 /* This is a temporary kludge to force data and bss to use the
4369 same offsets because that's what nlmconv does now. The real
4370 solution requires changes to the stub and remote.c that I
4371 don't have time to do right now. */
31d99776 4372
a42d7dd8
TT
4373 offs[SECT_OFF_DATA (objf)] = data_addr;
4374 offs[SECT_OFF_BSS (objf)] = data_addr;
31d99776 4375 }
c906108c 4376
a42d7dd8 4377 objfile_relocate (objf, offs);
c906108c
SS
4378}
4379
9a7071a8 4380/* Send interrupt_sequence to remote target. */
6b8edb51
PA
4381
4382void
4383remote_target::send_interrupt_sequence ()
9a7071a8 4384{
5d93a237
TT
4385 struct remote_state *rs = get_remote_state ();
4386
9a7071a8 4387 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 4388 remote_serial_write ("\x03", 1);
9a7071a8 4389 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 4390 serial_send_break (rs->remote_desc);
9a7071a8
JB
4391 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4392 {
5d93a237 4393 serial_send_break (rs->remote_desc);
c33e31fd 4394 remote_serial_write ("g", 1);
9a7071a8
JB
4395 }
4396 else
4397 internal_error (__FILE__, __LINE__,
4398 _("Invalid value for interrupt_sequence_mode: %s."),
4399 interrupt_sequence_mode);
4400}
4401
3405876a
PA
4402
4403/* If STOP_REPLY is a T stop reply, look for the "thread" register,
4404 and extract the PTID. Returns NULL_PTID if not found. */
4405
4406static ptid_t
e3b2741b 4407stop_reply_extract_thread (const char *stop_reply)
3405876a
PA
4408{
4409 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4410 {
256642e8 4411 const char *p;
3405876a
PA
4412
4413 /* Txx r:val ; r:val (...) */
4414 p = &stop_reply[3];
4415
4416 /* Look for "register" named "thread". */
4417 while (*p != '\0')
4418 {
256642e8 4419 const char *p1;
3405876a
PA
4420
4421 p1 = strchr (p, ':');
4422 if (p1 == NULL)
4423 return null_ptid;
4424
4425 if (strncmp (p, "thread", p1 - p) == 0)
4426 return read_ptid (++p1, &p);
4427
4428 p1 = strchr (p, ';');
4429 if (p1 == NULL)
4430 return null_ptid;
4431 p1++;
4432
4433 p = p1;
4434 }
4435 }
4436
4437 return null_ptid;
4438}
4439
b7ea362b
PA
4440/* Determine the remote side's current thread. If we have a stop
4441 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4442 "thread" register we can extract the current thread from. If not,
4443 ask the remote which is the current thread with qC. The former
4444 method avoids a roundtrip. */
4445
6b8edb51 4446ptid_t
e3b2741b 4447remote_target::get_current_thread (const char *wait_status)
b7ea362b 4448{
6a49a997 4449 ptid_t ptid = null_ptid;
b7ea362b
PA
4450
4451 /* Note we don't use remote_parse_stop_reply as that makes use of
4452 the target architecture, which we haven't yet fully determined at
4453 this point. */
4454 if (wait_status != NULL)
4455 ptid = stop_reply_extract_thread (wait_status);
d7e15655 4456 if (ptid == null_ptid)
b7ea362b
PA
4457 ptid = remote_current_thread (inferior_ptid);
4458
4459 return ptid;
4460}
4461
49c62f2e
PA
4462/* Query the remote target for which is the current thread/process,
4463 add it to our tables, and update INFERIOR_PTID. The caller is
4464 responsible for setting the state such that the remote end is ready
3405876a
PA
4465 to return the current thread.
4466
4467 This function is called after handling the '?' or 'vRun' packets,
4468 whose response is a stop reply from which we can also try
4469 extracting the thread. If the target doesn't support the explicit
4470 qC query, we infer the current thread from that stop reply, passed
64d38fdd 4471 in in WAIT_STATUS, which may be NULL.
49c62f2e 4472
64d38fdd
JM
4473 The function returns pointer to the main thread of the inferior. */
4474
4475thread_info *
e3b2741b 4476remote_target::add_current_inferior_and_thread (const char *wait_status)
49c62f2e
PA
4477{
4478 struct remote_state *rs = get_remote_state ();
9ab8741a 4479 bool fake_pid_p = false;
49c62f2e 4480
0ac55310 4481 switch_to_no_thread ();
49c62f2e 4482
0ac55310
PA
4483 /* Now, if we have thread information, update the current thread's
4484 ptid. */
87215ad1 4485 ptid_t curr_ptid = get_current_thread (wait_status);
3405876a 4486
87215ad1 4487 if (curr_ptid != null_ptid)
49c62f2e
PA
4488 {
4489 if (!remote_multi_process_p (rs))
9ab8741a 4490 fake_pid_p = true;
49c62f2e
PA
4491 }
4492 else
4493 {
4494 /* Without this, some commands which require an active target
4495 (such as kill) won't work. This variable serves (at least)
4496 double duty as both the pid of the target process (if it has
4497 such), and as a flag indicating that a target is active. */
87215ad1 4498 curr_ptid = magic_null_ptid;
9ab8741a 4499 fake_pid_p = true;
49c62f2e
PA
4500 }
4501
e99b03dc 4502 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
49c62f2e 4503
87215ad1
SDJ
4504 /* Add the main thread and switch to it. Don't try reading
4505 registers yet, since we haven't fetched the target description
4506 yet. */
5b6d1e4f 4507 thread_info *tp = add_thread_silent (this, curr_ptid);
87215ad1 4508 switch_to_thread_no_regs (tp);
64d38fdd
JM
4509
4510 return tp;
49c62f2e
PA
4511}
4512
6efcd9a8
PA
4513/* Print info about a thread that was found already stopped on
4514 connection. */
4515
1edb66d8
SM
4516void
4517remote_target::print_one_stopped_thread (thread_info *thread)
6efcd9a8 4518{
1edb66d8
SM
4519 target_waitstatus ws;
4520
4521 /* If there is a pending waitstatus, use it. If there isn't it's because
4522 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4523 and process_initial_stop_replies decided it wasn't interesting to save
4524 and report to the core. */
4525 if (thread->has_pending_waitstatus ())
4526 {
4527 ws = thread->pending_waitstatus ();
4528 thread->clear_pending_waitstatus ();
4529 }
4530 else
4531 {
183be222 4532 ws.set_stopped (GDB_SIGNAL_0);
1edb66d8 4533 }
6efcd9a8 4534
00431a78 4535 switch_to_thread (thread);
1edb66d8 4536 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
6efcd9a8
PA
4537 set_current_sal_from_frame (get_current_frame ());
4538
1edb66d8
SM
4539 /* For "info program". */
4540 set_last_target_status (this, thread->ptid, ws);
6efcd9a8 4541
183be222 4542 if (ws.kind () == TARGET_WAITKIND_STOPPED)
6efcd9a8 4543 {
183be222 4544 enum gdb_signal sig = ws.sig ();
6efcd9a8
PA
4545
4546 if (signal_print_state (sig))
76727919 4547 gdb::observers::signal_received.notify (sig);
6efcd9a8 4548 }
76727919 4549 gdb::observers::normal_stop.notify (NULL, 1);
6efcd9a8
PA
4550}
4551
221e1a37
PA
4552/* Process all initial stop replies the remote side sent in response
4553 to the ? packet. These indicate threads that were already stopped
4554 on initial connection. We mark these threads as stopped and print
4555 their current frame before giving the user the prompt. */
4556
6b8edb51
PA
4557void
4558remote_target::process_initial_stop_replies (int from_tty)
221e1a37
PA
4559{
4560 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
4561 struct thread_info *selected = NULL;
4562 struct thread_info *lowest_stopped = NULL;
4563 struct thread_info *first = NULL;
221e1a37 4564
1edb66d8
SM
4565 /* This is only used when the target is non-stop. */
4566 gdb_assert (target_is_non_stop_p ());
4567
221e1a37
PA
4568 /* Consume the initial pending events. */
4569 while (pending_stop_replies-- > 0)
4570 {
4571 ptid_t waiton_ptid = minus_one_ptid;
4572 ptid_t event_ptid;
4573 struct target_waitstatus ws;
4574 int ignore_event = 0;
4575
221e1a37
PA
4576 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4577 if (remote_debug)
c272a98c 4578 print_target_wait_results (waiton_ptid, event_ptid, ws);
221e1a37 4579
183be222 4580 switch (ws.kind ())
221e1a37
PA
4581 {
4582 case TARGET_WAITKIND_IGNORE:
4583 case TARGET_WAITKIND_NO_RESUMED:
4584 case TARGET_WAITKIND_SIGNALLED:
4585 case TARGET_WAITKIND_EXITED:
4586 /* We shouldn't see these, but if we do, just ignore. */
2189c312 4587 remote_debug_printf ("event ignored");
221e1a37
PA
4588 ignore_event = 1;
4589 break;
4590
221e1a37
PA
4591 default:
4592 break;
4593 }
4594
4595 if (ignore_event)
4596 continue;
4597
5b6d1e4f 4598 thread_info *evthread = find_thread_ptid (this, event_ptid);
221e1a37 4599
183be222 4600 if (ws.kind () == TARGET_WAITKIND_STOPPED)
221e1a37 4601 {
183be222 4602 enum gdb_signal sig = ws.sig ();
221e1a37
PA
4603
4604 /* Stubs traditionally report SIGTRAP as initial signal,
4605 instead of signal 0. Suppress it. */
4606 if (sig == GDB_SIGNAL_TRAP)
4607 sig = GDB_SIGNAL_0;
1edb66d8 4608 evthread->set_stop_signal (sig);
183be222 4609 ws.set_stopped (sig);
6efcd9a8 4610 }
221e1a37 4611
183be222
SM
4612 if (ws.kind () != TARGET_WAITKIND_STOPPED
4613 || ws.sig () != GDB_SIGNAL_0)
1edb66d8 4614 evthread->set_pending_waitstatus (ws);
6efcd9a8 4615
719546c4
SM
4616 set_executing (this, event_ptid, false);
4617 set_running (this, event_ptid, false);
c9d22089 4618 get_remote_thread_info (evthread)->set_not_resumed ();
6efcd9a8
PA
4619 }
4620
4621 /* "Notice" the new inferiors before anything related to
4622 registers/memory. */
5b6d1e4f 4623 for (inferior *inf : all_non_exited_inferiors (this))
6efcd9a8 4624 {
6efcd9a8
PA
4625 inf->needs_setup = 1;
4626
4627 if (non_stop)
4628 {
08036331 4629 thread_info *thread = any_live_thread_of_inferior (inf);
00431a78 4630 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
6efcd9a8
PA
4631 from_tty);
4632 }
4633 }
4634
4635 /* If all-stop on top of non-stop, pause all threads. Note this
4636 records the threads' stop pc, so must be done after "noticing"
4637 the inferiors. */
4638 if (!non_stop)
4639 {
abe8cab7
SM
4640 {
4641 /* At this point, the remote target is not async. It needs to be for
4642 the poll in stop_all_threads to consider events from it, so enable
4643 it temporarily. */
4644 gdb_assert (!this->is_async_p ());
4645 SCOPE_EXIT { target_async (0); };
4646 target_async (1);
4f5539f0 4647 stop_all_threads ("remote connect in all-stop");
abe8cab7 4648 }
6efcd9a8
PA
4649
4650 /* If all threads of an inferior were already stopped, we
4651 haven't setup the inferior yet. */
5b6d1e4f 4652 for (inferior *inf : all_non_exited_inferiors (this))
6efcd9a8 4653 {
6efcd9a8
PA
4654 if (inf->needs_setup)
4655 {
08036331 4656 thread_info *thread = any_live_thread_of_inferior (inf);
6efcd9a8
PA
4657 switch_to_thread_no_regs (thread);
4658 setup_inferior (0);
4659 }
4660 }
221e1a37 4661 }
6efcd9a8
PA
4662
4663 /* Now go over all threads that are stopped, and print their current
4664 frame. If all-stop, then if there's a signalled thread, pick
4665 that as current. */
5b6d1e4f 4666 for (thread_info *thread : all_non_exited_threads (this))
6efcd9a8 4667 {
6efcd9a8
PA
4668 if (first == NULL)
4669 first = thread;
4670
4671 if (!non_stop)
00431a78 4672 thread->set_running (false);
6efcd9a8
PA
4673 else if (thread->state != THREAD_STOPPED)
4674 continue;
4675
1edb66d8 4676 if (selected == nullptr && thread->has_pending_waitstatus ())
6efcd9a8
PA
4677 selected = thread;
4678
5d5658a1
PA
4679 if (lowest_stopped == NULL
4680 || thread->inf->num < lowest_stopped->inf->num
4681 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
4682 lowest_stopped = thread;
4683
4684 if (non_stop)
4685 print_one_stopped_thread (thread);
4686 }
4687
4688 /* In all-stop, we only print the status of one thread, and leave
4689 others with their status pending. */
4690 if (!non_stop)
4691 {
08036331 4692 thread_info *thread = selected;
6efcd9a8
PA
4693 if (thread == NULL)
4694 thread = lowest_stopped;
4695 if (thread == NULL)
4696 thread = first;
4697
4698 print_one_stopped_thread (thread);
4699 }
221e1a37
PA
4700}
4701
7a34f66b
AB
4702/* Mark a remote_target as marking (by setting the starting_up flag within
4703 its remote_state) for the lifetime of this object. The reference count
4704 on the remote target is temporarily incremented, to prevent the target
4705 being deleted under our feet. */
4706
4707struct scoped_mark_target_starting
4708{
4709 /* Constructor, TARGET is the target to be marked as starting, its
4710 reference count will be incremented. */
4711 scoped_mark_target_starting (remote_target *target)
4712 : m_remote_target (target)
4713 {
4714 m_remote_target->incref ();
4715 remote_state *rs = m_remote_target->get_remote_state ();
4716 rs->starting_up = true;
4717 }
4718
4719 /* Destructor, mark the target being worked on as no longer starting, and
4720 decrement the reference count. */
4721 ~scoped_mark_target_starting ()
4722 {
4723 remote_state *rs = m_remote_target->get_remote_state ();
4724 rs->starting_up = false;
4725 decref_target (m_remote_target);
4726 }
4727
4728private:
4729
4730 /* The target on which we are operating. */
4731 remote_target *m_remote_target;
4732};
4733
288712bb
AB
4734/* Helper for remote_target::start_remote, start the remote connection and
4735 sync state. Return true if everything goes OK, otherwise, return false.
4736 This function exists so that the scoped_restore created within it will
4737 expire before we return to remote_target::start_remote. */
048094ac 4738
288712bb
AB
4739bool
4740remote_target::start_remote_1 (int from_tty, int extended_p)
c906108c 4741{
2189c312
SM
4742 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4743
c8d104ad
PA
4744 struct remote_state *rs = get_remote_state ();
4745 struct packet_config *noack_config;
8621d6a9 4746
048094ac
PA
4747 /* Signal other parts that we're going through the initial setup,
4748 and so things may not be stable yet. E.g., we don't try to
4749 install tracepoints until we've relocated symbols. Also, a
4750 Ctrl-C before we're connected and synced up can't interrupt the
4751 target. Instead, it offers to drop the (potentially wedged)
4752 connection. */
7a34f66b 4753 scoped_mark_target_starting target_is_starting (this);
048094ac 4754
522002f9 4755 QUIT;
c906108c 4756
9a7071a8
JB
4757 if (interrupt_on_connect)
4758 send_interrupt_sequence ();
4759
57e12211 4760 /* Ack any packet which the remote side has already sent. */
048094ac 4761 remote_serial_write ("+", 1);
1e51243a 4762
c8d104ad
PA
4763 /* The first packet we send to the target is the optional "supported
4764 packets" request. If the target can answer this, it will tell us
4765 which later probes to skip. */
4766 remote_query_supported ();
4767
d914c394 4768 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 4769 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
f6ac5f3d 4770 set_permissions ();
d914c394 4771
57809e5e
JK
4772 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4773 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4774 as a reply to known packet. For packet "vFile:setfs:" it is an
4775 invalid reply and GDB would return error in
4776 remote_hostio_set_filesystem, making remote files access impossible.
4777 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4778 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4779 {
4780 const char v_mustreplyempty[] = "vMustReplyEmpty";
4781
4782 putpkt (v_mustreplyempty);
8d64371b
TT
4783 getpkt (&rs->buf, 0);
4784 if (strcmp (rs->buf.data (), "OK") == 0)
57809e5e 4785 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
8d64371b 4786 else if (strcmp (rs->buf.data (), "") != 0)
57809e5e 4787 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
8d64371b 4788 rs->buf.data ());
57809e5e
JK
4789 }
4790
c8d104ad
PA
4791 /* Next, we possibly activate noack mode.
4792
4793 If the QStartNoAckMode packet configuration is set to AUTO,
4794 enable noack mode if the stub reported a wish for it with
4795 qSupported.
4796
4797 If set to TRUE, then enable noack mode even if the stub didn't
4798 report it in qSupported. If the stub doesn't reply OK, the
4799 session ends with an error.
4800
4801 If FALSE, then don't activate noack mode, regardless of what the
4802 stub claimed should be the default with qSupported. */
4803
4804 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 4805 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
4806 {
4807 putpkt ("QStartNoAckMode");
8d64371b 4808 getpkt (&rs->buf, 0);
c8d104ad
PA
4809 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4810 rs->noack_mode = 1;
4811 }
4812
04bd08de 4813 if (extended_p)
5fe04517
PA
4814 {
4815 /* Tell the remote that we are using the extended protocol. */
4816 putpkt ("!");
8d64371b 4817 getpkt (&rs->buf, 0);
5fe04517
PA
4818 }
4819
9b224c5e
PA
4820 /* Let the target know which signals it is allowed to pass down to
4821 the program. */
4822 update_signals_program_target ();
4823
d962ef82
DJ
4824 /* Next, if the target can specify a description, read it. We do
4825 this before anything involving memory or registers. */
4826 target_find_description ();
4827
6c95b8df
PA
4828 /* Next, now that we know something about the target, update the
4829 address spaces in the program spaces. */
4830 update_address_spaces ();
4831
50c71eaf
PA
4832 /* On OSs where the list of libraries is global to all
4833 processes, we fetch them early. */
f5656ead 4834 if (gdbarch_has_global_solist (target_gdbarch ()))
e696b3ad 4835 solib_add (NULL, from_tty, auto_solib_add);
50c71eaf 4836
6efcd9a8 4837 if (target_is_non_stop_p ())
74531fed 4838 {
4082afcc 4839 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
4840 error (_("Non-stop mode requested, but remote "
4841 "does not support non-stop"));
74531fed
PA
4842
4843 putpkt ("QNonStop:1");
8d64371b 4844 getpkt (&rs->buf, 0);
74531fed 4845
8d64371b
TT
4846 if (strcmp (rs->buf.data (), "OK") != 0)
4847 error (_("Remote refused setting non-stop mode with: %s"),
4848 rs->buf.data ());
74531fed
PA
4849
4850 /* Find about threads and processes the stub is already
4851 controlling. We default to adding them in the running state.
4852 The '?' query below will then tell us about which threads are
4853 stopped. */
f6ac5f3d 4854 this->update_thread_list ();
74531fed 4855 }
4082afcc 4856 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4857 {
4858 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4859 Request it explicitly. */
74531fed 4860 putpkt ("QNonStop:0");
8d64371b 4861 getpkt (&rs->buf, 0);
74531fed 4862
8d64371b
TT
4863 if (strcmp (rs->buf.data (), "OK") != 0)
4864 error (_("Remote refused setting all-stop mode with: %s"),
4865 rs->buf.data ());
74531fed
PA
4866 }
4867
a0743c90
YQ
4868 /* Upload TSVs regardless of whether the target is running or not. The
4869 remote stub, such as GDBserver, may have some predefined or builtin
4870 TSVs, even if the target is not running. */
f6ac5f3d 4871 if (get_trace_status (current_trace_status ()) != -1)
a0743c90
YQ
4872 {
4873 struct uploaded_tsv *uploaded_tsvs = NULL;
4874
f6ac5f3d 4875 upload_trace_state_variables (&uploaded_tsvs);
a0743c90
YQ
4876 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4877 }
4878
2d717e4f
DJ
4879 /* Check whether the target is running now. */
4880 putpkt ("?");
8d64371b 4881 getpkt (&rs->buf, 0);
2d717e4f 4882
6efcd9a8 4883 if (!target_is_non_stop_p ())
2d717e4f 4884 {
b5c8f22d
SM
4885 char *wait_status = NULL;
4886
74531fed 4887 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4888 {
04bd08de 4889 if (!extended_p)
74531fed 4890 error (_("The target is not running (try extended-remote?)"));
288712bb 4891 return false;
2d717e4f
DJ
4892 }
4893 else
74531fed 4894 {
74531fed 4895 /* Save the reply for later. */
8d64371b
TT
4896 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
4897 strcpy (wait_status, rs->buf.data ());
74531fed
PA
4898 }
4899
b7ea362b 4900 /* Fetch thread list. */
e8032dde 4901 target_update_thread_list ();
b7ea362b 4902
74531fed
PA
4903 /* Let the stub know that we want it to return the thread. */
4904 set_continue_thread (minus_one_ptid);
4905
5b6d1e4f 4906 if (thread_count (this) == 0)
b7ea362b
PA
4907 {
4908 /* Target has no concept of threads at all. GDB treats
4909 non-threaded target as single-threaded; add a main
4910 thread. */
64d38fdd
JM
4911 thread_info *tp = add_current_inferior_and_thread (wait_status);
4912 get_remote_thread_info (tp)->set_resumed ();
b7ea362b
PA
4913 }
4914 else
4915 {
4916 /* We have thread information; select the thread the target
4917 says should be current. If we're reconnecting to a
4918 multi-threaded program, this will ideally be the thread
4919 that last reported an event before GDB disconnected. */
75c6c844
PA
4920 ptid_t curr_thread = get_current_thread (wait_status);
4921 if (curr_thread == null_ptid)
b7ea362b
PA
4922 {
4923 /* Odd... The target was able to list threads, but not
4924 tell us which thread was current (no "thread"
4925 register in T stop reply?). Just pick the first
4926 thread in the thread list then. */
2189c312
SM
4927
4928 remote_debug_printf ("warning: couldn't determine remote "
4929 "current thread; picking first in list.");
c9f35b34 4930
5b6d1e4f
PA
4931 for (thread_info *tp : all_non_exited_threads (this,
4932 minus_one_ptid))
75c6c844
PA
4933 {
4934 switch_to_thread (tp);
4935 break;
4936 }
b7ea362b 4937 }
75c6c844 4938 else
5b6d1e4f 4939 switch_to_thread (find_thread_ptid (this, curr_thread));
b7ea362b 4940 }
74531fed 4941
6e586cc5
YQ
4942 /* init_wait_for_inferior should be called before get_offsets in order
4943 to manage `inserted' flag in bp loc in a correct state.
4944 breakpoint_init_inferior, called from init_wait_for_inferior, set
4945 `inserted' flag to 0, while before breakpoint_re_set, called from
4946 start_remote, set `inserted' flag to 1. In the initialization of
4947 inferior, breakpoint_init_inferior should be called first, and then
4948 breakpoint_re_set can be called. If this order is broken, state of
4949 `inserted' flag is wrong, and cause some problems on breakpoint
4950 manipulation. */
4951 init_wait_for_inferior ();
4952
74531fed
PA
4953 get_offsets (); /* Get text, data & bss offsets. */
4954
d962ef82
DJ
4955 /* If we could not find a description using qXfer, and we know
4956 how to do it some other way, try again. This is not
4957 supported for non-stop; it could be, but it is tricky if
4958 there are no stopped threads when we connect. */
f6ac5f3d 4959 if (remote_read_description_p (this)
f5656ead 4960 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4961 {
4962 target_clear_description ();
4963 target_find_description ();
4964 }
4965
74531fed
PA
4966 /* Use the previously fetched status. */
4967 gdb_assert (wait_status != NULL);
4f626cad
AB
4968 struct notif_event *reply
4969 = remote_notif_parse (this, &notif_client_stop, wait_status);
4970 push_stop_reply ((struct stop_reply *) reply);
74531fed 4971
f6ac5f3d 4972 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4973 }
4974 else
4975 {
68c97600
PA
4976 /* Clear WFI global state. Do this before finding about new
4977 threads and inferiors, and setting the current inferior.
4978 Otherwise we would clear the proceed status of the current
4979 inferior when we want its stop_soon state to be preserved
4980 (see notice_new_inferior). */
4981 init_wait_for_inferior ();
4982
74531fed
PA
4983 /* In non-stop, we will either get an "OK", meaning that there
4984 are no stopped threads at this time; or, a regular stop
4985 reply. In the latter case, there may be more than one thread
4986 stopped --- we pull them all out using the vStopped
4987 mechanism. */
8d64371b 4988 if (strcmp (rs->buf.data (), "OK") != 0)
74531fed 4989 {
722247f1 4990 struct notif_client *notif = &notif_client_stop;
2d717e4f 4991
722247f1
YQ
4992 /* remote_notif_get_pending_replies acks this one, and gets
4993 the rest out. */
f48ff2a7 4994 rs->notif_state->pending_event[notif_client_stop.id]
8d64371b 4995 = remote_notif_parse (this, notif, rs->buf.data ());
722247f1 4996 remote_notif_get_pending_events (notif);
74531fed 4997 }
2d717e4f 4998
5b6d1e4f 4999 if (thread_count (this) == 0)
74531fed 5000 {
04bd08de 5001 if (!extended_p)
74531fed 5002 error (_("The target is not running (try extended-remote?)"));
288712bb 5003 return false;
c35b1492 5004 }
74531fed 5005
2455069d 5006 /* Report all signals during attach/startup. */
adc6a863 5007 pass_signals ({});
221e1a37
PA
5008
5009 /* If there are already stopped threads, mark them stopped and
5010 report their stops before giving the prompt to the user. */
6efcd9a8 5011 process_initial_stop_replies (from_tty);
221e1a37
PA
5012
5013 if (target_can_async_p ())
5014 target_async (1);
74531fed 5015 }
c8d104ad 5016
c8d104ad 5017 /* If we connected to a live target, do some additional setup. */
55f6301a 5018 if (target_has_execution ())
c8d104ad 5019 {
a42d7dd8
TT
5020 /* No use without a symbol-file. */
5021 if (current_program_space->symfile_object_file)
36d25514 5022 remote_check_symbols ();
c8d104ad 5023 }
50c71eaf 5024
d5551862
SS
5025 /* Possibly the target has been engaged in a trace run started
5026 previously; find out where things are at. */
f6ac5f3d 5027 if (get_trace_status (current_trace_status ()) != -1)
d5551862 5028 {
00bf0b85 5029 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 5030
00bf0b85 5031 if (current_trace_status ()->running)
6cb06a8c 5032 gdb_printf (_("Trace is already running on the target.\n"));
00bf0b85 5033
f6ac5f3d 5034 upload_tracepoints (&uploaded_tps);
00bf0b85
SS
5035
5036 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
5037 }
5038
c0272db5
TW
5039 /* Possibly the target has been engaged in a btrace record started
5040 previously; find out where things are at. */
5041 remote_btrace_maybe_reopen ();
5042
288712bb
AB
5043 return true;
5044}
5045
5046/* Start the remote connection and sync state. */
1e51243a 5047
288712bb
AB
5048void
5049remote_target::start_remote (int from_tty, int extended_p)
5050{
5051 if (start_remote_1 (from_tty, extended_p)
5052 && breakpoints_should_be_inserted_now ())
50c71eaf 5053 insert_breakpoints ();
c906108c
SS
5054}
5055
121b3efd
PA
5056const char *
5057remote_target::connection_string ()
5058{
5059 remote_state *rs = get_remote_state ();
5060
5061 if (rs->remote_desc->name != NULL)
5062 return rs->remote_desc->name;
5063 else
5064 return NULL;
5065}
5066
c906108c
SS
5067/* Open a connection to a remote debugger.
5068 NAME is the filename used for communication. */
5069
f6ac5f3d
PA
5070void
5071remote_target::open (const char *name, int from_tty)
c906108c 5072{
f6ac5f3d 5073 open_1 (name, from_tty, 0);
43ff13b4
JM
5074}
5075
c906108c
SS
5076/* Open a connection to a remote debugger using the extended
5077 remote gdb protocol. NAME is the filename used for communication. */
5078
f6ac5f3d
PA
5079void
5080extended_remote_target::open (const char *name, int from_tty)
c906108c 5081{
f6ac5f3d 5082 open_1 (name, from_tty, 1 /*extended_p */);
43ff13b4
JM
5083}
5084
ca4f7f8b
PA
5085/* Reset all packets back to "unknown support". Called when opening a
5086 new connection to a remote target. */
c906108c 5087
d471ea57 5088static void
ca4f7f8b 5089reset_all_packet_configs_support (void)
d471ea57
AC
5090{
5091 int i;
a744cf53 5092
444abaca 5093 for (i = 0; i < PACKET_MAX; i++)
4082afcc 5094 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
5095}
5096
ca4f7f8b
PA
5097/* Initialize all packet configs. */
5098
5099static void
5100init_all_packet_configs (void)
5101{
5102 int i;
5103
5104 for (i = 0; i < PACKET_MAX; i++)
5105 {
5106 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5107 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5108 }
5109}
5110
23860348 5111/* Symbol look-up. */
dc8acb97 5112
6b8edb51
PA
5113void
5114remote_target::remote_check_symbols ()
dc8acb97 5115{
8d64371b 5116 char *tmp;
dc8acb97
MS
5117 int end;
5118
63154eca
PA
5119 /* The remote side has no concept of inferiors that aren't running
5120 yet, it only knows about running processes. If we're connected
5121 but our current inferior is not running, we should not invite the
5122 remote target to request symbol lookups related to its
5123 (unrelated) current process. */
55f6301a 5124 if (!target_has_execution ())
63154eca
PA
5125 return;
5126
4082afcc 5127 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
5128 return;
5129
63154eca
PA
5130 /* Make sure the remote is pointing at the right process. Note
5131 there's no way to select "no process". */
3c9c4b83
PA
5132 set_general_process ();
5133
6d820c5c
DJ
5134 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5135 because we need both at the same time. */
66644cd3 5136 gdb::char_vector msg (get_remote_packet_size ());
8d64371b 5137 gdb::char_vector reply (get_remote_packet_size ());
6d820c5c 5138
23860348 5139 /* Invite target to request symbol lookups. */
dc8acb97
MS
5140
5141 putpkt ("qSymbol::");
8d64371b 5142 getpkt (&reply, 0);
28170b88 5143 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
dc8acb97 5144
8d64371b 5145 while (startswith (reply.data (), "qSymbol:"))
dc8acb97 5146 {
77e371c0
TT
5147 struct bound_minimal_symbol sym;
5148
dc8acb97 5149 tmp = &reply[8];
66644cd3
AB
5150 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5151 strlen (tmp) / 2);
dc8acb97 5152 msg[end] = '\0';
66644cd3 5153 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
3b7344d5 5154 if (sym.minsym == NULL)
66644cd3
AB
5155 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5156 &reply[8]);
dc8acb97 5157 else
2bbe3cc1 5158 {
f5656ead 5159 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4aeddc50 5160 CORE_ADDR sym_addr = sym.value_address ();
2bbe3cc1
DJ
5161
5162 /* If this is a function address, return the start of code
5163 instead of any data function descriptor. */
328d42d8
SM
5164 sym_addr = gdbarch_convert_from_func_ptr_addr
5165 (target_gdbarch (), sym_addr, current_inferior ()->top_target ());
2bbe3cc1 5166
66644cd3 5167 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 5168 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1 5169 }
66644cd3
AB
5170
5171 putpkt (msg.data ());
8d64371b 5172 getpkt (&reply, 0);
dc8acb97
MS
5173 }
5174}
5175
9db8d71f 5176static struct serial *
baa336ce 5177remote_serial_open (const char *name)
9db8d71f
DJ
5178{
5179 static int udp_warning = 0;
5180
5181 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5182 of in ser-tcp.c, because it is the remote protocol assuming that the
5183 serial connection is reliable and not the serial connection promising
5184 to be. */
61012eef 5185 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 5186 {
3e43a32a
MS
5187 warning (_("The remote protocol may be unreliable over UDP.\n"
5188 "Some events may be lost, rendering further debugging "
5189 "impossible."));
9db8d71f
DJ
5190 udp_warning = 1;
5191 }
5192
5193 return serial_open (name);
5194}
5195
d914c394
SS
5196/* Inform the target of our permission settings. The permission flags
5197 work without this, but if the target knows the settings, it can do
5198 a couple things. First, it can add its own check, to catch cases
5199 that somehow manage to get by the permissions checks in target
5200 methods. Second, if the target is wired to disallow particular
5201 settings (for instance, a system in the field that is not set up to
5202 be able to stop at a breakpoint), it can object to any unavailable
5203 permissions. */
5204
5205void
f6ac5f3d 5206remote_target::set_permissions ()
d914c394
SS
5207{
5208 struct remote_state *rs = get_remote_state ();
5209
8d64371b 5210 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
bba74b36
YQ
5211 "WriteReg:%x;WriteMem:%x;"
5212 "InsertBreak:%x;InsertTrace:%x;"
5213 "InsertFastTrace:%x;Stop:%x",
5214 may_write_registers, may_write_memory,
5215 may_insert_breakpoints, may_insert_tracepoints,
5216 may_insert_fast_tracepoints, may_stop);
d914c394 5217 putpkt (rs->buf);
8d64371b 5218 getpkt (&rs->buf, 0);
d914c394
SS
5219
5220 /* If the target didn't like the packet, warn the user. Do not try
5221 to undo the user's settings, that would just be maddening. */
8d64371b
TT
5222 if (strcmp (rs->buf.data (), "OK") != 0)
5223 warning (_("Remote refused setting permissions with: %s"),
5224 rs->buf.data ());
d914c394
SS
5225}
5226
be2a5f71
DJ
5227/* This type describes each known response to the qSupported
5228 packet. */
5229struct protocol_feature
5230{
5231 /* The name of this protocol feature. */
5232 const char *name;
5233
5234 /* The default for this protocol feature. */
5235 enum packet_support default_support;
5236
5237 /* The function to call when this feature is reported, or after
5238 qSupported processing if the feature is not supported.
5239 The first argument points to this structure. The second
5240 argument indicates whether the packet requested support be
5241 enabled, disabled, or probed (or the default, if this function
5242 is being called at the end of processing and this feature was
5243 not reported). The third argument may be NULL; if not NULL, it
5244 is a NUL-terminated string taken from the packet following
5245 this feature's name and an equals sign. */
6b8edb51
PA
5246 void (*func) (remote_target *remote, const struct protocol_feature *,
5247 enum packet_support, const char *);
be2a5f71
DJ
5248
5249 /* The corresponding packet for this feature. Only used if
5250 FUNC is remote_supported_packet. */
5251 int packet;
5252};
5253
be2a5f71 5254static void
6b8edb51
PA
5255remote_supported_packet (remote_target *remote,
5256 const struct protocol_feature *feature,
be2a5f71
DJ
5257 enum packet_support support,
5258 const char *argument)
5259{
5260 if (argument)
5261 {
5262 warning (_("Remote qSupported response supplied an unexpected value for"
5263 " \"%s\"."), feature->name);
5264 return;
5265 }
5266
4082afcc 5267 remote_protocol_packets[feature->packet].support = support;
be2a5f71 5268}
be2a5f71 5269
6b8edb51
PA
5270void
5271remote_target::remote_packet_size (const protocol_feature *feature,
5272 enum packet_support support, const char *value)
be2a5f71
DJ
5273{
5274 struct remote_state *rs = get_remote_state ();
5275
5276 int packet_size;
5277 char *value_end;
5278
5279 if (support != PACKET_ENABLE)
5280 return;
5281
5282 if (value == NULL || *value == '\0')
5283 {
5284 warning (_("Remote target reported \"%s\" without a size."),
5285 feature->name);
5286 return;
5287 }
5288
5289 errno = 0;
5290 packet_size = strtol (value, &value_end, 16);
5291 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5292 {
5293 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5294 feature->name, value);
5295 return;
5296 }
5297
be2a5f71
DJ
5298 /* Record the new maximum packet size. */
5299 rs->explicit_packet_size = packet_size;
5300}
5301
cb8c24b6 5302static void
6b8edb51
PA
5303remote_packet_size (remote_target *remote, const protocol_feature *feature,
5304 enum packet_support support, const char *value)
5305{
5306 remote->remote_packet_size (feature, support, value);
5307}
5308
dc473cfb 5309static const struct protocol_feature remote_protocol_features[] = {
0876f84a 5310 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 5311 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 5312 PACKET_qXfer_auxv },
c78fa86a
GB
5313 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5314 PACKET_qXfer_exec_file },
23181151
DJ
5315 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5316 PACKET_qXfer_features },
cfa9d6d9
DJ
5317 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5318 PACKET_qXfer_libraries },
2268b414
JK
5319 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5320 PACKET_qXfer_libraries_svr4 },
ced63ec0 5321 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 5322 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 5323 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 5324 PACKET_qXfer_memory_map },
07e059b5
VP
5325 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5326 PACKET_qXfer_osdata },
dc146f7c
VP
5327 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5328 PACKET_qXfer_threads },
b3b9301e
PA
5329 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5330 PACKET_qXfer_traceframe_info },
89be2091
DJ
5331 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5332 PACKET_QPassSignals },
82075af2
JS
5333 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5334 PACKET_QCatchSyscalls },
9b224c5e
PA
5335 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5336 PACKET_QProgramSignals },
bc3b087d
SDJ
5337 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5338 PACKET_QSetWorkingDir },
aefd8b33
SDJ
5339 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5340 PACKET_QStartupWithShell },
0a2dde4a
SDJ
5341 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5342 PACKET_QEnvironmentHexEncoded },
5343 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5344 PACKET_QEnvironmentReset },
5345 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5346 PACKET_QEnvironmentUnset },
a6f3e723
SL
5347 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5348 PACKET_QStartNoAckMode },
4082afcc
PA
5349 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5350 PACKET_multiprocess_feature },
5351 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
5352 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5353 PACKET_qXfer_siginfo_read },
5354 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5355 PACKET_qXfer_siginfo_write },
4082afcc 5356 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 5357 PACKET_ConditionalTracepoints },
4082afcc 5358 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 5359 PACKET_ConditionalBreakpoints },
4082afcc 5360 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 5361 PACKET_BreakpointCommands },
4082afcc 5362 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 5363 PACKET_FastTracepoints },
4082afcc 5364 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 5365 PACKET_StaticTracepoints },
4082afcc 5366 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 5367 PACKET_InstallInTrace},
4082afcc
PA
5368 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5369 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
5370 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5371 PACKET_bc },
5372 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5373 PACKET_bs },
409873ef
SS
5374 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5375 PACKET_TracepointSource },
d914c394
SS
5376 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5377 PACKET_QAllow },
4082afcc
PA
5378 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5379 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
5380 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5381 PACKET_qXfer_fdpic },
169081d0
TG
5382 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5383 PACKET_qXfer_uib },
03583c20
UW
5384 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5385 PACKET_QDisableRandomization },
d1feda86 5386 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
5387 { "QTBuffer:size", PACKET_DISABLE,
5388 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 5389 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
5390 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5391 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 5392 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 5393 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
5394 PACKET_qXfer_btrace },
5395 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
5396 PACKET_qXfer_btrace_conf },
5397 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
5398 PACKET_Qbtrace_conf_bts_size },
5399 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 5400 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
5401 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5402 PACKET_fork_event_feature },
5403 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5404 PACKET_vfork_event_feature },
94585166
DB
5405 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5406 PACKET_exec_event_feature },
b20a6524 5407 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 5408 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
5409 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5410 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 5411 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
2c2e7f87
LM
5412 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5413 PACKET_memory_tagging_feature },
be2a5f71
DJ
5414};
5415
c8d5aac9
L
5416static char *remote_support_xml;
5417
5418/* Register string appended to "xmlRegisters=" in qSupported query. */
5419
5420void
6e39997a 5421register_remote_support_xml (const char *xml)
c8d5aac9
L
5422{
5423#if defined(HAVE_LIBEXPAT)
5424 if (remote_support_xml == NULL)
c4f7c687 5425 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
5426 else
5427 {
5428 char *copy = xstrdup (remote_support_xml + 13);
ca3a04f6
CB
5429 char *saveptr;
5430 char *p = strtok_r (copy, ",", &saveptr);
c8d5aac9
L
5431
5432 do
5433 {
5434 if (strcmp (p, xml) == 0)
5435 {
5436 /* already there */
5437 xfree (copy);
5438 return;
5439 }
5440 }
ca3a04f6 5441 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
c8d5aac9
L
5442 xfree (copy);
5443
94b0dee1
PA
5444 remote_support_xml = reconcat (remote_support_xml,
5445 remote_support_xml, ",", xml,
5446 (char *) NULL);
c8d5aac9
L
5447 }
5448#endif
5449}
5450
69b6ecb0
TT
5451static void
5452remote_query_supported_append (std::string *msg, const char *append)
c8d5aac9 5453{
69b6ecb0
TT
5454 if (!msg->empty ())
5455 msg->append (";");
5456 msg->append (append);
c8d5aac9
L
5457}
5458
6b8edb51
PA
5459void
5460remote_target::remote_query_supported ()
be2a5f71
DJ
5461{
5462 struct remote_state *rs = get_remote_state ();
5463 char *next;
5464 int i;
5465 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5466
5467 /* The packet support flags are handled differently for this packet
5468 than for most others. We treat an error, a disabled packet, and
5469 an empty response identically: any features which must be reported
5470 to be used will be automatically disabled. An empty buffer
5471 accomplishes this, since that is also the representation for a list
5472 containing no features. */
5473
5474 rs->buf[0] = 0;
4082afcc 5475 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 5476 {
69b6ecb0 5477 std::string q;
c8d5aac9 5478
73b8c1fd 5479 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5480 remote_query_supported_append (&q, "multiprocess+");
c8d5aac9 5481
f7e6eed5 5482 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5483 remote_query_supported_append (&q, "swbreak+");
f7e6eed5 5484 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5485 remote_query_supported_append (&q, "hwbreak+");
f7e6eed5 5486
69b6ecb0 5487 remote_query_supported_append (&q, "qRelocInsn+");
dde08ee1 5488
8020350c
DB
5489 if (packet_set_cmd_state (PACKET_fork_event_feature)
5490 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5491 remote_query_supported_append (&q, "fork-events+");
8020350c
DB
5492 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5493 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5494 remote_query_supported_append (&q, "vfork-events+");
8020350c
DB
5495 if (packet_set_cmd_state (PACKET_exec_event_feature)
5496 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5497 remote_query_supported_append (&q, "exec-events+");
89245bc0 5498
750ce8d1 5499 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5500 remote_query_supported_append (&q, "vContSupported+");
750ce8d1 5501
65706a29 5502 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5503 remote_query_supported_append (&q, "QThreadEvents+");
65706a29 5504
f2faf941 5505 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5506 remote_query_supported_append (&q, "no-resumed+");
f2faf941 5507
2c2e7f87
LM
5508 if (packet_set_cmd_state (PACKET_memory_tagging_feature)
5509 != AUTO_BOOLEAN_FALSE)
5510 remote_query_supported_append (&q, "memory-tagging+");
5511
b35d5edb
PA
5512 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5513 the qSupported:xmlRegisters=i386 handling. */
7cc244de
PA
5514 if (remote_support_xml != NULL
5515 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
69b6ecb0 5516 remote_query_supported_append (&q, remote_support_xml);
82f73884 5517
69b6ecb0
TT
5518 q = "qSupported:" + q;
5519 putpkt (q.c_str ());
94b0dee1 5520
8d64371b 5521 getpkt (&rs->buf, 0);
be2a5f71
DJ
5522
5523 /* If an error occured, warn, but do not return - just reset the
5524 buffer to empty and go on to disable features. */
5525 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5526 == PACKET_ERROR)
5527 {
8d64371b 5528 warning (_("Remote failure reply: %s"), rs->buf.data ());
be2a5f71
DJ
5529 rs->buf[0] = 0;
5530 }
5531 }
5532
5533 memset (seen, 0, sizeof (seen));
5534
8d64371b 5535 next = rs->buf.data ();
be2a5f71
DJ
5536 while (*next)
5537 {
5538 enum packet_support is_supported;
5539 char *p, *end, *name_end, *value;
5540
5541 /* First separate out this item from the rest of the packet. If
5542 there's another item after this, we overwrite the separator
5543 (terminated strings are much easier to work with). */
5544 p = next;
5545 end = strchr (p, ';');
5546 if (end == NULL)
5547 {
5548 end = p + strlen (p);
5549 next = end;
5550 }
5551 else
5552 {
89be2091
DJ
5553 *end = '\0';
5554 next = end + 1;
5555
be2a5f71
DJ
5556 if (end == p)
5557 {
5558 warning (_("empty item in \"qSupported\" response"));
5559 continue;
5560 }
be2a5f71
DJ
5561 }
5562
5563 name_end = strchr (p, '=');
5564 if (name_end)
5565 {
5566 /* This is a name=value entry. */
5567 is_supported = PACKET_ENABLE;
5568 value = name_end + 1;
5569 *name_end = '\0';
5570 }
5571 else
5572 {
5573 value = NULL;
5574 switch (end[-1])
5575 {
5576 case '+':
5577 is_supported = PACKET_ENABLE;
5578 break;
5579
5580 case '-':
5581 is_supported = PACKET_DISABLE;
5582 break;
5583
5584 case '?':
5585 is_supported = PACKET_SUPPORT_UNKNOWN;
5586 break;
5587
5588 default:
3e43a32a
MS
5589 warning (_("unrecognized item \"%s\" "
5590 "in \"qSupported\" response"), p);
be2a5f71
DJ
5591 continue;
5592 }
5593 end[-1] = '\0';
5594 }
5595
5596 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5597 if (strcmp (remote_protocol_features[i].name, p) == 0)
5598 {
5599 const struct protocol_feature *feature;
5600
5601 seen[i] = 1;
5602 feature = &remote_protocol_features[i];
6b8edb51 5603 feature->func (this, feature, is_supported, value);
be2a5f71
DJ
5604 break;
5605 }
5606 }
5607
5608 /* If we increased the packet size, make sure to increase the global
5609 buffer size also. We delay this until after parsing the entire
5610 qSupported packet, because this is the same buffer we were
5611 parsing. */
8d64371b
TT
5612 if (rs->buf.size () < rs->explicit_packet_size)
5613 rs->buf.resize (rs->explicit_packet_size);
be2a5f71
DJ
5614
5615 /* Handle the defaults for unmentioned features. */
5616 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5617 if (!seen[i])
5618 {
5619 const struct protocol_feature *feature;
5620
5621 feature = &remote_protocol_features[i];
6b8edb51 5622 feature->func (this, feature, feature->default_support, NULL);
be2a5f71
DJ
5623 }
5624}
5625
048094ac
PA
5626/* Serial QUIT handler for the remote serial descriptor.
5627
5628 Defers handling a Ctrl-C until we're done with the current
5629 command/response packet sequence, unless:
5630
5631 - We're setting up the connection. Don't send a remote interrupt
5632 request, as we're not fully synced yet. Quit immediately
5633 instead.
5634
5635 - The target has been resumed in the foreground
223ffa71 5636 (target_terminal::is_ours is false) with a synchronous resume
048094ac
PA
5637 packet, and we're blocked waiting for the stop reply, thus a
5638 Ctrl-C should be immediately sent to the target.
5639
5640 - We get a second Ctrl-C while still within the same serial read or
5641 write. In that case the serial is seemingly wedged --- offer to
5642 quit/disconnect.
5643
5644 - We see a second Ctrl-C without target response, after having
5645 previously interrupted the target. In that case the target/stub
5646 is probably wedged --- offer to quit/disconnect.
5647*/
5648
6b8edb51
PA
5649void
5650remote_target::remote_serial_quit_handler ()
048094ac
PA
5651{
5652 struct remote_state *rs = get_remote_state ();
5653
5654 if (check_quit_flag ())
5655 {
5656 /* If we're starting up, we're not fully synced yet. Quit
5657 immediately. */
5658 if (rs->starting_up)
5659 quit ();
5660 else if (rs->got_ctrlc_during_io)
5661 {
5662 if (query (_("The target is not responding to GDB commands.\n"
5663 "Stop debugging it? ")))
5b6d1e4f 5664 remote_unpush_and_throw (this);
048094ac
PA
5665 }
5666 /* If ^C has already been sent once, offer to disconnect. */
223ffa71 5667 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
048094ac
PA
5668 interrupt_query ();
5669 /* All-stop protocol, and blocked waiting for stop reply. Send
5670 an interrupt request. */
223ffa71 5671 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
e671cd59 5672 target_interrupt ();
048094ac
PA
5673 else
5674 rs->got_ctrlc_during_io = 1;
5675 }
5676}
5677
6b8edb51
PA
5678/* The remote_target that is current while the quit handler is
5679 overridden with remote_serial_quit_handler. */
5680static remote_target *curr_quit_handler_target;
5681
5682static void
5683remote_serial_quit_handler ()
5684{
5685 curr_quit_handler_target->remote_serial_quit_handler ();
5686}
5687
5b6d1e4f
PA
5688/* Remove the remote target from the target stack of each inferior
5689 that is using it. Upper targets depend on it so remove them
5690 first. */
78a095c3
JK
5691
5692static void
5b6d1e4f 5693remote_unpush_target (remote_target *target)
78a095c3 5694{
5b6d1e4f
PA
5695 /* We have to unpush the target from all inferiors, even those that
5696 aren't running. */
5697 scoped_restore_current_inferior restore_current_inferior;
5698
5699 for (inferior *inf : all_inferiors (target))
5700 {
5701 switch_to_inferior_no_thread (inf);
5702 pop_all_targets_at_and_above (process_stratum);
5703 generic_mourn_inferior ();
5704 }
d7cb0ef3
PA
5705
5706 /* Don't rely on target_close doing this when the target is popped
5707 from the last remote inferior above, because something may be
5708 holding a reference to the target higher up on the stack, meaning
5709 target_close won't be called yet. We lost the connection to the
5710 target, so clear these now, otherwise we may later throw
5711 TARGET_CLOSE_ERROR while trying to tell the remote target to
5712 close the file. */
5713 fileio_handles_invalidate_target (target);
78a095c3 5714}
be2a5f71 5715
048094ac 5716static void
5b6d1e4f 5717remote_unpush_and_throw (remote_target *target)
048094ac 5718{
5b6d1e4f 5719 remote_unpush_target (target);
048094ac
PA
5720 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5721}
5722
f6ac5f3d
PA
5723void
5724remote_target::open_1 (const char *name, int from_tty, int extended_p)
c906108c 5725{
6b8edb51 5726 remote_target *curr_remote = get_current_remote_target ();
a6f3e723 5727
c906108c 5728 if (name == 0)
8a3fe4f8 5729 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 5730 "serial device is attached to the remote system\n"
8a3fe4f8 5731 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 5732
2d717e4f 5733 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
5734 Ask this question first, before target_preopen has a chance to kill
5735 anything. */
55f6301a 5736 if (curr_remote != NULL && !target_has_execution ())
2d717e4f 5737 {
78a095c3
JK
5738 if (from_tty
5739 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
5740 error (_("Still connected."));
5741 }
5742
78a095c3 5743 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
5744 target_preopen (from_tty);
5745
ad9a8f3f 5746 remote_fileio_reset ();
1dd41f16 5747 reopen_exec_file ();
9dec38d3 5748 reread_symbols (from_tty);
1dd41f16 5749
6b8edb51
PA
5750 remote_target *remote
5751 = (extended_p ? new extended_remote_target () : new remote_target ());
5752 target_ops_up target_holder (remote);
5753
5754 remote_state *rs = remote->get_remote_state ();
5755
5756 /* See FIXME above. */
5757 if (!target_async_permitted)
5758 rs->wait_forever_enabled_p = 1;
5759
5d93a237
TT
5760 rs->remote_desc = remote_serial_open (name);
5761 if (!rs->remote_desc)
c906108c
SS
5762 perror_with_name (name);
5763
5764 if (baud_rate != -1)
5765 {
5d93a237 5766 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 5767 {
9b74d5d3
KB
5768 /* The requested speed could not be set. Error out to
5769 top level after closing remote_desc. Take care to
5770 set remote_desc to NULL to avoid closing remote_desc
5771 more than once. */
5d93a237
TT
5772 serial_close (rs->remote_desc);
5773 rs->remote_desc = NULL;
c906108c
SS
5774 perror_with_name (name);
5775 }
5776 }
5777
236af5e3 5778 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 5779 serial_raw (rs->remote_desc);
c906108c
SS
5780
5781 /* If there is something sitting in the buffer we might take it as a
5782 response to a command, which would be bad. */
5d93a237 5783 serial_flush_input (rs->remote_desc);
c906108c
SS
5784
5785 if (from_tty)
5786 {
0426ad51
TT
5787 gdb_puts ("Remote debugging using ");
5788 gdb_puts (name);
5789 gdb_puts ("\n");
c906108c 5790 }
d9f719f1 5791
6b8edb51 5792 /* Switch to using the remote target now. */
02980c56 5793 current_inferior ()->push_target (std::move (target_holder));
c906108c 5794
74531fed 5795 /* Register extra event sources in the event loop. */
6b8edb51 5796 rs->remote_async_inferior_event_token
baa8575b 5797 = create_async_event_handler (remote_async_inferior_event_handler, nullptr,
db20ebdf 5798 "remote");
6b8edb51 5799 rs->notif_state = remote_notif_state_allocate (remote);
74531fed 5800
be2a5f71
DJ
5801 /* Reset the target state; these things will be queried either by
5802 remote_query_supported or as they are needed. */
ca4f7f8b 5803 reset_all_packet_configs_support ();
be2a5f71 5804 rs->explicit_packet_size = 0;
a6f3e723 5805 rs->noack_mode = 0;
82f73884 5806 rs->extended = extended_p;
e24a49d8 5807 rs->waiting_for_stop_reply = 0;
3a29589a 5808 rs->ctrlc_pending_p = 0;
048094ac 5809 rs->got_ctrlc_during_io = 0;
802188a7 5810
47f8a51d
TT
5811 rs->general_thread = not_sent_ptid;
5812 rs->continue_thread = not_sent_ptid;
262e1174 5813 rs->remote_traceframe_number = -1;
c906108c 5814
3a00c802
PA
5815 rs->last_resume_exec_dir = EXEC_FORWARD;
5816
9d1f7ab2 5817 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
5818 rs->use_threadinfo_query = 1;
5819 rs->use_threadextra_query = 1;
9d1f7ab2 5820
dd194f6b 5821 rs->readahead_cache.invalidate ();
80152258 5822
c6ebd6cf 5823 if (target_async_permitted)
92d1e331 5824 {
92d1e331
DJ
5825 /* FIXME: cagney/1999-09-23: During the initial connection it is
5826 assumed that the target is already ready and able to respond to
0df8b418 5827 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 5828 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 5829 around this. Eventually a mechanism that allows
92d1e331 5830 wait_for_inferior() to expect/get timeouts will be
23860348 5831 implemented. */
6b8edb51 5832 rs->wait_forever_enabled_p = 0;
92d1e331
DJ
5833 }
5834
23860348 5835 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 5836 no_shared_libraries (NULL, 0);
f78f6cf1 5837
36918e70 5838 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
5839 target (we'd otherwise be in an inconsistent state) and then
5840 propogate the error on up the exception chain. This ensures that
5841 the caller doesn't stumble along blindly assuming that the
5842 function succeeded. The CLI doesn't have this problem but other
5843 UI's, such as MI do.
36918e70
AC
5844
5845 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5846 this function should return an error indication letting the
ce2826aa 5847 caller restore the previous state. Unfortunately the command
36918e70
AC
5848 ``target remote'' is directly wired to this function making that
5849 impossible. On a positive note, the CLI side of this problem has
5850 been fixed - the function set_cmd_context() makes it possible for
5851 all the ``target ....'' commands to share a common callback
5852 function. See cli-dump.c. */
109c3e39 5853 {
2d717e4f 5854
a70b8144 5855 try
04bd08de 5856 {
6b8edb51 5857 remote->start_remote (from_tty, extended_p);
04bd08de 5858 }
230d2906 5859 catch (const gdb_exception &ex)
109c3e39 5860 {
c8d104ad
PA
5861 /* Pop the partially set up target - unless something else did
5862 already before throwing the exception. */
6b8edb51 5863 if (ex.error != TARGET_CLOSE_ERROR)
5b6d1e4f 5864 remote_unpush_target (remote);
eedc3f4f 5865 throw;
109c3e39
AC
5866 }
5867 }
c906108c 5868
6b8edb51 5869 remote_btrace_reset (rs);
f4abbc16 5870
c6ebd6cf 5871 if (target_async_permitted)
6b8edb51 5872 rs->wait_forever_enabled_p = 1;
43ff13b4
JM
5873}
5874
28561a65 5875/* Determine if WS represents a fork status. */
a4543480 5876
28561a65
SM
5877static bool
5878is_fork_status (target_waitkind kind)
a4543480 5879{
28561a65
SM
5880 return (kind == TARGET_WAITKIND_FORKED
5881 || kind == TARGET_WAITKIND_VFORKED);
a4543480
SM
5882}
5883
28561a65
SM
5884/* Return THREAD's pending status if it is a pending fork parent, else
5885 return nullptr. */
a4543480 5886
28561a65 5887static const target_waitstatus *
a4543480
SM
5888thread_pending_fork_status (struct thread_info *thread)
5889{
28561a65
SM
5890 const target_waitstatus &ws
5891 = (thread->has_pending_waitstatus ()
5892 ? thread->pending_waitstatus ()
5893 : thread->pending_follow);
a4543480 5894
28561a65
SM
5895 if (!is_fork_status (ws.kind ()))
5896 return nullptr;
a4543480 5897
28561a65 5898 return &ws;
a4543480
SM
5899}
5900
de0d863e
DB
5901/* Detach the specified process. */
5902
6b8edb51
PA
5903void
5904remote_target::remote_detach_pid (int pid)
de0d863e
DB
5905{
5906 struct remote_state *rs = get_remote_state ();
5907
4c7333b3
PA
5908 /* This should not be necessary, but the handling for D;PID in
5909 GDBserver versions prior to 8.2 incorrectly assumes that the
5910 selected process points to the same process we're detaching,
5911 leading to misbehavior (and possibly GDBserver crashing) when it
5912 does not. Since it's easy and cheap, work around it by forcing
5913 GDBserver to select GDB's current process. */
5914 set_general_process ();
5915
de0d863e 5916 if (remote_multi_process_p (rs))
8d64371b 5917 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
de0d863e 5918 else
8d64371b 5919 strcpy (rs->buf.data (), "D");
de0d863e
DB
5920
5921 putpkt (rs->buf);
8d64371b 5922 getpkt (&rs->buf, 0);
de0d863e
DB
5923
5924 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5925 ;
5926 else if (rs->buf[0] == '\0')
5927 error (_("Remote doesn't know how to detach"));
5928 else
5929 error (_("Can't detach process."));
5930}
5931
5932/* This detaches a program to which we previously attached, using
5933 inferior_ptid to identify the process. After this is done, GDB
5934 can be used to debug some other program. We better not have left
5935 any breakpoints in the target program or it'll die when it hits
5936 one. */
c906108c 5937
6b8edb51 5938void
00431a78 5939remote_target::remote_detach_1 (inferior *inf, int from_tty)
c906108c 5940{
e99b03dc 5941 int pid = inferior_ptid.pid ();
d01949b6 5942 struct remote_state *rs = get_remote_state ();
de0d863e 5943 int is_fork_parent;
c906108c 5944
55f6301a 5945 if (!target_has_execution ())
2d717e4f
DJ
5946 error (_("No process to detach from."));
5947
0f48b757 5948 target_announce_detach (from_tty);
7cee1e54 5949
e87f0fe8
PA
5950 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
5951 {
5952 /* If we're in breakpoints-always-inserted mode, or the inferior
5953 is running, we have to remove breakpoints before detaching.
5954 We don't do this in common code instead because not all
5955 targets support removing breakpoints while the target is
5956 running. The remote target / gdbserver does, though. */
5957 remove_breakpoints_inf (current_inferior ());
5958 }
5959
c906108c 5960 /* Tell the remote target to detach. */
de0d863e 5961 remote_detach_pid (pid);
82f73884 5962
8020350c 5963 /* Exit only if this is the only active inferior. */
5b6d1e4f 5964 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
0426ad51 5965 gdb_puts (_("Ending remote debugging.\n"));
82f73884 5966
df5ad102
SM
5967 /* See if any thread of the inferior we are detaching has a pending fork
5968 status. In that case, we must detach from the child resulting from
5969 that fork. */
5970 for (thread_info *thread : inf->non_exited_threads ())
5971 {
5972 const target_waitstatus *ws = thread_pending_fork_status (thread);
5973
5974 if (ws == nullptr)
5975 continue;
5976
5977 remote_detach_pid (ws->child_ptid ().pid ());
5978 }
5979
5980 /* Check also for any pending fork events in the stop reply queue. */
5981 remote_notif_get_pending_events (&notif_client_stop);
5982 for (stop_reply_up &reply : rs->stop_reply_queue)
5983 {
5984 if (reply->ptid.pid () != pid)
5985 continue;
5986
5987 if (!is_fork_status (reply->ws.kind ()))
5988 continue;
5989
5990 remote_detach_pid (reply->ws.child_ptid ().pid ());
5991 }
5992
5b6d1e4f 5993 thread_info *tp = find_thread_ptid (this, inferior_ptid);
00431a78 5994
de0d863e
DB
5995 /* Check to see if we are detaching a fork parent. Note that if we
5996 are detaching a fork child, tp == NULL. */
5997 is_fork_parent = (tp != NULL
183be222 5998 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
de0d863e
DB
5999
6000 /* If doing detach-on-fork, we don't mourn, because that will delete
6001 breakpoints that should be available for the followed inferior. */
6002 if (!is_fork_parent)
f67c0c91 6003 {
249b5733
PA
6004 /* Save the pid as a string before mourning, since that will
6005 unpush the remote target, and we need the string after. */
f2907e49 6006 std::string infpid = target_pid_to_str (ptid_t (pid));
f67c0c91
SDJ
6007
6008 target_mourn_inferior (inferior_ptid);
6009 if (print_inferior_events)
6cb06a8c
TT
6010 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6011 inf->num, infpid.c_str ());
f67c0c91 6012 }
de0d863e
DB
6013 else
6014 {
0ac55310 6015 switch_to_no_thread ();
00431a78 6016 detach_inferior (current_inferior ());
de0d863e 6017 }
2d717e4f
DJ
6018}
6019
f6ac5f3d
PA
6020void
6021remote_target::detach (inferior *inf, int from_tty)
2d717e4f 6022{
00431a78 6023 remote_detach_1 (inf, from_tty);
2d717e4f
DJ
6024}
6025
f6ac5f3d
PA
6026void
6027extended_remote_target::detach (inferior *inf, int from_tty)
2d717e4f 6028{
00431a78 6029 remote_detach_1 (inf, from_tty);
de0d863e
DB
6030}
6031
6032/* Target follow-fork function for remote targets. On entry, and
6033 at return, the current inferior is the fork parent.
6034
6035 Note that although this is currently only used for extended-remote,
6036 it is named remote_follow_fork in anticipation of using it for the
6037 remote target as well. */
6038
e97007b6 6039void
82d1f134
SM
6040remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6041 target_waitkind fork_kind, bool follow_child,
6042 bool detach_fork)
de0d863e 6043{
82d1f134
SM
6044 process_stratum_target::follow_fork (child_inf, child_ptid,
6045 fork_kind, follow_child, detach_fork);
6046
de0d863e
DB
6047 struct remote_state *rs = get_remote_state ();
6048
3a849a34
SM
6049 if ((fork_kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
6050 || (fork_kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
6051 {
6052 /* When following the parent and detaching the child, we detach
6053 the child here. For the case of following the child and
6054 detaching the parent, the detach is done in the target-
6055 independent follow fork code in infrun.c. We can't use
6056 target_detach when detaching an unfollowed child because
6057 the client side doesn't know anything about the child. */
6058 if (detach_fork && !follow_child)
6059 {
6060 /* Detach the fork child. */
3a849a34 6061 remote_detach_pid (child_ptid.pid ());
de0d863e
DB
6062 }
6063 }
c906108c
SS
6064}
6065
94585166 6066/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
294c36eb 6067 in the program space of the new inferior. */
94585166 6068
f6ac5f3d 6069void
294c36eb
SM
6070remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6071 const char *execd_pathname)
94585166 6072{
294c36eb
SM
6073 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6074
94585166
DB
6075 /* We know that this is a target file name, so if it has the "target:"
6076 prefix we strip it off before saving it in the program space. */
6077 if (is_target_filename (execd_pathname))
6078 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6079
294c36eb 6080 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
94585166
DB
6081}
6082
6ad8ae5c
DJ
6083/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6084
f6ac5f3d
PA
6085void
6086remote_target::disconnect (const char *args, int from_tty)
43ff13b4 6087{
43ff13b4 6088 if (args)
2d717e4f 6089 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 6090
8020350c 6091 /* Make sure we unpush even the extended remote targets. Calling
5b6d1e4f
PA
6092 target_mourn_inferior won't unpush, and
6093 remote_target::mourn_inferior won't unpush if there is more than
6094 one inferior left. */
6095 remote_unpush_target (this);
2d717e4f 6096
43ff13b4 6097 if (from_tty)
0426ad51 6098 gdb_puts ("Ending remote debugging.\n");
43ff13b4
JM
6099}
6100
2d717e4f
DJ
6101/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6102 be chatty about it. */
6103
f6ac5f3d
PA
6104void
6105extended_remote_target::attach (const char *args, int from_tty)
2d717e4f
DJ
6106{
6107 struct remote_state *rs = get_remote_state ();
be86555c 6108 int pid;
96ef3384 6109 char *wait_status = NULL;
2d717e4f 6110
74164c56 6111 pid = parse_pid_to_attach (args);
2d717e4f 6112
74164c56
JK
6113 /* Remote PID can be freely equal to getpid, do not check it here the same
6114 way as in other targets. */
2d717e4f 6115
4082afcc 6116 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
6117 error (_("This target does not support attaching to a process"));
6118
bc521517 6119 target_announce_attach (from_tty, pid);
7cee1e54 6120
8d64371b 6121 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f 6122 putpkt (rs->buf);
8d64371b 6123 getpkt (&rs->buf, 0);
2d717e4f 6124
4082afcc
PA
6125 switch (packet_ok (rs->buf,
6126 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 6127 {
4082afcc 6128 case PACKET_OK:
6efcd9a8 6129 if (!target_is_non_stop_p ())
74531fed
PA
6130 {
6131 /* Save the reply for later. */
8d64371b
TT
6132 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6133 strcpy (wait_status, rs->buf.data ());
74531fed 6134 }
8d64371b 6135 else if (strcmp (rs->buf.data (), "OK") != 0)
74531fed 6136 error (_("Attaching to %s failed with: %s"),
a068643d 6137 target_pid_to_str (ptid_t (pid)).c_str (),
8d64371b 6138 rs->buf.data ());
4082afcc
PA
6139 break;
6140 case PACKET_UNKNOWN:
6141 error (_("This target does not support attaching to a process"));
6142 default:
50fa3001
SDJ
6143 error (_("Attaching to %s failed"),
6144 target_pid_to_str (ptid_t (pid)).c_str ());
2d717e4f 6145 }
2d717e4f 6146
0ac55310 6147 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
bad34192 6148
f2907e49 6149 inferior_ptid = ptid_t (pid);
79d7f229 6150
6efcd9a8 6151 if (target_is_non_stop_p ())
bad34192 6152 {
bad34192 6153 /* Get list of threads. */
f6ac5f3d 6154 update_thread_list ();
82f73884 6155
0ac55310
PA
6156 thread_info *thread = first_thread_of_inferior (current_inferior ());
6157 if (thread != nullptr)
6158 switch_to_thread (thread);
bad34192
PA
6159
6160 /* Invalidate our notion of the remote current thread. */
47f8a51d 6161 record_currthread (rs, minus_one_ptid);
bad34192 6162 }
74531fed 6163 else
bad34192 6164 {
0ac55310
PA
6165 /* Now, if we have thread information, update the main thread's
6166 ptid. */
6167 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
bad34192 6168
b622494e
AB
6169 /* Add the main thread to the thread list. We add the thread
6170 silently in this case (the final true parameter). */
6171 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
0ac55310
PA
6172
6173 switch_to_thread (thr);
bad34192 6174 }
c0a2216e 6175
96ef3384
UW
6176 /* Next, if the target can specify a description, read it. We do
6177 this before anything involving memory or registers. */
6178 target_find_description ();
6179
6efcd9a8 6180 if (!target_is_non_stop_p ())
74531fed
PA
6181 {
6182 /* Use the previously fetched status. */
6183 gdb_assert (wait_status != NULL);
6184
4f626cad
AB
6185 struct notif_event *reply
6186 = remote_notif_parse (this, &notif_client_stop, wait_status);
74531fed 6187
4f626cad 6188 push_stop_reply ((struct stop_reply *) reply);
74531fed
PA
6189 }
6190 else
621cc310
PA
6191 {
6192 gdb_assert (wait_status == NULL);
6193
6194 gdb_assert (target_can_async_p ());
621cc310 6195 }
2d717e4f
DJ
6196}
6197
b9c1d481
AS
6198/* Implementation of the to_post_attach method. */
6199
f6ac5f3d
PA
6200void
6201extended_remote_target::post_attach (int pid)
b9c1d481 6202{
6efcd9a8
PA
6203 /* Get text, data & bss offsets. */
6204 get_offsets ();
6205
b9c1d481
AS
6206 /* In certain cases GDB might not have had the chance to start
6207 symbol lookup up until now. This could happen if the debugged
6208 binary is not using shared libraries, the vsyscall page is not
6209 present (on Linux) and the binary itself hadn't changed since the
6210 debugging process was started. */
a42d7dd8 6211 if (current_program_space->symfile_object_file != NULL)
b9c1d481
AS
6212 remote_check_symbols();
6213}
6214
c906108c 6215\f
506fb367
DJ
6216/* Check for the availability of vCont. This function should also check
6217 the response. */
c906108c 6218
6b8edb51
PA
6219void
6220remote_target::remote_vcont_probe ()
c906108c 6221{
6b8edb51 6222 remote_state *rs = get_remote_state ();
2e9f7625 6223 char *buf;
6d820c5c 6224
8d64371b 6225 strcpy (rs->buf.data (), "vCont?");
2e9f7625 6226 putpkt (rs->buf);
8d64371b
TT
6227 getpkt (&rs->buf, 0);
6228 buf = rs->buf.data ();
c906108c 6229
506fb367 6230 /* Make sure that the features we assume are supported. */
61012eef 6231 if (startswith (buf, "vCont"))
506fb367
DJ
6232 {
6233 char *p = &buf[5];
750ce8d1 6234 int support_c, support_C;
506fb367 6235
750ce8d1
YQ
6236 rs->supports_vCont.s = 0;
6237 rs->supports_vCont.S = 0;
506fb367
DJ
6238 support_c = 0;
6239 support_C = 0;
d458bd84 6240 rs->supports_vCont.t = 0;
c1e36e3e 6241 rs->supports_vCont.r = 0;
506fb367
DJ
6242 while (p && *p == ';')
6243 {
6244 p++;
6245 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 6246 rs->supports_vCont.s = 1;
506fb367 6247 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 6248 rs->supports_vCont.S = 1;
506fb367
DJ
6249 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6250 support_c = 1;
6251 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6252 support_C = 1;
74531fed 6253 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 6254 rs->supports_vCont.t = 1;
c1e36e3e
PA
6255 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6256 rs->supports_vCont.r = 1;
506fb367
DJ
6257
6258 p = strchr (p, ';');
6259 }
c906108c 6260
750ce8d1
YQ
6261 /* If c, and C are not all supported, we can't use vCont. Clearing
6262 BUF will make packet_ok disable the packet. */
6263 if (!support_c || !support_C)
506fb367
DJ
6264 buf[0] = 0;
6265 }
c906108c 6266
8d64371b 6267 packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCont]);
5b6d1e4f 6268 rs->supports_vCont_probed = true;
506fb367 6269}
c906108c 6270
0d8f58ca
PA
6271/* Helper function for building "vCont" resumptions. Write a
6272 resumption to P. ENDP points to one-passed-the-end of the buffer
6273 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6274 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6275 resumed thread should be single-stepped and/or signalled. If PTID
6276 equals minus_one_ptid, then all threads are resumed; if PTID
d51926f0
PA
6277 represents a process, then all threads of the process are
6278 resumed. */
0d8f58ca 6279
6b8edb51
PA
6280char *
6281remote_target::append_resumption (char *p, char *endp,
6282 ptid_t ptid, int step, gdb_signal siggnal)
0d8f58ca
PA
6283{
6284 struct remote_state *rs = get_remote_state ();
6285
a493e3e2 6286 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 6287 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
6288 else if (step
6289 /* GDB is willing to range step. */
6290 && use_range_stepping
6291 /* Target supports range stepping. */
6292 && rs->supports_vCont.r
6293 /* We don't currently support range stepping multiple
6294 threads with a wildcard (though the protocol allows it,
6295 so stubs shouldn't make an active effort to forbid
6296 it). */
0e998d96 6297 && !(remote_multi_process_p (rs) && ptid.is_pid ()))
c1e36e3e
PA
6298 {
6299 struct thread_info *tp;
6300
d7e15655 6301 if (ptid == minus_one_ptid)
c1e36e3e
PA
6302 {
6303 /* If we don't know about the target thread's tid, then
6304 we're resuming magic_null_ptid (see caller). */
5b6d1e4f 6305 tp = find_thread_ptid (this, magic_null_ptid);
c1e36e3e
PA
6306 }
6307 else
5b6d1e4f 6308 tp = find_thread_ptid (this, ptid);
c1e36e3e
PA
6309 gdb_assert (tp != NULL);
6310
6311 if (tp->control.may_range_step)
6312 {
6313 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6314
6315 p += xsnprintf (p, endp - p, ";r%s,%s",
6316 phex_nz (tp->control.step_range_start,
6317 addr_size),
6318 phex_nz (tp->control.step_range_end,
6319 addr_size));
6320 }
6321 else
6322 p += xsnprintf (p, endp - p, ";s");
6323 }
0d8f58ca
PA
6324 else if (step)
6325 p += xsnprintf (p, endp - p, ";s");
a493e3e2 6326 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
6327 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6328 else
6329 p += xsnprintf (p, endp - p, ";c");
6330
0e998d96 6331 if (remote_multi_process_p (rs) && ptid.is_pid ())
0d8f58ca
PA
6332 {
6333 ptid_t nptid;
6334
6335 /* All (-1) threads of process. */
184ea2f7 6336 nptid = ptid_t (ptid.pid (), -1);
0d8f58ca
PA
6337
6338 p += xsnprintf (p, endp - p, ":");
6339 p = write_ptid (p, endp, nptid);
6340 }
d7e15655 6341 else if (ptid != minus_one_ptid)
0d8f58ca
PA
6342 {
6343 p += xsnprintf (p, endp - p, ":");
6344 p = write_ptid (p, endp, ptid);
6345 }
6346
6347 return p;
6348}
6349
799a2abe
PA
6350/* Clear the thread's private info on resume. */
6351
6352static void
6353resume_clear_thread_private_info (struct thread_info *thread)
6354{
6355 if (thread->priv != NULL)
6356 {
7aabaf9d
SM
6357 remote_thread_info *priv = get_remote_thread_info (thread);
6358
6359 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6360 priv->watch_data_address = 0;
799a2abe
PA
6361 }
6362}
6363
e5ef252a
PA
6364/* Append a vCont continue-with-signal action for threads that have a
6365 non-zero stop signal. */
6366
6b8edb51
PA
6367char *
6368remote_target::append_pending_thread_resumptions (char *p, char *endp,
6369 ptid_t ptid)
e5ef252a 6370{
5b6d1e4f 6371 for (thread_info *thread : all_non_exited_threads (this, ptid))
08036331 6372 if (inferior_ptid != thread->ptid
1edb66d8 6373 && thread->stop_signal () != GDB_SIGNAL_0)
e5ef252a
PA
6374 {
6375 p = append_resumption (p, endp, thread->ptid,
1edb66d8
SM
6376 0, thread->stop_signal ());
6377 thread->set_stop_signal (GDB_SIGNAL_0);
799a2abe 6378 resume_clear_thread_private_info (thread);
e5ef252a
PA
6379 }
6380
6381 return p;
6382}
6383
7b68ffbb
PA
6384/* Set the target running, using the packets that use Hc
6385 (c/s/C/S). */
6386
6b8edb51
PA
6387void
6388remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6389 gdb_signal siggnal)
7b68ffbb
PA
6390{
6391 struct remote_state *rs = get_remote_state ();
7b68ffbb
PA
6392 char *buf;
6393
6394 rs->last_sent_signal = siggnal;
6395 rs->last_sent_step = step;
6396
6397 /* The c/s/C/S resume packets use Hc, so set the continue
6398 thread. */
d7e15655 6399 if (ptid == minus_one_ptid)
7b68ffbb
PA
6400 set_continue_thread (any_thread_ptid);
6401 else
6402 set_continue_thread (ptid);
6403
5b6d1e4f 6404 for (thread_info *thread : all_non_exited_threads (this))
7b68ffbb
PA
6405 resume_clear_thread_private_info (thread);
6406
8d64371b 6407 buf = rs->buf.data ();
6b8edb51 6408 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6409 {
6410 /* We don't pass signals to the target in reverse exec mode. */
6411 if (info_verbose && siggnal != GDB_SIGNAL_0)
6412 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6413 siggnal);
6414
6415 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6416 error (_("Remote reverse-step not supported."));
6417 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6418 error (_("Remote reverse-continue not supported."));
6419
6420 strcpy (buf, step ? "bs" : "bc");
6421 }
6422 else if (siggnal != GDB_SIGNAL_0)
6423 {
6424 buf[0] = step ? 'S' : 'C';
6425 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6426 buf[2] = tohex (((int) siggnal) & 0xf);
6427 buf[3] = '\0';
6428 }
6429 else
6430 strcpy (buf, step ? "s" : "c");
6431
6432 putpkt (buf);
6433}
6434
d51926f0
PA
6435/* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6436 STEP, and SIGGNAL have the same meaning as in target_resume. This
6437 function returns non-zero iff it resumes the inferior.
44eaed12 6438
7b68ffbb
PA
6439 This function issues a strict subset of all possible vCont commands
6440 at the moment. */
44eaed12 6441
6b8edb51 6442int
d51926f0 6443remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6b8edb51 6444 enum gdb_signal siggnal)
506fb367
DJ
6445{
6446 struct remote_state *rs = get_remote_state ();
82f73884
PA
6447 char *p;
6448 char *endp;
44eaed12 6449
7b68ffbb 6450 /* No reverse execution actions defined for vCont. */
6b8edb51 6451 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6452 return 0;
6453
4082afcc 6454 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 6455 remote_vcont_probe ();
44eaed12 6456
4082afcc 6457 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 6458 return 0;
44eaed12 6459
8d64371b
TT
6460 p = rs->buf.data ();
6461 endp = p + get_remote_packet_size ();
82f73884 6462
506fb367
DJ
6463 /* If we could generate a wider range of packets, we'd have to worry
6464 about overflowing BUF. Should there be a generic
6465 "multi-part-packet" packet? */
6466
0d8f58ca
PA
6467 p += xsnprintf (p, endp - p, "vCont");
6468
d51926f0 6469 if (scope_ptid == magic_null_ptid)
c906108c 6470 {
79d7f229
PA
6471 /* MAGIC_NULL_PTID means that we don't have any active threads,
6472 so we don't have any TID numbers the inferior will
6473 understand. Make sure to only send forms that do not specify
6474 a TID. */
a9cbf802 6475 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 6476 }
d51926f0 6477 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
506fb367 6478 {
0d8f58ca
PA
6479 /* Resume all threads (of all processes, or of a single
6480 process), with preference for INFERIOR_PTID. This assumes
6481 inferior_ptid belongs to the set of all threads we are about
6482 to resume. */
a493e3e2 6483 if (step || siggnal != GDB_SIGNAL_0)
82f73884 6484 {
0d8f58ca
PA
6485 /* Step inferior_ptid, with or without signal. */
6486 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 6487 }
0d8f58ca 6488
e5ef252a
PA
6489 /* Also pass down any pending signaled resumption for other
6490 threads not the current. */
d51926f0 6491 p = append_pending_thread_resumptions (p, endp, scope_ptid);
e5ef252a 6492
0d8f58ca 6493 /* And continue others without a signal. */
d51926f0 6494 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
6495 }
6496 else
506fb367 6497 {
d51926f0
PA
6498 /* Scheduler locking; resume only SCOPE_PTID. */
6499 append_resumption (p, endp, scope_ptid, step, siggnal);
506fb367 6500 }
c906108c 6501
8d64371b 6502 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
82f73884 6503 putpkt (rs->buf);
506fb367 6504
6efcd9a8 6505 if (target_is_non_stop_p ())
74531fed
PA
6506 {
6507 /* In non-stop, the stub replies to vCont with "OK". The stop
6508 reply will be reported asynchronously by means of a `%Stop'
6509 notification. */
8d64371b
TT
6510 getpkt (&rs->buf, 0);
6511 if (strcmp (rs->buf.data (), "OK") != 0)
6512 error (_("Unexpected vCont reply in non-stop mode: %s"),
6513 rs->buf.data ());
74531fed
PA
6514 }
6515
506fb367 6516 return 1;
c906108c 6517}
43ff13b4 6518
506fb367
DJ
6519/* Tell the remote machine to resume. */
6520
f6ac5f3d 6521void
d51926f0 6522remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
43ff13b4 6523{
d01949b6 6524 struct remote_state *rs = get_remote_state ();
43ff13b4 6525
85ad3aaf
PA
6526 /* When connected in non-stop mode, the core resumes threads
6527 individually. Resuming remote threads directly in target_resume
6528 would thus result in sending one packet per thread. Instead, to
6529 minimize roundtrip latency, here we just store the resume
c9d22089
SM
6530 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6531 resumption will be done in remote_target::commit_resume, where we'll be
6532 able to do vCont action coalescing. */
f6ac5f3d 6533 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
85ad3aaf 6534 {
d51926f0
PA
6535 remote_thread_info *remote_thr
6536 = get_remote_thread_info (inferior_thread ());
7aabaf9d 6537
c9d22089
SM
6538 /* We don't expect the core to ask to resume an already resumed (from
6539 its point of view) thread. */
a6c11cbb 6540 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
c9d22089
SM
6541
6542 remote_thr->set_resumed_pending_vcont (step, siggnal);
d51926f0
PA
6543
6544 /* There's actually nothing that says that the core can't
6545 request a wildcard resume in non-stop mode, though. It's
6546 just that we know it doesn't currently, so we don't bother
6547 with it. */
6548 gdb_assert (scope_ptid == inferior_ptid);
85ad3aaf
PA
6549 return;
6550 }
6551
722247f1
YQ
6552 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6553 (explained in remote-notif.c:handle_notification) so
6554 remote_notif_process is not called. We need find a place where
6555 it is safe to start a 'vNotif' sequence. It is good to do it
6556 before resuming inferior, because inferior was stopped and no RSP
6557 traffic at that moment. */
6efcd9a8 6558 if (!target_is_non_stop_p ())
5965e028 6559 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 6560
f6ac5f3d 6561 rs->last_resume_exec_dir = ::execution_direction;
3a00c802 6562
7b68ffbb 6563 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
d51926f0
PA
6564 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
6565 remote_resume_with_hc (scope_ptid, step, siggnal);
43ff13b4 6566
c9d22089 6567 /* Update resumed state tracked by the remote target. */
d51926f0 6568 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
c9d22089
SM
6569 get_remote_thread_info (tp)->set_resumed ();
6570
e24a49d8
PA
6571 /* We've just told the target to resume. The remote server will
6572 wait for the inferior to stop, and then send a stop reply. In
6573 the mean time, we can't start another command/query ourselves
74531fed
PA
6574 because the stub wouldn't be ready to process it. This applies
6575 only to the base all-stop protocol, however. In non-stop (which
6576 only supports vCont), the stub replies with an "OK", and is
6577 immediate able to process further serial input. */
6efcd9a8 6578 if (!target_is_non_stop_p ())
74531fed 6579 rs->waiting_for_stop_reply = 1;
43ff13b4 6580}
85ad3aaf 6581
85ad3aaf
PA
6582/* Private per-inferior info for target remote processes. */
6583
089354bb 6584struct remote_inferior : public private_inferior
85ad3aaf
PA
6585{
6586 /* Whether we can send a wildcard vCont for this process. */
089354bb 6587 bool may_wildcard_vcont = true;
85ad3aaf
PA
6588};
6589
089354bb
SM
6590/* Get the remote private inferior data associated to INF. */
6591
6592static remote_inferior *
6593get_remote_inferior (inferior *inf)
6594{
6595 if (inf->priv == NULL)
6596 inf->priv.reset (new remote_inferior);
6597
6598 return static_cast<remote_inferior *> (inf->priv.get ());
6599}
6600
f5db4863 6601/* Class used to track the construction of a vCont packet in the
85ad3aaf
PA
6602 outgoing packet buffer. This is used to send multiple vCont
6603 packets if we have more actions than would fit a single packet. */
6604
f5db4863 6605class vcont_builder
85ad3aaf 6606{
f5db4863 6607public:
6b8edb51
PA
6608 explicit vcont_builder (remote_target *remote)
6609 : m_remote (remote)
f5db4863
PA
6610 {
6611 restart ();
6612 }
6613
6614 void flush ();
6615 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6616
6617private:
6618 void restart ();
6619
6b8edb51
PA
6620 /* The remote target. */
6621 remote_target *m_remote;
6622
85ad3aaf
PA
6623 /* Pointer to the first action. P points here if no action has been
6624 appended yet. */
f5db4863 6625 char *m_first_action;
85ad3aaf
PA
6626
6627 /* Where the next action will be appended. */
f5db4863 6628 char *m_p;
85ad3aaf
PA
6629
6630 /* The end of the buffer. Must never write past this. */
f5db4863 6631 char *m_endp;
85ad3aaf
PA
6632};
6633
6634/* Prepare the outgoing buffer for a new vCont packet. */
6635
f5db4863
PA
6636void
6637vcont_builder::restart ()
85ad3aaf 6638{
6b8edb51 6639 struct remote_state *rs = m_remote->get_remote_state ();
85ad3aaf 6640
8d64371b
TT
6641 m_p = rs->buf.data ();
6642 m_endp = m_p + m_remote->get_remote_packet_size ();
f5db4863
PA
6643 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6644 m_first_action = m_p;
85ad3aaf
PA
6645}
6646
6647/* If the vCont packet being built has any action, send it to the
6648 remote end. */
6649
f5db4863
PA
6650void
6651vcont_builder::flush ()
85ad3aaf
PA
6652{
6653 struct remote_state *rs;
6654
f5db4863 6655 if (m_p == m_first_action)
85ad3aaf
PA
6656 return;
6657
6b8edb51
PA
6658 rs = m_remote->get_remote_state ();
6659 m_remote->putpkt (rs->buf);
8d64371b
TT
6660 m_remote->getpkt (&rs->buf, 0);
6661 if (strcmp (rs->buf.data (), "OK") != 0)
6662 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
85ad3aaf
PA
6663}
6664
6665/* The largest action is range-stepping, with its two addresses. This
6666 is more than sufficient. If a new, bigger action is created, it'll
6667 quickly trigger a failed assertion in append_resumption (and we'll
6668 just bump this). */
6669#define MAX_ACTION_SIZE 200
6670
6671/* Append a new vCont action in the outgoing packet being built. If
6672 the action doesn't fit the packet along with previous actions, push
6673 what we've got so far to the remote end and start over a new vCont
6674 packet (with the new action). */
6675
f5db4863
PA
6676void
6677vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
85ad3aaf
PA
6678{
6679 char buf[MAX_ACTION_SIZE + 1];
85ad3aaf 6680
6b8edb51
PA
6681 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6682 ptid, step, siggnal);
85ad3aaf
PA
6683
6684 /* Check whether this new action would fit in the vCont packet along
6685 with previous actions. If not, send what we've got so far and
6686 start a new vCont packet. */
f5db4863
PA
6687 size_t rsize = endp - buf;
6688 if (rsize > m_endp - m_p)
85ad3aaf 6689 {
f5db4863
PA
6690 flush ();
6691 restart ();
85ad3aaf
PA
6692
6693 /* Should now fit. */
f5db4863 6694 gdb_assert (rsize <= m_endp - m_p);
85ad3aaf
PA
6695 }
6696
f5db4863
PA
6697 memcpy (m_p, buf, rsize);
6698 m_p += rsize;
6699 *m_p = '\0';
85ad3aaf
PA
6700}
6701
6702/* to_commit_resume implementation. */
6703
f6ac5f3d 6704void
1192f124 6705remote_target::commit_resumed ()
85ad3aaf 6706{
85ad3aaf
PA
6707 /* If connected in all-stop mode, we'd send the remote resume
6708 request directly from remote_resume. Likewise if
6709 reverse-debugging, as there are no defined vCont actions for
6710 reverse execution. */
f6ac5f3d 6711 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
85ad3aaf
PA
6712 return;
6713
6714 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6715 instead of resuming all threads of each process individually.
6716 However, if any thread of a process must remain halted, we can't
6717 send wildcard resumes and must send one action per thread.
6718
6719 Care must be taken to not resume threads/processes the server
6720 side already told us are stopped, but the core doesn't know about
6721 yet, because the events are still in the vStopped notification
6722 queue. For example:
6723
6724 #1 => vCont s:p1.1;c
6725 #2 <= OK
6726 #3 <= %Stopped T05 p1.1
6727 #4 => vStopped
6728 #5 <= T05 p1.2
6729 #6 => vStopped
6730 #7 <= OK
6731 #8 (infrun handles the stop for p1.1 and continues stepping)
6732 #9 => vCont s:p1.1;c
6733
6734 The last vCont above would resume thread p1.2 by mistake, because
6735 the server has no idea that the event for p1.2 had not been
6736 handled yet.
6737
6738 The server side must similarly ignore resume actions for the
6739 thread that has a pending %Stopped notification (and any other
6740 threads with events pending), until GDB acks the notification
6741 with vStopped. Otherwise, e.g., the following case is
6742 mishandled:
6743
6744 #1 => g (or any other packet)
6745 #2 <= [registers]
6746 #3 <= %Stopped T05 p1.2
6747 #4 => vCont s:p1.1;c
6748 #5 <= OK
6749
6750 Above, the server must not resume thread p1.2. GDB can't know
6751 that p1.2 stopped until it acks the %Stopped notification, and
6752 since from GDB's perspective all threads should be running, it
6753 sends a "c" action.
6754
6755 Finally, special care must also be given to handling fork/vfork
6756 events. A (v)fork event actually tells us that two processes
6757 stopped -- the parent and the child. Until we follow the fork,
6758 we must not resume the child. Therefore, if we have a pending
6759 fork follow, we must not send a global wildcard resume action
6760 (vCont;c). We can still send process-wide wildcards though. */
6761
6762 /* Start by assuming a global wildcard (vCont;c) is possible. */
2f63ec5c 6763 bool may_global_wildcard_vcont = true;
85ad3aaf
PA
6764
6765 /* And assume every process is individually wildcard-able too. */
5b6d1e4f 6766 for (inferior *inf : all_non_exited_inferiors (this))
85ad3aaf 6767 {
089354bb
SM
6768 remote_inferior *priv = get_remote_inferior (inf);
6769
6770 priv->may_wildcard_vcont = true;
85ad3aaf
PA
6771 }
6772
6773 /* Check for any pending events (not reported or processed yet) and
6774 disable process and global wildcard resumes appropriately. */
6775 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6776
1192f124
SM
6777 bool any_pending_vcont_resume = false;
6778
5b6d1e4f 6779 for (thread_info *tp : all_non_exited_threads (this))
85ad3aaf 6780 {
c9d22089
SM
6781 remote_thread_info *priv = get_remote_thread_info (tp);
6782
85ad3aaf
PA
6783 /* If a thread of a process is not meant to be resumed, then we
6784 can't wildcard that process. */
a6c11cbb 6785 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
85ad3aaf 6786 {
089354bb 6787 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
85ad3aaf
PA
6788
6789 /* And if we can't wildcard a process, we can't wildcard
6790 everything either. */
2f63ec5c 6791 may_global_wildcard_vcont = false;
85ad3aaf
PA
6792 continue;
6793 }
6794
1192f124
SM
6795 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
6796 any_pending_vcont_resume = true;
6797
85ad3aaf
PA
6798 /* If a thread is the parent of an unfollowed fork, then we
6799 can't do a global wildcard, as that would resume the fork
6800 child. */
28561a65 6801 if (thread_pending_fork_status (tp) != nullptr)
2f63ec5c 6802 may_global_wildcard_vcont = false;
85ad3aaf
PA
6803 }
6804
1192f124
SM
6805 /* We didn't have any resumed thread pending a vCont resume, so nothing to
6806 do. */
6807 if (!any_pending_vcont_resume)
6808 return;
6809
85ad3aaf
PA
6810 /* Now let's build the vCont packet(s). Actions must be appended
6811 from narrower to wider scopes (thread -> process -> global). If
6812 we end up with too many actions for a single packet vcont_builder
6813 flushes the current vCont packet to the remote side and starts a
6814 new one. */
6b8edb51 6815 struct vcont_builder vcont_builder (this);
85ad3aaf
PA
6816
6817 /* Threads first. */
5b6d1e4f 6818 for (thread_info *tp : all_non_exited_threads (this))
85ad3aaf 6819 {
7aabaf9d 6820 remote_thread_info *remote_thr = get_remote_thread_info (tp);
85ad3aaf 6821
c9d22089
SM
6822 /* If the thread was previously vCont-resumed, no need to send a specific
6823 action for it. If we didn't receive a resume request for it, don't
6824 send an action for it either. */
a6c11cbb 6825 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
85ad3aaf
PA
6826 continue;
6827
6828 gdb_assert (!thread_is_in_step_over_chain (tp));
6829
1192f124
SM
6830 /* We should never be commit-resuming a thread that has a stop reply.
6831 Otherwise, we would end up reporting a stop event for a thread while
6832 it is running on the remote target. */
6833 remote_state *rs = get_remote_state ();
6834 for (const auto &stop_reply : rs->stop_reply_queue)
6835 gdb_assert (stop_reply->ptid != tp->ptid);
6836
c9d22089
SM
6837 const resumed_pending_vcont_info &info
6838 = remote_thr->resumed_pending_vcont_info ();
85ad3aaf 6839
c9d22089
SM
6840 /* Check if we need to send a specific action for this thread. If not,
6841 it will be included in a wildcard resume instead. */
6842 if (info.step || info.sig != GDB_SIGNAL_0
6843 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
6844 vcont_builder.push_action (tp->ptid, info.step, info.sig);
6845
6846 remote_thr->set_resumed ();
85ad3aaf
PA
6847 }
6848
6849 /* Now check whether we can send any process-wide wildcard. This is
6850 to avoid sending a global wildcard in the case nothing is
6851 supposed to be resumed. */
2f63ec5c 6852 bool any_process_wildcard = false;
85ad3aaf 6853
5b6d1e4f 6854 for (inferior *inf : all_non_exited_inferiors (this))
85ad3aaf 6855 {
089354bb 6856 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf 6857 {
2f63ec5c 6858 any_process_wildcard = true;
85ad3aaf
PA
6859 break;
6860 }
6861 }
6862
6863 if (any_process_wildcard)
6864 {
6865 /* If all processes are wildcard-able, then send a single "c"
6866 action, otherwise, send an "all (-1) threads of process"
6867 continue action for each running process, if any. */
6868 if (may_global_wildcard_vcont)
6869 {
f5db4863
PA
6870 vcont_builder.push_action (minus_one_ptid,
6871 false, GDB_SIGNAL_0);
85ad3aaf
PA
6872 }
6873 else
6874 {
5b6d1e4f 6875 for (inferior *inf : all_non_exited_inferiors (this))
85ad3aaf 6876 {
089354bb 6877 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf 6878 {
f2907e49 6879 vcont_builder.push_action (ptid_t (inf->pid),
f5db4863 6880 false, GDB_SIGNAL_0);
85ad3aaf
PA
6881 }
6882 }
6883 }
6884 }
6885
f5db4863 6886 vcont_builder.flush ();
85ad3aaf
PA
6887}
6888
b4b1a226
SM
6889/* Implementation of target_has_pending_events. */
6890
6891bool
6892remote_target::has_pending_events ()
6893{
6894 if (target_can_async_p ())
6895 {
6896 remote_state *rs = get_remote_state ();
6897
6898 if (async_event_handler_marked (rs->remote_async_inferior_event_token))
6899 return true;
6900
6901 /* Note that BUFCNT can be negative, indicating sticky
6902 error. */
6903 if (rs->remote_desc->bufcnt != 0)
6904 return true;
6905 }
6906 return false;
6907}
6908
c906108c 6909\f
43ff13b4 6910
74531fed
PA
6911/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6912 thread, all threads of a remote process, or all threads of all
6913 processes. */
6914
6b8edb51
PA
6915void
6916remote_target::remote_stop_ns (ptid_t ptid)
74531fed
PA
6917{
6918 struct remote_state *rs = get_remote_state ();
8d64371b
TT
6919 char *p = rs->buf.data ();
6920 char *endp = p + get_remote_packet_size ();
74531fed 6921
1192f124
SM
6922 /* If any thread that needs to stop was resumed but pending a vCont
6923 resume, generate a phony stop_reply. However, first check
6924 whether the thread wasn't resumed with a signal. Generating a
6925 phony stop in that case would result in losing the signal. */
6926 bool needs_commit = false;
6927 for (thread_info *tp : all_non_exited_threads (this, ptid))
6928 {
6929 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6930
6931 if (remote_thr->get_resume_state ()
6932 == resume_state::RESUMED_PENDING_VCONT)
6933 {
6934 const resumed_pending_vcont_info &info
6935 = remote_thr->resumed_pending_vcont_info ();
6936 if (info.sig != GDB_SIGNAL_0)
6937 {
6938 /* This signal must be forwarded to the inferior. We
6939 could commit-resume just this thread, but its simpler
6940 to just commit-resume everything. */
6941 needs_commit = true;
6942 break;
6943 }
6944 }
6945 }
6946
6947 if (needs_commit)
6948 commit_resumed ();
6949 else
6950 for (thread_info *tp : all_non_exited_threads (this, ptid))
6951 {
6952 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6953
6954 if (remote_thr->get_resume_state ()
6955 == resume_state::RESUMED_PENDING_VCONT)
6956 {
6957 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
96bbe3ef
TT
6958 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
6959 tp->ptid.lwp (),
6960 pulongest (tp->ptid.tid ()));
1192f124
SM
6961
6962 /* Check that the thread wasn't resumed with a signal.
6963 Generating a phony stop would result in losing the
6964 signal. */
6965 const resumed_pending_vcont_info &info
6966 = remote_thr->resumed_pending_vcont_info ();
6967 gdb_assert (info.sig == GDB_SIGNAL_0);
6968
6969 stop_reply *sr = new stop_reply ();
6970 sr->ptid = tp->ptid;
6971 sr->rs = rs;
183be222 6972 sr->ws.set_stopped (GDB_SIGNAL_0);
1192f124
SM
6973 sr->arch = tp->inf->gdbarch;
6974 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6975 sr->watch_data_address = 0;
6976 sr->core = 0;
6977 this->push_stop_reply (sr);
6978
6979 /* Pretend that this thread was actually resumed on the
6980 remote target, then stopped. If we leave it in the
6981 RESUMED_PENDING_VCONT state and the commit_resumed
6982 method is called while the stop reply is still in the
6983 queue, we'll end up reporting a stop event to the core
6984 for that thread while it is running on the remote
6985 target... that would be bad. */
6986 remote_thr->set_resumed ();
6987 }
6988 }
6989
5b6d1e4f
PA
6990 /* FIXME: This supports_vCont_probed check is a workaround until
6991 packet_support is per-connection. */
6992 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN
6993 || !rs->supports_vCont_probed)
6b8edb51 6994 remote_vcont_probe ();
74531fed 6995
d458bd84 6996 if (!rs->supports_vCont.t)
74531fed
PA
6997 error (_("Remote server does not support stopping threads"));
6998
d7e15655 6999 if (ptid == minus_one_ptid
0e998d96 7000 || (!remote_multi_process_p (rs) && ptid.is_pid ()))
74531fed
PA
7001 p += xsnprintf (p, endp - p, "vCont;t");
7002 else
7003 {
7004 ptid_t nptid;
7005
74531fed
PA
7006 p += xsnprintf (p, endp - p, "vCont;t:");
7007
0e998d96 7008 if (ptid.is_pid ())
74531fed 7009 /* All (-1) threads of process. */
184ea2f7 7010 nptid = ptid_t (ptid.pid (), -1);
74531fed
PA
7011 else
7012 {
7013 /* Small optimization: if we already have a stop reply for
7014 this thread, no use in telling the stub we want this
7015 stopped. */
7016 if (peek_stop_reply (ptid))
7017 return;
7018
7019 nptid = ptid;
7020 }
7021
a9cbf802 7022 write_ptid (p, endp, nptid);
74531fed
PA
7023 }
7024
7025 /* In non-stop, we get an immediate OK reply. The stop reply will
7026 come in asynchronously by notification. */
7027 putpkt (rs->buf);
8d64371b
TT
7028 getpkt (&rs->buf, 0);
7029 if (strcmp (rs->buf.data (), "OK") != 0)
a068643d 7030 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
8d64371b 7031 rs->buf.data ());
74531fed
PA
7032}
7033
bfedc46a
PA
7034/* All-stop version of target_interrupt. Sends a break or a ^C to
7035 interrupt the remote target. It is undefined which thread of which
7036 process reports the interrupt. */
74531fed 7037
6b8edb51
PA
7038void
7039remote_target::remote_interrupt_as ()
74531fed
PA
7040{
7041 struct remote_state *rs = get_remote_state ();
7042
3a29589a
DJ
7043 rs->ctrlc_pending_p = 1;
7044
74531fed 7045 /* If the inferior is stopped already, but the core didn't know
4f626cad 7046 about it yet, just ignore the request. The pending stop events
74531fed 7047 will be collected in remote_wait. */
4f626cad 7048 if (stop_reply_queue_length () > 0)
74531fed
PA
7049 return;
7050
9a7071a8
JB
7051 /* Send interrupt_sequence to remote target. */
7052 send_interrupt_sequence ();
74531fed
PA
7053}
7054
de979965
PA
7055/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7056 the remote target. It is undefined which thread of which process
e42de8c7
PA
7057 reports the interrupt. Throws an error if the packet is not
7058 supported by the server. */
de979965 7059
6b8edb51
PA
7060void
7061remote_target::remote_interrupt_ns ()
de979965
PA
7062{
7063 struct remote_state *rs = get_remote_state ();
8d64371b
TT
7064 char *p = rs->buf.data ();
7065 char *endp = p + get_remote_packet_size ();
de979965
PA
7066
7067 xsnprintf (p, endp - p, "vCtrlC");
7068
7069 /* In non-stop, we get an immediate OK reply. The stop reply will
7070 come in asynchronously by notification. */
7071 putpkt (rs->buf);
8d64371b 7072 getpkt (&rs->buf, 0);
de979965
PA
7073
7074 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
7075 {
7076 case PACKET_OK:
7077 break;
7078 case PACKET_UNKNOWN:
e42de8c7 7079 error (_("No support for interrupting the remote target."));
de979965 7080 case PACKET_ERROR:
8d64371b 7081 error (_("Interrupting target failed: %s"), rs->buf.data ());
de979965 7082 }
de979965
PA
7083}
7084
bfedc46a 7085/* Implement the to_stop function for the remote targets. */
74531fed 7086
f6ac5f3d
PA
7087void
7088remote_target::stop (ptid_t ptid)
c906108c 7089{
2189c312 7090 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
c906108c 7091
6efcd9a8 7092 if (target_is_non_stop_p ())
74531fed 7093 remote_stop_ns (ptid);
c906108c 7094 else
bfedc46a
PA
7095 {
7096 /* We don't currently have a way to transparently pause the
7097 remote target in all-stop mode. Interrupt it instead. */
de979965 7098 remote_interrupt_as ();
bfedc46a
PA
7099 }
7100}
7101
7102/* Implement the to_interrupt function for the remote targets. */
7103
f6ac5f3d
PA
7104void
7105remote_target::interrupt ()
bfedc46a 7106{
2189c312 7107 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
bfedc46a 7108
e42de8c7
PA
7109 if (target_is_non_stop_p ())
7110 remote_interrupt_ns ();
bfedc46a 7111 else
e42de8c7 7112 remote_interrupt_as ();
c906108c
SS
7113}
7114
93692b58
PA
7115/* Implement the to_pass_ctrlc function for the remote targets. */
7116
f6ac5f3d
PA
7117void
7118remote_target::pass_ctrlc ()
93692b58 7119{
2189c312 7120 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
93692b58 7121
2189c312 7122 struct remote_state *rs = get_remote_state ();
93692b58
PA
7123
7124 /* If we're starting up, we're not fully synced yet. Quit
7125 immediately. */
7126 if (rs->starting_up)
7127 quit ();
7128 /* If ^C has already been sent once, offer to disconnect. */
7129 else if (rs->ctrlc_pending_p)
7130 interrupt_query ();
7131 else
e671cd59 7132 target_interrupt ();
93692b58
PA
7133}
7134
c906108c
SS
7135/* Ask the user what to do when an interrupt is received. */
7136
6b8edb51
PA
7137void
7138remote_target::interrupt_query ()
c906108c 7139{
abc56d60 7140 struct remote_state *rs = get_remote_state ();
c906108c 7141
abc56d60 7142 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 7143 {
abc56d60
PA
7144 if (query (_("The target is not responding to interrupt requests.\n"
7145 "Stop debugging it? ")))
74531fed 7146 {
5b6d1e4f 7147 remote_unpush_target (this);
abc56d60 7148 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
7149 }
7150 }
abc56d60
PA
7151 else
7152 {
7153 if (query (_("Interrupted while waiting for the program.\n"
7154 "Give up waiting? ")))
7155 quit ();
7156 }
c906108c
SS
7157}
7158
6426a772
JM
7159/* Enable/disable target terminal ownership. Most targets can use
7160 terminal groups to control terminal ownership. Remote targets are
7161 different in that explicit transfer of ownership to/from GDB/target
23860348 7162 is required. */
6426a772 7163
f6ac5f3d
PA
7164void
7165remote_target::terminal_inferior ()
6426a772 7166{
6426a772
JM
7167 /* NOTE: At this point we could also register our selves as the
7168 recipient of all input. Any characters typed could then be
23860348 7169 passed on down to the target. */
6426a772
JM
7170}
7171
f6ac5f3d
PA
7172void
7173remote_target::terminal_ours ()
6426a772 7174{
6426a772
JM
7175}
7176
176a6961 7177static void
05be00a8 7178remote_console_output (const char *msg)
c906108c 7179{
05be00a8 7180 const char *p;
c906108c 7181
c5aa993b 7182 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
7183 {
7184 char tb[2];
7185 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 7186
c906108c
SS
7187 tb[0] = c;
7188 tb[1] = 0;
da5bd37e 7189 gdb_stdtarg->puts (tb);
c906108c 7190 }
da5bd37e 7191 gdb_stdtarg->flush ();
00db5b94 7192}
74531fed 7193
221e1a37
PA
7194/* Return the length of the stop reply queue. */
7195
6b8edb51
PA
7196int
7197remote_target::stop_reply_queue_length ()
221e1a37 7198{
6b8edb51 7199 remote_state *rs = get_remote_state ();
953edf2b 7200 return rs->stop_reply_queue.size ();
221e1a37
PA
7201}
7202
cb8c24b6 7203static void
6b8edb51 7204remote_notif_stop_parse (remote_target *remote,
bb277751 7205 struct notif_client *self, const char *buf,
722247f1
YQ
7206 struct notif_event *event)
7207{
6b8edb51 7208 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
722247f1
YQ
7209}
7210
7211static void
6b8edb51 7212remote_notif_stop_ack (remote_target *remote,
bb277751 7213 struct notif_client *self, const char *buf,
722247f1
YQ
7214 struct notif_event *event)
7215{
7216 struct stop_reply *stop_reply = (struct stop_reply *) event;
7217
7218 /* acknowledge */
6b8edb51 7219 putpkt (remote, self->ack_command);
722247f1 7220
b0083dd7
PA
7221 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7222 the notification. It was left in the queue because we need to
7223 acknowledge it and pull the rest of the notifications out. */
183be222 7224 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
b0083dd7 7225 remote->push_stop_reply (stop_reply);
722247f1
YQ
7226}
7227
7228static int
6b8edb51
PA
7229remote_notif_stop_can_get_pending_events (remote_target *remote,
7230 struct notif_client *self)
722247f1
YQ
7231{
7232 /* We can't get pending events in remote_notif_process for
7233 notification stop, and we have to do this in remote_wait_ns
7234 instead. If we fetch all queued events from stub, remote stub
7235 may exit and we have no chance to process them back in
7236 remote_wait_ns. */
6b8edb51
PA
7237 remote_state *rs = remote->get_remote_state ();
7238 mark_async_event_handler (rs->remote_async_inferior_event_token);
722247f1
YQ
7239 return 0;
7240}
7241
32603266 7242stop_reply::~stop_reply ()
722247f1 7243{
32603266
TT
7244 for (cached_reg_t &reg : regcache)
7245 xfree (reg.data);
722247f1
YQ
7246}
7247
32603266
TT
7248static notif_event_up
7249remote_notif_stop_alloc_reply ()
722247f1 7250{
32603266 7251 return notif_event_up (new struct stop_reply ());
722247f1
YQ
7252}
7253
7254/* A client of notification Stop. */
7255
7256struct notif_client notif_client_stop =
7257{
7258 "Stop",
7259 "vStopped",
7260 remote_notif_stop_parse,
7261 remote_notif_stop_ack,
7262 remote_notif_stop_can_get_pending_events,
7263 remote_notif_stop_alloc_reply,
f48ff2a7 7264 REMOTE_NOTIF_STOP,
722247f1
YQ
7265};
7266
cbb8991c
DB
7267/* If CONTEXT contains any fork child threads that have not been
7268 reported yet, remove them from the CONTEXT list. If such a
7269 thread exists it is because we are stopped at a fork catchpoint
7270 and have not yet called follow_fork, which will set up the
7271 host-side data structures for the new process. */
7272
6b8edb51
PA
7273void
7274remote_target::remove_new_fork_children (threads_listing_context *context)
cbb8991c 7275{
cbb8991c 7276 struct notif_client *notif = &notif_client_stop;
cbb8991c
DB
7277
7278 /* For any threads stopped at a fork event, remove the corresponding
7279 fork child threads from the CONTEXT list. */
5b6d1e4f 7280 for (thread_info *thread : all_non_exited_threads (this))
cbb8991c 7281 {
28561a65
SM
7282 const target_waitstatus *ws = thread_pending_fork_status (thread);
7283
7284 if (ws == nullptr)
7285 continue;
cbb8991c 7286
28561a65 7287 context->remove_thread (ws->child_ptid ());
cbb8991c
DB
7288 }
7289
7290 /* Check for any pending fork events (not reported or processed yet)
7291 in process PID and remove those fork child threads from the
7292 CONTEXT list as well. */
7293 remote_notif_get_pending_events (notif);
953edf2b 7294 for (auto &event : get_remote_state ()->stop_reply_queue)
183be222 7295 if (event->ws.kind () == TARGET_WAITKIND_FORKED
3890f02a 7296 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
183be222 7297 context->remove_thread (event->ws.child_ptid ());
3890f02a
SM
7298 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7299 context->remove_thread (event->ptid);
85ad3aaf
PA
7300}
7301
2f63ec5c
AB
7302/* Check whether any event pending in the vStopped queue would prevent a
7303 global or process wildcard vCont action. Set *may_global_wildcard to
7304 false if we can't do a global wildcard (vCont;c), and clear the event
7305 inferior's may_wildcard_vcont flag if we can't do a process-wide
7306 wildcard resume (vCont;c:pPID.-1). */
85ad3aaf 7307
6b8edb51
PA
7308void
7309remote_target::check_pending_events_prevent_wildcard_vcont
2f63ec5c 7310 (bool *may_global_wildcard)
85ad3aaf
PA
7311{
7312 struct notif_client *notif = &notif_client_stop;
7313
7314 remote_notif_get_pending_events (notif);
953edf2b
TT
7315 for (auto &event : get_remote_state ()->stop_reply_queue)
7316 {
183be222
SM
7317 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7318 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
953edf2b 7319 continue;
85ad3aaf 7320
183be222
SM
7321 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7322 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
2f63ec5c 7323 *may_global_wildcard = false;
722247f1 7324
953edf2b
TT
7325 /* This may be the first time we heard about this process.
7326 Regardless, we must not do a global wildcard resume, otherwise
7327 we'd resume this process too. */
2f63ec5c 7328 *may_global_wildcard = false;
323fd5b9
PA
7329 if (event->ptid != null_ptid)
7330 {
7331 inferior *inf = find_inferior_ptid (this, event->ptid);
7332 if (inf != NULL)
7333 get_remote_inferior (inf)->may_wildcard_vcont = false;
7334 }
722247f1 7335 }
722247f1
YQ
7336}
7337
f48ff2a7 7338/* Discard all pending stop replies of inferior INF. */
c906108c 7339
6b8edb51
PA
7340void
7341remote_target::discard_pending_stop_replies (struct inferior *inf)
c906108c 7342{
f48ff2a7
YQ
7343 struct stop_reply *reply;
7344 struct remote_state *rs = get_remote_state ();
7345 struct remote_notif_state *rns = rs->notif_state;
7346
7347 /* This function can be notified when an inferior exists. When the
7348 target is not remote, the notification state is NULL. */
7349 if (rs->remote_desc == NULL)
7350 return;
7351
7352 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 7353
74531fed 7354 /* Discard the in-flight notification. */
e99b03dc 7355 if (reply != NULL && reply->ptid.pid () == inf->pid)
74531fed 7356 {
b0083dd7
PA
7357 /* Leave the notification pending, since the server expects that
7358 we acknowledge it with vStopped. But clear its contents, so
7359 that later on when we acknowledge it, we also discard it. */
df5ad102
SM
7360 remote_debug_printf
7361 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7362 reply->ptid.to_string().c_str(),
7363 reply->ws.to_string ().c_str ());
183be222 7364 reply->ws.set_ignore ();
74531fed 7365 }
c906108c 7366
74531fed
PA
7367 /* Discard the stop replies we have already pulled with
7368 vStopped. */
953edf2b
TT
7369 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7370 rs->stop_reply_queue.end (),
7371 [=] (const stop_reply_up &event)
7372 {
7373 return event->ptid.pid () == inf->pid;
7374 });
df5ad102
SM
7375 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7376 remote_debug_printf
7377 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7378 reply->ptid.to_string().c_str(),
7379 reply->ws.to_string ().c_str ());
953edf2b 7380 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
bcc75809
YQ
7381}
7382
7383/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7 7384
6b8edb51
PA
7385void
7386remote_target::discard_pending_stop_replies_in_queue ()
f48ff2a7 7387{
6b8edb51 7388 remote_state *rs = get_remote_state ();
f48ff2a7 7389
f48ff2a7
YQ
7390 /* Discard the stop replies we have already pulled with
7391 vStopped. */
953edf2b
TT
7392 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7393 rs->stop_reply_queue.end (),
7394 [=] (const stop_reply_up &event)
7395 {
7396 return event->rs == rs;
7397 });
7398 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
74531fed 7399}
43ff13b4 7400
722247f1
YQ
7401/* Remove the first reply in 'stop_reply_queue' which matches
7402 PTID. */
2e9f7625 7403
6b8edb51
PA
7404struct stop_reply *
7405remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 7406{
953edf2b 7407 remote_state *rs = get_remote_state ();
722247f1 7408
953edf2b
TT
7409 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7410 rs->stop_reply_queue.end (),
7411 [=] (const stop_reply_up &event)
7412 {
7413 return event->ptid.matches (ptid);
7414 });
7415 struct stop_reply *result;
7416 if (iter == rs->stop_reply_queue.end ())
7417 result = nullptr;
7418 else
7419 {
7420 result = iter->release ();
7421 rs->stop_reply_queue.erase (iter);
7422 }
722247f1 7423
722247f1 7424 if (notif_debug)
6cb06a8c
TT
7425 gdb_printf (gdb_stdlog,
7426 "notif: discard queued event: 'Stop' in %s\n",
7427 ptid.to_string ().c_str ());
a744cf53 7428
953edf2b 7429 return result;
74531fed 7430}
75c99385 7431
74531fed
PA
7432/* Look for a queued stop reply belonging to PTID. If one is found,
7433 remove it from the queue, and return it. Returns NULL if none is
7434 found. If there are still queued events left to process, tell the
7435 event loop to get back to target_wait soon. */
e24a49d8 7436
6b8edb51
PA
7437struct stop_reply *
7438remote_target::queued_stop_reply (ptid_t ptid)
74531fed 7439{
953edf2b 7440 remote_state *rs = get_remote_state ();
722247f1 7441 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 7442
4f626cad 7443 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
6b8edb51 7444 {
6b8edb51
PA
7445 /* There's still at least an event left. */
7446 mark_async_event_handler (rs->remote_async_inferior_event_token);
7447 }
74531fed 7448
722247f1 7449 return r;
74531fed
PA
7450}
7451
7452/* Push a fully parsed stop reply in the stop reply queue. Since we
7453 know that we now have at least one queued event left to pass to the
7454 core side, tell the event loop to get back to target_wait soon. */
7455
6b8edb51
PA
7456void
7457remote_target::push_stop_reply (struct stop_reply *new_event)
74531fed 7458{
6b8edb51 7459 remote_state *rs = get_remote_state ();
953edf2b 7460 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
74531fed 7461
722247f1 7462 if (notif_debug)
6cb06a8c
TT
7463 gdb_printf (gdb_stdlog,
7464 "notif: push 'Stop' %s to queue %d\n",
7465 new_event->ptid.to_string ().c_str (),
7466 int (rs->stop_reply_queue.size ()));
74531fed 7467
4f626cad
AB
7468 /* Mark the pending event queue only if async mode is currently enabled.
7469 If async mode is not currently enabled, then, if it later becomes
7470 enabled, and there are events in this queue, we will mark the event
7471 token at that point, see remote_target::async. */
7472 if (target_is_async_p ())
7473 mark_async_event_handler (rs->remote_async_inferior_event_token);
74531fed
PA
7474}
7475
7476/* Returns true if we have a stop reply for PTID. */
7477
6b8edb51
PA
7478int
7479remote_target::peek_stop_reply (ptid_t ptid)
74531fed 7480{
6b8edb51 7481 remote_state *rs = get_remote_state ();
953edf2b
TT
7482 for (auto &event : rs->stop_reply_queue)
7483 if (ptid == event->ptid
183be222 7484 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
953edf2b
TT
7485 return 1;
7486 return 0;
74531fed
PA
7487}
7488
26d56a93
SL
7489/* Helper for remote_parse_stop_reply. Return nonzero if the substring
7490 starting with P and ending with PEND matches PREFIX. */
7491
7492static int
7493strprefix (const char *p, const char *pend, const char *prefix)
7494{
7495 for ( ; p < pend; p++, prefix++)
7496 if (*p != *prefix)
7497 return 0;
7498 return *prefix == '\0';
7499}
7500
74531fed
PA
7501/* Parse the stop reply in BUF. Either the function succeeds, and the
7502 result is stored in EVENT, or throws an error. */
7503
6b8edb51 7504void
bb277751 7505remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
74531fed 7506{
5cd63fda 7507 remote_arch_state *rsa = NULL;
74531fed 7508 ULONGEST addr;
256642e8 7509 const char *p;
94585166 7510 int skipregs = 0;
74531fed
PA
7511
7512 event->ptid = null_ptid;
bcc75809 7513 event->rs = get_remote_state ();
183be222 7514 event->ws.set_ignore ();
f7e6eed5 7515 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
32603266 7516 event->regcache.clear ();
dc146f7c 7517 event->core = -1;
74531fed
PA
7518
7519 switch (buf[0])
7520 {
7521 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
7522 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7523 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7524 ss = signal number
7525 n... = register number
7526 r... = register contents
7527 */
7528
7529 p = &buf[3]; /* after Txx */
7530 while (*p)
7531 {
256642e8 7532 const char *p1;
cea39f65 7533 int fieldsize;
43ff13b4 7534
1f10ba14
PA
7535 p1 = strchr (p, ':');
7536 if (p1 == NULL)
7537 error (_("Malformed packet(a) (missing colon): %s\n\
7538Packet: '%s'\n"),
7539 p, buf);
7540 if (p == p1)
7541 error (_("Malformed packet(a) (missing register number): %s\n\
7542Packet: '%s'\n"),
7543 p, buf);
3c3bea1c 7544
1f10ba14
PA
7545 /* Some "registers" are actually extended stop information.
7546 Note if you're adding a new entry here: GDB 7.9 and
7547 earlier assume that all register "numbers" that start
7548 with an hex digit are real register numbers. Make sure
7549 the server only sends such a packet if it knows the
7550 client understands it. */
c8e38a49 7551
26d56a93 7552 if (strprefix (p, p1, "thread"))
1f10ba14 7553 event->ptid = read_ptid (++p1, &p);
82075af2
JS
7554 else if (strprefix (p, p1, "syscall_entry"))
7555 {
7556 ULONGEST sysno;
7557
82075af2 7558 p = unpack_varlen_hex (++p1, &sysno);
183be222 7559 event->ws.set_syscall_entry ((int) sysno);
82075af2
JS
7560 }
7561 else if (strprefix (p, p1, "syscall_return"))
7562 {
7563 ULONGEST sysno;
7564
82075af2 7565 p = unpack_varlen_hex (++p1, &sysno);
183be222 7566 event->ws.set_syscall_return ((int) sysno);
82075af2 7567 }
26d56a93
SL
7568 else if (strprefix (p, p1, "watch")
7569 || strprefix (p, p1, "rwatch")
7570 || strprefix (p, p1, "awatch"))
cea39f65 7571 {
f7e6eed5 7572 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
7573 p = unpack_varlen_hex (++p1, &addr);
7574 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 7575 }
26d56a93 7576 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
7577 {
7578 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7579
7580 /* Make sure the stub doesn't forget to indicate support
7581 with qSupported. */
7582 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7583 error (_("Unexpected swbreak stop reason"));
7584
7585 /* The value part is documented as "must be empty",
7586 though we ignore it, in case we ever decide to make
7587 use of it in a backward compatible way. */
8424cc97 7588 p = strchrnul (p1 + 1, ';');
f7e6eed5 7589 }
26d56a93 7590 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
7591 {
7592 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7593
7594 /* Make sure the stub doesn't forget to indicate support
7595 with qSupported. */
7596 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7597 error (_("Unexpected hwbreak stop reason"));
7598
7599 /* See above. */
8424cc97 7600 p = strchrnul (p1 + 1, ';');
f7e6eed5 7601 }
26d56a93 7602 else if (strprefix (p, p1, "library"))
cea39f65 7603 {
183be222 7604 event->ws.set_loaded ();
8424cc97 7605 p = strchrnul (p1 + 1, ';');
1f10ba14 7606 }
26d56a93 7607 else if (strprefix (p, p1, "replaylog"))
1f10ba14 7608 {
183be222 7609 event->ws.set_no_history ();
1f10ba14
PA
7610 /* p1 will indicate "begin" or "end", but it makes
7611 no difference for now, so ignore it. */
8424cc97 7612 p = strchrnul (p1 + 1, ';');
1f10ba14 7613 }
26d56a93 7614 else if (strprefix (p, p1, "core"))
1f10ba14
PA
7615 {
7616 ULONGEST c;
a744cf53 7617
1f10ba14
PA
7618 p = unpack_varlen_hex (++p1, &c);
7619 event->core = c;
cea39f65 7620 }
26d56a93 7621 else if (strprefix (p, p1, "fork"))
183be222 7622 event->ws.set_forked (read_ptid (++p1, &p));
26d56a93 7623 else if (strprefix (p, p1, "vfork"))
183be222 7624 event->ws.set_vforked (read_ptid (++p1, &p));
26d56a93 7625 else if (strprefix (p, p1, "vforkdone"))
c269dbdb 7626 {
183be222 7627 event->ws.set_vfork_done ();
8424cc97 7628 p = strchrnul (p1 + 1, ';');
c269dbdb 7629 }
6ab24463 7630 else if (strprefix (p, p1, "exec"))
94585166
DB
7631 {
7632 ULONGEST ignored;
94585166
DB
7633 int pathlen;
7634
7635 /* Determine the length of the execd pathname. */
7636 p = unpack_varlen_hex (++p1, &ignored);
7637 pathlen = (p - p1) / 2;
7638
7639 /* Save the pathname for event reporting and for
7640 the next run command. */
183be222 7641 gdb::unique_xmalloc_ptr<char> pathname
c6321f19
TT
7642 ((char *) xmalloc (pathlen + 1));
7643 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
183be222 7644 pathname.get ()[pathlen] = '\0';
94585166
DB
7645
7646 /* This is freed during event handling. */
183be222 7647 event->ws.set_execd (std::move (pathname));
94585166
DB
7648
7649 /* Skip the registers included in this packet, since
7650 they may be for an architecture different from the
7651 one used by the original program. */
7652 skipregs = 1;
7653 }
65706a29
PA
7654 else if (strprefix (p, p1, "create"))
7655 {
183be222 7656 event->ws.set_thread_created ();
8424cc97 7657 p = strchrnul (p1 + 1, ';');
65706a29 7658 }
cea39f65
MS
7659 else
7660 {
1f10ba14 7661 ULONGEST pnum;
256642e8 7662 const char *p_temp;
1f10ba14 7663
94585166
DB
7664 if (skipregs)
7665 {
8424cc97 7666 p = strchrnul (p1 + 1, ';');
94585166
DB
7667 p++;
7668 continue;
7669 }
7670
1f10ba14
PA
7671 /* Maybe a real ``P'' register number. */
7672 p_temp = unpack_varlen_hex (p, &pnum);
7673 /* If the first invalid character is the colon, we got a
7674 register number. Otherwise, it's an unknown stop
7675 reason. */
7676 if (p_temp == p1)
7677 {
5cd63fda
PA
7678 /* If we haven't parsed the event's thread yet, find
7679 it now, in order to find the architecture of the
7680 reported expedited registers. */
7681 if (event->ptid == null_ptid)
7682 {
24ed6739
AB
7683 /* If there is no thread-id information then leave
7684 the event->ptid as null_ptid. Later in
7685 process_stop_reply we will pick a suitable
7686 thread. */
5cd63fda
PA
7687 const char *thr = strstr (p1 + 1, ";thread:");
7688 if (thr != NULL)
7689 event->ptid = read_ptid (thr + strlen (";thread:"),
7690 NULL);
5cd63fda
PA
7691 }
7692
7693 if (rsa == NULL)
7694 {
5b6d1e4f
PA
7695 inferior *inf
7696 = (event->ptid == null_ptid
7697 ? NULL
7698 : find_inferior_ptid (this, event->ptid));
5cd63fda
PA
7699 /* If this is the first time we learn anything
7700 about this process, skip the registers
7701 included in this packet, since we don't yet
7702 know which architecture to use to parse them.
7703 We'll determine the architecture later when
7704 we process the stop reply and retrieve the
7705 target description, via
7706 remote_notice_new_inferior ->
7707 post_create_inferior. */
7708 if (inf == NULL)
7709 {
7710 p = strchrnul (p1 + 1, ';');
7711 p++;
7712 continue;
7713 }
7714
7715 event->arch = inf->gdbarch;
9d6eea31 7716 rsa = event->rs->get_remote_arch_state (event->arch);
5cd63fda
PA
7717 }
7718
7719 packet_reg *reg
7720 = packet_reg_from_pnum (event->arch, rsa, pnum);
1f10ba14 7721 cached_reg_t cached_reg;
43ff13b4 7722
1f10ba14
PA
7723 if (reg == NULL)
7724 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 7725Packet: '%s'\n"),
1f10ba14 7726 hex_string (pnum), p, buf);
c8e38a49 7727
1f10ba14 7728 cached_reg.num = reg->regnum;
d1dff226 7729 cached_reg.data = (gdb_byte *)
5cd63fda 7730 xmalloc (register_size (event->arch, reg->regnum));
4100683b 7731
1f10ba14
PA
7732 p = p1 + 1;
7733 fieldsize = hex2bin (p, cached_reg.data,
5cd63fda 7734 register_size (event->arch, reg->regnum));
1f10ba14 7735 p += 2 * fieldsize;
5cd63fda 7736 if (fieldsize < register_size (event->arch, reg->regnum))
1f10ba14 7737 warning (_("Remote reply is too short: %s"), buf);
74531fed 7738
32603266 7739 event->regcache.push_back (cached_reg);
1f10ba14
PA
7740 }
7741 else
7742 {
7743 /* Not a number. Silently skip unknown optional
7744 info. */
8424cc97 7745 p = strchrnul (p1 + 1, ';');
1f10ba14 7746 }
cea39f65 7747 }
c8e38a49 7748
cea39f65
MS
7749 if (*p != ';')
7750 error (_("Remote register badly formatted: %s\nhere: %s"),
7751 buf, p);
7752 ++p;
7753 }
5b5596ff 7754
183be222 7755 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
5b5596ff
PA
7756 break;
7757
c8e38a49
PA
7758 /* fall through */
7759 case 'S': /* Old style status, just signal only. */
3a09da41
PA
7760 {
7761 int sig;
7762
3a09da41
PA
7763 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7764 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
183be222 7765 event->ws.set_stopped ((enum gdb_signal) sig);
3a09da41 7766 else
183be222 7767 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
3a09da41 7768 }
c8e38a49 7769 break;
65706a29
PA
7770 case 'w': /* Thread exited. */
7771 {
65706a29
PA
7772 ULONGEST value;
7773
65706a29 7774 p = unpack_varlen_hex (&buf[1], &value);
183be222 7775 event->ws.set_thread_exited (value);
65706a29
PA
7776 if (*p != ';')
7777 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 7778 event->ptid = read_ptid (++p, NULL);
65706a29
PA
7779 break;
7780 }
c8e38a49
PA
7781 case 'W': /* Target exited. */
7782 case 'X':
7783 {
c8e38a49 7784 ULONGEST value;
82f73884 7785
c8e38a49
PA
7786 /* GDB used to accept only 2 hex chars here. Stubs should
7787 only send more if they detect GDB supports multi-process
7788 support. */
7789 p = unpack_varlen_hex (&buf[1], &value);
82f73884 7790
c8e38a49
PA
7791 if (buf[0] == 'W')
7792 {
7793 /* The remote process exited. */
183be222 7794 event->ws.set_exited (value);
c8e38a49
PA
7795 }
7796 else
7797 {
7798 /* The remote process exited with a signal. */
3a09da41 7799 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
183be222 7800 event->ws.set_signalled ((enum gdb_signal) value);
3a09da41 7801 else
183be222 7802 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
c8e38a49 7803 }
82f73884 7804
e7af6c70
TBA
7805 /* If no process is specified, return null_ptid, and let the
7806 caller figure out the right process to use. */
7807 int pid = 0;
c8e38a49
PA
7808 if (*p == '\0')
7809 ;
7810 else if (*p == ';')
7811 {
7812 p++;
7813
0b24eb2d 7814 if (*p == '\0')
82f73884 7815 ;
61012eef 7816 else if (startswith (p, "process:"))
82f73884 7817 {
c8e38a49 7818 ULONGEST upid;
a744cf53 7819
c8e38a49
PA
7820 p += sizeof ("process:") - 1;
7821 unpack_varlen_hex (p, &upid);
7822 pid = upid;
82f73884
PA
7823 }
7824 else
7825 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 7826 }
c8e38a49
PA
7827 else
7828 error (_("unknown stop reply packet: %s"), buf);
f2907e49 7829 event->ptid = ptid_t (pid);
74531fed
PA
7830 }
7831 break;
f2faf941 7832 case 'N':
183be222 7833 event->ws.set_no_resumed ();
f2faf941
PA
7834 event->ptid = minus_one_ptid;
7835 break;
74531fed 7836 }
74531fed
PA
7837}
7838
722247f1
YQ
7839/* When the stub wants to tell GDB about a new notification reply, it
7840 sends a notification (%Stop, for example). Those can come it at
7841 any time, hence, we have to make sure that any pending
7842 putpkt/getpkt sequence we're making is finished, before querying
7843 the stub for more events with the corresponding ack command
7844 (vStopped, for example). E.g., if we started a vStopped sequence
7845 immediately upon receiving the notification, something like this
7846 could happen:
74531fed
PA
7847
7848 1.1) --> Hg 1
7849 1.2) <-- OK
7850 1.3) --> g
7851 1.4) <-- %Stop
7852 1.5) --> vStopped
7853 1.6) <-- (registers reply to step #1.3)
7854
7855 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7856 query.
7857
796cb314 7858 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
7859 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7860 doing whatever we were doing:
7861
7862 2.1) --> Hg 1
7863 2.2) <-- OK
7864 2.3) --> g
7865 2.4) <-- %Stop
7866 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7867 2.5) <-- (registers reply to step #2.3)
7868
85102364 7869 Eventually after step #2.5, we return to the event loop, which
74531fed
PA
7870 notices there's an event on the
7871 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7872 associated callback --- the function below. At this point, we're
7873 always safe to start a vStopped sequence. :
7874
7875 2.6) --> vStopped
7876 2.7) <-- T05 thread:2
7877 2.8) --> vStopped
7878 2.9) --> OK
7879*/
7880
722247f1 7881void
6b8edb51 7882remote_target::remote_notif_get_pending_events (notif_client *nc)
74531fed
PA
7883{
7884 struct remote_state *rs = get_remote_state ();
74531fed 7885
f48ff2a7 7886 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 7887 {
722247f1 7888 if (notif_debug)
6cb06a8c
TT
7889 gdb_printf (gdb_stdlog,
7890 "notif: process: '%s' ack pending event\n",
7891 nc->name);
74531fed 7892
722247f1 7893 /* acknowledge */
8d64371b
TT
7894 nc->ack (this, nc, rs->buf.data (),
7895 rs->notif_state->pending_event[nc->id]);
f48ff2a7 7896 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
7897
7898 while (1)
7899 {
8d64371b
TT
7900 getpkt (&rs->buf, 0);
7901 if (strcmp (rs->buf.data (), "OK") == 0)
74531fed
PA
7902 break;
7903 else
8d64371b 7904 remote_notif_ack (this, nc, rs->buf.data ());
74531fed
PA
7905 }
7906 }
722247f1
YQ
7907 else
7908 {
7909 if (notif_debug)
6cb06a8c
TT
7910 gdb_printf (gdb_stdlog,
7911 "notif: process: '%s' no pending reply\n",
7912 nc->name);
722247f1 7913 }
74531fed
PA
7914}
7915
6b8edb51
PA
7916/* Wrapper around remote_target::remote_notif_get_pending_events to
7917 avoid having to export the whole remote_target class. */
7918
7919void
7920remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7921{
7922 remote->remote_notif_get_pending_events (nc);
7923}
7924
8f66807b
AB
7925/* Called from process_stop_reply when the stop packet we are responding
7926 to didn't include a process-id or thread-id. STATUS is the stop event
7927 we are responding to.
7928
7929 It is the task of this function to select a suitable thread (or process)
7930 and return its ptid, this is the thread (or process) we will assume the
7931 stop event came from.
7932
7933 In some cases there isn't really any choice about which thread (or
7934 process) is selected, a basic remote with a single process containing a
7935 single thread might choose not to send any process-id or thread-id in
7936 its stop packets, this function will select and return the one and only
7937 thread.
7938
7939 However, if a target supports multiple threads (or processes) and still
7940 doesn't include a thread-id (or process-id) in its stop packet then
7941 first, this is a badly behaving target, and second, we're going to have
7942 to select a thread (or process) at random and use that. This function
7943 will print a warning to the user if it detects that there is the
7944 possibility that GDB is guessing which thread (or process) to
7945 report.
7946
7947 Note that this is called before GDB fetches the updated thread list from the
7948 target. So it's possible for the stop reply to be ambiguous and for GDB to
7949 not realize it. For example, if there's initially one thread, the target
7950 spawns a second thread, and then sends a stop reply without an id that
7951 concerns the first thread. GDB will assume the stop reply is about the
7952 first thread - the only thread it knows about - without printing a warning.
7953 Anyway, if the remote meant for the stop reply to be about the second thread,
7954 then it would be really broken, because GDB doesn't know about that thread
7955 yet. */
74531fed 7956
6b8edb51 7957ptid_t
8f66807b 7958remote_target::select_thread_for_ambiguous_stop_reply
c272a98c 7959 (const target_waitstatus &status)
74531fed 7960{
4351271e
AB
7961 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7962
8f66807b
AB
7963 /* Some stop events apply to all threads in an inferior, while others
7964 only apply to a single thread. */
7965 bool process_wide_stop
c272a98c
SM
7966 = (status.kind () == TARGET_WAITKIND_EXITED
7967 || status.kind () == TARGET_WAITKIND_SIGNALLED);
74531fed 7968
4351271e
AB
7969 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
7970
8f66807b
AB
7971 thread_info *first_resumed_thread = nullptr;
7972 bool ambiguous = false;
74531fed 7973
8f66807b
AB
7974 /* Consider all non-exited threads of the target, find the first resumed
7975 one. */
7976 for (thread_info *thr : all_non_exited_threads (this))
24ed6739 7977 {
8f66807b 7978 remote_thread_info *remote_thr = get_remote_thread_info (thr);
cada5fc9 7979
a6c11cbb 7980 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8f66807b 7981 continue;
24ed6739 7982
8f66807b
AB
7983 if (first_resumed_thread == nullptr)
7984 first_resumed_thread = thr;
7985 else if (!process_wide_stop
7986 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
7987 ambiguous = true;
7988 }
7989
b622494e
AB
7990 gdb_assert (first_resumed_thread != nullptr);
7991
4351271e
AB
7992 remote_debug_printf ("first resumed thread is %s",
7993 pid_to_str (first_resumed_thread->ptid).c_str ());
7994 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
7995
8f66807b
AB
7996 /* Warn if the remote target is sending ambiguous stop replies. */
7997 if (ambiguous)
7998 {
7999 static bool warned = false;
8000
8001 if (!warned)
8002 {
8003 /* If you are seeing this warning then the remote target has
8004 stopped without specifying a thread-id, but the target
8005 does have multiple threads (or inferiors), and so GDB is
8006 having to guess which thread stopped.
8007
8008 Examples of what might cause this are the target sending
8009 and 'S' stop packet, or a 'T' stop packet and not
8010 including a thread-id.
8011
8012 Additionally, the target might send a 'W' or 'X packet
8013 without including a process-id, when the target has
8014 multiple running inferiors. */
8015 if (process_wide_stop)
8016 warning (_("multi-inferior target stopped without "
8017 "sending a process-id, using first "
8018 "non-exited inferior"));
cada5fc9 8019 else
8f66807b
AB
8020 warning (_("multi-threaded target stopped without "
8021 "sending a thread-id, using first "
8022 "non-exited thread"));
8023 warned = true;
24ed6739 8024 }
24ed6739 8025 }
74531fed 8026
8f66807b
AB
8027 /* If this is a stop for all threads then don't use a particular threads
8028 ptid, instead create a new ptid where only the pid field is set. */
8029 if (process_wide_stop)
8030 return ptid_t (first_resumed_thread->ptid.pid ());
8031 else
8032 return first_resumed_thread->ptid;
8033}
8034
8035/* Called when it is decided that STOP_REPLY holds the info of the
8036 event that is to be returned to the core. This function always
8037 destroys STOP_REPLY. */
8038
8039ptid_t
8040remote_target::process_stop_reply (struct stop_reply *stop_reply,
8041 struct target_waitstatus *status)
8042{
8043 *status = stop_reply->ws;
8044 ptid_t ptid = stop_reply->ptid;
8045
8046 /* If no thread/process was reported by the stub then select a suitable
8047 thread/process. */
8048 if (ptid == null_ptid)
c272a98c 8049 ptid = select_thread_for_ambiguous_stop_reply (*status);
8f66807b
AB
8050 gdb_assert (ptid != null_ptid);
8051
183be222
SM
8052 if (status->kind () != TARGET_WAITKIND_EXITED
8053 && status->kind () != TARGET_WAITKIND_SIGNALLED
8054 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
74531fed 8055 {
5f3563ea 8056 /* Expedited registers. */
32603266 8057 if (!stop_reply->regcache.empty ())
5f3563ea 8058 {
217f1f79 8059 struct regcache *regcache
5b6d1e4f 8060 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
5f3563ea 8061
32603266
TT
8062 for (cached_reg_t &reg : stop_reply->regcache)
8063 {
8064 regcache->raw_supply (reg.num, reg.data);
8065 xfree (reg.data);
8066 }
d1dff226 8067
32603266 8068 stop_reply->regcache.clear ();
5f3563ea 8069 }
74531fed 8070
8a82de58 8071 remote_notice_new_inferior (ptid, false);
5b6d1e4f 8072 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
799a2abe
PA
8073 remote_thr->core = stop_reply->core;
8074 remote_thr->stop_reason = stop_reply->stop_reason;
8075 remote_thr->watch_data_address = stop_reply->watch_data_address;
c9d22089
SM
8076
8077 if (target_is_non_stop_p ())
8078 {
8079 /* If the target works in non-stop mode, a stop-reply indicates that
8080 only this thread stopped. */
8081 remote_thr->set_not_resumed ();
8082 }
8083 else
8084 {
8085 /* If the target works in all-stop mode, a stop-reply indicates that
8086 all the target's threads stopped. */
8087 for (thread_info *tp : all_non_exited_threads (this))
8088 get_remote_thread_info (tp)->set_not_resumed ();
8089 }
74531fed
PA
8090 }
8091
32603266 8092 delete stop_reply;
74531fed
PA
8093 return ptid;
8094}
8095
8096/* The non-stop mode version of target_wait. */
8097
6b8edb51 8098ptid_t
b60cea74
TT
8099remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8100 target_wait_flags options)
74531fed
PA
8101{
8102 struct remote_state *rs = get_remote_state ();
74531fed
PA
8103 struct stop_reply *stop_reply;
8104 int ret;
fee9eda9 8105 int is_notif = 0;
74531fed
PA
8106
8107 /* If in non-stop mode, get out of getpkt even if a
8108 notification is received. */
8109
8d64371b 8110 ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
74531fed
PA
8111 while (1)
8112 {
fee9eda9 8113 if (ret != -1 && !is_notif)
74531fed
PA
8114 switch (rs->buf[0])
8115 {
8116 case 'E': /* Error of some sort. */
8117 /* We're out of sync with the target now. Did it continue
8118 or not? We can't tell which thread it was in non-stop,
8119 so just ignore this. */
8d64371b 8120 warning (_("Remote failure reply: %s"), rs->buf.data ());
74531fed
PA
8121 break;
8122 case 'O': /* Console output. */
8d64371b 8123 remote_console_output (&rs->buf[1]);
74531fed
PA
8124 break;
8125 default:
8d64371b 8126 warning (_("Invalid remote reply: %s"), rs->buf.data ());
74531fed
PA
8127 break;
8128 }
8129
8130 /* Acknowledge a pending stop reply that may have arrived in the
8131 mean time. */
f48ff2a7 8132 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 8133 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
8134
8135 /* If indeed we noticed a stop reply, we're done. */
8136 stop_reply = queued_stop_reply (ptid);
8137 if (stop_reply != NULL)
8138 return process_stop_reply (stop_reply, status);
8139
47608cb1 8140 /* Still no event. If we're just polling for an event, then
74531fed 8141 return to the event loop. */
47608cb1 8142 if (options & TARGET_WNOHANG)
74531fed 8143 {
183be222 8144 status->set_ignore ();
74531fed
PA
8145 return minus_one_ptid;
8146 }
8147
47608cb1 8148 /* Otherwise do a blocking wait. */
8d64371b 8149 ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
74531fed
PA
8150 }
8151}
8152
31ba933e
PA
8153/* Return the first resumed thread. */
8154
8155static ptid_t
5b6d1e4f 8156first_remote_resumed_thread (remote_target *target)
31ba933e 8157{
5b6d1e4f 8158 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
7846f3aa 8159 if (tp->resumed ())
31ba933e
PA
8160 return tp->ptid;
8161 return null_ptid;
8162}
8163
74531fed
PA
8164/* Wait until the remote machine stops, then return, storing status in
8165 STATUS just as `wait' would. */
8166
6b8edb51 8167ptid_t
b60cea74
TT
8168remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8169 target_wait_flags options)
74531fed
PA
8170{
8171 struct remote_state *rs = get_remote_state ();
74531fed 8172 ptid_t event_ptid = null_ptid;
cea39f65 8173 char *buf;
74531fed
PA
8174 struct stop_reply *stop_reply;
8175
47608cb1
PA
8176 again:
8177
183be222 8178 status->set_ignore ();
74531fed
PA
8179
8180 stop_reply = queued_stop_reply (ptid);
8181 if (stop_reply != NULL)
4f626cad
AB
8182 {
8183 /* None of the paths that push a stop reply onto the queue should
8184 have set the waiting_for_stop_reply flag. */
8185 gdb_assert (!rs->waiting_for_stop_reply);
8186 event_ptid = process_stop_reply (stop_reply, status);
8187 }
74531fed
PA
8188 else
8189 {
567420d1 8190 int forever = ((options & TARGET_WNOHANG) == 0
6b8edb51 8191 && rs->wait_forever_enabled_p);
567420d1
PA
8192
8193 if (!rs->waiting_for_stop_reply)
8194 {
183be222 8195 status->set_no_resumed ();
567420d1
PA
8196 return minus_one_ptid;
8197 }
74531fed 8198
74531fed
PA
8199 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8200 _never_ wait for ever -> test on target_is_async_p().
8201 However, before we do that we need to ensure that the caller
8202 knows how to take the target into/out of async mode. */
4f626cad
AB
8203 int is_notif;
8204 int ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
722247f1
YQ
8205
8206 /* GDB gets a notification. Return to core as this event is
8207 not interesting. */
8208 if (ret != -1 && is_notif)
8209 return minus_one_ptid;
567420d1
PA
8210
8211 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8212 return minus_one_ptid;
74531fed 8213
4f626cad 8214 buf = rs->buf.data ();
74531fed 8215
4f626cad
AB
8216 /* Assume that the target has acknowledged Ctrl-C unless we receive
8217 an 'F' or 'O' packet. */
8218 if (buf[0] != 'F' && buf[0] != 'O')
8219 rs->ctrlc_pending_p = 0;
3a29589a 8220
4f626cad
AB
8221 switch (buf[0])
8222 {
8223 case 'E': /* Error of some sort. */
8224 /* We're out of sync with the target now. Did it continue or
8225 not? Not is more likely, so report a stop. */
8226 rs->waiting_for_stop_reply = 0;
29090fb6 8227
4f626cad
AB
8228 warning (_("Remote failure reply: %s"), buf);
8229 status->set_stopped (GDB_SIGNAL_0);
8230 break;
8231 case 'F': /* File-I/O request. */
8232 /* GDB may access the inferior memory while handling the File-I/O
8233 request, but we don't want GDB accessing memory while waiting
8234 for a stop reply. See the comments in putpkt_binary. Set
8235 waiting_for_stop_reply to 0 temporarily. */
8236 rs->waiting_for_stop_reply = 0;
8237 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8238 rs->ctrlc_pending_p = 0;
8239 /* GDB handled the File-I/O request, and the target is running
8240 again. Keep waiting for events. */
8241 rs->waiting_for_stop_reply = 1;
8242 break;
8243 case 'N': case 'T': case 'S': case 'X': case 'W':
8244 {
8245 /* There is a stop reply to handle. */
8246 rs->waiting_for_stop_reply = 0;
29090fb6 8247
4f626cad
AB
8248 stop_reply
8249 = (struct stop_reply *) remote_notif_parse (this,
8250 &notif_client_stop,
8251 rs->buf.data ());
74531fed 8252
4f626cad
AB
8253 event_ptid = process_stop_reply (stop_reply, status);
8254 break;
8255 }
8256 case 'O': /* Console output. */
8257 remote_console_output (buf + 1);
8258 break;
8259 case '\0':
8260 if (rs->last_sent_signal != GDB_SIGNAL_0)
8261 {
8262 /* Zero length reply means that we tried 'S' or 'C' and the
8263 remote system doesn't support it. */
8264 target_terminal::ours_for_output ();
6cb06a8c 8265 gdb_printf
4f626cad
AB
8266 ("Can't send signals to this remote system. %s not sent.\n",
8267 gdb_signal_to_name (rs->last_sent_signal));
8268 rs->last_sent_signal = GDB_SIGNAL_0;
8269 target_terminal::inferior ();
8270
8271 strcpy (buf, rs->last_sent_step ? "s" : "c");
8272 putpkt (buf);
8273 break;
8274 }
8275 /* fallthrough */
8276 default:
8277 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 8278 break;
43ff13b4
JM
8279 }
8280 }
c8e38a49 8281
183be222 8282 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
f2faf941 8283 return minus_one_ptid;
183be222 8284 else if (status->kind () == TARGET_WAITKIND_IGNORE)
47608cb1
PA
8285 {
8286 /* Nothing interesting happened. If we're doing a non-blocking
8287 poll, we're done. Otherwise, go back to waiting. */
8288 if (options & TARGET_WNOHANG)
8289 return minus_one_ptid;
8290 else
8291 goto again;
8292 }
183be222
SM
8293 else if (status->kind () != TARGET_WAITKIND_EXITED
8294 && status->kind () != TARGET_WAITKIND_SIGNALLED)
82f73884 8295 {
d7e15655 8296 if (event_ptid != null_ptid)
47f8a51d 8297 record_currthread (rs, event_ptid);
82f73884 8298 else
5b6d1e4f 8299 event_ptid = first_remote_resumed_thread (this);
43ff13b4 8300 }
74531fed 8301 else
e7af6c70
TBA
8302 {
8303 /* A process exit. Invalidate our notion of current thread. */
8304 record_currthread (rs, minus_one_ptid);
8305 /* It's possible that the packet did not include a pid. */
8306 if (event_ptid == null_ptid)
5b6d1e4f 8307 event_ptid = first_remote_resumed_thread (this);
e7af6c70
TBA
8308 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8309 if (event_ptid == null_ptid)
8310 event_ptid = magic_null_ptid;
8311 }
79d7f229 8312
82f73884 8313 return event_ptid;
43ff13b4
JM
8314}
8315
74531fed
PA
8316/* Wait until the remote machine stops, then return, storing status in
8317 STATUS just as `wait' would. */
8318
f6ac5f3d 8319ptid_t
b60cea74
TT
8320remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8321 target_wait_flags options)
c8e38a49 8322{
2189c312
SM
8323 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8324
baa8575b
SM
8325 remote_state *rs = get_remote_state ();
8326
8327 /* Start by clearing the flag that asks for our wait method to be called,
8d34471f
AB
8328 we'll mark it again at the end if needed. If the target is not in
8329 async mode then the async token should not be marked. */
baa8575b
SM
8330 if (target_is_async_p ())
8331 clear_async_event_handler (rs->remote_async_inferior_event_token);
8d34471f
AB
8332 else
8333 gdb_assert (!async_event_handler_marked
8334 (rs->remote_async_inferior_event_token));
baa8575b 8335
c8e38a49
PA
8336 ptid_t event_ptid;
8337
6efcd9a8 8338 if (target_is_non_stop_p ())
6b8edb51 8339 event_ptid = wait_ns (ptid, status, options);
74531fed 8340 else
6b8edb51 8341 event_ptid = wait_as (ptid, status, options);
c8e38a49 8342
d9d41e78 8343 if (target_is_async_p ())
c8e38a49 8344 {
baa8575b
SM
8345 /* If there are events left in the queue, or unacknowledged
8346 notifications, then tell the event loop to call us again. */
8347 if (!rs->stop_reply_queue.empty ()
8348 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
6b8edb51 8349 mark_async_event_handler (rs->remote_async_inferior_event_token);
c8e38a49 8350 }
c8e38a49
PA
8351
8352 return event_ptid;
8353}
8354
74ca34ce 8355/* Fetch a single register using a 'p' packet. */
c906108c 8356
6b8edb51
PA
8357int
8358remote_target::fetch_register_using_p (struct regcache *regcache,
8359 packet_reg *reg)
b96ec7ac 8360{
ac7936df 8361 struct gdbarch *gdbarch = regcache->arch ();
b96ec7ac 8362 struct remote_state *rs = get_remote_state ();
2e9f7625 8363 char *buf, *p;
9890e433 8364 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
b96ec7ac
AC
8365 int i;
8366
4082afcc 8367 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
8368 return 0;
8369
8370 if (reg->pnum == -1)
8371 return 0;
8372
8d64371b 8373 p = rs->buf.data ();
fcad0fa4 8374 *p++ = 'p';
74ca34ce 8375 p += hexnumstr (p, reg->pnum);
fcad0fa4 8376 *p++ = '\0';
1f4437a4 8377 putpkt (rs->buf);
8d64371b 8378 getpkt (&rs->buf, 0);
3f9a994c 8379
8d64371b 8380 buf = rs->buf.data ();
2e9f7625 8381
8d64371b 8382 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_p]))
74ca34ce
DJ
8383 {
8384 case PACKET_OK:
8385 break;
8386 case PACKET_UNKNOWN:
8387 return 0;
8388 case PACKET_ERROR:
27a9c0bf 8389 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
ac7936df 8390 gdbarch_register_name (regcache->arch (),
27a9c0bf
MS
8391 reg->regnum),
8392 buf);
74ca34ce 8393 }
3f9a994c
JB
8394
8395 /* If this register is unfetchable, tell the regcache. */
8396 if (buf[0] == 'x')
8480adf2 8397 {
73e1c03f 8398 regcache->raw_supply (reg->regnum, NULL);
8480adf2 8399 return 1;
b96ec7ac 8400 }
b96ec7ac 8401
3f9a994c
JB
8402 /* Otherwise, parse and supply the value. */
8403 p = buf;
8404 i = 0;
8405 while (p[0] != 0)
8406 {
8407 if (p[1] == 0)
74ca34ce 8408 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
8409
8410 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8411 p += 2;
8412 }
73e1c03f 8413 regcache->raw_supply (reg->regnum, regp);
3f9a994c 8414 return 1;
b96ec7ac
AC
8415}
8416
74ca34ce
DJ
8417/* Fetch the registers included in the target's 'g' packet. */
8418
6b8edb51
PA
8419int
8420remote_target::send_g_packet ()
c906108c 8421{
d01949b6 8422 struct remote_state *rs = get_remote_state ();
cea39f65 8423 int buf_len;
c906108c 8424
8d64371b 8425 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
b75abf5b 8426 putpkt (rs->buf);
8d64371b 8427 getpkt (&rs->buf, 0);
b75abf5b
AK
8428 if (packet_check_result (rs->buf) == PACKET_ERROR)
8429 error (_("Could not read registers; remote failure reply '%s'"),
dda83cd7 8430 rs->buf.data ());
c906108c 8431
29709017
DJ
8432 /* We can get out of synch in various cases. If the first character
8433 in the buffer is not a hex character, assume that has happened
8434 and try to fetch another packet to read. */
8435 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8436 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8437 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8438 && rs->buf[0] != 'x') /* New: unavailable register value. */
8439 {
2189c312 8440 remote_debug_printf ("Bad register packet; fetching a new packet");
8d64371b 8441 getpkt (&rs->buf, 0);
29709017
DJ
8442 }
8443
8d64371b 8444 buf_len = strlen (rs->buf.data ());
74ca34ce
DJ
8445
8446 /* Sanity check the received packet. */
8447 if (buf_len % 2 != 0)
8d64371b 8448 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
29709017
DJ
8449
8450 return buf_len / 2;
8451}
8452
6b8edb51
PA
8453void
8454remote_target::process_g_packet (struct regcache *regcache)
29709017 8455{
ac7936df 8456 struct gdbarch *gdbarch = regcache->arch ();
29709017 8457 struct remote_state *rs = get_remote_state ();
9d6eea31 8458 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
29709017
DJ
8459 int i, buf_len;
8460 char *p;
8461 char *regs;
8462
8d64371b 8463 buf_len = strlen (rs->buf.data ());
29709017
DJ
8464
8465 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce 8466 if (buf_len > 2 * rsa->sizeof_g_packet)
fc809827 8467 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8d64371b
TT
8468 "bytes): %s"),
8469 rsa->sizeof_g_packet, buf_len / 2,
8470 rs->buf.data ());
74ca34ce
DJ
8471
8472 /* Save the size of the packet sent to us by the target. It is used
8473 as a heuristic when determining the max size of packets that the
8474 target can safely receive. */
8475 if (rsa->actual_register_packet_size == 0)
8476 rsa->actual_register_packet_size = buf_len;
8477
8478 /* If this is smaller than we guessed the 'g' packet would be,
8479 update our records. A 'g' reply that doesn't include a register's
8480 value implies either that the register is not available, or that
8481 the 'p' packet must be used. */
8482 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 8483 {
9dc193c3 8484 long sizeof_g_packet = buf_len / 2;
74ca34ce 8485
4a22f64d 8486 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 8487 {
9dc193c3
LF
8488 long offset = rsa->regs[i].offset;
8489 long reg_size = register_size (gdbarch, i);
8490
74ca34ce
DJ
8491 if (rsa->regs[i].pnum == -1)
8492 continue;
8493
9dc193c3 8494 if (offset >= sizeof_g_packet)
74ca34ce 8495 rsa->regs[i].in_g_packet = 0;
9dc193c3
LF
8496 else if (offset + reg_size > sizeof_g_packet)
8497 error (_("Truncated register %d in remote 'g' packet"), i);
b96ec7ac 8498 else
74ca34ce 8499 rsa->regs[i].in_g_packet = 1;
b96ec7ac 8500 }
9dc193c3
LF
8501
8502 /* Looks valid enough, we can assume this is the correct length
dda83cd7
SM
8503 for a 'g' packet. It's important not to adjust
8504 rsa->sizeof_g_packet if we have truncated registers otherwise
8505 this "if" won't be run the next time the method is called
8506 with a packet of the same size and one of the internal errors
8507 below will trigger instead. */
9dc193c3 8508 rsa->sizeof_g_packet = sizeof_g_packet;
74ca34ce 8509 }
b323314b 8510
224c3ddb 8511 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
8512
8513 /* Unimplemented registers read as all bits zero. */
ea9c271d 8514 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 8515
c906108c
SS
8516 /* Reply describes registers byte by byte, each byte encoded as two
8517 hex characters. Suck them all up, then supply them to the
8518 register cacheing/storage mechanism. */
8519
8d64371b 8520 p = rs->buf.data ();
ea9c271d 8521 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 8522 {
74ca34ce
DJ
8523 if (p[0] == 0 || p[1] == 0)
8524 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8525 internal_error (__FILE__, __LINE__,
9b20d036 8526 _("unexpected end of 'g' packet reply"));
74ca34ce 8527
c906108c 8528 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 8529 regs[i] = 0; /* 'x' */
c906108c
SS
8530 else
8531 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8532 p += 2;
8533 }
8534
a744cf53
MS
8535 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8536 {
8537 struct packet_reg *r = &rsa->regs[i];
9dc193c3 8538 long reg_size = register_size (gdbarch, i);
a744cf53
MS
8539
8540 if (r->in_g_packet)
8541 {
8d64371b 8542 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
a744cf53
MS
8543 /* This shouldn't happen - we adjusted in_g_packet above. */
8544 internal_error (__FILE__, __LINE__,
9b20d036 8545 _("unexpected end of 'g' packet reply"));
a744cf53
MS
8546 else if (rs->buf[r->offset * 2] == 'x')
8547 {
8d64371b 8548 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
a744cf53
MS
8549 /* The register isn't available, mark it as such (at
8550 the same time setting the value to zero). */
73e1c03f 8551 regcache->raw_supply (r->regnum, NULL);
a744cf53
MS
8552 }
8553 else
73e1c03f 8554 regcache->raw_supply (r->regnum, regs + r->offset);
a744cf53
MS
8555 }
8556 }
c906108c
SS
8557}
8558
6b8edb51
PA
8559void
8560remote_target::fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
8561{
8562 send_g_packet ();
56be3814 8563 process_g_packet (regcache);
29709017
DJ
8564}
8565
e6e4e701
PA
8566/* Make the remote selected traceframe match GDB's selected
8567 traceframe. */
8568
6b8edb51
PA
8569void
8570remote_target::set_remote_traceframe ()
e6e4e701
PA
8571{
8572 int newnum;
262e1174 8573 struct remote_state *rs = get_remote_state ();
e6e4e701 8574
262e1174 8575 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
8576 return;
8577
8578 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 8579 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
8580
8581 newnum = target_trace_find (tfind_number,
8582 get_traceframe_number (), 0, 0, NULL);
8583
8584 /* Should not happen. If it does, all bets are off. */
8585 if (newnum != get_traceframe_number ())
8586 warning (_("could not set remote traceframe"));
8587}
8588
f6ac5f3d
PA
8589void
8590remote_target::fetch_registers (struct regcache *regcache, int regnum)
74ca34ce 8591{
ac7936df 8592 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8593 struct remote_state *rs = get_remote_state ();
8594 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8595 int i;
8596
e6e4e701 8597 set_remote_traceframe ();
222312d3 8598 set_general_thread (regcache->ptid ());
74ca34ce
DJ
8599
8600 if (regnum >= 0)
8601 {
5cd63fda 8602 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8603
74ca34ce
DJ
8604 gdb_assert (reg != NULL);
8605
8606 /* If this register might be in the 'g' packet, try that first -
8607 we are likely to read more than one register. If this is the
8608 first 'g' packet, we might be overly optimistic about its
8609 contents, so fall back to 'p'. */
8610 if (reg->in_g_packet)
8611 {
56be3814 8612 fetch_registers_using_g (regcache);
74ca34ce
DJ
8613 if (reg->in_g_packet)
8614 return;
8615 }
8616
56be3814 8617 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
8618 return;
8619
8620 /* This register is not available. */
73e1c03f 8621 regcache->raw_supply (reg->regnum, NULL);
74ca34ce
DJ
8622
8623 return;
8624 }
8625
56be3814 8626 fetch_registers_using_g (regcache);
74ca34ce 8627
5cd63fda 8628 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8629 if (!rsa->regs[i].in_g_packet)
56be3814 8630 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
8631 {
8632 /* This register is not available. */
73e1c03f 8633 regcache->raw_supply (i, NULL);
74ca34ce
DJ
8634 }
8635}
8636
c906108c
SS
8637/* Prepare to store registers. Since we may send them all (using a
8638 'G' request), we have to read out the ones we don't want to change
8639 first. */
8640
f6ac5f3d
PA
8641void
8642remote_target::prepare_to_store (struct regcache *regcache)
c906108c 8643{
9d6eea31
PA
8644 struct remote_state *rs = get_remote_state ();
8645 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cf0e1e0d 8646 int i;
cf0e1e0d 8647
c906108c 8648 /* Make sure the entire registers array is valid. */
4082afcc 8649 switch (packet_support (PACKET_P))
5a2468f5
JM
8650 {
8651 case PACKET_DISABLE:
8652 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 8653 /* Make sure all the necessary registers are cached. */
ac7936df 8654 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
ea9c271d 8655 if (rsa->regs[i].in_g_packet)
0b47d985 8656 regcache->raw_update (rsa->regs[i].regnum);
5a2468f5
JM
8657 break;
8658 case PACKET_ENABLE:
8659 break;
8660 }
8661}
8662
ad10f812 8663/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 8664 packet was not recognized. */
5a2468f5 8665
6b8edb51
PA
8666int
8667remote_target::store_register_using_P (const struct regcache *regcache,
8668 packet_reg *reg)
5a2468f5 8669{
ac7936df 8670 struct gdbarch *gdbarch = regcache->arch ();
d01949b6 8671 struct remote_state *rs = get_remote_state ();
5a2468f5 8672 /* Try storing a single register. */
8d64371b 8673 char *buf = rs->buf.data ();
9890e433 8674 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
5a2468f5 8675 char *p;
5a2468f5 8676
4082afcc 8677 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
8678 return 0;
8679
8680 if (reg->pnum == -1)
8681 return 0;
8682
ea9c271d 8683 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 8684 p = buf + strlen (buf);
34a79281 8685 regcache->raw_collect (reg->regnum, regp);
4a22f64d 8686 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4 8687 putpkt (rs->buf);
8d64371b 8688 getpkt (&rs->buf, 0);
5a2468f5 8689
74ca34ce
DJ
8690 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8691 {
8692 case PACKET_OK:
8693 return 1;
8694 case PACKET_ERROR:
27a9c0bf 8695 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8d64371b 8696 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
74ca34ce
DJ
8697 case PACKET_UNKNOWN:
8698 return 0;
8699 default:
8700 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8701 }
c906108c
SS
8702}
8703
23860348
MS
8704/* Store register REGNUM, or all registers if REGNUM == -1, from the
8705 contents of the register cache buffer. FIXME: ignores errors. */
c906108c 8706
6b8edb51
PA
8707void
8708remote_target::store_registers_using_G (const struct regcache *regcache)
c906108c 8709{
d01949b6 8710 struct remote_state *rs = get_remote_state ();
9d6eea31 8711 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cfd77fa1 8712 gdb_byte *regs;
c906108c
SS
8713 char *p;
8714
193cb69f
AC
8715 /* Extract all the registers in the regcache copying them into a
8716 local buffer. */
8717 {
b323314b 8718 int i;
a744cf53 8719
224c3ddb 8720 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 8721 memset (regs, 0, rsa->sizeof_g_packet);
ac7936df 8722 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
193cb69f 8723 {
ea9c271d 8724 struct packet_reg *r = &rsa->regs[i];
a744cf53 8725
b323314b 8726 if (r->in_g_packet)
34a79281 8727 regcache->raw_collect (r->regnum, regs + r->offset);
193cb69f
AC
8728 }
8729 }
c906108c
SS
8730
8731 /* Command describes registers byte by byte,
8732 each byte encoded as two hex characters. */
8d64371b 8733 p = rs->buf.data ();
193cb69f 8734 *p++ = 'G';
74ca34ce 8735 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4 8736 putpkt (rs->buf);
8d64371b 8737 getpkt (&rs->buf, 0);
1f4437a4 8738 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf 8739 error (_("Could not write registers; remote failure reply '%s'"),
8d64371b 8740 rs->buf.data ());
c906108c 8741}
74ca34ce
DJ
8742
8743/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8744 of the register cache buffer. FIXME: ignores errors. */
8745
f6ac5f3d
PA
8746void
8747remote_target::store_registers (struct regcache *regcache, int regnum)
74ca34ce 8748{
5cd63fda 8749 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8750 struct remote_state *rs = get_remote_state ();
8751 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8752 int i;
8753
e6e4e701 8754 set_remote_traceframe ();
222312d3 8755 set_general_thread (regcache->ptid ());
74ca34ce
DJ
8756
8757 if (regnum >= 0)
8758 {
5cd63fda 8759 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8760
74ca34ce
DJ
8761 gdb_assert (reg != NULL);
8762
8763 /* Always prefer to store registers using the 'P' packet if
8764 possible; we often change only a small number of registers.
8765 Sometimes we change a larger number; we'd need help from a
8766 higher layer to know to use 'G'. */
56be3814 8767 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
8768 return;
8769
8770 /* For now, don't complain if we have no way to write the
8771 register. GDB loses track of unavailable registers too
8772 easily. Some day, this may be an error. We don't have
0df8b418 8773 any way to read the register, either... */
74ca34ce
DJ
8774 if (!reg->in_g_packet)
8775 return;
8776
56be3814 8777 store_registers_using_G (regcache);
74ca34ce
DJ
8778 return;
8779 }
8780
56be3814 8781 store_registers_using_G (regcache);
74ca34ce 8782
5cd63fda 8783 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8784 if (!rsa->regs[i].in_g_packet)
56be3814 8785 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
8786 /* See above for why we do not issue an error here. */
8787 continue;
8788}
c906108c
SS
8789\f
8790
8791/* Return the number of hex digits in num. */
8792
8793static int
fba45db2 8794hexnumlen (ULONGEST num)
c906108c
SS
8795{
8796 int i;
8797
8798 for (i = 0; num != 0; i++)
8799 num >>= 4;
8800
325fac50 8801 return std::max (i, 1);
c906108c
SS
8802}
8803
2df3850c 8804/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
8805
8806static int
fba45db2 8807hexnumstr (char *buf, ULONGEST num)
c906108c 8808{
c906108c 8809 int len = hexnumlen (num);
a744cf53 8810
2df3850c
JM
8811 return hexnumnstr (buf, num, len);
8812}
8813
c906108c 8814
2df3850c 8815/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 8816
2df3850c 8817static int
fba45db2 8818hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
8819{
8820 int i;
8821
8822 buf[width] = '\0';
8823
8824 for (i = width - 1; i >= 0; i--)
c906108c 8825 {
c5aa993b 8826 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
8827 num >>= 4;
8828 }
8829
2df3850c 8830 return width;
c906108c
SS
8831}
8832
23860348 8833/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
8834
8835static CORE_ADDR
fba45db2 8836remote_address_masked (CORE_ADDR addr)
c906108c 8837{
883b9c6c 8838 unsigned int address_size = remote_address_size;
a744cf53 8839
911c95a5
UW
8840 /* If "remoteaddresssize" was not set, default to target address size. */
8841 if (!address_size)
f5656ead 8842 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
8843
8844 if (address_size > 0
8845 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
8846 {
8847 /* Only create a mask when that mask can safely be constructed
dda83cd7 8848 in a ULONGEST variable. */
c906108c 8849 ULONGEST mask = 1;
a744cf53 8850
911c95a5 8851 mask = (mask << address_size) - 1;
c906108c
SS
8852 addr &= mask;
8853 }
8854 return addr;
8855}
8856
8857/* Determine whether the remote target supports binary downloading.
8858 This is accomplished by sending a no-op memory write of zero length
8859 to the target at the specified address. It does not suffice to send
23860348
MS
8860 the whole packet, since many stubs strip the eighth bit and
8861 subsequently compute a wrong checksum, which causes real havoc with
8862 remote_write_bytes.
7a292a7a 8863
96baa820 8864 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 8865 clean. In cases like this, the user should clear "remote
23860348 8866 X-packet". */
96baa820 8867
6b8edb51
PA
8868void
8869remote_target::check_binary_download (CORE_ADDR addr)
c906108c 8870{
d01949b6 8871 struct remote_state *rs = get_remote_state ();
24b06219 8872
4082afcc 8873 switch (packet_support (PACKET_X))
c906108c 8874 {
96baa820
JM
8875 case PACKET_DISABLE:
8876 break;
8877 case PACKET_ENABLE:
8878 break;
8879 case PACKET_SUPPORT_UNKNOWN:
8880 {
96baa820 8881 char *p;
802188a7 8882
8d64371b 8883 p = rs->buf.data ();
96baa820
JM
8884 *p++ = 'X';
8885 p += hexnumstr (p, (ULONGEST) addr);
8886 *p++ = ',';
8887 p += hexnumstr (p, (ULONGEST) 0);
8888 *p++ = ':';
8889 *p = '\0';
802188a7 8890
8d64371b
TT
8891 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
8892 getpkt (&rs->buf, 0);
c906108c 8893
2e9f7625 8894 if (rs->buf[0] == '\0')
96baa820 8895 {
2189c312 8896 remote_debug_printf ("binary downloading NOT supported by target");
444abaca 8897 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
8898 }
8899 else
8900 {
2189c312 8901 remote_debug_printf ("binary downloading supported by target");
444abaca 8902 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
8903 }
8904 break;
8905 }
c906108c
SS
8906 }
8907}
8908
124e13d9
SM
8909/* Helper function to resize the payload in order to try to get a good
8910 alignment. We try to write an amount of data such that the next write will
8911 start on an address aligned on REMOTE_ALIGN_WRITES. */
8912
8913static int
8914align_for_efficient_write (int todo, CORE_ADDR memaddr)
8915{
8916 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8917}
8918
c906108c
SS
8919/* Write memory data directly to the remote machine.
8920 This does not inform the data cache; the data cache uses this.
a76d924d 8921 HEADER is the starting part of the packet.
c906108c
SS
8922 MEMADDR is the address in the remote memory space.
8923 MYADDR is the address of the buffer in our space.
124e13d9
SM
8924 LEN_UNITS is the number of addressable units to write.
8925 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
8926 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8927 should send data as binary ('X'), or hex-encoded ('M').
8928
8929 The function creates packet of the form
8930 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8931
124e13d9 8932 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
8933
8934 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8935 are omitted.
8936
9b409511 8937 Return the transferred status, error or OK (an
124e13d9
SM
8938 'enum target_xfer_status' value). Save the number of addressable units
8939 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8940
8941 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8942 exchange between gdb and the stub could look like (?? in place of the
8943 checksum):
8944
8945 -> $m1000,4#??
8946 <- aaaabbbbccccdddd
8947
8948 -> $M1000,3:eeeeffffeeee#??
8949 <- OK
8950
8951 -> $m1000,4#??
8952 <- eeeeffffeeeedddd */
c906108c 8953
6b8edb51
PA
8954target_xfer_status
8955remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8956 const gdb_byte *myaddr,
8957 ULONGEST len_units,
8958 int unit_size,
8959 ULONGEST *xfered_len_units,
8960 char packet_format, int use_length)
c906108c 8961{
6d820c5c 8962 struct remote_state *rs = get_remote_state ();
cfd77fa1 8963 char *p;
a76d924d
DJ
8964 char *plen = NULL;
8965 int plenlen = 0;
124e13d9
SM
8966 int todo_units;
8967 int units_written;
8968 int payload_capacity_bytes;
8969 int payload_length_bytes;
a76d924d
DJ
8970
8971 if (packet_format != 'X' && packet_format != 'M')
8972 internal_error (__FILE__, __LINE__,
9b20d036 8973 _("remote_write_bytes_aux: bad packet format"));
c906108c 8974
124e13d9 8975 if (len_units == 0)
9b409511 8976 return TARGET_XFER_EOF;
b2182ed2 8977
124e13d9 8978 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 8979
6d820c5c
DJ
8980 /* The packet buffer will be large enough for the payload;
8981 get_memory_packet_size ensures this. */
a76d924d 8982 rs->buf[0] = '\0';
c906108c 8983
a257b5bb 8984 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
8985 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8986
124e13d9 8987 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 8988 if (!use_length)
0df8b418 8989 /* The comma won't be used. */
124e13d9
SM
8990 payload_capacity_bytes += 1;
8991 payload_capacity_bytes -= strlen (header);
8992 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 8993
a76d924d 8994 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 8995
8d64371b
TT
8996 strcat (rs->buf.data (), header);
8997 p = rs->buf.data () + strlen (header);
a76d924d
DJ
8998
8999 /* Compute a best guess of the number of bytes actually transfered. */
9000 if (packet_format == 'X')
c906108c 9001 {
23860348 9002 /* Best guess at number of bytes that will fit. */
325fac50
PA
9003 todo_units = std::min (len_units,
9004 (ULONGEST) payload_capacity_bytes / unit_size);
a76d924d 9005 if (use_length)
124e13d9 9006 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50 9007 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
9008 }
9009 else
9010 {
124e13d9 9011 /* Number of bytes that will fit. */
325fac50
PA
9012 todo_units
9013 = std::min (len_units,
9014 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
a76d924d 9015 if (use_length)
124e13d9 9016 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50
PA
9017 todo_units = std::min (todo_units,
9018 (payload_capacity_bytes / unit_size) / 2);
917317f4 9019 }
a76d924d 9020
124e13d9 9021 if (todo_units <= 0)
3de11b2e 9022 internal_error (__FILE__, __LINE__,
405f8e94 9023 _("minimum packet size too small to write data"));
802188a7 9024
6765f3e5
DJ
9025 /* If we already need another packet, then try to align the end
9026 of this packet to a useful boundary. */
124e13d9
SM
9027 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9028 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 9029
a257b5bb 9030 /* Append "<memaddr>". */
917317f4
JM
9031 memaddr = remote_address_masked (memaddr);
9032 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 9033
a76d924d
DJ
9034 if (use_length)
9035 {
9036 /* Append ",". */
9037 *p++ = ',';
802188a7 9038
124e13d9 9039 /* Append the length and retain its location and size. It may need to be
dda83cd7 9040 adjusted once the packet body has been created. */
a76d924d 9041 plen = p;
124e13d9 9042 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
9043 p += plenlen;
9044 }
a257b5bb
AC
9045
9046 /* Append ":". */
917317f4
JM
9047 *p++ = ':';
9048 *p = '\0';
802188a7 9049
a257b5bb 9050 /* Append the packet body. */
a76d924d 9051 if (packet_format == 'X')
917317f4 9052 {
917317f4
JM
9053 /* Binary mode. Send target system values byte by byte, in
9054 increasing byte addresses. Only escape certain critical
9055 characters. */
124e13d9
SM
9056 payload_length_bytes =
9057 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9058 &units_written, payload_capacity_bytes);
6765f3e5 9059
124e13d9 9060 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
9061 a second try to keep the end of the packet aligned. Don't do
9062 this if the packet is tiny. */
124e13d9 9063 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 9064 {
124e13d9
SM
9065 int new_todo_units;
9066
9067 new_todo_units = align_for_efficient_write (units_written, memaddr);
9068
9069 if (new_todo_units != units_written)
9070 payload_length_bytes =
9071 remote_escape_output (myaddr, new_todo_units, unit_size,
9072 (gdb_byte *) p, &units_written,
9073 payload_capacity_bytes);
6765f3e5
DJ
9074 }
9075
124e13d9
SM
9076 p += payload_length_bytes;
9077 if (use_length && units_written < todo_units)
c906108c 9078 {
802188a7 9079 /* Escape chars have filled up the buffer prematurely,
124e13d9 9080 and we have actually sent fewer units than planned.
917317f4
JM
9081 Fix-up the length field of the packet. Use the same
9082 number of characters as before. */
124e13d9
SM
9083 plen += hexnumnstr (plen, (ULONGEST) units_written,
9084 plenlen);
917317f4 9085 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 9086 }
a76d924d
DJ
9087 }
9088 else
9089 {
917317f4
JM
9090 /* Normal mode: Send target system values byte by byte, in
9091 increasing byte addresses. Each byte is encoded as a two hex
9092 value. */
124e13d9
SM
9093 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9094 units_written = todo_units;
c906108c 9095 }
802188a7 9096
8d64371b
TT
9097 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9098 getpkt (&rs->buf, 0);
802188a7 9099
2e9f7625 9100 if (rs->buf[0] == 'E')
00d84524 9101 return TARGET_XFER_E_IO;
802188a7 9102
124e13d9
SM
9103 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9104 send fewer units than we'd planned. */
9105 *xfered_len_units = (ULONGEST) units_written;
92ffd475 9106 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
9107}
9108
a76d924d
DJ
9109/* Write memory data directly to the remote machine.
9110 This does not inform the data cache; the data cache uses this.
9111 MEMADDR is the address in the remote memory space.
9112 MYADDR is the address of the buffer in our space.
9113 LEN is the number of bytes.
9114
9b409511
YQ
9115 Return the transferred status, error or OK (an
9116 'enum target_xfer_status' value). Save the number of bytes
9117 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 9118
6b8edb51
PA
9119target_xfer_status
9120remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9121 ULONGEST len, int unit_size,
9122 ULONGEST *xfered_len)
a76d924d 9123{
a121b7c1 9124 const char *packet_format = NULL;
a76d924d
DJ
9125
9126 /* Check whether the target supports binary download. */
9127 check_binary_download (memaddr);
9128
4082afcc 9129 switch (packet_support (PACKET_X))
a76d924d
DJ
9130 {
9131 case PACKET_ENABLE:
9132 packet_format = "X";
9133 break;
9134 case PACKET_DISABLE:
9135 packet_format = "M";
9136 break;
9137 case PACKET_SUPPORT_UNKNOWN:
9138 internal_error (__FILE__, __LINE__,
9139 _("remote_write_bytes: bad internal state"));
9140 default:
9141 internal_error (__FILE__, __LINE__, _("bad switch"));
9142 }
9143
9144 return remote_write_bytes_aux (packet_format,
124e13d9 9145 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 9146 packet_format[0], 1);
a76d924d
DJ
9147}
9148
9217e74e
YQ
9149/* Read memory data directly from the remote machine.
9150 This does not use the data cache; the data cache uses this.
9151 MEMADDR is the address in the remote memory space.
9152 MYADDR is the address of the buffer in our space.
124e13d9
SM
9153 LEN_UNITS is the number of addressable memory units to read..
9154 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
9155
9156 Return the transferred status, error or OK (an
9157 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
9158 transferred in *XFERED_LEN_UNITS.
9159
9160 See the comment of remote_write_bytes_aux for an example of
9161 memory read/write exchange between gdb and the stub. */
9217e74e 9162
6b8edb51
PA
9163target_xfer_status
9164remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9165 ULONGEST len_units,
9166 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
9167{
9168 struct remote_state *rs = get_remote_state ();
124e13d9 9169 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 9170 char *p;
124e13d9
SM
9171 int todo_units;
9172 int decoded_bytes;
9217e74e 9173
124e13d9 9174 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
9175 /* The packet buffer will be large enough for the payload;
9176 get_memory_packet_size ensures this. */
9177
124e13d9 9178 /* Number of units that will fit. */
325fac50
PA
9179 todo_units = std::min (len_units,
9180 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
9181
9182 /* Construct "m"<memaddr>","<len>". */
9183 memaddr = remote_address_masked (memaddr);
8d64371b 9184 p = rs->buf.data ();
9217e74e
YQ
9185 *p++ = 'm';
9186 p += hexnumstr (p, (ULONGEST) memaddr);
9187 *p++ = ',';
124e13d9 9188 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
9189 *p = '\0';
9190 putpkt (rs->buf);
8d64371b 9191 getpkt (&rs->buf, 0);
9217e74e
YQ
9192 if (rs->buf[0] == 'E'
9193 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9194 && rs->buf[3] == '\0')
9195 return TARGET_XFER_E_IO;
9196 /* Reply describes memory byte by byte, each byte encoded as two hex
9197 characters. */
8d64371b 9198 p = rs->buf.data ();
124e13d9 9199 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 9200 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 9201 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
92ffd475 9202 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9217e74e
YQ
9203}
9204
b55fbac4
YQ
9205/* Using the set of read-only target sections of remote, read live
9206 read-only memory.
8acf9577
YQ
9207
9208 For interface/parameters/return description see target.h,
9209 to_xfer_partial. */
9210
6b8edb51
PA
9211target_xfer_status
9212remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9213 ULONGEST memaddr,
9214 ULONGEST len,
9215 int unit_size,
9216 ULONGEST *xfered_len)
8acf9577 9217{
19cf757a 9218 const struct target_section *secp;
8acf9577 9219
6b8edb51 9220 secp = target_section_by_addr (this, memaddr);
8acf9577 9221 if (secp != NULL
fd361982 9222 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
8acf9577 9223 {
8acf9577
YQ
9224 ULONGEST memend = memaddr + len;
9225
19cf757a
AB
9226 const target_section_table *table = target_get_section_table (this);
9227 for (const target_section &p : *table)
8acf9577 9228 {
bb2a6777 9229 if (memaddr >= p.addr)
8acf9577 9230 {
bb2a6777 9231 if (memend <= p.endaddr)
8acf9577
YQ
9232 {
9233 /* Entire transfer is within this section. */
124e13d9 9234 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 9235 xfered_len);
8acf9577 9236 }
bb2a6777 9237 else if (memaddr >= p.endaddr)
8acf9577
YQ
9238 {
9239 /* This section ends before the transfer starts. */
9240 continue;
9241 }
9242 else
9243 {
9244 /* This section overlaps the transfer. Just do half. */
bb2a6777 9245 len = p.endaddr - memaddr;
124e13d9 9246 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 9247 xfered_len);
8acf9577
YQ
9248 }
9249 }
9250 }
9251 }
9252
9253 return TARGET_XFER_EOF;
9254}
9255
9217e74e
YQ
9256/* Similar to remote_read_bytes_1, but it reads from the remote stub
9257 first if the requested memory is unavailable in traceframe.
9258 Otherwise, fall back to remote_read_bytes_1. */
c906108c 9259
6b8edb51
PA
9260target_xfer_status
9261remote_target::remote_read_bytes (CORE_ADDR memaddr,
9262 gdb_byte *myaddr, ULONGEST len, int unit_size,
9263 ULONGEST *xfered_len)
c906108c 9264{
6b6aa828 9265 if (len == 0)
96c4f946 9266 return TARGET_XFER_EOF;
b2182ed2 9267
8acf9577
YQ
9268 if (get_traceframe_number () != -1)
9269 {
a79b1bc6 9270 std::vector<mem_range> available;
8acf9577
YQ
9271
9272 /* If we fail to get the set of available memory, then the
9273 target does not support querying traceframe info, and so we
9274 attempt reading from the traceframe anyway (assuming the
9275 target implements the old QTro packet then). */
9276 if (traceframe_available_memory (&available, memaddr, len))
9277 {
a79b1bc6 9278 if (available.empty () || available[0].start != memaddr)
8acf9577
YQ
9279 {
9280 enum target_xfer_status res;
9281
9282 /* Don't read into the traceframe's available
9283 memory. */
a79b1bc6 9284 if (!available.empty ())
8acf9577
YQ
9285 {
9286 LONGEST oldlen = len;
9287
a79b1bc6 9288 len = available[0].start - memaddr;
8acf9577
YQ
9289 gdb_assert (len <= oldlen);
9290 }
9291
8acf9577 9292 /* This goes through the topmost target again. */
6b8edb51 9293 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
124e13d9 9294 len, unit_size, xfered_len);
8acf9577
YQ
9295 if (res == TARGET_XFER_OK)
9296 return TARGET_XFER_OK;
9297 else
9298 {
9299 /* No use trying further, we know some memory starting
9300 at MEMADDR isn't available. */
9301 *xfered_len = len;
92ffd475
PC
9302 return (*xfered_len != 0) ?
9303 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8acf9577
YQ
9304 }
9305 }
9306
9307 /* Don't try to read more than how much is available, in
9308 case the target implements the deprecated QTro packet to
9309 cater for older GDBs (the target's knowledge of read-only
9310 sections may be outdated by now). */
a79b1bc6 9311 len = available[0].length;
8acf9577
YQ
9312 }
9313 }
9314
124e13d9 9315 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 9316}
74531fed 9317
c906108c 9318\f
c906108c 9319
a76d924d
DJ
9320/* Sends a packet with content determined by the printf format string
9321 FORMAT and the remaining arguments, then gets the reply. Returns
9322 whether the packet was a success, a failure, or unknown. */
9323
6b8edb51
PA
9324packet_result
9325remote_target::remote_send_printf (const char *format, ...)
a76d924d
DJ
9326{
9327 struct remote_state *rs = get_remote_state ();
9328 int max_size = get_remote_packet_size ();
a76d924d 9329 va_list ap;
a744cf53 9330
a76d924d
DJ
9331 va_start (ap, format);
9332
9333 rs->buf[0] = '\0';
8d64371b 9334 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
33b031ce
GB
9335
9336 va_end (ap);
9337
9338 if (size >= max_size)
9b20d036 9339 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
9340
9341 if (putpkt (rs->buf) < 0)
9342 error (_("Communication problem with target."));
9343
9344 rs->buf[0] = '\0';
8d64371b 9345 getpkt (&rs->buf, 0);
a76d924d
DJ
9346
9347 return packet_check_result (rs->buf);
9348}
9349
a76d924d
DJ
9350/* Flash writing can take quite some time. We'll set
9351 effectively infinite timeout for flash operations.
9352 In future, we'll need to decide on a better approach. */
9353static const int remote_flash_timeout = 1000;
9354
f6ac5f3d
PA
9355void
9356remote_target::flash_erase (ULONGEST address, LONGEST length)
a76d924d 9357{
f5656ead 9358 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d 9359 enum packet_result ret;
2ec845e7
TT
9360 scoped_restore restore_timeout
9361 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
a76d924d
DJ
9362
9363 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 9364 phex (address, addr_size),
a76d924d
DJ
9365 phex (length, 4));
9366 switch (ret)
9367 {
9368 case PACKET_UNKNOWN:
9369 error (_("Remote target does not support flash erase"));
9370 case PACKET_ERROR:
9371 error (_("Error erasing flash with vFlashErase packet"));
9372 default:
9373 break;
9374 }
a76d924d
DJ
9375}
9376
6b8edb51
PA
9377target_xfer_status
9378remote_target::remote_flash_write (ULONGEST address,
9379 ULONGEST length, ULONGEST *xfered_len,
9380 const gdb_byte *data)
a76d924d 9381{
2ec845e7
TT
9382 scoped_restore restore_timeout
9383 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9384 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9385 xfered_len,'X', 0);
a76d924d
DJ
9386}
9387
f6ac5f3d
PA
9388void
9389remote_target::flash_done ()
a76d924d 9390{
a76d924d 9391 int ret;
a76d924d 9392
2ec845e7
TT
9393 scoped_restore restore_timeout
9394 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9395
a76d924d 9396 ret = remote_send_printf ("vFlashDone");
a76d924d
DJ
9397
9398 switch (ret)
9399 {
9400 case PACKET_UNKNOWN:
9401 error (_("Remote target does not support vFlashDone"));
9402 case PACKET_ERROR:
9403 error (_("Error finishing flash operation"));
9404 default:
9405 break;
9406 }
9407}
9408
c906108c
SS
9409\f
9410/* Stuff for dealing with the packets which are part of this protocol.
9411 See comment at top of file for details. */
9412
1927e618
PA
9413/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9414 error to higher layers. Called when a serial error is detected.
9415 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
9416 the system error message for errno at function entry and final dot
9417 for output compatibility with throw_perror_with_name. */
1927e618
PA
9418
9419static void
5b6d1e4f 9420unpush_and_perror (remote_target *target, const char *string)
1927e618 9421{
d6cb50a2 9422 int saved_errno = errno;
1927e618 9423
5b6d1e4f 9424 remote_unpush_target (target);
d6cb50a2
JK
9425 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9426 safe_strerror (saved_errno));
1927e618
PA
9427}
9428
048094ac
PA
9429/* Read a single character from the remote end. The current quit
9430 handler is overridden to avoid quitting in the middle of packet
9431 sequence, as that would break communication with the remote server.
9432 See remote_serial_quit_handler for more detail. */
c906108c 9433
6b8edb51
PA
9434int
9435remote_target::readchar (int timeout)
c906108c
SS
9436{
9437 int ch;
5d93a237 9438 struct remote_state *rs = get_remote_state ();
048094ac 9439
2ec845e7 9440 {
6b8edb51
PA
9441 scoped_restore restore_quit_target
9442 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9443 scoped_restore restore_quit
6b8edb51 9444 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
c906108c 9445
2ec845e7 9446 rs->got_ctrlc_during_io = 0;
c906108c 9447
2ec845e7 9448 ch = serial_readchar (rs->remote_desc, timeout);
048094ac 9449
2ec845e7
TT
9450 if (rs->got_ctrlc_during_io)
9451 set_quit_flag ();
9452 }
048094ac 9453
2acceee2 9454 if (ch >= 0)
0876f84a 9455 return ch;
2acceee2
JM
9456
9457 switch ((enum serial_rc) ch)
c906108c
SS
9458 {
9459 case SERIAL_EOF:
5b6d1e4f 9460 remote_unpush_target (this);
598d3636 9461 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 9462 /* no return */
c906108c 9463 case SERIAL_ERROR:
5b6d1e4f
PA
9464 unpush_and_perror (this, _("Remote communication error. "
9465 "Target disconnected."));
2acceee2 9466 /* no return */
c906108c 9467 case SERIAL_TIMEOUT:
2acceee2 9468 break;
c906108c 9469 }
2acceee2 9470 return ch;
c906108c
SS
9471}
9472
c33e31fd 9473/* Wrapper for serial_write that closes the target and throws if
048094ac
PA
9474 writing fails. The current quit handler is overridden to avoid
9475 quitting in the middle of packet sequence, as that would break
9476 communication with the remote server. See
9477 remote_serial_quit_handler for more detail. */
c33e31fd 9478
6b8edb51
PA
9479void
9480remote_target::remote_serial_write (const char *str, int len)
c33e31fd 9481{
5d93a237 9482 struct remote_state *rs = get_remote_state ();
048094ac 9483
6b8edb51
PA
9484 scoped_restore restore_quit_target
9485 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9486 scoped_restore restore_quit
6b8edb51 9487 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
048094ac
PA
9488
9489 rs->got_ctrlc_during_io = 0;
5d93a237
TT
9490
9491 if (serial_write (rs->remote_desc, str, len))
c33e31fd 9492 {
5b6d1e4f
PA
9493 unpush_and_perror (this, _("Remote communication error. "
9494 "Target disconnected."));
c33e31fd 9495 }
048094ac
PA
9496
9497 if (rs->got_ctrlc_during_io)
9498 set_quit_flag ();
c33e31fd
PA
9499}
9500
b3ced9ba
PA
9501/* Return a string representing an escaped version of BUF, of len N.
9502 E.g. \n is converted to \\n, \t to \\t, etc. */
6e5abd65 9503
b3ced9ba 9504static std::string
6e5abd65
PA
9505escape_buffer (const char *buf, int n)
9506{
d7e74731 9507 string_file stb;
6e5abd65 9508
d7e74731 9509 stb.putstrn (buf, n, '\\');
5d10a204 9510 return stb.release ();
6e5abd65
PA
9511}
9512
c906108c 9513int
6b8edb51 9514remote_target::putpkt (const char *buf)
c906108c
SS
9515{
9516 return putpkt_binary (buf, strlen (buf));
9517}
9518
6b8edb51
PA
9519/* Wrapper around remote_target::putpkt to avoid exporting
9520 remote_target. */
9521
9522int
9523putpkt (remote_target *remote, const char *buf)
9524{
9525 return remote->putpkt (buf);
9526}
9527
c906108c 9528/* Send a packet to the remote machine, with error checking. The data
23860348 9529 of the packet is in BUF. The string in BUF can be at most
ea9c271d 9530 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
9531 and for a possible /0 if we are debugging (remote_debug) and want
9532 to print the sent packet as a string. */
c906108c 9533
6b8edb51
PA
9534int
9535remote_target::putpkt_binary (const char *buf, int cnt)
c906108c 9536{
2d717e4f 9537 struct remote_state *rs = get_remote_state ();
c906108c
SS
9538 int i;
9539 unsigned char csum = 0;
b80406ac
TT
9540 gdb::def_vector<char> data (cnt + 6);
9541 char *buf2 = data.data ();
085dd6e6 9542
c906108c
SS
9543 int ch;
9544 int tcount = 0;
9545 char *p;
9546
e24a49d8
PA
9547 /* Catch cases like trying to read memory or listing threads while
9548 we're waiting for a stop reply. The remote server wouldn't be
9549 ready to handle this request, so we'd hang and timeout. We don't
9550 have to worry about this in synchronous mode, because in that
9551 case it's not possible to issue a command while the target is
74531fed
PA
9552 running. This is not a problem in non-stop mode, because in that
9553 case, the stub is always ready to process serial input. */
6efcd9a8
PA
9554 if (!target_is_non_stop_p ()
9555 && target_is_async_p ()
9556 && rs->waiting_for_stop_reply)
9597b22a
DE
9557 {
9558 error (_("Cannot execute this command while the target is running.\n"
9559 "Use the \"interrupt\" command to stop the target\n"
9560 "and then try again."));
9561 }
e24a49d8 9562
c906108c
SS
9563 /* Copy the packet into buffer BUF2, encapsulating it
9564 and giving it a checksum. */
9565
c906108c
SS
9566 p = buf2;
9567 *p++ = '$';
9568
9569 for (i = 0; i < cnt; i++)
9570 {
9571 csum += buf[i];
9572 *p++ = buf[i];
9573 }
9574 *p++ = '#';
9575 *p++ = tohex ((csum >> 4) & 0xf);
9576 *p++ = tohex (csum & 0xf);
9577
9578 /* Send it over and over until we get a positive ack. */
9579
9580 while (1)
9581 {
c906108c
SS
9582 if (remote_debug)
9583 {
9584 *p = '\0';
b3ced9ba 9585
6f8976bf 9586 int len = (int) (p - buf2);
6cc8564b
LM
9587 int max_chars;
9588
9589 if (remote_packet_max_chars < 0)
9590 max_chars = len;
9591 else
9592 max_chars = remote_packet_max_chars;
6f8976bf
YQ
9593
9594 std::string str
6cc8564b 9595 = escape_buffer (buf2, std::min (len, max_chars));
6f8976bf 9596
6cc8564b 9597 if (len > max_chars)
2189c312
SM
9598 remote_debug_printf_nofunc
9599 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9600 len - max_chars);
9601 else
9602 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
c906108c 9603 }
c33e31fd 9604 remote_serial_write (buf2, p - buf2);
c906108c 9605
a6f3e723
SL
9606 /* If this is a no acks version of the remote protocol, send the
9607 packet and move on. */
9608 if (rs->noack_mode)
dda83cd7 9609 break;
a6f3e723 9610
74531fed
PA
9611 /* Read until either a timeout occurs (-2) or '+' is read.
9612 Handle any notification that arrives in the mean time. */
c906108c
SS
9613 while (1)
9614 {
9615 ch = readchar (remote_timeout);
9616
c906108c
SS
9617 switch (ch)
9618 {
9619 case '+':
2189c312 9620 remote_debug_printf_nofunc ("Received Ack");
c906108c 9621 return 1;
1216fa2c 9622 case '-':
2189c312 9623 remote_debug_printf_nofunc ("Received Nak");
a17d146e 9624 /* FALLTHROUGH */
c906108c 9625 case SERIAL_TIMEOUT:
c5aa993b 9626 tcount++;
c906108c 9627 if (tcount > 3)
b80406ac 9628 return 0;
23860348 9629 break; /* Retransmit buffer. */
c906108c
SS
9630 case '$':
9631 {
2189c312 9632 remote_debug_printf ("Packet instead of Ack, ignoring it");
d6f7abdf
AC
9633 /* It's probably an old response sent because an ACK
9634 was lost. Gobble up the packet and ack it so it
9635 doesn't get retransmitted when we resend this
9636 packet. */
6d820c5c 9637 skip_frame ();
c33e31fd 9638 remote_serial_write ("+", 1);
23860348 9639 continue; /* Now, go look for +. */
c906108c 9640 }
74531fed
PA
9641
9642 case '%':
9643 {
9644 int val;
9645
9646 /* If we got a notification, handle it, and go back to looking
9647 for an ack. */
9648 /* We've found the start of a notification. Now
9649 collect the data. */
8d64371b 9650 val = read_frame (&rs->buf);
74531fed
PA
9651 if (val >= 0)
9652 {
2189c312
SM
9653 remote_debug_printf_nofunc
9654 (" Notification received: %s",
9655 escape_buffer (rs->buf.data (), val).c_str ());
6e5abd65 9656
8d64371b 9657 handle_notification (rs->notif_state, rs->buf.data ());
74531fed
PA
9658 /* We're in sync now, rewait for the ack. */
9659 tcount = 0;
9660 }
9661 else
2189c312
SM
9662 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9663 rs->buf.data ());
74531fed
PA
9664 continue;
9665 }
9666 /* fall-through */
c906108c 9667 default:
2189c312
SM
9668 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9669 rs->buf.data ());
c906108c
SS
9670 continue;
9671 }
23860348 9672 break; /* Here to retransmit. */
c906108c
SS
9673 }
9674
9675#if 0
9676 /* This is wrong. If doing a long backtrace, the user should be
dda83cd7
SM
9677 able to get out next time we call QUIT, without anything as
9678 violent as interrupt_query. If we want to provide a way out of
9679 here without getting to the next QUIT, it should be based on
9680 hitting ^C twice as in remote_wait. */
c906108c
SS
9681 if (quit_flag)
9682 {
9683 quit_flag = 0;
9684 interrupt_query ();
9685 }
9686#endif
9687 }
a5c0808e 9688
a6f3e723 9689 return 0;
c906108c
SS
9690}
9691
6d820c5c
DJ
9692/* Come here after finding the start of a frame when we expected an
9693 ack. Do our best to discard the rest of this packet. */
9694
6b8edb51
PA
9695void
9696remote_target::skip_frame ()
6d820c5c
DJ
9697{
9698 int c;
9699
9700 while (1)
9701 {
9702 c = readchar (remote_timeout);
9703 switch (c)
9704 {
9705 case SERIAL_TIMEOUT:
9706 /* Nothing we can do. */
9707 return;
9708 case '#':
9709 /* Discard the two bytes of checksum and stop. */
9710 c = readchar (remote_timeout);
9711 if (c >= 0)
9712 c = readchar (remote_timeout);
9713
9714 return;
9715 case '*': /* Run length encoding. */
9716 /* Discard the repeat count. */
9717 c = readchar (remote_timeout);
9718 if (c < 0)
9719 return;
9720 break;
9721 default:
9722 /* A regular character. */
9723 break;
9724 }
9725 }
9726}
9727
c906108c 9728/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
9729 into *BUF, verifying the checksum, length, and handling run-length
9730 compression. NUL terminate the buffer. If there is not enough room,
8d64371b 9731 expand *BUF.
c906108c 9732
c2d11a7d
JM
9733 Returns -1 on error, number of characters in buffer (ignoring the
9734 trailing NULL) on success. (could be extended to return one of the
23860348 9735 SERIAL status indications). */
c2d11a7d 9736
6b8edb51 9737long
8d64371b 9738remote_target::read_frame (gdb::char_vector *buf_p)
c906108c
SS
9739{
9740 unsigned char csum;
c2d11a7d 9741 long bc;
c906108c 9742 int c;
8d64371b 9743 char *buf = buf_p->data ();
a6f3e723 9744 struct remote_state *rs = get_remote_state ();
c906108c
SS
9745
9746 csum = 0;
c2d11a7d 9747 bc = 0;
c906108c
SS
9748
9749 while (1)
9750 {
9751 c = readchar (remote_timeout);
c906108c
SS
9752 switch (c)
9753 {
9754 case SERIAL_TIMEOUT:
2189c312 9755 remote_debug_printf ("Timeout in mid-packet, retrying");
c2d11a7d 9756 return -1;
2189c312 9757
c906108c 9758 case '$':
2189c312 9759 remote_debug_printf ("Saw new packet start in middle of old one");
23860348 9760 return -1; /* Start a new packet, count retries. */
2189c312 9761
c906108c
SS
9762 case '#':
9763 {
9764 unsigned char pktcsum;
e1b09194
AC
9765 int check_0 = 0;
9766 int check_1 = 0;
c906108c 9767
c2d11a7d 9768 buf[bc] = '\0';
c906108c 9769
e1b09194
AC
9770 check_0 = readchar (remote_timeout);
9771 if (check_0 >= 0)
9772 check_1 = readchar (remote_timeout);
802188a7 9773
e1b09194
AC
9774 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9775 {
2189c312 9776 remote_debug_printf ("Timeout in checksum, retrying");
e1b09194
AC
9777 return -1;
9778 }
9779 else if (check_0 < 0 || check_1 < 0)
40e3f985 9780 {
2189c312 9781 remote_debug_printf ("Communication error in checksum");
40e3f985
FN
9782 return -1;
9783 }
c906108c 9784
a6f3e723
SL
9785 /* Don't recompute the checksum; with no ack packets we
9786 don't have any way to indicate a packet retransmission
9787 is necessary. */
9788 if (rs->noack_mode)
9789 return bc;
9790
e1b09194 9791 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 9792 if (csum == pktcsum)
dda83cd7 9793 return bc;
c906108c 9794
2189c312
SM
9795 remote_debug_printf
9796 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
9797 pktcsum, csum, escape_buffer (buf, bc).c_str ());
6e5abd65 9798
c2d11a7d 9799 /* Number of characters in buffer ignoring trailing
dda83cd7 9800 NULL. */
c2d11a7d 9801 return -1;
c906108c 9802 }
23860348 9803 case '*': /* Run length encoding. */
dda83cd7 9804 {
c2c6d25f 9805 int repeat;
c906108c 9806
24b21115 9807 csum += c;
b4501125
AC
9808 c = readchar (remote_timeout);
9809 csum += c;
23860348 9810 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 9811
23860348 9812 /* The character before ``*'' is repeated. */
c2d11a7d 9813
6d820c5c 9814 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 9815 {
8d64371b 9816 if (bc + repeat - 1 >= buf_p->size () - 1)
6d820c5c
DJ
9817 {
9818 /* Make some more room in the buffer. */
8d64371b
TT
9819 buf_p->resize (buf_p->size () + repeat);
9820 buf = buf_p->data ();
6d820c5c
DJ
9821 }
9822
c2d11a7d
JM
9823 memset (&buf[bc], buf[bc - 1], repeat);
9824 bc += repeat;
c2c6d25f
JM
9825 continue;
9826 }
9827
c2d11a7d 9828 buf[bc] = '\0';
6cb06a8c 9829 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 9830 return -1;
c2c6d25f 9831 }
c906108c 9832 default:
8d64371b 9833 if (bc >= buf_p->size () - 1)
c906108c 9834 {
6d820c5c 9835 /* Make some more room in the buffer. */
8d64371b
TT
9836 buf_p->resize (buf_p->size () * 2);
9837 buf = buf_p->data ();
c906108c
SS
9838 }
9839
6d820c5c
DJ
9840 buf[bc++] = c;
9841 csum += c;
9842 continue;
c906108c
SS
9843 }
9844 }
9845}
9846
ed2b7c17
TT
9847/* Set this to the maximum number of seconds to wait instead of waiting forever
9848 in target_wait(). If this timer times out, then it generates an error and
9849 the command is aborted. This replaces most of the need for timeouts in the
9850 GDB test suite, and makes it possible to distinguish between a hung target
9851 and one with slow communications. */
9852
9853static int watchdog = 0;
9854static void
9855show_watchdog (struct ui_file *file, int from_tty,
9856 struct cmd_list_element *c, const char *value)
9857{
6cb06a8c 9858 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
ed2b7c17
TT
9859}
9860
c906108c 9861/* Read a packet from the remote machine, with error checking, and
8d64371b
TT
9862 store it in *BUF. Resize *BUF if necessary to hold the result. If
9863 FOREVER, wait forever rather than timing out; this is used (in
9864 synchronous mode) to wait for a target that is is executing user
9865 code to stop. */
d9fcf2fb
JM
9866/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9867 don't have to change all the calls to getpkt to deal with the
9868 return value, because at the moment I don't know what the right
23860348 9869 thing to do it for those. */
6b8edb51 9870
c906108c 9871void
8d64371b 9872remote_target::getpkt (gdb::char_vector *buf, int forever)
d9fcf2fb 9873{
8d64371b 9874 getpkt_sane (buf, forever);
d9fcf2fb
JM
9875}
9876
9877
9878/* Read a packet from the remote machine, with error checking, and
8d64371b
TT
9879 store it in *BUF. Resize *BUF if necessary to hold the result. If
9880 FOREVER, wait forever rather than timing out; this is used (in
9881 synchronous mode) to wait for a target that is is executing user
9882 code to stop. If FOREVER == 0, this function is allowed to time
9883 out gracefully and return an indication of this to the caller.
9884 Otherwise return the number of bytes read. If EXPECTING_NOTIF,
9885 consider receiving a notification enough reason to return to the
9886 caller. *IS_NOTIF is an output boolean that indicates whether *BUF
9887 holds a notification or not (a regular packet). */
74531fed 9888
6b8edb51 9889int
8d64371b 9890remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
6b8edb51
PA
9891 int forever, int expecting_notif,
9892 int *is_notif)
c906108c 9893{
2d717e4f 9894 struct remote_state *rs = get_remote_state ();
c906108c
SS
9895 int c;
9896 int tries;
9897 int timeout;
df4b58fe 9898 int val = -1;
c906108c 9899
8d64371b 9900 strcpy (buf->data (), "timeout");
c906108c
SS
9901
9902 if (forever)
74531fed
PA
9903 timeout = watchdog > 0 ? watchdog : -1;
9904 else if (expecting_notif)
9905 timeout = 0; /* There should already be a char in the buffer. If
9906 not, bail out. */
c906108c
SS
9907 else
9908 timeout = remote_timeout;
9909
9910#define MAX_TRIES 3
9911
74531fed
PA
9912 /* Process any number of notifications, and then return when
9913 we get a packet. */
9914 for (;;)
c906108c 9915 {
d9c43928 9916 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
9917 times. */
9918 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 9919 {
74531fed
PA
9920 /* This can loop forever if the remote side sends us
9921 characters continuously, but if it pauses, we'll get
9922 SERIAL_TIMEOUT from readchar because of timeout. Then
9923 we'll count that as a retry.
9924
9925 Note that even when forever is set, we will only wait
9926 forever prior to the start of a packet. After that, we
9927 expect characters to arrive at a brisk pace. They should
9928 show up within remote_timeout intervals. */
9929 do
9930 c = readchar (timeout);
9931 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
9932
9933 if (c == SERIAL_TIMEOUT)
9934 {
74531fed
PA
9935 if (expecting_notif)
9936 return -1; /* Don't complain, it's normal to not get
9937 anything in this case. */
9938
23860348 9939 if (forever) /* Watchdog went off? Kill the target. */
c906108c 9940 {
5b6d1e4f 9941 remote_unpush_target (this);
598d3636
JK
9942 throw_error (TARGET_CLOSE_ERROR,
9943 _("Watchdog timeout has expired. "
9944 "Target detached."));
c906108c 9945 }
2189c312
SM
9946
9947 remote_debug_printf ("Timed out.");
c906108c 9948 }
74531fed
PA
9949 else
9950 {
9951 /* We've found the start of a packet or notification.
9952 Now collect the data. */
8d64371b 9953 val = read_frame (buf);
74531fed
PA
9954 if (val >= 0)
9955 break;
9956 }
9957
c33e31fd 9958 remote_serial_write ("-", 1);
c906108c 9959 }
c906108c 9960
74531fed
PA
9961 if (tries > MAX_TRIES)
9962 {
9963 /* We have tried hard enough, and just can't receive the
9964 packet/notification. Give up. */
6cb06a8c 9965 gdb_printf (_("Ignoring packet error, continuing...\n"));
c906108c 9966
74531fed
PA
9967 /* Skip the ack char if we're in no-ack mode. */
9968 if (!rs->noack_mode)
c33e31fd 9969 remote_serial_write ("+", 1);
74531fed
PA
9970 return -1;
9971 }
c906108c 9972
74531fed
PA
9973 /* If we got an ordinary packet, return that to our caller. */
9974 if (c == '$')
c906108c
SS
9975 {
9976 if (remote_debug)
43e526b9 9977 {
6cc8564b
LM
9978 int max_chars;
9979
9980 if (remote_packet_max_chars < 0)
9981 max_chars = val;
9982 else
9983 max_chars = remote_packet_max_chars;
9984
6f8976bf 9985 std::string str
8d64371b 9986 = escape_buffer (buf->data (),
6cc8564b 9987 std::min (val, max_chars));
6f8976bf 9988
6cc8564b 9989 if (val > max_chars)
2189c312
SM
9990 remote_debug_printf_nofunc
9991 ("Packet received: %s [%d bytes omitted]", str.c_str (),
9992 val - max_chars);
9993 else
9994 remote_debug_printf_nofunc ("Packet received: %s",
9995 str.c_str ());
43e526b9 9996 }
a6f3e723
SL
9997
9998 /* Skip the ack char if we're in no-ack mode. */
9999 if (!rs->noack_mode)
c33e31fd 10000 remote_serial_write ("+", 1);
fee9eda9
YQ
10001 if (is_notif != NULL)
10002 *is_notif = 0;
0876f84a 10003 return val;
c906108c
SS
10004 }
10005
74531fed
PA
10006 /* If we got a notification, handle it, and go back to looking
10007 for a packet. */
10008 else
10009 {
10010 gdb_assert (c == '%');
10011
2189c312
SM
10012 remote_debug_printf_nofunc
10013 (" Notification received: %s",
10014 escape_buffer (buf->data (), val).c_str ());
6e5abd65 10015
fee9eda9
YQ
10016 if (is_notif != NULL)
10017 *is_notif = 1;
c906108c 10018
8d64371b 10019 handle_notification (rs->notif_state, buf->data ());
c906108c 10020
74531fed 10021 /* Notifications require no acknowledgement. */
a6f3e723 10022
74531fed 10023 if (expecting_notif)
fee9eda9 10024 return val;
74531fed
PA
10025 }
10026 }
10027}
10028
6b8edb51 10029int
8d64371b 10030remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
74531fed 10031{
8d64371b 10032 return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
74531fed
PA
10033}
10034
6b8edb51 10035int
8d64371b 10036remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
6b8edb51 10037 int *is_notif)
74531fed 10038{
8d64371b 10039 return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
c906108c 10040}
74531fed 10041
28561a65 10042/* Kill any new fork children of inferior INF that haven't been
cbb8991c
DB
10043 processed by follow_fork. */
10044
6b8edb51 10045void
28561a65 10046remote_target::kill_new_fork_children (inferior *inf)
cbb8991c 10047{
6b8edb51 10048 remote_state *rs = get_remote_state ();
cbb8991c 10049 struct notif_client *notif = &notif_client_stop;
cbb8991c 10050
28561a65
SM
10051 /* Kill the fork child threads of any threads in inferior INF that are stopped
10052 at a fork event. */
10053 for (thread_info *thread : inf->non_exited_threads ())
cbb8991c 10054 {
28561a65 10055 const target_waitstatus *ws = thread_pending_fork_status (thread);
cbb8991c 10056
28561a65
SM
10057 if (ws == nullptr)
10058 continue;
cbb8991c 10059
28561a65
SM
10060 int child_pid = ws->child_ptid ().pid ();
10061 int res = remote_vkill (child_pid);
10062
10063 if (res != 0)
10064 error (_("Can't kill fork child process %d"), child_pid);
cbb8991c
DB
10065 }
10066
10067 /* Check for any pending fork events (not reported or processed yet)
28561a65 10068 in inferior INF and kill those fork child threads as well. */
cbb8991c 10069 remote_notif_get_pending_events (notif);
953edf2b 10070 for (auto &event : rs->stop_reply_queue)
28561a65
SM
10071 {
10072 if (event->ptid.pid () != inf->pid)
10073 continue;
953edf2b 10074
28561a65
SM
10075 if (!is_fork_status (event->ws.kind ()))
10076 continue;
10077
10078 int child_pid = event->ws.child_ptid ().pid ();
10079 int res = remote_vkill (child_pid);
10080
10081 if (res != 0)
10082 error (_("Can't kill fork child process %d"), child_pid);
10083 }
cbb8991c
DB
10084}
10085
c906108c 10086\f
8020350c
DB
10087/* Target hook to kill the current inferior. */
10088
f6ac5f3d
PA
10089void
10090remote_target::kill ()
43ff13b4 10091{
8020350c 10092 int res = -1;
28561a65 10093 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
8020350c 10094 struct remote_state *rs = get_remote_state ();
0fdf84ca 10095
28561a65
SM
10096 gdb_assert (inf != nullptr);
10097
8020350c 10098 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 10099 {
8020350c
DB
10100 /* If we're stopped while forking and we haven't followed yet,
10101 kill the child task. We need to do this before killing the
10102 parent task because if this is a vfork then the parent will
10103 be sleeping. */
28561a65 10104 kill_new_fork_children (inf);
8020350c 10105
28561a65 10106 res = remote_vkill (inf->pid);
8020350c 10107 if (res == 0)
0fdf84ca 10108 {
bc1e6c81 10109 target_mourn_inferior (inferior_ptid);
0fdf84ca
PA
10110 return;
10111 }
8020350c 10112 }
0fdf84ca 10113
8020350c
DB
10114 /* If we are in 'target remote' mode and we are killing the only
10115 inferior, then we will tell gdbserver to exit and unpush the
10116 target. */
10117 if (res == -1 && !remote_multi_process_p (rs)
5b6d1e4f 10118 && number_of_live_inferiors (this) == 1)
8020350c
DB
10119 {
10120 remote_kill_k ();
10121
10122 /* We've killed the remote end, we get to mourn it. If we are
10123 not in extended mode, mourning the inferior also unpushes
10124 remote_ops from the target stack, which closes the remote
10125 connection. */
bc1e6c81 10126 target_mourn_inferior (inferior_ptid);
8020350c
DB
10127
10128 return;
0fdf84ca 10129 }
43ff13b4 10130
8020350c 10131 error (_("Can't kill process"));
43ff13b4
JM
10132}
10133
8020350c
DB
10134/* Send a kill request to the target using the 'vKill' packet. */
10135
6b8edb51
PA
10136int
10137remote_target::remote_vkill (int pid)
82f73884 10138{
4082afcc 10139 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
10140 return -1;
10141
6b8edb51
PA
10142 remote_state *rs = get_remote_state ();
10143
82f73884 10144 /* Tell the remote target to detach. */
8d64371b 10145 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
82f73884 10146 putpkt (rs->buf);
8d64371b 10147 getpkt (&rs->buf, 0);
82f73884 10148
4082afcc
PA
10149 switch (packet_ok (rs->buf,
10150 &remote_protocol_packets[PACKET_vKill]))
10151 {
10152 case PACKET_OK:
10153 return 0;
10154 case PACKET_ERROR:
10155 return 1;
10156 case PACKET_UNKNOWN:
10157 return -1;
10158 default:
10159 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
10160 }
82f73884
PA
10161}
10162
8020350c
DB
10163/* Send a kill request to the target using the 'k' packet. */
10164
6b8edb51
PA
10165void
10166remote_target::remote_kill_k ()
82f73884 10167{
8020350c
DB
10168 /* Catch errors so the user can quit from gdb even when we
10169 aren't on speaking terms with the remote system. */
a70b8144 10170 try
82f73884 10171 {
82f73884 10172 putpkt ("k");
82f73884 10173 }
230d2906 10174 catch (const gdb_exception_error &ex)
8020350c
DB
10175 {
10176 if (ex.error == TARGET_CLOSE_ERROR)
10177 {
10178 /* If we got an (EOF) error that caused the target
10179 to go away, then we're done, that's what we wanted.
10180 "k" is susceptible to cause a premature EOF, given
10181 that the remote server isn't actually required to
10182 reply to "k", and it can happen that it doesn't
10183 even get to reply ACK to the "k". */
10184 return;
10185 }
82f73884 10186
8020350c
DB
10187 /* Otherwise, something went wrong. We didn't actually kill
10188 the target. Just propagate the exception, and let the
10189 user or higher layers decide what to do. */
eedc3f4f 10190 throw;
8020350c 10191 }
82f73884
PA
10192}
10193
f6ac5f3d
PA
10194void
10195remote_target::mourn_inferior ()
c906108c 10196{
8020350c 10197 struct remote_state *rs = get_remote_state ();
ce5ce7ed 10198
9607784a
PA
10199 /* We're no longer interested in notification events of an inferior
10200 that exited or was killed/detached. */
10201 discard_pending_stop_replies (current_inferior ());
10202
8020350c 10203 /* In 'target remote' mode with one inferior, we close the connection. */
5b6d1e4f 10204 if (!rs->extended && number_of_live_inferiors (this) <= 1)
8020350c 10205 {
5b6d1e4f 10206 remote_unpush_target (this);
8020350c
DB
10207 return;
10208 }
c906108c 10209
e24a49d8
PA
10210 /* In case we got here due to an error, but we're going to stay
10211 connected. */
10212 rs->waiting_for_stop_reply = 0;
10213
dc1981d7
PA
10214 /* If the current general thread belonged to the process we just
10215 detached from or has exited, the remote side current general
10216 thread becomes undefined. Considering a case like this:
10217
10218 - We just got here due to a detach.
10219 - The process that we're detaching from happens to immediately
10220 report a global breakpoint being hit in non-stop mode, in the
10221 same thread we had selected before.
10222 - GDB attaches to this process again.
10223 - This event happens to be the next event we handle.
10224
10225 GDB would consider that the current general thread didn't need to
10226 be set on the stub side (with Hg), since for all it knew,
10227 GENERAL_THREAD hadn't changed.
10228
10229 Notice that although in all-stop mode, the remote server always
10230 sets the current thread to the thread reporting the stop event,
10231 that doesn't happen in non-stop mode; in non-stop, the stub *must
10232 not* change the current thread when reporting a breakpoint hit,
10233 due to the decoupling of event reporting and event handling.
10234
10235 To keep things simple, we always invalidate our notion of the
10236 current thread. */
47f8a51d 10237 record_currthread (rs, minus_one_ptid);
dc1981d7 10238
8020350c 10239 /* Call common code to mark the inferior as not running. */
48aa3c27 10240 generic_mourn_inferior ();
2d717e4f 10241}
c906108c 10242
57810aa7 10243bool
f6ac5f3d 10244extended_remote_target::supports_disable_randomization ()
03583c20 10245{
4082afcc 10246 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
10247}
10248
6b8edb51
PA
10249void
10250remote_target::extended_remote_disable_randomization (int val)
03583c20
UW
10251{
10252 struct remote_state *rs = get_remote_state ();
10253 char *reply;
10254
8d64371b
TT
10255 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10256 "QDisableRandomization:%x", val);
03583c20 10257 putpkt (rs->buf);
b6bb3468 10258 reply = remote_get_noisy_reply ();
03583c20
UW
10259 if (*reply == '\0')
10260 error (_("Target does not support QDisableRandomization."));
10261 if (strcmp (reply, "OK") != 0)
10262 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10263}
10264
6b8edb51
PA
10265int
10266remote_target::extended_remote_run (const std::string &args)
2d717e4f
DJ
10267{
10268 struct remote_state *rs = get_remote_state ();
2d717e4f 10269 int len;
94585166 10270 const char *remote_exec_file = get_remote_exec_file ();
c906108c 10271
2d717e4f
DJ
10272 /* If the user has disabled vRun support, or we have detected that
10273 support is not available, do not try it. */
4082afcc 10274 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 10275 return -1;
424163ea 10276
8d64371b
TT
10277 strcpy (rs->buf.data (), "vRun;");
10278 len = strlen (rs->buf.data ());
c906108c 10279
2d717e4f
DJ
10280 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10281 error (_("Remote file name too long for run packet"));
8d64371b 10282 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
9f1b45b0 10283 strlen (remote_exec_file));
2d717e4f 10284
7c5ded6a 10285 if (!args.empty ())
2d717e4f 10286 {
2d717e4f 10287 int i;
2d717e4f 10288
773a1edc 10289 gdb_argv argv (args.c_str ());
2d717e4f
DJ
10290 for (i = 0; argv[i] != NULL; i++)
10291 {
10292 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10293 error (_("Argument list too long for run packet"));
10294 rs->buf[len++] = ';';
8d64371b 10295 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
9f1b45b0 10296 strlen (argv[i]));
2d717e4f 10297 }
2d717e4f
DJ
10298 }
10299
10300 rs->buf[len++] = '\0';
10301
10302 putpkt (rs->buf);
8d64371b 10303 getpkt (&rs->buf, 0);
2d717e4f 10304
4082afcc 10305 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 10306 {
4082afcc 10307 case PACKET_OK:
3405876a 10308 /* We have a wait response. All is well. */
2d717e4f 10309 return 0;
4082afcc
PA
10310 case PACKET_UNKNOWN:
10311 return -1;
10312 case PACKET_ERROR:
2d717e4f
DJ
10313 if (remote_exec_file[0] == '\0')
10314 error (_("Running the default executable on the remote target failed; "
10315 "try \"set remote exec-file\"?"));
10316 else
10317 error (_("Running \"%s\" on the remote target failed"),
10318 remote_exec_file);
4082afcc 10319 default:
557b4d76 10320 gdb_assert_not_reached ("bad switch");
2d717e4f 10321 }
c906108c
SS
10322}
10323
0a2dde4a
SDJ
10324/* Helper function to send set/unset environment packets. ACTION is
10325 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10326 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10327 sent. */
10328
6b8edb51
PA
10329void
10330remote_target::send_environment_packet (const char *action,
10331 const char *packet,
10332 const char *value)
0a2dde4a 10333{
6b8edb51
PA
10334 remote_state *rs = get_remote_state ();
10335
0a2dde4a
SDJ
10336 /* Convert the environment variable to an hex string, which
10337 is the best format to be transmitted over the wire. */
10338 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10339 strlen (value));
10340
8d64371b 10341 xsnprintf (rs->buf.data (), get_remote_packet_size (),
0a2dde4a
SDJ
10342 "%s:%s", packet, encoded_value.c_str ());
10343
10344 putpkt (rs->buf);
8d64371b
TT
10345 getpkt (&rs->buf, 0);
10346 if (strcmp (rs->buf.data (), "OK") != 0)
0a2dde4a
SDJ
10347 warning (_("Unable to %s environment variable '%s' on remote."),
10348 action, value);
10349}
10350
10351/* Helper function to handle the QEnvironment* packets. */
10352
6b8edb51
PA
10353void
10354remote_target::extended_remote_environment_support ()
0a2dde4a 10355{
6b8edb51
PA
10356 remote_state *rs = get_remote_state ();
10357
0a2dde4a
SDJ
10358 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10359 {
10360 putpkt ("QEnvironmentReset");
8d64371b
TT
10361 getpkt (&rs->buf, 0);
10362 if (strcmp (rs->buf.data (), "OK") != 0)
0a2dde4a
SDJ
10363 warning (_("Unable to reset environment on remote."));
10364 }
10365
10366 gdb_environ *e = &current_inferior ()->environment;
10367
10368 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10369 for (const std::string &el : e->user_set_env ())
6b8edb51 10370 send_environment_packet ("set", "QEnvironmentHexEncoded",
0a2dde4a
SDJ
10371 el.c_str ());
10372
10373 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10374 for (const std::string &el : e->user_unset_env ())
6b8edb51 10375 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
0a2dde4a
SDJ
10376}
10377
bc3b087d
SDJ
10378/* Helper function to set the current working directory for the
10379 inferior in the remote target. */
10380
6b8edb51
PA
10381void
10382remote_target::extended_remote_set_inferior_cwd ()
bc3b087d
SDJ
10383{
10384 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10385 {
11bd012e 10386 const std::string &inferior_cwd = current_inferior ()->cwd ();
6b8edb51 10387 remote_state *rs = get_remote_state ();
bc3b087d 10388
11bd012e 10389 if (!inferior_cwd.empty ())
bc3b087d 10390 {
11bd012e
SM
10391 std::string hexpath
10392 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10393 inferior_cwd.size ());
bc3b087d 10394
8d64371b 10395 xsnprintf (rs->buf.data (), get_remote_packet_size (),
bc3b087d
SDJ
10396 "QSetWorkingDir:%s", hexpath.c_str ());
10397 }
10398 else
10399 {
10400 /* An empty inferior_cwd means that the user wants us to
10401 reset the remote server's inferior's cwd. */
8d64371b 10402 xsnprintf (rs->buf.data (), get_remote_packet_size (),
bc3b087d
SDJ
10403 "QSetWorkingDir:");
10404 }
10405
10406 putpkt (rs->buf);
8d64371b 10407 getpkt (&rs->buf, 0);
bc3b087d
SDJ
10408 if (packet_ok (rs->buf,
10409 &remote_protocol_packets[PACKET_QSetWorkingDir])
10410 != PACKET_OK)
10411 error (_("\
10412Remote replied unexpectedly while setting the inferior's working\n\
10413directory: %s"),
8d64371b 10414 rs->buf.data ());
bc3b087d
SDJ
10415
10416 }
10417}
10418
2d717e4f
DJ
10419/* In the extended protocol we want to be able to do things like
10420 "run" and have them basically work as expected. So we need
10421 a special create_inferior function. We support changing the
10422 executable file and the command line arguments, but not the
10423 environment. */
10424
f6ac5f3d
PA
10425void
10426extended_remote_target::create_inferior (const char *exec_file,
10427 const std::string &args,
10428 char **env, int from_tty)
43ff13b4 10429{
3405876a
PA
10430 int run_worked;
10431 char *stop_reply;
10432 struct remote_state *rs = get_remote_state ();
94585166 10433 const char *remote_exec_file = get_remote_exec_file ();
3405876a 10434
43ff13b4 10435 /* If running asynchronously, register the target file descriptor
23860348 10436 with the event loop. */
75c99385 10437 if (target_can_async_p ())
6a3753b3 10438 target_async (1);
43ff13b4 10439
03583c20 10440 /* Disable address space randomization if requested (and supported). */
f6ac5f3d 10441 if (supports_disable_randomization ())
03583c20
UW
10442 extended_remote_disable_randomization (disable_randomization);
10443
aefd8b33
SDJ
10444 /* If startup-with-shell is on, we inform gdbserver to start the
10445 remote inferior using a shell. */
10446 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10447 {
8d64371b 10448 xsnprintf (rs->buf.data (), get_remote_packet_size (),
aefd8b33
SDJ
10449 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10450 putpkt (rs->buf);
8d64371b
TT
10451 getpkt (&rs->buf, 0);
10452 if (strcmp (rs->buf.data (), "OK") != 0)
aefd8b33
SDJ
10453 error (_("\
10454Remote replied unexpectedly while setting startup-with-shell: %s"),
8d64371b 10455 rs->buf.data ());
aefd8b33
SDJ
10456 }
10457
6b8edb51 10458 extended_remote_environment_support ();
0a2dde4a 10459
6b8edb51 10460 extended_remote_set_inferior_cwd ();
bc3b087d 10461
43ff13b4 10462 /* Now restart the remote server. */
3405876a
PA
10463 run_worked = extended_remote_run (args) != -1;
10464 if (!run_worked)
2d717e4f
DJ
10465 {
10466 /* vRun was not supported. Fail if we need it to do what the
10467 user requested. */
10468 if (remote_exec_file[0])
10469 error (_("Remote target does not support \"set remote exec-file\""));
7c5ded6a 10470 if (!args.empty ())
65e65158 10471 error (_("Remote target does not support \"set args\" or run ARGS"));
43ff13b4 10472
2d717e4f
DJ
10473 /* Fall back to "R". */
10474 extended_remote_restart ();
10475 }
424163ea 10476
3405876a 10477 /* vRun's success return is a stop reply. */
8d64371b 10478 stop_reply = run_worked ? rs->buf.data () : NULL;
3405876a 10479 add_current_inferior_and_thread (stop_reply);
c0a2216e 10480
2d717e4f
DJ
10481 /* Get updated offsets, if the stub uses qOffsets. */
10482 get_offsets ();
2d717e4f 10483}
c906108c 10484\f
c5aa993b 10485
b775012e
LM
10486/* Given a location's target info BP_TGT and the packet buffer BUF, output
10487 the list of conditions (in agent expression bytecode format), if any, the
10488 target needs to evaluate. The output is placed into the packet buffer
bba74b36 10489 started from BUF and ended at BUF_END. */
b775012e
LM
10490
10491static int
10492remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
10493 struct bp_target_info *bp_tgt, char *buf,
10494 char *buf_end)
b775012e 10495{
3cde5c42 10496 if (bp_tgt->conditions.empty ())
b775012e
LM
10497 return 0;
10498
10499 buf += strlen (buf);
bba74b36 10500 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
10501 buf++;
10502
83621223 10503 /* Send conditions to the target. */
d538e36d 10504 for (agent_expr *aexpr : bp_tgt->conditions)
b775012e 10505 {
bba74b36 10506 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e 10507 buf += strlen (buf);
3cde5c42 10508 for (int i = 0; i < aexpr->len; ++i)
b775012e
LM
10509 buf = pack_hex_byte (buf, aexpr->buf[i]);
10510 *buf = '\0';
10511 }
b775012e
LM
10512 return 0;
10513}
10514
d3ce09f5
SS
10515static void
10516remote_add_target_side_commands (struct gdbarch *gdbarch,
10517 struct bp_target_info *bp_tgt, char *buf)
10518{
3cde5c42 10519 if (bp_tgt->tcommands.empty ())
d3ce09f5
SS
10520 return;
10521
10522 buf += strlen (buf);
10523
10524 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10525 buf += strlen (buf);
10526
10527 /* Concatenate all the agent expressions that are commands into the
10528 cmds parameter. */
df97be55 10529 for (agent_expr *aexpr : bp_tgt->tcommands)
d3ce09f5
SS
10530 {
10531 sprintf (buf, "X%x,", aexpr->len);
10532 buf += strlen (buf);
3cde5c42 10533 for (int i = 0; i < aexpr->len; ++i)
d3ce09f5
SS
10534 buf = pack_hex_byte (buf, aexpr->buf[i]);
10535 *buf = '\0';
10536 }
d3ce09f5
SS
10537}
10538
8181d85f
DJ
10539/* Insert a breakpoint. On targets that have software breakpoint
10540 support, we ask the remote target to do the work; on targets
10541 which don't, we insert a traditional memory breakpoint. */
c906108c 10542
f6ac5f3d
PA
10543int
10544remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10545 struct bp_target_info *bp_tgt)
c906108c 10546{
d471ea57
AC
10547 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10548 If it succeeds, then set the support to PACKET_ENABLE. If it
10549 fails, and the user has explicitly requested the Z support then
23860348 10550 report an error, otherwise, mark it disabled and go on. */
802188a7 10551
4082afcc 10552 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10553 {
0d5ed153 10554 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10555 struct remote_state *rs;
bba74b36 10556 char *p, *endbuf;
4fff2411 10557
28439a30
PA
10558 /* Make sure the remote is pointing at the right process, if
10559 necessary. */
10560 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10561 set_general_process ();
10562
4fff2411 10563 rs = get_remote_state ();
8d64371b
TT
10564 p = rs->buf.data ();
10565 endbuf = p + get_remote_packet_size ();
802188a7 10566
96baa820
JM
10567 *(p++) = 'Z';
10568 *(p++) = '0';
10569 *(p++) = ',';
7c0f6dcc 10570 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 10571 p += hexnumstr (p, addr);
579c6ad9 10572 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10573
f6ac5f3d 10574 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10575 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10576
f6ac5f3d 10577 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10578 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10579
6d820c5c 10580 putpkt (rs->buf);
8d64371b 10581 getpkt (&rs->buf, 0);
96baa820 10582
6d820c5c 10583 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 10584 {
d471ea57
AC
10585 case PACKET_ERROR:
10586 return -1;
10587 case PACKET_OK:
10588 return 0;
10589 case PACKET_UNKNOWN:
10590 break;
96baa820
JM
10591 }
10592 }
c906108c 10593
0000e5cc
PA
10594 /* If this breakpoint has target-side commands but this stub doesn't
10595 support Z0 packets, throw error. */
3cde5c42 10596 if (!bp_tgt->tcommands.empty ())
0000e5cc
PA
10597 throw_error (NOT_SUPPORTED_ERROR, _("\
10598Target doesn't support breakpoints that have target side commands."));
10599
f6ac5f3d 10600 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
c906108c
SS
10601}
10602
f6ac5f3d
PA
10603int
10604remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10605 struct bp_target_info *bp_tgt,
10606 enum remove_bp_reason reason)
c906108c 10607{
8181d85f 10608 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 10609 struct remote_state *rs = get_remote_state ();
96baa820 10610
4082afcc 10611 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10612 {
8d64371b
TT
10613 char *p = rs->buf.data ();
10614 char *endbuf = p + get_remote_packet_size ();
802188a7 10615
28439a30
PA
10616 /* Make sure the remote is pointing at the right process, if
10617 necessary. */
10618 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10619 set_general_process ();
10620
96baa820
JM
10621 *(p++) = 'z';
10622 *(p++) = '0';
10623 *(p++) = ',';
10624
8181d85f
DJ
10625 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10626 p += hexnumstr (p, addr);
579c6ad9 10627 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10628
6d820c5c 10629 putpkt (rs->buf);
8d64371b 10630 getpkt (&rs->buf, 0);
96baa820 10631
6d820c5c 10632 return (rs->buf[0] == 'E');
96baa820
JM
10633 }
10634
f6ac5f3d 10635 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
c906108c
SS
10636}
10637
f486487f 10638static enum Z_packet_type
d471ea57
AC
10639watchpoint_to_Z_packet (int type)
10640{
10641 switch (type)
10642 {
10643 case hw_write:
bb858e6a 10644 return Z_PACKET_WRITE_WP;
d471ea57
AC
10645 break;
10646 case hw_read:
bb858e6a 10647 return Z_PACKET_READ_WP;
d471ea57
AC
10648 break;
10649 case hw_access:
bb858e6a 10650 return Z_PACKET_ACCESS_WP;
d471ea57
AC
10651 break;
10652 default:
8e65ff28 10653 internal_error (__FILE__, __LINE__,
e2e0b3e5 10654 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
10655 }
10656}
10657
f6ac5f3d
PA
10658int
10659remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10660 enum target_hw_bp_type type, struct expression *cond)
96baa820 10661{
d01949b6 10662 struct remote_state *rs = get_remote_state ();
8d64371b 10663 char *endbuf = rs->buf.data () + get_remote_packet_size ();
e514a9d6 10664 char *p;
d471ea57 10665 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 10666
4082afcc 10667 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 10668 return 1;
802188a7 10669
28439a30
PA
10670 /* Make sure the remote is pointing at the right process, if
10671 necessary. */
10672 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10673 set_general_process ();
10674
8d64371b
TT
10675 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10676 p = strchr (rs->buf.data (), '\0');
96baa820
JM
10677 addr = remote_address_masked (addr);
10678 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10679 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 10680
6d820c5c 10681 putpkt (rs->buf);
8d64371b 10682 getpkt (&rs->buf, 0);
96baa820 10683
6d820c5c 10684 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10685 {
10686 case PACKET_ERROR:
d471ea57 10687 return -1;
85d721b8
PA
10688 case PACKET_UNKNOWN:
10689 return 1;
d471ea57
AC
10690 case PACKET_OK:
10691 return 0;
10692 }
8e65ff28 10693 internal_error (__FILE__, __LINE__,
e2e0b3e5 10694 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
10695}
10696
57810aa7 10697bool
f6ac5f3d
PA
10698remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10699 CORE_ADDR start, int length)
283002cf
MR
10700{
10701 CORE_ADDR diff = remote_address_masked (addr - start);
10702
10703 return diff < length;
10704}
10705
d471ea57 10706
f6ac5f3d
PA
10707int
10708remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10709 enum target_hw_bp_type type, struct expression *cond)
96baa820 10710{
d01949b6 10711 struct remote_state *rs = get_remote_state ();
8d64371b 10712 char *endbuf = rs->buf.data () + get_remote_packet_size ();
e514a9d6 10713 char *p;
d471ea57
AC
10714 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10715
4082afcc 10716 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 10717 return -1;
802188a7 10718
28439a30
PA
10719 /* Make sure the remote is pointing at the right process, if
10720 necessary. */
10721 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10722 set_general_process ();
10723
8d64371b
TT
10724 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10725 p = strchr (rs->buf.data (), '\0');
96baa820
JM
10726 addr = remote_address_masked (addr);
10727 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10728 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c 10729 putpkt (rs->buf);
8d64371b 10730 getpkt (&rs->buf, 0);
96baa820 10731
6d820c5c 10732 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10733 {
10734 case PACKET_ERROR:
10735 case PACKET_UNKNOWN:
10736 return -1;
10737 case PACKET_OK:
10738 return 0;
10739 }
8e65ff28 10740 internal_error (__FILE__, __LINE__,
e2e0b3e5 10741 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
10742}
10743
3c3bea1c 10744
60fcc1c3
TT
10745static int remote_hw_watchpoint_limit = -1;
10746static int remote_hw_watchpoint_length_limit = -1;
10747static int remote_hw_breakpoint_limit = -1;
d471ea57 10748
f6ac5f3d
PA
10749int
10750remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
480a3f21
PW
10751{
10752 if (remote_hw_watchpoint_length_limit == 0)
10753 return 0;
10754 else if (remote_hw_watchpoint_length_limit < 0)
10755 return 1;
10756 else if (len <= remote_hw_watchpoint_length_limit)
10757 return 1;
10758 else
10759 return 0;
10760}
10761
f6ac5f3d
PA
10762int
10763remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
96baa820 10764{
3c3bea1c
GS
10765 if (type == bp_hardware_breakpoint)
10766 {
10767 if (remote_hw_breakpoint_limit == 0)
10768 return 0;
501eef12
AC
10769 else if (remote_hw_breakpoint_limit < 0)
10770 return 1;
3c3bea1c
GS
10771 else if (cnt <= remote_hw_breakpoint_limit)
10772 return 1;
10773 }
10774 else
10775 {
10776 if (remote_hw_watchpoint_limit == 0)
10777 return 0;
501eef12
AC
10778 else if (remote_hw_watchpoint_limit < 0)
10779 return 1;
3c3bea1c
GS
10780 else if (ot)
10781 return -1;
10782 else if (cnt <= remote_hw_watchpoint_limit)
10783 return 1;
10784 }
10785 return -1;
10786}
10787
f7e6eed5
PA
10788/* The to_stopped_by_sw_breakpoint method of target remote. */
10789
57810aa7 10790bool
f6ac5f3d 10791remote_target::stopped_by_sw_breakpoint ()
f7e6eed5 10792{
799a2abe 10793 struct thread_info *thread = inferior_thread ();
f7e6eed5 10794
799a2abe 10795 return (thread->priv != NULL
7aabaf9d
SM
10796 && (get_remote_thread_info (thread)->stop_reason
10797 == TARGET_STOPPED_BY_SW_BREAKPOINT));
f7e6eed5
PA
10798}
10799
10800/* The to_supports_stopped_by_sw_breakpoint method of target
10801 remote. */
10802
57810aa7 10803bool
f6ac5f3d 10804remote_target::supports_stopped_by_sw_breakpoint ()
f7e6eed5 10805{
f7e6eed5
PA
10806 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10807}
10808
10809/* The to_stopped_by_hw_breakpoint method of target remote. */
10810
57810aa7 10811bool
f6ac5f3d 10812remote_target::stopped_by_hw_breakpoint ()
f7e6eed5 10813{
799a2abe 10814 struct thread_info *thread = inferior_thread ();
f7e6eed5 10815
799a2abe 10816 return (thread->priv != NULL
7aabaf9d
SM
10817 && (get_remote_thread_info (thread)->stop_reason
10818 == TARGET_STOPPED_BY_HW_BREAKPOINT));
f7e6eed5
PA
10819}
10820
10821/* The to_supports_stopped_by_hw_breakpoint method of target
10822 remote. */
10823
57810aa7 10824bool
f6ac5f3d 10825remote_target::supports_stopped_by_hw_breakpoint ()
f7e6eed5 10826{
f7e6eed5
PA
10827 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10828}
10829
57810aa7 10830bool
f6ac5f3d 10831remote_target::stopped_by_watchpoint ()
3c3bea1c 10832{
799a2abe 10833 struct thread_info *thread = inferior_thread ();
ee154bee 10834
799a2abe 10835 return (thread->priv != NULL
7aabaf9d
SM
10836 && (get_remote_thread_info (thread)->stop_reason
10837 == TARGET_STOPPED_BY_WATCHPOINT));
3c3bea1c
GS
10838}
10839
57810aa7 10840bool
f6ac5f3d 10841remote_target::stopped_data_address (CORE_ADDR *addr_p)
3c3bea1c 10842{
799a2abe 10843 struct thread_info *thread = inferior_thread ();
a744cf53 10844
799a2abe 10845 if (thread->priv != NULL
7aabaf9d
SM
10846 && (get_remote_thread_info (thread)->stop_reason
10847 == TARGET_STOPPED_BY_WATCHPOINT))
4aa7a7f5 10848 {
7aabaf9d 10849 *addr_p = get_remote_thread_info (thread)->watch_data_address;
57810aa7 10850 return true;
4aa7a7f5
JJ
10851 }
10852
57810aa7 10853 return false;
3c3bea1c
GS
10854}
10855
10856
f6ac5f3d
PA
10857int
10858remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10859 struct bp_target_info *bp_tgt)
3c3bea1c 10860{
0d5ed153 10861 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10862 struct remote_state *rs;
bba74b36 10863 char *p, *endbuf;
dd61ec5c 10864 char *message;
3c3bea1c 10865
4082afcc 10866 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10867 return -1;
2bc416ba 10868
28439a30
PA
10869 /* Make sure the remote is pointing at the right process, if
10870 necessary. */
10871 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10872 set_general_process ();
10873
4fff2411 10874 rs = get_remote_state ();
8d64371b
TT
10875 p = rs->buf.data ();
10876 endbuf = p + get_remote_packet_size ();
4fff2411 10877
96baa820
JM
10878 *(p++) = 'Z';
10879 *(p++) = '1';
10880 *(p++) = ',';
802188a7 10881
0d5ed153 10882 addr = remote_address_masked (addr);
96baa820 10883 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10884 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10885
f6ac5f3d 10886 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10887 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10888
f6ac5f3d 10889 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10890 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10891
6d820c5c 10892 putpkt (rs->buf);
8d64371b 10893 getpkt (&rs->buf, 0);
96baa820 10894
6d820c5c 10895 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10896 {
10897 case PACKET_ERROR:
dd61ec5c 10898 if (rs->buf[1] == '.')
dda83cd7
SM
10899 {
10900 message = strchr (&rs->buf[2], '.');
10901 if (message)
10902 error (_("Remote failure reply: %s"), message + 1);
10903 }
dd61ec5c 10904 return -1;
d471ea57
AC
10905 case PACKET_UNKNOWN:
10906 return -1;
10907 case PACKET_OK:
10908 return 0;
10909 }
8e65ff28 10910 internal_error (__FILE__, __LINE__,
e2e0b3e5 10911 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
10912}
10913
d471ea57 10914
f6ac5f3d
PA
10915int
10916remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10917 struct bp_target_info *bp_tgt)
96baa820 10918{
8181d85f 10919 CORE_ADDR addr;
d01949b6 10920 struct remote_state *rs = get_remote_state ();
8d64371b
TT
10921 char *p = rs->buf.data ();
10922 char *endbuf = p + get_remote_packet_size ();
c8189ed1 10923
4082afcc 10924 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10925 return -1;
802188a7 10926
28439a30
PA
10927 /* Make sure the remote is pointing at the right process, if
10928 necessary. */
10929 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10930 set_general_process ();
10931
96baa820
JM
10932 *(p++) = 'z';
10933 *(p++) = '1';
10934 *(p++) = ',';
802188a7 10935
8181d85f 10936 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 10937 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10938 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10939
6d820c5c 10940 putpkt (rs->buf);
8d64371b 10941 getpkt (&rs->buf, 0);
802188a7 10942
6d820c5c 10943 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10944 {
10945 case PACKET_ERROR:
10946 case PACKET_UNKNOWN:
10947 return -1;
10948 case PACKET_OK:
10949 return 0;
10950 }
8e65ff28 10951 internal_error (__FILE__, __LINE__,
e2e0b3e5 10952 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 10953}
96baa820 10954
4a5e7a5b
PA
10955/* Verify memory using the "qCRC:" request. */
10956
f6ac5f3d
PA
10957int
10958remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
4a5e7a5b
PA
10959{
10960 struct remote_state *rs = get_remote_state ();
10961 unsigned long host_crc, target_crc;
10962 char *tmp;
10963
936d2992
PA
10964 /* It doesn't make sense to use qCRC if the remote target is
10965 connected but not running. */
55f6301a
TT
10966 if (target_has_execution ()
10967 && packet_support (PACKET_qCRC) != PACKET_DISABLE)
936d2992
PA
10968 {
10969 enum packet_result result;
28439a30 10970
936d2992
PA
10971 /* Make sure the remote is pointing at the right process. */
10972 set_general_process ();
4a5e7a5b 10973
936d2992 10974 /* FIXME: assumes lma can fit into long. */
8d64371b 10975 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
936d2992
PA
10976 (long) lma, (long) size);
10977 putpkt (rs->buf);
4a5e7a5b 10978
936d2992
PA
10979 /* Be clever; compute the host_crc before waiting for target
10980 reply. */
10981 host_crc = xcrc32 (data, size, 0xffffffff);
10982
8d64371b 10983 getpkt (&rs->buf, 0);
4a5e7a5b 10984
936d2992
PA
10985 result = packet_ok (rs->buf,
10986 &remote_protocol_packets[PACKET_qCRC]);
10987 if (result == PACKET_ERROR)
10988 return -1;
10989 else if (result == PACKET_OK)
10990 {
10991 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10992 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 10993
936d2992
PA
10994 return (host_crc == target_crc);
10995 }
10996 }
4a5e7a5b 10997
f6ac5f3d 10998 return simple_verify_memory (this, data, lma, size);
4a5e7a5b
PA
10999}
11000
c906108c
SS
11001/* compare-sections command
11002
11003 With no arguments, compares each loadable section in the exec bfd
11004 with the same memory range on the target, and reports mismatches.
4a5e7a5b 11005 Useful for verifying the image on the target against the exec file. */
e514a9d6 11006
c906108c 11007static void
ac88e2de 11008compare_sections_command (const char *args, int from_tty)
c906108c
SS
11009{
11010 asection *s;
ce359b09 11011 const char *sectname;
c906108c
SS
11012 bfd_size_type size;
11013 bfd_vma lma;
11014 int matched = 0;
11015 int mismatched = 0;
4a5e7a5b 11016 int res;
95cf3b38 11017 int read_only = 0;
c906108c 11018
7e10abd1 11019 if (!current_program_space->exec_bfd ())
8a3fe4f8 11020 error (_("command cannot be used without an exec file"));
c906108c 11021
95cf3b38
DT
11022 if (args != NULL && strcmp (args, "-r") == 0)
11023 {
11024 read_only = 1;
11025 args = NULL;
11026 }
11027
7e10abd1 11028 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
c906108c
SS
11029 {
11030 if (!(s->flags & SEC_LOAD))
0df8b418 11031 continue; /* Skip non-loadable section. */
c906108c 11032
95cf3b38
DT
11033 if (read_only && (s->flags & SEC_READONLY) == 0)
11034 continue; /* Skip writeable sections */
11035
fd361982 11036 size = bfd_section_size (s);
c906108c 11037 if (size == 0)
0df8b418 11038 continue; /* Skip zero-length section. */
c906108c 11039
fd361982 11040 sectname = bfd_section_name (s);
c906108c 11041 if (args && strcmp (args, sectname) != 0)
0df8b418 11042 continue; /* Not the section selected by user. */
c906108c 11043
0df8b418 11044 matched = 1; /* Do this section. */
c906108c 11045 lma = s->lma;
c906108c 11046
b80406ac 11047 gdb::byte_vector sectdata (size);
7e10abd1
TT
11048 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11049 sectdata.data (), 0, size);
c906108c 11050
b80406ac 11051 res = target_verify_memory (sectdata.data (), lma, size);
4a5e7a5b
PA
11052
11053 if (res == -1)
5af949e3 11054 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
11055 paddress (target_gdbarch (), lma),
11056 paddress (target_gdbarch (), lma + size));
c906108c 11057
6cb06a8c
TT
11058 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11059 paddress (target_gdbarch (), lma),
11060 paddress (target_gdbarch (), lma + size));
4a5e7a5b 11061 if (res)
6cb06a8c 11062 gdb_printf ("matched.\n");
c906108c 11063 else
c5aa993b 11064 {
6cb06a8c 11065 gdb_printf ("MIS-MATCHED!\n");
c5aa993b
JM
11066 mismatched++;
11067 }
c906108c
SS
11068 }
11069 if (mismatched > 0)
936d2992 11070 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 11071the loaded file\n"));
c906108c 11072 if (args && !matched)
6cb06a8c 11073 gdb_printf (_("No loaded section named '%s'.\n"), args);
c906108c
SS
11074}
11075
0e7f50da
UW
11076/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11077 into remote target. The number of bytes written to the remote
11078 target is returned, or -1 for error. */
11079
6b8edb51
PA
11080target_xfer_status
11081remote_target::remote_write_qxfer (const char *object_name,
11082 const char *annex, const gdb_byte *writebuf,
11083 ULONGEST offset, LONGEST len,
11084 ULONGEST *xfered_len,
11085 struct packet_config *packet)
0e7f50da
UW
11086{
11087 int i, buf_len;
11088 ULONGEST n;
0e7f50da
UW
11089 struct remote_state *rs = get_remote_state ();
11090 int max_size = get_memory_write_packet_size ();
11091
7cc244de 11092 if (packet_config_support (packet) == PACKET_DISABLE)
2ed4b548 11093 return TARGET_XFER_E_IO;
0e7f50da
UW
11094
11095 /* Insert header. */
8d64371b 11096 i = snprintf (rs->buf.data (), max_size,
0e7f50da
UW
11097 "qXfer:%s:write:%s:%s:",
11098 object_name, annex ? annex : "",
11099 phex_nz (offset, sizeof offset));
11100 max_size -= (i + 1);
11101
11102 /* Escape as much data as fits into rs->buf. */
11103 buf_len = remote_escape_output
8d64371b 11104 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
0e7f50da 11105
8d64371b
TT
11106 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11107 || getpkt_sane (&rs->buf, 0) < 0
0e7f50da 11108 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 11109 return TARGET_XFER_E_IO;
0e7f50da 11110
8d64371b 11111 unpack_varlen_hex (rs->buf.data (), &n);
9b409511
YQ
11112
11113 *xfered_len = n;
92ffd475 11114 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
0e7f50da
UW
11115}
11116
0876f84a
DJ
11117/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11118 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11119 number of bytes read is returned, or 0 for EOF, or -1 for error.
11120 The number of bytes read may be less than LEN without indicating an
11121 EOF. PACKET is checked and updated to indicate whether the remote
11122 target supports this object. */
11123
6b8edb51
PA
11124target_xfer_status
11125remote_target::remote_read_qxfer (const char *object_name,
11126 const char *annex,
11127 gdb_byte *readbuf, ULONGEST offset,
11128 LONGEST len,
11129 ULONGEST *xfered_len,
11130 struct packet_config *packet)
0876f84a 11131{
0876f84a 11132 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
11133 LONGEST i, n, packet_len;
11134
7cc244de 11135 if (packet_config_support (packet) == PACKET_DISABLE)
2ed4b548 11136 return TARGET_XFER_E_IO;
0876f84a
DJ
11137
11138 /* Check whether we've cached an end-of-object packet that matches
11139 this request. */
8e88304f 11140 if (rs->finished_object)
0876f84a 11141 {
8e88304f
TT
11142 if (strcmp (object_name, rs->finished_object) == 0
11143 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11144 && offset == rs->finished_offset)
9b409511
YQ
11145 return TARGET_XFER_EOF;
11146
0876f84a
DJ
11147
11148 /* Otherwise, we're now reading something different. Discard
11149 the cache. */
8e88304f
TT
11150 xfree (rs->finished_object);
11151 xfree (rs->finished_annex);
11152 rs->finished_object = NULL;
11153 rs->finished_annex = NULL;
0876f84a
DJ
11154 }
11155
11156 /* Request only enough to fit in a single packet. The actual data
11157 may not, since we don't know how much of it will need to be escaped;
11158 the target is free to respond with slightly less data. We subtract
11159 five to account for the response type and the protocol frame. */
768adc05 11160 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
8d64371b
TT
11161 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11162 "qXfer:%s:read:%s:%s,%s",
0876f84a
DJ
11163 object_name, annex ? annex : "",
11164 phex_nz (offset, sizeof offset),
11165 phex_nz (n, sizeof n));
11166 i = putpkt (rs->buf);
11167 if (i < 0)
2ed4b548 11168 return TARGET_XFER_E_IO;
0876f84a
DJ
11169
11170 rs->buf[0] = '\0';
8d64371b 11171 packet_len = getpkt_sane (&rs->buf, 0);
0876f84a 11172 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 11173 return TARGET_XFER_E_IO;
0876f84a
DJ
11174
11175 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8d64371b 11176 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
0876f84a
DJ
11177
11178 /* 'm' means there is (or at least might be) more data after this
11179 batch. That does not make sense unless there's at least one byte
11180 of data in this reply. */
11181 if (rs->buf[0] == 'm' && packet_len == 1)
11182 error (_("Remote qXfer reply contained no data."));
11183
11184 /* Got some data. */
8d64371b 11185 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
bc20a4af 11186 packet_len - 1, readbuf, n);
0876f84a
DJ
11187
11188 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
11189 or possibly empty. If we have the final block of a non-empty
11190 object, record this fact to bypass a subsequent partial read. */
11191 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 11192 {
8e88304f
TT
11193 rs->finished_object = xstrdup (object_name);
11194 rs->finished_annex = xstrdup (annex ? annex : "");
11195 rs->finished_offset = offset + i;
0876f84a
DJ
11196 }
11197
9b409511
YQ
11198 if (i == 0)
11199 return TARGET_XFER_EOF;
11200 else
11201 {
11202 *xfered_len = i;
11203 return TARGET_XFER_OK;
11204 }
0876f84a
DJ
11205}
11206
f6ac5f3d
PA
11207enum target_xfer_status
11208remote_target::xfer_partial (enum target_object object,
11209 const char *annex, gdb_byte *readbuf,
11210 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11211 ULONGEST *xfered_len)
c906108c 11212{
82f73884 11213 struct remote_state *rs;
c906108c 11214 int i;
6d820c5c 11215 char *p2;
1e3ff5ad 11216 char query_type;
124e13d9 11217 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 11218
e6e4e701 11219 set_remote_traceframe ();
82f73884
PA
11220 set_general_thread (inferior_ptid);
11221
11222 rs = get_remote_state ();
11223
b2182ed2 11224 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
11225 if (object == TARGET_OBJECT_MEMORY)
11226 {
2d717e4f
DJ
11227 /* If the remote target is connected but not running, we should
11228 pass this request down to a lower stratum (e.g. the executable
11229 file). */
55f6301a 11230 if (!target_has_execution ())
9b409511 11231 return TARGET_XFER_EOF;
2d717e4f 11232
21e3b9b9 11233 if (writebuf != NULL)
124e13d9
SM
11234 return remote_write_bytes (offset, writebuf, len, unit_size,
11235 xfered_len);
21e3b9b9 11236 else
6b8edb51 11237 return remote_read_bytes (offset, readbuf, len, unit_size,
124e13d9 11238 xfered_len);
21e3b9b9
DJ
11239 }
11240
4aa995e1
PA
11241 /* Handle extra signal info using qxfer packets. */
11242 if (object == TARGET_OBJECT_SIGNAL_INFO)
11243 {
11244 if (readbuf)
f6ac5f3d 11245 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
9b409511 11246 xfered_len, &remote_protocol_packets
4aa995e1
PA
11247 [PACKET_qXfer_siginfo_read]);
11248 else
f6ac5f3d 11249 return remote_write_qxfer ("siginfo", annex,
9b409511 11250 writebuf, offset, len, xfered_len,
4aa995e1
PA
11251 &remote_protocol_packets
11252 [PACKET_qXfer_siginfo_write]);
11253 }
11254
0fb4aa4b
PA
11255 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11256 {
11257 if (readbuf)
f6ac5f3d 11258 return remote_read_qxfer ("statictrace", annex,
9b409511 11259 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
11260 &remote_protocol_packets
11261 [PACKET_qXfer_statictrace_read]);
11262 else
2ed4b548 11263 return TARGET_XFER_E_IO;
0fb4aa4b
PA
11264 }
11265
a76d924d
DJ
11266 /* Only handle flash writes. */
11267 if (writebuf != NULL)
11268 {
a76d924d
DJ
11269 switch (object)
11270 {
11271 case TARGET_OBJECT_FLASH:
6b8edb51 11272 return remote_flash_write (offset, len, xfered_len,
9b409511 11273 writebuf);
a76d924d
DJ
11274
11275 default:
2ed4b548 11276 return TARGET_XFER_E_IO;
a76d924d
DJ
11277 }
11278 }
4b8a223f 11279
1e3ff5ad
AC
11280 /* Map pre-existing objects onto letters. DO NOT do this for new
11281 objects!!! Instead specify new query packets. */
11282 switch (object)
c906108c 11283 {
1e3ff5ad
AC
11284 case TARGET_OBJECT_AVR:
11285 query_type = 'R';
11286 break;
802188a7
RM
11287
11288 case TARGET_OBJECT_AUXV:
0876f84a 11289 gdb_assert (annex == NULL);
f6ac5f3d 11290 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
9b409511 11291 xfered_len,
0876f84a 11292 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 11293
23181151
DJ
11294 case TARGET_OBJECT_AVAILABLE_FEATURES:
11295 return remote_read_qxfer
f6ac5f3d 11296 ("features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
11297 &remote_protocol_packets[PACKET_qXfer_features]);
11298
cfa9d6d9
DJ
11299 case TARGET_OBJECT_LIBRARIES:
11300 return remote_read_qxfer
f6ac5f3d 11301 ("libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
11302 &remote_protocol_packets[PACKET_qXfer_libraries]);
11303
2268b414
JK
11304 case TARGET_OBJECT_LIBRARIES_SVR4:
11305 return remote_read_qxfer
f6ac5f3d 11306 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
11307 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
11308
fd79ecee
DJ
11309 case TARGET_OBJECT_MEMORY_MAP:
11310 gdb_assert (annex == NULL);
f6ac5f3d 11311 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
9b409511 11312 xfered_len,
fd79ecee
DJ
11313 &remote_protocol_packets[PACKET_qXfer_memory_map]);
11314
07e059b5
VP
11315 case TARGET_OBJECT_OSDATA:
11316 /* Should only get here if we're connected. */
5d93a237 11317 gdb_assert (rs->remote_desc);
07e059b5 11318 return remote_read_qxfer
f6ac5f3d 11319 ("osdata", annex, readbuf, offset, len, xfered_len,
dda83cd7 11320 &remote_protocol_packets[PACKET_qXfer_osdata]);
07e059b5 11321
dc146f7c
VP
11322 case TARGET_OBJECT_THREADS:
11323 gdb_assert (annex == NULL);
f6ac5f3d 11324 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
9b409511 11325 xfered_len,
dc146f7c
VP
11326 &remote_protocol_packets[PACKET_qXfer_threads]);
11327
b3b9301e
PA
11328 case TARGET_OBJECT_TRACEFRAME_INFO:
11329 gdb_assert (annex == NULL);
11330 return remote_read_qxfer
f6ac5f3d 11331 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 11332 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
11333
11334 case TARGET_OBJECT_FDPIC:
f6ac5f3d 11335 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
9b409511 11336 xfered_len,
78d85199 11337 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
11338
11339 case TARGET_OBJECT_OPENVMS_UIB:
f6ac5f3d 11340 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
9b409511 11341 xfered_len,
169081d0
TG
11342 &remote_protocol_packets[PACKET_qXfer_uib]);
11343
9accd112 11344 case TARGET_OBJECT_BTRACE:
f6ac5f3d 11345 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
9b409511 11346 xfered_len,
dda83cd7 11347 &remote_protocol_packets[PACKET_qXfer_btrace]);
9accd112 11348
f4abbc16 11349 case TARGET_OBJECT_BTRACE_CONF:
f6ac5f3d 11350 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
f4abbc16
MM
11351 len, xfered_len,
11352 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11353
c78fa86a 11354 case TARGET_OBJECT_EXEC_FILE:
f6ac5f3d 11355 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
c78fa86a
GB
11356 len, xfered_len,
11357 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11358
1e3ff5ad 11359 default:
2ed4b548 11360 return TARGET_XFER_E_IO;
c906108c
SS
11361 }
11362
0df8b418 11363 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 11364 large enough let the caller deal with it. */
ea9c271d 11365 if (len < get_remote_packet_size ())
2ed4b548 11366 return TARGET_XFER_E_IO;
ea9c271d 11367 len = get_remote_packet_size ();
1e3ff5ad 11368
23860348 11369 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 11370 if (!rs->remote_desc)
8a3fe4f8 11371 error (_("remote query is only available after target open"));
c906108c 11372
1e3ff5ad 11373 gdb_assert (annex != NULL);
4b8a223f 11374 gdb_assert (readbuf != NULL);
c906108c 11375
8d64371b 11376 p2 = rs->buf.data ();
c906108c
SS
11377 *p2++ = 'q';
11378 *p2++ = query_type;
11379
23860348
MS
11380 /* We used one buffer char for the remote protocol q command and
11381 another for the query type. As the remote protocol encapsulation
11382 uses 4 chars plus one extra in case we are debugging
11383 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11384 string. */
c906108c 11385 i = 0;
ea9c271d 11386 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 11387 {
1e3ff5ad
AC
11388 /* Bad caller may have sent forbidden characters. */
11389 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11390 *p2++ = annex[i];
c906108c
SS
11391 i++;
11392 }
1e3ff5ad
AC
11393 *p2 = '\0';
11394 gdb_assert (annex[i] == '\0');
c906108c 11395
6d820c5c 11396 i = putpkt (rs->buf);
c5aa993b 11397 if (i < 0)
2ed4b548 11398 return TARGET_XFER_E_IO;
c906108c 11399
8d64371b
TT
11400 getpkt (&rs->buf, 0);
11401 strcpy ((char *) readbuf, rs->buf.data ());
c906108c 11402
9b409511 11403 *xfered_len = strlen ((char *) readbuf);
92ffd475 11404 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
11405}
11406
09c98b44
DB
11407/* Implementation of to_get_memory_xfer_limit. */
11408
f6ac5f3d
PA
11409ULONGEST
11410remote_target::get_memory_xfer_limit ()
09c98b44
DB
11411{
11412 return get_memory_write_packet_size ();
11413}
11414
f6ac5f3d
PA
11415int
11416remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11417 const gdb_byte *pattern, ULONGEST pattern_len,
11418 CORE_ADDR *found_addrp)
08388c79 11419{
f5656ead 11420 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
11421 struct remote_state *rs = get_remote_state ();
11422 int max_size = get_memory_write_packet_size ();
11423 struct packet_config *packet =
11424 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
11425 /* Number of packet bytes used to encode the pattern;
11426 this could be more than PATTERN_LEN due to escape characters. */
08388c79 11427 int escaped_pattern_len;
0df8b418 11428 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
11429 int used_pattern_len;
11430 int i;
11431 int found;
11432 ULONGEST found_addr;
11433
4a72de73
TT
11434 auto read_memory = [=] (CORE_ADDR addr, gdb_byte *result, size_t len)
11435 {
11436 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11437 == len);
11438 };
11439
7cc244de
PA
11440 /* Don't go to the target if we don't have to. This is done before
11441 checking packet_config_support to avoid the possibility that a
11442 success for this edge case means the facility works in
11443 general. */
08388c79
DE
11444 if (pattern_len > search_space_len)
11445 return 0;
11446 if (pattern_len == 0)
11447 {
11448 *found_addrp = start_addr;
11449 return 1;
11450 }
11451
11452 /* If we already know the packet isn't supported, fall back to the simple
11453 way of searching memory. */
11454
4082afcc 11455 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
11456 {
11457 /* Target doesn't provided special support, fall back and use the
11458 standard support (copy memory and do the search here). */
4a72de73 11459 return simple_search_memory (read_memory, start_addr, search_space_len,
08388c79
DE
11460 pattern, pattern_len, found_addrp);
11461 }
11462
28439a30
PA
11463 /* Make sure the remote is pointing at the right process. */
11464 set_general_process ();
11465
08388c79 11466 /* Insert header. */
8d64371b 11467 i = snprintf (rs->buf.data (), max_size,
08388c79 11468 "qSearch:memory:%s;%s;",
5af949e3 11469 phex_nz (start_addr, addr_size),
08388c79
DE
11470 phex_nz (search_space_len, sizeof (search_space_len)));
11471 max_size -= (i + 1);
11472
11473 /* Escape as much data as fits into rs->buf. */
11474 escaped_pattern_len =
8d64371b
TT
11475 remote_escape_output (pattern, pattern_len, 1,
11476 (gdb_byte *) rs->buf.data () + i,
08388c79
DE
11477 &used_pattern_len, max_size);
11478
11479 /* Bail if the pattern is too large. */
11480 if (used_pattern_len != pattern_len)
9b20d036 11481 error (_("Pattern is too large to transmit to remote target."));
08388c79 11482
8d64371b
TT
11483 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11484 || getpkt_sane (&rs->buf, 0) < 0
08388c79
DE
11485 || packet_ok (rs->buf, packet) != PACKET_OK)
11486 {
11487 /* The request may not have worked because the command is not
11488 supported. If so, fall back to the simple way. */
7cc244de 11489 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79 11490 {
4a72de73 11491 return simple_search_memory (read_memory, start_addr, search_space_len,
08388c79
DE
11492 pattern, pattern_len, found_addrp);
11493 }
11494 return -1;
11495 }
11496
11497 if (rs->buf[0] == '0')
11498 found = 0;
11499 else if (rs->buf[0] == '1')
11500 {
11501 found = 1;
11502 if (rs->buf[1] != ',')
8d64371b
TT
11503 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11504 unpack_varlen_hex (&rs->buf[2], &found_addr);
08388c79
DE
11505 *found_addrp = found_addr;
11506 }
11507 else
8d64371b 11508 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
08388c79
DE
11509
11510 return found;
11511}
11512
f6ac5f3d
PA
11513void
11514remote_target::rcmd (const char *command, struct ui_file *outbuf)
96baa820 11515{
d01949b6 11516 struct remote_state *rs = get_remote_state ();
8d64371b 11517 char *p = rs->buf.data ();
96baa820 11518
5d93a237 11519 if (!rs->remote_desc)
8a3fe4f8 11520 error (_("remote rcmd is only available after target open"));
96baa820 11521
23860348 11522 /* Send a NULL command across as an empty command. */
7be570e7
JM
11523 if (command == NULL)
11524 command = "";
11525
23860348 11526 /* The query prefix. */
8d64371b
TT
11527 strcpy (rs->buf.data (), "qRcmd,");
11528 p = strchr (rs->buf.data (), '\0');
96baa820 11529
8d64371b 11530 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
3e43a32a 11531 > get_remote_packet_size ())
8a3fe4f8 11532 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 11533
23860348 11534 /* Encode the actual command. */
a30bf1f1 11535 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 11536
6d820c5c 11537 if (putpkt (rs->buf) < 0)
8a3fe4f8 11538 error (_("Communication problem with target."));
96baa820
JM
11539
11540 /* get/display the response */
11541 while (1)
11542 {
2e9f7625
DJ
11543 char *buf;
11544
00bf0b85 11545 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 11546 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 11547 rs->buf[0] = '\0';
8d64371b 11548 if (getpkt_sane (&rs->buf, 0) == -1)
dda83cd7
SM
11549 {
11550 /* Timeout. Continue to (try to) read responses.
11551 This is better than stopping with an error, assuming the stub
11552 is still executing the (long) monitor command.
11553 If needed, the user can interrupt gdb using C-c, obtaining
11554 an effect similar to stop on timeout. */
11555 continue;
11556 }
8d64371b 11557 buf = rs->buf.data ();
96baa820 11558 if (buf[0] == '\0')
8a3fe4f8 11559 error (_("Target does not support this command."));
96baa820
JM
11560 if (buf[0] == 'O' && buf[1] != 'K')
11561 {
23860348 11562 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
11563 continue;
11564 }
11565 if (strcmp (buf, "OK") == 0)
11566 break;
7be570e7 11567 if (strlen (buf) == 3 && buf[0] == 'E'
d5ce6f2d 11568 && isxdigit (buf[1]) && isxdigit (buf[2]))
7be570e7 11569 {
8a3fe4f8 11570 error (_("Protocol error with Rcmd"));
7be570e7 11571 }
96baa820
JM
11572 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11573 {
11574 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 11575
a11ac3b3 11576 gdb_putc (c, outbuf);
96baa820
JM
11577 }
11578 break;
11579 }
11580}
11581
f6ac5f3d
PA
11582std::vector<mem_region>
11583remote_target::memory_map ()
fd79ecee 11584{
a664f67e 11585 std::vector<mem_region> result;
9018be22 11586 gdb::optional<gdb::char_vector> text
328d42d8
SM
11587 = target_read_stralloc (current_inferior ()->top_target (),
11588 TARGET_OBJECT_MEMORY_MAP, NULL);
fd79ecee
DJ
11589
11590 if (text)
9018be22 11591 result = parse_memory_map (text->data ());
fd79ecee
DJ
11592
11593 return result;
11594}
11595
e5b176f2
AB
11596/* Set of callbacks used to implement the 'maint packet' command. */
11597
11598struct cli_packet_command_callbacks : public send_remote_packet_callbacks
c906108c 11599{
e5b176f2
AB
11600 /* Called before the packet is sent. BUF is the packet content before
11601 the protocol specific prefix, suffix, and escaping is added. */
c906108c 11602
e5b176f2
AB
11603 void sending (gdb::array_view<const char> &buf) override
11604 {
0426ad51 11605 gdb_puts ("sending: ");
e5b176f2 11606 print_packet (buf);
0426ad51 11607 gdb_puts ("\n");
e5b176f2 11608 }
c906108c 11609
e5b176f2
AB
11610 /* Called with BUF, the reply from the remote target. */
11611
11612 void received (gdb::array_view<const char> &buf) override
11613 {
0426ad51 11614 gdb_puts ("received: \"");
e5b176f2 11615 print_packet (buf);
0426ad51 11616 gdb_puts ("\"\n");
e5b176f2
AB
11617 }
11618
11619private:
11620
11621 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11622 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11623
11624 static void
11625 print_packet (gdb::array_view<const char> &buf)
11626 {
11627 string_file stb;
11628
11629 for (int i = 0; i < buf.size (); ++i)
11630 {
11631 gdb_byte c = buf[i];
11632 if (isprint (c))
a11ac3b3 11633 gdb_putc (c, &stb);
e5b176f2 11634 else
6cb06a8c 11635 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
e5b176f2
AB
11636 }
11637
0426ad51 11638 gdb_puts (stb.string ().c_str ());
e5b176f2
AB
11639 }
11640};
11641
11642/* See remote.h. */
6b8edb51
PA
11643
11644void
e5b176f2
AB
11645send_remote_packet (gdb::array_view<const char> &buf,
11646 send_remote_packet_callbacks *callbacks)
6b8edb51 11647{
e5b176f2
AB
11648 if (buf.size () == 0 || buf.data ()[0] == '\0')
11649 error (_("a remote packet must not be empty"));
c906108c 11650
e5b176f2
AB
11651 remote_target *remote = get_current_remote_target ();
11652 if (remote == nullptr)
11653 error (_("packets can only be sent to a remote target"));
c906108c 11654
e5b176f2 11655 callbacks->sending (buf);
6b8edb51 11656
e5b176f2
AB
11657 remote->putpkt_binary (buf.data (), buf.size ());
11658 remote_state *rs = remote->get_remote_state ();
11659 int bytes = remote->getpkt_sane (&rs->buf, 0);
11660
11661 if (bytes < 0)
11662 error (_("error while fetching packet from remote target"));
11663
11664 gdb::array_view<const char> view (&rs->buf[0], bytes);
11665 callbacks->received (view);
11666}
11667
11668/* Entry point for the 'maint packet' command. */
11669
11670static void
11671cli_packet_command (const char *args, int from_tty)
11672{
11673 cli_packet_command_callbacks cb;
11674 gdb::array_view<const char> view
11675 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11676 send_remote_packet (view, &cb);
c906108c
SS
11677}
11678
11679#if 0
23860348 11680/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 11681
a14ed312 11682static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 11683
a14ed312 11684static void threadset_test_cmd (char *cmd, int tty);
c906108c 11685
a14ed312 11686static void threadalive_test (char *cmd, int tty);
c906108c 11687
a14ed312 11688static void threadlist_test_cmd (char *cmd, int tty);
c906108c 11689
23860348 11690int get_and_display_threadinfo (threadref *ref);
c906108c 11691
a14ed312 11692static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 11693
23860348 11694static int thread_display_step (threadref *ref, void *context);
c906108c 11695
a14ed312 11696static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 11697
a14ed312 11698static void init_remote_threadtests (void);
c906108c 11699
23860348 11700#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
11701
11702static void
0b39b52e 11703threadset_test_cmd (const char *cmd, int tty)
c906108c
SS
11704{
11705 int sample_thread = SAMPLE_THREAD;
11706
6cb06a8c 11707 gdb_printf (_("Remote threadset test\n"));
79d7f229 11708 set_general_thread (sample_thread);
c906108c
SS
11709}
11710
11711
11712static void
0b39b52e 11713threadalive_test (const char *cmd, int tty)
c906108c
SS
11714{
11715 int sample_thread = SAMPLE_THREAD;
e99b03dc 11716 int pid = inferior_ptid.pid ();
fd79271b 11717 ptid_t ptid = ptid_t (pid, sample_thread, 0);
c906108c 11718
79d7f229 11719 if (remote_thread_alive (ptid))
6cb06a8c 11720 gdb_printf ("PASS: Thread alive test\n");
c906108c 11721 else
6cb06a8c 11722 gdb_printf ("FAIL: Thread alive test\n");
c906108c
SS
11723}
11724
23860348 11725void output_threadid (char *title, threadref *ref);
c906108c
SS
11726
11727void
fba45db2 11728output_threadid (char *title, threadref *ref)
c906108c
SS
11729{
11730 char hexid[20];
11731
405feb71 11732 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
c906108c 11733 hexid[16] = 0;
6cb06a8c 11734 gdb_printf ("%s %s\n", title, (&hexid[0]));
c906108c
SS
11735}
11736
11737static void
0b39b52e 11738threadlist_test_cmd (const char *cmd, int tty)
c906108c
SS
11739{
11740 int startflag = 1;
11741 threadref nextthread;
11742 int done, result_count;
11743 threadref threadlist[3];
11744
6cb06a8c 11745 gdb_printf ("Remote Threadlist test\n");
c906108c
SS
11746 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11747 &result_count, &threadlist[0]))
6cb06a8c 11748 gdb_printf ("FAIL: threadlist test\n");
c906108c
SS
11749 else
11750 {
11751 threadref *scan = threadlist;
11752 threadref *limit = scan + result_count;
11753
11754 while (scan < limit)
11755 output_threadid (" thread ", scan++);
11756 }
11757}
11758
11759void
fba45db2 11760display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
11761{
11762 output_threadid ("Threadid: ", &info->threadid);
6cb06a8c
TT
11763 gdb_printf ("Name: %s\n ", info->shortname);
11764 gdb_printf ("State: %s\n", info->display);
11765 gdb_printf ("other: %s\n\n", info->more_display);
c906108c
SS
11766}
11767
11768int
fba45db2 11769get_and_display_threadinfo (threadref *ref)
c906108c
SS
11770{
11771 int result;
11772 int set;
11773 struct gdb_ext_thread_info threadinfo;
11774
11775 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11776 | TAG_MOREDISPLAY | TAG_DISPLAY;
11777 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11778 display_thread_info (&threadinfo);
11779 return result;
11780}
11781
11782static void
0b39b52e 11783threadinfo_test_cmd (const char *cmd, int tty)
c906108c
SS
11784{
11785 int athread = SAMPLE_THREAD;
11786 threadref thread;
11787 int set;
11788
11789 int_to_threadref (&thread, athread);
6cb06a8c 11790 gdb_printf ("Remote Threadinfo test\n");
c906108c 11791 if (!get_and_display_threadinfo (&thread))
6cb06a8c 11792 gdb_printf ("FAIL cannot get thread info\n");
c906108c
SS
11793}
11794
11795static int
fba45db2 11796thread_display_step (threadref *ref, void *context)
c906108c
SS
11797{
11798 /* output_threadid(" threadstep ",ref); *//* simple test */
11799 return get_and_display_threadinfo (ref);
11800}
11801
11802static void
0b39b52e 11803threadlist_update_test_cmd (const char *cmd, int tty)
c906108c 11804{
6cb06a8c 11805 gdb_printf ("Remote Threadlist update test\n");
c906108c
SS
11806 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11807}
11808
11809static void
11810init_remote_threadtests (void)
11811{
3e43a32a
MS
11812 add_com ("tlist", class_obscure, threadlist_test_cmd,
11813 _("Fetch and print the remote list of "
590042fc 11814 "thread identifiers, one pkt only."));
c906108c 11815 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
590042fc 11816 _("Fetch and display info about one thread."));
c906108c 11817 add_com ("tset", class_obscure, threadset_test_cmd,
590042fc 11818 _("Test setting to a different thread."));
c906108c 11819 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
590042fc 11820 _("Iterate through updating all remote thread info."));
c906108c 11821 add_com ("talive", class_obscure, threadalive_test,
590042fc 11822 _("Remote thread alive test."));
c906108c
SS
11823}
11824
11825#endif /* 0 */
11826
a068643d 11827/* Convert a thread ID to a string. */
f3fb8c85 11828
a068643d 11829std::string
f6ac5f3d 11830remote_target::pid_to_str (ptid_t ptid)
f3fb8c85 11831{
82f73884 11832 struct remote_state *rs = get_remote_state ();
f3fb8c85 11833
d7e15655 11834 if (ptid == null_ptid)
7cee1e54 11835 return normal_pid_to_str (ptid);
0e998d96 11836 else if (ptid.is_pid ())
ecd0ada5
PA
11837 {
11838 /* Printing an inferior target id. */
11839
11840 /* When multi-process extensions are off, there's no way in the
11841 remote protocol to know the remote process id, if there's any
11842 at all. There's one exception --- when we're connected with
11843 target extended-remote, and we manually attached to a process
11844 with "attach PID". We don't record anywhere a flag that
11845 allows us to distinguish that case from the case of
11846 connecting with extended-remote and the stub already being
11847 attached to a process, and reporting yes to qAttached, hence
11848 no smart special casing here. */
11849 if (!remote_multi_process_p (rs))
a068643d 11850 return "Remote target";
ecd0ada5
PA
11851
11852 return normal_pid_to_str (ptid);
82f73884 11853 }
ecd0ada5 11854 else
79d7f229 11855 {
d7e15655 11856 if (magic_null_ptid == ptid)
a068643d 11857 return "Thread <main>";
8020350c 11858 else if (remote_multi_process_p (rs))
e38504b3 11859 if (ptid.lwp () == 0)
de0d863e
DB
11860 return normal_pid_to_str (ptid);
11861 else
a068643d
TT
11862 return string_printf ("Thread %d.%ld",
11863 ptid.pid (), ptid.lwp ());
ecd0ada5 11864 else
a068643d 11865 return string_printf ("Thread %ld", ptid.lwp ());
79d7f229 11866 }
f3fb8c85
MS
11867}
11868
38691318
KB
11869/* Get the address of the thread local variable in OBJFILE which is
11870 stored at OFFSET within the thread local storage for thread PTID. */
11871
f6ac5f3d
PA
11872CORE_ADDR
11873remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11874 CORE_ADDR offset)
38691318 11875{
4082afcc 11876 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
11877 {
11878 struct remote_state *rs = get_remote_state ();
8d64371b
TT
11879 char *p = rs->buf.data ();
11880 char *endp = p + get_remote_packet_size ();
571dd617 11881 enum packet_result result;
38691318
KB
11882
11883 strcpy (p, "qGetTLSAddr:");
11884 p += strlen (p);
82f73884 11885 p = write_ptid (p, endp, ptid);
38691318
KB
11886 *p++ = ',';
11887 p += hexnumstr (p, offset);
11888 *p++ = ',';
11889 p += hexnumstr (p, lm);
11890 *p++ = '\0';
11891
6d820c5c 11892 putpkt (rs->buf);
8d64371b 11893 getpkt (&rs->buf, 0);
3e43a32a
MS
11894 result = packet_ok (rs->buf,
11895 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 11896 if (result == PACKET_OK)
38691318 11897 {
b926417a 11898 ULONGEST addr;
38691318 11899
8d64371b 11900 unpack_varlen_hex (rs->buf.data (), &addr);
b926417a 11901 return addr;
38691318 11902 }
571dd617 11903 else if (result == PACKET_UNKNOWN)
109c3e39
AC
11904 throw_error (TLS_GENERIC_ERROR,
11905 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 11906 else
109c3e39
AC
11907 throw_error (TLS_GENERIC_ERROR,
11908 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
11909 }
11910 else
109c3e39
AC
11911 throw_error (TLS_GENERIC_ERROR,
11912 _("TLS not supported or disabled on this target"));
38691318
KB
11913 /* Not reached. */
11914 return 0;
11915}
11916
711e434b
PM
11917/* Provide thread local base, i.e. Thread Information Block address.
11918 Returns 1 if ptid is found and thread_local_base is non zero. */
11919
57810aa7 11920bool
f6ac5f3d 11921remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
711e434b 11922{
4082afcc 11923 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
11924 {
11925 struct remote_state *rs = get_remote_state ();
8d64371b
TT
11926 char *p = rs->buf.data ();
11927 char *endp = p + get_remote_packet_size ();
711e434b
PM
11928 enum packet_result result;
11929
11930 strcpy (p, "qGetTIBAddr:");
11931 p += strlen (p);
11932 p = write_ptid (p, endp, ptid);
11933 *p++ = '\0';
11934
11935 putpkt (rs->buf);
8d64371b 11936 getpkt (&rs->buf, 0);
711e434b
PM
11937 result = packet_ok (rs->buf,
11938 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11939 if (result == PACKET_OK)
11940 {
b926417a 11941 ULONGEST val;
8d64371b 11942 unpack_varlen_hex (rs->buf.data (), &val);
711e434b 11943 if (addr)
b926417a 11944 *addr = (CORE_ADDR) val;
57810aa7 11945 return true;
711e434b
PM
11946 }
11947 else if (result == PACKET_UNKNOWN)
11948 error (_("Remote target doesn't support qGetTIBAddr packet"));
11949 else
11950 error (_("Remote target failed to process qGetTIBAddr request"));
11951 }
11952 else
11953 error (_("qGetTIBAddr not supported or disabled on this target"));
11954 /* Not reached. */
57810aa7 11955 return false;
711e434b
PM
11956}
11957
29709017
DJ
11958/* Support for inferring a target description based on the current
11959 architecture and the size of a 'g' packet. While the 'g' packet
11960 can have any size (since optional registers can be left off the
11961 end), some sizes are easily recognizable given knowledge of the
11962 approximate architecture. */
11963
11964struct remote_g_packet_guess
11965{
eefce37f
TT
11966 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
11967 : bytes (bytes_),
11968 tdesc (tdesc_)
11969 {
11970 }
11971
29709017
DJ
11972 int bytes;
11973 const struct target_desc *tdesc;
11974};
29709017 11975
eefce37f 11976struct remote_g_packet_data : public allocate_on_obstack
29709017 11977{
eefce37f 11978 std::vector<remote_g_packet_guess> guesses;
29709017
DJ
11979};
11980
11981static struct gdbarch_data *remote_g_packet_data_handle;
11982
11983static void *
11984remote_g_packet_data_init (struct obstack *obstack)
11985{
eefce37f 11986 return new (obstack) remote_g_packet_data;
29709017
DJ
11987}
11988
11989void
11990register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11991 const struct target_desc *tdesc)
11992{
11993 struct remote_g_packet_data *data
19ba03f4
SM
11994 = ((struct remote_g_packet_data *)
11995 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
11996
11997 gdb_assert (tdesc != NULL);
11998
eefce37f
TT
11999 for (const remote_g_packet_guess &guess : data->guesses)
12000 if (guess.bytes == bytes)
29709017 12001 internal_error (__FILE__, __LINE__,
9b20d036 12002 _("Duplicate g packet description added for size %d"),
29709017
DJ
12003 bytes);
12004
eefce37f 12005 data->guesses.emplace_back (bytes, tdesc);
29709017
DJ
12006}
12007
eefce37f
TT
12008/* Return true if remote_read_description would do anything on this target
12009 and architecture, false otherwise. */
d962ef82 12010
eefce37f 12011static bool
d962ef82
DJ
12012remote_read_description_p (struct target_ops *target)
12013{
12014 struct remote_g_packet_data *data
19ba03f4
SM
12015 = ((struct remote_g_packet_data *)
12016 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82 12017
eefce37f 12018 return !data->guesses.empty ();
d962ef82
DJ
12019}
12020
f6ac5f3d
PA
12021const struct target_desc *
12022remote_target::read_description ()
29709017
DJ
12023{
12024 struct remote_g_packet_data *data
19ba03f4
SM
12025 = ((struct remote_g_packet_data *)
12026 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 12027
d962ef82
DJ
12028 /* Do not try this during initial connection, when we do not know
12029 whether there is a running but stopped thread. */
55f6301a 12030 if (!target_has_execution () || inferior_ptid == null_ptid)
b6a8c27b 12031 return beneath ()->read_description ();
d962ef82 12032
eefce37f 12033 if (!data->guesses.empty ())
29709017 12034 {
29709017
DJ
12035 int bytes = send_g_packet ();
12036
eefce37f
TT
12037 for (const remote_g_packet_guess &guess : data->guesses)
12038 if (guess.bytes == bytes)
12039 return guess.tdesc;
29709017
DJ
12040
12041 /* We discard the g packet. A minor optimization would be to
12042 hold on to it, and fill the register cache once we have selected
12043 an architecture, but it's too tricky to do safely. */
12044 }
12045
b6a8c27b 12046 return beneath ()->read_description ();
29709017
DJ
12047}
12048
a6b151f1
DJ
12049/* Remote file transfer support. This is host-initiated I/O, not
12050 target-initiated; for target-initiated, see remote-fileio.c. */
12051
12052/* If *LEFT is at least the length of STRING, copy STRING to
12053 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12054 decrease *LEFT. Otherwise raise an error. */
12055
12056static void
a121b7c1 12057remote_buffer_add_string (char **buffer, int *left, const char *string)
a6b151f1
DJ
12058{
12059 int len = strlen (string);
12060
12061 if (len > *left)
12062 error (_("Packet too long for target."));
12063
12064 memcpy (*buffer, string, len);
12065 *buffer += len;
12066 *left -= len;
12067
12068 /* NUL-terminate the buffer as a convenience, if there is
12069 room. */
12070 if (*left)
12071 **buffer = '\0';
12072}
12073
12074/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12075 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12076 decrease *LEFT. Otherwise raise an error. */
12077
12078static void
12079remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12080 int len)
12081{
12082 if (2 * len > *left)
12083 error (_("Packet too long for target."));
12084
12085 bin2hex (bytes, *buffer, len);
12086 *buffer += 2 * len;
12087 *left -= 2 * len;
12088
12089 /* NUL-terminate the buffer as a convenience, if there is
12090 room. */
12091 if (*left)
12092 **buffer = '\0';
12093}
12094
12095/* If *LEFT is large enough, convert VALUE to hex and add it to
12096 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12097 decrease *LEFT. Otherwise raise an error. */
12098
12099static void
12100remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12101{
12102 int len = hexnumlen (value);
12103
12104 if (len > *left)
12105 error (_("Packet too long for target."));
12106
12107 hexnumstr (*buffer, value);
12108 *buffer += len;
12109 *left -= len;
12110
12111 /* NUL-terminate the buffer as a convenience, if there is
12112 room. */
12113 if (*left)
12114 **buffer = '\0';
12115}
12116
12117/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12118 value, *REMOTE_ERRNO to the remote error number or zero if none
12119 was included, and *ATTACHMENT to point to the start of the annex
12120 if any. The length of the packet isn't needed here; there may
12121 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12122
12123 Return 0 if the packet could be parsed, -1 if it could not. If
12124 -1 is returned, the other variables may not be initialized. */
12125
12126static int
aa2838cc
SM
12127remote_hostio_parse_result (const char *buffer, int *retcode,
12128 int *remote_errno, const char **attachment)
a6b151f1
DJ
12129{
12130 char *p, *p2;
12131
12132 *remote_errno = 0;
12133 *attachment = NULL;
12134
12135 if (buffer[0] != 'F')
12136 return -1;
12137
12138 errno = 0;
12139 *retcode = strtol (&buffer[1], &p, 16);
12140 if (errno != 0 || p == &buffer[1])
12141 return -1;
12142
12143 /* Check for ",errno". */
12144 if (*p == ',')
12145 {
12146 errno = 0;
12147 *remote_errno = strtol (p + 1, &p2, 16);
12148 if (errno != 0 || p + 1 == p2)
12149 return -1;
12150 p = p2;
12151 }
12152
12153 /* Check for ";attachment". If there is no attachment, the
12154 packet should end here. */
12155 if (*p == ';')
12156 {
12157 *attachment = p + 1;
12158 return 0;
12159 }
12160 else if (*p == '\0')
12161 return 0;
12162 else
12163 return -1;
12164}
12165
12166/* Send a prepared I/O packet to the target and read its response.
12167 The prepared packet is in the global RS->BUF before this function
12168 is called, and the answer is there when we return.
12169
12170 COMMAND_BYTES is the length of the request to send, which may include
12171 binary data. WHICH_PACKET is the packet configuration to check
12172 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12173 is set to the error number and -1 is returned. Otherwise the value
12174 returned by the function is returned.
12175
12176 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12177 attachment is expected; an error will be reported if there's a
12178 mismatch. If one is found, *ATTACHMENT will be set to point into
12179 the packet buffer and *ATTACHMENT_LEN will be set to the
12180 attachment's length. */
12181
6b8edb51
PA
12182int
12183remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
aa2838cc 12184 int *remote_errno, const char **attachment,
6b8edb51 12185 int *attachment_len)
a6b151f1
DJ
12186{
12187 struct remote_state *rs = get_remote_state ();
12188 int ret, bytes_read;
aa2838cc 12189 const char *attachment_tmp;
a6b151f1 12190
20db9c52 12191 if (packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
12192 {
12193 *remote_errno = FILEIO_ENOSYS;
12194 return -1;
12195 }
12196
8d64371b
TT
12197 putpkt_binary (rs->buf.data (), command_bytes);
12198 bytes_read = getpkt_sane (&rs->buf, 0);
a6b151f1
DJ
12199
12200 /* If it timed out, something is wrong. Don't try to parse the
12201 buffer. */
12202 if (bytes_read < 0)
12203 {
12204 *remote_errno = FILEIO_EINVAL;
12205 return -1;
12206 }
12207
12208 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
12209 {
12210 case PACKET_ERROR:
12211 *remote_errno = FILEIO_EINVAL;
12212 return -1;
12213 case PACKET_UNKNOWN:
12214 *remote_errno = FILEIO_ENOSYS;
12215 return -1;
12216 case PACKET_OK:
12217 break;
12218 }
12219
8d64371b 12220 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
a6b151f1
DJ
12221 &attachment_tmp))
12222 {
12223 *remote_errno = FILEIO_EINVAL;
12224 return -1;
12225 }
12226
12227 /* Make sure we saw an attachment if and only if we expected one. */
12228 if ((attachment_tmp == NULL && attachment != NULL)
12229 || (attachment_tmp != NULL && attachment == NULL))
12230 {
12231 *remote_errno = FILEIO_EINVAL;
12232 return -1;
12233 }
12234
12235 /* If an attachment was found, it must point into the packet buffer;
12236 work out how many bytes there were. */
12237 if (attachment_tmp != NULL)
12238 {
12239 *attachment = attachment_tmp;
8d64371b 12240 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
a6b151f1
DJ
12241 }
12242
12243 return ret;
12244}
12245
dd194f6b 12246/* See declaration.h. */
80152258 12247
dd194f6b
PA
12248void
12249readahead_cache::invalidate ()
80152258 12250{
dd194f6b 12251 this->fd = -1;
80152258
PA
12252}
12253
dd194f6b 12254/* See declaration.h. */
80152258 12255
dd194f6b
PA
12256void
12257readahead_cache::invalidate_fd (int fd)
80152258 12258{
dd194f6b
PA
12259 if (this->fd == fd)
12260 this->fd = -1;
80152258
PA
12261}
12262
15a201c8
GB
12263/* Set the filesystem remote_hostio functions that take FILENAME
12264 arguments will use. Return 0 on success, or -1 if an error
12265 occurs (and set *REMOTE_ERRNO). */
12266
6b8edb51
PA
12267int
12268remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12269 int *remote_errno)
15a201c8
GB
12270{
12271 struct remote_state *rs = get_remote_state ();
12272 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
8d64371b 12273 char *p = rs->buf.data ();
15a201c8
GB
12274 int left = get_remote_packet_size () - 1;
12275 char arg[9];
12276 int ret;
12277
12278 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12279 return 0;
12280
12281 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12282 return 0;
12283
12284 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12285
12286 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12287 remote_buffer_add_string (&p, &left, arg);
12288
8d64371b 12289 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
15a201c8
GB
12290 remote_errno, NULL, NULL);
12291
12292 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12293 return 0;
12294
12295 if (ret == 0)
12296 rs->fs_pid = required_pid;
12297
12298 return ret;
12299}
12300
12e2a5fd 12301/* Implementation of to_fileio_open. */
a6b151f1 12302
6b8edb51
PA
12303int
12304remote_target::remote_hostio_open (inferior *inf, const char *filename,
12305 int flags, int mode, int warn_if_slow,
12306 int *remote_errno)
a6b151f1
DJ
12307{
12308 struct remote_state *rs = get_remote_state ();
8d64371b 12309 char *p = rs->buf.data ();
a6b151f1
DJ
12310 int left = get_remote_packet_size () - 1;
12311
4313b8c0
GB
12312 if (warn_if_slow)
12313 {
12314 static int warning_issued = 0;
12315
6cb06a8c
TT
12316 gdb_printf (_("Reading %s from remote target...\n"),
12317 filename);
4313b8c0
GB
12318
12319 if (!warning_issued)
12320 {
12321 warning (_("File transfers from remote targets can be slow."
12322 " Use \"set sysroot\" to access files locally"
12323 " instead."));
12324 warning_issued = 1;
12325 }
12326 }
12327
15a201c8
GB
12328 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12329 return -1;
12330
a6b151f1
DJ
12331 remote_buffer_add_string (&p, &left, "vFile:open:");
12332
12333 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12334 strlen (filename));
12335 remote_buffer_add_string (&p, &left, ",");
12336
12337 remote_buffer_add_int (&p, &left, flags);
12338 remote_buffer_add_string (&p, &left, ",");
12339
12340 remote_buffer_add_int (&p, &left, mode);
12341
8d64371b 12342 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
a6b151f1
DJ
12343 remote_errno, NULL, NULL);
12344}
12345
f6ac5f3d
PA
12346int
12347remote_target::fileio_open (struct inferior *inf, const char *filename,
12348 int flags, int mode, int warn_if_slow,
12349 int *remote_errno)
12350{
6b8edb51 12351 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
f6ac5f3d
PA
12352 remote_errno);
12353}
12354
12e2a5fd 12355/* Implementation of to_fileio_pwrite. */
a6b151f1 12356
6b8edb51
PA
12357int
12358remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12359 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
12360{
12361 struct remote_state *rs = get_remote_state ();
8d64371b 12362 char *p = rs->buf.data ();
a6b151f1
DJ
12363 int left = get_remote_packet_size ();
12364 int out_len;
12365
dd194f6b 12366 rs->readahead_cache.invalidate_fd (fd);
80152258 12367
a6b151f1
DJ
12368 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12369
12370 remote_buffer_add_int (&p, &left, fd);
12371 remote_buffer_add_string (&p, &left, ",");
12372
12373 remote_buffer_add_int (&p, &left, offset);
12374 remote_buffer_add_string (&p, &left, ",");
12375
124e13d9 12376 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
8d64371b
TT
12377 (get_remote_packet_size ()
12378 - (p - rs->buf.data ())));
a6b151f1 12379
8d64371b 12380 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
a6b151f1
DJ
12381 remote_errno, NULL, NULL);
12382}
12383
f6ac5f3d
PA
12384int
12385remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12386 ULONGEST offset, int *remote_errno)
12387{
6b8edb51 12388 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
f6ac5f3d
PA
12389}
12390
80152258
PA
12391/* Helper for the implementation of to_fileio_pread. Read the file
12392 from the remote side with vFile:pread. */
a6b151f1 12393
6b8edb51
PA
12394int
12395remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12396 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
12397{
12398 struct remote_state *rs = get_remote_state ();
8d64371b 12399 char *p = rs->buf.data ();
aa2838cc 12400 const char *attachment;
a6b151f1
DJ
12401 int left = get_remote_packet_size ();
12402 int ret, attachment_len;
12403 int read_len;
12404
12405 remote_buffer_add_string (&p, &left, "vFile:pread:");
12406
12407 remote_buffer_add_int (&p, &left, fd);
12408 remote_buffer_add_string (&p, &left, ",");
12409
12410 remote_buffer_add_int (&p, &left, len);
12411 remote_buffer_add_string (&p, &left, ",");
12412
12413 remote_buffer_add_int (&p, &left, offset);
12414
8d64371b 12415 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
a6b151f1
DJ
12416 remote_errno, &attachment,
12417 &attachment_len);
12418
12419 if (ret < 0)
12420 return ret;
12421
bc20a4af 12422 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
12423 read_buf, len);
12424 if (read_len != ret)
12425 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12426
12427 return ret;
12428}
12429
dd194f6b 12430/* See declaration.h. */
80152258 12431
dd194f6b
PA
12432int
12433readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12434 ULONGEST offset)
80152258 12435{
dd194f6b
PA
12436 if (this->fd == fd
12437 && this->offset <= offset
12438 && offset < this->offset + this->bufsize)
80152258 12439 {
dd194f6b 12440 ULONGEST max = this->offset + this->bufsize;
80152258
PA
12441
12442 if (offset + len > max)
12443 len = max - offset;
12444
dd194f6b 12445 memcpy (read_buf, this->buf + offset - this->offset, len);
80152258
PA
12446 return len;
12447 }
12448
12449 return 0;
12450}
12451
12452/* Implementation of to_fileio_pread. */
12453
6b8edb51
PA
12454int
12455remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12456 ULONGEST offset, int *remote_errno)
80152258
PA
12457{
12458 int ret;
12459 struct remote_state *rs = get_remote_state ();
dd194f6b 12460 readahead_cache *cache = &rs->readahead_cache;
80152258 12461
dd194f6b 12462 ret = cache->pread (fd, read_buf, len, offset);
80152258
PA
12463 if (ret > 0)
12464 {
12465 cache->hit_count++;
12466
2189c312
SM
12467 remote_debug_printf ("readahead cache hit %s",
12468 pulongest (cache->hit_count));
80152258
PA
12469 return ret;
12470 }
12471
12472 cache->miss_count++;
2189c312
SM
12473
12474 remote_debug_printf ("readahead cache miss %s",
12475 pulongest (cache->miss_count));
80152258
PA
12476
12477 cache->fd = fd;
12478 cache->offset = offset;
12479 cache->bufsize = get_remote_packet_size ();
224c3ddb 12480 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258 12481
6b8edb51 12482 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
80152258
PA
12483 cache->offset, remote_errno);
12484 if (ret <= 0)
12485 {
dd194f6b 12486 cache->invalidate_fd (fd);
80152258
PA
12487 return ret;
12488 }
12489
12490 cache->bufsize = ret;
dd194f6b 12491 return cache->pread (fd, read_buf, len, offset);
80152258
PA
12492}
12493
f6ac5f3d
PA
12494int
12495remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12496 ULONGEST offset, int *remote_errno)
12497{
6b8edb51 12498 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
f6ac5f3d
PA
12499}
12500
12e2a5fd 12501/* Implementation of to_fileio_close. */
a6b151f1 12502
6b8edb51
PA
12503int
12504remote_target::remote_hostio_close (int fd, int *remote_errno)
a6b151f1
DJ
12505{
12506 struct remote_state *rs = get_remote_state ();
8d64371b 12507 char *p = rs->buf.data ();
a6b151f1
DJ
12508 int left = get_remote_packet_size () - 1;
12509
dd194f6b 12510 rs->readahead_cache.invalidate_fd (fd);
80152258 12511
a6b151f1
DJ
12512 remote_buffer_add_string (&p, &left, "vFile:close:");
12513
12514 remote_buffer_add_int (&p, &left, fd);
12515
8d64371b 12516 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
a6b151f1
DJ
12517 remote_errno, NULL, NULL);
12518}
12519
f6ac5f3d
PA
12520int
12521remote_target::fileio_close (int fd, int *remote_errno)
12522{
6b8edb51 12523 return remote_hostio_close (fd, remote_errno);
f6ac5f3d
PA
12524}
12525
12e2a5fd 12526/* Implementation of to_fileio_unlink. */
a6b151f1 12527
6b8edb51
PA
12528int
12529remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12530 int *remote_errno)
a6b151f1
DJ
12531{
12532 struct remote_state *rs = get_remote_state ();
8d64371b 12533 char *p = rs->buf.data ();
a6b151f1
DJ
12534 int left = get_remote_packet_size () - 1;
12535
15a201c8
GB
12536 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12537 return -1;
12538
a6b151f1
DJ
12539 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12540
12541 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12542 strlen (filename));
12543
8d64371b 12544 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
a6b151f1
DJ
12545 remote_errno, NULL, NULL);
12546}
12547
f6ac5f3d
PA
12548int
12549remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12550 int *remote_errno)
12551{
6b8edb51 12552 return remote_hostio_unlink (inf, filename, remote_errno);
f6ac5f3d
PA
12553}
12554
12e2a5fd 12555/* Implementation of to_fileio_readlink. */
b9e7b9c3 12556
f6ac5f3d
PA
12557gdb::optional<std::string>
12558remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12559 int *remote_errno)
b9e7b9c3
UW
12560{
12561 struct remote_state *rs = get_remote_state ();
8d64371b 12562 char *p = rs->buf.data ();
aa2838cc 12563 const char *attachment;
b9e7b9c3
UW
12564 int left = get_remote_packet_size ();
12565 int len, attachment_len;
12566 int read_len;
b9e7b9c3 12567
15a201c8 12568 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
e0d3522b 12569 return {};
15a201c8 12570
b9e7b9c3
UW
12571 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12572
12573 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12574 strlen (filename));
12575
8d64371b 12576 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
b9e7b9c3
UW
12577 remote_errno, &attachment,
12578 &attachment_len);
12579
12580 if (len < 0)
e0d3522b 12581 return {};
b9e7b9c3 12582
e0d3522b 12583 std::string ret (len, '\0');
b9e7b9c3 12584
bc20a4af 12585 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
e0d3522b 12586 (gdb_byte *) &ret[0], len);
b9e7b9c3
UW
12587 if (read_len != len)
12588 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12589
b9e7b9c3
UW
12590 return ret;
12591}
12592
12e2a5fd 12593/* Implementation of to_fileio_fstat. */
0a93529c 12594
f6ac5f3d
PA
12595int
12596remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
0a93529c
GB
12597{
12598 struct remote_state *rs = get_remote_state ();
8d64371b 12599 char *p = rs->buf.data ();
0a93529c
GB
12600 int left = get_remote_packet_size ();
12601 int attachment_len, ret;
aa2838cc 12602 const char *attachment;
0a93529c
GB
12603 struct fio_stat fst;
12604 int read_len;
12605
464b0089
GB
12606 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12607
12608 remote_buffer_add_int (&p, &left, fd);
12609
8d64371b 12610 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
464b0089
GB
12611 remote_errno, &attachment,
12612 &attachment_len);
12613 if (ret < 0)
0a93529c 12614 {
464b0089
GB
12615 if (*remote_errno != FILEIO_ENOSYS)
12616 return ret;
12617
0a93529c
GB
12618 /* Strictly we should return -1, ENOSYS here, but when
12619 "set sysroot remote:" was implemented in August 2008
12620 BFD's need for a stat function was sidestepped with
12621 this hack. This was not remedied until March 2015
12622 so we retain the previous behavior to avoid breaking
12623 compatibility.
12624
12625 Note that the memset is a March 2015 addition; older
12626 GDBs set st_size *and nothing else* so the structure
12627 would have garbage in all other fields. This might
12628 break something but retaining the previous behavior
12629 here would be just too wrong. */
12630
12631 memset (st, 0, sizeof (struct stat));
12632 st->st_size = INT_MAX;
12633 return 0;
12634 }
12635
0a93529c
GB
12636 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12637 (gdb_byte *) &fst, sizeof (fst));
12638
12639 if (read_len != ret)
12640 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12641
12642 if (read_len != sizeof (fst))
12643 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12644 read_len, (int) sizeof (fst));
12645
12646 remote_fileio_to_host_stat (&fst, st);
12647
12648 return 0;
12649}
12650
12e2a5fd 12651/* Implementation of to_filesystem_is_local. */
e3dd7556 12652
57810aa7 12653bool
f6ac5f3d 12654remote_target::filesystem_is_local ()
e3dd7556
GB
12655{
12656 /* Valgrind GDB presents itself as a remote target but works
12657 on the local filesystem: it does not implement remote get
12658 and users are not expected to set a sysroot. To handle
12659 this case we treat the remote filesystem as local if the
12660 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12661 does not support vFile:open. */
e0700ba4 12662 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
e3dd7556
GB
12663 {
12664 enum packet_support ps = packet_support (PACKET_vFile_open);
12665
12666 if (ps == PACKET_SUPPORT_UNKNOWN)
12667 {
12668 int fd, remote_errno;
12669
12670 /* Try opening a file to probe support. The supplied
12671 filename is irrelevant, we only care about whether
12672 the stub recognizes the packet or not. */
6b8edb51 12673 fd = remote_hostio_open (NULL, "just probing",
4313b8c0 12674 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
12675 &remote_errno);
12676
12677 if (fd >= 0)
6b8edb51 12678 remote_hostio_close (fd, &remote_errno);
e3dd7556
GB
12679
12680 ps = packet_support (PACKET_vFile_open);
12681 }
12682
12683 if (ps == PACKET_DISABLE)
12684 {
12685 static int warning_issued = 0;
12686
12687 if (!warning_issued)
12688 {
12689 warning (_("remote target does not support file"
12690 " transfer, attempting to access files"
12691 " from local filesystem."));
12692 warning_issued = 1;
12693 }
12694
57810aa7 12695 return true;
e3dd7556
GB
12696 }
12697 }
12698
57810aa7 12699 return false;
e3dd7556
GB
12700}
12701
a6b151f1
DJ
12702static int
12703remote_fileio_errno_to_host (int errnum)
12704{
12705 switch (errnum)
12706 {
12707 case FILEIO_EPERM:
dda83cd7 12708 return EPERM;
a6b151f1 12709 case FILEIO_ENOENT:
dda83cd7 12710 return ENOENT;
a6b151f1 12711 case FILEIO_EINTR:
dda83cd7 12712 return EINTR;
a6b151f1 12713 case FILEIO_EIO:
dda83cd7 12714 return EIO;
a6b151f1 12715 case FILEIO_EBADF:
dda83cd7 12716 return EBADF;
a6b151f1 12717 case FILEIO_EACCES:
dda83cd7 12718 return EACCES;
a6b151f1 12719 case FILEIO_EFAULT:
dda83cd7 12720 return EFAULT;
a6b151f1 12721 case FILEIO_EBUSY:
dda83cd7 12722 return EBUSY;
a6b151f1 12723 case FILEIO_EEXIST:
dda83cd7 12724 return EEXIST;
a6b151f1 12725 case FILEIO_ENODEV:
dda83cd7 12726 return ENODEV;
a6b151f1 12727 case FILEIO_ENOTDIR:
dda83cd7 12728 return ENOTDIR;
a6b151f1 12729 case FILEIO_EISDIR:
dda83cd7 12730 return EISDIR;
a6b151f1 12731 case FILEIO_EINVAL:
dda83cd7 12732 return EINVAL;
a6b151f1 12733 case FILEIO_ENFILE:
dda83cd7 12734 return ENFILE;
a6b151f1 12735 case FILEIO_EMFILE:
dda83cd7 12736 return EMFILE;
a6b151f1 12737 case FILEIO_EFBIG:
dda83cd7 12738 return EFBIG;
a6b151f1 12739 case FILEIO_ENOSPC:
dda83cd7 12740 return ENOSPC;
a6b151f1 12741 case FILEIO_ESPIPE:
dda83cd7 12742 return ESPIPE;
a6b151f1 12743 case FILEIO_EROFS:
dda83cd7 12744 return EROFS;
a6b151f1 12745 case FILEIO_ENOSYS:
dda83cd7 12746 return ENOSYS;
a6b151f1 12747 case FILEIO_ENAMETOOLONG:
dda83cd7 12748 return ENAMETOOLONG;
a6b151f1
DJ
12749 }
12750 return -1;
12751}
12752
12753static char *
12754remote_hostio_error (int errnum)
12755{
12756 int host_error = remote_fileio_errno_to_host (errnum);
12757
12758 if (host_error == -1)
12759 error (_("Unknown remote I/O error %d"), errnum);
12760 else
12761 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12762}
12763
440b7aec
PA
12764/* A RAII wrapper around a remote file descriptor. */
12765
12766class scoped_remote_fd
a6b151f1 12767{
440b7aec 12768public:
6b8edb51
PA
12769 scoped_remote_fd (remote_target *remote, int fd)
12770 : m_remote (remote), m_fd (fd)
440b7aec
PA
12771 {
12772 }
a6b151f1 12773
440b7aec
PA
12774 ~scoped_remote_fd ()
12775 {
12776 if (m_fd != -1)
12777 {
12778 try
12779 {
12780 int remote_errno;
6b8edb51 12781 m_remote->remote_hostio_close (m_fd, &remote_errno);
440b7aec
PA
12782 }
12783 catch (...)
12784 {
12785 /* Swallow exception before it escapes the dtor. If
12786 something goes wrong, likely the connection is gone,
12787 and there's nothing else that can be done. */
12788 }
12789 }
12790 }
12791
12792 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12793
12794 /* Release ownership of the file descriptor, and return it. */
88a774b9 12795 ATTRIBUTE_UNUSED_RESULT int release () noexcept
440b7aec
PA
12796 {
12797 int fd = m_fd;
12798 m_fd = -1;
12799 return fd;
12800 }
12801
12802 /* Return the owned file descriptor. */
12803 int get () const noexcept
12804 {
12805 return m_fd;
12806 }
12807
12808private:
6b8edb51
PA
12809 /* The remote target. */
12810 remote_target *m_remote;
12811
440b7aec
PA
12812 /* The owned remote I/O file descriptor. */
12813 int m_fd;
12814};
a6b151f1
DJ
12815
12816void
12817remote_file_put (const char *local_file, const char *remote_file, int from_tty)
6b8edb51
PA
12818{
12819 remote_target *remote = get_current_remote_target ();
12820
12821 if (remote == nullptr)
12822 error (_("command can only be used with remote target"));
12823
12824 remote->remote_file_put (local_file, remote_file, from_tty);
12825}
12826
12827void
12828remote_target::remote_file_put (const char *local_file, const char *remote_file,
12829 int from_tty)
a6b151f1 12830{
440b7aec 12831 int retcode, remote_errno, bytes, io_size;
a6b151f1
DJ
12832 int bytes_in_buffer;
12833 int saw_eof;
12834 ULONGEST offset;
a6b151f1 12835
d419f42d 12836 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
12837 if (file == NULL)
12838 perror_with_name (local_file);
a6b151f1 12839
440b7aec 12840 scoped_remote_fd fd
6b8edb51
PA
12841 (this, remote_hostio_open (NULL,
12842 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12843 | FILEIO_O_TRUNC),
12844 0700, 0, &remote_errno));
440b7aec 12845 if (fd.get () == -1)
a6b151f1
DJ
12846 remote_hostio_error (remote_errno);
12847
12848 /* Send up to this many bytes at once. They won't all fit in the
12849 remote packet limit, so we'll transfer slightly fewer. */
12850 io_size = get_remote_packet_size ();
5ca3b260 12851 gdb::byte_vector buffer (io_size);
a6b151f1 12852
a6b151f1
DJ
12853 bytes_in_buffer = 0;
12854 saw_eof = 0;
12855 offset = 0;
12856 while (bytes_in_buffer || !saw_eof)
12857 {
12858 if (!saw_eof)
12859 {
5ca3b260 12860 bytes = fread (buffer.data () + bytes_in_buffer, 1,
3e43a32a 12861 io_size - bytes_in_buffer,
d419f42d 12862 file.get ());
a6b151f1
DJ
12863 if (bytes == 0)
12864 {
d419f42d 12865 if (ferror (file.get ()))
a6b151f1
DJ
12866 error (_("Error reading %s."), local_file);
12867 else
12868 {
12869 /* EOF. Unless there is something still in the
12870 buffer from the last iteration, we are done. */
12871 saw_eof = 1;
12872 if (bytes_in_buffer == 0)
12873 break;
12874 }
12875 }
12876 }
12877 else
12878 bytes = 0;
12879
12880 bytes += bytes_in_buffer;
12881 bytes_in_buffer = 0;
12882
5ca3b260 12883 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
3e43a32a 12884 offset, &remote_errno);
a6b151f1
DJ
12885
12886 if (retcode < 0)
12887 remote_hostio_error (remote_errno);
12888 else if (retcode == 0)
12889 error (_("Remote write of %d bytes returned 0!"), bytes);
12890 else if (retcode < bytes)
12891 {
12892 /* Short write. Save the rest of the read data for the next
12893 write. */
12894 bytes_in_buffer = bytes - retcode;
5ca3b260 12895 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
a6b151f1
DJ
12896 }
12897
12898 offset += retcode;
12899 }
12900
6b8edb51 12901 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
12902 remote_hostio_error (remote_errno);
12903
12904 if (from_tty)
6cb06a8c 12905 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
a6b151f1
DJ
12906}
12907
12908void
12909remote_file_get (const char *remote_file, const char *local_file, int from_tty)
6b8edb51
PA
12910{
12911 remote_target *remote = get_current_remote_target ();
12912
12913 if (remote == nullptr)
12914 error (_("command can only be used with remote target"));
12915
12916 remote->remote_file_get (remote_file, local_file, from_tty);
12917}
12918
12919void
12920remote_target::remote_file_get (const char *remote_file, const char *local_file,
12921 int from_tty)
a6b151f1 12922{
440b7aec 12923 int remote_errno, bytes, io_size;
a6b151f1 12924 ULONGEST offset;
a6b151f1 12925
440b7aec 12926 scoped_remote_fd fd
6b8edb51
PA
12927 (this, remote_hostio_open (NULL,
12928 remote_file, FILEIO_O_RDONLY, 0, 0,
12929 &remote_errno));
440b7aec 12930 if (fd.get () == -1)
a6b151f1
DJ
12931 remote_hostio_error (remote_errno);
12932
d419f42d 12933 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
12934 if (file == NULL)
12935 perror_with_name (local_file);
a6b151f1
DJ
12936
12937 /* Send up to this many bytes at once. They won't all fit in the
12938 remote packet limit, so we'll transfer slightly fewer. */
12939 io_size = get_remote_packet_size ();
5ca3b260 12940 gdb::byte_vector buffer (io_size);
a6b151f1 12941
a6b151f1
DJ
12942 offset = 0;
12943 while (1)
12944 {
5ca3b260 12945 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
440b7aec 12946 &remote_errno);
a6b151f1
DJ
12947 if (bytes == 0)
12948 /* Success, but no bytes, means end-of-file. */
12949 break;
12950 if (bytes == -1)
12951 remote_hostio_error (remote_errno);
12952
12953 offset += bytes;
12954
5ca3b260 12955 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
a6b151f1
DJ
12956 if (bytes == 0)
12957 perror_with_name (local_file);
12958 }
12959
6b8edb51 12960 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
12961 remote_hostio_error (remote_errno);
12962
12963 if (from_tty)
6cb06a8c 12964 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
a6b151f1
DJ
12965}
12966
12967void
12968remote_file_delete (const char *remote_file, int from_tty)
12969{
6b8edb51 12970 remote_target *remote = get_current_remote_target ();
a6b151f1 12971
6b8edb51 12972 if (remote == nullptr)
a6b151f1
DJ
12973 error (_("command can only be used with remote target"));
12974
6b8edb51
PA
12975 remote->remote_file_delete (remote_file, from_tty);
12976}
12977
12978void
12979remote_target::remote_file_delete (const char *remote_file, int from_tty)
12980{
12981 int retcode, remote_errno;
12982
12983 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
a6b151f1
DJ
12984 if (retcode == -1)
12985 remote_hostio_error (remote_errno);
12986
12987 if (from_tty)
6cb06a8c 12988 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
a6b151f1
DJ
12989}
12990
12991static void
ac88e2de 12992remote_put_command (const char *args, int from_tty)
a6b151f1 12993{
d1a41061
PP
12994 if (args == NULL)
12995 error_no_arg (_("file to put"));
12996
773a1edc 12997 gdb_argv argv (args);
a6b151f1
DJ
12998 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12999 error (_("Invalid parameters to remote put"));
13000
13001 remote_file_put (argv[0], argv[1], from_tty);
a6b151f1
DJ
13002}
13003
13004static void
ac88e2de 13005remote_get_command (const char *args, int from_tty)
a6b151f1 13006{
d1a41061
PP
13007 if (args == NULL)
13008 error_no_arg (_("file to get"));
13009
773a1edc 13010 gdb_argv argv (args);
a6b151f1
DJ
13011 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13012 error (_("Invalid parameters to remote get"));
13013
13014 remote_file_get (argv[0], argv[1], from_tty);
a6b151f1
DJ
13015}
13016
13017static void
ac88e2de 13018remote_delete_command (const char *args, int from_tty)
a6b151f1 13019{
d1a41061
PP
13020 if (args == NULL)
13021 error_no_arg (_("file to delete"));
13022
773a1edc 13023 gdb_argv argv (args);
a6b151f1
DJ
13024 if (argv[0] == NULL || argv[1] != NULL)
13025 error (_("Invalid parameters to remote delete"));
13026
13027 remote_file_delete (argv[0], from_tty);
a6b151f1
DJ
13028}
13029
57810aa7 13030bool
f6ac5f3d 13031remote_target::can_execute_reverse ()
b2175913 13032{
4082afcc
PA
13033 if (packet_support (PACKET_bs) == PACKET_ENABLE
13034 || packet_support (PACKET_bc) == PACKET_ENABLE)
57810aa7 13035 return true;
40ab02ce 13036 else
57810aa7 13037 return false;
b2175913
MS
13038}
13039
57810aa7 13040bool
f6ac5f3d 13041remote_target::supports_non_stop ()
74531fed 13042{
57810aa7 13043 return true;
74531fed
PA
13044}
13045
57810aa7 13046bool
f6ac5f3d 13047remote_target::supports_disable_randomization ()
03583c20
UW
13048{
13049 /* Only supported in extended mode. */
57810aa7 13050 return false;
03583c20
UW
13051}
13052
57810aa7 13053bool
f6ac5f3d 13054remote_target::supports_multi_process ()
8a305172
PA
13055{
13056 struct remote_state *rs = get_remote_state ();
a744cf53 13057
8020350c 13058 return remote_multi_process_p (rs);
8a305172
PA
13059}
13060
70221824 13061static int
f6ac5f3d 13062remote_supports_cond_tracepoints ()
782b2b07 13063{
4082afcc 13064 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
13065}
13066
57810aa7 13067bool
f6ac5f3d 13068remote_target::supports_evaluation_of_breakpoint_conditions ()
3788aec7 13069{
4082afcc 13070 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
13071}
13072
70221824 13073static int
f6ac5f3d 13074remote_supports_fast_tracepoints ()
7a697b8d 13075{
4082afcc 13076 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
13077}
13078
0fb4aa4b 13079static int
f6ac5f3d 13080remote_supports_static_tracepoints ()
0fb4aa4b 13081{
4082afcc 13082 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
13083}
13084
1e4d1764 13085static int
f6ac5f3d 13086remote_supports_install_in_trace ()
1e4d1764 13087{
4082afcc 13088 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
13089}
13090
57810aa7 13091bool
f6ac5f3d 13092remote_target::supports_enable_disable_tracepoint ()
d248b706 13093{
4082afcc
PA
13094 return (packet_support (PACKET_EnableDisableTracepoints_feature)
13095 == PACKET_ENABLE);
d248b706
KY
13096}
13097
57810aa7 13098bool
f6ac5f3d 13099remote_target::supports_string_tracing ()
3065dfb6 13100{
4082afcc 13101 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
13102}
13103
57810aa7 13104bool
f6ac5f3d 13105remote_target::can_run_breakpoint_commands ()
d3ce09f5 13106{
4082afcc 13107 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
13108}
13109
f6ac5f3d
PA
13110void
13111remote_target::trace_init ()
35b1e5cc 13112{
b6bb3468
PA
13113 struct remote_state *rs = get_remote_state ();
13114
35b1e5cc 13115 putpkt ("QTinit");
b6bb3468 13116 remote_get_noisy_reply ();
8d64371b 13117 if (strcmp (rs->buf.data (), "OK") != 0)
35b1e5cc
SS
13118 error (_("Target does not support this command."));
13119}
13120
409873ef
SS
13121/* Recursive routine to walk through command list including loops, and
13122 download packets for each command. */
13123
6b8edb51
PA
13124void
13125remote_target::remote_download_command_source (int num, ULONGEST addr,
13126 struct command_line *cmds)
409873ef
SS
13127{
13128 struct remote_state *rs = get_remote_state ();
13129 struct command_line *cmd;
13130
13131 for (cmd = cmds; cmd; cmd = cmd->next)
13132 {
0df8b418 13133 QUIT; /* Allow user to bail out with ^C. */
8d64371b 13134 strcpy (rs->buf.data (), "QTDPsrc:");
409873ef 13135 encode_source_string (num, addr, "cmd", cmd->line,
8d64371b
TT
13136 rs->buf.data () + strlen (rs->buf.data ()),
13137 rs->buf.size () - strlen (rs->buf.data ()));
409873ef 13138 putpkt (rs->buf);
b6bb3468 13139 remote_get_noisy_reply ();
8d64371b 13140 if (strcmp (rs->buf.data (), "OK"))
409873ef
SS
13141 warning (_("Target does not support source download."));
13142
13143 if (cmd->control_type == while_control
13144 || cmd->control_type == while_stepping_control)
13145 {
12973681 13146 remote_download_command_source (num, addr, cmd->body_list_0.get ());
409873ef 13147
0df8b418 13148 QUIT; /* Allow user to bail out with ^C. */
8d64371b 13149 strcpy (rs->buf.data (), "QTDPsrc:");
409873ef 13150 encode_source_string (num, addr, "cmd", "end",
8d64371b
TT
13151 rs->buf.data () + strlen (rs->buf.data ()),
13152 rs->buf.size () - strlen (rs->buf.data ()));
409873ef 13153 putpkt (rs->buf);
b6bb3468 13154 remote_get_noisy_reply ();
8d64371b 13155 if (strcmp (rs->buf.data (), "OK"))
409873ef
SS
13156 warning (_("Target does not support source download."));
13157 }
13158 }
13159}
13160
f6ac5f3d
PA
13161void
13162remote_target::download_tracepoint (struct bp_location *loc)
35b1e5cc
SS
13163{
13164 CORE_ADDR tpaddr;
409873ef 13165 char addrbuf[40];
b44ec619
SM
13166 std::vector<std::string> tdp_actions;
13167 std::vector<std::string> stepping_actions;
35b1e5cc 13168 char *pkt;
e8ba3115 13169 struct breakpoint *b = loc->owner;
d9b3f62e 13170 struct tracepoint *t = (struct tracepoint *) b;
b6bb3468 13171 struct remote_state *rs = get_remote_state ();
3df3a985 13172 int ret;
ff36536c 13173 const char *err_msg = _("Tracepoint packet too large for target.");
3df3a985
PFC
13174 size_t size_left;
13175
13176 /* We use a buffer other than rs->buf because we'll build strings
13177 across multiple statements, and other statements in between could
13178 modify rs->buf. */
13179 gdb::char_vector buf (get_remote_packet_size ());
35b1e5cc 13180
dc673c81 13181 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
13182
13183 tpaddr = loc->address;
53807e9f 13184 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
3df3a985
PFC
13185 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13186 b->number, addrbuf, /* address */
13187 (b->enable_state == bp_enabled ? 'E' : 'D'),
13188 t->step_count, t->pass_count);
13189
13190 if (ret < 0 || ret >= buf.size ())
a7f25a84 13191 error ("%s", err_msg);
3df3a985 13192
e8ba3115
YQ
13193 /* Fast tracepoints are mostly handled by the target, but we can
13194 tell the target how big of an instruction block should be moved
13195 around. */
13196 if (b->type == bp_fast_tracepoint)
13197 {
13198 /* Only test for support at download time; we may not know
13199 target capabilities at definition time. */
13200 if (remote_supports_fast_tracepoints ())
35b1e5cc 13201 {
6b940e6a
PL
13202 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13203 NULL))
3df3a985
PFC
13204 {
13205 size_left = buf.size () - strlen (buf.data ());
13206 ret = snprintf (buf.data () + strlen (buf.data ()),
13207 size_left, ":F%x",
13208 gdb_insn_length (loc->gdbarch, tpaddr));
13209
13210 if (ret < 0 || ret >= size_left)
a7f25a84 13211 error ("%s", err_msg);
3df3a985 13212 }
35b1e5cc 13213 else
e8ba3115
YQ
13214 /* If it passed validation at definition but fails now,
13215 something is very wrong. */
13216 internal_error (__FILE__, __LINE__,
13217 _("Fast tracepoint not "
13218 "valid during download"));
35b1e5cc 13219 }
e8ba3115
YQ
13220 else
13221 /* Fast tracepoints are functionally identical to regular
13222 tracepoints, so don't take lack of support as a reason to
13223 give up on the trace run. */
13224 warning (_("Target does not support fast tracepoints, "
13225 "downloading %d as regular tracepoint"), b->number);
13226 }
13227 else if (b->type == bp_static_tracepoint)
13228 {
13229 /* Only test for support at download time; we may not know
13230 target capabilities at definition time. */
13231 if (remote_supports_static_tracepoints ())
0fb4aa4b 13232 {
e8ba3115 13233 struct static_tracepoint_marker marker;
0fb4aa4b 13234
e8ba3115 13235 if (target_static_tracepoint_marker_at (tpaddr, &marker))
3df3a985
PFC
13236 {
13237 size_left = buf.size () - strlen (buf.data ());
13238 ret = snprintf (buf.data () + strlen (buf.data ()),
13239 size_left, ":S");
13240
13241 if (ret < 0 || ret >= size_left)
a7f25a84 13242 error ("%s", err_msg);
3df3a985 13243 }
0fb4aa4b 13244 else
e8ba3115 13245 error (_("Static tracepoint not valid during download"));
0fb4aa4b 13246 }
e8ba3115
YQ
13247 else
13248 /* Fast tracepoints are functionally identical to regular
13249 tracepoints, so don't take lack of support as a reason
13250 to give up on the trace run. */
13251 error (_("Target does not support static tracepoints"));
13252 }
13253 /* If the tracepoint has a conditional, make it into an agent
13254 expression and append to the definition. */
13255 if (loc->cond)
13256 {
13257 /* Only test support at download time, we may not know target
13258 capabilities at definition time. */
13259 if (remote_supports_cond_tracepoints ())
35b1e5cc 13260 {
3df3a985
PFC
13261 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13262 loc->cond.get ());
13263
13264 size_left = buf.size () - strlen (buf.data ());
13265
13266 ret = snprintf (buf.data () + strlen (buf.data ()),
13267 size_left, ":X%x,", aexpr->len);
13268
13269 if (ret < 0 || ret >= size_left)
a7f25a84 13270 error ("%s", err_msg);
3df3a985
PFC
13271
13272 size_left = buf.size () - strlen (buf.data ());
13273
13274 /* Two bytes to encode each aexpr byte, plus the terminating
13275 null byte. */
13276 if (aexpr->len * 2 + 1 > size_left)
a7f25a84 13277 error ("%s", err_msg);
3df3a985
PFC
13278
13279 pkt = buf.data () + strlen (buf.data ());
13280
b44ec619 13281 for (int ndx = 0; ndx < aexpr->len; ++ndx)
e8ba3115
YQ
13282 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13283 *pkt = '\0';
35b1e5cc 13284 }
e8ba3115
YQ
13285 else
13286 warning (_("Target does not support conditional tracepoints, "
13287 "ignoring tp %d cond"), b->number);
13288 }
35b1e5cc 13289
e0700ba4 13290 if (b->commands || !default_collect.empty ())
3df3a985
PFC
13291 {
13292 size_left = buf.size () - strlen (buf.data ());
13293
13294 ret = snprintf (buf.data () + strlen (buf.data ()),
13295 size_left, "-");
13296
13297 if (ret < 0 || ret >= size_left)
a7f25a84 13298 error ("%s", err_msg);
3df3a985
PFC
13299 }
13300
13301 putpkt (buf.data ());
b6bb3468 13302 remote_get_noisy_reply ();
8d64371b 13303 if (strcmp (rs->buf.data (), "OK"))
e8ba3115 13304 error (_("Target does not support tracepoints."));
35b1e5cc 13305
e8ba3115 13306 /* do_single_steps (t); */
b44ec619
SM
13307 for (auto action_it = tdp_actions.begin ();
13308 action_it != tdp_actions.end (); action_it++)
e8ba3115 13309 {
b44ec619
SM
13310 QUIT; /* Allow user to bail out with ^C. */
13311
aa6f3694 13312 bool has_more = ((action_it + 1) != tdp_actions.end ()
b44ec619
SM
13313 || !stepping_actions.empty ());
13314
3df3a985
PFC
13315 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13316 b->number, addrbuf, /* address */
13317 action_it->c_str (),
13318 has_more ? '-' : 0);
13319
13320 if (ret < 0 || ret >= buf.size ())
a7f25a84 13321 error ("%s", err_msg);
3df3a985
PFC
13322
13323 putpkt (buf.data ());
b44ec619 13324 remote_get_noisy_reply ();
8d64371b 13325 if (strcmp (rs->buf.data (), "OK"))
b44ec619 13326 error (_("Error on target while setting tracepoints."));
e8ba3115 13327 }
409873ef 13328
05abfc39
PFC
13329 for (auto action_it = stepping_actions.begin ();
13330 action_it != stepping_actions.end (); action_it++)
13331 {
13332 QUIT; /* Allow user to bail out with ^C. */
13333
13334 bool is_first = action_it == stepping_actions.begin ();
aa6f3694 13335 bool has_more = (action_it + 1) != stepping_actions.end ();
05abfc39 13336
3df3a985
PFC
13337 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13338 b->number, addrbuf, /* address */
13339 is_first ? "S" : "",
13340 action_it->c_str (),
13341 has_more ? "-" : "");
13342
13343 if (ret < 0 || ret >= buf.size ())
a7f25a84 13344 error ("%s", err_msg);
3df3a985
PFC
13345
13346 putpkt (buf.data ());
05abfc39 13347 remote_get_noisy_reply ();
8d64371b 13348 if (strcmp (rs->buf.data (), "OK"))
05abfc39
PFC
13349 error (_("Error on target while setting tracepoints."));
13350 }
b44ec619 13351
4082afcc 13352 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 13353 {
f00aae0f 13354 if (b->location != NULL)
409873ef 13355 {
3df3a985
PFC
13356 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13357
13358 if (ret < 0 || ret >= buf.size ())
a7f25a84 13359 error ("%s", err_msg);
3df3a985 13360
f00aae0f 13361 encode_source_string (b->number, loc->address, "at",
d28cd78a 13362 event_location_to_string (b->location.get ()),
3df3a985
PFC
13363 buf.data () + strlen (buf.data ()),
13364 buf.size () - strlen (buf.data ()));
13365 putpkt (buf.data ());
b6bb3468 13366 remote_get_noisy_reply ();
8d64371b 13367 if (strcmp (rs->buf.data (), "OK"))
e8ba3115 13368 warning (_("Target does not support source download."));
409873ef 13369 }
e8ba3115
YQ
13370 if (b->cond_string)
13371 {
3df3a985
PFC
13372 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13373
13374 if (ret < 0 || ret >= buf.size ())
a7f25a84 13375 error ("%s", err_msg);
3df3a985 13376
e8ba3115 13377 encode_source_string (b->number, loc->address,
6f781ee3 13378 "cond", b->cond_string.get (),
3df3a985
PFC
13379 buf.data () + strlen (buf.data ()),
13380 buf.size () - strlen (buf.data ()));
13381 putpkt (buf.data ());
b6bb3468 13382 remote_get_noisy_reply ();
8d64371b 13383 if (strcmp (rs->buf.data (), "OK"))
e8ba3115
YQ
13384 warning (_("Target does not support source download."));
13385 }
13386 remote_download_command_source (b->number, loc->address,
13387 breakpoint_commands (b));
35b1e5cc 13388 }
35b1e5cc
SS
13389}
13390
57810aa7 13391bool
f6ac5f3d 13392remote_target::can_download_tracepoint ()
1e4d1764 13393{
1e51243a
PA
13394 struct remote_state *rs = get_remote_state ();
13395 struct trace_status *ts;
13396 int status;
13397
13398 /* Don't try to install tracepoints until we've relocated our
13399 symbols, and fetched and merged the target's tracepoint list with
13400 ours. */
13401 if (rs->starting_up)
57810aa7 13402 return false;
1e51243a
PA
13403
13404 ts = current_trace_status ();
f6ac5f3d 13405 status = get_trace_status (ts);
1e4d1764
YQ
13406
13407 if (status == -1 || !ts->running_known || !ts->running)
57810aa7 13408 return false;
1e4d1764
YQ
13409
13410 /* If we are in a tracing experiment, but remote stub doesn't support
13411 installing tracepoint in trace, we have to return. */
13412 if (!remote_supports_install_in_trace ())
57810aa7 13413 return false;
1e4d1764 13414
57810aa7 13415 return true;
1e4d1764
YQ
13416}
13417
13418
f6ac5f3d
PA
13419void
13420remote_target::download_trace_state_variable (const trace_state_variable &tsv)
35b1e5cc
SS
13421{
13422 struct remote_state *rs = get_remote_state ();
00bf0b85 13423 char *p;
35b1e5cc 13424
8d64371b 13425 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
c252925c
SM
13426 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13427 tsv.builtin);
8d64371b
TT
13428 p = rs->buf.data () + strlen (rs->buf.data ());
13429 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13430 >= get_remote_packet_size ())
00bf0b85 13431 error (_("Trace state variable name too long for tsv definition packet"));
c252925c 13432 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
00bf0b85 13433 *p++ = '\0';
35b1e5cc 13434 putpkt (rs->buf);
b6bb3468 13435 remote_get_noisy_reply ();
8d64371b 13436 if (rs->buf[0] == '\0')
ad91cd99 13437 error (_("Target does not support this command."));
8d64371b 13438 if (strcmp (rs->buf.data (), "OK") != 0)
ad91cd99 13439 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
13440}
13441
f6ac5f3d
PA
13442void
13443remote_target::enable_tracepoint (struct bp_location *location)
d248b706
KY
13444{
13445 struct remote_state *rs = get_remote_state ();
d248b706 13446
8d64371b 13447 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
53807e9f
TT
13448 location->owner->number,
13449 phex (location->address, sizeof (CORE_ADDR)));
d248b706 13450 putpkt (rs->buf);
b6bb3468 13451 remote_get_noisy_reply ();
8d64371b 13452 if (rs->buf[0] == '\0')
d248b706 13453 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
8d64371b 13454 if (strcmp (rs->buf.data (), "OK") != 0)
d248b706
KY
13455 error (_("Error on target while enabling tracepoint."));
13456}
13457
f6ac5f3d
PA
13458void
13459remote_target::disable_tracepoint (struct bp_location *location)
d248b706
KY
13460{
13461 struct remote_state *rs = get_remote_state ();
d248b706 13462
8d64371b 13463 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
53807e9f
TT
13464 location->owner->number,
13465 phex (location->address, sizeof (CORE_ADDR)));
d248b706 13466 putpkt (rs->buf);
b6bb3468 13467 remote_get_noisy_reply ();
8d64371b 13468 if (rs->buf[0] == '\0')
d248b706 13469 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
8d64371b 13470 if (strcmp (rs->buf.data (), "OK") != 0)
d248b706
KY
13471 error (_("Error on target while disabling tracepoint."));
13472}
13473
f6ac5f3d
PA
13474void
13475remote_target::trace_set_readonly_regions ()
35b1e5cc
SS
13476{
13477 asection *s;
13478 bfd_size_type size;
608bcef2 13479 bfd_vma vma;
35b1e5cc 13480 int anysecs = 0;
c2fa21f1 13481 int offset = 0;
35b1e5cc 13482
7e10abd1 13483 if (!current_program_space->exec_bfd ())
35b1e5cc
SS
13484 return; /* No information to give. */
13485
b6bb3468
PA
13486 struct remote_state *rs = get_remote_state ();
13487
8d64371b
TT
13488 strcpy (rs->buf.data (), "QTro");
13489 offset = strlen (rs->buf.data ());
7e10abd1 13490 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
35b1e5cc
SS
13491 {
13492 char tmp1[40], tmp2[40];
c2fa21f1 13493 int sec_length;
35b1e5cc
SS
13494
13495 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 13496 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
13497 (s->flags & SEC_READONLY) == 0)
13498 continue;
13499
13500 anysecs = 1;
fd361982
AM
13501 vma = bfd_section_vma (s);
13502 size = bfd_section_size (s);
608bcef2
HZ
13503 sprintf_vma (tmp1, vma);
13504 sprintf_vma (tmp2, vma + size);
c2fa21f1 13505 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
8d64371b 13506 if (offset + sec_length + 1 > rs->buf.size ())
c2fa21f1 13507 {
4082afcc 13508 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 13509 warning (_("\
c2fa21f1
HZ
13510Too many sections for read-only sections definition packet."));
13511 break;
13512 }
8d64371b 13513 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
bba74b36 13514 tmp1, tmp2);
c2fa21f1 13515 offset += sec_length;
35b1e5cc
SS
13516 }
13517 if (anysecs)
13518 {
b6bb3468 13519 putpkt (rs->buf);
8d64371b 13520 getpkt (&rs->buf, 0);
35b1e5cc
SS
13521 }
13522}
13523
f6ac5f3d
PA
13524void
13525remote_target::trace_start ()
35b1e5cc 13526{
b6bb3468
PA
13527 struct remote_state *rs = get_remote_state ();
13528
35b1e5cc 13529 putpkt ("QTStart");
b6bb3468 13530 remote_get_noisy_reply ();
8d64371b 13531 if (rs->buf[0] == '\0')
ad91cd99 13532 error (_("Target does not support this command."));
8d64371b
TT
13533 if (strcmp (rs->buf.data (), "OK") != 0)
13534 error (_("Bogus reply from target: %s"), rs->buf.data ());
35b1e5cc
SS
13535}
13536
f6ac5f3d
PA
13537int
13538remote_target::get_trace_status (struct trace_status *ts)
35b1e5cc 13539{
953b98d1 13540 /* Initialize it just to avoid a GCC false warning. */
f652de6f 13541 char *p = NULL;
bd3eecc3 13542 enum packet_result result;
b6bb3468 13543 struct remote_state *rs = get_remote_state ();
bd3eecc3 13544
4082afcc 13545 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 13546 return -1;
a744cf53 13547
7b9a15e1 13548 /* FIXME we need to get register block size some other way. */
5cd63fda 13549 trace_regblock_size
9d6eea31 13550 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
00bf0b85 13551
049dc89b
JK
13552 putpkt ("qTStatus");
13553
a70b8144 13554 try
67f41397 13555 {
b6bb3468 13556 p = remote_get_noisy_reply ();
67f41397 13557 }
230d2906 13558 catch (const gdb_exception_error &ex)
67f41397 13559 {
598d3636
JK
13560 if (ex.error != TARGET_CLOSE_ERROR)
13561 {
13562 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13563 return -1;
13564 }
eedc3f4f 13565 throw;
67f41397 13566 }
00bf0b85 13567
bd3eecc3
PA
13568 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13569
00bf0b85 13570 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 13571 if (result == PACKET_UNKNOWN)
00bf0b85 13572 return -1;
35b1e5cc 13573
00bf0b85 13574 /* We're working with a live target. */
f5911ea1 13575 ts->filename = NULL;
00bf0b85 13576
00bf0b85 13577 if (*p++ != 'T')
8d64371b 13578 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
35b1e5cc 13579
84cebc4a
YQ
13580 /* Function 'parse_trace_status' sets default value of each field of
13581 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
13582 parse_trace_status (p, ts);
13583
13584 return ts->running;
35b1e5cc
SS
13585}
13586
f6ac5f3d
PA
13587void
13588remote_target::get_tracepoint_status (struct breakpoint *bp,
13589 struct uploaded_tp *utp)
f196051f
SS
13590{
13591 struct remote_state *rs = get_remote_state ();
f196051f 13592 char *reply;
f196051f 13593 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 13594 size_t size = get_remote_packet_size ();
f196051f
SS
13595
13596 if (tp)
13597 {
c1fc2657 13598 tp->hit_count = 0;
f196051f 13599 tp->traceframe_usage = 0;
40cb8ca5 13600 for (bp_location *loc : tp->locations ())
f196051f
SS
13601 {
13602 /* If the tracepoint was never downloaded, don't go asking for
13603 any status. */
13604 if (tp->number_on_target == 0)
13605 continue;
8d64371b 13606 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
bba74b36 13607 phex_nz (loc->address, 0));
f196051f 13608 putpkt (rs->buf);
b6bb3468 13609 reply = remote_get_noisy_reply ();
f196051f
SS
13610 if (reply && *reply)
13611 {
13612 if (*reply == 'V')
13613 parse_tracepoint_status (reply + 1, bp, utp);
13614 }
13615 }
13616 }
13617 else if (utp)
13618 {
13619 utp->hit_count = 0;
13620 utp->traceframe_usage = 0;
8d64371b 13621 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
bba74b36 13622 phex_nz (utp->addr, 0));
f196051f 13623 putpkt (rs->buf);
b6bb3468 13624 reply = remote_get_noisy_reply ();
f196051f
SS
13625 if (reply && *reply)
13626 {
13627 if (*reply == 'V')
13628 parse_tracepoint_status (reply + 1, bp, utp);
13629 }
13630 }
13631}
13632
f6ac5f3d
PA
13633void
13634remote_target::trace_stop ()
35b1e5cc 13635{
b6bb3468
PA
13636 struct remote_state *rs = get_remote_state ();
13637
35b1e5cc 13638 putpkt ("QTStop");
b6bb3468 13639 remote_get_noisy_reply ();
8d64371b 13640 if (rs->buf[0] == '\0')
ad91cd99 13641 error (_("Target does not support this command."));
8d64371b
TT
13642 if (strcmp (rs->buf.data (), "OK") != 0)
13643 error (_("Bogus reply from target: %s"), rs->buf.data ());
35b1e5cc
SS
13644}
13645
f6ac5f3d
PA
13646int
13647remote_target::trace_find (enum trace_find_type type, int num,
13648 CORE_ADDR addr1, CORE_ADDR addr2,
13649 int *tpp)
35b1e5cc
SS
13650{
13651 struct remote_state *rs = get_remote_state ();
8d64371b 13652 char *endbuf = rs->buf.data () + get_remote_packet_size ();
35b1e5cc
SS
13653 char *p, *reply;
13654 int target_frameno = -1, target_tracept = -1;
13655
e6e4e701
PA
13656 /* Lookups other than by absolute frame number depend on the current
13657 trace selected, so make sure it is correct on the remote end
13658 first. */
13659 if (type != tfind_number)
13660 set_remote_traceframe ();
13661
8d64371b 13662 p = rs->buf.data ();
35b1e5cc
SS
13663 strcpy (p, "QTFrame:");
13664 p = strchr (p, '\0');
13665 switch (type)
13666 {
13667 case tfind_number:
bba74b36 13668 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
13669 break;
13670 case tfind_pc:
bba74b36 13671 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
13672 break;
13673 case tfind_tp:
bba74b36 13674 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
13675 break;
13676 case tfind_range:
bba74b36
YQ
13677 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13678 phex_nz (addr2, 0));
35b1e5cc
SS
13679 break;
13680 case tfind_outside:
bba74b36
YQ
13681 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13682 phex_nz (addr2, 0));
35b1e5cc
SS
13683 break;
13684 default:
9b20d036 13685 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
13686 }
13687
13688 putpkt (rs->buf);
b6bb3468 13689 reply = remote_get_noisy_reply ();
ad91cd99
PA
13690 if (*reply == '\0')
13691 error (_("Target does not support this command."));
35b1e5cc
SS
13692
13693 while (reply && *reply)
13694 switch (*reply)
13695 {
13696 case 'F':
f197e0f1
VP
13697 p = ++reply;
13698 target_frameno = (int) strtol (p, &reply, 16);
13699 if (reply == p)
13700 error (_("Unable to parse trace frame number"));
e6e4e701
PA
13701 /* Don't update our remote traceframe number cache on failure
13702 to select a remote traceframe. */
f197e0f1
VP
13703 if (target_frameno == -1)
13704 return -1;
35b1e5cc
SS
13705 break;
13706 case 'T':
f197e0f1
VP
13707 p = ++reply;
13708 target_tracept = (int) strtol (p, &reply, 16);
13709 if (reply == p)
13710 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
13711 break;
13712 case 'O': /* "OK"? */
13713 if (reply[1] == 'K' && reply[2] == '\0')
13714 reply += 2;
13715 else
13716 error (_("Bogus reply from target: %s"), reply);
13717 break;
13718 default:
13719 error (_("Bogus reply from target: %s"), reply);
13720 }
13721 if (tpp)
13722 *tpp = target_tracept;
e6e4e701 13723
262e1174 13724 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
13725 return target_frameno;
13726}
13727
57810aa7 13728bool
f6ac5f3d 13729remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
35b1e5cc
SS
13730{
13731 struct remote_state *rs = get_remote_state ();
13732 char *reply;
13733 ULONGEST uval;
13734
e6e4e701
PA
13735 set_remote_traceframe ();
13736
8d64371b 13737 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc 13738 putpkt (rs->buf);
b6bb3468 13739 reply = remote_get_noisy_reply ();
35b1e5cc
SS
13740 if (reply && *reply)
13741 {
13742 if (*reply == 'V')
13743 {
13744 unpack_varlen_hex (reply + 1, &uval);
13745 *val = (LONGEST) uval;
57810aa7 13746 return true;
35b1e5cc
SS
13747 }
13748 }
57810aa7 13749 return false;
35b1e5cc
SS
13750}
13751
f6ac5f3d
PA
13752int
13753remote_target::save_trace_data (const char *filename)
00bf0b85
SS
13754{
13755 struct remote_state *rs = get_remote_state ();
13756 char *p, *reply;
13757
8d64371b 13758 p = rs->buf.data ();
00bf0b85
SS
13759 strcpy (p, "QTSave:");
13760 p += strlen (p);
8d64371b
TT
13761 if ((p - rs->buf.data ()) + strlen (filename) * 2
13762 >= get_remote_packet_size ())
00bf0b85 13763 error (_("Remote file name too long for trace save packet"));
9f1b45b0 13764 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
13765 *p++ = '\0';
13766 putpkt (rs->buf);
b6bb3468 13767 reply = remote_get_noisy_reply ();
d6c5869f 13768 if (*reply == '\0')
ad91cd99
PA
13769 error (_("Target does not support this command."));
13770 if (strcmp (reply, "OK") != 0)
13771 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
13772 return 0;
13773}
13774
13775/* This is basically a memory transfer, but needs to be its own packet
13776 because we don't know how the target actually organizes its trace
13777 memory, plus we want to be able to ask for as much as possible, but
13778 not be unhappy if we don't get as much as we ask for. */
13779
f6ac5f3d
PA
13780LONGEST
13781remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
13782{
13783 struct remote_state *rs = get_remote_state ();
13784 char *reply;
13785 char *p;
13786 int rslt;
13787
8d64371b 13788 p = rs->buf.data ();
00bf0b85
SS
13789 strcpy (p, "qTBuffer:");
13790 p += strlen (p);
13791 p += hexnumstr (p, offset);
13792 *p++ = ',';
13793 p += hexnumstr (p, len);
13794 *p++ = '\0';
13795
13796 putpkt (rs->buf);
b6bb3468 13797 reply = remote_get_noisy_reply ();
00bf0b85
SS
13798 if (reply && *reply)
13799 {
13800 /* 'l' by itself means we're at the end of the buffer and
13801 there is nothing more to get. */
13802 if (*reply == 'l')
13803 return 0;
13804
13805 /* Convert the reply into binary. Limit the number of bytes to
13806 convert according to our passed-in buffer size, rather than
13807 what was returned in the packet; if the target is
13808 unexpectedly generous and gives us a bigger reply than we
13809 asked for, we don't want to crash. */
b6bb3468 13810 rslt = hex2bin (reply, buf, len);
00bf0b85
SS
13811 return rslt;
13812 }
13813
13814 /* Something went wrong, flag as an error. */
13815 return -1;
13816}
13817
f6ac5f3d
PA
13818void
13819remote_target::set_disconnected_tracing (int val)
35b1e5cc
SS
13820{
13821 struct remote_state *rs = get_remote_state ();
13822
4082afcc 13823 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 13824 {
ad91cd99
PA
13825 char *reply;
13826
8d64371b
TT
13827 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13828 "QTDisconnected:%x", val);
33da3f1c 13829 putpkt (rs->buf);
b6bb3468 13830 reply = remote_get_noisy_reply ();
ad91cd99 13831 if (*reply == '\0')
33da3f1c 13832 error (_("Target does not support this command."));
ad91cd99 13833 if (strcmp (reply, "OK") != 0)
dda83cd7 13834 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
13835 }
13836 else if (val)
13837 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
13838}
13839
f6ac5f3d
PA
13840int
13841remote_target::core_of_thread (ptid_t ptid)
dc146f7c 13842{
5b6d1e4f 13843 thread_info *info = find_thread_ptid (this, ptid);
a744cf53 13844
7aabaf9d
SM
13845 if (info != NULL && info->priv != NULL)
13846 return get_remote_thread_info (info)->core;
13847
dc146f7c
VP
13848 return -1;
13849}
13850
f6ac5f3d
PA
13851void
13852remote_target::set_circular_trace_buffer (int val)
4daf5ac0
SS
13853{
13854 struct remote_state *rs = get_remote_state ();
ad91cd99 13855 char *reply;
4daf5ac0 13856
8d64371b
TT
13857 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13858 "QTBuffer:circular:%x", val);
4daf5ac0 13859 putpkt (rs->buf);
b6bb3468 13860 reply = remote_get_noisy_reply ();
ad91cd99 13861 if (*reply == '\0')
4daf5ac0 13862 error (_("Target does not support this command."));
ad91cd99
PA
13863 if (strcmp (reply, "OK") != 0)
13864 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
13865}
13866
f6ac5f3d
PA
13867traceframe_info_up
13868remote_target::traceframe_info ()
b3b9301e 13869{
9018be22 13870 gdb::optional<gdb::char_vector> text
328d42d8
SM
13871 = target_read_stralloc (current_inferior ()->top_target (),
13872 TARGET_OBJECT_TRACEFRAME_INFO,
b7b030ad 13873 NULL);
9018be22
SM
13874 if (text)
13875 return parse_traceframe_info (text->data ());
b3b9301e
PA
13876
13877 return NULL;
13878}
13879
405f8e94
SS
13880/* Handle the qTMinFTPILen packet. Returns the minimum length of
13881 instruction on which a fast tracepoint may be placed. Returns -1
13882 if the packet is not supported, and 0 if the minimum instruction
13883 length is unknown. */
13884
f6ac5f3d
PA
13885int
13886remote_target::get_min_fast_tracepoint_insn_len ()
405f8e94
SS
13887{
13888 struct remote_state *rs = get_remote_state ();
13889 char *reply;
13890
e886a173
PA
13891 /* If we're not debugging a process yet, the IPA can't be
13892 loaded. */
55f6301a 13893 if (!target_has_execution ())
e886a173
PA
13894 return 0;
13895
13896 /* Make sure the remote is pointing at the right process. */
13897 set_general_process ();
13898
8d64371b 13899 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
405f8e94 13900 putpkt (rs->buf);
b6bb3468 13901 reply = remote_get_noisy_reply ();
405f8e94
SS
13902 if (*reply == '\0')
13903 return -1;
13904 else
13905 {
13906 ULONGEST min_insn_len;
13907
13908 unpack_varlen_hex (reply, &min_insn_len);
13909
13910 return (int) min_insn_len;
13911 }
13912}
13913
f6ac5f3d
PA
13914void
13915remote_target::set_trace_buffer_size (LONGEST val)
f6f899bf 13916{
4082afcc 13917 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
13918 {
13919 struct remote_state *rs = get_remote_state ();
8d64371b
TT
13920 char *buf = rs->buf.data ();
13921 char *endbuf = buf + get_remote_packet_size ();
f6f899bf
HAQ
13922 enum packet_result result;
13923
13924 gdb_assert (val >= 0 || val == -1);
13925 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13926 /* Send -1 as literal "-1" to avoid host size dependency. */
13927 if (val < 0)
13928 {
13929 *buf++ = '-';
dda83cd7 13930 buf += hexnumstr (buf, (ULONGEST) -val);
f6f899bf
HAQ
13931 }
13932 else
13933 buf += hexnumstr (buf, (ULONGEST) val);
13934
13935 putpkt (rs->buf);
b6bb3468 13936 remote_get_noisy_reply ();
f6f899bf
HAQ
13937 result = packet_ok (rs->buf,
13938 &remote_protocol_packets[PACKET_QTBuffer_size]);
13939
13940 if (result != PACKET_OK)
8d64371b 13941 warning (_("Bogus reply from target: %s"), rs->buf.data ());
f6f899bf
HAQ
13942 }
13943}
13944
57810aa7 13945bool
f6ac5f3d
PA
13946remote_target::set_trace_notes (const char *user, const char *notes,
13947 const char *stop_notes)
f196051f
SS
13948{
13949 struct remote_state *rs = get_remote_state ();
13950 char *reply;
8d64371b
TT
13951 char *buf = rs->buf.data ();
13952 char *endbuf = buf + get_remote_packet_size ();
f196051f
SS
13953 int nbytes;
13954
13955 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13956 if (user)
13957 {
13958 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 13959 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
13960 buf += 2 * nbytes;
13961 *buf++ = ';';
13962 }
13963 if (notes)
13964 {
13965 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 13966 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
13967 buf += 2 * nbytes;
13968 *buf++ = ';';
13969 }
13970 if (stop_notes)
13971 {
13972 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 13973 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
13974 buf += 2 * nbytes;
13975 *buf++ = ';';
13976 }
13977 /* Ensure the buffer is terminated. */
13978 *buf = '\0';
13979
13980 putpkt (rs->buf);
b6bb3468 13981 reply = remote_get_noisy_reply ();
f196051f 13982 if (*reply == '\0')
57810aa7 13983 return false;
f196051f
SS
13984
13985 if (strcmp (reply, "OK") != 0)
13986 error (_("Bogus reply from target: %s"), reply);
13987
57810aa7 13988 return true;
f196051f
SS
13989}
13990
57810aa7
PA
13991bool
13992remote_target::use_agent (bool use)
d1feda86 13993{
4082afcc 13994 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
13995 {
13996 struct remote_state *rs = get_remote_state ();
13997
13998 /* If the stub supports QAgent. */
8d64371b 13999 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
d1feda86 14000 putpkt (rs->buf);
8d64371b 14001 getpkt (&rs->buf, 0);
d1feda86 14002
8d64371b 14003 if (strcmp (rs->buf.data (), "OK") == 0)
d1feda86 14004 {
f6ac5f3d 14005 ::use_agent = use;
57810aa7 14006 return true;
d1feda86
YQ
14007 }
14008 }
14009
57810aa7 14010 return false;
d1feda86
YQ
14011}
14012
57810aa7 14013bool
f6ac5f3d 14014remote_target::can_use_agent ()
d1feda86 14015{
4082afcc 14016 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
14017}
14018
9accd112
MM
14019struct btrace_target_info
14020{
14021 /* The ptid of the traced thread. */
14022 ptid_t ptid;
f4abbc16
MM
14023
14024 /* The obtained branch trace configuration. */
14025 struct btrace_config conf;
9accd112
MM
14026};
14027
f4abbc16
MM
14028/* Reset our idea of our target's btrace configuration. */
14029
14030static void
6b8edb51 14031remote_btrace_reset (remote_state *rs)
f4abbc16 14032{
f4abbc16
MM
14033 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14034}
14035
f4abbc16
MM
14036/* Synchronize the configuration with the target. */
14037
6b8edb51
PA
14038void
14039remote_target::btrace_sync_conf (const btrace_config *conf)
f4abbc16 14040{
d33501a5
MM
14041 struct packet_config *packet;
14042 struct remote_state *rs;
14043 char *buf, *pos, *endbuf;
14044
14045 rs = get_remote_state ();
8d64371b 14046 buf = rs->buf.data ();
d33501a5
MM
14047 endbuf = buf + get_remote_packet_size ();
14048
14049 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
14050 if (packet_config_support (packet) == PACKET_ENABLE
14051 && conf->bts.size != rs->btrace_config.bts.size)
14052 {
14053 pos = buf;
14054 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
dda83cd7 14055 conf->bts.size);
d33501a5
MM
14056
14057 putpkt (buf);
8d64371b 14058 getpkt (&rs->buf, 0);
d33501a5
MM
14059
14060 if (packet_ok (buf, packet) == PACKET_ERROR)
14061 {
14062 if (buf[0] == 'E' && buf[1] == '.')
14063 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14064 else
14065 error (_("Failed to configure the BTS buffer size."));
14066 }
14067
14068 rs->btrace_config.bts.size = conf->bts.size;
14069 }
b20a6524
MM
14070
14071 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
14072 if (packet_config_support (packet) == PACKET_ENABLE
14073 && conf->pt.size != rs->btrace_config.pt.size)
14074 {
14075 pos = buf;
14076 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
dda83cd7 14077 conf->pt.size);
b20a6524
MM
14078
14079 putpkt (buf);
8d64371b 14080 getpkt (&rs->buf, 0);
b20a6524
MM
14081
14082 if (packet_ok (buf, packet) == PACKET_ERROR)
14083 {
14084 if (buf[0] == 'E' && buf[1] == '.')
14085 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14086 else
14087 error (_("Failed to configure the trace buffer size."));
14088 }
14089
14090 rs->btrace_config.pt.size = conf->pt.size;
14091 }
f4abbc16
MM
14092}
14093
0d8cbc5f 14094/* Read TP's btrace configuration from the target and store it into CONF. */
f4abbc16
MM
14095
14096static void
0d8cbc5f 14097btrace_read_config (thread_info *tp, struct btrace_config *conf)
f4abbc16 14098{
0d8cbc5f
MM
14099 /* target_read_stralloc relies on INFERIOR_PTID. */
14100 scoped_restore_current_thread restore_thread;
14101 switch_to_thread (tp);
14102
9018be22 14103 gdb::optional<gdb::char_vector> xml
328d42d8
SM
14104 = target_read_stralloc (current_inferior ()->top_target (),
14105 TARGET_OBJECT_BTRACE_CONF, "");
9018be22
SM
14106 if (xml)
14107 parse_xml_btrace_conf (conf, xml->data ());
f4abbc16
MM
14108}
14109
c0272db5
TW
14110/* Maybe reopen target btrace. */
14111
6b8edb51
PA
14112void
14113remote_target::remote_btrace_maybe_reopen ()
c0272db5
TW
14114{
14115 struct remote_state *rs = get_remote_state ();
c0272db5 14116 int btrace_target_pushed = 0;
15766370 14117#if !defined (HAVE_LIBIPT)
c0272db5 14118 int warned = 0;
15766370 14119#endif
c0272db5 14120
aedbe3bb
CM
14121 /* Don't bother walking the entirety of the remote thread list when
14122 we know the feature isn't supported by the remote. */
14123 if (packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14124 return;
14125
5b6d1e4f 14126 for (thread_info *tp : all_non_exited_threads (this))
c0272db5 14127 {
c0272db5 14128 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
0d8cbc5f 14129 btrace_read_config (tp, &rs->btrace_config);
c0272db5
TW
14130
14131 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14132 continue;
14133
14134#if !defined (HAVE_LIBIPT)
14135 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14136 {
14137 if (!warned)
14138 {
14139 warned = 1;
c4e12631
MM
14140 warning (_("Target is recording using Intel Processor Trace "
14141 "but support was disabled at compile time."));
c0272db5
TW
14142 }
14143
14144 continue;
14145 }
14146#endif /* !defined (HAVE_LIBIPT) */
14147
14148 /* Push target, once, but before anything else happens. This way our
14149 changes to the threads will be cleaned up by unpushing the target
14150 in case btrace_read_config () throws. */
14151 if (!btrace_target_pushed)
14152 {
14153 btrace_target_pushed = 1;
14154 record_btrace_push_target ();
6cb06a8c
TT
14155 gdb_printf (_("Target is recording using %s.\n"),
14156 btrace_format_string (rs->btrace_config.format));
c0272db5
TW
14157 }
14158
14159 tp->btrace.target = XCNEW (struct btrace_target_info);
14160 tp->btrace.target->ptid = tp->ptid;
14161 tp->btrace.target->conf = rs->btrace_config;
14162 }
c0272db5
TW
14163}
14164
9accd112
MM
14165/* Enable branch tracing. */
14166
f6ac5f3d 14167struct btrace_target_info *
696c0d5e
MM
14168remote_target::enable_btrace (thread_info *tp,
14169 const struct btrace_config *conf)
9accd112
MM
14170{
14171 struct btrace_target_info *tinfo = NULL;
b20a6524 14172 struct packet_config *packet = NULL;
9accd112 14173 struct remote_state *rs = get_remote_state ();
8d64371b
TT
14174 char *buf = rs->buf.data ();
14175 char *endbuf = buf + get_remote_packet_size ();
9accd112 14176
b20a6524
MM
14177 switch (conf->format)
14178 {
14179 case BTRACE_FORMAT_BTS:
14180 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
14181 break;
14182
14183 case BTRACE_FORMAT_PT:
14184 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
14185 break;
14186 }
14187
14188 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
14189 error (_("Target does not support branch tracing."));
14190
f4abbc16
MM
14191 btrace_sync_conf (conf);
14192
696c0d5e 14193 ptid_t ptid = tp->ptid;
9accd112
MM
14194 set_general_thread (ptid);
14195
14196 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14197 putpkt (rs->buf);
8d64371b 14198 getpkt (&rs->buf, 0);
9accd112
MM
14199
14200 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14201 {
14202 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14203 error (_("Could not enable branch tracing for %s: %s"),
a068643d 14204 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
9accd112
MM
14205 else
14206 error (_("Could not enable branch tracing for %s."),
a068643d 14207 target_pid_to_str (ptid).c_str ());
9accd112
MM
14208 }
14209
8d749320 14210 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
14211 tinfo->ptid = ptid;
14212
f4abbc16
MM
14213 /* If we fail to read the configuration, we lose some information, but the
14214 tracing itself is not impacted. */
a70b8144 14215 try
492d29ea 14216 {
0d8cbc5f 14217 btrace_read_config (tp, &tinfo->conf);
492d29ea 14218 }
230d2906 14219 catch (const gdb_exception_error &err)
492d29ea
PA
14220 {
14221 if (err.message != NULL)
3d6e9d23 14222 warning ("%s", err.what ());
492d29ea 14223 }
f4abbc16 14224
9accd112
MM
14225 return tinfo;
14226}
14227
14228/* Disable branch tracing. */
14229
f6ac5f3d
PA
14230void
14231remote_target::disable_btrace (struct btrace_target_info *tinfo)
9accd112
MM
14232{
14233 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
14234 struct remote_state *rs = get_remote_state ();
8d64371b
TT
14235 char *buf = rs->buf.data ();
14236 char *endbuf = buf + get_remote_packet_size ();
9accd112 14237
4082afcc 14238 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
14239 error (_("Target does not support branch tracing."));
14240
14241 set_general_thread (tinfo->ptid);
14242
14243 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14244 putpkt (rs->buf);
8d64371b 14245 getpkt (&rs->buf, 0);
9accd112
MM
14246
14247 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14248 {
14249 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14250 error (_("Could not disable branch tracing for %s: %s"),
a068643d 14251 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
9accd112
MM
14252 else
14253 error (_("Could not disable branch tracing for %s."),
a068643d 14254 target_pid_to_str (tinfo->ptid).c_str ());
9accd112
MM
14255 }
14256
14257 xfree (tinfo);
14258}
14259
14260/* Teardown branch tracing. */
14261
f6ac5f3d
PA
14262void
14263remote_target::teardown_btrace (struct btrace_target_info *tinfo)
9accd112
MM
14264{
14265 /* We must not talk to the target during teardown. */
14266 xfree (tinfo);
14267}
14268
14269/* Read the branch trace. */
14270
f6ac5f3d
PA
14271enum btrace_error
14272remote_target::read_btrace (struct btrace_data *btrace,
14273 struct btrace_target_info *tinfo,
14274 enum btrace_read_type type)
9accd112
MM
14275{
14276 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
9accd112 14277 const char *annex;
9accd112 14278
4082afcc 14279 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
14280 error (_("Target does not support branch tracing."));
14281
14282#if !defined(HAVE_LIBEXPAT)
14283 error (_("Cannot process branch tracing result. XML parsing not supported."));
14284#endif
14285
14286 switch (type)
14287 {
864089d2 14288 case BTRACE_READ_ALL:
9accd112
MM
14289 annex = "all";
14290 break;
864089d2 14291 case BTRACE_READ_NEW:
9accd112
MM
14292 annex = "new";
14293 break;
969c39fb
MM
14294 case BTRACE_READ_DELTA:
14295 annex = "delta";
14296 break;
9accd112
MM
14297 default:
14298 internal_error (__FILE__, __LINE__,
14299 _("Bad branch tracing read type: %u."),
14300 (unsigned int) type);
14301 }
14302
9018be22 14303 gdb::optional<gdb::char_vector> xml
328d42d8
SM
14304 = target_read_stralloc (current_inferior ()->top_target (),
14305 TARGET_OBJECT_BTRACE, annex);
9018be22 14306 if (!xml)
969c39fb 14307 return BTRACE_ERR_UNKNOWN;
9accd112 14308
9018be22 14309 parse_xml_btrace (btrace, xml->data ());
9accd112 14310
969c39fb 14311 return BTRACE_ERR_NONE;
9accd112
MM
14312}
14313
f6ac5f3d
PA
14314const struct btrace_config *
14315remote_target::btrace_conf (const struct btrace_target_info *tinfo)
f4abbc16
MM
14316{
14317 return &tinfo->conf;
14318}
14319
57810aa7 14320bool
f6ac5f3d 14321remote_target::augmented_libraries_svr4_read ()
ced63ec0 14322{
4082afcc
PA
14323 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
14324 == PACKET_ENABLE);
ced63ec0
GB
14325}
14326
9dd130a0
TT
14327/* Implementation of to_load. */
14328
f6ac5f3d
PA
14329void
14330remote_target::load (const char *name, int from_tty)
9dd130a0
TT
14331{
14332 generic_load (name, from_tty);
14333}
14334
c78fa86a
GB
14335/* Accepts an integer PID; returns a string representing a file that
14336 can be opened on the remote side to get the symbols for the child
14337 process. Returns NULL if the operation is not supported. */
14338
f6ac5f3d
PA
14339char *
14340remote_target::pid_to_exec_file (int pid)
c78fa86a 14341{
9018be22 14342 static gdb::optional<gdb::char_vector> filename;
835205d0 14343 char *annex = NULL;
c78fa86a
GB
14344
14345 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14346 return NULL;
14347
5b6d1e4f 14348 inferior *inf = find_inferior_pid (this, pid);
835205d0
GB
14349 if (inf == NULL)
14350 internal_error (__FILE__, __LINE__,
14351 _("not currently attached to process %d"), pid);
14352
14353 if (!inf->fake_pid_p)
14354 {
14355 const int annex_size = 9;
14356
224c3ddb 14357 annex = (char *) alloca (annex_size);
835205d0
GB
14358 xsnprintf (annex, annex_size, "%x", pid);
14359 }
14360
328d42d8 14361 filename = target_read_stralloc (current_inferior ()->top_target (),
c78fa86a
GB
14362 TARGET_OBJECT_EXEC_FILE, annex);
14363
9018be22 14364 return filename ? filename->data () : nullptr;
c78fa86a
GB
14365}
14366
750ce8d1
YQ
14367/* Implement the to_can_do_single_step target_ops method. */
14368
f6ac5f3d
PA
14369int
14370remote_target::can_do_single_step ()
750ce8d1
YQ
14371{
14372 /* We can only tell whether target supports single step or not by
14373 supported s and S vCont actions if the stub supports vContSupported
14374 feature. If the stub doesn't support vContSupported feature,
14375 we have conservatively to think target doesn't supports single
14376 step. */
14377 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14378 {
14379 struct remote_state *rs = get_remote_state ();
14380
14381 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 14382 remote_vcont_probe ();
750ce8d1
YQ
14383
14384 return rs->supports_vCont.s && rs->supports_vCont.S;
14385 }
14386 else
14387 return 0;
14388}
14389
3a00c802
PA
14390/* Implementation of the to_execution_direction method for the remote
14391 target. */
14392
f6ac5f3d
PA
14393enum exec_direction_kind
14394remote_target::execution_direction ()
3a00c802
PA
14395{
14396 struct remote_state *rs = get_remote_state ();
14397
14398 return rs->last_resume_exec_dir;
14399}
14400
f6327dcb
KB
14401/* Return pointer to the thread_info struct which corresponds to
14402 THREAD_HANDLE (having length HANDLE_LEN). */
14403
f6ac5f3d
PA
14404thread_info *
14405remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14406 int handle_len,
14407 inferior *inf)
f6327dcb 14408{
5b6d1e4f 14409 for (thread_info *tp : all_non_exited_threads (this))
f6327dcb 14410 {
7aabaf9d 14411 remote_thread_info *priv = get_remote_thread_info (tp);
f6327dcb
KB
14412
14413 if (tp->inf == inf && priv != NULL)
dda83cd7 14414 {
7aabaf9d 14415 if (handle_len != priv->thread_handle.size ())
f6327dcb 14416 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
dda83cd7 14417 handle_len, priv->thread_handle.size ());
7aabaf9d 14418 if (memcmp (thread_handle, priv->thread_handle.data (),
dda83cd7 14419 handle_len) == 0)
f6327dcb
KB
14420 return tp;
14421 }
14422 }
14423
14424 return NULL;
14425}
14426
3d6c6204
KB
14427gdb::byte_vector
14428remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14429{
14430 remote_thread_info *priv = get_remote_thread_info (tp);
14431 return priv->thread_handle;
14432}
14433
57810aa7 14434bool
f6ac5f3d 14435remote_target::can_async_p ()
6426a772 14436{
fce6cd34
AB
14437 /* This flag should be checked in the common target.c code. */
14438 gdb_assert (target_async_permitted);
75c99385 14439
fce6cd34
AB
14440 /* We're async whenever the serial device can. */
14441 struct remote_state *rs = get_remote_state ();
5d93a237 14442 return serial_can_async_p (rs->remote_desc);
6426a772
JM
14443}
14444
57810aa7 14445bool
f6ac5f3d 14446remote_target::is_async_p ()
6426a772 14447{
23860348 14448 /* We're async whenever the serial device is. */
7054fa5b 14449 struct remote_state *rs = get_remote_state ();
5d93a237 14450 return serial_is_async_p (rs->remote_desc);
6426a772
JM
14451}
14452
2acceee2
JM
14453/* Pass the SERIAL event on and up to the client. One day this code
14454 will be able to delay notifying the client of an event until the
23860348 14455 point where an entire packet has been received. */
2acceee2 14456
2acceee2
JM
14457static serial_event_ftype remote_async_serial_handler;
14458
6426a772 14459static void
819cc324 14460remote_async_serial_handler (struct serial *scb, void *context)
6426a772 14461{
2acceee2
JM
14462 /* Don't propogate error information up to the client. Instead let
14463 the client find out about the error by querying the target. */
b1a35af2 14464 inferior_event_handler (INF_REG_EVENT);
2acceee2
JM
14465}
14466
74531fed
PA
14467static void
14468remote_async_inferior_event_handler (gdb_client_data data)
14469{
6b36ddeb 14470 inferior_event_handler (INF_REG_EVENT);
74531fed
PA
14471}
14472
5b6d1e4f
PA
14473int
14474remote_target::async_wait_fd ()
14475{
14476 struct remote_state *rs = get_remote_state ();
14477 return rs->remote_desc->fd;
14478}
14479
f6ac5f3d
PA
14480void
14481remote_target::async (int enable)
2acceee2 14482{
5d93a237
TT
14483 struct remote_state *rs = get_remote_state ();
14484
6a3753b3 14485 if (enable)
2acceee2 14486 {
88b496c3 14487 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
14488
14489 /* If there are pending events in the stop reply queue tell the
14490 event loop to process them. */
953edf2b 14491 if (!rs->stop_reply_queue.empty ())
6b8edb51 14492 mark_async_event_handler (rs->remote_async_inferior_event_token);
6efcd9a8
PA
14493 /* For simplicity, below we clear the pending events token
14494 without remembering whether it is marked, so here we always
14495 mark it. If there's actually no pending notification to
14496 process, this ends up being a no-op (other than a spurious
14497 event-loop wakeup). */
14498 if (target_is_non_stop_p ())
14499 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
14500 }
14501 else
b7d2e916
PA
14502 {
14503 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
14504 /* If the core is disabling async, it doesn't want to be
14505 disturbed with target events. Clear all async event sources
14506 too. */
6b8edb51 14507 clear_async_event_handler (rs->remote_async_inferior_event_token);
6efcd9a8
PA
14508 if (target_is_non_stop_p ())
14509 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 14510 }
6426a772
JM
14511}
14512
65706a29
PA
14513/* Implementation of the to_thread_events method. */
14514
f6ac5f3d
PA
14515void
14516remote_target::thread_events (int enable)
65706a29
PA
14517{
14518 struct remote_state *rs = get_remote_state ();
14519 size_t size = get_remote_packet_size ();
65706a29
PA
14520
14521 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14522 return;
14523
8d64371b 14524 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
65706a29 14525 putpkt (rs->buf);
8d64371b 14526 getpkt (&rs->buf, 0);
65706a29
PA
14527
14528 switch (packet_ok (rs->buf,
14529 &remote_protocol_packets[PACKET_QThreadEvents]))
14530 {
14531 case PACKET_OK:
8d64371b
TT
14532 if (strcmp (rs->buf.data (), "OK") != 0)
14533 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
65706a29
PA
14534 break;
14535 case PACKET_ERROR:
8d64371b 14536 warning (_("Remote failure reply: %s"), rs->buf.data ());
65706a29
PA
14537 break;
14538 case PACKET_UNKNOWN:
14539 break;
14540 }
14541}
14542
d471ea57 14543static void
981a3fb3 14544show_remote_cmd (const char *args, int from_tty)
d471ea57 14545{
37a105a1 14546 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 14547 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1 14548 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 14549 struct ui_out *uiout = current_uiout;
37a105a1 14550
2e783024 14551 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
37a105a1
DJ
14552 for (; list != NULL; list = list->next)
14553 if (strcmp (list->name, "Z-packet") == 0)
14554 continue;
427c3a89
DJ
14555 else if (list->type == not_set_cmd)
14556 /* Alias commands are exactly like the original, except they
14557 don't have the normal type. */
14558 continue;
14559 else
37a105a1 14560 {
2e783024 14561 ui_out_emit_tuple option_emitter (uiout, "option");
a744cf53 14562
112e8700
SM
14563 uiout->field_string ("name", list->name);
14564 uiout->text (": ");
427c3a89 14565 if (list->type == show_cmd)
f5c4fcd9 14566 do_show_command (NULL, from_tty, list);
427c3a89
DJ
14567 else
14568 cmd_func (list, NULL, from_tty);
37a105a1 14569 }
d471ea57 14570}
5a2468f5 14571
0f71a2f6 14572
23860348 14573/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
14574static void
14575remote_new_objfile (struct objfile *objfile)
14576{
6b8edb51 14577 remote_target *remote = get_current_remote_target ();
5d93a237 14578
122373f7
SM
14579 /* First, check whether the current inferior's process target is a remote
14580 target. */
14581 if (remote == nullptr)
14582 return;
14583
14584 /* When we are attaching or handling a fork child and the shared library
14585 subsystem reads the list of loaded libraries, we receive new objfile
14586 events in between each found library. The libraries are read in an
14587 undefined order, so if we gave the remote side a chance to look up
14588 symbols between each objfile, we might give it an inconsistent picture
14589 of the inferior. It could appear that a library A appears loaded but
14590 a library B does not, even though library A requires library B. That
14591 would present a state that couldn't normally exist in the inferior.
14592
14593 So, skip these events, we'll give the remote a chance to look up symbols
14594 once all the loaded libraries and their symbols are known to GDB. */
d424629d
JB
14595 if (current_inferior ()->in_initial_library_scan)
14596 return;
122373f7
SM
14597
14598 remote->remote_check_symbols ();
dc8acb97
MS
14599}
14600
00bf0b85
SS
14601/* Pull all the tracepoints defined on the target and create local
14602 data structures representing them. We don't want to create real
14603 tracepoints yet, we don't want to mess up the user's existing
14604 collection. */
14605
f6ac5f3d
PA
14606int
14607remote_target::upload_tracepoints (struct uploaded_tp **utpp)
d5551862 14608{
00bf0b85
SS
14609 struct remote_state *rs = get_remote_state ();
14610 char *p;
d5551862 14611
00bf0b85
SS
14612 /* Ask for a first packet of tracepoint definition. */
14613 putpkt ("qTfP");
8d64371b
TT
14614 getpkt (&rs->buf, 0);
14615 p = rs->buf.data ();
00bf0b85 14616 while (*p && *p != 'l')
d5551862 14617 {
00bf0b85
SS
14618 parse_tracepoint_definition (p, utpp);
14619 /* Ask for another packet of tracepoint definition. */
14620 putpkt ("qTsP");
8d64371b
TT
14621 getpkt (&rs->buf, 0);
14622 p = rs->buf.data ();
d5551862 14623 }
00bf0b85 14624 return 0;
d5551862
SS
14625}
14626
f6ac5f3d
PA
14627int
14628remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
d5551862 14629{
00bf0b85 14630 struct remote_state *rs = get_remote_state ();
d5551862 14631 char *p;
d5551862 14632
00bf0b85
SS
14633 /* Ask for a first packet of variable definition. */
14634 putpkt ("qTfV");
8d64371b
TT
14635 getpkt (&rs->buf, 0);
14636 p = rs->buf.data ();
00bf0b85 14637 while (*p && *p != 'l')
d5551862 14638 {
00bf0b85
SS
14639 parse_tsv_definition (p, utsvp);
14640 /* Ask for another packet of variable definition. */
14641 putpkt ("qTsV");
8d64371b
TT
14642 getpkt (&rs->buf, 0);
14643 p = rs->buf.data ();
d5551862 14644 }
00bf0b85 14645 return 0;
d5551862
SS
14646}
14647
c1e36e3e
PA
14648/* The "set/show range-stepping" show hook. */
14649
14650static void
14651show_range_stepping (struct ui_file *file, int from_tty,
14652 struct cmd_list_element *c,
14653 const char *value)
14654{
6cb06a8c
TT
14655 gdb_printf (file,
14656 _("Debugger's willingness to use range stepping "
14657 "is %s.\n"), value);
c1e36e3e
PA
14658}
14659
6b8edb51
PA
14660/* Return true if the vCont;r action is supported by the remote
14661 stub. */
14662
14663bool
14664remote_target::vcont_r_supported ()
14665{
14666 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14667 remote_vcont_probe ();
14668
14669 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14670 && get_remote_state ()->supports_vCont.r);
14671}
14672
c1e36e3e
PA
14673/* The "set/show range-stepping" set hook. */
14674
14675static void
eb4c3f4a 14676set_range_stepping (const char *ignore_args, int from_tty,
c1e36e3e
PA
14677 struct cmd_list_element *c)
14678{
6b8edb51
PA
14679 /* When enabling, check whether range stepping is actually supported
14680 by the target, and warn if not. */
c1e36e3e
PA
14681 if (use_range_stepping)
14682 {
6b8edb51
PA
14683 remote_target *remote = get_current_remote_target ();
14684 if (remote == NULL
14685 || !remote->vcont_r_supported ())
14686 warning (_("Range stepping is not supported by the current target"));
c1e36e3e
PA
14687 }
14688}
14689
baf2b57f
SM
14690static void
14691show_remote_debug (struct ui_file *file, int from_tty,
14692 struct cmd_list_element *c, const char *value)
14693{
6cb06a8c
TT
14694 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
14695 value);
baf2b57f
SM
14696}
14697
14698static void
14699show_remote_timeout (struct ui_file *file, int from_tty,
14700 struct cmd_list_element *c, const char *value)
14701{
6cb06a8c
TT
14702 gdb_printf (file,
14703 _("Timeout limit to wait for target to respond is %s.\n"),
14704 value);
baf2b57f
SM
14705}
14706
dbe692af
LM
14707/* Implement the "supports_memory_tagging" target_ops method. */
14708
14709bool
14710remote_target::supports_memory_tagging ()
14711{
2c2e7f87
LM
14712 return remote_memory_tagging_p ();
14713}
14714
14715/* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
14716
14717static void
14718create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14719 size_t len, int type)
14720{
14721 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14722
14723 std::string request = string_printf ("qMemTags:%s,%s:%s",
14724 phex_nz (address, addr_size),
14725 phex_nz (len, sizeof (len)),
14726 phex_nz (type, sizeof (type)));
14727
14728 strcpy (packet.data (), request.c_str ());
14729}
14730
14731/* Parse the qMemTags packet reply into TAGS.
14732
14733 Return true if successful, false otherwise. */
14734
14735static bool
14736parse_fetch_memtags_reply (const gdb::char_vector &reply,
14737 gdb::byte_vector &tags)
14738{
14739 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
14740 return false;
14741
14742 /* Copy the tag data. */
14743 tags = hex2bin (reply.data () + 1);
14744
14745 return true;
14746}
14747
14748/* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
14749
14750static void
14751create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14752 size_t len, int type,
14753 const gdb::byte_vector &tags)
14754{
14755 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14756
14757 /* Put together the main packet, address and length. */
14758 std::string request = string_printf ("QMemTags:%s,%s:%s:",
14759 phex_nz (address, addr_size),
14760 phex_nz (len, sizeof (len)),
14761 phex_nz (type, sizeof (type)));
14762 request += bin2hex (tags.data (), tags.size ());
14763
14764 /* Check if we have exceeded the maximum packet size. */
14765 if (packet.size () < request.length ())
14766 error (_("Contents too big for packet QMemTags."));
14767
14768 strcpy (packet.data (), request.c_str ());
dbe692af
LM
14769}
14770
14771/* Implement the "fetch_memtags" target_ops method. */
14772
14773bool
14774remote_target::fetch_memtags (CORE_ADDR address, size_t len,
14775 gdb::byte_vector &tags, int type)
14776{
2c2e7f87
LM
14777 /* Make sure the qMemTags packet is supported. */
14778 if (!remote_memory_tagging_p ())
14779 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
14780
14781 struct remote_state *rs = get_remote_state ();
14782
14783 create_fetch_memtags_request (rs->buf, address, len, type);
14784
14785 putpkt (rs->buf);
14786 getpkt (&rs->buf, 0);
14787
14788 return parse_fetch_memtags_reply (rs->buf, tags);
dbe692af
LM
14789}
14790
14791/* Implement the "store_memtags" target_ops method. */
14792
14793bool
14794remote_target::store_memtags (CORE_ADDR address, size_t len,
14795 const gdb::byte_vector &tags, int type)
14796{
2c2e7f87
LM
14797 /* Make sure the QMemTags packet is supported. */
14798 if (!remote_memory_tagging_p ())
14799 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
14800
14801 struct remote_state *rs = get_remote_state ();
14802
14803 create_store_memtags_request (rs->buf, address, len, type, tags);
14804
14805 putpkt (rs->buf);
14806 getpkt (&rs->buf, 0);
14807
14808 /* Verify if the request was successful. */
14809 return packet_check_result (rs->buf.data ()) == PACKET_OK;
dbe692af
LM
14810}
14811
c39ebbf4
TV
14812/* Return true if remote target T is non-stop. */
14813
14814bool
14815remote_target_is_non_stop_p (remote_target *t)
14816{
14817 scoped_restore_current_thread restore_thread;
14818 switch_to_target_no_thread (t);
14819
14820 return target_is_non_stop_p ();
14821}
14822
754487e2
LM
14823#if GDB_SELF_TEST
14824
14825namespace selftests {
14826
14827static void
14828test_memory_tagging_functions ()
14829{
14830 remote_target remote;
14831
14832 struct packet_config *config
14833 = &remote_protocol_packets[PACKET_memory_tagging_feature];
14834
14835 scoped_restore restore_memtag_support_
14836 = make_scoped_restore (&config->support);
14837
14838 /* Test memory tagging packet support. */
14839 config->support = PACKET_SUPPORT_UNKNOWN;
14840 SELF_CHECK (remote.supports_memory_tagging () == false);
14841 config->support = PACKET_DISABLE;
14842 SELF_CHECK (remote.supports_memory_tagging () == false);
14843 config->support = PACKET_ENABLE;
14844 SELF_CHECK (remote.supports_memory_tagging () == true);
14845
14846 /* Setup testing. */
14847 gdb::char_vector packet;
14848 gdb::byte_vector tags, bv;
14849 std::string expected, reply;
14850 packet.resize (32000);
14851
14852 /* Test creating a qMemTags request. */
14853
14854 expected = "qMemTags:0,0:0";
14855 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
14856 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14857
14858 expected = "qMemTags:deadbeef,10:1";
14859 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
14860 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14861
14862 /* Test parsing a qMemTags reply. */
14863
14864 /* Error reply, tags vector unmodified. */
14865 reply = "E00";
14866 strcpy (packet.data (), reply.c_str ());
14867 tags.resize (0);
14868 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
14869 SELF_CHECK (tags.size () == 0);
14870
14871 /* Valid reply, tags vector updated. */
14872 tags.resize (0);
14873 bv.resize (0);
14874
14875 for (int i = 0; i < 5; i++)
14876 bv.push_back (i);
14877
14878 reply = "m" + bin2hex (bv.data (), bv.size ());
14879 strcpy (packet.data (), reply.c_str ());
14880
14881 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
14882 SELF_CHECK (tags.size () == 5);
14883
14884 for (int i = 0; i < 5; i++)
14885 SELF_CHECK (tags[i] == i);
14886
14887 /* Test creating a QMemTags request. */
14888
14889 /* Empty tag data. */
14890 tags.resize (0);
14891 expected = "QMemTags:0,0:0:";
14892 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
14893 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14894 expected.length ()) == 0);
14895
14896 /* Non-empty tag data. */
14897 tags.resize (0);
14898 for (int i = 0; i < 5; i++)
14899 tags.push_back (i);
14900 expected = "QMemTags:deadbeef,ff:1:0001020304";
14901 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
14902 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14903 expected.length ()) == 0);
14904}
14905
14906} // namespace selftests
14907#endif /* GDB_SELF_TEST */
14908
6c265988 14909void _initialize_remote ();
c906108c 14910void
6c265988 14911_initialize_remote ()
c906108c 14912{
0f71a2f6 14913 /* architecture specific data */
29709017
DJ
14914 remote_g_packet_data_handle =
14915 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 14916
d9f719f1
PA
14917 add_target (remote_target_info, remote_target::open);
14918 add_target (extended_remote_target_info, extended_remote_target::open);
cce74817 14919
dc8acb97 14920 /* Hook into new objfile notification. */
c90e7d63 14921 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
dc8acb97 14922
c906108c
SS
14923#if 0
14924 init_remote_threadtests ();
14925#endif
14926
23860348 14927 /* set/show remote ... */
d471ea57 14928
0743fc83 14929 add_basic_prefix_cmd ("remote", class_maintenance, _("\
590042fc 14930Remote protocol specific variables.\n\
5a2468f5 14931Configure various remote-protocol specific variables such as\n\
590042fc 14932the packets being used."),
2f822da5 14933 &remote_set_cmdlist,
0743fc83 14934 0 /* allow-unknown */, &setlist);
1bedd215 14935 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
590042fc 14936Remote protocol specific variables.\n\
5a2468f5 14937Configure various remote-protocol specific variables such as\n\
590042fc 14938the packets being used."),
2f822da5 14939 &remote_show_cmdlist,
23860348 14940 0 /* allow-unknown */, &showlist);
5a2468f5 14941
1a966eab
AC
14942 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14943Compare section data on target to the exec file.\n\
95cf3b38
DT
14944Argument is a single section name (default: all loaded sections).\n\
14945To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
14946 &cmdlist);
14947
e5b176f2 14948 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
1a966eab 14949Send an arbitrary packet to a remote target.\n\
c906108c
SS
14950 maintenance packet TEXT\n\
14951If GDB is talking to an inferior via the GDB serial protocol, then\n\
14952this command sends the string TEXT to the inferior, and displays the\n\
14953response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 14954terminating `#' character and checksum."),
c906108c
SS
14955 &maintenancelist);
14956
9f260536
SM
14957 set_show_commands remotebreak_cmds
14958 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
7915a72c
AC
14959Set whether to send break if interrupted."), _("\
14960Show whether to send break if interrupted."), _("\
14961If set, a break, instead of a cntrl-c, is sent to the remote target."),
9f260536
SM
14962 set_remotebreak, show_remotebreak,
14963 &setlist, &showlist);
14964 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
14965 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
9a7071a8
JB
14966
14967 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
14968 interrupt_sequence_modes, &interrupt_sequence_mode,
14969 _("\
9a7071a8
JB
14970Set interrupt sequence to remote target."), _("\
14971Show interrupt sequence to remote target."), _("\
14972Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14973 NULL, show_interrupt_sequence,
14974 &remote_set_cmdlist,
14975 &remote_show_cmdlist);
14976
14977 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14978 &interrupt_on_connect, _("\
590042fc
PW
14979Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
14980Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
9a7071a8
JB
14981If set, interrupt sequence is sent to remote target."),
14982 NULL, NULL,
14983 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 14984
23860348 14985 /* Install commands for configuring memory read/write packets. */
11cf8741 14986
1a966eab
AC
14987 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14988Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 14989 &setlist);
1a966eab
AC
14990 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14991Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
14992 &showlist);
14993 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
14994 set_memory_write_packet_size, _("\
14995Set the maximum number of bytes per memory-write packet.\n\
14996Specify the number of bytes in a packet or 0 (zero) for the\n\
14997default packet size. The actual limit is further reduced\n\
14998dependent on the target. Specify ``fixed'' to disable the\n\
14999further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
15000 &remote_set_cmdlist);
15001 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
15002 set_memory_read_packet_size, _("\
15003Set the maximum number of bytes per memory-read packet.\n\
15004Specify the number of bytes in a packet or 0 (zero) for the\n\
15005default packet size. The actual limit is further reduced\n\
15006dependent on the target. Specify ``fixed'' to disable the\n\
15007further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
15008 &remote_set_cmdlist);
15009 add_cmd ("memory-write-packet-size", no_class,
15010 show_memory_write_packet_size,
1a966eab 15011 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
15012 &remote_show_cmdlist);
15013 add_cmd ("memory-read-packet-size", no_class,
15014 show_memory_read_packet_size,
1a966eab 15015 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 15016 &remote_show_cmdlist);
c906108c 15017
055303e2 15018 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
15019 &remote_hw_watchpoint_limit, _("\
15020Set the maximum number of target hardware watchpoints."), _("\
15021Show the maximum number of target hardware watchpoints."), _("\
055303e2
AB
15022Specify \"unlimited\" for unlimited hardware watchpoints."),
15023 NULL, show_hardware_watchpoint_limit,
15024 &remote_set_cmdlist,
15025 &remote_show_cmdlist);
15026 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15027 no_class,
480a3f21
PW
15028 &remote_hw_watchpoint_length_limit, _("\
15029Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15030Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
055303e2
AB
15031Specify \"unlimited\" to allow watchpoints of unlimited size."),
15032 NULL, show_hardware_watchpoint_length_limit,
480a3f21 15033 &remote_set_cmdlist, &remote_show_cmdlist);
055303e2 15034 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
15035 &remote_hw_breakpoint_limit, _("\
15036Set the maximum number of target hardware breakpoints."), _("\
15037Show the maximum number of target hardware breakpoints."), _("\
055303e2
AB
15038Specify \"unlimited\" for unlimited hardware breakpoints."),
15039 NULL, show_hardware_breakpoint_limit,
b3f42336 15040 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 15041
1b493192
PA
15042 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15043 &remote_address_size, _("\
4d28ad1e
AC
15044Set the maximum size of the address (in bits) in a memory packet."), _("\
15045Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
15046 NULL,
15047 NULL, /* FIXME: i18n: */
15048 &setlist, &showlist);
c906108c 15049
ca4f7f8b
PA
15050 init_all_packet_configs ();
15051
444abaca 15052 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 15053 "X", "binary-download", 1);
0f71a2f6 15054
444abaca 15055 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 15056 "vCont", "verbose-resume", 0);
506fb367 15057
89be2091
DJ
15058 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
15059 "QPassSignals", "pass-signals", 0);
15060
82075af2
JS
15061 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
15062 "QCatchSyscalls", "catch-syscalls", 0);
15063
9b224c5e
PA
15064 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
15065 "QProgramSignals", "program-signals", 0);
15066
bc3b087d
SDJ
15067 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
15068 "QSetWorkingDir", "set-working-dir", 0);
15069
aefd8b33
SDJ
15070 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
15071 "QStartupWithShell", "startup-with-shell", 0);
15072
0a2dde4a
SDJ
15073 add_packet_config_cmd (&remote_protocol_packets
15074 [PACKET_QEnvironmentHexEncoded],
15075 "QEnvironmentHexEncoded", "environment-hex-encoded",
15076 0);
15077
15078 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
15079 "QEnvironmentReset", "environment-reset",
15080 0);
15081
15082 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
15083 "QEnvironmentUnset", "environment-unset",
15084 0);
15085
444abaca 15086 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 15087 "qSymbol", "symbol-lookup", 0);
dc8acb97 15088
444abaca 15089 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 15090 "P", "set-register", 1);
d471ea57 15091
444abaca 15092 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 15093 "p", "fetch-register", 1);
b96ec7ac 15094
444abaca 15095 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 15096 "Z0", "software-breakpoint", 0);
d471ea57 15097
444abaca 15098 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 15099 "Z1", "hardware-breakpoint", 0);
d471ea57 15100
444abaca 15101 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 15102 "Z2", "write-watchpoint", 0);
d471ea57 15103
444abaca 15104 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 15105 "Z3", "read-watchpoint", 0);
d471ea57 15106
444abaca 15107 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 15108 "Z4", "access-watchpoint", 0);
d471ea57 15109
0876f84a
DJ
15110 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
15111 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 15112
c78fa86a
GB
15113 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
15114 "qXfer:exec-file:read", "pid-to-exec-file", 0);
15115
23181151
DJ
15116 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
15117 "qXfer:features:read", "target-features", 0);
15118
cfa9d6d9
DJ
15119 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
15120 "qXfer:libraries:read", "library-info", 0);
15121
2268b414
JK
15122 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
15123 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15124
fd79ecee
DJ
15125 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
15126 "qXfer:memory-map:read", "memory-map", 0);
15127
07e059b5 15128 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
dda83cd7 15129 "qXfer:osdata:read", "osdata", 0);
07e059b5 15130
dc146f7c
VP
15131 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
15132 "qXfer:threads:read", "threads", 0);
15133
4aa995e1 15134 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
dda83cd7 15135 "qXfer:siginfo:read", "read-siginfo-object", 0);
4aa995e1
PA
15136
15137 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
dda83cd7 15138 "qXfer:siginfo:write", "write-siginfo-object", 0);
4aa995e1 15139
b3b9301e
PA
15140 add_packet_config_cmd
15141 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 15142 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 15143
169081d0
TG
15144 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
15145 "qXfer:uib:read", "unwind-info-block", 0);
15146
444abaca 15147 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 15148 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
15149 0);
15150
711e434b
PM
15151 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
15152 "qGetTIBAddr", "get-thread-information-block-address",
15153 0);
15154
40ab02ce
MS
15155 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
15156 "bc", "reverse-continue", 0);
15157
15158 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
15159 "bs", "reverse-step", 0);
15160
be2a5f71
DJ
15161 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
15162 "qSupported", "supported-packets", 0);
15163
08388c79
DE
15164 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
15165 "qSearch:memory", "search-memory", 0);
15166
bd3eecc3
PA
15167 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
15168 "qTStatus", "trace-status", 0);
15169
15a201c8
GB
15170 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
15171 "vFile:setfs", "hostio-setfs", 0);
15172
a6b151f1
DJ
15173 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
15174 "vFile:open", "hostio-open", 0);
15175
15176 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
15177 "vFile:pread", "hostio-pread", 0);
15178
15179 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
15180 "vFile:pwrite", "hostio-pwrite", 0);
15181
15182 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
15183 "vFile:close", "hostio-close", 0);
15184
15185 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
15186 "vFile:unlink", "hostio-unlink", 0);
15187
b9e7b9c3
UW
15188 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
15189 "vFile:readlink", "hostio-readlink", 0);
15190
0a93529c
GB
15191 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
15192 "vFile:fstat", "hostio-fstat", 0);
15193
2d717e4f
DJ
15194 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
15195 "vAttach", "attach", 0);
15196
15197 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
15198 "vRun", "run", 0);
15199
a6f3e723
SL
15200 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
15201 "QStartNoAckMode", "noack", 0);
15202
82f73884
PA
15203 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
15204 "vKill", "kill", 0);
15205
0b16c5cf
PA
15206 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
15207 "qAttached", "query-attached", 0);
15208
782b2b07 15209 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
15210 "ConditionalTracepoints",
15211 "conditional-tracepoints", 0);
3788aec7
LM
15212
15213 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
15214 "ConditionalBreakpoints",
15215 "conditional-breakpoints", 0);
15216
d3ce09f5
SS
15217 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
15218 "BreakpointCommands",
15219 "breakpoint-commands", 0);
15220
7a697b8d
SS
15221 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
15222 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 15223
409873ef
SS
15224 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
15225 "TracepointSource", "TracepointSource", 0);
15226
d914c394
SS
15227 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
15228 "QAllow", "allow", 0);
15229
0fb4aa4b
PA
15230 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
15231 "StaticTracepoints", "static-tracepoints", 0);
15232
1e4d1764
YQ
15233 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
15234 "InstallInTrace", "install-in-trace", 0);
15235
0fb4aa4b 15236 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
dda83cd7 15237 "qXfer:statictrace:read", "read-sdata-object", 0);
0fb4aa4b 15238
78d85199
YQ
15239 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
15240 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
15241
03583c20
UW
15242 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
15243 "QDisableRandomization", "disable-randomization", 0);
15244
d1feda86
YQ
15245 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
15246 "QAgent", "agent", 0);
15247
f6f899bf
HAQ
15248 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
15249 "QTBuffer:size", "trace-buffer-size", 0);
15250
9accd112
MM
15251 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
15252 "Qbtrace:off", "disable-btrace", 0);
15253
15254 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
15255 "Qbtrace:bts", "enable-btrace-bts", 0);
15256
15257 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
15258 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
15259
15260 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
15261 "qXfer:btrace", "read-btrace", 0);
15262
f4abbc16
MM
15263 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
15264 "qXfer:btrace-conf", "read-btrace-conf", 0);
15265
d33501a5
MM
15266 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
15267 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
15268
73b8c1fd
PA
15269 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
15270 "multiprocess-feature", "multiprocess-feature", 0);
15271
f7e6eed5 15272 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
dda83cd7 15273 "swbreak-feature", "swbreak-feature", 0);
f7e6eed5
PA
15274
15275 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
dda83cd7 15276 "hwbreak-feature", "hwbreak-feature", 0);
f7e6eed5 15277
89245bc0
DB
15278 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
15279 "fork-event-feature", "fork-event-feature", 0);
15280
15281 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
15282 "vfork-event-feature", "vfork-event-feature", 0);
15283
b20a6524
MM
15284 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
15285 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
15286
750ce8d1
YQ
15287 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
15288 "vContSupported", "verbose-resume-supported", 0);
15289
94585166
DB
15290 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
15291 "exec-event-feature", "exec-event-feature", 0);
15292
de979965
PA
15293 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
15294 "vCtrlC", "ctrl-c", 0);
15295
65706a29
PA
15296 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
15297 "QThreadEvents", "thread-events", 0);
15298
f2faf941
PA
15299 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
15300 "N stop reply", "no-resumed-stop-reply", 0);
15301
2c2e7f87
LM
15302 add_packet_config_cmd (&remote_protocol_packets[PACKET_memory_tagging_feature],
15303 "memory-tagging-feature", "memory-tagging-feature", 0);
15304
0b736949
DB
15305 /* Assert that we've registered "set remote foo-packet" commands
15306 for all packet configs. */
ca4f7f8b
PA
15307 {
15308 int i;
15309
15310 for (i = 0; i < PACKET_MAX; i++)
15311 {
15312 /* Ideally all configs would have a command associated. Some
15313 still don't though. */
15314 int excepted;
15315
15316 switch (i)
15317 {
15318 case PACKET_QNonStop:
ca4f7f8b
PA
15319 case PACKET_EnableDisableTracepoints_feature:
15320 case PACKET_tracenz_feature:
15321 case PACKET_DisconnectedTracing_feature:
15322 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
15323 case PACKET_qCRC:
15324 /* Additions to this list need to be well justified:
15325 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
15326 excepted = 1;
15327 break;
15328 default:
15329 excepted = 0;
15330 break;
15331 }
15332
15333 /* This catches both forgetting to add a config command, and
15334 forgetting to remove a packet from the exception list. */
15335 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
15336 }
15337 }
15338
37a105a1
DJ
15339 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15340 Z sub-packet has its own set and show commands, but users may
15341 have sets to this variable in their .gdbinit files (or in their
15342 documentation). */
e9e68a56 15343 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c 15344 &remote_Z_packet_detect, _("\
590042fc
PW
15345Set use of remote protocol `Z' packets."), _("\
15346Show use of remote protocol `Z' packets."), _("\
3b64bf98 15347When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 15348packets."),
e9e68a56 15349 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
15350 show_remote_protocol_Z_packet_cmd,
15351 /* FIXME: i18n: Use of remote protocol
15352 `Z' packets is %s. */
e9e68a56 15353 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 15354
0743fc83 15355 add_basic_prefix_cmd ("remote", class_files, _("\
590042fc 15356Manipulate files on the remote system.\n\
a6b151f1 15357Transfer files to and from the remote target system."),
2f822da5 15358 &remote_cmdlist,
0743fc83 15359 0 /* allow-unknown */, &cmdlist);
a6b151f1
DJ
15360
15361 add_cmd ("put", class_files, remote_put_command,
15362 _("Copy a local file to the remote system."),
15363 &remote_cmdlist);
15364
15365 add_cmd ("get", class_files, remote_get_command,
15366 _("Copy a remote file to the local system."),
15367 &remote_cmdlist);
15368
15369 add_cmd ("delete", class_files, remote_delete_command,
15370 _("Delete a remote file."),
15371 &remote_cmdlist);
15372
2d717e4f 15373 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 15374 &remote_exec_file_var, _("\
590042fc
PW
15375Set the remote pathname for \"run\"."), _("\
15376Show the remote pathname for \"run\"."), NULL,
94585166
DB
15377 set_remote_exec_file,
15378 show_remote_exec_file,
15379 &remote_set_cmdlist,
15380 &remote_show_cmdlist);
2d717e4f 15381
c1e36e3e
PA
15382 add_setshow_boolean_cmd ("range-stepping", class_run,
15383 &use_range_stepping, _("\
15384Enable or disable range stepping."), _("\
15385Show whether target-assisted range stepping is enabled."), _("\
15386If on, and the target supports it, when stepping a source line, GDB\n\
15387tells the target to step the corresponding range of addresses itself instead\n\
15388of issuing multiple single-steps. This speeds up source level\n\
15389stepping. If off, GDB always issues single-steps, even if range\n\
15390stepping is supported by the target. The default is on."),
15391 set_range_stepping,
15392 show_range_stepping,
15393 &setlist,
15394 &showlist);
15395
ed2b7c17
TT
15396 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15397Set watchdog timer."), _("\
15398Show watchdog timer."), _("\
15399When non-zero, this timeout is used instead of waiting forever for a target\n\
15400to finish a low-level step or continue operation. If the specified amount\n\
15401of time passes without a response from the target, an error occurs."),
15402 NULL,
15403 show_watchdog,
15404 &setlist, &showlist);
15405
6cc8564b
LM
15406 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15407 &remote_packet_max_chars, _("\
15408Set the maximum number of characters to display for each remote packet."), _("\
15409Show the maximum number of characters to display for each remote packet."), _("\
15410Specify \"unlimited\" to display all the characters."),
15411 NULL, show_remote_packet_max_chars,
15412 &setdebuglist, &showdebuglist);
15413
02349803
SM
15414 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15415 _("Set debugging of remote protocol."),
15416 _("Show debugging of remote protocol."),
15417 _("\
baf2b57f
SM
15418When enabled, each packet sent or received with the remote target\n\
15419is displayed."),
02349803
SM
15420 NULL,
15421 show_remote_debug,
15422 &setdebuglist, &showdebuglist);
baf2b57f
SM
15423
15424 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15425 &remote_timeout, _("\
15426Set timeout limit to wait for target to respond."), _("\
15427Show timeout limit to wait for target to respond."), _("\
15428This value is used to set the time limit for gdb to wait for a response\n\
15429from the target."),
15430 NULL,
15431 show_remote_timeout,
15432 &setlist, &showlist);
15433
449092f6 15434 /* Eventually initialize fileio. See fileio.c */
3f4d92eb 15435 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
754487e2
LM
15436
15437#if GDB_SELF_TEST
15438 selftests::register_test ("remote_memory_tagging",
15439 selftests::test_memory_tagging_functions);
15440#endif
c906108c 15441}