gdb: remove target_ops::commit_resume implementation in record-{btrace, full}.c
[deliverable/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
3666a048 3 Copyright (C) 1988-2021 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"
35b1e5cc 82
f6ac5f3d
PA
83/* The remote target. */
84
d9f719f1
PA
85static const char remote_doc[] = N_("\
86Use a remote computer via a serial line, using a gdb-specific protocol.\n\
87Specify the serial device it is connected to\n\
88(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
89
6b8edb51
PA
90#define OPAQUETHREADBYTES 8
91
92/* a 64 bit opaque identifier */
93typedef unsigned char threadref[OPAQUETHREADBYTES];
94
95struct gdb_ext_thread_info;
96struct threads_listing_context;
97typedef int (*rmt_thread_action) (threadref *ref, void *context);
98struct protocol_feature;
99struct packet_reg;
100
101struct stop_reply;
32603266 102typedef std::unique_ptr<stop_reply> stop_reply_up;
6b8edb51
PA
103
104/* Generic configuration support for packets the stub optionally
105 supports. Allows the user to specify the use of the packet as well
106 as allowing GDB to auto-detect support in the remote stub. */
107
108enum packet_support
109 {
110 PACKET_SUPPORT_UNKNOWN = 0,
111 PACKET_ENABLE,
112 PACKET_DISABLE
113 };
114
115/* Analyze a packet's return value and update the packet config
116 accordingly. */
117
118enum packet_result
119{
120 PACKET_ERROR,
121 PACKET_OK,
122 PACKET_UNKNOWN
123};
124
125struct threads_listing_context;
3c69da40
PA
126
127/* Stub vCont actions support.
128
129 Each field is a boolean flag indicating whether the stub reports
130 support for the corresponding action. */
131
132struct vCont_action_support
133{
134 /* vCont;t */
135 bool t = false;
136
137 /* vCont;r */
138 bool r = false;
139
140 /* vCont;s */
141 bool s = false;
142
143 /* vCont;S */
144 bool S = false;
145};
146
405feb71 147/* About this many threadids fit in a packet. */
3c69da40
PA
148
149#define MAXTHREADLISTRESULTS 32
150
151/* Data for the vFile:pread readahead cache. */
152
153struct readahead_cache
154{
155 /* Invalidate the readahead cache. */
156 void invalidate ();
157
158 /* Invalidate the readahead cache if it is holding data for FD. */
159 void invalidate_fd (int fd);
160
161 /* Serve pread from the readahead cache. Returns number of bytes
162 read, or 0 if the request can't be served from the cache. */
163 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
164
165 /* The file descriptor for the file that is being cached. -1 if the
166 cache is invalid. */
167 int fd = -1;
168
169 /* The offset into the file that the cache buffer corresponds
170 to. */
171 ULONGEST offset = 0;
172
173 /* The buffer holding the cache contents. */
174 gdb_byte *buf = nullptr;
175 /* The buffer's size. We try to read as much as fits into a packet
176 at a time. */
177 size_t bufsize = 0;
178
179 /* Cache hit and miss counters. */
180 ULONGEST hit_count = 0;
181 ULONGEST miss_count = 0;
182};
183
184/* Description of the remote protocol for a given architecture. */
185
186struct packet_reg
187{
188 long offset; /* Offset into G packet. */
189 long regnum; /* GDB's internal register number. */
190 LONGEST pnum; /* Remote protocol register number. */
191 int in_g_packet; /* Always part of G packet. */
192 /* long size in bytes; == register_size (target_gdbarch (), regnum);
193 at present. */
194 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
195 at present. */
196};
197
198struct remote_arch_state
199{
200 explicit remote_arch_state (struct gdbarch *gdbarch);
201
202 /* Description of the remote protocol registers. */
203 long sizeof_g_packet;
204
205 /* Description of the remote protocol registers indexed by REGNUM
206 (making an array gdbarch_num_regs in size). */
207 std::unique_ptr<packet_reg[]> regs;
208
209 /* This is the size (in chars) of the first response to the ``g''
210 packet. It is used as a heuristic when determining the maximum
211 size of memory-read and memory-write packets. A target will
212 typically only reserve a buffer large enough to hold the ``g''
213 packet. The size does not include packet overhead (headers and
214 trailers). */
215 long actual_register_packet_size;
216
217 /* This is the maximum size (in chars) of a non read/write packet.
218 It is also used as a cap on the size of read/write packets. */
219 long remote_packet_size;
220};
221
222/* Description of the remote protocol state for the currently
223 connected target. This is per-target state, and independent of the
224 selected architecture. */
225
226class remote_state
227{
228public:
229
230 remote_state ();
231 ~remote_state ();
232
233 /* Get the remote arch state for GDBARCH. */
234 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
235
236public: /* data */
237
238 /* A buffer to use for incoming packets, and its current size. The
239 buffer is grown dynamically for larger incoming packets.
240 Outgoing packets may also be constructed in this buffer.
8d64371b 241 The size of the buffer is always at least REMOTE_PACKET_SIZE;
3c69da40
PA
242 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
243 packets. */
8d64371b 244 gdb::char_vector buf;
3c69da40
PA
245
246 /* True if we're going through initial connection setup (finding out
247 about the remote side's threads, relocating symbols, etc.). */
248 bool starting_up = false;
249
250 /* If we negotiated packet size explicitly (and thus can bypass
251 heuristics for the largest packet size that will not overflow
252 a buffer in the stub), this will be set to that packet size.
253 Otherwise zero, meaning to use the guessed size. */
254 long explicit_packet_size = 0;
255
256 /* remote_wait is normally called when the target is running and
257 waits for a stop reply packet. But sometimes we need to call it
258 when the target is already stopped. We can send a "?" packet
259 and have remote_wait read the response. Or, if we already have
260 the response, we can stash it in BUF and tell remote_wait to
261 skip calling getpkt. This flag is set when BUF contains a
262 stop reply packet and the target is not waiting. */
263 int cached_wait_status = 0;
264
265 /* True, if in no ack mode. That is, neither GDB nor the stub will
266 expect acks from each other. The connection is assumed to be
267 reliable. */
268 bool noack_mode = false;
269
270 /* True if we're connected in extended remote mode. */
271 bool extended = false;
272
273 /* True if we resumed the target and we're waiting for the target to
274 stop. In the mean time, we can't start another command/query.
275 The remote server wouldn't be ready to process it, so we'd
276 timeout waiting for a reply that would never come and eventually
277 we'd close the connection. This can happen in asynchronous mode
278 because we allow GDB commands while the target is running. */
279 bool waiting_for_stop_reply = false;
280
281 /* The status of the stub support for the various vCont actions. */
282 vCont_action_support supports_vCont;
5b6d1e4f
PA
283 /* Whether vCont support was probed already. This is a workaround
284 until packet_support is per-connection. */
285 bool supports_vCont_probed;
3c69da40
PA
286
287 /* True if the user has pressed Ctrl-C, but the target hasn't
288 responded to that. */
289 bool ctrlc_pending_p = false;
290
291 /* True if we saw a Ctrl-C while reading or writing from/to the
292 remote descriptor. At that point it is not safe to send a remote
293 interrupt packet, so we instead remember we saw the Ctrl-C and
294 process it once we're done with sending/receiving the current
295 packet, which should be shortly. If however that takes too long,
296 and the user presses Ctrl-C again, we offer to disconnect. */
297 bool got_ctrlc_during_io = false;
298
299 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
300 remote_open knows that we don't have a file open when the program
301 starts. */
302 struct serial *remote_desc = nullptr;
303
304 /* These are the threads which we last sent to the remote system. The
305 TID member will be -1 for all or -2 for not sent yet. */
306 ptid_t general_thread = null_ptid;
307 ptid_t continue_thread = null_ptid;
308
309 /* This is the traceframe which we last selected on the remote system.
310 It will be -1 if no traceframe is selected. */
311 int remote_traceframe_number = -1;
312
313 char *last_pass_packet = nullptr;
314
315 /* The last QProgramSignals packet sent to the target. We bypass
316 sending a new program signals list down to the target if the new
317 packet is exactly the same as the last we sent. IOW, we only let
318 the target know about program signals list changes. */
319 char *last_program_signals_packet = nullptr;
320
321 gdb_signal last_sent_signal = GDB_SIGNAL_0;
322
323 bool last_sent_step = false;
324
325 /* The execution direction of the last resume we got. */
326 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
327
328 char *finished_object = nullptr;
329 char *finished_annex = nullptr;
330 ULONGEST finished_offset = 0;
331
332 /* Should we try the 'ThreadInfo' query packet?
333
334 This variable (NOT available to the user: auto-detect only!)
335 determines whether GDB will use the new, simpler "ThreadInfo"
336 query or the older, more complex syntax for thread queries.
337 This is an auto-detect variable (set to true at each connect,
338 and set to false when the target fails to recognize it). */
339 bool use_threadinfo_query = false;
340 bool use_threadextra_query = false;
341
342 threadref echo_nextthread {};
343 threadref nextthread {};
344 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
345
346 /* The state of remote notification. */
347 struct remote_notif_state *notif_state = nullptr;
348
349 /* The branch trace configuration. */
350 struct btrace_config btrace_config {};
351
352 /* The argument to the last "vFile:setfs:" packet we sent, used
353 to avoid sending repeated unnecessary "vFile:setfs:" packets.
354 Initialized to -1 to indicate that no "vFile:setfs:" packet
355 has yet been sent. */
356 int fs_pid = -1;
357
358 /* A readahead cache for vFile:pread. Often, reading a binary
359 involves a sequence of small reads. E.g., when parsing an ELF
360 file. A readahead cache helps mostly the case of remote
361 debugging on a connection with higher latency, due to the
362 request/reply nature of the RSP. We only cache data for a single
363 file descriptor at a time. */
364 struct readahead_cache readahead_cache;
365
366 /* The list of already fetched and acknowledged stop events. This
367 queue is used for notification Stop, and other notifications
368 don't need queue for their events, because the notification
369 events of Stop can't be consumed immediately, so that events
370 should be queued first, and be consumed by remote_wait_{ns,as}
371 one per time. Other notifications can consume their events
372 immediately, so queue is not needed for them. */
953edf2b 373 std::vector<stop_reply_up> stop_reply_queue;
3c69da40
PA
374
375 /* Asynchronous signal handle registered as event loop source for
376 when we have pending events ready to be passed to the core. */
377 struct async_event_handler *remote_async_inferior_event_token = nullptr;
378
379 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
380 ``forever'' still use the normal timeout mechanism. This is
381 currently used by the ASYNC code to guarentee that target reads
382 during the initial connect always time-out. Once getpkt has been
383 modified to return a timeout indication and, in turn
384 remote_wait()/wait_for_inferior() have gained a timeout parameter
385 this can go away. */
386 int wait_forever_enabled_p = 1;
387
388private:
389 /* Mapping of remote protocol data for each gdbarch. Usually there
390 is only one entry here, though we may see more with stubs that
391 support multi-process. */
392 std::unordered_map<struct gdbarch *, remote_arch_state>
393 m_arch_states;
394};
6b8edb51 395
d9f719f1
PA
396static const target_info remote_target_info = {
397 "remote",
398 N_("Remote serial target in gdb-specific protocol"),
399 remote_doc
400};
401
3b3dac9b 402class remote_target : public process_stratum_target
f6ac5f3d
PA
403{
404public:
3b3dac9b 405 remote_target () = default;
6b8edb51 406 ~remote_target () override;
f6ac5f3d 407
d9f719f1
PA
408 const target_info &info () const override
409 { return remote_target_info; }
f6ac5f3d 410
121b3efd
PA
411 const char *connection_string () override;
412
f6ac5f3d
PA
413 thread_control_capabilities get_thread_control_capabilities () override
414 { return tc_schedlock; }
415
d9f719f1
PA
416 /* Open a remote connection. */
417 static void open (const char *, int);
418
f6ac5f3d
PA
419 void close () override;
420
421 void detach (inferior *, int) override;
422 void disconnect (const char *, int) override;
423
424 void commit_resume () override;
425 void resume (ptid_t, int, enum gdb_signal) override;
b60cea74 426 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
f6ac5f3d
PA
427
428 void fetch_registers (struct regcache *, int) override;
429 void store_registers (struct regcache *, int) override;
430 void prepare_to_store (struct regcache *) override;
431
432 void files_info () override;
433
434 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
435
436 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
437 enum remove_bp_reason) override;
438
439
57810aa7
PA
440 bool stopped_by_sw_breakpoint () override;
441 bool supports_stopped_by_sw_breakpoint () override;
f6ac5f3d 442
57810aa7 443 bool stopped_by_hw_breakpoint () override;
f6ac5f3d 444
57810aa7 445 bool supports_stopped_by_hw_breakpoint () override;
f6ac5f3d 446
57810aa7 447 bool stopped_by_watchpoint () override;
f6ac5f3d 448
57810aa7 449 bool stopped_data_address (CORE_ADDR *) override;
f6ac5f3d 450
57810aa7 451 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
f6ac5f3d
PA
452
453 int can_use_hw_breakpoint (enum bptype, int, int) override;
454
455 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
456
457 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
458
459 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
460
461 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
462 struct expression *) override;
463
464 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
465 struct expression *) override;
466
467 void kill () override;
468
469 void load (const char *, int) override;
470
471 void mourn_inferior () override;
472
adc6a863 473 void pass_signals (gdb::array_view<const unsigned char>) override;
f6ac5f3d
PA
474
475 int set_syscall_catchpoint (int, bool, int,
476 gdb::array_view<const int>) override;
477
adc6a863 478 void program_signals (gdb::array_view<const unsigned char>) override;
f6ac5f3d 479
57810aa7 480 bool thread_alive (ptid_t ptid) override;
f6ac5f3d
PA
481
482 const char *thread_name (struct thread_info *) override;
483
484 void update_thread_list () override;
485
a068643d 486 std::string pid_to_str (ptid_t) override;
f6ac5f3d
PA
487
488 const char *extra_thread_info (struct thread_info *) override;
489
490 ptid_t get_ada_task_ptid (long lwp, long thread) override;
491
492 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
493 int handle_len,
494 inferior *inf) override;
495
3d6c6204
KB
496 gdb::byte_vector thread_info_to_thread_handle (struct thread_info *tp)
497 override;
498
f6ac5f3d
PA
499 void stop (ptid_t) override;
500
501 void interrupt () override;
502
503 void pass_ctrlc () override;
504
505 enum target_xfer_status xfer_partial (enum target_object object,
506 const char *annex,
507 gdb_byte *readbuf,
508 const gdb_byte *writebuf,
509 ULONGEST offset, ULONGEST len,
510 ULONGEST *xfered_len) override;
511
512 ULONGEST get_memory_xfer_limit () override;
513
514 void rcmd (const char *command, struct ui_file *output) override;
515
516 char *pid_to_exec_file (int pid) override;
517
518 void log_command (const char *cmd) override
519 {
520 serial_log_command (this, cmd);
521 }
522
523 CORE_ADDR get_thread_local_address (ptid_t ptid,
524 CORE_ADDR load_module_addr,
525 CORE_ADDR offset) override;
526
57810aa7 527 bool can_execute_reverse () override;
f6ac5f3d
PA
528
529 std::vector<mem_region> memory_map () override;
530
531 void flash_erase (ULONGEST address, LONGEST length) override;
532
533 void flash_done () override;
534
535 const struct target_desc *read_description () override;
536
537 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
538 const gdb_byte *pattern, ULONGEST pattern_len,
539 CORE_ADDR *found_addrp) override;
540
57810aa7 541 bool can_async_p () override;
f6ac5f3d 542
57810aa7 543 bool is_async_p () override;
f6ac5f3d
PA
544
545 void async (int) override;
546
5b6d1e4f
PA
547 int async_wait_fd () override;
548
f6ac5f3d
PA
549 void thread_events (int) override;
550
551 int can_do_single_step () override;
552
553 void terminal_inferior () override;
554
555 void terminal_ours () override;
556
57810aa7 557 bool supports_non_stop () override;
f6ac5f3d 558
57810aa7 559 bool supports_multi_process () override;
f6ac5f3d 560
57810aa7 561 bool supports_disable_randomization () override;
f6ac5f3d 562
57810aa7 563 bool filesystem_is_local () override;
f6ac5f3d
PA
564
565
566 int fileio_open (struct inferior *inf, const char *filename,
567 int flags, int mode, int warn_if_slow,
568 int *target_errno) override;
569
570 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
571 ULONGEST offset, int *target_errno) override;
572
573 int fileio_pread (int fd, gdb_byte *read_buf, int len,
574 ULONGEST offset, int *target_errno) override;
575
576 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
577
578 int fileio_close (int fd, int *target_errno) override;
579
580 int fileio_unlink (struct inferior *inf,
581 const char *filename,
582 int *target_errno) override;
583
584 gdb::optional<std::string>
585 fileio_readlink (struct inferior *inf,
586 const char *filename,
587 int *target_errno) override;
588
57810aa7 589 bool supports_enable_disable_tracepoint () override;
f6ac5f3d 590
57810aa7 591 bool supports_string_tracing () override;
f6ac5f3d 592
57810aa7 593 bool supports_evaluation_of_breakpoint_conditions () override;
f6ac5f3d 594
57810aa7 595 bool can_run_breakpoint_commands () override;
f6ac5f3d
PA
596
597 void trace_init () override;
598
599 void download_tracepoint (struct bp_location *location) override;
600
57810aa7 601 bool can_download_tracepoint () override;
f6ac5f3d
PA
602
603 void download_trace_state_variable (const trace_state_variable &tsv) override;
604
605 void enable_tracepoint (struct bp_location *location) override;
606
607 void disable_tracepoint (struct bp_location *location) override;
608
609 void trace_set_readonly_regions () override;
610
611 void trace_start () override;
612
613 int get_trace_status (struct trace_status *ts) override;
614
615 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
616 override;
617
618 void trace_stop () override;
619
620 int trace_find (enum trace_find_type type, int num,
621 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
622
57810aa7 623 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
f6ac5f3d
PA
624
625 int save_trace_data (const char *filename) override;
626
627 int upload_tracepoints (struct uploaded_tp **utpp) override;
628
629 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
630
631 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
632
633 int get_min_fast_tracepoint_insn_len () override;
634
635 void set_disconnected_tracing (int val) override;
636
637 void set_circular_trace_buffer (int val) override;
638
639 void set_trace_buffer_size (LONGEST val) override;
640
57810aa7
PA
641 bool set_trace_notes (const char *user, const char *notes,
642 const char *stopnotes) override;
f6ac5f3d
PA
643
644 int core_of_thread (ptid_t ptid) override;
645
646 int verify_memory (const gdb_byte *data,
647 CORE_ADDR memaddr, ULONGEST size) override;
648
649
57810aa7 650 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
f6ac5f3d
PA
651
652 void set_permissions () override;
653
654 bool static_tracepoint_marker_at (CORE_ADDR,
655 struct static_tracepoint_marker *marker)
656 override;
657
658 std::vector<static_tracepoint_marker>
659 static_tracepoint_markers_by_strid (const char *id) override;
660
661 traceframe_info_up traceframe_info () override;
662
57810aa7
PA
663 bool use_agent (bool use) override;
664 bool can_use_agent () override;
f6ac5f3d
PA
665
666 struct btrace_target_info *enable_btrace (ptid_t ptid,
667 const struct btrace_config *conf) override;
668
669 void disable_btrace (struct btrace_target_info *tinfo) override;
670
671 void teardown_btrace (struct btrace_target_info *tinfo) override;
672
673 enum btrace_error read_btrace (struct btrace_data *data,
674 struct btrace_target_info *btinfo,
675 enum btrace_read_type type) override;
676
677 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
57810aa7 678 bool augmented_libraries_svr4_read () override;
5ab2fbf1 679 bool follow_fork (bool, bool) override;
4ca51187 680 void follow_exec (struct inferior *, const char *) override;
f6ac5f3d
PA
681 int insert_fork_catchpoint (int) override;
682 int remove_fork_catchpoint (int) override;
683 int insert_vfork_catchpoint (int) override;
684 int remove_vfork_catchpoint (int) override;
685 int insert_exec_catchpoint (int) override;
686 int remove_exec_catchpoint (int) override;
687 enum exec_direction_kind execution_direction () override;
688
6b8edb51
PA
689public: /* Remote specific methods. */
690
691 void remote_download_command_source (int num, ULONGEST addr,
692 struct command_line *cmds);
693
694 void remote_file_put (const char *local_file, const char *remote_file,
695 int from_tty);
696 void remote_file_get (const char *remote_file, const char *local_file,
697 int from_tty);
698 void remote_file_delete (const char *remote_file, int from_tty);
699
700 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
701 ULONGEST offset, int *remote_errno);
702 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
703 ULONGEST offset, int *remote_errno);
704 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
705 ULONGEST offset, int *remote_errno);
706
707 int remote_hostio_send_command (int command_bytes, int which_packet,
708 int *remote_errno, char **attachment,
709 int *attachment_len);
710 int remote_hostio_set_filesystem (struct inferior *inf,
711 int *remote_errno);
712 /* We should get rid of this and use fileio_open directly. */
713 int remote_hostio_open (struct inferior *inf, const char *filename,
714 int flags, int mode, int warn_if_slow,
715 int *remote_errno);
716 int remote_hostio_close (int fd, int *remote_errno);
717
718 int remote_hostio_unlink (inferior *inf, const char *filename,
719 int *remote_errno);
720
721 struct remote_state *get_remote_state ();
722
723 long get_remote_packet_size (void);
724 long get_memory_packet_size (struct memory_packet_config *config);
725
726 long get_memory_write_packet_size ();
727 long get_memory_read_packet_size ();
728
729 char *append_pending_thread_resumptions (char *p, char *endp,
730 ptid_t ptid);
d9f719f1 731 static void open_1 (const char *name, int from_tty, int extended_p);
f6ac5f3d 732 void start_remote (int from_tty, int extended_p);
00431a78 733 void remote_detach_1 (struct inferior *inf, int from_tty);
6b8edb51
PA
734
735 char *append_resumption (char *p, char *endp,
736 ptid_t ptid, int step, gdb_signal siggnal);
737 int remote_resume_with_vcont (ptid_t ptid, int step,
738 gdb_signal siggnal);
739
740 void add_current_inferior_and_thread (char *wait_status);
741
742 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
b60cea74 743 target_wait_flags options);
6b8edb51 744 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
b60cea74 745 target_wait_flags options);
6b8edb51
PA
746
747 ptid_t process_stop_reply (struct stop_reply *stop_reply,
748 target_waitstatus *status);
749
750 void remote_notice_new_inferior (ptid_t currthread, int executing);
751
752 void process_initial_stop_replies (int from_tty);
753
00431a78 754 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing);
6b8edb51
PA
755
756 void btrace_sync_conf (const btrace_config *conf);
757
758 void remote_btrace_maybe_reopen ();
759
760 void remove_new_fork_children (threads_listing_context *context);
761 void kill_new_fork_children (int pid);
762 void discard_pending_stop_replies (struct inferior *inf);
763 int stop_reply_queue_length ();
764
765 void check_pending_events_prevent_wildcard_vcont
766 (int *may_global_wildcard_vcont);
767
768 void discard_pending_stop_replies_in_queue ();
769 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
770 struct stop_reply *queued_stop_reply (ptid_t ptid);
771 int peek_stop_reply (ptid_t ptid);
bb277751 772 void remote_parse_stop_reply (const char *buf, stop_reply *event);
6b8edb51
PA
773
774 void remote_stop_ns (ptid_t ptid);
775 void remote_interrupt_as ();
776 void remote_interrupt_ns ();
777
778 char *remote_get_noisy_reply ();
779 int remote_query_attached (int pid);
9ab8741a 780 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
6b8edb51
PA
781 int try_open_exec);
782
783 ptid_t remote_current_thread (ptid_t oldpid);
784 ptid_t get_current_thread (char *wait_status);
785
786 void set_thread (ptid_t ptid, int gen);
787 void set_general_thread (ptid_t ptid);
788 void set_continue_thread (ptid_t ptid);
789 void set_general_process ();
790
791 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
792
793 int remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
794 gdb_ext_thread_info *info);
795 int remote_get_threadinfo (threadref *threadid, int fieldset,
796 gdb_ext_thread_info *info);
797
798 int parse_threadlist_response (char *pkt, int result_limit,
799 threadref *original_echo,
800 threadref *resultlist,
801 int *doneflag);
802 int remote_get_threadlist (int startflag, threadref *nextthread,
803 int result_limit, int *done, int *result_count,
804 threadref *threadlist);
805
806 int remote_threadlist_iterator (rmt_thread_action stepfunction,
807 void *context, int looplimit);
808
809 int remote_get_threads_with_ql (threads_listing_context *context);
810 int remote_get_threads_with_qxfer (threads_listing_context *context);
811 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
812
813 void extended_remote_restart ();
814
815 void get_offsets ();
816
817 void remote_check_symbols ();
818
819 void remote_supported_packet (const struct protocol_feature *feature,
820 enum packet_support support,
821 const char *argument);
822
823 void remote_query_supported ();
824
825 void remote_packet_size (const protocol_feature *feature,
826 packet_support support, const char *value);
827
828 void remote_serial_quit_handler ();
829
830 void remote_detach_pid (int pid);
831
832 void remote_vcont_probe ();
833
834 void remote_resume_with_hc (ptid_t ptid, int step,
835 gdb_signal siggnal);
836
837 void send_interrupt_sequence ();
838 void interrupt_query ();
839
840 void remote_notif_get_pending_events (notif_client *nc);
841
842 int fetch_register_using_p (struct regcache *regcache,
843 packet_reg *reg);
844 int send_g_packet ();
845 void process_g_packet (struct regcache *regcache);
846 void fetch_registers_using_g (struct regcache *regcache);
847 int store_register_using_P (const struct regcache *regcache,
848 packet_reg *reg);
849 void store_registers_using_G (const struct regcache *regcache);
850
851 void set_remote_traceframe ();
852
853 void check_binary_download (CORE_ADDR addr);
854
855 target_xfer_status remote_write_bytes_aux (const char *header,
856 CORE_ADDR memaddr,
857 const gdb_byte *myaddr,
858 ULONGEST len_units,
859 int unit_size,
860 ULONGEST *xfered_len_units,
861 char packet_format,
862 int use_length);
863
864 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
865 const gdb_byte *myaddr, ULONGEST len,
866 int unit_size, ULONGEST *xfered_len);
867
868 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
869 ULONGEST len_units,
870 int unit_size, ULONGEST *xfered_len_units);
871
872 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
873 ULONGEST memaddr,
874 ULONGEST len,
875 int unit_size,
876 ULONGEST *xfered_len);
877
878 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
879 gdb_byte *myaddr, ULONGEST len,
880 int unit_size,
881 ULONGEST *xfered_len);
882
883 packet_result remote_send_printf (const char *format, ...)
884 ATTRIBUTE_PRINTF (2, 3);
885
886 target_xfer_status remote_flash_write (ULONGEST address,
887 ULONGEST length, ULONGEST *xfered_len,
888 const gdb_byte *data);
889
890 int readchar (int timeout);
891
892 void remote_serial_write (const char *str, int len);
893
894 int putpkt (const char *buf);
895 int putpkt_binary (const char *buf, int cnt);
896
8d64371b
TT
897 int putpkt (const gdb::char_vector &buf)
898 {
899 return putpkt (buf.data ());
900 }
901
6b8edb51 902 void skip_frame ();
8d64371b
TT
903 long read_frame (gdb::char_vector *buf_p);
904 void getpkt (gdb::char_vector *buf, int forever);
905 int getpkt_or_notif_sane_1 (gdb::char_vector *buf, int forever,
6b8edb51 906 int expecting_notif, int *is_notif);
8d64371b
TT
907 int getpkt_sane (gdb::char_vector *buf, int forever);
908 int getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
6b8edb51
PA
909 int *is_notif);
910 int remote_vkill (int pid);
911 void remote_kill_k ();
912
913 void extended_remote_disable_randomization (int val);
914 int extended_remote_run (const std::string &args);
915
916 void send_environment_packet (const char *action,
917 const char *packet,
918 const char *value);
919
920 void extended_remote_environment_support ();
3c69da40 921 void extended_remote_set_inferior_cwd ();
80152258 922
3c69da40
PA
923 target_xfer_status remote_write_qxfer (const char *object_name,
924 const char *annex,
925 const gdb_byte *writebuf,
926 ULONGEST offset, LONGEST len,
927 ULONGEST *xfered_len,
928 struct packet_config *packet);
43c3a0e4 929
3c69da40
PA
930 target_xfer_status remote_read_qxfer (const char *object_name,
931 const char *annex,
932 gdb_byte *readbuf, ULONGEST offset,
933 LONGEST len,
934 ULONGEST *xfered_len,
935 struct packet_config *packet);
43c3a0e4 936
3c69da40 937 void push_stop_reply (struct stop_reply *new_event);
43c3a0e4 938
3c69da40 939 bool vcont_r_supported ();
43c3a0e4 940
3c69da40 941 void packet_command (const char *args, int from_tty);
43c3a0e4 942
3c69da40 943private: /* data fields */
43c3a0e4 944
3c69da40
PA
945 /* The remote state. Don't reference this directly. Use the
946 get_remote_state method instead. */
947 remote_state m_remote_state;
43c3a0e4
PA
948};
949
3c69da40
PA
950static const target_info extended_remote_target_info = {
951 "extended-remote",
952 N_("Extended remote serial target in gdb-specific protocol"),
953 remote_doc
954};
ea9c271d 955
3c69da40
PA
956/* Set up the extended remote target by extending the standard remote
957 target and adding to it. */
958
959class extended_remote_target final : public remote_target
ea9c271d 960{
9d6eea31 961public:
3c69da40
PA
962 const target_info &info () const override
963 { return extended_remote_target_info; }
9d6eea31 964
3c69da40
PA
965 /* Open an extended-remote connection. */
966 static void open (const char *, int);
de44f5a7 967
3c69da40
PA
968 bool can_create_inferior () override { return true; }
969 void create_inferior (const char *, const std::string &,
970 char **, int) override;
9d6eea31 971
3c69da40 972 void detach (inferior *, int) override;
9d6eea31 973
3c69da40
PA
974 bool can_attach () override { return true; }
975 void attach (const char *, int) override;
be2a5f71 976
3c69da40
PA
977 void post_attach (int) override;
978 bool supports_disable_randomization () override;
979};
1e51243a 980
3c69da40 981/* Per-program-space data key. */
7b4a314f
TT
982static const struct program_space_key<char, gdb::xfree_deleter<char>>
983 remote_pspace_data;
2d717e4f 984
3c69da40
PA
985/* The variable registered as the control variable used by the
986 remote exec-file commands. While the remote exec-file setting is
987 per-program-space, the set/show machinery uses this as the
988 location of the remote exec-file value. */
989static char *remote_exec_file_var;
a6f3e723 990
3c69da40
PA
991/* The size to align memory write packets, when practical. The protocol
992 does not guarantee any alignment, and gdb will generate short
993 writes and unaligned writes, but even as a best-effort attempt this
994 can improve bulk transfers. For instance, if a write is misaligned
995 relative to the target's data bus, the stub may need to make an extra
996 round trip fetching data from the target. This doesn't make a
997 huge difference, but it's easy to do, so we try to be helpful.
82f73884 998
3c69da40
PA
999 The alignment chosen is arbitrary; usually data bus width is
1000 important here, not the possibly larger cache line size. */
1001enum { REMOTE_ALIGN_WRITES = 16 };
82f73884 1002
3c69da40 1003/* Prototypes for local functions. */
74531fed 1004
3c69da40 1005static int hexnumlen (ULONGEST num);
782b2b07 1006
3c69da40 1007static int stubhex (int ch);
5d93a237 1008
3c69da40 1009static int hexnumstr (char *, ULONGEST);
048094ac 1010
3c69da40 1011static int hexnumnstr (char *, ULONGEST, int);
47f8a51d 1012
3c69da40 1013static CORE_ADDR remote_address_masked (CORE_ADDR);
262e1174 1014
3c69da40 1015static void print_packet (const char *);
747dc59d 1016
3c69da40 1017static int stub_unpack_int (char *buff, int fieldlength);
5e4a05c4 1018
3c69da40 1019struct packet_config;
b73be471 1020
3c69da40 1021static void show_packet_config_cmd (struct packet_config *config);
280ceea3 1022
3c69da40
PA
1023static void show_remote_protocol_packet_cmd (struct ui_file *file,
1024 int from_tty,
1025 struct cmd_list_element *c,
1026 const char *value);
8e88304f 1027
3c69da40 1028static ptid_t read_ptid (const char *buf, const char **obuf);
3a00c802 1029
3c69da40 1030static void remote_async_inferior_event_handler (gdb_client_data);
b80fafe3 1031
eefce37f 1032static bool remote_read_description_p (struct target_ops *target);
88b496c3 1033
05be00a8 1034static void remote_console_output (const char *msg);
5965e028 1035
3c69da40 1036static void remote_btrace_reset (remote_state *rs);
f4abbc16 1037
5b6d1e4f 1038static void remote_unpush_and_throw (remote_target *target);
15a201c8 1039
3c69da40 1040/* For "remote". */
80152258 1041
3c69da40 1042static struct cmd_list_element *remote_cmdlist;
9d6eea31 1043
3c69da40 1044/* For "set remote" and "show remote". */
6b8edb51 1045
3c69da40
PA
1046static struct cmd_list_element *remote_set_cmdlist;
1047static struct cmd_list_element *remote_show_cmdlist;
6b8edb51 1048
3c69da40 1049/* Controls whether GDB is willing to use range stepping. */
6b8edb51 1050
491144b5 1051static bool use_range_stepping = true;
3c69da40 1052
c9d22089
SM
1053/* From the remote target's point of view, each thread is in one of these three
1054 states. */
1055enum class resume_state
1056{
1057 /* Not resumed - we haven't been asked to resume this thread. */
1058 NOT_RESUMED,
1059
1060 /* We have been asked to resume this thread, but haven't sent a vCont action
1061 for it yet. We'll need to consider it next time commit_resume is
1062 called. */
1063 RESUMED_PENDING_VCONT,
1064
1065 /* We have been asked to resume this thread, and we have sent a vCont action
1066 for it. */
1067 RESUMED,
1068};
1069
1070/* Information about a thread's pending vCont-resume. Used when a thread is in
1071 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1072 stores this information which is then picked up by
1073 remote_target::commit_resume to know which is the proper action for this
1074 thread to include in the vCont packet. */
1075struct resumed_pending_vcont_info
1076{
1077 /* True if the last resume call for this thread was a step request, false
1078 if a continue request. */
1079 bool step;
1080
1081 /* The signal specified in the last resume call for this thread. */
1082 gdb_signal sig;
1083};
1084
7aabaf9d
SM
1085/* Private data that we'll store in (struct thread_info)->priv. */
1086struct remote_thread_info : public private_thread_info
dc146f7c 1087{
7aabaf9d
SM
1088 std::string extra;
1089 std::string name;
1090 int core = -1;
799a2abe 1091
f6327dcb
KB
1092 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1093 sequence of bytes. */
7aabaf9d 1094 gdb::byte_vector thread_handle;
f6327dcb 1095
799a2abe 1096 /* Whether the target stopped for a breakpoint/watchpoint. */
7aabaf9d 1097 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
799a2abe
PA
1098
1099 /* This is set to the data address of the access causing the target
1100 to stop for a watchpoint. */
7aabaf9d 1101 CORE_ADDR watch_data_address = 0;
85ad3aaf 1102
c9d22089
SM
1103 /* Get the thread's resume state. */
1104 enum resume_state resume_state () const
1105 {
1106 return m_resume_state;
1107 }
1108
1109 /* Put the thread in the NOT_RESUMED state. */
1110 void set_not_resumed ()
1111 {
1112 m_resume_state = resume_state::NOT_RESUMED;
1113 }
85ad3aaf 1114
c9d22089
SM
1115 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1116 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1117 {
1118 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1119 m_resumed_pending_vcont_info.step = step;
1120 m_resumed_pending_vcont_info.sig = sig;
1121 }
85ad3aaf 1122
c9d22089 1123 /* Get the information this thread's pending vCont-resumption.
85ad3aaf 1124
c9d22089
SM
1125 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1126 state. */
1127 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1128 {
1129 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1130
1131 return m_resumed_pending_vcont_info;
1132 }
1133
1134 /* Put the thread in the VCONT_RESUMED state. */
1135 void set_resumed ()
1136 {
1137 m_resume_state = resume_state::RESUMED;
1138 }
1139
1140private:
1141 /* Resume state for this thread. This is used to implement vCont action
1142 coalescing (only when the target operates in non-stop mode).
1143
1144 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1145 which notes that this thread must be considered in the next commit_resume
1146 call.
1147
1148 remote_target::commit_resume sends a vCont packet with actions for the
1149 threads in the RESUMED_PENDING_VCONT state and moves them to the
1150 VCONT_RESUMED state.
1151
1152 When reporting a stop to the core for a thread, that thread is moved back
1153 to the NOT_RESUMED state. */
1154 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1155
1156 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1157 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
dc146f7c
VP
1158};
1159
de44f5a7 1160remote_state::remote_state ()
8d64371b 1161 : buf (400)
de44f5a7 1162{
de44f5a7
PA
1163}
1164
1165remote_state::~remote_state ()
1166{
1167 xfree (this->last_pass_packet);
1168 xfree (this->last_program_signals_packet);
de44f5a7
PA
1169 xfree (this->finished_object);
1170 xfree (this->finished_annex);
cf792862
TT
1171}
1172
35b1e5cc
SS
1173/* Utility: generate error from an incoming stub packet. */
1174static void
1175trace_error (char *buf)
1176{
1177 if (*buf++ != 'E')
1178 return; /* not an error msg */
1179 switch (*buf)
1180 {
1181 case '1': /* malformed packet error */
1182 if (*++buf == '0') /* general case: */
1183 error (_("remote.c: error in outgoing packet."));
1184 else
1185 error (_("remote.c: error in outgoing packet at field #%ld."),
1186 strtol (buf, NULL, 16));
35b1e5cc
SS
1187 default:
1188 error (_("Target returns error code '%s'."), buf);
1189 }
1190}
1191
1192/* Utility: wait for reply from stub, while accepting "O" packets. */
b6bb3468 1193
6b8edb51
PA
1194char *
1195remote_target::remote_get_noisy_reply ()
35b1e5cc 1196{
b6bb3468
PA
1197 struct remote_state *rs = get_remote_state ();
1198
35b1e5cc
SS
1199 do /* Loop on reply from remote stub. */
1200 {
1201 char *buf;
a744cf53 1202
0df8b418 1203 QUIT; /* Allow user to bail out with ^C. */
8d64371b
TT
1204 getpkt (&rs->buf, 0);
1205 buf = rs->buf.data ();
ad91cd99 1206 if (buf[0] == 'E')
35b1e5cc 1207 trace_error (buf);
61012eef 1208 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
1209 {
1210 ULONGEST ul;
1211 CORE_ADDR from, to, org_to;
256642e8 1212 const char *p, *pp;
dde08ee1 1213 int adjusted_size = 0;
7556d4a4 1214 int relocated = 0;
dde08ee1
PA
1215
1216 p = buf + strlen ("qRelocInsn:");
1217 pp = unpack_varlen_hex (p, &ul);
1218 if (*pp != ';')
cb91c06a 1219 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
1220 from = ul;
1221
1222 p = pp + 1;
a9cbf802 1223 unpack_varlen_hex (p, &ul);
dde08ee1
PA
1224 to = ul;
1225
1226 org_to = to;
1227
a70b8144 1228 try
dde08ee1 1229 {
f5656ead 1230 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 1231 relocated = 1;
dde08ee1 1232 }
230d2906 1233 catch (const gdb_exception &ex)
7556d4a4
PA
1234 {
1235 if (ex.error == MEMORY_ERROR)
1236 {
1237 /* Propagate memory errors silently back to the
1238 target. The stub may have limited the range of
1239 addresses we can write to, for example. */
1240 }
1241 else
1242 {
1243 /* Something unexpectedly bad happened. Be verbose
1244 so we can tell what, and propagate the error back
1245 to the stub, so it doesn't get stuck waiting for
1246 a response. */
1247 exception_fprintf (gdb_stderr, ex,
1248 _("warning: relocating instruction: "));
1249 }
1250 putpkt ("E01");
1251 }
1252
1253 if (relocated)
dde08ee1
PA
1254 {
1255 adjusted_size = to - org_to;
1256
8d64371b 1257 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
1258 putpkt (buf);
1259 }
dde08ee1 1260 }
ad91cd99 1261 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
1262 remote_console_output (buf + 1); /* 'O' message from stub */
1263 else
0df8b418 1264 return buf; /* Here's the actual reply. */
35b1e5cc
SS
1265 }
1266 while (1);
1267}
3c3bea1c 1268
9d6eea31
PA
1269struct remote_arch_state *
1270remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
d01949b6 1271{
43c3a0e4
PA
1272 remote_arch_state *rsa;
1273
1274 auto it = this->m_arch_states.find (gdbarch);
1275 if (it == this->m_arch_states.end ())
9d6eea31 1276 {
43c3a0e4
PA
1277 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1278 std::forward_as_tuple (gdbarch),
1279 std::forward_as_tuple (gdbarch));
1280 rsa = &p.first->second;
9d6eea31
PA
1281
1282 /* Make sure that the packet buffer is plenty big enough for
1283 this architecture. */
8d64371b
TT
1284 if (this->buf.size () < rsa->remote_packet_size)
1285 this->buf.resize (2 * rsa->remote_packet_size);
9d6eea31 1286 }
43c3a0e4
PA
1287 else
1288 rsa = &it->second;
1289
1290 return rsa;
d01949b6
AC
1291}
1292
0b83947e
DJ
1293/* Fetch the global remote target state. */
1294
6b8edb51
PA
1295remote_state *
1296remote_target::get_remote_state ()
0b83947e
DJ
1297{
1298 /* Make sure that the remote architecture state has been
1299 initialized, because doing so might reallocate rs->buf. Any
1300 function which calls getpkt also needs to be mindful of changes
1301 to rs->buf, but this call limits the number of places which run
1302 into trouble. */
3c69da40 1303 m_remote_state.get_remote_arch_state (target_gdbarch ());
0b83947e 1304
3c69da40 1305 return &m_remote_state;
0b83947e
DJ
1306}
1307
94585166
DB
1308/* Fetch the remote exec-file from the current program space. */
1309
1310static const char *
1311get_remote_exec_file (void)
1312{
1313 char *remote_exec_file;
1314
7b4a314f 1315 remote_exec_file = remote_pspace_data.get (current_program_space);
94585166
DB
1316 if (remote_exec_file == NULL)
1317 return "";
1318
1319 return remote_exec_file;
1320}
1321
1322/* Set the remote exec file for PSPACE. */
1323
1324static void
1325set_pspace_remote_exec_file (struct program_space *pspace,
7b4a314f 1326 const char *remote_exec_file)
94585166 1327{
7b4a314f 1328 char *old_file = remote_pspace_data.get (pspace);
94585166
DB
1329
1330 xfree (old_file);
7b4a314f 1331 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
94585166
DB
1332}
1333
1334/* The "set/show remote exec-file" set command hook. */
1335
1336static void
eb4c3f4a 1337set_remote_exec_file (const char *ignored, int from_tty,
94585166
DB
1338 struct cmd_list_element *c)
1339{
1340 gdb_assert (remote_exec_file_var != NULL);
1341 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
1342}
1343
1344/* The "set/show remote exec-file" show command hook. */
1345
1346static void
1347show_remote_exec_file (struct ui_file *file, int from_tty,
1348 struct cmd_list_element *cmd, const char *value)
1349{
acdf84a6 1350 fprintf_filtered (file, "%s\n", get_remote_exec_file ());
94585166
DB
1351}
1352
c21236dc
PA
1353static int
1354map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 1355{
74ca34ce 1356 int regnum, num_remote_regs, offset;
74ca34ce 1357 struct packet_reg **remote_regs;
ea9c271d 1358
4a22f64d 1359 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 1360 {
c21236dc 1361 struct packet_reg *r = &regs[regnum];
baef701f 1362
4a22f64d 1363 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
1364 /* Do not try to fetch zero-sized (placeholder) registers. */
1365 r->pnum = -1;
1366 else
1367 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1368
b323314b 1369 r->regnum = regnum;
74ca34ce
DJ
1370 }
1371
1372 /* Define the g/G packet format as the contents of each register
1373 with a remote protocol number, in order of ascending protocol
1374 number. */
1375
224c3ddb 1376 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 1377 for (num_remote_regs = 0, regnum = 0;
4a22f64d 1378 regnum < gdbarch_num_regs (gdbarch);
f57d151a 1379 regnum++)
c21236dc
PA
1380 if (regs[regnum].pnum != -1)
1381 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 1382
39ef2f62
CB
1383 std::sort (remote_regs, remote_regs + num_remote_regs,
1384 [] (const packet_reg *a, const packet_reg *b)
1385 { return a->pnum < b->pnum; });
74ca34ce
DJ
1386
1387 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1388 {
1389 remote_regs[regnum]->in_g_packet = 1;
1390 remote_regs[regnum]->offset = offset;
4a22f64d 1391 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
1392 }
1393
c21236dc
PA
1394 return offset;
1395}
1396
1397/* Given the architecture described by GDBARCH, return the remote
1398 protocol register's number and the register's offset in the g/G
1399 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1400 If the target does not have a mapping for REGNUM, return false,
1401 otherwise, return true. */
1402
1403int
1404remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1405 int *pnum, int *poffset)
1406{
c21236dc
PA
1407 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1408
b80406ac 1409 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
c21236dc 1410
b80406ac 1411 map_regcache_remote_table (gdbarch, regs.data ());
c21236dc
PA
1412
1413 *pnum = regs[regnum].pnum;
1414 *poffset = regs[regnum].offset;
1415
c21236dc
PA
1416 return *pnum != -1;
1417}
1418
9d6eea31 1419remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
c21236dc 1420{
c21236dc
PA
1421 /* Use the architecture to build a regnum<->pnum table, which will be
1422 1:1 unless a feature set specifies otherwise. */
9d6eea31 1423 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
c21236dc 1424
74ca34ce
DJ
1425 /* Record the maximum possible size of the g packet - it may turn out
1426 to be smaller. */
9d6eea31
PA
1427 this->sizeof_g_packet
1428 = map_regcache_remote_table (gdbarch, this->regs.get ());
74ca34ce 1429
0df8b418 1430 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
1431 remote stubs have a hardwired buffer size of 400 bytes
1432 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1433 as the maximum packet-size to ensure that the packet and an extra
1434 NUL character can always fit in the buffer. This stops GDB
1435 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d 1436 already a full buffer (As of 1999-12-04 that was most stubs). */
9d6eea31 1437 this->remote_packet_size = 400 - 1;
d01949b6 1438
ea9c271d 1439 /* This one is filled in when a ``g'' packet is received. */
9d6eea31 1440 this->actual_register_packet_size = 0;
ea9c271d
DJ
1441
1442 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
1443 default, adjust the size accordingly. Remember that each byte is
1444 encoded as two characters. 32 is the overhead for the packet
1445 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 1446 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 1447 little. */
9d6eea31
PA
1448 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1449 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
ea9c271d
DJ
1450}
1451
6b8edb51
PA
1452/* Get a pointer to the current remote target. If not connected to a
1453 remote target, return NULL. */
1454
1455static remote_target *
1456get_current_remote_target ()
1457{
5b6d1e4f 1458 target_ops *proc_target = current_inferior ()->process_target ();
6b8edb51
PA
1459 return dynamic_cast<remote_target *> (proc_target);
1460}
1461
ea9c271d
DJ
1462/* Return the current allowed size of a remote packet. This is
1463 inferred from the current architecture, and should be used to
1464 limit the length of outgoing packets. */
6b8edb51
PA
1465long
1466remote_target::get_remote_packet_size ()
ea9c271d 1467{
be2a5f71 1468 struct remote_state *rs = get_remote_state ();
9d6eea31 1469 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
ea9c271d 1470
be2a5f71
DJ
1471 if (rs->explicit_packet_size)
1472 return rs->explicit_packet_size;
1473
ea9c271d 1474 return rsa->remote_packet_size;
d01949b6
AC
1475}
1476
ad10f812 1477static struct packet_reg *
5cd63fda
PA
1478packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1479 long regnum)
ad10f812 1480{
5cd63fda 1481 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
b323314b
AC
1482 return NULL;
1483 else
ad10f812 1484 {
ea9c271d 1485 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 1486
b323314b
AC
1487 gdb_assert (r->regnum == regnum);
1488 return r;
ad10f812 1489 }
ad10f812
AC
1490}
1491
1492static struct packet_reg *
5cd63fda
PA
1493packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1494 LONGEST pnum)
ad10f812 1495{
b323314b 1496 int i;
a744cf53 1497
5cd63fda 1498 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
ad10f812 1499 {
ea9c271d 1500 struct packet_reg *r = &rsa->regs[i];
a744cf53 1501
b323314b
AC
1502 if (r->pnum == pnum)
1503 return r;
ad10f812
AC
1504 }
1505 return NULL;
d01949b6
AC
1506}
1507
9a7071a8
JB
1508/* Allow the user to specify what sequence to send to the remote
1509 when he requests a program interruption: Although ^C is usually
1510 what remote systems expect (this is the default, here), it is
1511 sometimes preferable to send a break. On other systems such
1512 as the Linux kernel, a break followed by g, which is Magic SysRq g
1513 is required in order to interrupt the execution. */
1514const char interrupt_sequence_control_c[] = "Ctrl-C";
1515const char interrupt_sequence_break[] = "BREAK";
1516const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 1517static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
1518 {
1519 interrupt_sequence_control_c,
1520 interrupt_sequence_break,
1521 interrupt_sequence_break_g,
1522 NULL
1523 };
1524static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1525
1526static void
1527show_interrupt_sequence (struct ui_file *file, int from_tty,
1528 struct cmd_list_element *c,
1529 const char *value)
1530{
1531 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1532 fprintf_filtered (file,
1533 _("Send the ASCII ETX character (Ctrl-c) "
1534 "to the remote target to interrupt the "
1535 "execution of the program.\n"));
1536 else if (interrupt_sequence_mode == interrupt_sequence_break)
1537 fprintf_filtered (file,
1538 _("send a break signal to the remote target "
1539 "to interrupt the execution of the program.\n"));
1540 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1541 fprintf_filtered (file,
1542 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1543 "the remote target to interrupt the execution "
1544 "of Linux kernel.\n"));
1545 else
1546 internal_error (__FILE__, __LINE__,
1547 _("Invalid value for interrupt_sequence_mode: %s."),
1548 interrupt_sequence_mode);
1549}
6426a772 1550
9a7071a8
JB
1551/* This boolean variable specifies whether interrupt_sequence is sent
1552 to the remote target when gdb connects to it.
1553 This is mostly needed when you debug the Linux kernel: The Linux kernel
1554 expects BREAK g which is Magic SysRq g for connecting gdb. */
491144b5 1555static bool interrupt_on_connect = false;
c906108c 1556
9a7071a8
JB
1557/* This variable is used to implement the "set/show remotebreak" commands.
1558 Since these commands are now deprecated in favor of "set/show remote
1559 interrupt-sequence", it no longer has any effect on the code. */
491144b5 1560static bool remote_break;
c906108c 1561
9a7071a8 1562static void
eb4c3f4a 1563set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
9a7071a8
JB
1564{
1565 if (remote_break)
1566 interrupt_sequence_mode = interrupt_sequence_break;
1567 else
1568 interrupt_sequence_mode = interrupt_sequence_control_c;
1569}
1570
1571static void
1572show_remotebreak (struct ui_file *file, int from_tty,
1573 struct cmd_list_element *c,
1574 const char *value)
1575{
1576}
1577
c906108c
SS
1578/* This variable sets the number of bits in an address that are to be
1579 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 1580 leading zeros, the entire address would be sent. This variable
c906108c
SS
1581 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1582 initial implementation of remote.c restricted the address sent in
1583 memory packets to ``host::sizeof long'' bytes - (typically 32
1584 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1585 address was never sent. Since fixing this bug may cause a break in
85102364 1586 some remote targets this variable is principally provided to
23860348 1587 facilitate backward compatibility. */
c906108c 1588
883b9c6c 1589static unsigned int remote_address_size;
c906108c 1590
11cf8741 1591\f
11cf8741 1592/* User configurable variables for the number of characters in a
ea9c271d
DJ
1593 memory read/write packet. MIN (rsa->remote_packet_size,
1594 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 1595 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
1596 (speed up transfers). The variables ``preferred_*'' (the user
1597 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 1598 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
1599
1600struct memory_packet_config
1601{
a121b7c1 1602 const char *name;
11cf8741
JM
1603 long size;
1604 int fixed_p;
1605};
1606
cc0be08f
PA
1607/* The default max memory-write-packet-size, when the setting is
1608 "fixed". The 16k is historical. (It came from older GDB's using
1609 alloca for buffers and the knowledge (folklore?) that some hosts
1610 don't cope very well with large alloca calls.) */
1611#define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
a5c0808e
PA
1612
1613/* The minimum remote packet size for memory transfers. Ensures we
1614 can write at least one byte. */
1615#define MIN_MEMORY_PACKET_SIZE 20
1616
cc0be08f
PA
1617/* Get the memory packet size, assuming it is fixed. */
1618
1619static long
1620get_fixed_memory_packet_size (struct memory_packet_config *config)
1621{
1622 gdb_assert (config->fixed_p);
1623
1624 if (config->size <= 0)
1625 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1626 else
1627 return config->size;
1628}
1629
11cf8741
JM
1630/* Compute the current size of a read/write packet. Since this makes
1631 use of ``actual_register_packet_size'' the computation is dynamic. */
1632
6b8edb51
PA
1633long
1634remote_target::get_memory_packet_size (struct memory_packet_config *config)
11cf8741 1635{
d01949b6 1636 struct remote_state *rs = get_remote_state ();
9d6eea31 1637 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
ea9c271d 1638
11cf8741
JM
1639 long what_they_get;
1640 if (config->fixed_p)
cc0be08f 1641 what_they_get = get_fixed_memory_packet_size (config);
11cf8741
JM
1642 else
1643 {
ea9c271d 1644 what_they_get = get_remote_packet_size ();
23860348 1645 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1646 if (config->size > 0
1647 && what_they_get > config->size)
1648 what_they_get = config->size;
be2a5f71
DJ
1649
1650 /* Limit it to the size of the targets ``g'' response unless we have
1651 permission from the stub to use a larger packet size. */
1652 if (rs->explicit_packet_size == 0
1653 && rsa->actual_register_packet_size > 0
1654 && what_they_get > rsa->actual_register_packet_size)
1655 what_they_get = rsa->actual_register_packet_size;
11cf8741 1656 }
a5c0808e
PA
1657 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1658 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1659
1660 /* Make sure there is room in the global buffer for this packet
1661 (including its trailing NUL byte). */
8d64371b
TT
1662 if (rs->buf.size () < what_they_get + 1)
1663 rs->buf.resize (2 * what_they_get);
6d820c5c 1664
11cf8741
JM
1665 return what_they_get;
1666}
1667
0df8b418 1668/* Update the size of a read/write packet. If they user wants
23860348 1669 something really big then do a sanity check. */
11cf8741
JM
1670
1671static void
ac88e2de 1672set_memory_packet_size (const char *args, struct memory_packet_config *config)
11cf8741
JM
1673{
1674 int fixed_p = config->fixed_p;
1675 long size = config->size;
a744cf53 1676
11cf8741 1677 if (args == NULL)
8a3fe4f8 1678 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1679 else if (strcmp (args, "hard") == 0
1680 || strcmp (args, "fixed") == 0)
1681 fixed_p = 1;
1682 else if (strcmp (args, "soft") == 0
1683 || strcmp (args, "limit") == 0)
1684 fixed_p = 0;
1685 else
1686 {
1687 char *end;
a744cf53 1688
11cf8741
JM
1689 size = strtoul (args, &end, 0);
1690 if (args == end)
8a3fe4f8 1691 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1692
1693 /* Instead of explicitly capping the size of a packet to or
1694 disallowing it, the user is allowed to set the size to
1695 something arbitrarily large. */
11cf8741 1696 }
a5c0808e 1697
23860348 1698 /* Extra checks? */
11cf8741
JM
1699 if (fixed_p && !config->fixed_p)
1700 {
cc0be08f
PA
1701 /* So that the query shows the correct value. */
1702 long query_size = (size <= 0
1703 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1704 : size);
1705
e2e0b3e5
AC
1706 if (! query (_("The target may not be able to correctly handle a %s\n"
1707 "of %ld bytes. Change the packet size? "),
cc0be08f 1708 config->name, query_size))
8a3fe4f8 1709 error (_("Packet size not changed."));
11cf8741 1710 }
23860348 1711 /* Update the config. */
11cf8741
JM
1712 config->fixed_p = fixed_p;
1713 config->size = size;
1714}
1715
1716static void
1717show_memory_packet_size (struct memory_packet_config *config)
1718{
cc0be08f
PA
1719 if (config->size == 0)
1720 printf_filtered (_("The %s is 0 (default). "), config->name);
1721 else
1722 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1723 if (config->fixed_p)
a3f17187 1724 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
cc0be08f 1725 get_fixed_memory_packet_size (config));
11cf8741 1726 else
cc0be08f 1727 {
6b8edb51 1728 remote_target *remote = get_current_remote_target ();
cc0be08f 1729
6b8edb51 1730 if (remote != NULL)
cc0be08f 1731 printf_filtered (_("Packets are limited to %ld bytes.\n"),
6b8edb51 1732 remote->get_memory_packet_size (config));
cc0be08f
PA
1733 else
1734 puts_filtered ("The actual limit will be further reduced "
1735 "dependent on the target.\n");
1736 }
11cf8741
JM
1737}
1738
5b6d1e4f 1739/* FIXME: needs to be per-remote-target. */
11cf8741
JM
1740static struct memory_packet_config memory_write_packet_config =
1741{
1742 "memory-write-packet-size",
1743};
1744
1745static void
ac88e2de 1746set_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1747{
1748 set_memory_packet_size (args, &memory_write_packet_config);
1749}
1750
1751static void
ac88e2de 1752show_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1753{
1754 show_memory_packet_size (&memory_write_packet_config);
1755}
1756
055303e2
AB
1757/* Show the number of hardware watchpoints that can be used. */
1758
1759static void
1760show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
1761 struct cmd_list_element *c,
1762 const char *value)
1763{
1764 fprintf_filtered (file, _("The maximum number of target hardware "
1765 "watchpoints is %s.\n"), value);
1766}
1767
1768/* Show the length limit (in bytes) for hardware watchpoints. */
1769
1770static void
1771show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
1772 struct cmd_list_element *c,
1773 const char *value)
1774{
1775 fprintf_filtered (file, _("The maximum length (in bytes) of a target "
1776 "hardware watchpoint is %s.\n"), value);
1777}
1778
1779/* Show the number of hardware breakpoints that can be used. */
1780
1781static void
1782show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
1783 struct cmd_list_element *c,
1784 const char *value)
1785{
1786 fprintf_filtered (file, _("The maximum number of target hardware "
1787 "breakpoints is %s.\n"), value);
1788}
1789
6cc8564b
LM
1790/* Controls the maximum number of characters to display in the debug output
1791 for each remote packet. The remaining characters are omitted. */
1792
1793static int remote_packet_max_chars = 512;
1794
1795/* Show the maximum number of characters to display for each remote packet
1796 when remote debugging is enabled. */
1797
1798static void
1799show_remote_packet_max_chars (struct ui_file *file, int from_tty,
1800 struct cmd_list_element *c,
1801 const char *value)
1802{
1803 fprintf_filtered (file, _("Number of remote packet characters to "
1804 "display is %s.\n"), value);
1805}
1806
6b8edb51
PA
1807long
1808remote_target::get_memory_write_packet_size ()
11cf8741
JM
1809{
1810 return get_memory_packet_size (&memory_write_packet_config);
1811}
1812
5b6d1e4f 1813/* FIXME: needs to be per-remote-target. */
11cf8741
JM
1814static struct memory_packet_config memory_read_packet_config =
1815{
1816 "memory-read-packet-size",
1817};
1818
1819static void
ac88e2de 1820set_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1821{
1822 set_memory_packet_size (args, &memory_read_packet_config);
1823}
1824
1825static void
ac88e2de 1826show_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1827{
1828 show_memory_packet_size (&memory_read_packet_config);
1829}
1830
6b8edb51
PA
1831long
1832remote_target::get_memory_read_packet_size ()
11cf8741
JM
1833{
1834 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1835
11cf8741
JM
1836 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1837 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1838 increased beyond this. */
1839 if (size > get_remote_packet_size ())
1840 size = get_remote_packet_size ();
11cf8741
JM
1841 return size;
1842}
1843
11cf8741 1844\f
5a2468f5 1845
5a2468f5
JM
1846struct packet_config
1847 {
bb572ddd
DJ
1848 const char *name;
1849 const char *title;
4082afcc
PA
1850
1851 /* If auto, GDB auto-detects support for this packet or feature,
1852 either through qSupported, or by trying the packet and looking
1853 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1854 packet. If false, the packet is disabled. Configs that don't
1855 have an associated command always have this set to auto. */
7f19b9a2 1856 enum auto_boolean detect;
4082afcc
PA
1857
1858 /* Does the target support this packet? */
5a2468f5
JM
1859 enum packet_support support;
1860 };
1861
4082afcc
PA
1862static enum packet_support packet_config_support (struct packet_config *config);
1863static enum packet_support packet_support (int packet);
5a2468f5
JM
1864
1865static void
fba45db2 1866show_packet_config_cmd (struct packet_config *config)
5a2468f5 1867{
a121b7c1 1868 const char *support = "internal-error";
a744cf53 1869
4082afcc 1870 switch (packet_config_support (config))
5a2468f5
JM
1871 {
1872 case PACKET_ENABLE:
1873 support = "enabled";
1874 break;
1875 case PACKET_DISABLE:
1876 support = "disabled";
1877 break;
1878 case PACKET_SUPPORT_UNKNOWN:
1879 support = "unknown";
1880 break;
1881 }
1882 switch (config->detect)
1883 {
7f19b9a2 1884 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1885 printf_filtered (_("Support for the `%s' packet "
1886 "is auto-detected, currently %s.\n"),
37a105a1 1887 config->name, support);
5a2468f5 1888 break;
7f19b9a2
AC
1889 case AUTO_BOOLEAN_TRUE:
1890 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1891 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1892 config->name, support);
8e248173 1893 break;
5a2468f5
JM
1894 }
1895}
1896
1897static void
bb572ddd
DJ
1898add_packet_config_cmd (struct packet_config *config, const char *name,
1899 const char *title, int legacy)
d471ea57 1900{
5a2468f5
JM
1901 char *set_doc;
1902 char *show_doc;
d471ea57 1903 char *cmd_name;
3ed07be4 1904
5a2468f5
JM
1905 config->name = name;
1906 config->title = title;
590042fc 1907 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
b435e160 1908 name, title);
3e43a32a 1909 show_doc = xstrprintf ("Show current use of remote "
590042fc 1910 "protocol `%s' (%s) packet.",
b435e160 1911 name, title);
d471ea57 1912 /* set/show TITLE-packet {auto,on,off} */
b435e160 1913 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1914 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1915 &config->detect, set_doc,
1916 show_doc, NULL, /* help_doc */
4082afcc 1917 NULL,
bb572ddd
DJ
1918 show_remote_protocol_packet_cmd,
1919 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1920 /* The command code copies the documentation strings. */
1921 xfree (set_doc);
1922 xfree (show_doc);
23860348 1923 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1924 if (legacy)
1925 {
1926 char *legacy_name;
a744cf53 1927
b435e160 1928 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1929 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1930 &remote_set_cmdlist);
d471ea57 1931 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1932 &remote_show_cmdlist);
d471ea57 1933 }
5a2468f5
JM
1934}
1935
d471ea57 1936static enum packet_result
a76d924d 1937packet_check_result (const char *buf)
5a2468f5 1938{
d471ea57 1939 if (buf[0] != '\0')
5a2468f5 1940 {
d471ea57 1941 /* The stub recognized the packet request. Check that the
23860348 1942 operation succeeded. */
a76d924d
DJ
1943 if (buf[0] == 'E'
1944 && isxdigit (buf[1]) && isxdigit (buf[2])
1945 && buf[3] == '\0')
85102364 1946 /* "Enn" - definitely an error. */
a76d924d
DJ
1947 return PACKET_ERROR;
1948
1949 /* Always treat "E." as an error. This will be used for
1950 more verbose error messages, such as E.memtypes. */
1951 if (buf[0] == 'E' && buf[1] == '.')
1952 return PACKET_ERROR;
1953
1954 /* The packet may or may not be OK. Just assume it is. */
1955 return PACKET_OK;
1956 }
1957 else
1958 /* The stub does not support the packet. */
1959 return PACKET_UNKNOWN;
1960}
1961
8d64371b
TT
1962static enum packet_result
1963packet_check_result (const gdb::char_vector &buf)
1964{
1965 return packet_check_result (buf.data ());
1966}
1967
a76d924d
DJ
1968static enum packet_result
1969packet_ok (const char *buf, struct packet_config *config)
1970{
1971 enum packet_result result;
1972
4082afcc
PA
1973 if (config->detect != AUTO_BOOLEAN_TRUE
1974 && config->support == PACKET_DISABLE)
1975 internal_error (__FILE__, __LINE__,
1976 _("packet_ok: attempt to use a disabled packet"));
1977
a76d924d
DJ
1978 result = packet_check_result (buf);
1979 switch (result)
1980 {
1981 case PACKET_OK:
1982 case PACKET_ERROR:
1983 /* The stub recognized the packet request. */
4082afcc 1984 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1985 {
d471ea57
AC
1986 if (remote_debug)
1987 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1988 "Packet %s (%s) is supported\n",
1989 config->name, config->title);
d471ea57 1990 config->support = PACKET_ENABLE;
d471ea57 1991 }
a76d924d
DJ
1992 break;
1993 case PACKET_UNKNOWN:
23860348 1994 /* The stub does not support the packet. */
4082afcc
PA
1995 if (config->detect == AUTO_BOOLEAN_AUTO
1996 && config->support == PACKET_ENABLE)
d471ea57 1997 {
4082afcc
PA
1998 /* If the stub previously indicated that the packet was
1999 supported then there is a protocol error. */
2000 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2001 config->name, config->title);
2002 }
2003 else if (config->detect == AUTO_BOOLEAN_TRUE)
2004 {
2005 /* The user set it wrong. */
2006 error (_("Enabled packet %s (%s) not recognized by stub"),
2007 config->name, config->title);
d471ea57 2008 }
4082afcc
PA
2009
2010 if (remote_debug)
2011 fprintf_unfiltered (gdb_stdlog,
2012 "Packet %s (%s) is NOT supported\n",
2013 config->name, config->title);
2014 config->support = PACKET_DISABLE;
a76d924d 2015 break;
5a2468f5 2016 }
a76d924d
DJ
2017
2018 return result;
5a2468f5
JM
2019}
2020
8d64371b
TT
2021static enum packet_result
2022packet_ok (const gdb::char_vector &buf, struct packet_config *config)
2023{
2024 return packet_ok (buf.data (), config);
2025}
2026
444abaca
DJ
2027enum {
2028 PACKET_vCont = 0,
2029 PACKET_X,
2030 PACKET_qSymbol,
2031 PACKET_P,
2032 PACKET_p,
2033 PACKET_Z0,
2034 PACKET_Z1,
2035 PACKET_Z2,
2036 PACKET_Z3,
2037 PACKET_Z4,
15a201c8 2038 PACKET_vFile_setfs,
a6b151f1
DJ
2039 PACKET_vFile_open,
2040 PACKET_vFile_pread,
2041 PACKET_vFile_pwrite,
2042 PACKET_vFile_close,
2043 PACKET_vFile_unlink,
b9e7b9c3 2044 PACKET_vFile_readlink,
0a93529c 2045 PACKET_vFile_fstat,
0876f84a 2046 PACKET_qXfer_auxv,
23181151 2047 PACKET_qXfer_features,
c78fa86a 2048 PACKET_qXfer_exec_file,
cfa9d6d9 2049 PACKET_qXfer_libraries,
2268b414 2050 PACKET_qXfer_libraries_svr4,
fd79ecee 2051 PACKET_qXfer_memory_map,
07e059b5 2052 PACKET_qXfer_osdata,
dc146f7c 2053 PACKET_qXfer_threads,
0fb4aa4b 2054 PACKET_qXfer_statictrace_read,
b3b9301e 2055 PACKET_qXfer_traceframe_info,
169081d0 2056 PACKET_qXfer_uib,
711e434b 2057 PACKET_qGetTIBAddr,
444abaca 2058 PACKET_qGetTLSAddr,
be2a5f71 2059 PACKET_qSupported,
bd3eecc3 2060 PACKET_qTStatus,
89be2091 2061 PACKET_QPassSignals,
82075af2 2062 PACKET_QCatchSyscalls,
9b224c5e 2063 PACKET_QProgramSignals,
bc3b087d 2064 PACKET_QSetWorkingDir,
aefd8b33 2065 PACKET_QStartupWithShell,
0a2dde4a
SDJ
2066 PACKET_QEnvironmentHexEncoded,
2067 PACKET_QEnvironmentReset,
2068 PACKET_QEnvironmentUnset,
936d2992 2069 PACKET_qCRC,
08388c79 2070 PACKET_qSearch_memory,
2d717e4f
DJ
2071 PACKET_vAttach,
2072 PACKET_vRun,
a6f3e723 2073 PACKET_QStartNoAckMode,
82f73884 2074 PACKET_vKill,
4aa995e1
PA
2075 PACKET_qXfer_siginfo_read,
2076 PACKET_qXfer_siginfo_write,
0b16c5cf 2077 PACKET_qAttached,
4082afcc
PA
2078
2079 /* Support for conditional tracepoints. */
782b2b07 2080 PACKET_ConditionalTracepoints,
4082afcc
PA
2081
2082 /* Support for target-side breakpoint conditions. */
3788aec7 2083 PACKET_ConditionalBreakpoints,
4082afcc
PA
2084
2085 /* Support for target-side breakpoint commands. */
d3ce09f5 2086 PACKET_BreakpointCommands,
4082afcc
PA
2087
2088 /* Support for fast tracepoints. */
7a697b8d 2089 PACKET_FastTracepoints,
4082afcc
PA
2090
2091 /* Support for static tracepoints. */
0fb4aa4b 2092 PACKET_StaticTracepoints,
4082afcc
PA
2093
2094 /* Support for installing tracepoints while a trace experiment is
2095 running. */
1e4d1764 2096 PACKET_InstallInTrace,
4082afcc 2097
40ab02ce
MS
2098 PACKET_bc,
2099 PACKET_bs,
409873ef 2100 PACKET_TracepointSource,
d914c394 2101 PACKET_QAllow,
78d85199 2102 PACKET_qXfer_fdpic,
03583c20 2103 PACKET_QDisableRandomization,
d1feda86 2104 PACKET_QAgent,
f6f899bf 2105 PACKET_QTBuffer_size,
9accd112
MM
2106 PACKET_Qbtrace_off,
2107 PACKET_Qbtrace_bts,
b20a6524 2108 PACKET_Qbtrace_pt,
9accd112 2109 PACKET_qXfer_btrace,
4082afcc
PA
2110
2111 /* Support for the QNonStop packet. */
2112 PACKET_QNonStop,
2113
65706a29
PA
2114 /* Support for the QThreadEvents packet. */
2115 PACKET_QThreadEvents,
2116
4082afcc
PA
2117 /* Support for multi-process extensions. */
2118 PACKET_multiprocess_feature,
2119
2120 /* Support for enabling and disabling tracepoints while a trace
2121 experiment is running. */
2122 PACKET_EnableDisableTracepoints_feature,
2123
2124 /* Support for collecting strings using the tracenz bytecode. */
2125 PACKET_tracenz_feature,
2126
2127 /* Support for continuing to run a trace experiment while GDB is
2128 disconnected. */
2129 PACKET_DisconnectedTracing_feature,
2130
2131 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2132 PACKET_augmented_libraries_svr4_read_feature,
2133
f4abbc16
MM
2134 /* Support for the qXfer:btrace-conf:read packet. */
2135 PACKET_qXfer_btrace_conf,
2136
d33501a5
MM
2137 /* Support for the Qbtrace-conf:bts:size packet. */
2138 PACKET_Qbtrace_conf_bts_size,
2139
f7e6eed5
PA
2140 /* Support for swbreak+ feature. */
2141 PACKET_swbreak_feature,
2142
2143 /* Support for hwbreak+ feature. */
2144 PACKET_hwbreak_feature,
2145
89245bc0
DB
2146 /* Support for fork events. */
2147 PACKET_fork_event_feature,
2148
2149 /* Support for vfork events. */
2150 PACKET_vfork_event_feature,
2151
b20a6524
MM
2152 /* Support for the Qbtrace-conf:pt:size packet. */
2153 PACKET_Qbtrace_conf_pt_size,
2154
94585166
DB
2155 /* Support for exec events. */
2156 PACKET_exec_event_feature,
2157
750ce8d1
YQ
2158 /* Support for query supported vCont actions. */
2159 PACKET_vContSupported,
2160
de979965
PA
2161 /* Support remote CTRL-C. */
2162 PACKET_vCtrlC,
2163
f2faf941
PA
2164 /* Support TARGET_WAITKIND_NO_RESUMED. */
2165 PACKET_no_resumed,
2166
444abaca
DJ
2167 PACKET_MAX
2168};
506fb367 2169
5b6d1e4f
PA
2170/* FIXME: needs to be per-remote-target. Ignoring this for now,
2171 assuming all remote targets are the same server (thus all support
2172 the same packets). */
444abaca 2173static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 2174
f7e6eed5
PA
2175/* Returns the packet's corresponding "set remote foo-packet" command
2176 state. See struct packet_config for more details. */
2177
2178static enum auto_boolean
2179packet_set_cmd_state (int packet)
2180{
2181 return remote_protocol_packets[packet].detect;
2182}
2183
4082afcc
PA
2184/* Returns whether a given packet or feature is supported. This takes
2185 into account the state of the corresponding "set remote foo-packet"
2186 command, which may be used to bypass auto-detection. */
dc8acb97 2187
4082afcc
PA
2188static enum packet_support
2189packet_config_support (struct packet_config *config)
2190{
2191 switch (config->detect)
444abaca 2192 {
4082afcc
PA
2193 case AUTO_BOOLEAN_TRUE:
2194 return PACKET_ENABLE;
2195 case AUTO_BOOLEAN_FALSE:
2196 return PACKET_DISABLE;
2197 case AUTO_BOOLEAN_AUTO:
2198 return config->support;
2199 default:
2200 gdb_assert_not_reached (_("bad switch"));
444abaca 2201 }
4082afcc
PA
2202}
2203
2204/* Same as packet_config_support, but takes the packet's enum value as
2205 argument. */
2206
2207static enum packet_support
2208packet_support (int packet)
2209{
2210 struct packet_config *config = &remote_protocol_packets[packet];
2211
2212 return packet_config_support (config);
dc8acb97
MS
2213}
2214
5a2468f5 2215static void
444abaca
DJ
2216show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2217 struct cmd_list_element *c,
2218 const char *value)
5a2468f5 2219{
444abaca 2220 struct packet_config *packet;
5a2468f5 2221
444abaca
DJ
2222 for (packet = remote_protocol_packets;
2223 packet < &remote_protocol_packets[PACKET_MAX];
2224 packet++)
2225 {
2226 if (&packet->detect == c->var)
2227 {
2228 show_packet_config_cmd (packet);
2229 return;
2230 }
2231 }
9b20d036 2232 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 2233 c->name);
5a2468f5
JM
2234}
2235
d471ea57
AC
2236/* Should we try one of the 'Z' requests? */
2237
2238enum Z_packet_type
2239{
2240 Z_PACKET_SOFTWARE_BP,
2241 Z_PACKET_HARDWARE_BP,
2242 Z_PACKET_WRITE_WP,
2243 Z_PACKET_READ_WP,
2244 Z_PACKET_ACCESS_WP,
2245 NR_Z_PACKET_TYPES
2246};
96baa820 2247
d471ea57 2248/* For compatibility with older distributions. Provide a ``set remote
23860348 2249 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 2250
7f19b9a2 2251static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
2252
2253static void
eb4c3f4a 2254set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
fba45db2 2255 struct cmd_list_element *c)
96baa820 2256{
d471ea57 2257 int i;
a744cf53 2258
d471ea57 2259 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 2260 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
2261}
2262
2263static void
08546159
AC
2264show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2265 struct cmd_list_element *c,
2266 const char *value)
96baa820 2267{
d471ea57 2268 int i;
a744cf53 2269
d471ea57
AC
2270 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2271 {
444abaca 2272 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 2273 }
96baa820
JM
2274}
2275
4082afcc
PA
2276/* Returns true if the multi-process extensions are in effect. */
2277
2278static int
2279remote_multi_process_p (struct remote_state *rs)
2280{
2281 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2282}
2283
de0d863e
DB
2284/* Returns true if fork events are supported. */
2285
2286static int
2287remote_fork_event_p (struct remote_state *rs)
2288{
2289 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2290}
2291
c269dbdb
DB
2292/* Returns true if vfork events are supported. */
2293
2294static int
2295remote_vfork_event_p (struct remote_state *rs)
2296{
2297 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2298}
2299
d46addbb
DB
2300/* Returns true if exec events are supported. */
2301
2302static int
2303remote_exec_event_p (struct remote_state *rs)
2304{
2305 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2306}
2307
cbb8991c
DB
2308/* Insert fork catchpoint target routine. If fork events are enabled
2309 then return success, nothing more to do. */
2310
f6ac5f3d
PA
2311int
2312remote_target::insert_fork_catchpoint (int pid)
cbb8991c
DB
2313{
2314 struct remote_state *rs = get_remote_state ();
2315
2316 return !remote_fork_event_p (rs);
2317}
2318
2319/* Remove fork catchpoint target routine. Nothing to do, just
2320 return success. */
2321
f6ac5f3d
PA
2322int
2323remote_target::remove_fork_catchpoint (int pid)
cbb8991c
DB
2324{
2325 return 0;
2326}
2327
2328/* Insert vfork catchpoint target routine. If vfork events are enabled
2329 then return success, nothing more to do. */
2330
f6ac5f3d
PA
2331int
2332remote_target::insert_vfork_catchpoint (int pid)
cbb8991c
DB
2333{
2334 struct remote_state *rs = get_remote_state ();
2335
2336 return !remote_vfork_event_p (rs);
2337}
2338
2339/* Remove vfork catchpoint target routine. Nothing to do, just
2340 return success. */
2341
f6ac5f3d
PA
2342int
2343remote_target::remove_vfork_catchpoint (int pid)
cbb8991c
DB
2344{
2345 return 0;
2346}
2347
d46addbb
DB
2348/* Insert exec catchpoint target routine. If exec events are
2349 enabled, just return success. */
2350
f6ac5f3d
PA
2351int
2352remote_target::insert_exec_catchpoint (int pid)
d46addbb
DB
2353{
2354 struct remote_state *rs = get_remote_state ();
2355
2356 return !remote_exec_event_p (rs);
2357}
2358
2359/* Remove exec catchpoint target routine. Nothing to do, just
2360 return success. */
2361
f6ac5f3d
PA
2362int
2363remote_target::remove_exec_catchpoint (int pid)
d46addbb
DB
2364{
2365 return 0;
2366}
2367
c906108c
SS
2368\f
2369
ffdd69cf
TT
2370/* Take advantage of the fact that the TID field is not used, to tag
2371 special ptids with it set to != 0. */
2372static const ptid_t magic_null_ptid (42000, -1, 1);
2373static const ptid_t not_sent_ptid (42000, -2, 1);
2374static const ptid_t any_thread_ptid (42000, 0, 1);
79d7f229 2375
0b16c5cf
PA
2376/* Find out if the stub attached to PID (and hence GDB should offer to
2377 detach instead of killing it when bailing out). */
2378
6b8edb51
PA
2379int
2380remote_target::remote_query_attached (int pid)
0b16c5cf
PA
2381{
2382 struct remote_state *rs = get_remote_state ();
bba74b36 2383 size_t size = get_remote_packet_size ();
0b16c5cf 2384
4082afcc 2385 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
2386 return 0;
2387
2388 if (remote_multi_process_p (rs))
8d64371b 2389 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
0b16c5cf 2390 else
8d64371b 2391 xsnprintf (rs->buf.data (), size, "qAttached");
0b16c5cf
PA
2392
2393 putpkt (rs->buf);
8d64371b 2394 getpkt (&rs->buf, 0);
0b16c5cf
PA
2395
2396 switch (packet_ok (rs->buf,
1554e9be 2397 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
2398 {
2399 case PACKET_OK:
8d64371b 2400 if (strcmp (rs->buf.data (), "1") == 0)
0b16c5cf
PA
2401 return 1;
2402 break;
2403 case PACKET_ERROR:
8d64371b 2404 warning (_("Remote failure reply: %s"), rs->buf.data ());
0b16c5cf
PA
2405 break;
2406 case PACKET_UNKNOWN:
2407 break;
2408 }
2409
2410 return 0;
2411}
2412
49c62f2e
PA
2413/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2414 has been invented by GDB, instead of reported by the target. Since
2415 we can be connected to a remote system before before knowing about
2416 any inferior, mark the target with execution when we find the first
2417 inferior. If ATTACHED is 1, then we had just attached to this
2418 inferior. If it is 0, then we just created this inferior. If it
2419 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
2420 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2421 attempt to open this inferior's executable as the main executable
2422 if no main executable is open already. */
1941c569 2423
6b8edb51 2424inferior *
9ab8741a 2425remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
6b8edb51 2426 int try_open_exec)
1941c569 2427{
1941c569
PA
2428 struct inferior *inf;
2429
0b16c5cf
PA
2430 /* Check whether this process we're learning about is to be
2431 considered attached, or if is to be considered to have been
2432 spawned by the stub. */
2433 if (attached == -1)
2434 attached = remote_query_attached (pid);
2435
f5656ead 2436 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
2437 {
2438 /* If the target shares code across all inferiors, then every
2439 attach adds a new inferior. */
2440 inf = add_inferior (pid);
2441
2442 /* ... and every inferior is bound to the same program space.
2443 However, each inferior may still have its own address
2444 space. */
2445 inf->aspace = maybe_new_address_space ();
2446 inf->pspace = current_program_space;
2447 }
2448 else
2449 {
2450 /* In the traditional debugging scenario, there's a 1-1 match
2451 between program/address spaces. We simply bind the inferior
2452 to the program space's address space. */
2453 inf = current_inferior ();
78f2c40a
PA
2454
2455 /* However, if the current inferior is already bound to a
2456 process, find some other empty inferior. */
2457 if (inf->pid != 0)
2458 {
2459 inf = nullptr;
2460 for (inferior *it : all_inferiors ())
2461 if (it->pid == 0)
2462 {
2463 inf = it;
2464 break;
2465 }
2466 }
2467 if (inf == nullptr)
2468 {
2469 /* Since all inferiors were already bound to a process, add
2470 a new inferior. */
2471 inf = add_inferior_with_spaces ();
2472 }
2473 switch_to_inferior_no_thread (inf);
5b6d1e4f 2474 push_target (this);
6c95b8df
PA
2475 inferior_appeared (inf, pid);
2476 }
1941c569 2477
0b16c5cf 2478 inf->attach_flag = attached;
49c62f2e 2479 inf->fake_pid_p = fake_pid_p;
0b16c5cf 2480
1b6e6f5c
GB
2481 /* If no main executable is currently open then attempt to
2482 open the file that was executed to create this inferior. */
835205d0 2483 if (try_open_exec && get_exec_file (0) == NULL)
bb805577 2484 exec_file_locate_attach (pid, 0, 1);
1b6e6f5c 2485
a2fedca9
PW
2486 /* Check for exec file mismatch, and let the user solve it. */
2487 validate_exec_file (1);
2488
1941c569
PA
2489 return inf;
2490}
2491
7aabaf9d 2492static remote_thread_info *get_remote_thread_info (thread_info *thread);
5b6d1e4f
PA
2493static remote_thread_info *get_remote_thread_info (remote_target *target,
2494 ptid_t ptid);
85ad3aaf 2495
1941c569
PA
2496/* Add thread PTID to GDB's thread list. Tag it as executing/running
2497 according to RUNNING. */
2498
00431a78 2499thread_info *
6b8edb51 2500remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing)
c906108c 2501{
b7ea362b 2502 struct remote_state *rs = get_remote_state ();
85ad3aaf 2503 struct thread_info *thread;
b7ea362b
PA
2504
2505 /* GDB historically didn't pull threads in the initial connection
2506 setup. If the remote target doesn't even have a concept of
2507 threads (e.g., a bare-metal target), even if internally we
2508 consider that a single-threaded target, mentioning a new thread
2509 might be confusing to the user. Be silent then, preserving the
2510 age old behavior. */
2511 if (rs->starting_up)
5b6d1e4f 2512 thread = add_thread_silent (this, ptid);
b7ea362b 2513 else
5b6d1e4f 2514 thread = add_thread (this, ptid);
1941c569 2515
c9d22089
SM
2516 /* We start by assuming threads are resumed. That state then gets updated
2517 when we process a matching stop reply. */
2518 get_remote_thread_info (thread)->set_resumed ();
2519
5b6d1e4f
PA
2520 set_executing (this, ptid, executing);
2521 set_running (this, ptid, running);
00431a78
PA
2522
2523 return thread;
1941c569
PA
2524}
2525
2526/* Come here when we learn about a thread id from the remote target.
2527 It may be the first time we hear about such thread, so take the
2528 opportunity to add it to GDB's thread list. In case this is the
2529 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
2530 GDB's inferior list as well. EXECUTING indicates whether the
2531 thread is (internally) executing or stopped. */
1941c569 2532
6b8edb51
PA
2533void
2534remote_target::remote_notice_new_inferior (ptid_t currthread, int executing)
1941c569 2535{
0d5b594f
PA
2536 /* In non-stop mode, we assume new found threads are (externally)
2537 running until proven otherwise with a stop reply. In all-stop,
2538 we can only get here if all threads are stopped. */
2539 int running = target_is_non_stop_p () ? 1 : 0;
2540
c906108c
SS
2541 /* If this is a new thread, add it to GDB's thread list.
2542 If we leave it up to WFI to do this, bad things will happen. */
82f73884 2543
5b6d1e4f 2544 thread_info *tp = find_thread_ptid (this, currthread);
00431a78 2545 if (tp != NULL && tp->state == THREAD_EXITED)
82f73884
PA
2546 {
2547 /* We're seeing an event on a thread id we knew had exited.
2548 This has to be a new thread reusing the old id. Add it. */
0d5b594f 2549 remote_add_thread (currthread, running, executing);
82f73884
PA
2550 return;
2551 }
2552
5b6d1e4f 2553 if (!in_thread_list (this, currthread))
c0a2216e 2554 {
1941c569 2555 struct inferior *inf = NULL;
e99b03dc 2556 int pid = currthread.pid ();
1941c569 2557
0e998d96 2558 if (inferior_ptid.is_pid ()
e99b03dc 2559 && pid == inferior_ptid.pid ())
c0a2216e
PA
2560 {
2561 /* inferior_ptid has no thread member yet. This can happen
2562 with the vAttach -> remote_wait,"TAAthread:" path if the
2563 stub doesn't support qC. This is the first stop reported
2564 after an attach, so this is the main thread. Update the
2565 ptid in the thread list. */
5b6d1e4f
PA
2566 if (in_thread_list (this, ptid_t (pid)))
2567 thread_change_ptid (this, inferior_ptid, currthread);
bad34192
PA
2568 else
2569 {
0ac55310
PA
2570 thread_info *thr
2571 = remote_add_thread (currthread, running, executing);
2572 switch_to_thread (thr);
bad34192 2573 }
dc146f7c 2574 return;
c0a2216e 2575 }
82f73884 2576
d7e15655 2577 if (magic_null_ptid == inferior_ptid)
c0a2216e
PA
2578 {
2579 /* inferior_ptid is not set yet. This can happen with the
2580 vRun -> remote_wait,"TAAthread:" path if the stub
2581 doesn't support qC. This is the first stop reported
2582 after an attach, so this is the main thread. Update the
2583 ptid in the thread list. */
5b6d1e4f 2584 thread_change_ptid (this, inferior_ptid, currthread);
82f73884 2585 return;
c0a2216e 2586 }
82f73884 2587
29c87f7f
PA
2588 /* When connecting to a target remote, or to a target
2589 extended-remote which already was debugging an inferior, we
2590 may not know about it yet. Add it before adding its child
2591 thread, so notifications are emitted in a sensible order. */
5b6d1e4f 2592 if (find_inferior_pid (this, currthread.pid ()) == NULL)
49c62f2e
PA
2593 {
2594 struct remote_state *rs = get_remote_state ();
9ab8741a 2595 bool fake_pid_p = !remote_multi_process_p (rs);
49c62f2e
PA
2596
2597 inf = remote_add_inferior (fake_pid_p,
e99b03dc 2598 currthread.pid (), -1, 1);
49c62f2e 2599 }
29c87f7f 2600
82f73884 2601 /* This is really a new thread. Add it. */
00431a78
PA
2602 thread_info *new_thr
2603 = remote_add_thread (currthread, running, executing);
1941c569
PA
2604
2605 /* If we found a new inferior, let the common code do whatever
2606 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
2607 breakpoints), unless we're just setting up an all-stop
2608 connection. */
1941c569 2609 if (inf != NULL)
b7ea362b
PA
2610 {
2611 struct remote_state *rs = get_remote_state ();
2612
6efcd9a8 2613 if (!rs->starting_up)
00431a78 2614 notice_new_inferior (new_thr, executing, 0);
b7ea362b 2615 }
c0a2216e 2616 }
c906108c
SS
2617}
2618
85ad3aaf 2619/* Return THREAD's private thread data, creating it if necessary. */
dc146f7c 2620
7aabaf9d
SM
2621static remote_thread_info *
2622get_remote_thread_info (thread_info *thread)
dc146f7c 2623{
85ad3aaf 2624 gdb_assert (thread != NULL);
dc146f7c 2625
85ad3aaf 2626 if (thread->priv == NULL)
7aabaf9d 2627 thread->priv.reset (new remote_thread_info);
dc146f7c 2628
7aabaf9d 2629 return static_cast<remote_thread_info *> (thread->priv.get ());
85ad3aaf
PA
2630}
2631
5b6d1e4f
PA
2632/* Return PTID's private thread data, creating it if necessary. */
2633
7aabaf9d 2634static remote_thread_info *
5b6d1e4f 2635get_remote_thread_info (remote_target *target, ptid_t ptid)
85ad3aaf 2636{
5b6d1e4f 2637 thread_info *thr = find_thread_ptid (target, ptid);
00431a78 2638 return get_remote_thread_info (thr);
dc146f7c
VP
2639}
2640
74531fed
PA
2641/* Call this function as a result of
2642 1) A halt indication (T packet) containing a thread id
2643 2) A direct query of currthread
0df8b418 2644 3) Successful execution of set thread */
74531fed
PA
2645
2646static void
47f8a51d 2647record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 2648{
47f8a51d 2649 rs->general_thread = currthread;
74531fed
PA
2650}
2651
89be2091
DJ
2652/* If 'QPassSignals' is supported, tell the remote stub what signals
2653 it can simply pass through to the inferior without reporting. */
2654
f6ac5f3d 2655void
adc6a863 2656remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
89be2091 2657{
4082afcc 2658 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
2659 {
2660 char *pass_packet, *p;
adc6a863 2661 int count = 0;
747dc59d 2662 struct remote_state *rs = get_remote_state ();
89be2091 2663
adc6a863
PA
2664 gdb_assert (pass_signals.size () < 256);
2665 for (size_t i = 0; i < pass_signals.size (); i++)
89be2091 2666 {
2455069d 2667 if (pass_signals[i])
89be2091
DJ
2668 count++;
2669 }
224c3ddb 2670 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
2671 strcpy (pass_packet, "QPassSignals:");
2672 p = pass_packet + strlen (pass_packet);
adc6a863 2673 for (size_t i = 0; i < pass_signals.size (); i++)
89be2091 2674 {
2455069d 2675 if (pass_signals[i])
89be2091
DJ
2676 {
2677 if (i >= 16)
2678 *p++ = tohex (i >> 4);
2679 *p++ = tohex (i & 15);
2680 if (count)
2681 *p++ = ';';
2682 else
2683 break;
2684 count--;
2685 }
2686 }
2687 *p = 0;
747dc59d 2688 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 2689 {
89be2091 2690 putpkt (pass_packet);
8d64371b 2691 getpkt (&rs->buf, 0);
8dc5b319 2692 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
84d53fa9 2693 xfree (rs->last_pass_packet);
747dc59d 2694 rs->last_pass_packet = pass_packet;
89be2091
DJ
2695 }
2696 else
2697 xfree (pass_packet);
2698 }
2699}
2700
82075af2
JS
2701/* If 'QCatchSyscalls' is supported, tell the remote stub
2702 to report syscalls to GDB. */
2703
f6ac5f3d
PA
2704int
2705remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2706 gdb::array_view<const int> syscall_counts)
82075af2 2707{
b80406ac 2708 const char *catch_packet;
82075af2
JS
2709 enum packet_result result;
2710 int n_sysno = 0;
2711
2712 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2713 {
2714 /* Not supported. */
2715 return 1;
2716 }
2717
649a140c 2718 if (needed && any_count == 0)
82075af2 2719 {
649a140c
PA
2720 /* Count how many syscalls are to be caught. */
2721 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2722 {
649a140c 2723 if (syscall_counts[i] != 0)
82075af2
JS
2724 n_sysno++;
2725 }
2726 }
2727
2728 if (remote_debug)
2729 {
2730 fprintf_unfiltered (gdb_stdlog,
2731 "remote_set_syscall_catchpoint "
2732 "pid %d needed %d any_count %d n_sysno %d\n",
2733 pid, needed, any_count, n_sysno);
2734 }
2735
1b81856f 2736 std::string built_packet;
82075af2
JS
2737 if (needed)
2738 {
2739 /* Prepare a packet with the sysno list, assuming max 8+1
2740 characters for a sysno. If the resulting packet size is too
2741 big, fallback on the non-selective packet. */
2742 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
1b81856f
PA
2743 built_packet.reserve (maxpktsz);
2744 built_packet = "QCatchSyscalls:1";
649a140c 2745 if (any_count == 0)
82075af2 2746 {
649a140c
PA
2747 /* Add in each syscall to be caught. */
2748 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2749 {
649a140c
PA
2750 if (syscall_counts[i] != 0)
2751 string_appendf (built_packet, ";%zx", i);
82075af2
JS
2752 }
2753 }
1b81856f 2754 if (built_packet.size () > get_remote_packet_size ())
82075af2
JS
2755 {
2756 /* catch_packet too big. Fallback to less efficient
2757 non selective mode, with GDB doing the filtering. */
b80406ac 2758 catch_packet = "QCatchSyscalls:1";
82075af2 2759 }
b80406ac 2760 else
1b81856f 2761 catch_packet = built_packet.c_str ();
82075af2
JS
2762 }
2763 else
b80406ac 2764 catch_packet = "QCatchSyscalls:0";
82075af2 2765
b80406ac 2766 struct remote_state *rs = get_remote_state ();
82075af2 2767
b80406ac 2768 putpkt (catch_packet);
8d64371b 2769 getpkt (&rs->buf, 0);
b80406ac
TT
2770 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2771 if (result == PACKET_OK)
2772 return 0;
2773 else
2774 return -1;
82075af2
JS
2775}
2776
9b224c5e
PA
2777/* If 'QProgramSignals' is supported, tell the remote stub what
2778 signals it should pass through to the inferior when detaching. */
2779
f6ac5f3d 2780void
adc6a863 2781remote_target::program_signals (gdb::array_view<const unsigned char> signals)
9b224c5e 2782{
4082afcc 2783 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
2784 {
2785 char *packet, *p;
adc6a863 2786 int count = 0;
5e4a05c4 2787 struct remote_state *rs = get_remote_state ();
9b224c5e 2788
adc6a863
PA
2789 gdb_assert (signals.size () < 256);
2790 for (size_t i = 0; i < signals.size (); i++)
9b224c5e
PA
2791 {
2792 if (signals[i])
2793 count++;
2794 }
224c3ddb 2795 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2796 strcpy (packet, "QProgramSignals:");
2797 p = packet + strlen (packet);
adc6a863 2798 for (size_t i = 0; i < signals.size (); i++)
9b224c5e
PA
2799 {
2800 if (signal_pass_state (i))
2801 {
2802 if (i >= 16)
2803 *p++ = tohex (i >> 4);
2804 *p++ = tohex (i & 15);
2805 if (count)
2806 *p++ = ';';
2807 else
2808 break;
2809 count--;
2810 }
2811 }
2812 *p = 0;
5e4a05c4
TT
2813 if (!rs->last_program_signals_packet
2814 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2815 {
9b224c5e 2816 putpkt (packet);
8d64371b 2817 getpkt (&rs->buf, 0);
8dc5b319 2818 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2819 xfree (rs->last_program_signals_packet);
2820 rs->last_program_signals_packet = packet;
9b224c5e
PA
2821 }
2822 else
2823 xfree (packet);
2824 }
2825}
2826
79d7f229
PA
2827/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2828 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2829 thread. If GEN is set, set the general thread, if not, then set
2830 the step/continue thread. */
6b8edb51
PA
2831void
2832remote_target::set_thread (ptid_t ptid, int gen)
c906108c 2833{
d01949b6 2834 struct remote_state *rs = get_remote_state ();
47f8a51d 2835 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
8d64371b
TT
2836 char *buf = rs->buf.data ();
2837 char *endbuf = buf + get_remote_packet_size ();
c906108c 2838
d7e15655 2839 if (state == ptid)
c906108c
SS
2840 return;
2841
79d7f229
PA
2842 *buf++ = 'H';
2843 *buf++ = gen ? 'g' : 'c';
d7e15655 2844 if (ptid == magic_null_ptid)
79d7f229 2845 xsnprintf (buf, endbuf - buf, "0");
d7e15655 2846 else if (ptid == any_thread_ptid)
79d7f229 2847 xsnprintf (buf, endbuf - buf, "0");
d7e15655 2848 else if (ptid == minus_one_ptid)
79d7f229
PA
2849 xsnprintf (buf, endbuf - buf, "-1");
2850 else
82f73884 2851 write_ptid (buf, endbuf, ptid);
79d7f229 2852 putpkt (rs->buf);
8d64371b 2853 getpkt (&rs->buf, 0);
c906108c 2854 if (gen)
47f8a51d 2855 rs->general_thread = ptid;
c906108c 2856 else
47f8a51d 2857 rs->continue_thread = ptid;
c906108c 2858}
79d7f229 2859
6b8edb51
PA
2860void
2861remote_target::set_general_thread (ptid_t ptid)
79d7f229
PA
2862{
2863 set_thread (ptid, 1);
2864}
2865
6b8edb51
PA
2866void
2867remote_target::set_continue_thread (ptid_t ptid)
79d7f229
PA
2868{
2869 set_thread (ptid, 0);
2870}
2871
3c9c4b83
PA
2872/* Change the remote current process. Which thread within the process
2873 ends up selected isn't important, as long as it is the same process
2874 as what INFERIOR_PTID points to.
2875
2876 This comes from that fact that there is no explicit notion of
2877 "selected process" in the protocol. The selected process for
2878 general operations is the process the selected general thread
2879 belongs to. */
2880
6b8edb51
PA
2881void
2882remote_target::set_general_process ()
3c9c4b83
PA
2883{
2884 struct remote_state *rs = get_remote_state ();
2885
2886 /* If the remote can't handle multiple processes, don't bother. */
8020350c 2887 if (!remote_multi_process_p (rs))
3c9c4b83
PA
2888 return;
2889
2890 /* We only need to change the remote current thread if it's pointing
2891 at some other process. */
e99b03dc 2892 if (rs->general_thread.pid () != inferior_ptid.pid ())
3c9c4b83
PA
2893 set_general_thread (inferior_ptid);
2894}
2895
c906108c 2896\f
7d1a114c
PA
2897/* Return nonzero if this is the main thread that we made up ourselves
2898 to model non-threaded targets as single-threaded. */
c906108c
SS
2899
2900static int
f6ac5f3d 2901remote_thread_always_alive (ptid_t ptid)
c906108c 2902{
d7e15655 2903 if (ptid == magic_null_ptid)
c0a2216e
PA
2904 /* The main thread is always alive. */
2905 return 1;
2906
e38504b3 2907 if (ptid.pid () != 0 && ptid.lwp () == 0)
c0a2216e
PA
2908 /* The main thread is always alive. This can happen after a
2909 vAttach, if the remote side doesn't support
2910 multi-threading. */
2911 return 1;
2912
7d1a114c
PA
2913 return 0;
2914}
2915
2916/* Return nonzero if the thread PTID is still alive on the remote
2917 system. */
2918
57810aa7 2919bool
f6ac5f3d 2920remote_target::thread_alive (ptid_t ptid)
7d1a114c
PA
2921{
2922 struct remote_state *rs = get_remote_state ();
2923 char *p, *endp;
2924
2925 /* Check if this is a thread that we made up ourselves to model
2926 non-threaded targets as single-threaded. */
f6ac5f3d 2927 if (remote_thread_always_alive (ptid))
7d1a114c
PA
2928 return 1;
2929
8d64371b
TT
2930 p = rs->buf.data ();
2931 endp = p + get_remote_packet_size ();
82f73884
PA
2932
2933 *p++ = 'T';
2934 write_ptid (p, endp, ptid);
2935
2e9f7625 2936 putpkt (rs->buf);
8d64371b 2937 getpkt (&rs->buf, 0);
2e9f7625 2938 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2939}
2940
79efa585
SM
2941/* Return a pointer to a thread name if we know it and NULL otherwise.
2942 The thread_info object owns the memory for the name. */
2943
f6ac5f3d
PA
2944const char *
2945remote_target::thread_name (struct thread_info *info)
79efa585
SM
2946{
2947 if (info->priv != NULL)
a9334058
SM
2948 {
2949 const std::string &name = get_remote_thread_info (info)->name;
2950 return !name.empty () ? name.c_str () : NULL;
2951 }
79efa585
SM
2952
2953 return NULL;
2954}
2955
c906108c
SS
2956/* About these extended threadlist and threadinfo packets. They are
2957 variable length packets but, the fields within them are often fixed
30baf67b 2958 length. They are redundant enough to send over UDP as is the
c906108c
SS
2959 remote protocol in general. There is a matching unit test module
2960 in libstub. */
2961
23860348 2962/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2963 libstub protocol encoding, and remote.c. It is not particularly
23860348 2964 changable. */
cce74817
JM
2965
2966/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2967 Plan to fix this. */
cce74817 2968
23860348 2969typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2970
9d1f7ab2 2971/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2972 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2973
2974struct gdb_ext_thread_info
c5aa993b 2975 {
23860348 2976 threadref threadid; /* External form of thread reference. */
2bc416ba 2977 int active; /* Has state interesting to GDB?
23860348 2978 regs, stack. */
2bc416ba 2979 char display[256]; /* Brief state display, name,
cedea757 2980 blocked/suspended. */
23860348 2981 char shortname[32]; /* To be used to name threads. */
2bc416ba 2982 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2983 whatever. */
c5aa993b 2984 };
cce74817
JM
2985
2986/* The volume of remote transfers can be limited by submitting
2987 a mask containing bits specifying the desired information.
2988 Use a union of these values as the 'selection' parameter to
0df8b418 2989 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2990
2991#define TAG_THREADID 1
2992#define TAG_EXISTS 2
2993#define TAG_DISPLAY 4
2994#define TAG_THREADNAME 8
c5aa993b 2995#define TAG_MOREDISPLAY 16
cce74817 2996
23860348 2997#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2998
a14ed312 2999static char *unpack_nibble (char *buf, int *val);
cce74817 3000
a14ed312 3001static char *unpack_byte (char *buf, int *value);
cce74817 3002
a14ed312 3003static char *pack_int (char *buf, int value);
cce74817 3004
a14ed312 3005static char *unpack_int (char *buf, int *value);
cce74817 3006
a14ed312 3007static char *unpack_string (char *src, char *dest, int length);
cce74817 3008
23860348 3009static char *pack_threadid (char *pkt, threadref *id);
cce74817 3010
23860348 3011static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 3012
23860348 3013void int_to_threadref (threadref *id, int value);
cce74817 3014
23860348 3015static int threadref_to_int (threadref *ref);
cce74817 3016
23860348 3017static void copy_threadref (threadref *dest, threadref *src);
cce74817 3018
23860348 3019static int threadmatch (threadref *dest, threadref *src);
cce74817 3020
2bc416ba 3021static char *pack_threadinfo_request (char *pkt, int mode,
23860348 3022 threadref *id);
cce74817 3023
a14ed312
KB
3024static char *pack_threadlist_request (char *pkt, int startflag,
3025 int threadcount,
23860348 3026 threadref *nextthread);
cce74817 3027
23860348 3028static int remote_newthread_step (threadref *ref, void *context);
cce74817 3029
82f73884
PA
3030
3031/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3032 buffer we're allowed to write to. Returns
3033 BUF+CHARACTERS_WRITTEN. */
3034
6b8edb51
PA
3035char *
3036remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
82f73884
PA
3037{
3038 int pid, tid;
3039 struct remote_state *rs = get_remote_state ();
3040
3041 if (remote_multi_process_p (rs))
3042 {
e99b03dc 3043 pid = ptid.pid ();
82f73884
PA
3044 if (pid < 0)
3045 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3046 else
3047 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3048 }
e38504b3 3049 tid = ptid.lwp ();
82f73884
PA
3050 if (tid < 0)
3051 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3052 else
3053 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3054
3055 return buf;
3056}
3057
256642e8
PA
3058/* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3059 last parsed char. Returns null_ptid if no thread id is found, and
3060 throws an error if the thread id has an invalid format. */
82f73884
PA
3061
3062static ptid_t
256642e8 3063read_ptid (const char *buf, const char **obuf)
82f73884 3064{
256642e8
PA
3065 const char *p = buf;
3066 const char *pp;
82f73884 3067 ULONGEST pid = 0, tid = 0;
82f73884
PA
3068
3069 if (*p == 'p')
3070 {
3071 /* Multi-process ptid. */
3072 pp = unpack_varlen_hex (p + 1, &pid);
3073 if (*pp != '.')
b37520b6 3074 error (_("invalid remote ptid: %s"), p);
82f73884
PA
3075
3076 p = pp;
3077 pp = unpack_varlen_hex (p + 1, &tid);
3078 if (obuf)
3079 *obuf = pp;
fd79271b 3080 return ptid_t (pid, tid, 0);
82f73884
PA
3081 }
3082
3083 /* No multi-process. Just a tid. */
3084 pp = unpack_varlen_hex (p, &tid);
3085
c9f35b34
KB
3086 /* Return null_ptid when no thread id is found. */
3087 if (p == pp)
3088 {
3089 if (obuf)
3090 *obuf = pp;
3091 return null_ptid;
3092 }
3093
82f73884 3094 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
3095 what's in inferior_ptid, unless it's null at this point. If so,
3096 then since there's no way to know the pid of the reported
3097 threads, use the magic number. */
d7e15655 3098 if (inferior_ptid == null_ptid)
e99b03dc 3099 pid = magic_null_ptid.pid ();
ca19bf23 3100 else
e99b03dc 3101 pid = inferior_ptid.pid ();
82f73884
PA
3102
3103 if (obuf)
3104 *obuf = pp;
fd79271b 3105 return ptid_t (pid, tid, 0);
82f73884
PA
3106}
3107
c906108c 3108static int
fba45db2 3109stubhex (int ch)
c906108c
SS
3110{
3111 if (ch >= 'a' && ch <= 'f')
3112 return ch - 'a' + 10;
3113 if (ch >= '0' && ch <= '9')
3114 return ch - '0';
3115 if (ch >= 'A' && ch <= 'F')
3116 return ch - 'A' + 10;
3117 return -1;
3118}
3119
3120static int
fba45db2 3121stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
3122{
3123 int nibble;
3124 int retval = 0;
3125
3126 while (fieldlength)
3127 {
3128 nibble = stubhex (*buff++);
3129 retval |= nibble;
3130 fieldlength--;
3131 if (fieldlength)
3132 retval = retval << 4;
3133 }
3134 return retval;
3135}
3136
c906108c 3137static char *
fba45db2 3138unpack_nibble (char *buf, int *val)
c906108c 3139{
b7589f7d 3140 *val = fromhex (*buf++);
c906108c
SS
3141 return buf;
3142}
3143
c906108c 3144static char *
fba45db2 3145unpack_byte (char *buf, int *value)
c906108c
SS
3146{
3147 *value = stub_unpack_int (buf, 2);
3148 return buf + 2;
3149}
3150
3151static char *
fba45db2 3152pack_int (char *buf, int value)
c906108c
SS
3153{
3154 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3155 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3156 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3157 buf = pack_hex_byte (buf, (value & 0xff));
3158 return buf;
3159}
3160
3161static char *
fba45db2 3162unpack_int (char *buf, int *value)
c906108c
SS
3163{
3164 *value = stub_unpack_int (buf, 8);
3165 return buf + 8;
3166}
3167
23860348 3168#if 0 /* Currently unused, uncomment when needed. */
a14ed312 3169static char *pack_string (char *pkt, char *string);
c906108c
SS
3170
3171static char *
fba45db2 3172pack_string (char *pkt, char *string)
c906108c
SS
3173{
3174 char ch;
3175 int len;
3176
3177 len = strlen (string);
3178 if (len > 200)
23860348 3179 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
3180 pkt = pack_hex_byte (pkt, len);
3181 while (len-- > 0)
3182 {
3183 ch = *string++;
3184 if ((ch == '\0') || (ch == '#'))
23860348 3185 ch = '*'; /* Protect encapsulation. */
c906108c
SS
3186 *pkt++ = ch;
3187 }
3188 return pkt;
3189}
3190#endif /* 0 (unused) */
3191
3192static char *
fba45db2 3193unpack_string (char *src, char *dest, int length)
c906108c
SS
3194{
3195 while (length--)
3196 *dest++ = *src++;
3197 *dest = '\0';
3198 return src;
3199}
3200
3201static char *
fba45db2 3202pack_threadid (char *pkt, threadref *id)
c906108c
SS
3203{
3204 char *limit;
3205 unsigned char *altid;
3206
3207 altid = (unsigned char *) id;
3208 limit = pkt + BUF_THREAD_ID_SIZE;
3209 while (pkt < limit)
3210 pkt = pack_hex_byte (pkt, *altid++);
3211 return pkt;
3212}
3213
3214
3215static char *
fba45db2 3216unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
3217{
3218 char *altref;
3219 char *limit = inbuf + BUF_THREAD_ID_SIZE;
3220 int x, y;
3221
3222 altref = (char *) id;
3223
3224 while (inbuf < limit)
3225 {
3226 x = stubhex (*inbuf++);
3227 y = stubhex (*inbuf++);
3228 *altref++ = (x << 4) | y;
3229 }
3230 return inbuf;
3231}
3232
3233/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 3234 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
3235 to use 64bit thread references internally. This is an adapter
3236 function. */
3237
3238void
fba45db2 3239int_to_threadref (threadref *id, int value)
c906108c
SS
3240{
3241 unsigned char *scan;
3242
3243 scan = (unsigned char *) id;
3244 {
3245 int i = 4;
3246 while (i--)
3247 *scan++ = 0;
3248 }
3249 *scan++ = (value >> 24) & 0xff;
3250 *scan++ = (value >> 16) & 0xff;
3251 *scan++ = (value >> 8) & 0xff;
3252 *scan++ = (value & 0xff);
3253}
3254
3255static int
fba45db2 3256threadref_to_int (threadref *ref)
c906108c
SS
3257{
3258 int i, value = 0;
3259 unsigned char *scan;
3260
cfd77fa1 3261 scan = *ref;
c906108c
SS
3262 scan += 4;
3263 i = 4;
3264 while (i-- > 0)
3265 value = (value << 8) | ((*scan++) & 0xff);
3266 return value;
3267}
3268
3269static void
fba45db2 3270copy_threadref (threadref *dest, threadref *src)
c906108c
SS
3271{
3272 int i;
3273 unsigned char *csrc, *cdest;
3274
3275 csrc = (unsigned char *) src;
3276 cdest = (unsigned char *) dest;
3277 i = 8;
3278 while (i--)
3279 *cdest++ = *csrc++;
3280}
3281
3282static int
fba45db2 3283threadmatch (threadref *dest, threadref *src)
c906108c 3284{
23860348 3285 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
3286#if 0
3287 unsigned char *srcp, *destp;
3288 int i, result;
3289 srcp = (char *) src;
3290 destp = (char *) dest;
3291
3292 result = 1;
3293 while (i-- > 0)
3294 result &= (*srcp++ == *destp++) ? 1 : 0;
3295 return result;
3296#endif
3297 return 1;
3298}
3299
3300/*
c5aa993b
JM
3301 threadid:1, # always request threadid
3302 context_exists:2,
3303 display:4,
3304 unique_name:8,
3305 more_display:16
3306 */
c906108c
SS
3307
3308/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3309
3310static char *
fba45db2 3311pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 3312{
23860348
MS
3313 *pkt++ = 'q'; /* Info Query */
3314 *pkt++ = 'P'; /* process or thread info */
3315 pkt = pack_int (pkt, mode); /* mode */
c906108c 3316 pkt = pack_threadid (pkt, id); /* threadid */
23860348 3317 *pkt = '\0'; /* terminate */
c906108c
SS
3318 return pkt;
3319}
3320
23860348 3321/* These values tag the fields in a thread info response packet. */
c906108c 3322/* Tagging the fields allows us to request specific fields and to
23860348 3323 add more fields as time goes by. */
c906108c 3324
23860348 3325#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 3326#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 3327 fetch registers and its stack? */
c5aa993b 3328#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 3329#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 3330#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 3331 the process. */
c906108c 3332
6b8edb51
PA
3333int
3334remote_target::remote_unpack_thread_info_response (char *pkt,
3335 threadref *expectedref,
3336 gdb_ext_thread_info *info)
c906108c 3337{
d01949b6 3338 struct remote_state *rs = get_remote_state ();
c906108c 3339 int mask, length;
cfd77fa1 3340 int tag;
c906108c 3341 threadref ref;
8d64371b 3342 char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
c906108c
SS
3343 int retval = 1;
3344
23860348 3345 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
3346 info->active = 0;
3347 info->display[0] = '\0';
3348 info->shortname[0] = '\0';
3349 info->more_display[0] = '\0';
3350
23860348
MS
3351 /* Assume the characters indicating the packet type have been
3352 stripped. */
c906108c
SS
3353 pkt = unpack_int (pkt, &mask); /* arg mask */
3354 pkt = unpack_threadid (pkt, &ref);
3355
3356 if (mask == 0)
8a3fe4f8 3357 warning (_("Incomplete response to threadinfo request."));
c906108c 3358 if (!threadmatch (&ref, expectedref))
23860348 3359 { /* This is an answer to a different request. */
8a3fe4f8 3360 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
3361 return 0;
3362 }
3363 copy_threadref (&info->threadid, &ref);
3364
405feb71 3365 /* Loop on tagged fields , try to bail if something goes wrong. */
c906108c 3366
23860348
MS
3367 /* Packets are terminated with nulls. */
3368 while ((pkt < limit) && mask && *pkt)
c906108c
SS
3369 {
3370 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
3371 pkt = unpack_byte (pkt, &length); /* length */
3372 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 3373 {
8a3fe4f8 3374 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
3375 retval = 0;
3376 break;
3377 }
3378 if (tag == TAG_THREADID)
3379 {
3380 if (length != 16)
3381 {
8a3fe4f8 3382 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
3383 retval = 0;
3384 break;
3385 }
3386 pkt = unpack_threadid (pkt, &ref);
3387 mask = mask & ~TAG_THREADID;
3388 continue;
3389 }
3390 if (tag == TAG_EXISTS)
3391 {
3392 info->active = stub_unpack_int (pkt, length);
3393 pkt += length;
3394 mask = mask & ~(TAG_EXISTS);
3395 if (length > 8)
3396 {
8a3fe4f8 3397 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
3398 retval = 0;
3399 break;
3400 }
3401 continue;
3402 }
3403 if (tag == TAG_THREADNAME)
3404 {
3405 pkt = unpack_string (pkt, &info->shortname[0], length);
3406 mask = mask & ~TAG_THREADNAME;
3407 continue;
3408 }
3409 if (tag == TAG_DISPLAY)
3410 {
3411 pkt = unpack_string (pkt, &info->display[0], length);
3412 mask = mask & ~TAG_DISPLAY;
3413 continue;
3414 }
3415 if (tag == TAG_MOREDISPLAY)
3416 {
3417 pkt = unpack_string (pkt, &info->more_display[0], length);
3418 mask = mask & ~TAG_MOREDISPLAY;
3419 continue;
3420 }
8a3fe4f8 3421 warning (_("ERROR RMT: unknown thread info tag."));
23860348 3422 break; /* Not a tag we know about. */
c906108c
SS
3423 }
3424 return retval;
3425}
3426
6b8edb51
PA
3427int
3428remote_target::remote_get_threadinfo (threadref *threadid,
3429 int fieldset,
3430 gdb_ext_thread_info *info)
c906108c 3431{
d01949b6 3432 struct remote_state *rs = get_remote_state ();
c906108c 3433 int result;
c906108c 3434
8d64371b 3435 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
2e9f7625 3436 putpkt (rs->buf);
8d64371b 3437 getpkt (&rs->buf, 0);
3084dd77
PA
3438
3439 if (rs->buf[0] == '\0')
3440 return 0;
3441
8d64371b 3442 result = remote_unpack_thread_info_response (&rs->buf[2],
23860348 3443 threadid, info);
c906108c
SS
3444 return result;
3445}
3446
c906108c
SS
3447/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3448
3449static char *
fba45db2
KB
3450pack_threadlist_request (char *pkt, int startflag, int threadcount,
3451 threadref *nextthread)
c906108c
SS
3452{
3453 *pkt++ = 'q'; /* info query packet */
3454 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 3455 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
3456 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3457 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3458 *pkt = '\0';
3459 return pkt;
3460}
3461
3462/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3463
6b8edb51
PA
3464int
3465remote_target::parse_threadlist_response (char *pkt, int result_limit,
3466 threadref *original_echo,
3467 threadref *resultlist,
3468 int *doneflag)
c906108c 3469{
d01949b6 3470 struct remote_state *rs = get_remote_state ();
c906108c
SS
3471 char *limit;
3472 int count, resultcount, done;
3473
3474 resultcount = 0;
3475 /* Assume the 'q' and 'M chars have been stripped. */
8d64371b 3476 limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
23860348 3477 /* done parse past here */
c906108c
SS
3478 pkt = unpack_byte (pkt, &count); /* count field */
3479 pkt = unpack_nibble (pkt, &done);
3480 /* The first threadid is the argument threadid. */
3481 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3482 while ((count-- > 0) && (pkt < limit))
3483 {
3484 pkt = unpack_threadid (pkt, resultlist++);
3485 if (resultcount++ >= result_limit)
3486 break;
3487 }
3488 if (doneflag)
3489 *doneflag = done;
3490 return resultcount;
3491}
3492
6dc54d91
PA
3493/* Fetch the next batch of threads from the remote. Returns -1 if the
3494 qL packet is not supported, 0 on error and 1 on success. */
3495
6b8edb51
PA
3496int
3497remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3498 int result_limit, int *done, int *result_count,
3499 threadref *threadlist)
c906108c 3500{
d01949b6 3501 struct remote_state *rs = get_remote_state ();
c906108c
SS
3502 int result = 1;
3503
405feb71 3504 /* Truncate result limit to be smaller than the packet size. */
3e43a32a
MS
3505 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3506 >= get_remote_packet_size ())
ea9c271d 3507 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 3508
8d64371b
TT
3509 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3510 nextthread);
6d820c5c 3511 putpkt (rs->buf);
8d64371b
TT
3512 getpkt (&rs->buf, 0);
3513 if (rs->buf[0] == '\0')
6dc54d91
PA
3514 {
3515 /* Packet not supported. */
3516 return -1;
3517 }
3518
3519 *result_count =
8d64371b 3520 parse_threadlist_response (&rs->buf[2], result_limit,
6dc54d91 3521 &rs->echo_nextthread, threadlist, done);
c906108c 3522
0d031856 3523 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 3524 {
23860348 3525 /* FIXME: This is a good reason to drop the packet. */
405feb71
TV
3526 /* Possibly, there is a duplicate response. */
3527 /* Possibilities :
dda83cd7
SM
3528 retransmit immediatly - race conditions
3529 retransmit after timeout - yes
3530 exit
3531 wait for packet, then exit
c906108c 3532 */
8a3fe4f8 3533 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 3534 return 0; /* I choose simply exiting. */
c906108c
SS
3535 }
3536 if (*result_count <= 0)
3537 {
3538 if (*done != 1)
3539 {
8a3fe4f8 3540 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
3541 result = 0;
3542 }
3543 return result; /* break; */
3544 }
3545 if (*result_count > result_limit)
3546 {
3547 *result_count = 0;
8a3fe4f8 3548 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
3549 return 0;
3550 }
3551 return result;
3552}
3553
6dc54d91
PA
3554/* Fetch the list of remote threads, with the qL packet, and call
3555 STEPFUNCTION for each thread found. Stops iterating and returns 1
3556 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3557 STEPFUNCTION returns false. If the packet is not supported,
3558 returns -1. */
c906108c 3559
6b8edb51
PA
3560int
3561remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3562 void *context, int looplimit)
c906108c 3563{
0d031856 3564 struct remote_state *rs = get_remote_state ();
c906108c
SS
3565 int done, i, result_count;
3566 int startflag = 1;
3567 int result = 1;
3568 int loopcount = 0;
c906108c
SS
3569
3570 done = 0;
3571 while (!done)
3572 {
3573 if (loopcount++ > looplimit)
3574 {
3575 result = 0;
8a3fe4f8 3576 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
3577 break;
3578 }
6dc54d91
PA
3579 result = remote_get_threadlist (startflag, &rs->nextthread,
3580 MAXTHREADLISTRESULTS,
3581 &done, &result_count,
3582 rs->resultthreadlist);
3583 if (result <= 0)
3584 break;
23860348 3585 /* Clear for later iterations. */
c906108c
SS
3586 startflag = 0;
3587 /* Setup to resume next batch of thread references, set nextthread. */
3588 if (result_count >= 1)
0d031856
TT
3589 copy_threadref (&rs->nextthread,
3590 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
3591 i = 0;
3592 while (result_count--)
6dc54d91
PA
3593 {
3594 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3595 {
3596 result = 0;
3597 break;
3598 }
3599 }
c906108c
SS
3600 }
3601 return result;
3602}
3603
6dc54d91
PA
3604/* A thread found on the remote target. */
3605
21fe1c75 3606struct thread_item
6dc54d91 3607{
21fe1c75
SM
3608 explicit thread_item (ptid_t ptid_)
3609 : ptid (ptid_)
3610 {}
3611
3612 thread_item (thread_item &&other) = default;
3613 thread_item &operator= (thread_item &&other) = default;
3614
3615 DISABLE_COPY_AND_ASSIGN (thread_item);
3616
6dc54d91
PA
3617 /* The thread's PTID. */
3618 ptid_t ptid;
3619
21fe1c75
SM
3620 /* The thread's extra info. */
3621 std::string extra;
6dc54d91 3622
21fe1c75
SM
3623 /* The thread's name. */
3624 std::string name;
79efa585 3625
6dc54d91 3626 /* The core the thread was running on. -1 if not known. */
21fe1c75 3627 int core = -1;
f6327dcb
KB
3628
3629 /* The thread handle associated with the thread. */
21fe1c75 3630 gdb::byte_vector thread_handle;
21fe1c75 3631};
6dc54d91
PA
3632
3633/* Context passed around to the various methods listing remote
3634 threads. As new threads are found, they're added to the ITEMS
3635 vector. */
3636
3637struct threads_listing_context
3638{
21fe1c75
SM
3639 /* Return true if this object contains an entry for a thread with ptid
3640 PTID. */
6dc54d91 3641
21fe1c75
SM
3642 bool contains_thread (ptid_t ptid) const
3643 {
3644 auto match_ptid = [&] (const thread_item &item)
3645 {
3646 return item.ptid == ptid;
3647 };
80134cf5 3648
21fe1c75
SM
3649 auto it = std::find_if (this->items.begin (),
3650 this->items.end (),
3651 match_ptid);
80134cf5 3652
21fe1c75
SM
3653 return it != this->items.end ();
3654 }
80134cf5 3655
21fe1c75 3656 /* Remove the thread with ptid PTID. */
80134cf5 3657
21fe1c75
SM
3658 void remove_thread (ptid_t ptid)
3659 {
3660 auto match_ptid = [&] (const thread_item &item)
3661 {
dda83cd7 3662 return item.ptid == ptid;
21fe1c75 3663 };
cbb8991c 3664
21fe1c75
SM
3665 auto it = std::remove_if (this->items.begin (),
3666 this->items.end (),
3667 match_ptid);
cbb8991c 3668
21fe1c75
SM
3669 if (it != this->items.end ())
3670 this->items.erase (it);
3671 }
3672
3673 /* The threads found on the remote target. */
3674 std::vector<thread_item> items;
3675};
cbb8991c 3676
c906108c 3677static int
6dc54d91 3678remote_newthread_step (threadref *ref, void *data)
c906108c 3679{
19ba03f4
SM
3680 struct threads_listing_context *context
3681 = (struct threads_listing_context *) data;
21fe1c75
SM
3682 int pid = inferior_ptid.pid ();
3683 int lwp = threadref_to_int (ref);
3684 ptid_t ptid (pid, lwp);
6dc54d91 3685
21fe1c75 3686 context->items.emplace_back (ptid);
6dc54d91 3687
c906108c
SS
3688 return 1; /* continue iterator */
3689}
3690
3691#define CRAZY_MAX_THREADS 1000
3692
6b8edb51
PA
3693ptid_t
3694remote_target::remote_current_thread (ptid_t oldpid)
c906108c 3695{
d01949b6 3696 struct remote_state *rs = get_remote_state ();
c906108c
SS
3697
3698 putpkt ("qC");
8d64371b 3699 getpkt (&rs->buf, 0);
2e9f7625 3700 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34 3701 {
256642e8 3702 const char *obuf;
c9f35b34
KB
3703 ptid_t result;
3704
3705 result = read_ptid (&rs->buf[2], &obuf);
3706 if (*obuf != '\0' && remote_debug)
dda83cd7
SM
3707 fprintf_unfiltered (gdb_stdlog,
3708 "warning: garbage in qC reply\n");
c9f35b34
KB
3709
3710 return result;
3711 }
c906108c
SS
3712 else
3713 return oldpid;
3714}
3715
6dc54d91 3716/* List remote threads using the deprecated qL packet. */
cce74817 3717
6b8edb51
PA
3718int
3719remote_target::remote_get_threads_with_ql (threads_listing_context *context)
c906108c 3720{
6dc54d91
PA
3721 if (remote_threadlist_iterator (remote_newthread_step, context,
3722 CRAZY_MAX_THREADS) >= 0)
3723 return 1;
3724
3725 return 0;
c906108c
SS
3726}
3727
dc146f7c
VP
3728#if defined(HAVE_LIBEXPAT)
3729
dc146f7c
VP
3730static void
3731start_thread (struct gdb_xml_parser *parser,
3732 const struct gdb_xml_element *element,
4d0fdd9b
SM
3733 void *user_data,
3734 std::vector<gdb_xml_value> &attributes)
dc146f7c 3735{
19ba03f4
SM
3736 struct threads_listing_context *data
3737 = (struct threads_listing_context *) user_data;
3d2c1d41 3738 struct gdb_xml_value *attr;
dc146f7c 3739
4d0fdd9b 3740 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
21fe1c75
SM
3741 ptid_t ptid = read_ptid (id, NULL);
3742
3743 data->items.emplace_back (ptid);
3744 thread_item &item = data->items.back ();
dc146f7c 3745
3d2c1d41
PA
3746 attr = xml_find_attribute (attributes, "core");
3747 if (attr != NULL)
4d0fdd9b 3748 item.core = *(ULONGEST *) attr->value.get ();
dc146f7c 3749
79efa585 3750 attr = xml_find_attribute (attributes, "name");
21fe1c75 3751 if (attr != NULL)
4d0fdd9b 3752 item.name = (const char *) attr->value.get ();
79efa585 3753
f6327dcb
KB
3754 attr = xml_find_attribute (attributes, "handle");
3755 if (attr != NULL)
4d0fdd9b 3756 item.thread_handle = hex2bin ((const char *) attr->value.get ());
dc146f7c
VP
3757}
3758
3759static void
3760end_thread (struct gdb_xml_parser *parser,
3761 const struct gdb_xml_element *element,
3762 void *user_data, const char *body_text)
3763{
19ba03f4
SM
3764 struct threads_listing_context *data
3765 = (struct threads_listing_context *) user_data;
dc146f7c 3766
21fe1c75
SM
3767 if (body_text != NULL && *body_text != '\0')
3768 data->items.back ().extra = body_text;
dc146f7c
VP
3769}
3770
3771const struct gdb_xml_attribute thread_attributes[] = {
3772 { "id", GDB_XML_AF_NONE, NULL, NULL },
3773 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3774 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
f6327dcb 3775 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3776 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3777};
3778
3779const struct gdb_xml_element thread_children[] = {
3780 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3781};
3782
3783const struct gdb_xml_element threads_children[] = {
3784 { "thread", thread_attributes, thread_children,
3785 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3786 start_thread, end_thread },
3787 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3788};
3789
3790const struct gdb_xml_element threads_elements[] = {
3791 { "threads", NULL, threads_children,
3792 GDB_XML_EF_NONE, NULL, NULL },
3793 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3794};
3795
3796#endif
3797
6dc54d91 3798/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3799
6b8edb51
PA
3800int
3801remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
0f71a2f6 3802{
dc146f7c 3803#if defined(HAVE_LIBEXPAT)
4082afcc 3804 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3805 {
9018be22 3806 gdb::optional<gdb::char_vector> xml
6b8edb51 3807 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
efc0eabd 3808
9018be22 3809 if (xml && (*xml)[0] != '\0')
dc146f7c 3810 {
6dc54d91 3811 gdb_xml_parse_quick (_("threads"), "threads.dtd",
9018be22 3812 threads_elements, xml->data (), context);
dc146f7c
VP
3813 }
3814
6dc54d91 3815 return 1;
dc146f7c
VP
3816 }
3817#endif
3818
6dc54d91
PA
3819 return 0;
3820}
3821
3822/* List remote threads using qfThreadInfo/qsThreadInfo. */
3823
6b8edb51
PA
3824int
3825remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
6dc54d91
PA
3826{
3827 struct remote_state *rs = get_remote_state ();
3828
b80fafe3 3829 if (rs->use_threadinfo_query)
9d1f7ab2 3830 {
256642e8 3831 const char *bufp;
6dc54d91 3832
9d1f7ab2 3833 putpkt ("qfThreadInfo");
8d64371b
TT
3834 getpkt (&rs->buf, 0);
3835 bufp = rs->buf.data ();
9d1f7ab2 3836 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3837 {
9d1f7ab2
MS
3838 while (*bufp++ == 'm') /* reply contains one or more TID */
3839 {
3840 do
3841 {
21fe1c75
SM
3842 ptid_t ptid = read_ptid (bufp, &bufp);
3843 context->items.emplace_back (ptid);
9d1f7ab2
MS
3844 }
3845 while (*bufp++ == ','); /* comma-separated list */
3846 putpkt ("qsThreadInfo");
8d64371b
TT
3847 getpkt (&rs->buf, 0);
3848 bufp = rs->buf.data ();
9d1f7ab2 3849 }
6dc54d91
PA
3850 return 1;
3851 }
3852 else
3853 {
3854 /* Packet not recognized. */
3855 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3856 }
3857 }
3858
6dc54d91
PA
3859 return 0;
3860}
3861
a05575d3
TBA
3862/* Return true if INF only has one non-exited thread. */
3863
3864static bool
3865has_single_non_exited_thread (inferior *inf)
3866{
3867 int count = 0;
3868 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
3869 if (++count > 1)
3870 break;
3871 return count == 1;
3872}
3873
e8032dde 3874/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3875 targets. */
3876
f6ac5f3d
PA
3877void
3878remote_target::update_thread_list ()
6dc54d91 3879{
6dc54d91 3880 struct threads_listing_context context;
ab970af1 3881 int got_list = 0;
e8032dde 3882
6dc54d91
PA
3883 /* We have a few different mechanisms to fetch the thread list. Try
3884 them all, starting with the most preferred one first, falling
3885 back to older methods. */
6b8edb51
PA
3886 if (remote_get_threads_with_qxfer (&context)
3887 || remote_get_threads_with_qthreadinfo (&context)
3888 || remote_get_threads_with_ql (&context))
6dc54d91 3889 {
ab970af1
PA
3890 got_list = 1;
3891
21fe1c75 3892 if (context.items.empty ()
f6ac5f3d 3893 && remote_thread_always_alive (inferior_ptid))
7d1a114c
PA
3894 {
3895 /* Some targets don't really support threads, but still
3896 reply an (empty) thread list in response to the thread
3897 listing packets, instead of replying "packet not
3898 supported". Exit early so we don't delete the main
3899 thread. */
7d1a114c
PA
3900 return;
3901 }
3902
ab970af1
PA
3903 /* CONTEXT now holds the current thread list on the remote
3904 target end. Delete GDB-side threads no longer found on the
3905 target. */
08036331 3906 for (thread_info *tp : all_threads_safe ())
cbb8991c 3907 {
5b6d1e4f
PA
3908 if (tp->inf->process_target () != this)
3909 continue;
3910
21fe1c75 3911 if (!context.contains_thread (tp->ptid))
ab970af1 3912 {
a05575d3
TBA
3913 /* Do not remove the thread if it is the last thread in
3914 the inferior. This situation happens when we have a
3915 pending exit process status to process. Otherwise we
3916 may end up with a seemingly live inferior (i.e. pid
3917 != 0) that has no threads. */
3918 if (has_single_non_exited_thread (tp->inf))
3919 continue;
3920
ab970af1 3921 /* Not found. */
00431a78 3922 delete_thread (tp);
ab970af1 3923 }
cbb8991c
DB
3924 }
3925
3926 /* Remove any unreported fork child threads from CONTEXT so
3927 that we don't interfere with follow fork, which is where
3928 creation of such threads is handled. */
3929 remove_new_fork_children (&context);
74531fed 3930
ab970af1 3931 /* And now add threads we don't know about yet to our list. */
21fe1c75 3932 for (thread_item &item : context.items)
6dc54d91 3933 {
21fe1c75 3934 if (item.ptid != null_ptid)
6dc54d91 3935 {
6dc54d91 3936 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
3937 executing until proven otherwise with a stop reply.
3938 In all-stop, we can only get here if all threads are
6dc54d91 3939 stopped. */
0d5b594f 3940 int executing = target_is_non_stop_p () ? 1 : 0;
6dc54d91 3941
21fe1c75 3942 remote_notice_new_inferior (item.ptid, executing);
6dc54d91 3943
5b6d1e4f 3944 thread_info *tp = find_thread_ptid (this, item.ptid);
00431a78 3945 remote_thread_info *info = get_remote_thread_info (tp);
21fe1c75 3946 info->core = item.core;
7aabaf9d
SM
3947 info->extra = std::move (item.extra);
3948 info->name = std::move (item.name);
3949 info->thread_handle = std::move (item.thread_handle);
6dc54d91
PA
3950 }
3951 }
3952 }
3953
ab970af1
PA
3954 if (!got_list)
3955 {
3956 /* If no thread listing method is supported, then query whether
3957 each known thread is alive, one by one, with the T packet.
3958 If the target doesn't support threads at all, then this is a
3959 no-op. See remote_thread_alive. */
3960 prune_threads ();
3961 }
9d1f7ab2
MS
3962}
3963
802188a7 3964/*
9d1f7ab2
MS
3965 * Collect a descriptive string about the given thread.
3966 * The target may say anything it wants to about the thread
3967 * (typically info about its blocked / runnable state, name, etc.).
3968 * This string will appear in the info threads display.
802188a7 3969 *
9d1f7ab2
MS
3970 * Optional: targets are not required to implement this function.
3971 */
3972
f6ac5f3d
PA
3973const char *
3974remote_target::extra_thread_info (thread_info *tp)
9d1f7ab2 3975{
d01949b6 3976 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3977 int set;
3978 threadref id;
3979 struct gdb_ext_thread_info threadinfo;
9d1f7ab2 3980
5d93a237 3981 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3982 internal_error (__FILE__, __LINE__,
e2e0b3e5 3983 _("remote_threads_extra_info"));
9d1f7ab2 3984
d7e15655 3985 if (tp->ptid == magic_null_ptid
e38504b3 3986 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
60e569b9
PA
3987 /* This is the main thread which was added by GDB. The remote
3988 server doesn't know about it. */
3989 return NULL;
3990
c76a8ea3
PA
3991 std::string &extra = get_remote_thread_info (tp)->extra;
3992
3993 /* If already have cached info, use it. */
3994 if (!extra.empty ())
3995 return extra.c_str ();
3996
4082afcc 3997 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3998 {
c76a8ea3
PA
3999 /* If we're using qXfer:threads:read, then the extra info is
4000 included in the XML. So if we didn't have anything cached,
4001 it's because there's really no extra info. */
4002 return NULL;
dc146f7c
VP
4003 }
4004
b80fafe3 4005 if (rs->use_threadextra_query)
9d1f7ab2 4006 {
8d64371b
TT
4007 char *b = rs->buf.data ();
4008 char *endb = b + get_remote_packet_size ();
82f73884
PA
4009
4010 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4011 b += strlen (b);
4012 write_ptid (b, endb, tp->ptid);
4013
2e9f7625 4014 putpkt (rs->buf);
8d64371b 4015 getpkt (&rs->buf, 0);
2e9f7625 4016 if (rs->buf[0] != 0)
9d1f7ab2 4017 {
8d64371b
TT
4018 extra.resize (strlen (rs->buf.data ()) / 2);
4019 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
c76a8ea3 4020 return extra.c_str ();
9d1f7ab2 4021 }
0f71a2f6 4022 }
9d1f7ab2
MS
4023
4024 /* If the above query fails, fall back to the old method. */
b80fafe3 4025 rs->use_threadextra_query = 0;
9d1f7ab2
MS
4026 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4027 | TAG_MOREDISPLAY | TAG_DISPLAY;
e38504b3 4028 int_to_threadref (&id, tp->ptid.lwp ());
9d1f7ab2
MS
4029 if (remote_get_threadinfo (&id, set, &threadinfo))
4030 if (threadinfo.active)
0f71a2f6 4031 {
9d1f7ab2 4032 if (*threadinfo.shortname)
c76a8ea3 4033 string_appendf (extra, " Name: %s", threadinfo.shortname);
9d1f7ab2 4034 if (*threadinfo.display)
c76a8ea3
PA
4035 {
4036 if (!extra.empty ())
4037 extra += ',';
4038 string_appendf (extra, " State: %s", threadinfo.display);
4039 }
9d1f7ab2 4040 if (*threadinfo.more_display)
c5aa993b 4041 {
c76a8ea3
PA
4042 if (!extra.empty ())
4043 extra += ',';
4044 string_appendf (extra, " Priority: %s", threadinfo.more_display);
c5aa993b 4045 }
c76a8ea3 4046 return extra.c_str ();
0f71a2f6 4047 }
9d1f7ab2 4048 return NULL;
0f71a2f6 4049}
c906108c 4050\f
c5aa993b 4051
f6ac5f3d
PA
4052bool
4053remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4054 struct static_tracepoint_marker *marker)
0fb4aa4b
PA
4055{
4056 struct remote_state *rs = get_remote_state ();
8d64371b 4057 char *p = rs->buf.data ();
0fb4aa4b 4058
bba74b36 4059 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
4060 p += strlen (p);
4061 p += hexnumstr (p, addr);
4062 putpkt (rs->buf);
8d64371b
TT
4063 getpkt (&rs->buf, 0);
4064 p = rs->buf.data ();
0fb4aa4b
PA
4065
4066 if (*p == 'E')
4067 error (_("Remote failure reply: %s"), p);
4068
4069 if (*p++ == 'm')
4070 {
256642e8 4071 parse_static_tracepoint_marker_definition (p, NULL, marker);
5d9310c4 4072 return true;
0fb4aa4b
PA
4073 }
4074
5d9310c4 4075 return false;
0fb4aa4b
PA
4076}
4077
f6ac5f3d
PA
4078std::vector<static_tracepoint_marker>
4079remote_target::static_tracepoint_markers_by_strid (const char *strid)
0fb4aa4b
PA
4080{
4081 struct remote_state *rs = get_remote_state ();
5d9310c4 4082 std::vector<static_tracepoint_marker> markers;
256642e8 4083 const char *p;
5d9310c4 4084 static_tracepoint_marker marker;
0fb4aa4b
PA
4085
4086 /* Ask for a first packet of static tracepoint marker
4087 definition. */
4088 putpkt ("qTfSTM");
8d64371b
TT
4089 getpkt (&rs->buf, 0);
4090 p = rs->buf.data ();
0fb4aa4b
PA
4091 if (*p == 'E')
4092 error (_("Remote failure reply: %s"), p);
4093
0fb4aa4b
PA
4094 while (*p++ == 'm')
4095 {
0fb4aa4b
PA
4096 do
4097 {
5d9310c4 4098 parse_static_tracepoint_marker_definition (p, &p, &marker);
0fb4aa4b 4099
5d9310c4
SM
4100 if (strid == NULL || marker.str_id == strid)
4101 markers.push_back (std::move (marker));
0fb4aa4b
PA
4102 }
4103 while (*p++ == ','); /* comma-separated list */
4104 /* Ask for another packet of static tracepoint definition. */
4105 putpkt ("qTsSTM");
8d64371b
TT
4106 getpkt (&rs->buf, 0);
4107 p = rs->buf.data ();
0fb4aa4b
PA
4108 }
4109
0fb4aa4b
PA
4110 return markers;
4111}
4112
4113\f
10760264
JB
4114/* Implement the to_get_ada_task_ptid function for the remote targets. */
4115
f6ac5f3d
PA
4116ptid_t
4117remote_target::get_ada_task_ptid (long lwp, long thread)
10760264 4118{
e99b03dc 4119 return ptid_t (inferior_ptid.pid (), lwp, 0);
10760264
JB
4120}
4121\f
4122
24b06219 4123/* Restart the remote side; this is an extended protocol operation. */
c906108c 4124
6b8edb51
PA
4125void
4126remote_target::extended_remote_restart ()
c906108c 4127{
d01949b6 4128 struct remote_state *rs = get_remote_state ();
c906108c
SS
4129
4130 /* Send the restart command; for reasons I don't understand the
4131 remote side really expects a number after the "R". */
8d64371b 4132 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
6d820c5c 4133 putpkt (rs->buf);
c906108c 4134
ad9a8f3f 4135 remote_fileio_reset ();
c906108c
SS
4136}
4137\f
4138/* Clean up connection to a remote debugger. */
4139
f6ac5f3d
PA
4140void
4141remote_target::close ()
c906108c 4142{
048094ac 4143 /* Make sure we leave stdin registered in the event loop. */
f6ac5f3d 4144 terminal_ours ();
ce5ce7ed 4145
6b8edb51
PA
4146 trace_reset_local_state ();
4147
4148 delete this;
4149}
4150
4151remote_target::~remote_target ()
4152{
4153 struct remote_state *rs = get_remote_state ();
4154
4155 /* Check for NULL because we may get here with a partially
4156 constructed target/connection. */
4157 if (rs->remote_desc == nullptr)
4158 return;
4159
4160 serial_close (rs->remote_desc);
4161
4162 /* We are destroying the remote target, so we should discard
f48ff2a7 4163 everything of this target. */
6b8edb51 4164 discard_pending_stop_replies_in_queue ();
74531fed 4165
6b8edb51
PA
4166 if (rs->remote_async_inferior_event_token)
4167 delete_async_event_handler (&rs->remote_async_inferior_event_token);
722247f1 4168
97dfbadd 4169 delete rs->notif_state;
c906108c
SS
4170}
4171
23860348 4172/* Query the remote side for the text, data and bss offsets. */
c906108c 4173
6b8edb51
PA
4174void
4175remote_target::get_offsets ()
c906108c 4176{
d01949b6 4177 struct remote_state *rs = get_remote_state ();
2e9f7625 4178 char *buf;
085dd6e6 4179 char *ptr;
31d99776
DJ
4180 int lose, num_segments = 0, do_sections, do_segments;
4181 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
31d99776 4182
a42d7dd8 4183 if (current_program_space->symfile_object_file == NULL)
31d99776 4184 return;
c906108c
SS
4185
4186 putpkt ("qOffsets");
8d64371b
TT
4187 getpkt (&rs->buf, 0);
4188 buf = rs->buf.data ();
c906108c
SS
4189
4190 if (buf[0] == '\000')
4191 return; /* Return silently. Stub doesn't support
23860348 4192 this command. */
c906108c
SS
4193 if (buf[0] == 'E')
4194 {
8a3fe4f8 4195 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
4196 return;
4197 }
4198
4199 /* Pick up each field in turn. This used to be done with scanf, but
4200 scanf will make trouble if CORE_ADDR size doesn't match
4201 conversion directives correctly. The following code will work
4202 with any size of CORE_ADDR. */
4203 text_addr = data_addr = bss_addr = 0;
4204 ptr = buf;
4205 lose = 0;
4206
61012eef 4207 if (startswith (ptr, "Text="))
c906108c
SS
4208 {
4209 ptr += 5;
4210 /* Don't use strtol, could lose on big values. */
4211 while (*ptr && *ptr != ';')
4212 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 4213
61012eef 4214 if (startswith (ptr, ";Data="))
31d99776
DJ
4215 {
4216 ptr += 6;
4217 while (*ptr && *ptr != ';')
4218 data_addr = (data_addr << 4) + fromhex (*ptr++);
4219 }
4220 else
4221 lose = 1;
4222
61012eef 4223 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
4224 {
4225 ptr += 5;
4226 while (*ptr && *ptr != ';')
4227 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 4228
31d99776
DJ
4229 if (bss_addr != data_addr)
4230 warning (_("Target reported unsupported offsets: %s"), buf);
4231 }
4232 else
4233 lose = 1;
4234 }
61012eef 4235 else if (startswith (ptr, "TextSeg="))
c906108c 4236 {
31d99776
DJ
4237 ptr += 8;
4238 /* Don't use strtol, could lose on big values. */
c906108c 4239 while (*ptr && *ptr != ';')
31d99776
DJ
4240 text_addr = (text_addr << 4) + fromhex (*ptr++);
4241 num_segments = 1;
4242
61012eef 4243 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
4244 {
4245 ptr += 9;
4246 while (*ptr && *ptr != ';')
4247 data_addr = (data_addr << 4) + fromhex (*ptr++);
4248 num_segments++;
4249 }
c906108c
SS
4250 }
4251 else
4252 lose = 1;
4253
4254 if (lose)
8a3fe4f8 4255 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
4256 else if (*ptr != '\0')
4257 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 4258
a42d7dd8
TT
4259 objfile *objf = current_program_space->symfile_object_file;
4260 section_offsets offs = objf->section_offsets;
c906108c 4261
a42d7dd8 4262 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd);
31d99776
DJ
4263 do_segments = (data != NULL);
4264 do_sections = num_segments == 0;
c906108c 4265
28c32713 4266 if (num_segments > 0)
31d99776 4267 {
31d99776
DJ
4268 segments[0] = text_addr;
4269 segments[1] = data_addr;
4270 }
28c32713
JB
4271 /* If we have two segments, we can still try to relocate everything
4272 by assuming that the .text and .data offsets apply to the whole
4273 text and data segments. Convert the offsets given in the packet
4274 to base addresses for symfile_map_offsets_to_segments. */
68b888ff 4275 else if (data != nullptr && data->segments.size () == 2)
28c32713 4276 {
68b888ff
SM
4277 segments[0] = data->segments[0].base + text_addr;
4278 segments[1] = data->segments[1].base + data_addr;
28c32713
JB
4279 num_segments = 2;
4280 }
8d385431
DJ
4281 /* If the object file has only one segment, assume that it is text
4282 rather than data; main programs with no writable data are rare,
4283 but programs with no code are useless. Of course the code might
4284 have ended up in the data segment... to detect that we would need
4285 the permissions here. */
68b888ff 4286 else if (data && data->segments.size () == 1)
8d385431 4287 {
68b888ff 4288 segments[0] = data->segments[0].base + text_addr;
8d385431
DJ
4289 num_segments = 1;
4290 }
28c32713
JB
4291 /* There's no way to relocate by segment. */
4292 else
4293 do_segments = 0;
31d99776
DJ
4294
4295 if (do_segments)
4296 {
a42d7dd8 4297 int ret = symfile_map_offsets_to_segments (objf->obfd,
62982abd
SM
4298 data.get (), offs,
4299 num_segments, segments);
31d99776
DJ
4300
4301 if (ret == 0 && !do_sections)
3e43a32a
MS
4302 error (_("Can not handle qOffsets TextSeg "
4303 "response with this symbol file"));
31d99776
DJ
4304
4305 if (ret > 0)
4306 do_sections = 0;
4307 }
c906108c 4308
31d99776
DJ
4309 if (do_sections)
4310 {
a42d7dd8 4311 offs[SECT_OFF_TEXT (objf)] = text_addr;
31d99776 4312
3e43a32a
MS
4313 /* This is a temporary kludge to force data and bss to use the
4314 same offsets because that's what nlmconv does now. The real
4315 solution requires changes to the stub and remote.c that I
4316 don't have time to do right now. */
31d99776 4317
a42d7dd8
TT
4318 offs[SECT_OFF_DATA (objf)] = data_addr;
4319 offs[SECT_OFF_BSS (objf)] = data_addr;
31d99776 4320 }
c906108c 4321
a42d7dd8 4322 objfile_relocate (objf, offs);
c906108c
SS
4323}
4324
9a7071a8 4325/* Send interrupt_sequence to remote target. */
6b8edb51
PA
4326
4327void
4328remote_target::send_interrupt_sequence ()
9a7071a8 4329{
5d93a237
TT
4330 struct remote_state *rs = get_remote_state ();
4331
9a7071a8 4332 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 4333 remote_serial_write ("\x03", 1);
9a7071a8 4334 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 4335 serial_send_break (rs->remote_desc);
9a7071a8
JB
4336 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4337 {
5d93a237 4338 serial_send_break (rs->remote_desc);
c33e31fd 4339 remote_serial_write ("g", 1);
9a7071a8
JB
4340 }
4341 else
4342 internal_error (__FILE__, __LINE__,
4343 _("Invalid value for interrupt_sequence_mode: %s."),
4344 interrupt_sequence_mode);
4345}
4346
3405876a
PA
4347
4348/* If STOP_REPLY is a T stop reply, look for the "thread" register,
4349 and extract the PTID. Returns NULL_PTID if not found. */
4350
4351static ptid_t
4352stop_reply_extract_thread (char *stop_reply)
4353{
4354 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4355 {
256642e8 4356 const char *p;
3405876a
PA
4357
4358 /* Txx r:val ; r:val (...) */
4359 p = &stop_reply[3];
4360
4361 /* Look for "register" named "thread". */
4362 while (*p != '\0')
4363 {
256642e8 4364 const char *p1;
3405876a
PA
4365
4366 p1 = strchr (p, ':');
4367 if (p1 == NULL)
4368 return null_ptid;
4369
4370 if (strncmp (p, "thread", p1 - p) == 0)
4371 return read_ptid (++p1, &p);
4372
4373 p1 = strchr (p, ';');
4374 if (p1 == NULL)
4375 return null_ptid;
4376 p1++;
4377
4378 p = p1;
4379 }
4380 }
4381
4382 return null_ptid;
4383}
4384
b7ea362b
PA
4385/* Determine the remote side's current thread. If we have a stop
4386 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4387 "thread" register we can extract the current thread from. If not,
4388 ask the remote which is the current thread with qC. The former
4389 method avoids a roundtrip. */
4390
6b8edb51
PA
4391ptid_t
4392remote_target::get_current_thread (char *wait_status)
b7ea362b 4393{
6a49a997 4394 ptid_t ptid = null_ptid;
b7ea362b
PA
4395
4396 /* Note we don't use remote_parse_stop_reply as that makes use of
4397 the target architecture, which we haven't yet fully determined at
4398 this point. */
4399 if (wait_status != NULL)
4400 ptid = stop_reply_extract_thread (wait_status);
d7e15655 4401 if (ptid == null_ptid)
b7ea362b
PA
4402 ptid = remote_current_thread (inferior_ptid);
4403
4404 return ptid;
4405}
4406
49c62f2e
PA
4407/* Query the remote target for which is the current thread/process,
4408 add it to our tables, and update INFERIOR_PTID. The caller is
4409 responsible for setting the state such that the remote end is ready
3405876a
PA
4410 to return the current thread.
4411
4412 This function is called after handling the '?' or 'vRun' packets,
4413 whose response is a stop reply from which we can also try
4414 extracting the thread. If the target doesn't support the explicit
4415 qC query, we infer the current thread from that stop reply, passed
4416 in in WAIT_STATUS, which may be NULL. */
49c62f2e 4417
6b8edb51
PA
4418void
4419remote_target::add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
4420{
4421 struct remote_state *rs = get_remote_state ();
9ab8741a 4422 bool fake_pid_p = false;
49c62f2e 4423
0ac55310 4424 switch_to_no_thread ();
49c62f2e 4425
0ac55310
PA
4426 /* Now, if we have thread information, update the current thread's
4427 ptid. */
87215ad1 4428 ptid_t curr_ptid = get_current_thread (wait_status);
3405876a 4429
87215ad1 4430 if (curr_ptid != null_ptid)
49c62f2e
PA
4431 {
4432 if (!remote_multi_process_p (rs))
9ab8741a 4433 fake_pid_p = true;
49c62f2e
PA
4434 }
4435 else
4436 {
4437 /* Without this, some commands which require an active target
4438 (such as kill) won't work. This variable serves (at least)
4439 double duty as both the pid of the target process (if it has
4440 such), and as a flag indicating that a target is active. */
87215ad1 4441 curr_ptid = magic_null_ptid;
9ab8741a 4442 fake_pid_p = true;
49c62f2e
PA
4443 }
4444
e99b03dc 4445 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
49c62f2e 4446
87215ad1
SDJ
4447 /* Add the main thread and switch to it. Don't try reading
4448 registers yet, since we haven't fetched the target description
4449 yet. */
5b6d1e4f 4450 thread_info *tp = add_thread_silent (this, curr_ptid);
87215ad1 4451 switch_to_thread_no_regs (tp);
49c62f2e
PA
4452}
4453
6efcd9a8
PA
4454/* Print info about a thread that was found already stopped on
4455 connection. */
4456
4457static void
4458print_one_stopped_thread (struct thread_info *thread)
4459{
4460 struct target_waitstatus *ws = &thread->suspend.waitstatus;
4461
00431a78 4462 switch_to_thread (thread);
f2ffa92b 4463 thread->suspend.stop_pc = get_frame_pc (get_current_frame ());
6efcd9a8
PA
4464 set_current_sal_from_frame (get_current_frame ());
4465
4466 thread->suspend.waitstatus_pending_p = 0;
4467
4468 if (ws->kind == TARGET_WAITKIND_STOPPED)
4469 {
4470 enum gdb_signal sig = ws->value.sig;
4471
4472 if (signal_print_state (sig))
76727919 4473 gdb::observers::signal_received.notify (sig);
6efcd9a8 4474 }
76727919 4475 gdb::observers::normal_stop.notify (NULL, 1);
6efcd9a8
PA
4476}
4477
221e1a37
PA
4478/* Process all initial stop replies the remote side sent in response
4479 to the ? packet. These indicate threads that were already stopped
4480 on initial connection. We mark these threads as stopped and print
4481 their current frame before giving the user the prompt. */
4482
6b8edb51
PA
4483void
4484remote_target::process_initial_stop_replies (int from_tty)
221e1a37
PA
4485{
4486 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
4487 struct thread_info *selected = NULL;
4488 struct thread_info *lowest_stopped = NULL;
4489 struct thread_info *first = NULL;
221e1a37
PA
4490
4491 /* Consume the initial pending events. */
4492 while (pending_stop_replies-- > 0)
4493 {
4494 ptid_t waiton_ptid = minus_one_ptid;
4495 ptid_t event_ptid;
4496 struct target_waitstatus ws;
4497 int ignore_event = 0;
4498
4499 memset (&ws, 0, sizeof (ws));
4500 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4501 if (remote_debug)
4502 print_target_wait_results (waiton_ptid, event_ptid, &ws);
4503
4504 switch (ws.kind)
4505 {
4506 case TARGET_WAITKIND_IGNORE:
4507 case TARGET_WAITKIND_NO_RESUMED:
4508 case TARGET_WAITKIND_SIGNALLED:
4509 case TARGET_WAITKIND_EXITED:
4510 /* We shouldn't see these, but if we do, just ignore. */
4511 if (remote_debug)
4512 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4513 ignore_event = 1;
4514 break;
4515
4516 case TARGET_WAITKIND_EXECD:
4517 xfree (ws.value.execd_pathname);
4518 break;
4519 default:
4520 break;
4521 }
4522
4523 if (ignore_event)
4524 continue;
4525
5b6d1e4f 4526 thread_info *evthread = find_thread_ptid (this, event_ptid);
221e1a37
PA
4527
4528 if (ws.kind == TARGET_WAITKIND_STOPPED)
4529 {
4530 enum gdb_signal sig = ws.value.sig;
4531
4532 /* Stubs traditionally report SIGTRAP as initial signal,
4533 instead of signal 0. Suppress it. */
4534 if (sig == GDB_SIGNAL_TRAP)
4535 sig = GDB_SIGNAL_0;
b926417a 4536 evthread->suspend.stop_signal = sig;
6efcd9a8
PA
4537 ws.value.sig = sig;
4538 }
221e1a37 4539
b926417a 4540 evthread->suspend.waitstatus = ws;
6efcd9a8
PA
4541
4542 if (ws.kind != TARGET_WAITKIND_STOPPED
4543 || ws.value.sig != GDB_SIGNAL_0)
b926417a 4544 evthread->suspend.waitstatus_pending_p = 1;
6efcd9a8 4545
719546c4
SM
4546 set_executing (this, event_ptid, false);
4547 set_running (this, event_ptid, false);
c9d22089 4548 get_remote_thread_info (evthread)->set_not_resumed ();
6efcd9a8
PA
4549 }
4550
4551 /* "Notice" the new inferiors before anything related to
4552 registers/memory. */
5b6d1e4f 4553 for (inferior *inf : all_non_exited_inferiors (this))
6efcd9a8 4554 {
6efcd9a8
PA
4555 inf->needs_setup = 1;
4556
4557 if (non_stop)
4558 {
08036331 4559 thread_info *thread = any_live_thread_of_inferior (inf);
00431a78 4560 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
6efcd9a8
PA
4561 from_tty);
4562 }
4563 }
4564
4565 /* If all-stop on top of non-stop, pause all threads. Note this
4566 records the threads' stop pc, so must be done after "noticing"
4567 the inferiors. */
4568 if (!non_stop)
4569 {
4570 stop_all_threads ();
4571
4572 /* If all threads of an inferior were already stopped, we
4573 haven't setup the inferior yet. */
5b6d1e4f 4574 for (inferior *inf : all_non_exited_inferiors (this))
6efcd9a8 4575 {
6efcd9a8
PA
4576 if (inf->needs_setup)
4577 {
08036331 4578 thread_info *thread = any_live_thread_of_inferior (inf);
6efcd9a8
PA
4579 switch_to_thread_no_regs (thread);
4580 setup_inferior (0);
4581 }
4582 }
221e1a37 4583 }
6efcd9a8
PA
4584
4585 /* Now go over all threads that are stopped, and print their current
4586 frame. If all-stop, then if there's a signalled thread, pick
4587 that as current. */
5b6d1e4f 4588 for (thread_info *thread : all_non_exited_threads (this))
6efcd9a8 4589 {
6efcd9a8
PA
4590 if (first == NULL)
4591 first = thread;
4592
4593 if (!non_stop)
00431a78 4594 thread->set_running (false);
6efcd9a8
PA
4595 else if (thread->state != THREAD_STOPPED)
4596 continue;
4597
6efcd9a8
PA
4598 if (selected == NULL
4599 && thread->suspend.waitstatus_pending_p)
4600 selected = thread;
4601
5d5658a1
PA
4602 if (lowest_stopped == NULL
4603 || thread->inf->num < lowest_stopped->inf->num
4604 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
4605 lowest_stopped = thread;
4606
4607 if (non_stop)
4608 print_one_stopped_thread (thread);
4609 }
4610
4611 /* In all-stop, we only print the status of one thread, and leave
4612 others with their status pending. */
4613 if (!non_stop)
4614 {
08036331 4615 thread_info *thread = selected;
6efcd9a8
PA
4616 if (thread == NULL)
4617 thread = lowest_stopped;
4618 if (thread == NULL)
4619 thread = first;
4620
4621 print_one_stopped_thread (thread);
4622 }
4623
4624 /* For "info program". */
08036331 4625 thread_info *thread = inferior_thread ();
6efcd9a8 4626 if (thread->state == THREAD_STOPPED)
5b6d1e4f 4627 set_last_target_status (this, inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
4628}
4629
048094ac
PA
4630/* Start the remote connection and sync state. */
4631
f6ac5f3d
PA
4632void
4633remote_target::start_remote (int from_tty, int extended_p)
c906108c 4634{
c8d104ad
PA
4635 struct remote_state *rs = get_remote_state ();
4636 struct packet_config *noack_config;
2d717e4f 4637 char *wait_status = NULL;
8621d6a9 4638
048094ac
PA
4639 /* Signal other parts that we're going through the initial setup,
4640 and so things may not be stable yet. E.g., we don't try to
4641 install tracepoints until we've relocated symbols. Also, a
4642 Ctrl-C before we're connected and synced up can't interrupt the
4643 target. Instead, it offers to drop the (potentially wedged)
4644 connection. */
4645 rs->starting_up = 1;
4646
522002f9 4647 QUIT;
c906108c 4648
9a7071a8
JB
4649 if (interrupt_on_connect)
4650 send_interrupt_sequence ();
4651
57e12211 4652 /* Ack any packet which the remote side has already sent. */
048094ac 4653 remote_serial_write ("+", 1);
1e51243a 4654
c8d104ad
PA
4655 /* The first packet we send to the target is the optional "supported
4656 packets" request. If the target can answer this, it will tell us
4657 which later probes to skip. */
4658 remote_query_supported ();
4659
d914c394 4660 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 4661 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
f6ac5f3d 4662 set_permissions ();
d914c394 4663
57809e5e
JK
4664 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4665 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4666 as a reply to known packet. For packet "vFile:setfs:" it is an
4667 invalid reply and GDB would return error in
4668 remote_hostio_set_filesystem, making remote files access impossible.
4669 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4670 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4671 {
4672 const char v_mustreplyempty[] = "vMustReplyEmpty";
4673
4674 putpkt (v_mustreplyempty);
8d64371b
TT
4675 getpkt (&rs->buf, 0);
4676 if (strcmp (rs->buf.data (), "OK") == 0)
57809e5e 4677 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
8d64371b 4678 else if (strcmp (rs->buf.data (), "") != 0)
57809e5e 4679 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
8d64371b 4680 rs->buf.data ());
57809e5e
JK
4681 }
4682
c8d104ad
PA
4683 /* Next, we possibly activate noack mode.
4684
4685 If the QStartNoAckMode packet configuration is set to AUTO,
4686 enable noack mode if the stub reported a wish for it with
4687 qSupported.
4688
4689 If set to TRUE, then enable noack mode even if the stub didn't
4690 report it in qSupported. If the stub doesn't reply OK, the
4691 session ends with an error.
4692
4693 If FALSE, then don't activate noack mode, regardless of what the
4694 stub claimed should be the default with qSupported. */
4695
4696 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 4697 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
4698 {
4699 putpkt ("QStartNoAckMode");
8d64371b 4700 getpkt (&rs->buf, 0);
c8d104ad
PA
4701 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4702 rs->noack_mode = 1;
4703 }
4704
04bd08de 4705 if (extended_p)
5fe04517
PA
4706 {
4707 /* Tell the remote that we are using the extended protocol. */
4708 putpkt ("!");
8d64371b 4709 getpkt (&rs->buf, 0);
5fe04517
PA
4710 }
4711
9b224c5e
PA
4712 /* Let the target know which signals it is allowed to pass down to
4713 the program. */
4714 update_signals_program_target ();
4715
d962ef82
DJ
4716 /* Next, if the target can specify a description, read it. We do
4717 this before anything involving memory or registers. */
4718 target_find_description ();
4719
6c95b8df
PA
4720 /* Next, now that we know something about the target, update the
4721 address spaces in the program spaces. */
4722 update_address_spaces ();
4723
50c71eaf
PA
4724 /* On OSs where the list of libraries is global to all
4725 processes, we fetch them early. */
f5656ead 4726 if (gdbarch_has_global_solist (target_gdbarch ()))
e696b3ad 4727 solib_add (NULL, from_tty, auto_solib_add);
50c71eaf 4728
6efcd9a8 4729 if (target_is_non_stop_p ())
74531fed 4730 {
4082afcc 4731 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
4732 error (_("Non-stop mode requested, but remote "
4733 "does not support non-stop"));
74531fed
PA
4734
4735 putpkt ("QNonStop:1");
8d64371b 4736 getpkt (&rs->buf, 0);
74531fed 4737
8d64371b
TT
4738 if (strcmp (rs->buf.data (), "OK") != 0)
4739 error (_("Remote refused setting non-stop mode with: %s"),
4740 rs->buf.data ());
74531fed
PA
4741
4742 /* Find about threads and processes the stub is already
4743 controlling. We default to adding them in the running state.
4744 The '?' query below will then tell us about which threads are
4745 stopped. */
f6ac5f3d 4746 this->update_thread_list ();
74531fed 4747 }
4082afcc 4748 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4749 {
4750 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4751 Request it explicitly. */
74531fed 4752 putpkt ("QNonStop:0");
8d64371b 4753 getpkt (&rs->buf, 0);
74531fed 4754
8d64371b
TT
4755 if (strcmp (rs->buf.data (), "OK") != 0)
4756 error (_("Remote refused setting all-stop mode with: %s"),
4757 rs->buf.data ());
74531fed
PA
4758 }
4759
a0743c90
YQ
4760 /* Upload TSVs regardless of whether the target is running or not. The
4761 remote stub, such as GDBserver, may have some predefined or builtin
4762 TSVs, even if the target is not running. */
f6ac5f3d 4763 if (get_trace_status (current_trace_status ()) != -1)
a0743c90
YQ
4764 {
4765 struct uploaded_tsv *uploaded_tsvs = NULL;
4766
f6ac5f3d 4767 upload_trace_state_variables (&uploaded_tsvs);
a0743c90
YQ
4768 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4769 }
4770
2d717e4f
DJ
4771 /* Check whether the target is running now. */
4772 putpkt ("?");
8d64371b 4773 getpkt (&rs->buf, 0);
2d717e4f 4774
6efcd9a8 4775 if (!target_is_non_stop_p ())
2d717e4f 4776 {
74531fed 4777 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4778 {
04bd08de 4779 if (!extended_p)
74531fed 4780 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4781
4782 /* We're connected, but not running. Drop out before we
4783 call start_remote. */
e278ad5b 4784 rs->starting_up = 0;
c35b1492 4785 return;
2d717e4f
DJ
4786 }
4787 else
74531fed 4788 {
74531fed 4789 /* Save the reply for later. */
8d64371b
TT
4790 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
4791 strcpy (wait_status, rs->buf.data ());
74531fed
PA
4792 }
4793
b7ea362b 4794 /* Fetch thread list. */
e8032dde 4795 target_update_thread_list ();
b7ea362b 4796
74531fed
PA
4797 /* Let the stub know that we want it to return the thread. */
4798 set_continue_thread (minus_one_ptid);
4799
5b6d1e4f 4800 if (thread_count (this) == 0)
b7ea362b
PA
4801 {
4802 /* Target has no concept of threads at all. GDB treats
4803 non-threaded target as single-threaded; add a main
4804 thread. */
4805 add_current_inferior_and_thread (wait_status);
4806 }
4807 else
4808 {
4809 /* We have thread information; select the thread the target
4810 says should be current. If we're reconnecting to a
4811 multi-threaded program, this will ideally be the thread
4812 that last reported an event before GDB disconnected. */
75c6c844
PA
4813 ptid_t curr_thread = get_current_thread (wait_status);
4814 if (curr_thread == null_ptid)
b7ea362b
PA
4815 {
4816 /* Odd... The target was able to list threads, but not
4817 tell us which thread was current (no "thread"
4818 register in T stop reply?). Just pick the first
4819 thread in the thread list then. */
c9f35b34
KB
4820
4821 if (remote_debug)
4822 fprintf_unfiltered (gdb_stdlog,
dda83cd7 4823 "warning: couldn't determine remote "
c9f35b34
KB
4824 "current thread; picking first in list.\n");
4825
5b6d1e4f
PA
4826 for (thread_info *tp : all_non_exited_threads (this,
4827 minus_one_ptid))
75c6c844
PA
4828 {
4829 switch_to_thread (tp);
4830 break;
4831 }
b7ea362b 4832 }
75c6c844 4833 else
5b6d1e4f 4834 switch_to_thread (find_thread_ptid (this, curr_thread));
b7ea362b 4835 }
74531fed 4836
6e586cc5
YQ
4837 /* init_wait_for_inferior should be called before get_offsets in order
4838 to manage `inserted' flag in bp loc in a correct state.
4839 breakpoint_init_inferior, called from init_wait_for_inferior, set
4840 `inserted' flag to 0, while before breakpoint_re_set, called from
4841 start_remote, set `inserted' flag to 1. In the initialization of
4842 inferior, breakpoint_init_inferior should be called first, and then
4843 breakpoint_re_set can be called. If this order is broken, state of
4844 `inserted' flag is wrong, and cause some problems on breakpoint
4845 manipulation. */
4846 init_wait_for_inferior ();
4847
74531fed
PA
4848 get_offsets (); /* Get text, data & bss offsets. */
4849
d962ef82
DJ
4850 /* If we could not find a description using qXfer, and we know
4851 how to do it some other way, try again. This is not
4852 supported for non-stop; it could be, but it is tricky if
4853 there are no stopped threads when we connect. */
f6ac5f3d 4854 if (remote_read_description_p (this)
f5656ead 4855 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4856 {
4857 target_clear_description ();
4858 target_find_description ();
4859 }
4860
74531fed
PA
4861 /* Use the previously fetched status. */
4862 gdb_assert (wait_status != NULL);
8d64371b 4863 strcpy (rs->buf.data (), wait_status);
74531fed
PA
4864 rs->cached_wait_status = 1;
4865
f6ac5f3d 4866 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4867 }
4868 else
4869 {
68c97600
PA
4870 /* Clear WFI global state. Do this before finding about new
4871 threads and inferiors, and setting the current inferior.
4872 Otherwise we would clear the proceed status of the current
4873 inferior when we want its stop_soon state to be preserved
4874 (see notice_new_inferior). */
4875 init_wait_for_inferior ();
4876
74531fed
PA
4877 /* In non-stop, we will either get an "OK", meaning that there
4878 are no stopped threads at this time; or, a regular stop
4879 reply. In the latter case, there may be more than one thread
4880 stopped --- we pull them all out using the vStopped
4881 mechanism. */
8d64371b 4882 if (strcmp (rs->buf.data (), "OK") != 0)
74531fed 4883 {
722247f1 4884 struct notif_client *notif = &notif_client_stop;
2d717e4f 4885
722247f1
YQ
4886 /* remote_notif_get_pending_replies acks this one, and gets
4887 the rest out. */
f48ff2a7 4888 rs->notif_state->pending_event[notif_client_stop.id]
8d64371b 4889 = remote_notif_parse (this, notif, rs->buf.data ());
722247f1 4890 remote_notif_get_pending_events (notif);
74531fed 4891 }
2d717e4f 4892
5b6d1e4f 4893 if (thread_count (this) == 0)
74531fed 4894 {
04bd08de 4895 if (!extended_p)
74531fed 4896 error (_("The target is not running (try extended-remote?)"));
82f73884 4897
c35b1492
PA
4898 /* We're connected, but not running. Drop out before we
4899 call start_remote. */
e278ad5b 4900 rs->starting_up = 0;
c35b1492
PA
4901 return;
4902 }
74531fed 4903
74531fed
PA
4904 /* In non-stop mode, any cached wait status will be stored in
4905 the stop reply queue. */
4906 gdb_assert (wait_status == NULL);
f0223081 4907
2455069d 4908 /* Report all signals during attach/startup. */
adc6a863 4909 pass_signals ({});
221e1a37
PA
4910
4911 /* If there are already stopped threads, mark them stopped and
4912 report their stops before giving the prompt to the user. */
6efcd9a8 4913 process_initial_stop_replies (from_tty);
221e1a37
PA
4914
4915 if (target_can_async_p ())
4916 target_async (1);
74531fed 4917 }
c8d104ad 4918
c8d104ad 4919 /* If we connected to a live target, do some additional setup. */
55f6301a 4920 if (target_has_execution ())
c8d104ad 4921 {
a42d7dd8
TT
4922 /* No use without a symbol-file. */
4923 if (current_program_space->symfile_object_file)
36d25514 4924 remote_check_symbols ();
c8d104ad 4925 }
50c71eaf 4926
d5551862
SS
4927 /* Possibly the target has been engaged in a trace run started
4928 previously; find out where things are at. */
f6ac5f3d 4929 if (get_trace_status (current_trace_status ()) != -1)
d5551862 4930 {
00bf0b85 4931 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4932
00bf0b85
SS
4933 if (current_trace_status ()->running)
4934 printf_filtered (_("Trace is already running on the target.\n"));
4935
f6ac5f3d 4936 upload_tracepoints (&uploaded_tps);
00bf0b85
SS
4937
4938 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4939 }
4940
c0272db5
TW
4941 /* Possibly the target has been engaged in a btrace record started
4942 previously; find out where things are at. */
4943 remote_btrace_maybe_reopen ();
4944
1e51243a
PA
4945 /* The thread and inferior lists are now synchronized with the
4946 target, our symbols have been relocated, and we're merged the
4947 target's tracepoints with ours. We're done with basic start
4948 up. */
4949 rs->starting_up = 0;
4950
a25a5a45
PA
4951 /* Maybe breakpoints are global and need to be inserted now. */
4952 if (breakpoints_should_be_inserted_now ())
50c71eaf 4953 insert_breakpoints ();
c906108c
SS
4954}
4955
121b3efd
PA
4956const char *
4957remote_target::connection_string ()
4958{
4959 remote_state *rs = get_remote_state ();
4960
4961 if (rs->remote_desc->name != NULL)
4962 return rs->remote_desc->name;
4963 else
4964 return NULL;
4965}
4966
c906108c
SS
4967/* Open a connection to a remote debugger.
4968 NAME is the filename used for communication. */
4969
f6ac5f3d
PA
4970void
4971remote_target::open (const char *name, int from_tty)
c906108c 4972{
f6ac5f3d 4973 open_1 (name, from_tty, 0);
43ff13b4
JM
4974}
4975
c906108c
SS
4976/* Open a connection to a remote debugger using the extended
4977 remote gdb protocol. NAME is the filename used for communication. */
4978
f6ac5f3d
PA
4979void
4980extended_remote_target::open (const char *name, int from_tty)
c906108c 4981{
f6ac5f3d 4982 open_1 (name, from_tty, 1 /*extended_p */);
43ff13b4
JM
4983}
4984
ca4f7f8b
PA
4985/* Reset all packets back to "unknown support". Called when opening a
4986 new connection to a remote target. */
c906108c 4987
d471ea57 4988static void
ca4f7f8b 4989reset_all_packet_configs_support (void)
d471ea57
AC
4990{
4991 int i;
a744cf53 4992
444abaca 4993 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4994 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4995}
4996
ca4f7f8b
PA
4997/* Initialize all packet configs. */
4998
4999static void
5000init_all_packet_configs (void)
5001{
5002 int i;
5003
5004 for (i = 0; i < PACKET_MAX; i++)
5005 {
5006 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5007 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5008 }
5009}
5010
23860348 5011/* Symbol look-up. */
dc8acb97 5012
6b8edb51
PA
5013void
5014remote_target::remote_check_symbols ()
dc8acb97 5015{
8d64371b 5016 char *tmp;
dc8acb97
MS
5017 int end;
5018
63154eca
PA
5019 /* The remote side has no concept of inferiors that aren't running
5020 yet, it only knows about running processes. If we're connected
5021 but our current inferior is not running, we should not invite the
5022 remote target to request symbol lookups related to its
5023 (unrelated) current process. */
55f6301a 5024 if (!target_has_execution ())
63154eca
PA
5025 return;
5026
4082afcc 5027 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
5028 return;
5029
63154eca
PA
5030 /* Make sure the remote is pointing at the right process. Note
5031 there's no way to select "no process". */
3c9c4b83
PA
5032 set_general_process ();
5033
6d820c5c
DJ
5034 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5035 because we need both at the same time. */
66644cd3 5036 gdb::char_vector msg (get_remote_packet_size ());
8d64371b 5037 gdb::char_vector reply (get_remote_packet_size ());
6d820c5c 5038
23860348 5039 /* Invite target to request symbol lookups. */
dc8acb97
MS
5040
5041 putpkt ("qSymbol::");
8d64371b 5042 getpkt (&reply, 0);
28170b88 5043 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
dc8acb97 5044
8d64371b 5045 while (startswith (reply.data (), "qSymbol:"))
dc8acb97 5046 {
77e371c0
TT
5047 struct bound_minimal_symbol sym;
5048
dc8acb97 5049 tmp = &reply[8];
66644cd3
AB
5050 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5051 strlen (tmp) / 2);
dc8acb97 5052 msg[end] = '\0';
66644cd3 5053 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
3b7344d5 5054 if (sym.minsym == NULL)
66644cd3
AB
5055 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5056 &reply[8]);
dc8acb97 5057 else
2bbe3cc1 5058 {
f5656ead 5059 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 5060 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
5061
5062 /* If this is a function address, return the start of code
5063 instead of any data function descriptor. */
f5656ead 5064 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1 5065 sym_addr,
8b88a78e 5066 current_top_target ());
2bbe3cc1 5067
66644cd3 5068 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 5069 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1 5070 }
66644cd3
AB
5071
5072 putpkt (msg.data ());
8d64371b 5073 getpkt (&reply, 0);
dc8acb97
MS
5074 }
5075}
5076
9db8d71f 5077static struct serial *
baa336ce 5078remote_serial_open (const char *name)
9db8d71f
DJ
5079{
5080 static int udp_warning = 0;
5081
5082 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5083 of in ser-tcp.c, because it is the remote protocol assuming that the
5084 serial connection is reliable and not the serial connection promising
5085 to be. */
61012eef 5086 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 5087 {
3e43a32a
MS
5088 warning (_("The remote protocol may be unreliable over UDP.\n"
5089 "Some events may be lost, rendering further debugging "
5090 "impossible."));
9db8d71f
DJ
5091 udp_warning = 1;
5092 }
5093
5094 return serial_open (name);
5095}
5096
d914c394
SS
5097/* Inform the target of our permission settings. The permission flags
5098 work without this, but if the target knows the settings, it can do
5099 a couple things. First, it can add its own check, to catch cases
5100 that somehow manage to get by the permissions checks in target
5101 methods. Second, if the target is wired to disallow particular
5102 settings (for instance, a system in the field that is not set up to
5103 be able to stop at a breakpoint), it can object to any unavailable
5104 permissions. */
5105
5106void
f6ac5f3d 5107remote_target::set_permissions ()
d914c394
SS
5108{
5109 struct remote_state *rs = get_remote_state ();
5110
8d64371b 5111 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
bba74b36
YQ
5112 "WriteReg:%x;WriteMem:%x;"
5113 "InsertBreak:%x;InsertTrace:%x;"
5114 "InsertFastTrace:%x;Stop:%x",
5115 may_write_registers, may_write_memory,
5116 may_insert_breakpoints, may_insert_tracepoints,
5117 may_insert_fast_tracepoints, may_stop);
d914c394 5118 putpkt (rs->buf);
8d64371b 5119 getpkt (&rs->buf, 0);
d914c394
SS
5120
5121 /* If the target didn't like the packet, warn the user. Do not try
5122 to undo the user's settings, that would just be maddening. */
8d64371b
TT
5123 if (strcmp (rs->buf.data (), "OK") != 0)
5124 warning (_("Remote refused setting permissions with: %s"),
5125 rs->buf.data ());
d914c394
SS
5126}
5127
be2a5f71
DJ
5128/* This type describes each known response to the qSupported
5129 packet. */
5130struct protocol_feature
5131{
5132 /* The name of this protocol feature. */
5133 const char *name;
5134
5135 /* The default for this protocol feature. */
5136 enum packet_support default_support;
5137
5138 /* The function to call when this feature is reported, or after
5139 qSupported processing if the feature is not supported.
5140 The first argument points to this structure. The second
5141 argument indicates whether the packet requested support be
5142 enabled, disabled, or probed (or the default, if this function
5143 is being called at the end of processing and this feature was
5144 not reported). The third argument may be NULL; if not NULL, it
5145 is a NUL-terminated string taken from the packet following
5146 this feature's name and an equals sign. */
6b8edb51
PA
5147 void (*func) (remote_target *remote, const struct protocol_feature *,
5148 enum packet_support, const char *);
be2a5f71
DJ
5149
5150 /* The corresponding packet for this feature. Only used if
5151 FUNC is remote_supported_packet. */
5152 int packet;
5153};
5154
be2a5f71 5155static void
6b8edb51
PA
5156remote_supported_packet (remote_target *remote,
5157 const struct protocol_feature *feature,
be2a5f71
DJ
5158 enum packet_support support,
5159 const char *argument)
5160{
5161 if (argument)
5162 {
5163 warning (_("Remote qSupported response supplied an unexpected value for"
5164 " \"%s\"."), feature->name);
5165 return;
5166 }
5167
4082afcc 5168 remote_protocol_packets[feature->packet].support = support;
be2a5f71 5169}
be2a5f71 5170
6b8edb51
PA
5171void
5172remote_target::remote_packet_size (const protocol_feature *feature,
5173 enum packet_support support, const char *value)
be2a5f71
DJ
5174{
5175 struct remote_state *rs = get_remote_state ();
5176
5177 int packet_size;
5178 char *value_end;
5179
5180 if (support != PACKET_ENABLE)
5181 return;
5182
5183 if (value == NULL || *value == '\0')
5184 {
5185 warning (_("Remote target reported \"%s\" without a size."),
5186 feature->name);
5187 return;
5188 }
5189
5190 errno = 0;
5191 packet_size = strtol (value, &value_end, 16);
5192 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5193 {
5194 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5195 feature->name, value);
5196 return;
5197 }
5198
be2a5f71
DJ
5199 /* Record the new maximum packet size. */
5200 rs->explicit_packet_size = packet_size;
5201}
5202
cb8c24b6 5203static void
6b8edb51
PA
5204remote_packet_size (remote_target *remote, const protocol_feature *feature,
5205 enum packet_support support, const char *value)
5206{
5207 remote->remote_packet_size (feature, support, value);
5208}
5209
dc473cfb 5210static const struct protocol_feature remote_protocol_features[] = {
0876f84a 5211 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 5212 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 5213 PACKET_qXfer_auxv },
c78fa86a
GB
5214 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5215 PACKET_qXfer_exec_file },
23181151
DJ
5216 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5217 PACKET_qXfer_features },
cfa9d6d9
DJ
5218 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5219 PACKET_qXfer_libraries },
2268b414
JK
5220 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5221 PACKET_qXfer_libraries_svr4 },
ced63ec0 5222 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 5223 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 5224 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 5225 PACKET_qXfer_memory_map },
07e059b5
VP
5226 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5227 PACKET_qXfer_osdata },
dc146f7c
VP
5228 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5229 PACKET_qXfer_threads },
b3b9301e
PA
5230 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5231 PACKET_qXfer_traceframe_info },
89be2091
DJ
5232 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5233 PACKET_QPassSignals },
82075af2
JS
5234 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5235 PACKET_QCatchSyscalls },
9b224c5e
PA
5236 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5237 PACKET_QProgramSignals },
bc3b087d
SDJ
5238 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5239 PACKET_QSetWorkingDir },
aefd8b33
SDJ
5240 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5241 PACKET_QStartupWithShell },
0a2dde4a
SDJ
5242 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5243 PACKET_QEnvironmentHexEncoded },
5244 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5245 PACKET_QEnvironmentReset },
5246 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5247 PACKET_QEnvironmentUnset },
a6f3e723
SL
5248 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5249 PACKET_QStartNoAckMode },
4082afcc
PA
5250 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5251 PACKET_multiprocess_feature },
5252 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
5253 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5254 PACKET_qXfer_siginfo_read },
5255 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5256 PACKET_qXfer_siginfo_write },
4082afcc 5257 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 5258 PACKET_ConditionalTracepoints },
4082afcc 5259 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 5260 PACKET_ConditionalBreakpoints },
4082afcc 5261 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 5262 PACKET_BreakpointCommands },
4082afcc 5263 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 5264 PACKET_FastTracepoints },
4082afcc 5265 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 5266 PACKET_StaticTracepoints },
4082afcc 5267 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 5268 PACKET_InstallInTrace},
4082afcc
PA
5269 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5270 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
5271 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5272 PACKET_bc },
5273 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5274 PACKET_bs },
409873ef
SS
5275 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5276 PACKET_TracepointSource },
d914c394
SS
5277 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5278 PACKET_QAllow },
4082afcc
PA
5279 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5280 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
5281 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5282 PACKET_qXfer_fdpic },
169081d0
TG
5283 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5284 PACKET_qXfer_uib },
03583c20
UW
5285 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5286 PACKET_QDisableRandomization },
d1feda86 5287 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
5288 { "QTBuffer:size", PACKET_DISABLE,
5289 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 5290 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
5291 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5292 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 5293 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 5294 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
5295 PACKET_qXfer_btrace },
5296 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
5297 PACKET_qXfer_btrace_conf },
5298 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
5299 PACKET_Qbtrace_conf_bts_size },
5300 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 5301 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
5302 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5303 PACKET_fork_event_feature },
5304 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5305 PACKET_vfork_event_feature },
94585166
DB
5306 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5307 PACKET_exec_event_feature },
b20a6524 5308 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 5309 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
5310 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5311 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 5312 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
be2a5f71
DJ
5313};
5314
c8d5aac9
L
5315static char *remote_support_xml;
5316
5317/* Register string appended to "xmlRegisters=" in qSupported query. */
5318
5319void
6e39997a 5320register_remote_support_xml (const char *xml)
c8d5aac9
L
5321{
5322#if defined(HAVE_LIBEXPAT)
5323 if (remote_support_xml == NULL)
c4f7c687 5324 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
5325 else
5326 {
5327 char *copy = xstrdup (remote_support_xml + 13);
ca3a04f6
CB
5328 char *saveptr;
5329 char *p = strtok_r (copy, ",", &saveptr);
c8d5aac9
L
5330
5331 do
5332 {
5333 if (strcmp (p, xml) == 0)
5334 {
5335 /* already there */
5336 xfree (copy);
5337 return;
5338 }
5339 }
ca3a04f6 5340 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
c8d5aac9
L
5341 xfree (copy);
5342
94b0dee1
PA
5343 remote_support_xml = reconcat (remote_support_xml,
5344 remote_support_xml, ",", xml,
5345 (char *) NULL);
c8d5aac9
L
5346 }
5347#endif
5348}
5349
69b6ecb0
TT
5350static void
5351remote_query_supported_append (std::string *msg, const char *append)
c8d5aac9 5352{
69b6ecb0
TT
5353 if (!msg->empty ())
5354 msg->append (";");
5355 msg->append (append);
c8d5aac9
L
5356}
5357
6b8edb51
PA
5358void
5359remote_target::remote_query_supported ()
be2a5f71
DJ
5360{
5361 struct remote_state *rs = get_remote_state ();
5362 char *next;
5363 int i;
5364 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5365
5366 /* The packet support flags are handled differently for this packet
5367 than for most others. We treat an error, a disabled packet, and
5368 an empty response identically: any features which must be reported
5369 to be used will be automatically disabled. An empty buffer
5370 accomplishes this, since that is also the representation for a list
5371 containing no features. */
5372
5373 rs->buf[0] = 0;
4082afcc 5374 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 5375 {
69b6ecb0 5376 std::string q;
c8d5aac9 5377
73b8c1fd 5378 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5379 remote_query_supported_append (&q, "multiprocess+");
c8d5aac9 5380
f7e6eed5 5381 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5382 remote_query_supported_append (&q, "swbreak+");
f7e6eed5 5383 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5384 remote_query_supported_append (&q, "hwbreak+");
f7e6eed5 5385
69b6ecb0 5386 remote_query_supported_append (&q, "qRelocInsn+");
dde08ee1 5387
8020350c
DB
5388 if (packet_set_cmd_state (PACKET_fork_event_feature)
5389 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5390 remote_query_supported_append (&q, "fork-events+");
8020350c
DB
5391 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5392 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5393 remote_query_supported_append (&q, "vfork-events+");
8020350c
DB
5394 if (packet_set_cmd_state (PACKET_exec_event_feature)
5395 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5396 remote_query_supported_append (&q, "exec-events+");
89245bc0 5397
750ce8d1 5398 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5399 remote_query_supported_append (&q, "vContSupported+");
750ce8d1 5400
65706a29 5401 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5402 remote_query_supported_append (&q, "QThreadEvents+");
65706a29 5403
f2faf941 5404 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5405 remote_query_supported_append (&q, "no-resumed+");
f2faf941 5406
b35d5edb
PA
5407 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5408 the qSupported:xmlRegisters=i386 handling. */
7cc244de
PA
5409 if (remote_support_xml != NULL
5410 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
69b6ecb0 5411 remote_query_supported_append (&q, remote_support_xml);
82f73884 5412
69b6ecb0
TT
5413 q = "qSupported:" + q;
5414 putpkt (q.c_str ());
94b0dee1 5415
8d64371b 5416 getpkt (&rs->buf, 0);
be2a5f71
DJ
5417
5418 /* If an error occured, warn, but do not return - just reset the
5419 buffer to empty and go on to disable features. */
5420 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5421 == PACKET_ERROR)
5422 {
8d64371b 5423 warning (_("Remote failure reply: %s"), rs->buf.data ());
be2a5f71
DJ
5424 rs->buf[0] = 0;
5425 }
5426 }
5427
5428 memset (seen, 0, sizeof (seen));
5429
8d64371b 5430 next = rs->buf.data ();
be2a5f71
DJ
5431 while (*next)
5432 {
5433 enum packet_support is_supported;
5434 char *p, *end, *name_end, *value;
5435
5436 /* First separate out this item from the rest of the packet. If
5437 there's another item after this, we overwrite the separator
5438 (terminated strings are much easier to work with). */
5439 p = next;
5440 end = strchr (p, ';');
5441 if (end == NULL)
5442 {
5443 end = p + strlen (p);
5444 next = end;
5445 }
5446 else
5447 {
89be2091
DJ
5448 *end = '\0';
5449 next = end + 1;
5450
be2a5f71
DJ
5451 if (end == p)
5452 {
5453 warning (_("empty item in \"qSupported\" response"));
5454 continue;
5455 }
be2a5f71
DJ
5456 }
5457
5458 name_end = strchr (p, '=');
5459 if (name_end)
5460 {
5461 /* This is a name=value entry. */
5462 is_supported = PACKET_ENABLE;
5463 value = name_end + 1;
5464 *name_end = '\0';
5465 }
5466 else
5467 {
5468 value = NULL;
5469 switch (end[-1])
5470 {
5471 case '+':
5472 is_supported = PACKET_ENABLE;
5473 break;
5474
5475 case '-':
5476 is_supported = PACKET_DISABLE;
5477 break;
5478
5479 case '?':
5480 is_supported = PACKET_SUPPORT_UNKNOWN;
5481 break;
5482
5483 default:
3e43a32a
MS
5484 warning (_("unrecognized item \"%s\" "
5485 "in \"qSupported\" response"), p);
be2a5f71
DJ
5486 continue;
5487 }
5488 end[-1] = '\0';
5489 }
5490
5491 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5492 if (strcmp (remote_protocol_features[i].name, p) == 0)
5493 {
5494 const struct protocol_feature *feature;
5495
5496 seen[i] = 1;
5497 feature = &remote_protocol_features[i];
6b8edb51 5498 feature->func (this, feature, is_supported, value);
be2a5f71
DJ
5499 break;
5500 }
5501 }
5502
5503 /* If we increased the packet size, make sure to increase the global
5504 buffer size also. We delay this until after parsing the entire
5505 qSupported packet, because this is the same buffer we were
5506 parsing. */
8d64371b
TT
5507 if (rs->buf.size () < rs->explicit_packet_size)
5508 rs->buf.resize (rs->explicit_packet_size);
be2a5f71
DJ
5509
5510 /* Handle the defaults for unmentioned features. */
5511 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5512 if (!seen[i])
5513 {
5514 const struct protocol_feature *feature;
5515
5516 feature = &remote_protocol_features[i];
6b8edb51 5517 feature->func (this, feature, feature->default_support, NULL);
be2a5f71
DJ
5518 }
5519}
5520
048094ac
PA
5521/* Serial QUIT handler for the remote serial descriptor.
5522
5523 Defers handling a Ctrl-C until we're done with the current
5524 command/response packet sequence, unless:
5525
5526 - We're setting up the connection. Don't send a remote interrupt
5527 request, as we're not fully synced yet. Quit immediately
5528 instead.
5529
5530 - The target has been resumed in the foreground
223ffa71 5531 (target_terminal::is_ours is false) with a synchronous resume
048094ac
PA
5532 packet, and we're blocked waiting for the stop reply, thus a
5533 Ctrl-C should be immediately sent to the target.
5534
5535 - We get a second Ctrl-C while still within the same serial read or
5536 write. In that case the serial is seemingly wedged --- offer to
5537 quit/disconnect.
5538
5539 - We see a second Ctrl-C without target response, after having
5540 previously interrupted the target. In that case the target/stub
5541 is probably wedged --- offer to quit/disconnect.
5542*/
5543
6b8edb51
PA
5544void
5545remote_target::remote_serial_quit_handler ()
048094ac
PA
5546{
5547 struct remote_state *rs = get_remote_state ();
5548
5549 if (check_quit_flag ())
5550 {
5551 /* If we're starting up, we're not fully synced yet. Quit
5552 immediately. */
5553 if (rs->starting_up)
5554 quit ();
5555 else if (rs->got_ctrlc_during_io)
5556 {
5557 if (query (_("The target is not responding to GDB commands.\n"
5558 "Stop debugging it? ")))
5b6d1e4f 5559 remote_unpush_and_throw (this);
048094ac
PA
5560 }
5561 /* If ^C has already been sent once, offer to disconnect. */
223ffa71 5562 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
048094ac
PA
5563 interrupt_query ();
5564 /* All-stop protocol, and blocked waiting for stop reply. Send
5565 an interrupt request. */
223ffa71 5566 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
e671cd59 5567 target_interrupt ();
048094ac
PA
5568 else
5569 rs->got_ctrlc_during_io = 1;
5570 }
5571}
5572
6b8edb51
PA
5573/* The remote_target that is current while the quit handler is
5574 overridden with remote_serial_quit_handler. */
5575static remote_target *curr_quit_handler_target;
5576
5577static void
5578remote_serial_quit_handler ()
5579{
5580 curr_quit_handler_target->remote_serial_quit_handler ();
5581}
5582
5b6d1e4f
PA
5583/* Remove the remote target from the target stack of each inferior
5584 that is using it. Upper targets depend on it so remove them
5585 first. */
78a095c3
JK
5586
5587static void
5b6d1e4f 5588remote_unpush_target (remote_target *target)
78a095c3 5589{
5b6d1e4f
PA
5590 /* We have to unpush the target from all inferiors, even those that
5591 aren't running. */
5592 scoped_restore_current_inferior restore_current_inferior;
5593
5594 for (inferior *inf : all_inferiors (target))
5595 {
5596 switch_to_inferior_no_thread (inf);
5597 pop_all_targets_at_and_above (process_stratum);
5598 generic_mourn_inferior ();
5599 }
78a095c3 5600}
be2a5f71 5601
048094ac 5602static void
5b6d1e4f 5603remote_unpush_and_throw (remote_target *target)
048094ac 5604{
5b6d1e4f 5605 remote_unpush_target (target);
048094ac
PA
5606 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5607}
5608
f6ac5f3d
PA
5609void
5610remote_target::open_1 (const char *name, int from_tty, int extended_p)
c906108c 5611{
6b8edb51 5612 remote_target *curr_remote = get_current_remote_target ();
a6f3e723 5613
c906108c 5614 if (name == 0)
8a3fe4f8 5615 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 5616 "serial device is attached to the remote system\n"
8a3fe4f8 5617 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 5618
2d717e4f 5619 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
5620 Ask this question first, before target_preopen has a chance to kill
5621 anything. */
55f6301a 5622 if (curr_remote != NULL && !target_has_execution ())
2d717e4f 5623 {
78a095c3
JK
5624 if (from_tty
5625 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
5626 error (_("Still connected."));
5627 }
5628
78a095c3 5629 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
5630 target_preopen (from_tty);
5631
ad9a8f3f 5632 remote_fileio_reset ();
1dd41f16
NS
5633 reopen_exec_file ();
5634 reread_symbols ();
5635
6b8edb51
PA
5636 remote_target *remote
5637 = (extended_p ? new extended_remote_target () : new remote_target ());
5638 target_ops_up target_holder (remote);
5639
5640 remote_state *rs = remote->get_remote_state ();
5641
5642 /* See FIXME above. */
5643 if (!target_async_permitted)
5644 rs->wait_forever_enabled_p = 1;
5645
5d93a237
TT
5646 rs->remote_desc = remote_serial_open (name);
5647 if (!rs->remote_desc)
c906108c
SS
5648 perror_with_name (name);
5649
5650 if (baud_rate != -1)
5651 {
5d93a237 5652 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 5653 {
9b74d5d3
KB
5654 /* The requested speed could not be set. Error out to
5655 top level after closing remote_desc. Take care to
5656 set remote_desc to NULL to avoid closing remote_desc
5657 more than once. */
5d93a237
TT
5658 serial_close (rs->remote_desc);
5659 rs->remote_desc = NULL;
c906108c
SS
5660 perror_with_name (name);
5661 }
5662 }
5663
236af5e3 5664 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 5665 serial_raw (rs->remote_desc);
c906108c
SS
5666
5667 /* If there is something sitting in the buffer we might take it as a
5668 response to a command, which would be bad. */
5d93a237 5669 serial_flush_input (rs->remote_desc);
c906108c
SS
5670
5671 if (from_tty)
5672 {
5673 puts_filtered ("Remote debugging using ");
5674 puts_filtered (name);
5675 puts_filtered ("\n");
5676 }
d9f719f1 5677
6b8edb51 5678 /* Switch to using the remote target now. */
dea57a62 5679 push_target (std::move (target_holder));
c906108c 5680
74531fed 5681 /* Register extra event sources in the event loop. */
6b8edb51 5682 rs->remote_async_inferior_event_token
db20ebdf
SM
5683 = create_async_event_handler (remote_async_inferior_event_handler, remote,
5684 "remote");
6b8edb51 5685 rs->notif_state = remote_notif_state_allocate (remote);
74531fed 5686
be2a5f71
DJ
5687 /* Reset the target state; these things will be queried either by
5688 remote_query_supported or as they are needed. */
ca4f7f8b 5689 reset_all_packet_configs_support ();
74531fed 5690 rs->cached_wait_status = 0;
be2a5f71 5691 rs->explicit_packet_size = 0;
a6f3e723 5692 rs->noack_mode = 0;
82f73884 5693 rs->extended = extended_p;
e24a49d8 5694 rs->waiting_for_stop_reply = 0;
3a29589a 5695 rs->ctrlc_pending_p = 0;
048094ac 5696 rs->got_ctrlc_during_io = 0;
802188a7 5697
47f8a51d
TT
5698 rs->general_thread = not_sent_ptid;
5699 rs->continue_thread = not_sent_ptid;
262e1174 5700 rs->remote_traceframe_number = -1;
c906108c 5701
3a00c802
PA
5702 rs->last_resume_exec_dir = EXEC_FORWARD;
5703
9d1f7ab2 5704 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
5705 rs->use_threadinfo_query = 1;
5706 rs->use_threadextra_query = 1;
9d1f7ab2 5707
dd194f6b 5708 rs->readahead_cache.invalidate ();
80152258 5709
c6ebd6cf 5710 if (target_async_permitted)
92d1e331 5711 {
92d1e331
DJ
5712 /* FIXME: cagney/1999-09-23: During the initial connection it is
5713 assumed that the target is already ready and able to respond to
0df8b418 5714 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 5715 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 5716 around this. Eventually a mechanism that allows
92d1e331 5717 wait_for_inferior() to expect/get timeouts will be
23860348 5718 implemented. */
6b8edb51 5719 rs->wait_forever_enabled_p = 0;
92d1e331
DJ
5720 }
5721
23860348 5722 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 5723 no_shared_libraries (NULL, 0);
f78f6cf1 5724
36918e70 5725 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
5726 target (we'd otherwise be in an inconsistent state) and then
5727 propogate the error on up the exception chain. This ensures that
5728 the caller doesn't stumble along blindly assuming that the
5729 function succeeded. The CLI doesn't have this problem but other
5730 UI's, such as MI do.
36918e70
AC
5731
5732 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5733 this function should return an error indication letting the
ce2826aa 5734 caller restore the previous state. Unfortunately the command
36918e70
AC
5735 ``target remote'' is directly wired to this function making that
5736 impossible. On a positive note, the CLI side of this problem has
5737 been fixed - the function set_cmd_context() makes it possible for
5738 all the ``target ....'' commands to share a common callback
5739 function. See cli-dump.c. */
109c3e39 5740 {
2d717e4f 5741
a70b8144 5742 try
04bd08de 5743 {
6b8edb51 5744 remote->start_remote (from_tty, extended_p);
04bd08de 5745 }
230d2906 5746 catch (const gdb_exception &ex)
109c3e39 5747 {
c8d104ad
PA
5748 /* Pop the partially set up target - unless something else did
5749 already before throwing the exception. */
6b8edb51 5750 if (ex.error != TARGET_CLOSE_ERROR)
5b6d1e4f 5751 remote_unpush_target (remote);
eedc3f4f 5752 throw;
109c3e39
AC
5753 }
5754 }
c906108c 5755
6b8edb51 5756 remote_btrace_reset (rs);
f4abbc16 5757
c6ebd6cf 5758 if (target_async_permitted)
6b8edb51 5759 rs->wait_forever_enabled_p = 1;
43ff13b4
JM
5760}
5761
de0d863e
DB
5762/* Detach the specified process. */
5763
6b8edb51
PA
5764void
5765remote_target::remote_detach_pid (int pid)
de0d863e
DB
5766{
5767 struct remote_state *rs = get_remote_state ();
5768
4c7333b3
PA
5769 /* This should not be necessary, but the handling for D;PID in
5770 GDBserver versions prior to 8.2 incorrectly assumes that the
5771 selected process points to the same process we're detaching,
5772 leading to misbehavior (and possibly GDBserver crashing) when it
5773 does not. Since it's easy and cheap, work around it by forcing
5774 GDBserver to select GDB's current process. */
5775 set_general_process ();
5776
de0d863e 5777 if (remote_multi_process_p (rs))
8d64371b 5778 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
de0d863e 5779 else
8d64371b 5780 strcpy (rs->buf.data (), "D");
de0d863e
DB
5781
5782 putpkt (rs->buf);
8d64371b 5783 getpkt (&rs->buf, 0);
de0d863e
DB
5784
5785 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5786 ;
5787 else if (rs->buf[0] == '\0')
5788 error (_("Remote doesn't know how to detach"));
5789 else
5790 error (_("Can't detach process."));
5791}
5792
5793/* This detaches a program to which we previously attached, using
5794 inferior_ptid to identify the process. After this is done, GDB
5795 can be used to debug some other program. We better not have left
5796 any breakpoints in the target program or it'll die when it hits
5797 one. */
c906108c 5798
6b8edb51 5799void
00431a78 5800remote_target::remote_detach_1 (inferior *inf, int from_tty)
c906108c 5801{
e99b03dc 5802 int pid = inferior_ptid.pid ();
d01949b6 5803 struct remote_state *rs = get_remote_state ();
de0d863e 5804 int is_fork_parent;
c906108c 5805
55f6301a 5806 if (!target_has_execution ())
2d717e4f
DJ
5807 error (_("No process to detach from."));
5808
0f48b757 5809 target_announce_detach (from_tty);
7cee1e54 5810
c906108c 5811 /* Tell the remote target to detach. */
de0d863e 5812 remote_detach_pid (pid);
82f73884 5813
8020350c 5814 /* Exit only if this is the only active inferior. */
5b6d1e4f 5815 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
7cee1e54 5816 puts_filtered (_("Ending remote debugging.\n"));
82f73884 5817
5b6d1e4f 5818 thread_info *tp = find_thread_ptid (this, inferior_ptid);
00431a78 5819
de0d863e
DB
5820 /* Check to see if we are detaching a fork parent. Note that if we
5821 are detaching a fork child, tp == NULL. */
5822 is_fork_parent = (tp != NULL
5823 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5824
5825 /* If doing detach-on-fork, we don't mourn, because that will delete
5826 breakpoints that should be available for the followed inferior. */
5827 if (!is_fork_parent)
f67c0c91 5828 {
249b5733
PA
5829 /* Save the pid as a string before mourning, since that will
5830 unpush the remote target, and we need the string after. */
f2907e49 5831 std::string infpid = target_pid_to_str (ptid_t (pid));
f67c0c91
SDJ
5832
5833 target_mourn_inferior (inferior_ptid);
5834 if (print_inferior_events)
5835 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5836 inf->num, infpid.c_str ());
5837 }
de0d863e
DB
5838 else
5839 {
0ac55310 5840 switch_to_no_thread ();
00431a78 5841 detach_inferior (current_inferior ());
de0d863e 5842 }
2d717e4f
DJ
5843}
5844
f6ac5f3d
PA
5845void
5846remote_target::detach (inferior *inf, int from_tty)
2d717e4f 5847{
00431a78 5848 remote_detach_1 (inf, from_tty);
2d717e4f
DJ
5849}
5850
f6ac5f3d
PA
5851void
5852extended_remote_target::detach (inferior *inf, int from_tty)
2d717e4f 5853{
00431a78 5854 remote_detach_1 (inf, from_tty);
de0d863e
DB
5855}
5856
5857/* Target follow-fork function for remote targets. On entry, and
5858 at return, the current inferior is the fork parent.
5859
5860 Note that although this is currently only used for extended-remote,
5861 it is named remote_follow_fork in anticipation of using it for the
5862 remote target as well. */
5863
5ab2fbf1
SM
5864bool
5865remote_target::follow_fork (bool follow_child, bool detach_fork)
de0d863e
DB
5866{
5867 struct remote_state *rs = get_remote_state ();
c269dbdb 5868 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5869
c269dbdb
DB
5870 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5871 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5872 {
5873 /* When following the parent and detaching the child, we detach
5874 the child here. For the case of following the child and
5875 detaching the parent, the detach is done in the target-
5876 independent follow fork code in infrun.c. We can't use
5877 target_detach when detaching an unfollowed child because
5878 the client side doesn't know anything about the child. */
5879 if (detach_fork && !follow_child)
5880 {
5881 /* Detach the fork child. */
5882 ptid_t child_ptid;
5883 pid_t child_pid;
5884
5885 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
e99b03dc 5886 child_pid = child_ptid.pid ();
de0d863e
DB
5887
5888 remote_detach_pid (child_pid);
de0d863e
DB
5889 }
5890 }
5ab2fbf1
SM
5891
5892 return false;
c906108c
SS
5893}
5894
94585166
DB
5895/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5896 in the program space of the new inferior. On entry and at return the
5897 current inferior is the exec'ing inferior. INF is the new exec'd
5898 inferior, which may be the same as the exec'ing inferior unless
5899 follow-exec-mode is "new". */
5900
f6ac5f3d 5901void
4ca51187 5902remote_target::follow_exec (struct inferior *inf, const char *execd_pathname)
94585166
DB
5903{
5904 /* We know that this is a target file name, so if it has the "target:"
5905 prefix we strip it off before saving it in the program space. */
5906 if (is_target_filename (execd_pathname))
5907 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5908
5909 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5910}
5911
6ad8ae5c
DJ
5912/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5913
f6ac5f3d
PA
5914void
5915remote_target::disconnect (const char *args, int from_tty)
43ff13b4 5916{
43ff13b4 5917 if (args)
2d717e4f 5918 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5919
8020350c 5920 /* Make sure we unpush even the extended remote targets. Calling
5b6d1e4f
PA
5921 target_mourn_inferior won't unpush, and
5922 remote_target::mourn_inferior won't unpush if there is more than
5923 one inferior left. */
5924 remote_unpush_target (this);
2d717e4f 5925
43ff13b4
JM
5926 if (from_tty)
5927 puts_filtered ("Ending remote debugging.\n");
5928}
5929
2d717e4f
DJ
5930/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5931 be chatty about it. */
5932
f6ac5f3d
PA
5933void
5934extended_remote_target::attach (const char *args, int from_tty)
2d717e4f
DJ
5935{
5936 struct remote_state *rs = get_remote_state ();
be86555c 5937 int pid;
96ef3384 5938 char *wait_status = NULL;
2d717e4f 5939
74164c56 5940 pid = parse_pid_to_attach (args);
2d717e4f 5941
74164c56
JK
5942 /* Remote PID can be freely equal to getpid, do not check it here the same
5943 way as in other targets. */
2d717e4f 5944
4082afcc 5945 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5946 error (_("This target does not support attaching to a process"));
5947
7cee1e54
PA
5948 if (from_tty)
5949 {
d9fa87f4 5950 const char *exec_file = get_exec_file (0);
7cee1e54
PA
5951
5952 if (exec_file)
5953 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
a068643d 5954 target_pid_to_str (ptid_t (pid)).c_str ());
7cee1e54
PA
5955 else
5956 printf_unfiltered (_("Attaching to %s\n"),
a068643d 5957 target_pid_to_str (ptid_t (pid)).c_str ());
7cee1e54
PA
5958 }
5959
8d64371b 5960 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f 5961 putpkt (rs->buf);
8d64371b 5962 getpkt (&rs->buf, 0);
2d717e4f 5963
4082afcc
PA
5964 switch (packet_ok (rs->buf,
5965 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5966 {
4082afcc 5967 case PACKET_OK:
6efcd9a8 5968 if (!target_is_non_stop_p ())
74531fed
PA
5969 {
5970 /* Save the reply for later. */
8d64371b
TT
5971 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
5972 strcpy (wait_status, rs->buf.data ());
74531fed 5973 }
8d64371b 5974 else if (strcmp (rs->buf.data (), "OK") != 0)
74531fed 5975 error (_("Attaching to %s failed with: %s"),
a068643d 5976 target_pid_to_str (ptid_t (pid)).c_str (),
8d64371b 5977 rs->buf.data ());
4082afcc
PA
5978 break;
5979 case PACKET_UNKNOWN:
5980 error (_("This target does not support attaching to a process"));
5981 default:
50fa3001
SDJ
5982 error (_("Attaching to %s failed"),
5983 target_pid_to_str (ptid_t (pid)).c_str ());
2d717e4f 5984 }
2d717e4f 5985
0ac55310 5986 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
bad34192 5987
f2907e49 5988 inferior_ptid = ptid_t (pid);
79d7f229 5989
6efcd9a8 5990 if (target_is_non_stop_p ())
bad34192 5991 {
bad34192 5992 /* Get list of threads. */
f6ac5f3d 5993 update_thread_list ();
82f73884 5994
0ac55310
PA
5995 thread_info *thread = first_thread_of_inferior (current_inferior ());
5996 if (thread != nullptr)
5997 switch_to_thread (thread);
bad34192
PA
5998
5999 /* Invalidate our notion of the remote current thread. */
47f8a51d 6000 record_currthread (rs, minus_one_ptid);
bad34192 6001 }
74531fed 6002 else
bad34192 6003 {
0ac55310
PA
6004 /* Now, if we have thread information, update the main thread's
6005 ptid. */
6006 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
bad34192
PA
6007
6008 /* Add the main thread to the thread list. */
0ac55310
PA
6009 thread_info *thr = add_thread_silent (this, curr_ptid);
6010
6011 switch_to_thread (thr);
6012
00aecdcf
PA
6013 /* Don't consider the thread stopped until we've processed the
6014 saved stop reply. */
5b6d1e4f 6015 set_executing (this, thr->ptid, true);
bad34192 6016 }
c0a2216e 6017
96ef3384
UW
6018 /* Next, if the target can specify a description, read it. We do
6019 this before anything involving memory or registers. */
6020 target_find_description ();
6021
6efcd9a8 6022 if (!target_is_non_stop_p ())
74531fed
PA
6023 {
6024 /* Use the previously fetched status. */
6025 gdb_assert (wait_status != NULL);
6026
6027 if (target_can_async_p ())
6028 {
722247f1 6029 struct notif_event *reply
6b8edb51 6030 = remote_notif_parse (this, &notif_client_stop, wait_status);
74531fed 6031
722247f1 6032 push_stop_reply ((struct stop_reply *) reply);
74531fed 6033
6a3753b3 6034 target_async (1);
74531fed
PA
6035 }
6036 else
6037 {
6038 gdb_assert (wait_status != NULL);
8d64371b 6039 strcpy (rs->buf.data (), wait_status);
74531fed
PA
6040 rs->cached_wait_status = 1;
6041 }
6042 }
6043 else
6044 gdb_assert (wait_status == NULL);
2d717e4f
DJ
6045}
6046
b9c1d481
AS
6047/* Implementation of the to_post_attach method. */
6048
f6ac5f3d
PA
6049void
6050extended_remote_target::post_attach (int pid)
b9c1d481 6051{
6efcd9a8
PA
6052 /* Get text, data & bss offsets. */
6053 get_offsets ();
6054
b9c1d481
AS
6055 /* In certain cases GDB might not have had the chance to start
6056 symbol lookup up until now. This could happen if the debugged
6057 binary is not using shared libraries, the vsyscall page is not
6058 present (on Linux) and the binary itself hadn't changed since the
6059 debugging process was started. */
a42d7dd8 6060 if (current_program_space->symfile_object_file != NULL)
b9c1d481
AS
6061 remote_check_symbols();
6062}
6063
c906108c 6064\f
506fb367
DJ
6065/* Check for the availability of vCont. This function should also check
6066 the response. */
c906108c 6067
6b8edb51
PA
6068void
6069remote_target::remote_vcont_probe ()
c906108c 6070{
6b8edb51 6071 remote_state *rs = get_remote_state ();
2e9f7625 6072 char *buf;
6d820c5c 6073
8d64371b 6074 strcpy (rs->buf.data (), "vCont?");
2e9f7625 6075 putpkt (rs->buf);
8d64371b
TT
6076 getpkt (&rs->buf, 0);
6077 buf = rs->buf.data ();
c906108c 6078
506fb367 6079 /* Make sure that the features we assume are supported. */
61012eef 6080 if (startswith (buf, "vCont"))
506fb367
DJ
6081 {
6082 char *p = &buf[5];
750ce8d1 6083 int support_c, support_C;
506fb367 6084
750ce8d1
YQ
6085 rs->supports_vCont.s = 0;
6086 rs->supports_vCont.S = 0;
506fb367
DJ
6087 support_c = 0;
6088 support_C = 0;
d458bd84 6089 rs->supports_vCont.t = 0;
c1e36e3e 6090 rs->supports_vCont.r = 0;
506fb367
DJ
6091 while (p && *p == ';')
6092 {
6093 p++;
6094 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 6095 rs->supports_vCont.s = 1;
506fb367 6096 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 6097 rs->supports_vCont.S = 1;
506fb367
DJ
6098 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6099 support_c = 1;
6100 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6101 support_C = 1;
74531fed 6102 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 6103 rs->supports_vCont.t = 1;
c1e36e3e
PA
6104 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6105 rs->supports_vCont.r = 1;
506fb367
DJ
6106
6107 p = strchr (p, ';');
6108 }
c906108c 6109
750ce8d1
YQ
6110 /* If c, and C are not all supported, we can't use vCont. Clearing
6111 BUF will make packet_ok disable the packet. */
6112 if (!support_c || !support_C)
506fb367
DJ
6113 buf[0] = 0;
6114 }
c906108c 6115
8d64371b 6116 packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCont]);
5b6d1e4f 6117 rs->supports_vCont_probed = true;
506fb367 6118}
c906108c 6119
0d8f58ca
PA
6120/* Helper function for building "vCont" resumptions. Write a
6121 resumption to P. ENDP points to one-passed-the-end of the buffer
6122 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6123 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6124 resumed thread should be single-stepped and/or signalled. If PTID
6125 equals minus_one_ptid, then all threads are resumed; if PTID
6126 represents a process, then all threads of the process are resumed;
6127 the thread to be stepped and/or signalled is given in the global
6128 INFERIOR_PTID. */
6129
6b8edb51
PA
6130char *
6131remote_target::append_resumption (char *p, char *endp,
6132 ptid_t ptid, int step, gdb_signal siggnal)
0d8f58ca
PA
6133{
6134 struct remote_state *rs = get_remote_state ();
6135
a493e3e2 6136 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 6137 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
6138 else if (step
6139 /* GDB is willing to range step. */
6140 && use_range_stepping
6141 /* Target supports range stepping. */
6142 && rs->supports_vCont.r
6143 /* We don't currently support range stepping multiple
6144 threads with a wildcard (though the protocol allows it,
6145 so stubs shouldn't make an active effort to forbid
6146 it). */
0e998d96 6147 && !(remote_multi_process_p (rs) && ptid.is_pid ()))
c1e36e3e
PA
6148 {
6149 struct thread_info *tp;
6150
d7e15655 6151 if (ptid == minus_one_ptid)
c1e36e3e
PA
6152 {
6153 /* If we don't know about the target thread's tid, then
6154 we're resuming magic_null_ptid (see caller). */
5b6d1e4f 6155 tp = find_thread_ptid (this, magic_null_ptid);
c1e36e3e
PA
6156 }
6157 else
5b6d1e4f 6158 tp = find_thread_ptid (this, ptid);
c1e36e3e
PA
6159 gdb_assert (tp != NULL);
6160
6161 if (tp->control.may_range_step)
6162 {
6163 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6164
6165 p += xsnprintf (p, endp - p, ";r%s,%s",
6166 phex_nz (tp->control.step_range_start,
6167 addr_size),
6168 phex_nz (tp->control.step_range_end,
6169 addr_size));
6170 }
6171 else
6172 p += xsnprintf (p, endp - p, ";s");
6173 }
0d8f58ca
PA
6174 else if (step)
6175 p += xsnprintf (p, endp - p, ";s");
a493e3e2 6176 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
6177 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6178 else
6179 p += xsnprintf (p, endp - p, ";c");
6180
0e998d96 6181 if (remote_multi_process_p (rs) && ptid.is_pid ())
0d8f58ca
PA
6182 {
6183 ptid_t nptid;
6184
6185 /* All (-1) threads of process. */
e99b03dc 6186 nptid = ptid_t (ptid.pid (), -1, 0);
0d8f58ca
PA
6187
6188 p += xsnprintf (p, endp - p, ":");
6189 p = write_ptid (p, endp, nptid);
6190 }
d7e15655 6191 else if (ptid != minus_one_ptid)
0d8f58ca
PA
6192 {
6193 p += xsnprintf (p, endp - p, ":");
6194 p = write_ptid (p, endp, ptid);
6195 }
6196
6197 return p;
6198}
6199
799a2abe
PA
6200/* Clear the thread's private info on resume. */
6201
6202static void
6203resume_clear_thread_private_info (struct thread_info *thread)
6204{
6205 if (thread->priv != NULL)
6206 {
7aabaf9d
SM
6207 remote_thread_info *priv = get_remote_thread_info (thread);
6208
6209 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6210 priv->watch_data_address = 0;
799a2abe
PA
6211 }
6212}
6213
e5ef252a
PA
6214/* Append a vCont continue-with-signal action for threads that have a
6215 non-zero stop signal. */
6216
6b8edb51
PA
6217char *
6218remote_target::append_pending_thread_resumptions (char *p, char *endp,
6219 ptid_t ptid)
e5ef252a 6220{
5b6d1e4f 6221 for (thread_info *thread : all_non_exited_threads (this, ptid))
08036331 6222 if (inferior_ptid != thread->ptid
70509625 6223 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
6224 {
6225 p = append_resumption (p, endp, thread->ptid,
6226 0, thread->suspend.stop_signal);
6227 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 6228 resume_clear_thread_private_info (thread);
e5ef252a
PA
6229 }
6230
6231 return p;
6232}
6233
7b68ffbb
PA
6234/* Set the target running, using the packets that use Hc
6235 (c/s/C/S). */
6236
6b8edb51
PA
6237void
6238remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6239 gdb_signal siggnal)
7b68ffbb
PA
6240{
6241 struct remote_state *rs = get_remote_state ();
7b68ffbb
PA
6242 char *buf;
6243
6244 rs->last_sent_signal = siggnal;
6245 rs->last_sent_step = step;
6246
6247 /* The c/s/C/S resume packets use Hc, so set the continue
6248 thread. */
d7e15655 6249 if (ptid == minus_one_ptid)
7b68ffbb
PA
6250 set_continue_thread (any_thread_ptid);
6251 else
6252 set_continue_thread (ptid);
6253
5b6d1e4f 6254 for (thread_info *thread : all_non_exited_threads (this))
7b68ffbb
PA
6255 resume_clear_thread_private_info (thread);
6256
8d64371b 6257 buf = rs->buf.data ();
6b8edb51 6258 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6259 {
6260 /* We don't pass signals to the target in reverse exec mode. */
6261 if (info_verbose && siggnal != GDB_SIGNAL_0)
6262 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6263 siggnal);
6264
6265 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6266 error (_("Remote reverse-step not supported."));
6267 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6268 error (_("Remote reverse-continue not supported."));
6269
6270 strcpy (buf, step ? "bs" : "bc");
6271 }
6272 else if (siggnal != GDB_SIGNAL_0)
6273 {
6274 buf[0] = step ? 'S' : 'C';
6275 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6276 buf[2] = tohex (((int) siggnal) & 0xf);
6277 buf[3] = '\0';
6278 }
6279 else
6280 strcpy (buf, step ? "s" : "c");
6281
6282 putpkt (buf);
6283}
6284
506fb367
DJ
6285/* Resume the remote inferior by using a "vCont" packet. The thread
6286 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
6287 resumed thread should be single-stepped and/or signalled. If PTID
6288 equals minus_one_ptid, then all threads are resumed; the thread to
6289 be stepped and/or signalled is given in the global INFERIOR_PTID.
6290 This function returns non-zero iff it resumes the inferior.
44eaed12 6291
7b68ffbb
PA
6292 This function issues a strict subset of all possible vCont commands
6293 at the moment. */
44eaed12 6294
6b8edb51
PA
6295int
6296remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6297 enum gdb_signal siggnal)
506fb367
DJ
6298{
6299 struct remote_state *rs = get_remote_state ();
82f73884
PA
6300 char *p;
6301 char *endp;
44eaed12 6302
7b68ffbb 6303 /* No reverse execution actions defined for vCont. */
6b8edb51 6304 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6305 return 0;
6306
4082afcc 6307 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 6308 remote_vcont_probe ();
44eaed12 6309
4082afcc 6310 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 6311 return 0;
44eaed12 6312
8d64371b
TT
6313 p = rs->buf.data ();
6314 endp = p + get_remote_packet_size ();
82f73884 6315
506fb367
DJ
6316 /* If we could generate a wider range of packets, we'd have to worry
6317 about overflowing BUF. Should there be a generic
6318 "multi-part-packet" packet? */
6319
0d8f58ca
PA
6320 p += xsnprintf (p, endp - p, "vCont");
6321
d7e15655 6322 if (ptid == magic_null_ptid)
c906108c 6323 {
79d7f229
PA
6324 /* MAGIC_NULL_PTID means that we don't have any active threads,
6325 so we don't have any TID numbers the inferior will
6326 understand. Make sure to only send forms that do not specify
6327 a TID. */
a9cbf802 6328 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 6329 }
d7e15655 6330 else if (ptid == minus_one_ptid || ptid.is_pid ())
506fb367 6331 {
0d8f58ca
PA
6332 /* Resume all threads (of all processes, or of a single
6333 process), with preference for INFERIOR_PTID. This assumes
6334 inferior_ptid belongs to the set of all threads we are about
6335 to resume. */
a493e3e2 6336 if (step || siggnal != GDB_SIGNAL_0)
82f73884 6337 {
0d8f58ca
PA
6338 /* Step inferior_ptid, with or without signal. */
6339 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 6340 }
0d8f58ca 6341
e5ef252a
PA
6342 /* Also pass down any pending signaled resumption for other
6343 threads not the current. */
6344 p = append_pending_thread_resumptions (p, endp, ptid);
6345
0d8f58ca 6346 /* And continue others without a signal. */
a493e3e2 6347 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
6348 }
6349 else
506fb367
DJ
6350 {
6351 /* Scheduler locking; resume only PTID. */
a9cbf802 6352 append_resumption (p, endp, ptid, step, siggnal);
506fb367 6353 }
c906108c 6354
8d64371b 6355 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
82f73884 6356 putpkt (rs->buf);
506fb367 6357
6efcd9a8 6358 if (target_is_non_stop_p ())
74531fed
PA
6359 {
6360 /* In non-stop, the stub replies to vCont with "OK". The stop
6361 reply will be reported asynchronously by means of a `%Stop'
6362 notification. */
8d64371b
TT
6363 getpkt (&rs->buf, 0);
6364 if (strcmp (rs->buf.data (), "OK") != 0)
6365 error (_("Unexpected vCont reply in non-stop mode: %s"),
6366 rs->buf.data ());
74531fed
PA
6367 }
6368
506fb367 6369 return 1;
c906108c 6370}
43ff13b4 6371
506fb367
DJ
6372/* Tell the remote machine to resume. */
6373
f6ac5f3d
PA
6374void
6375remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 6376{
d01949b6 6377 struct remote_state *rs = get_remote_state ();
43ff13b4 6378
85ad3aaf
PA
6379 /* When connected in non-stop mode, the core resumes threads
6380 individually. Resuming remote threads directly in target_resume
6381 would thus result in sending one packet per thread. Instead, to
6382 minimize roundtrip latency, here we just store the resume
c9d22089
SM
6383 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6384 resumption will be done in remote_target::commit_resume, where we'll be
6385 able to do vCont action coalescing. */
f6ac5f3d 6386 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
85ad3aaf 6387 {
7aabaf9d 6388 remote_thread_info *remote_thr;
85ad3aaf 6389
d7e15655 6390 if (minus_one_ptid == ptid || ptid.is_pid ())
5b6d1e4f 6391 remote_thr = get_remote_thread_info (this, inferior_ptid);
85ad3aaf 6392 else
5b6d1e4f 6393 remote_thr = get_remote_thread_info (this, ptid);
7aabaf9d 6394
c9d22089
SM
6395 /* We don't expect the core to ask to resume an already resumed (from
6396 its point of view) thread. */
6397 gdb_assert (remote_thr->resume_state () == resume_state::NOT_RESUMED);
6398
6399 remote_thr->set_resumed_pending_vcont (step, siggnal);
85ad3aaf
PA
6400 return;
6401 }
6402
722247f1
YQ
6403 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6404 (explained in remote-notif.c:handle_notification) so
6405 remote_notif_process is not called. We need find a place where
6406 it is safe to start a 'vNotif' sequence. It is good to do it
6407 before resuming inferior, because inferior was stopped and no RSP
6408 traffic at that moment. */
6efcd9a8 6409 if (!target_is_non_stop_p ())
5965e028 6410 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 6411
f6ac5f3d 6412 rs->last_resume_exec_dir = ::execution_direction;
3a00c802 6413
7b68ffbb
PA
6414 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6415 if (!remote_resume_with_vcont (ptid, step, siggnal))
6b8edb51 6416 remote_resume_with_hc (ptid, step, siggnal);
43ff13b4 6417
c9d22089
SM
6418 /* Update resumed state tracked by the remote target. */
6419 for (thread_info *tp : all_non_exited_threads (this, ptid))
6420 get_remote_thread_info (tp)->set_resumed ();
6421
2acceee2 6422 /* We are about to start executing the inferior, let's register it
0df8b418
MS
6423 with the event loop. NOTE: this is the one place where all the
6424 execution commands end up. We could alternatively do this in each
23860348 6425 of the execution commands in infcmd.c. */
2acceee2
JM
6426 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6427 into infcmd.c in order to allow inferior function calls to work
23860348 6428 NOT asynchronously. */
362646f5 6429 if (target_can_async_p ())
6a3753b3 6430 target_async (1);
e24a49d8
PA
6431
6432 /* We've just told the target to resume. The remote server will
6433 wait for the inferior to stop, and then send a stop reply. In
6434 the mean time, we can't start another command/query ourselves
74531fed
PA
6435 because the stub wouldn't be ready to process it. This applies
6436 only to the base all-stop protocol, however. In non-stop (which
6437 only supports vCont), the stub replies with an "OK", and is
6438 immediate able to process further serial input. */
6efcd9a8 6439 if (!target_is_non_stop_p ())
74531fed 6440 rs->waiting_for_stop_reply = 1;
43ff13b4 6441}
85ad3aaf 6442
85ad3aaf
PA
6443static int is_pending_fork_parent_thread (struct thread_info *thread);
6444
6445/* Private per-inferior info for target remote processes. */
6446
089354bb 6447struct remote_inferior : public private_inferior
85ad3aaf
PA
6448{
6449 /* Whether we can send a wildcard vCont for this process. */
089354bb 6450 bool may_wildcard_vcont = true;
85ad3aaf
PA
6451};
6452
089354bb
SM
6453/* Get the remote private inferior data associated to INF. */
6454
6455static remote_inferior *
6456get_remote_inferior (inferior *inf)
6457{
6458 if (inf->priv == NULL)
6459 inf->priv.reset (new remote_inferior);
6460
6461 return static_cast<remote_inferior *> (inf->priv.get ());
6462}
6463
f5db4863 6464/* Class used to track the construction of a vCont packet in the
85ad3aaf
PA
6465 outgoing packet buffer. This is used to send multiple vCont
6466 packets if we have more actions than would fit a single packet. */
6467
f5db4863 6468class vcont_builder
85ad3aaf 6469{
f5db4863 6470public:
6b8edb51
PA
6471 explicit vcont_builder (remote_target *remote)
6472 : m_remote (remote)
f5db4863
PA
6473 {
6474 restart ();
6475 }
6476
6477 void flush ();
6478 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6479
6480private:
6481 void restart ();
6482
6b8edb51
PA
6483 /* The remote target. */
6484 remote_target *m_remote;
6485
85ad3aaf
PA
6486 /* Pointer to the first action. P points here if no action has been
6487 appended yet. */
f5db4863 6488 char *m_first_action;
85ad3aaf
PA
6489
6490 /* Where the next action will be appended. */
f5db4863 6491 char *m_p;
85ad3aaf
PA
6492
6493 /* The end of the buffer. Must never write past this. */
f5db4863 6494 char *m_endp;
85ad3aaf
PA
6495};
6496
6497/* Prepare the outgoing buffer for a new vCont packet. */
6498
f5db4863
PA
6499void
6500vcont_builder::restart ()
85ad3aaf 6501{
6b8edb51 6502 struct remote_state *rs = m_remote->get_remote_state ();
85ad3aaf 6503
8d64371b
TT
6504 m_p = rs->buf.data ();
6505 m_endp = m_p + m_remote->get_remote_packet_size ();
f5db4863
PA
6506 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6507 m_first_action = m_p;
85ad3aaf
PA
6508}
6509
6510/* If the vCont packet being built has any action, send it to the
6511 remote end. */
6512
f5db4863
PA
6513void
6514vcont_builder::flush ()
85ad3aaf
PA
6515{
6516 struct remote_state *rs;
6517
f5db4863 6518 if (m_p == m_first_action)
85ad3aaf
PA
6519 return;
6520
6b8edb51
PA
6521 rs = m_remote->get_remote_state ();
6522 m_remote->putpkt (rs->buf);
8d64371b
TT
6523 m_remote->getpkt (&rs->buf, 0);
6524 if (strcmp (rs->buf.data (), "OK") != 0)
6525 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
85ad3aaf
PA
6526}
6527
6528/* The largest action is range-stepping, with its two addresses. This
6529 is more than sufficient. If a new, bigger action is created, it'll
6530 quickly trigger a failed assertion in append_resumption (and we'll
6531 just bump this). */
6532#define MAX_ACTION_SIZE 200
6533
6534/* Append a new vCont action in the outgoing packet being built. If
6535 the action doesn't fit the packet along with previous actions, push
6536 what we've got so far to the remote end and start over a new vCont
6537 packet (with the new action). */
6538
f5db4863
PA
6539void
6540vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
85ad3aaf
PA
6541{
6542 char buf[MAX_ACTION_SIZE + 1];
85ad3aaf 6543
6b8edb51
PA
6544 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6545 ptid, step, siggnal);
85ad3aaf
PA
6546
6547 /* Check whether this new action would fit in the vCont packet along
6548 with previous actions. If not, send what we've got so far and
6549 start a new vCont packet. */
f5db4863
PA
6550 size_t rsize = endp - buf;
6551 if (rsize > m_endp - m_p)
85ad3aaf 6552 {
f5db4863
PA
6553 flush ();
6554 restart ();
85ad3aaf
PA
6555
6556 /* Should now fit. */
f5db4863 6557 gdb_assert (rsize <= m_endp - m_p);
85ad3aaf
PA
6558 }
6559
f5db4863
PA
6560 memcpy (m_p, buf, rsize);
6561 m_p += rsize;
6562 *m_p = '\0';
85ad3aaf
PA
6563}
6564
6565/* to_commit_resume implementation. */
6566
f6ac5f3d
PA
6567void
6568remote_target::commit_resume ()
85ad3aaf 6569{
85ad3aaf
PA
6570 int any_process_wildcard;
6571 int may_global_wildcard_vcont;
85ad3aaf
PA
6572
6573 /* If connected in all-stop mode, we'd send the remote resume
6574 request directly from remote_resume. Likewise if
6575 reverse-debugging, as there are no defined vCont actions for
6576 reverse execution. */
f6ac5f3d 6577 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
85ad3aaf
PA
6578 return;
6579
6580 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6581 instead of resuming all threads of each process individually.
6582 However, if any thread of a process must remain halted, we can't
6583 send wildcard resumes and must send one action per thread.
6584
6585 Care must be taken to not resume threads/processes the server
6586 side already told us are stopped, but the core doesn't know about
6587 yet, because the events are still in the vStopped notification
6588 queue. For example:
6589
6590 #1 => vCont s:p1.1;c
6591 #2 <= OK
6592 #3 <= %Stopped T05 p1.1
6593 #4 => vStopped
6594 #5 <= T05 p1.2
6595 #6 => vStopped
6596 #7 <= OK
6597 #8 (infrun handles the stop for p1.1 and continues stepping)
6598 #9 => vCont s:p1.1;c
6599
6600 The last vCont above would resume thread p1.2 by mistake, because
6601 the server has no idea that the event for p1.2 had not been
6602 handled yet.
6603
6604 The server side must similarly ignore resume actions for the
6605 thread that has a pending %Stopped notification (and any other
6606 threads with events pending), until GDB acks the notification
6607 with vStopped. Otherwise, e.g., the following case is
6608 mishandled:
6609
6610 #1 => g (or any other packet)
6611 #2 <= [registers]
6612 #3 <= %Stopped T05 p1.2
6613 #4 => vCont s:p1.1;c
6614 #5 <= OK
6615
6616 Above, the server must not resume thread p1.2. GDB can't know
6617 that p1.2 stopped until it acks the %Stopped notification, and
6618 since from GDB's perspective all threads should be running, it
6619 sends a "c" action.
6620
6621 Finally, special care must also be given to handling fork/vfork
6622 events. A (v)fork event actually tells us that two processes
6623 stopped -- the parent and the child. Until we follow the fork,
6624 we must not resume the child. Therefore, if we have a pending
6625 fork follow, we must not send a global wildcard resume action
6626 (vCont;c). We can still send process-wide wildcards though. */
6627
6628 /* Start by assuming a global wildcard (vCont;c) is possible. */
6629 may_global_wildcard_vcont = 1;
6630
6631 /* And assume every process is individually wildcard-able too. */
5b6d1e4f 6632 for (inferior *inf : all_non_exited_inferiors (this))
85ad3aaf 6633 {
089354bb
SM
6634 remote_inferior *priv = get_remote_inferior (inf);
6635
6636 priv->may_wildcard_vcont = true;
85ad3aaf
PA
6637 }
6638
6639 /* Check for any pending events (not reported or processed yet) and
6640 disable process and global wildcard resumes appropriately. */
6641 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6642
5b6d1e4f 6643 for (thread_info *tp : all_non_exited_threads (this))
85ad3aaf 6644 {
c9d22089
SM
6645 remote_thread_info *priv = get_remote_thread_info (tp);
6646
85ad3aaf
PA
6647 /* If a thread of a process is not meant to be resumed, then we
6648 can't wildcard that process. */
c9d22089 6649 if (priv->resume_state () == resume_state::NOT_RESUMED)
85ad3aaf 6650 {
089354bb 6651 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
85ad3aaf
PA
6652
6653 /* And if we can't wildcard a process, we can't wildcard
6654 everything either. */
6655 may_global_wildcard_vcont = 0;
6656 continue;
6657 }
6658
6659 /* If a thread is the parent of an unfollowed fork, then we
6660 can't do a global wildcard, as that would resume the fork
6661 child. */
6662 if (is_pending_fork_parent_thread (tp))
6663 may_global_wildcard_vcont = 0;
6664 }
6665
6666 /* Now let's build the vCont packet(s). Actions must be appended
6667 from narrower to wider scopes (thread -> process -> global). If
6668 we end up with too many actions for a single packet vcont_builder
6669 flushes the current vCont packet to the remote side and starts a
6670 new one. */
6b8edb51 6671 struct vcont_builder vcont_builder (this);
85ad3aaf
PA
6672
6673 /* Threads first. */
5b6d1e4f 6674 for (thread_info *tp : all_non_exited_threads (this))
85ad3aaf 6675 {
7aabaf9d 6676 remote_thread_info *remote_thr = get_remote_thread_info (tp);
85ad3aaf 6677
c9d22089
SM
6678 /* If the thread was previously vCont-resumed, no need to send a specific
6679 action for it. If we didn't receive a resume request for it, don't
6680 send an action for it either. */
6681 if (remote_thr->resume_state () != resume_state::RESUMED_PENDING_VCONT)
85ad3aaf
PA
6682 continue;
6683
6684 gdb_assert (!thread_is_in_step_over_chain (tp));
6685
c9d22089
SM
6686 const resumed_pending_vcont_info &info
6687 = remote_thr->resumed_pending_vcont_info ();
85ad3aaf 6688
c9d22089
SM
6689 /* Check if we need to send a specific action for this thread. If not,
6690 it will be included in a wildcard resume instead. */
6691 if (info.step || info.sig != GDB_SIGNAL_0
6692 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
6693 vcont_builder.push_action (tp->ptid, info.step, info.sig);
6694
6695 remote_thr->set_resumed ();
85ad3aaf
PA
6696 }
6697
6698 /* Now check whether we can send any process-wide wildcard. This is
6699 to avoid sending a global wildcard in the case nothing is
6700 supposed to be resumed. */
6701 any_process_wildcard = 0;
6702
5b6d1e4f 6703 for (inferior *inf : all_non_exited_inferiors (this))
85ad3aaf 6704 {
089354bb 6705 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf
PA
6706 {
6707 any_process_wildcard = 1;
6708 break;
6709 }
6710 }
6711
6712 if (any_process_wildcard)
6713 {
6714 /* If all processes are wildcard-able, then send a single "c"
6715 action, otherwise, send an "all (-1) threads of process"
6716 continue action for each running process, if any. */
6717 if (may_global_wildcard_vcont)
6718 {
f5db4863
PA
6719 vcont_builder.push_action (minus_one_ptid,
6720 false, GDB_SIGNAL_0);
85ad3aaf
PA
6721 }
6722 else
6723 {
5b6d1e4f 6724 for (inferior *inf : all_non_exited_inferiors (this))
85ad3aaf 6725 {
089354bb 6726 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf 6727 {
f2907e49 6728 vcont_builder.push_action (ptid_t (inf->pid),
f5db4863 6729 false, GDB_SIGNAL_0);
85ad3aaf
PA
6730 }
6731 }
6732 }
6733 }
6734
f5db4863 6735 vcont_builder.flush ();
85ad3aaf
PA
6736}
6737
c906108c 6738\f
43ff13b4 6739
74531fed
PA
6740/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6741 thread, all threads of a remote process, or all threads of all
6742 processes. */
6743
6b8edb51
PA
6744void
6745remote_target::remote_stop_ns (ptid_t ptid)
74531fed
PA
6746{
6747 struct remote_state *rs = get_remote_state ();
8d64371b
TT
6748 char *p = rs->buf.data ();
6749 char *endp = p + get_remote_packet_size ();
74531fed 6750
5b6d1e4f
PA
6751 /* FIXME: This supports_vCont_probed check is a workaround until
6752 packet_support is per-connection. */
6753 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN
6754 || !rs->supports_vCont_probed)
6b8edb51 6755 remote_vcont_probe ();
74531fed 6756
d458bd84 6757 if (!rs->supports_vCont.t)
74531fed
PA
6758 error (_("Remote server does not support stopping threads"));
6759
d7e15655 6760 if (ptid == minus_one_ptid
0e998d96 6761 || (!remote_multi_process_p (rs) && ptid.is_pid ()))
74531fed
PA
6762 p += xsnprintf (p, endp - p, "vCont;t");
6763 else
6764 {
6765 ptid_t nptid;
6766
74531fed
PA
6767 p += xsnprintf (p, endp - p, "vCont;t:");
6768
0e998d96 6769 if (ptid.is_pid ())
74531fed 6770 /* All (-1) threads of process. */
e99b03dc 6771 nptid = ptid_t (ptid.pid (), -1, 0);
74531fed
PA
6772 else
6773 {
6774 /* Small optimization: if we already have a stop reply for
6775 this thread, no use in telling the stub we want this
6776 stopped. */
6777 if (peek_stop_reply (ptid))
6778 return;
6779
6780 nptid = ptid;
6781 }
6782
a9cbf802 6783 write_ptid (p, endp, nptid);
74531fed
PA
6784 }
6785
6786 /* In non-stop, we get an immediate OK reply. The stop reply will
6787 come in asynchronously by notification. */
6788 putpkt (rs->buf);
8d64371b
TT
6789 getpkt (&rs->buf, 0);
6790 if (strcmp (rs->buf.data (), "OK") != 0)
a068643d 6791 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
8d64371b 6792 rs->buf.data ());
74531fed
PA
6793}
6794
bfedc46a
PA
6795/* All-stop version of target_interrupt. Sends a break or a ^C to
6796 interrupt the remote target. It is undefined which thread of which
6797 process reports the interrupt. */
74531fed 6798
6b8edb51
PA
6799void
6800remote_target::remote_interrupt_as ()
74531fed
PA
6801{
6802 struct remote_state *rs = get_remote_state ();
6803
3a29589a
DJ
6804 rs->ctrlc_pending_p = 1;
6805
74531fed
PA
6806 /* If the inferior is stopped already, but the core didn't know
6807 about it yet, just ignore the request. The cached wait status
6808 will be collected in remote_wait. */
6809 if (rs->cached_wait_status)
6810 return;
6811
9a7071a8
JB
6812 /* Send interrupt_sequence to remote target. */
6813 send_interrupt_sequence ();
74531fed
PA
6814}
6815
de979965
PA
6816/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6817 the remote target. It is undefined which thread of which process
e42de8c7
PA
6818 reports the interrupt. Throws an error if the packet is not
6819 supported by the server. */
de979965 6820
6b8edb51
PA
6821void
6822remote_target::remote_interrupt_ns ()
de979965
PA
6823{
6824 struct remote_state *rs = get_remote_state ();
8d64371b
TT
6825 char *p = rs->buf.data ();
6826 char *endp = p + get_remote_packet_size ();
de979965
PA
6827
6828 xsnprintf (p, endp - p, "vCtrlC");
6829
6830 /* In non-stop, we get an immediate OK reply. The stop reply will
6831 come in asynchronously by notification. */
6832 putpkt (rs->buf);
8d64371b 6833 getpkt (&rs->buf, 0);
de979965
PA
6834
6835 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6836 {
6837 case PACKET_OK:
6838 break;
6839 case PACKET_UNKNOWN:
e42de8c7 6840 error (_("No support for interrupting the remote target."));
de979965 6841 case PACKET_ERROR:
8d64371b 6842 error (_("Interrupting target failed: %s"), rs->buf.data ());
de979965 6843 }
de979965
PA
6844}
6845
bfedc46a 6846/* Implement the to_stop function for the remote targets. */
74531fed 6847
f6ac5f3d
PA
6848void
6849remote_target::stop (ptid_t ptid)
c906108c 6850{
7a292a7a 6851 if (remote_debug)
0f71a2f6 6852 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 6853
6efcd9a8 6854 if (target_is_non_stop_p ())
74531fed 6855 remote_stop_ns (ptid);
c906108c 6856 else
bfedc46a
PA
6857 {
6858 /* We don't currently have a way to transparently pause the
6859 remote target in all-stop mode. Interrupt it instead. */
de979965 6860 remote_interrupt_as ();
bfedc46a
PA
6861 }
6862}
6863
6864/* Implement the to_interrupt function for the remote targets. */
6865
f6ac5f3d
PA
6866void
6867remote_target::interrupt ()
bfedc46a
PA
6868{
6869 if (remote_debug)
6870 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6871
e42de8c7
PA
6872 if (target_is_non_stop_p ())
6873 remote_interrupt_ns ();
bfedc46a 6874 else
e42de8c7 6875 remote_interrupt_as ();
c906108c
SS
6876}
6877
93692b58
PA
6878/* Implement the to_pass_ctrlc function for the remote targets. */
6879
f6ac5f3d
PA
6880void
6881remote_target::pass_ctrlc ()
93692b58
PA
6882{
6883 struct remote_state *rs = get_remote_state ();
6884
6885 if (remote_debug)
6886 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6887
6888 /* If we're starting up, we're not fully synced yet. Quit
6889 immediately. */
6890 if (rs->starting_up)
6891 quit ();
6892 /* If ^C has already been sent once, offer to disconnect. */
6893 else if (rs->ctrlc_pending_p)
6894 interrupt_query ();
6895 else
e671cd59 6896 target_interrupt ();
93692b58
PA
6897}
6898
c906108c
SS
6899/* Ask the user what to do when an interrupt is received. */
6900
6b8edb51
PA
6901void
6902remote_target::interrupt_query ()
c906108c 6903{
abc56d60 6904 struct remote_state *rs = get_remote_state ();
c906108c 6905
abc56d60 6906 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 6907 {
abc56d60
PA
6908 if (query (_("The target is not responding to interrupt requests.\n"
6909 "Stop debugging it? ")))
74531fed 6910 {
5b6d1e4f 6911 remote_unpush_target (this);
abc56d60 6912 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
6913 }
6914 }
abc56d60
PA
6915 else
6916 {
6917 if (query (_("Interrupted while waiting for the program.\n"
6918 "Give up waiting? ")))
6919 quit ();
6920 }
c906108c
SS
6921}
6922
6426a772
JM
6923/* Enable/disable target terminal ownership. Most targets can use
6924 terminal groups to control terminal ownership. Remote targets are
6925 different in that explicit transfer of ownership to/from GDB/target
23860348 6926 is required. */
6426a772 6927
f6ac5f3d
PA
6928void
6929remote_target::terminal_inferior ()
6426a772 6930{
6426a772
JM
6931 /* NOTE: At this point we could also register our selves as the
6932 recipient of all input. Any characters typed could then be
23860348 6933 passed on down to the target. */
6426a772
JM
6934}
6935
f6ac5f3d
PA
6936void
6937remote_target::terminal_ours ()
6426a772 6938{
6426a772
JM
6939}
6940
176a6961 6941static void
05be00a8 6942remote_console_output (const char *msg)
c906108c 6943{
05be00a8 6944 const char *p;
c906108c 6945
c5aa993b 6946 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
6947 {
6948 char tb[2];
6949 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 6950
c906108c
SS
6951 tb[0] = c;
6952 tb[1] = 0;
da5bd37e 6953 gdb_stdtarg->puts (tb);
c906108c 6954 }
da5bd37e 6955 gdb_stdtarg->flush ();
00db5b94 6956}
74531fed 6957
32603266 6958struct stop_reply : public notif_event
74531fed 6959{
32603266 6960 ~stop_reply ();
74531fed 6961
722247f1 6962 /* The identifier of the thread about this event */
74531fed
PA
6963 ptid_t ptid;
6964
340e3c99 6965 /* The remote state this event is associated with. When the remote
bcc75809
YQ
6966 connection, represented by a remote_state object, is closed,
6967 all the associated stop_reply events should be released. */
6968 struct remote_state *rs;
6969
74531fed
PA
6970 struct target_waitstatus ws;
6971
5cd63fda
PA
6972 /* The architecture associated with the expedited registers. */
6973 gdbarch *arch;
6974
15148d6a
PA
6975 /* Expedited registers. This makes remote debugging a bit more
6976 efficient for those targets that provide critical registers as
6977 part of their normal status mechanism (as another roundtrip to
6978 fetch them is avoided). */
32603266 6979 std::vector<cached_reg_t> regcache;
74531fed 6980
f7e6eed5
PA
6981 enum target_stop_reason stop_reason;
6982
74531fed
PA
6983 CORE_ADDR watch_data_address;
6984
dc146f7c 6985 int core;
32603266 6986};
c906108c 6987
221e1a37
PA
6988/* Return the length of the stop reply queue. */
6989
6b8edb51
PA
6990int
6991remote_target::stop_reply_queue_length ()
221e1a37 6992{
6b8edb51 6993 remote_state *rs = get_remote_state ();
953edf2b 6994 return rs->stop_reply_queue.size ();
221e1a37
PA
6995}
6996
cb8c24b6 6997static void
6b8edb51 6998remote_notif_stop_parse (remote_target *remote,
bb277751 6999 struct notif_client *self, const char *buf,
722247f1
YQ
7000 struct notif_event *event)
7001{
6b8edb51 7002 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
722247f1
YQ
7003}
7004
7005static void
6b8edb51 7006remote_notif_stop_ack (remote_target *remote,
bb277751 7007 struct notif_client *self, const char *buf,
722247f1
YQ
7008 struct notif_event *event)
7009{
7010 struct stop_reply *stop_reply = (struct stop_reply *) event;
7011
7012 /* acknowledge */
6b8edb51 7013 putpkt (remote, self->ack_command);
722247f1
YQ
7014
7015 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6b8edb51 7016 {
722247f1
YQ
7017 /* We got an unknown stop reply. */
7018 error (_("Unknown stop reply"));
6b8edb51 7019 }
722247f1 7020
6b8edb51 7021 remote->push_stop_reply (stop_reply);
722247f1
YQ
7022}
7023
7024static int
6b8edb51
PA
7025remote_notif_stop_can_get_pending_events (remote_target *remote,
7026 struct notif_client *self)
722247f1
YQ
7027{
7028 /* We can't get pending events in remote_notif_process for
7029 notification stop, and we have to do this in remote_wait_ns
7030 instead. If we fetch all queued events from stub, remote stub
7031 may exit and we have no chance to process them back in
7032 remote_wait_ns. */
6b8edb51
PA
7033 remote_state *rs = remote->get_remote_state ();
7034 mark_async_event_handler (rs->remote_async_inferior_event_token);
722247f1
YQ
7035 return 0;
7036}
7037
32603266 7038stop_reply::~stop_reply ()
722247f1 7039{
32603266
TT
7040 for (cached_reg_t &reg : regcache)
7041 xfree (reg.data);
722247f1
YQ
7042}
7043
32603266
TT
7044static notif_event_up
7045remote_notif_stop_alloc_reply ()
722247f1 7046{
32603266 7047 return notif_event_up (new struct stop_reply ());
722247f1
YQ
7048}
7049
7050/* A client of notification Stop. */
7051
7052struct notif_client notif_client_stop =
7053{
7054 "Stop",
7055 "vStopped",
7056 remote_notif_stop_parse,
7057 remote_notif_stop_ack,
7058 remote_notif_stop_can_get_pending_events,
7059 remote_notif_stop_alloc_reply,
f48ff2a7 7060 REMOTE_NOTIF_STOP,
722247f1
YQ
7061};
7062
85ad3aaf 7063/* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
cbb8991c
DB
7064 the pid of the process that owns the threads we want to check, or
7065 -1 if we want to check all threads. */
7066
7067static int
7068is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
7069 ptid_t thread_ptid)
7070{
7071 if (ws->kind == TARGET_WAITKIND_FORKED
7072 || ws->kind == TARGET_WAITKIND_VFORKED)
7073 {
e99b03dc 7074 if (event_pid == -1 || event_pid == thread_ptid.pid ())
cbb8991c
DB
7075 return 1;
7076 }
7077
7078 return 0;
7079}
7080
85ad3aaf
PA
7081/* Return the thread's pending status used to determine whether the
7082 thread is a fork parent stopped at a fork event. */
7083
7084static struct target_waitstatus *
7085thread_pending_fork_status (struct thread_info *thread)
7086{
7087 if (thread->suspend.waitstatus_pending_p)
7088 return &thread->suspend.waitstatus;
7089 else
7090 return &thread->pending_follow;
7091}
7092
7093/* Determine if THREAD is a pending fork parent thread. */
7094
7095static int
7096is_pending_fork_parent_thread (struct thread_info *thread)
7097{
7098 struct target_waitstatus *ws = thread_pending_fork_status (thread);
7099 int pid = -1;
7100
7101 return is_pending_fork_parent (ws, pid, thread->ptid);
7102}
7103
cbb8991c
DB
7104/* If CONTEXT contains any fork child threads that have not been
7105 reported yet, remove them from the CONTEXT list. If such a
7106 thread exists it is because we are stopped at a fork catchpoint
7107 and have not yet called follow_fork, which will set up the
7108 host-side data structures for the new process. */
7109
6b8edb51
PA
7110void
7111remote_target::remove_new_fork_children (threads_listing_context *context)
cbb8991c 7112{
cbb8991c
DB
7113 int pid = -1;
7114 struct notif_client *notif = &notif_client_stop;
cbb8991c
DB
7115
7116 /* For any threads stopped at a fork event, remove the corresponding
7117 fork child threads from the CONTEXT list. */
5b6d1e4f 7118 for (thread_info *thread : all_non_exited_threads (this))
cbb8991c 7119 {
85ad3aaf 7120 struct target_waitstatus *ws = thread_pending_fork_status (thread);
cbb8991c
DB
7121
7122 if (is_pending_fork_parent (ws, pid, thread->ptid))
21fe1c75 7123 context->remove_thread (ws->value.related_pid);
cbb8991c
DB
7124 }
7125
7126 /* Check for any pending fork events (not reported or processed yet)
7127 in process PID and remove those fork child threads from the
7128 CONTEXT list as well. */
7129 remote_notif_get_pending_events (notif);
953edf2b
TT
7130 for (auto &event : get_remote_state ()->stop_reply_queue)
7131 if (event->ws.kind == TARGET_WAITKIND_FORKED
7132 || event->ws.kind == TARGET_WAITKIND_VFORKED
7133 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
7134 context->remove_thread (event->ws.value.related_pid);
85ad3aaf
PA
7135}
7136
7137/* Check whether any event pending in the vStopped queue would prevent
7138 a global or process wildcard vCont action. Clear
7139 *may_global_wildcard if we can't do a global wildcard (vCont;c),
7140 and clear the event inferior's may_wildcard_vcont flag if we can't
7141 do a process-wide wildcard resume (vCont;c:pPID.-1). */
7142
6b8edb51
PA
7143void
7144remote_target::check_pending_events_prevent_wildcard_vcont
7145 (int *may_global_wildcard)
85ad3aaf
PA
7146{
7147 struct notif_client *notif = &notif_client_stop;
7148
7149 remote_notif_get_pending_events (notif);
953edf2b
TT
7150 for (auto &event : get_remote_state ()->stop_reply_queue)
7151 {
7152 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
7153 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
7154 continue;
85ad3aaf 7155
953edf2b
TT
7156 if (event->ws.kind == TARGET_WAITKIND_FORKED
7157 || event->ws.kind == TARGET_WAITKIND_VFORKED)
7158 *may_global_wildcard = 0;
722247f1 7159
5b6d1e4f 7160 struct inferior *inf = find_inferior_ptid (this, event->ptid);
722247f1 7161
953edf2b
TT
7162 /* This may be the first time we heard about this process.
7163 Regardless, we must not do a global wildcard resume, otherwise
7164 we'd resume this process too. */
7165 *may_global_wildcard = 0;
7166 if (inf != NULL)
7167 get_remote_inferior (inf)->may_wildcard_vcont = false;
722247f1 7168 }
722247f1
YQ
7169}
7170
f48ff2a7 7171/* Discard all pending stop replies of inferior INF. */
c906108c 7172
6b8edb51
PA
7173void
7174remote_target::discard_pending_stop_replies (struct inferior *inf)
c906108c 7175{
f48ff2a7
YQ
7176 struct stop_reply *reply;
7177 struct remote_state *rs = get_remote_state ();
7178 struct remote_notif_state *rns = rs->notif_state;
7179
7180 /* This function can be notified when an inferior exists. When the
7181 target is not remote, the notification state is NULL. */
7182 if (rs->remote_desc == NULL)
7183 return;
7184
7185 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 7186
74531fed 7187 /* Discard the in-flight notification. */
e99b03dc 7188 if (reply != NULL && reply->ptid.pid () == inf->pid)
74531fed 7189 {
32603266 7190 delete reply;
f48ff2a7 7191 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 7192 }
c906108c 7193
74531fed
PA
7194 /* Discard the stop replies we have already pulled with
7195 vStopped. */
953edf2b
TT
7196 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7197 rs->stop_reply_queue.end (),
7198 [=] (const stop_reply_up &event)
7199 {
7200 return event->ptid.pid () == inf->pid;
7201 });
7202 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
bcc75809
YQ
7203}
7204
7205/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7 7206
6b8edb51
PA
7207void
7208remote_target::discard_pending_stop_replies_in_queue ()
f48ff2a7 7209{
6b8edb51 7210 remote_state *rs = get_remote_state ();
f48ff2a7 7211
f48ff2a7
YQ
7212 /* Discard the stop replies we have already pulled with
7213 vStopped. */
953edf2b
TT
7214 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7215 rs->stop_reply_queue.end (),
7216 [=] (const stop_reply_up &event)
7217 {
7218 return event->rs == rs;
7219 });
7220 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
74531fed 7221}
43ff13b4 7222
722247f1
YQ
7223/* Remove the first reply in 'stop_reply_queue' which matches
7224 PTID. */
2e9f7625 7225
6b8edb51
PA
7226struct stop_reply *
7227remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 7228{
953edf2b 7229 remote_state *rs = get_remote_state ();
722247f1 7230
953edf2b
TT
7231 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7232 rs->stop_reply_queue.end (),
7233 [=] (const stop_reply_up &event)
7234 {
7235 return event->ptid.matches (ptid);
7236 });
7237 struct stop_reply *result;
7238 if (iter == rs->stop_reply_queue.end ())
7239 result = nullptr;
7240 else
7241 {
7242 result = iter->release ();
7243 rs->stop_reply_queue.erase (iter);
7244 }
722247f1 7245
722247f1
YQ
7246 if (notif_debug)
7247 fprintf_unfiltered (gdb_stdlog,
7248 "notif: discard queued event: 'Stop' in %s\n",
a068643d 7249 target_pid_to_str (ptid).c_str ());
a744cf53 7250
953edf2b 7251 return result;
74531fed 7252}
75c99385 7253
74531fed
PA
7254/* Look for a queued stop reply belonging to PTID. If one is found,
7255 remove it from the queue, and return it. Returns NULL if none is
7256 found. If there are still queued events left to process, tell the
7257 event loop to get back to target_wait soon. */
e24a49d8 7258
6b8edb51
PA
7259struct stop_reply *
7260remote_target::queued_stop_reply (ptid_t ptid)
74531fed 7261{
953edf2b 7262 remote_state *rs = get_remote_state ();
722247f1 7263 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 7264
953edf2b 7265 if (!rs->stop_reply_queue.empty ())
6b8edb51 7266 {
6b8edb51
PA
7267 /* There's still at least an event left. */
7268 mark_async_event_handler (rs->remote_async_inferior_event_token);
7269 }
74531fed 7270
722247f1 7271 return r;
74531fed
PA
7272}
7273
7274/* Push a fully parsed stop reply in the stop reply queue. Since we
7275 know that we now have at least one queued event left to pass to the
7276 core side, tell the event loop to get back to target_wait soon. */
7277
6b8edb51
PA
7278void
7279remote_target::push_stop_reply (struct stop_reply *new_event)
74531fed 7280{
6b8edb51 7281 remote_state *rs = get_remote_state ();
953edf2b 7282 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
74531fed 7283
722247f1
YQ
7284 if (notif_debug)
7285 fprintf_unfiltered (gdb_stdlog,
7286 "notif: push 'Stop' %s to queue %d\n",
a068643d 7287 target_pid_to_str (new_event->ptid).c_str (),
953edf2b 7288 int (rs->stop_reply_queue.size ()));
74531fed 7289
6b8edb51 7290 mark_async_event_handler (rs->remote_async_inferior_event_token);
74531fed
PA
7291}
7292
7293/* Returns true if we have a stop reply for PTID. */
7294
6b8edb51
PA
7295int
7296remote_target::peek_stop_reply (ptid_t ptid)
74531fed 7297{
6b8edb51 7298 remote_state *rs = get_remote_state ();
953edf2b
TT
7299 for (auto &event : rs->stop_reply_queue)
7300 if (ptid == event->ptid
7301 && event->ws.kind == TARGET_WAITKIND_STOPPED)
7302 return 1;
7303 return 0;
74531fed
PA
7304}
7305
26d56a93
SL
7306/* Helper for remote_parse_stop_reply. Return nonzero if the substring
7307 starting with P and ending with PEND matches PREFIX. */
7308
7309static int
7310strprefix (const char *p, const char *pend, const char *prefix)
7311{
7312 for ( ; p < pend; p++, prefix++)
7313 if (*p != *prefix)
7314 return 0;
7315 return *prefix == '\0';
7316}
7317
74531fed
PA
7318/* Parse the stop reply in BUF. Either the function succeeds, and the
7319 result is stored in EVENT, or throws an error. */
7320
6b8edb51 7321void
bb277751 7322remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
74531fed 7323{
5cd63fda 7324 remote_arch_state *rsa = NULL;
74531fed 7325 ULONGEST addr;
256642e8 7326 const char *p;
94585166 7327 int skipregs = 0;
74531fed
PA
7328
7329 event->ptid = null_ptid;
bcc75809 7330 event->rs = get_remote_state ();
74531fed
PA
7331 event->ws.kind = TARGET_WAITKIND_IGNORE;
7332 event->ws.value.integer = 0;
f7e6eed5 7333 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
32603266 7334 event->regcache.clear ();
dc146f7c 7335 event->core = -1;
74531fed
PA
7336
7337 switch (buf[0])
7338 {
7339 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
7340 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7341 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7342 ss = signal number
7343 n... = register number
7344 r... = register contents
7345 */
7346
7347 p = &buf[3]; /* after Txx */
7348 while (*p)
7349 {
256642e8 7350 const char *p1;
cea39f65 7351 int fieldsize;
43ff13b4 7352
1f10ba14
PA
7353 p1 = strchr (p, ':');
7354 if (p1 == NULL)
7355 error (_("Malformed packet(a) (missing colon): %s\n\
7356Packet: '%s'\n"),
7357 p, buf);
7358 if (p == p1)
7359 error (_("Malformed packet(a) (missing register number): %s\n\
7360Packet: '%s'\n"),
7361 p, buf);
3c3bea1c 7362
1f10ba14
PA
7363 /* Some "registers" are actually extended stop information.
7364 Note if you're adding a new entry here: GDB 7.9 and
7365 earlier assume that all register "numbers" that start
7366 with an hex digit are real register numbers. Make sure
7367 the server only sends such a packet if it knows the
7368 client understands it. */
c8e38a49 7369
26d56a93 7370 if (strprefix (p, p1, "thread"))
1f10ba14 7371 event->ptid = read_ptid (++p1, &p);
82075af2
JS
7372 else if (strprefix (p, p1, "syscall_entry"))
7373 {
7374 ULONGEST sysno;
7375
7376 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7377 p = unpack_varlen_hex (++p1, &sysno);
7378 event->ws.value.syscall_number = (int) sysno;
7379 }
7380 else if (strprefix (p, p1, "syscall_return"))
7381 {
7382 ULONGEST sysno;
7383
7384 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7385 p = unpack_varlen_hex (++p1, &sysno);
7386 event->ws.value.syscall_number = (int) sysno;
7387 }
26d56a93
SL
7388 else if (strprefix (p, p1, "watch")
7389 || strprefix (p, p1, "rwatch")
7390 || strprefix (p, p1, "awatch"))
cea39f65 7391 {
f7e6eed5 7392 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
7393 p = unpack_varlen_hex (++p1, &addr);
7394 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 7395 }
26d56a93 7396 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
7397 {
7398 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7399
7400 /* Make sure the stub doesn't forget to indicate support
7401 with qSupported. */
7402 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7403 error (_("Unexpected swbreak stop reason"));
7404
7405 /* The value part is documented as "must be empty",
7406 though we ignore it, in case we ever decide to make
7407 use of it in a backward compatible way. */
8424cc97 7408 p = strchrnul (p1 + 1, ';');
f7e6eed5 7409 }
26d56a93 7410 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
7411 {
7412 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7413
7414 /* Make sure the stub doesn't forget to indicate support
7415 with qSupported. */
7416 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7417 error (_("Unexpected hwbreak stop reason"));
7418
7419 /* See above. */
8424cc97 7420 p = strchrnul (p1 + 1, ';');
f7e6eed5 7421 }
26d56a93 7422 else if (strprefix (p, p1, "library"))
cea39f65 7423 {
1f10ba14 7424 event->ws.kind = TARGET_WAITKIND_LOADED;
8424cc97 7425 p = strchrnul (p1 + 1, ';');
1f10ba14 7426 }
26d56a93 7427 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
7428 {
7429 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7430 /* p1 will indicate "begin" or "end", but it makes
7431 no difference for now, so ignore it. */
8424cc97 7432 p = strchrnul (p1 + 1, ';');
1f10ba14 7433 }
26d56a93 7434 else if (strprefix (p, p1, "core"))
1f10ba14
PA
7435 {
7436 ULONGEST c;
a744cf53 7437
1f10ba14
PA
7438 p = unpack_varlen_hex (++p1, &c);
7439 event->core = c;
cea39f65 7440 }
26d56a93 7441 else if (strprefix (p, p1, "fork"))
de0d863e
DB
7442 {
7443 event->ws.value.related_pid = read_ptid (++p1, &p);
7444 event->ws.kind = TARGET_WAITKIND_FORKED;
7445 }
26d56a93 7446 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
7447 {
7448 event->ws.value.related_pid = read_ptid (++p1, &p);
7449 event->ws.kind = TARGET_WAITKIND_VFORKED;
7450 }
26d56a93 7451 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
7452 {
7453 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
8424cc97 7454 p = strchrnul (p1 + 1, ';');
c269dbdb 7455 }
6ab24463 7456 else if (strprefix (p, p1, "exec"))
94585166
DB
7457 {
7458 ULONGEST ignored;
94585166
DB
7459 int pathlen;
7460
7461 /* Determine the length of the execd pathname. */
7462 p = unpack_varlen_hex (++p1, &ignored);
7463 pathlen = (p - p1) / 2;
7464
7465 /* Save the pathname for event reporting and for
7466 the next run command. */
c6321f19
TT
7467 gdb::unique_xmalloc_ptr<char[]> pathname
7468 ((char *) xmalloc (pathlen + 1));
7469 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
94585166
DB
7470 pathname[pathlen] = '\0';
7471
7472 /* This is freed during event handling. */
c6321f19 7473 event->ws.value.execd_pathname = pathname.release ();
94585166
DB
7474 event->ws.kind = TARGET_WAITKIND_EXECD;
7475
7476 /* Skip the registers included in this packet, since
7477 they may be for an architecture different from the
7478 one used by the original program. */
7479 skipregs = 1;
7480 }
65706a29
PA
7481 else if (strprefix (p, p1, "create"))
7482 {
7483 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
8424cc97 7484 p = strchrnul (p1 + 1, ';');
65706a29 7485 }
cea39f65
MS
7486 else
7487 {
1f10ba14 7488 ULONGEST pnum;
256642e8 7489 const char *p_temp;
1f10ba14 7490
94585166
DB
7491 if (skipregs)
7492 {
8424cc97 7493 p = strchrnul (p1 + 1, ';');
94585166
DB
7494 p++;
7495 continue;
7496 }
7497
1f10ba14
PA
7498 /* Maybe a real ``P'' register number. */
7499 p_temp = unpack_varlen_hex (p, &pnum);
7500 /* If the first invalid character is the colon, we got a
7501 register number. Otherwise, it's an unknown stop
7502 reason. */
7503 if (p_temp == p1)
7504 {
5cd63fda
PA
7505 /* If we haven't parsed the event's thread yet, find
7506 it now, in order to find the architecture of the
7507 reported expedited registers. */
7508 if (event->ptid == null_ptid)
7509 {
24ed6739
AB
7510 /* If there is no thread-id information then leave
7511 the event->ptid as null_ptid. Later in
7512 process_stop_reply we will pick a suitable
7513 thread. */
5cd63fda
PA
7514 const char *thr = strstr (p1 + 1, ";thread:");
7515 if (thr != NULL)
7516 event->ptid = read_ptid (thr + strlen (";thread:"),
7517 NULL);
5cd63fda
PA
7518 }
7519
7520 if (rsa == NULL)
7521 {
5b6d1e4f
PA
7522 inferior *inf
7523 = (event->ptid == null_ptid
7524 ? NULL
7525 : find_inferior_ptid (this, event->ptid));
5cd63fda
PA
7526 /* If this is the first time we learn anything
7527 about this process, skip the registers
7528 included in this packet, since we don't yet
7529 know which architecture to use to parse them.
7530 We'll determine the architecture later when
7531 we process the stop reply and retrieve the
7532 target description, via
7533 remote_notice_new_inferior ->
7534 post_create_inferior. */
7535 if (inf == NULL)
7536 {
7537 p = strchrnul (p1 + 1, ';');
7538 p++;
7539 continue;
7540 }
7541
7542 event->arch = inf->gdbarch;
9d6eea31 7543 rsa = event->rs->get_remote_arch_state (event->arch);
5cd63fda
PA
7544 }
7545
7546 packet_reg *reg
7547 = packet_reg_from_pnum (event->arch, rsa, pnum);
1f10ba14 7548 cached_reg_t cached_reg;
43ff13b4 7549
1f10ba14
PA
7550 if (reg == NULL)
7551 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 7552Packet: '%s'\n"),
1f10ba14 7553 hex_string (pnum), p, buf);
c8e38a49 7554
1f10ba14 7555 cached_reg.num = reg->regnum;
d1dff226 7556 cached_reg.data = (gdb_byte *)
5cd63fda 7557 xmalloc (register_size (event->arch, reg->regnum));
4100683b 7558
1f10ba14
PA
7559 p = p1 + 1;
7560 fieldsize = hex2bin (p, cached_reg.data,
5cd63fda 7561 register_size (event->arch, reg->regnum));
1f10ba14 7562 p += 2 * fieldsize;
5cd63fda 7563 if (fieldsize < register_size (event->arch, reg->regnum))
1f10ba14 7564 warning (_("Remote reply is too short: %s"), buf);
74531fed 7565
32603266 7566 event->regcache.push_back (cached_reg);
1f10ba14
PA
7567 }
7568 else
7569 {
7570 /* Not a number. Silently skip unknown optional
7571 info. */
8424cc97 7572 p = strchrnul (p1 + 1, ';');
1f10ba14 7573 }
cea39f65 7574 }
c8e38a49 7575
cea39f65
MS
7576 if (*p != ';')
7577 error (_("Remote register badly formatted: %s\nhere: %s"),
7578 buf, p);
7579 ++p;
7580 }
5b5596ff
PA
7581
7582 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7583 break;
7584
c8e38a49
PA
7585 /* fall through */
7586 case 'S': /* Old style status, just signal only. */
3a09da41
PA
7587 {
7588 int sig;
7589
7590 event->ws.kind = TARGET_WAITKIND_STOPPED;
7591 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7592 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7593 event->ws.value.sig = (enum gdb_signal) sig;
7594 else
7595 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7596 }
c8e38a49 7597 break;
65706a29
PA
7598 case 'w': /* Thread exited. */
7599 {
65706a29
PA
7600 ULONGEST value;
7601
7602 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7603 p = unpack_varlen_hex (&buf[1], &value);
7604 event->ws.value.integer = value;
7605 if (*p != ';')
7606 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 7607 event->ptid = read_ptid (++p, NULL);
65706a29
PA
7608 break;
7609 }
c8e38a49
PA
7610 case 'W': /* Target exited. */
7611 case 'X':
7612 {
c8e38a49 7613 ULONGEST value;
82f73884 7614
c8e38a49
PA
7615 /* GDB used to accept only 2 hex chars here. Stubs should
7616 only send more if they detect GDB supports multi-process
7617 support. */
7618 p = unpack_varlen_hex (&buf[1], &value);
82f73884 7619
c8e38a49
PA
7620 if (buf[0] == 'W')
7621 {
7622 /* The remote process exited. */
74531fed
PA
7623 event->ws.kind = TARGET_WAITKIND_EXITED;
7624 event->ws.value.integer = value;
c8e38a49
PA
7625 }
7626 else
7627 {
7628 /* The remote process exited with a signal. */
74531fed 7629 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
7630 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7631 event->ws.value.sig = (enum gdb_signal) value;
7632 else
7633 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 7634 }
82f73884 7635
e7af6c70
TBA
7636 /* If no process is specified, return null_ptid, and let the
7637 caller figure out the right process to use. */
7638 int pid = 0;
c8e38a49
PA
7639 if (*p == '\0')
7640 ;
7641 else if (*p == ';')
7642 {
7643 p++;
7644
0b24eb2d 7645 if (*p == '\0')
82f73884 7646 ;
61012eef 7647 else if (startswith (p, "process:"))
82f73884 7648 {
c8e38a49 7649 ULONGEST upid;
a744cf53 7650
c8e38a49
PA
7651 p += sizeof ("process:") - 1;
7652 unpack_varlen_hex (p, &upid);
7653 pid = upid;
82f73884
PA
7654 }
7655 else
7656 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 7657 }
c8e38a49
PA
7658 else
7659 error (_("unknown stop reply packet: %s"), buf);
f2907e49 7660 event->ptid = ptid_t (pid);
74531fed
PA
7661 }
7662 break;
f2faf941
PA
7663 case 'N':
7664 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7665 event->ptid = minus_one_ptid;
7666 break;
74531fed 7667 }
74531fed
PA
7668}
7669
722247f1
YQ
7670/* When the stub wants to tell GDB about a new notification reply, it
7671 sends a notification (%Stop, for example). Those can come it at
7672 any time, hence, we have to make sure that any pending
7673 putpkt/getpkt sequence we're making is finished, before querying
7674 the stub for more events with the corresponding ack command
7675 (vStopped, for example). E.g., if we started a vStopped sequence
7676 immediately upon receiving the notification, something like this
7677 could happen:
74531fed
PA
7678
7679 1.1) --> Hg 1
7680 1.2) <-- OK
7681 1.3) --> g
7682 1.4) <-- %Stop
7683 1.5) --> vStopped
7684 1.6) <-- (registers reply to step #1.3)
7685
7686 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7687 query.
7688
796cb314 7689 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
7690 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7691 doing whatever we were doing:
7692
7693 2.1) --> Hg 1
7694 2.2) <-- OK
7695 2.3) --> g
7696 2.4) <-- %Stop
7697 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7698 2.5) <-- (registers reply to step #2.3)
7699
85102364 7700 Eventually after step #2.5, we return to the event loop, which
74531fed
PA
7701 notices there's an event on the
7702 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7703 associated callback --- the function below. At this point, we're
7704 always safe to start a vStopped sequence. :
7705
7706 2.6) --> vStopped
7707 2.7) <-- T05 thread:2
7708 2.8) --> vStopped
7709 2.9) --> OK
7710*/
7711
722247f1 7712void
6b8edb51 7713remote_target::remote_notif_get_pending_events (notif_client *nc)
74531fed
PA
7714{
7715 struct remote_state *rs = get_remote_state ();
74531fed 7716
f48ff2a7 7717 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 7718 {
722247f1
YQ
7719 if (notif_debug)
7720 fprintf_unfiltered (gdb_stdlog,
7721 "notif: process: '%s' ack pending event\n",
7722 nc->name);
74531fed 7723
722247f1 7724 /* acknowledge */
8d64371b
TT
7725 nc->ack (this, nc, rs->buf.data (),
7726 rs->notif_state->pending_event[nc->id]);
f48ff2a7 7727 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
7728
7729 while (1)
7730 {
8d64371b
TT
7731 getpkt (&rs->buf, 0);
7732 if (strcmp (rs->buf.data (), "OK") == 0)
74531fed
PA
7733 break;
7734 else
8d64371b 7735 remote_notif_ack (this, nc, rs->buf.data ());
74531fed
PA
7736 }
7737 }
722247f1
YQ
7738 else
7739 {
7740 if (notif_debug)
7741 fprintf_unfiltered (gdb_stdlog,
7742 "notif: process: '%s' no pending reply\n",
7743 nc->name);
7744 }
74531fed
PA
7745}
7746
6b8edb51
PA
7747/* Wrapper around remote_target::remote_notif_get_pending_events to
7748 avoid having to export the whole remote_target class. */
7749
7750void
7751remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7752{
7753 remote->remote_notif_get_pending_events (nc);
7754}
7755
74531fed
PA
7756/* Called when it is decided that STOP_REPLY holds the info of the
7757 event that is to be returned to the core. This function always
7758 destroys STOP_REPLY. */
7759
6b8edb51
PA
7760ptid_t
7761remote_target::process_stop_reply (struct stop_reply *stop_reply,
7762 struct target_waitstatus *status)
74531fed
PA
7763{
7764 ptid_t ptid;
7765
7766 *status = stop_reply->ws;
7767 ptid = stop_reply->ptid;
7768
24ed6739
AB
7769 /* If no thread/process was reported by the stub then use the first
7770 non-exited thread in the current target. */
d7e15655 7771 if (ptid == null_ptid)
24ed6739 7772 {
cada5fc9
AB
7773 /* Some stop events apply to all threads in an inferior, while others
7774 only apply to a single thread. */
7775 bool is_stop_for_all_threads
7776 = (status->kind == TARGET_WAITKIND_EXITED
7777 || status->kind == TARGET_WAITKIND_SIGNALLED);
7778
24ed6739
AB
7779 for (thread_info *thr : all_non_exited_threads (this))
7780 {
cada5fc9
AB
7781 if (ptid != null_ptid
7782 && (!is_stop_for_all_threads
7783 || ptid.pid () != thr->ptid.pid ()))
24ed6739
AB
7784 {
7785 static bool warned = false;
7786
7787 if (!warned)
7788 {
7789 /* If you are seeing this warning then the remote target
cada5fc9
AB
7790 has stopped without specifying a thread-id, but the
7791 target does have multiple threads (or inferiors), and
7792 so GDB is having to guess which thread stopped.
7793
7794 Examples of what might cause this are the target
7795 sending and 'S' stop packet, or a 'T' stop packet and
7796 not including a thread-id.
7797
7798 Additionally, the target might send a 'W' or 'X
7799 packet without including a process-id, when the target
7800 has multiple running inferiors. */
7801 if (is_stop_for_all_threads)
7802 warning (_("multi-inferior target stopped without "
7803 "sending a process-id, using first "
7804 "non-exited inferior"));
7805 else
7806 warning (_("multi-threaded target stopped without "
7807 "sending a thread-id, using first "
7808 "non-exited thread"));
24ed6739
AB
7809 warned = true;
7810 }
7811 break;
7812 }
cada5fc9
AB
7813
7814 /* If this is a stop for all threads then don't use a particular
7815 threads ptid, instead create a new ptid where only the pid
7816 field is set. */
7817 if (is_stop_for_all_threads)
7818 ptid = ptid_t (thr->ptid.pid ());
7819 else
7820 ptid = thr->ptid;
24ed6739
AB
7821 }
7822 gdb_assert (ptid != null_ptid);
7823 }
74531fed 7824
5f3563ea 7825 if (status->kind != TARGET_WAITKIND_EXITED
f2faf941
PA
7826 && status->kind != TARGET_WAITKIND_SIGNALLED
7827 && status->kind != TARGET_WAITKIND_NO_RESUMED)
74531fed 7828 {
5f3563ea 7829 /* Expedited registers. */
32603266 7830 if (!stop_reply->regcache.empty ())
5f3563ea 7831 {
217f1f79 7832 struct regcache *regcache
5b6d1e4f 7833 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
5f3563ea 7834
32603266
TT
7835 for (cached_reg_t &reg : stop_reply->regcache)
7836 {
7837 regcache->raw_supply (reg.num, reg.data);
7838 xfree (reg.data);
7839 }
d1dff226 7840
32603266 7841 stop_reply->regcache.clear ();
5f3563ea 7842 }
74531fed 7843
1941c569 7844 remote_notice_new_inferior (ptid, 0);
5b6d1e4f 7845 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
799a2abe
PA
7846 remote_thr->core = stop_reply->core;
7847 remote_thr->stop_reason = stop_reply->stop_reason;
7848 remote_thr->watch_data_address = stop_reply->watch_data_address;
c9d22089
SM
7849
7850 if (target_is_non_stop_p ())
7851 {
7852 /* If the target works in non-stop mode, a stop-reply indicates that
7853 only this thread stopped. */
7854 remote_thr->set_not_resumed ();
7855 }
7856 else
7857 {
7858 /* If the target works in all-stop mode, a stop-reply indicates that
7859 all the target's threads stopped. */
7860 for (thread_info *tp : all_non_exited_threads (this))
7861 get_remote_thread_info (tp)->set_not_resumed ();
7862 }
74531fed
PA
7863 }
7864
32603266 7865 delete stop_reply;
74531fed
PA
7866 return ptid;
7867}
7868
7869/* The non-stop mode version of target_wait. */
7870
6b8edb51 7871ptid_t
b60cea74
TT
7872remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
7873 target_wait_flags options)
74531fed
PA
7874{
7875 struct remote_state *rs = get_remote_state ();
74531fed
PA
7876 struct stop_reply *stop_reply;
7877 int ret;
fee9eda9 7878 int is_notif = 0;
74531fed
PA
7879
7880 /* If in non-stop mode, get out of getpkt even if a
7881 notification is received. */
7882
8d64371b 7883 ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
74531fed
PA
7884 while (1)
7885 {
fee9eda9 7886 if (ret != -1 && !is_notif)
74531fed
PA
7887 switch (rs->buf[0])
7888 {
7889 case 'E': /* Error of some sort. */
7890 /* We're out of sync with the target now. Did it continue
7891 or not? We can't tell which thread it was in non-stop,
7892 so just ignore this. */
8d64371b 7893 warning (_("Remote failure reply: %s"), rs->buf.data ());
74531fed
PA
7894 break;
7895 case 'O': /* Console output. */
8d64371b 7896 remote_console_output (&rs->buf[1]);
74531fed
PA
7897 break;
7898 default:
8d64371b 7899 warning (_("Invalid remote reply: %s"), rs->buf.data ());
74531fed
PA
7900 break;
7901 }
7902
7903 /* Acknowledge a pending stop reply that may have arrived in the
7904 mean time. */
f48ff2a7 7905 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 7906 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
7907
7908 /* If indeed we noticed a stop reply, we're done. */
7909 stop_reply = queued_stop_reply (ptid);
7910 if (stop_reply != NULL)
7911 return process_stop_reply (stop_reply, status);
7912
47608cb1 7913 /* Still no event. If we're just polling for an event, then
74531fed 7914 return to the event loop. */
47608cb1 7915 if (options & TARGET_WNOHANG)
74531fed
PA
7916 {
7917 status->kind = TARGET_WAITKIND_IGNORE;
7918 return minus_one_ptid;
7919 }
7920
47608cb1 7921 /* Otherwise do a blocking wait. */
8d64371b 7922 ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
74531fed
PA
7923 }
7924}
7925
31ba933e
PA
7926/* Return the first resumed thread. */
7927
7928static ptid_t
5b6d1e4f 7929first_remote_resumed_thread (remote_target *target)
31ba933e 7930{
5b6d1e4f 7931 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
31ba933e
PA
7932 if (tp->resumed)
7933 return tp->ptid;
7934 return null_ptid;
7935}
7936
74531fed
PA
7937/* Wait until the remote machine stops, then return, storing status in
7938 STATUS just as `wait' would. */
7939
6b8edb51 7940ptid_t
b60cea74
TT
7941remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
7942 target_wait_flags options)
74531fed
PA
7943{
7944 struct remote_state *rs = get_remote_state ();
74531fed 7945 ptid_t event_ptid = null_ptid;
cea39f65 7946 char *buf;
74531fed
PA
7947 struct stop_reply *stop_reply;
7948
47608cb1
PA
7949 again:
7950
74531fed
PA
7951 status->kind = TARGET_WAITKIND_IGNORE;
7952 status->value.integer = 0;
7953
7954 stop_reply = queued_stop_reply (ptid);
7955 if (stop_reply != NULL)
7956 return process_stop_reply (stop_reply, status);
7957
7958 if (rs->cached_wait_status)
7959 /* Use the cached wait status, but only once. */
7960 rs->cached_wait_status = 0;
7961 else
7962 {
7963 int ret;
722247f1 7964 int is_notif;
567420d1 7965 int forever = ((options & TARGET_WNOHANG) == 0
6b8edb51 7966 && rs->wait_forever_enabled_p);
567420d1
PA
7967
7968 if (!rs->waiting_for_stop_reply)
7969 {
7970 status->kind = TARGET_WAITKIND_NO_RESUMED;
7971 return minus_one_ptid;
7972 }
74531fed 7973
74531fed
PA
7974 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7975 _never_ wait for ever -> test on target_is_async_p().
7976 However, before we do that we need to ensure that the caller
7977 knows how to take the target into/out of async mode. */
8d64371b 7978 ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
722247f1
YQ
7979
7980 /* GDB gets a notification. Return to core as this event is
7981 not interesting. */
7982 if (ret != -1 && is_notif)
7983 return minus_one_ptid;
567420d1
PA
7984
7985 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7986 return minus_one_ptid;
74531fed
PA
7987 }
7988
8d64371b 7989 buf = rs->buf.data ();
74531fed 7990
3a29589a
DJ
7991 /* Assume that the target has acknowledged Ctrl-C unless we receive
7992 an 'F' or 'O' packet. */
7993 if (buf[0] != 'F' && buf[0] != 'O')
7994 rs->ctrlc_pending_p = 0;
7995
74531fed
PA
7996 switch (buf[0])
7997 {
7998 case 'E': /* Error of some sort. */
7999 /* We're out of sync with the target now. Did it continue or
8000 not? Not is more likely, so report a stop. */
29090fb6
LM
8001 rs->waiting_for_stop_reply = 0;
8002
74531fed
PA
8003 warning (_("Remote failure reply: %s"), buf);
8004 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 8005 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
8006 break;
8007 case 'F': /* File-I/O request. */
e42e5352
YQ
8008 /* GDB may access the inferior memory while handling the File-I/O
8009 request, but we don't want GDB accessing memory while waiting
8010 for a stop reply. See the comments in putpkt_binary. Set
8011 waiting_for_stop_reply to 0 temporarily. */
8012 rs->waiting_for_stop_reply = 0;
6b8edb51 8013 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
3a29589a 8014 rs->ctrlc_pending_p = 0;
e42e5352
YQ
8015 /* GDB handled the File-I/O request, and the target is running
8016 again. Keep waiting for events. */
8017 rs->waiting_for_stop_reply = 1;
74531fed 8018 break;
f2faf941 8019 case 'N': case 'T': case 'S': case 'X': case 'W':
74531fed 8020 {
29090fb6
LM
8021 /* There is a stop reply to handle. */
8022 rs->waiting_for_stop_reply = 0;
8023
8024 stop_reply
6b8edb51
PA
8025 = (struct stop_reply *) remote_notif_parse (this,
8026 &notif_client_stop,
8d64371b 8027 rs->buf.data ());
74531fed 8028
74531fed 8029 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
8030 break;
8031 }
8032 case 'O': /* Console output. */
8033 remote_console_output (buf + 1);
c8e38a49
PA
8034 break;
8035 case '\0':
b73be471 8036 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
8037 {
8038 /* Zero length reply means that we tried 'S' or 'C' and the
8039 remote system doesn't support it. */
223ffa71 8040 target_terminal::ours_for_output ();
c8e38a49
PA
8041 printf_filtered
8042 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
8043 gdb_signal_to_name (rs->last_sent_signal));
8044 rs->last_sent_signal = GDB_SIGNAL_0;
223ffa71 8045 target_terminal::inferior ();
c8e38a49 8046
f5c4fcd9
TT
8047 strcpy (buf, rs->last_sent_step ? "s" : "c");
8048 putpkt (buf);
c8e38a49 8049 break;
43ff13b4 8050 }
86a73007 8051 /* fallthrough */
c8e38a49
PA
8052 default:
8053 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 8054 break;
43ff13b4 8055 }
c8e38a49 8056
f2faf941
PA
8057 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
8058 return minus_one_ptid;
8059 else if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
8060 {
8061 /* Nothing interesting happened. If we're doing a non-blocking
8062 poll, we're done. Otherwise, go back to waiting. */
8063 if (options & TARGET_WNOHANG)
8064 return minus_one_ptid;
8065 else
8066 goto again;
8067 }
74531fed
PA
8068 else if (status->kind != TARGET_WAITKIND_EXITED
8069 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884 8070 {
d7e15655 8071 if (event_ptid != null_ptid)
47f8a51d 8072 record_currthread (rs, event_ptid);
82f73884 8073 else
5b6d1e4f 8074 event_ptid = first_remote_resumed_thread (this);
43ff13b4 8075 }
74531fed 8076 else
e7af6c70
TBA
8077 {
8078 /* A process exit. Invalidate our notion of current thread. */
8079 record_currthread (rs, minus_one_ptid);
8080 /* It's possible that the packet did not include a pid. */
8081 if (event_ptid == null_ptid)
5b6d1e4f 8082 event_ptid = first_remote_resumed_thread (this);
e7af6c70
TBA
8083 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8084 if (event_ptid == null_ptid)
8085 event_ptid = magic_null_ptid;
8086 }
79d7f229 8087
82f73884 8088 return event_ptid;
43ff13b4
JM
8089}
8090
74531fed
PA
8091/* Wait until the remote machine stops, then return, storing status in
8092 STATUS just as `wait' would. */
8093
f6ac5f3d 8094ptid_t
b60cea74
TT
8095remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8096 target_wait_flags options)
c8e38a49
PA
8097{
8098 ptid_t event_ptid;
8099
6efcd9a8 8100 if (target_is_non_stop_p ())
6b8edb51 8101 event_ptid = wait_ns (ptid, status, options);
74531fed 8102 else
6b8edb51 8103 event_ptid = wait_as (ptid, status, options);
c8e38a49 8104
d9d41e78 8105 if (target_is_async_p ())
c8e38a49 8106 {
6b8edb51
PA
8107 remote_state *rs = get_remote_state ();
8108
74531fed
PA
8109 /* If there are are events left in the queue tell the event loop
8110 to return here. */
953edf2b 8111 if (!rs->stop_reply_queue.empty ())
6b8edb51 8112 mark_async_event_handler (rs->remote_async_inferior_event_token);
c8e38a49 8113 }
c8e38a49
PA
8114
8115 return event_ptid;
8116}
8117
74ca34ce 8118/* Fetch a single register using a 'p' packet. */
c906108c 8119
6b8edb51
PA
8120int
8121remote_target::fetch_register_using_p (struct regcache *regcache,
8122 packet_reg *reg)
b96ec7ac 8123{
ac7936df 8124 struct gdbarch *gdbarch = regcache->arch ();
b96ec7ac 8125 struct remote_state *rs = get_remote_state ();
2e9f7625 8126 char *buf, *p;
9890e433 8127 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
b96ec7ac
AC
8128 int i;
8129
4082afcc 8130 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
8131 return 0;
8132
8133 if (reg->pnum == -1)
8134 return 0;
8135
8d64371b 8136 p = rs->buf.data ();
fcad0fa4 8137 *p++ = 'p';
74ca34ce 8138 p += hexnumstr (p, reg->pnum);
fcad0fa4 8139 *p++ = '\0';
1f4437a4 8140 putpkt (rs->buf);
8d64371b 8141 getpkt (&rs->buf, 0);
3f9a994c 8142
8d64371b 8143 buf = rs->buf.data ();
2e9f7625 8144
8d64371b 8145 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_p]))
74ca34ce
DJ
8146 {
8147 case PACKET_OK:
8148 break;
8149 case PACKET_UNKNOWN:
8150 return 0;
8151 case PACKET_ERROR:
27a9c0bf 8152 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
ac7936df 8153 gdbarch_register_name (regcache->arch (),
27a9c0bf
MS
8154 reg->regnum),
8155 buf);
74ca34ce 8156 }
3f9a994c
JB
8157
8158 /* If this register is unfetchable, tell the regcache. */
8159 if (buf[0] == 'x')
8480adf2 8160 {
73e1c03f 8161 regcache->raw_supply (reg->regnum, NULL);
8480adf2 8162 return 1;
b96ec7ac 8163 }
b96ec7ac 8164
3f9a994c
JB
8165 /* Otherwise, parse and supply the value. */
8166 p = buf;
8167 i = 0;
8168 while (p[0] != 0)
8169 {
8170 if (p[1] == 0)
74ca34ce 8171 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
8172
8173 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8174 p += 2;
8175 }
73e1c03f 8176 regcache->raw_supply (reg->regnum, regp);
3f9a994c 8177 return 1;
b96ec7ac
AC
8178}
8179
74ca34ce
DJ
8180/* Fetch the registers included in the target's 'g' packet. */
8181
6b8edb51
PA
8182int
8183remote_target::send_g_packet ()
c906108c 8184{
d01949b6 8185 struct remote_state *rs = get_remote_state ();
cea39f65 8186 int buf_len;
c906108c 8187
8d64371b 8188 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
b75abf5b 8189 putpkt (rs->buf);
8d64371b 8190 getpkt (&rs->buf, 0);
b75abf5b
AK
8191 if (packet_check_result (rs->buf) == PACKET_ERROR)
8192 error (_("Could not read registers; remote failure reply '%s'"),
dda83cd7 8193 rs->buf.data ());
c906108c 8194
29709017
DJ
8195 /* We can get out of synch in various cases. If the first character
8196 in the buffer is not a hex character, assume that has happened
8197 and try to fetch another packet to read. */
8198 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8199 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8200 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8201 && rs->buf[0] != 'x') /* New: unavailable register value. */
8202 {
8203 if (remote_debug)
8204 fprintf_unfiltered (gdb_stdlog,
8205 "Bad register packet; fetching a new packet\n");
8d64371b 8206 getpkt (&rs->buf, 0);
29709017
DJ
8207 }
8208
8d64371b 8209 buf_len = strlen (rs->buf.data ());
74ca34ce
DJ
8210
8211 /* Sanity check the received packet. */
8212 if (buf_len % 2 != 0)
8d64371b 8213 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
29709017
DJ
8214
8215 return buf_len / 2;
8216}
8217
6b8edb51
PA
8218void
8219remote_target::process_g_packet (struct regcache *regcache)
29709017 8220{
ac7936df 8221 struct gdbarch *gdbarch = regcache->arch ();
29709017 8222 struct remote_state *rs = get_remote_state ();
9d6eea31 8223 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
29709017
DJ
8224 int i, buf_len;
8225 char *p;
8226 char *regs;
8227
8d64371b 8228 buf_len = strlen (rs->buf.data ());
29709017
DJ
8229
8230 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce 8231 if (buf_len > 2 * rsa->sizeof_g_packet)
fc809827 8232 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8d64371b
TT
8233 "bytes): %s"),
8234 rsa->sizeof_g_packet, buf_len / 2,
8235 rs->buf.data ());
74ca34ce
DJ
8236
8237 /* Save the size of the packet sent to us by the target. It is used
8238 as a heuristic when determining the max size of packets that the
8239 target can safely receive. */
8240 if (rsa->actual_register_packet_size == 0)
8241 rsa->actual_register_packet_size = buf_len;
8242
8243 /* If this is smaller than we guessed the 'g' packet would be,
8244 update our records. A 'g' reply that doesn't include a register's
8245 value implies either that the register is not available, or that
8246 the 'p' packet must be used. */
8247 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 8248 {
9dc193c3 8249 long sizeof_g_packet = buf_len / 2;
74ca34ce 8250
4a22f64d 8251 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 8252 {
9dc193c3
LF
8253 long offset = rsa->regs[i].offset;
8254 long reg_size = register_size (gdbarch, i);
8255
74ca34ce
DJ
8256 if (rsa->regs[i].pnum == -1)
8257 continue;
8258
9dc193c3 8259 if (offset >= sizeof_g_packet)
74ca34ce 8260 rsa->regs[i].in_g_packet = 0;
9dc193c3
LF
8261 else if (offset + reg_size > sizeof_g_packet)
8262 error (_("Truncated register %d in remote 'g' packet"), i);
b96ec7ac 8263 else
74ca34ce 8264 rsa->regs[i].in_g_packet = 1;
b96ec7ac 8265 }
9dc193c3
LF
8266
8267 /* Looks valid enough, we can assume this is the correct length
dda83cd7
SM
8268 for a 'g' packet. It's important not to adjust
8269 rsa->sizeof_g_packet if we have truncated registers otherwise
8270 this "if" won't be run the next time the method is called
8271 with a packet of the same size and one of the internal errors
8272 below will trigger instead. */
9dc193c3 8273 rsa->sizeof_g_packet = sizeof_g_packet;
74ca34ce 8274 }
b323314b 8275
224c3ddb 8276 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
8277
8278 /* Unimplemented registers read as all bits zero. */
ea9c271d 8279 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 8280
c906108c
SS
8281 /* Reply describes registers byte by byte, each byte encoded as two
8282 hex characters. Suck them all up, then supply them to the
8283 register cacheing/storage mechanism. */
8284
8d64371b 8285 p = rs->buf.data ();
ea9c271d 8286 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 8287 {
74ca34ce
DJ
8288 if (p[0] == 0 || p[1] == 0)
8289 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8290 internal_error (__FILE__, __LINE__,
9b20d036 8291 _("unexpected end of 'g' packet reply"));
74ca34ce 8292
c906108c 8293 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 8294 regs[i] = 0; /* 'x' */
c906108c
SS
8295 else
8296 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8297 p += 2;
8298 }
8299
a744cf53
MS
8300 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8301 {
8302 struct packet_reg *r = &rsa->regs[i];
9dc193c3 8303 long reg_size = register_size (gdbarch, i);
a744cf53
MS
8304
8305 if (r->in_g_packet)
8306 {
8d64371b 8307 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
a744cf53
MS
8308 /* This shouldn't happen - we adjusted in_g_packet above. */
8309 internal_error (__FILE__, __LINE__,
9b20d036 8310 _("unexpected end of 'g' packet reply"));
a744cf53
MS
8311 else if (rs->buf[r->offset * 2] == 'x')
8312 {
8d64371b 8313 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
a744cf53
MS
8314 /* The register isn't available, mark it as such (at
8315 the same time setting the value to zero). */
73e1c03f 8316 regcache->raw_supply (r->regnum, NULL);
a744cf53
MS
8317 }
8318 else
73e1c03f 8319 regcache->raw_supply (r->regnum, regs + r->offset);
a744cf53
MS
8320 }
8321 }
c906108c
SS
8322}
8323
6b8edb51
PA
8324void
8325remote_target::fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
8326{
8327 send_g_packet ();
56be3814 8328 process_g_packet (regcache);
29709017
DJ
8329}
8330
e6e4e701
PA
8331/* Make the remote selected traceframe match GDB's selected
8332 traceframe. */
8333
6b8edb51
PA
8334void
8335remote_target::set_remote_traceframe ()
e6e4e701
PA
8336{
8337 int newnum;
262e1174 8338 struct remote_state *rs = get_remote_state ();
e6e4e701 8339
262e1174 8340 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
8341 return;
8342
8343 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 8344 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
8345
8346 newnum = target_trace_find (tfind_number,
8347 get_traceframe_number (), 0, 0, NULL);
8348
8349 /* Should not happen. If it does, all bets are off. */
8350 if (newnum != get_traceframe_number ())
8351 warning (_("could not set remote traceframe"));
8352}
8353
f6ac5f3d
PA
8354void
8355remote_target::fetch_registers (struct regcache *regcache, int regnum)
74ca34ce 8356{
ac7936df 8357 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8358 struct remote_state *rs = get_remote_state ();
8359 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8360 int i;
8361
e6e4e701 8362 set_remote_traceframe ();
222312d3 8363 set_general_thread (regcache->ptid ());
74ca34ce
DJ
8364
8365 if (regnum >= 0)
8366 {
5cd63fda 8367 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8368
74ca34ce
DJ
8369 gdb_assert (reg != NULL);
8370
8371 /* If this register might be in the 'g' packet, try that first -
8372 we are likely to read more than one register. If this is the
8373 first 'g' packet, we might be overly optimistic about its
8374 contents, so fall back to 'p'. */
8375 if (reg->in_g_packet)
8376 {
56be3814 8377 fetch_registers_using_g (regcache);
74ca34ce
DJ
8378 if (reg->in_g_packet)
8379 return;
8380 }
8381
56be3814 8382 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
8383 return;
8384
8385 /* This register is not available. */
73e1c03f 8386 regcache->raw_supply (reg->regnum, NULL);
74ca34ce
DJ
8387
8388 return;
8389 }
8390
56be3814 8391 fetch_registers_using_g (regcache);
74ca34ce 8392
5cd63fda 8393 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8394 if (!rsa->regs[i].in_g_packet)
56be3814 8395 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
8396 {
8397 /* This register is not available. */
73e1c03f 8398 regcache->raw_supply (i, NULL);
74ca34ce
DJ
8399 }
8400}
8401
c906108c
SS
8402/* Prepare to store registers. Since we may send them all (using a
8403 'G' request), we have to read out the ones we don't want to change
8404 first. */
8405
f6ac5f3d
PA
8406void
8407remote_target::prepare_to_store (struct regcache *regcache)
c906108c 8408{
9d6eea31
PA
8409 struct remote_state *rs = get_remote_state ();
8410 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cf0e1e0d 8411 int i;
cf0e1e0d 8412
c906108c 8413 /* Make sure the entire registers array is valid. */
4082afcc 8414 switch (packet_support (PACKET_P))
5a2468f5
JM
8415 {
8416 case PACKET_DISABLE:
8417 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 8418 /* Make sure all the necessary registers are cached. */
ac7936df 8419 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
ea9c271d 8420 if (rsa->regs[i].in_g_packet)
0b47d985 8421 regcache->raw_update (rsa->regs[i].regnum);
5a2468f5
JM
8422 break;
8423 case PACKET_ENABLE:
8424 break;
8425 }
8426}
8427
ad10f812 8428/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 8429 packet was not recognized. */
5a2468f5 8430
6b8edb51
PA
8431int
8432remote_target::store_register_using_P (const struct regcache *regcache,
8433 packet_reg *reg)
5a2468f5 8434{
ac7936df 8435 struct gdbarch *gdbarch = regcache->arch ();
d01949b6 8436 struct remote_state *rs = get_remote_state ();
5a2468f5 8437 /* Try storing a single register. */
8d64371b 8438 char *buf = rs->buf.data ();
9890e433 8439 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
5a2468f5 8440 char *p;
5a2468f5 8441
4082afcc 8442 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
8443 return 0;
8444
8445 if (reg->pnum == -1)
8446 return 0;
8447
ea9c271d 8448 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 8449 p = buf + strlen (buf);
34a79281 8450 regcache->raw_collect (reg->regnum, regp);
4a22f64d 8451 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4 8452 putpkt (rs->buf);
8d64371b 8453 getpkt (&rs->buf, 0);
5a2468f5 8454
74ca34ce
DJ
8455 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8456 {
8457 case PACKET_OK:
8458 return 1;
8459 case PACKET_ERROR:
27a9c0bf 8460 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8d64371b 8461 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
74ca34ce
DJ
8462 case PACKET_UNKNOWN:
8463 return 0;
8464 default:
8465 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8466 }
c906108c
SS
8467}
8468
23860348
MS
8469/* Store register REGNUM, or all registers if REGNUM == -1, from the
8470 contents of the register cache buffer. FIXME: ignores errors. */
c906108c 8471
6b8edb51
PA
8472void
8473remote_target::store_registers_using_G (const struct regcache *regcache)
c906108c 8474{
d01949b6 8475 struct remote_state *rs = get_remote_state ();
9d6eea31 8476 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cfd77fa1 8477 gdb_byte *regs;
c906108c
SS
8478 char *p;
8479
193cb69f
AC
8480 /* Extract all the registers in the regcache copying them into a
8481 local buffer. */
8482 {
b323314b 8483 int i;
a744cf53 8484
224c3ddb 8485 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 8486 memset (regs, 0, rsa->sizeof_g_packet);
ac7936df 8487 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
193cb69f 8488 {
ea9c271d 8489 struct packet_reg *r = &rsa->regs[i];
a744cf53 8490
b323314b 8491 if (r->in_g_packet)
34a79281 8492 regcache->raw_collect (r->regnum, regs + r->offset);
193cb69f
AC
8493 }
8494 }
c906108c
SS
8495
8496 /* Command describes registers byte by byte,
8497 each byte encoded as two hex characters. */
8d64371b 8498 p = rs->buf.data ();
193cb69f 8499 *p++ = 'G';
74ca34ce 8500 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4 8501 putpkt (rs->buf);
8d64371b 8502 getpkt (&rs->buf, 0);
1f4437a4 8503 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf 8504 error (_("Could not write registers; remote failure reply '%s'"),
8d64371b 8505 rs->buf.data ());
c906108c 8506}
74ca34ce
DJ
8507
8508/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8509 of the register cache buffer. FIXME: ignores errors. */
8510
f6ac5f3d
PA
8511void
8512remote_target::store_registers (struct regcache *regcache, int regnum)
74ca34ce 8513{
5cd63fda 8514 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8515 struct remote_state *rs = get_remote_state ();
8516 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8517 int i;
8518
e6e4e701 8519 set_remote_traceframe ();
222312d3 8520 set_general_thread (regcache->ptid ());
74ca34ce
DJ
8521
8522 if (regnum >= 0)
8523 {
5cd63fda 8524 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8525
74ca34ce
DJ
8526 gdb_assert (reg != NULL);
8527
8528 /* Always prefer to store registers using the 'P' packet if
8529 possible; we often change only a small number of registers.
8530 Sometimes we change a larger number; we'd need help from a
8531 higher layer to know to use 'G'. */
56be3814 8532 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
8533 return;
8534
8535 /* For now, don't complain if we have no way to write the
8536 register. GDB loses track of unavailable registers too
8537 easily. Some day, this may be an error. We don't have
0df8b418 8538 any way to read the register, either... */
74ca34ce
DJ
8539 if (!reg->in_g_packet)
8540 return;
8541
56be3814 8542 store_registers_using_G (regcache);
74ca34ce
DJ
8543 return;
8544 }
8545
56be3814 8546 store_registers_using_G (regcache);
74ca34ce 8547
5cd63fda 8548 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8549 if (!rsa->regs[i].in_g_packet)
56be3814 8550 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
8551 /* See above for why we do not issue an error here. */
8552 continue;
8553}
c906108c
SS
8554\f
8555
8556/* Return the number of hex digits in num. */
8557
8558static int
fba45db2 8559hexnumlen (ULONGEST num)
c906108c
SS
8560{
8561 int i;
8562
8563 for (i = 0; num != 0; i++)
8564 num >>= 4;
8565
325fac50 8566 return std::max (i, 1);
c906108c
SS
8567}
8568
2df3850c 8569/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
8570
8571static int
fba45db2 8572hexnumstr (char *buf, ULONGEST num)
c906108c 8573{
c906108c 8574 int len = hexnumlen (num);
a744cf53 8575
2df3850c
JM
8576 return hexnumnstr (buf, num, len);
8577}
8578
c906108c 8579
2df3850c 8580/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 8581
2df3850c 8582static int
fba45db2 8583hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
8584{
8585 int i;
8586
8587 buf[width] = '\0';
8588
8589 for (i = width - 1; i >= 0; i--)
c906108c 8590 {
c5aa993b 8591 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
8592 num >>= 4;
8593 }
8594
2df3850c 8595 return width;
c906108c
SS
8596}
8597
23860348 8598/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
8599
8600static CORE_ADDR
fba45db2 8601remote_address_masked (CORE_ADDR addr)
c906108c 8602{
883b9c6c 8603 unsigned int address_size = remote_address_size;
a744cf53 8604
911c95a5
UW
8605 /* If "remoteaddresssize" was not set, default to target address size. */
8606 if (!address_size)
f5656ead 8607 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
8608
8609 if (address_size > 0
8610 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
8611 {
8612 /* Only create a mask when that mask can safely be constructed
dda83cd7 8613 in a ULONGEST variable. */
c906108c 8614 ULONGEST mask = 1;
a744cf53 8615
911c95a5 8616 mask = (mask << address_size) - 1;
c906108c
SS
8617 addr &= mask;
8618 }
8619 return addr;
8620}
8621
8622/* Determine whether the remote target supports binary downloading.
8623 This is accomplished by sending a no-op memory write of zero length
8624 to the target at the specified address. It does not suffice to send
23860348
MS
8625 the whole packet, since many stubs strip the eighth bit and
8626 subsequently compute a wrong checksum, which causes real havoc with
8627 remote_write_bytes.
7a292a7a 8628
96baa820 8629 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 8630 clean. In cases like this, the user should clear "remote
23860348 8631 X-packet". */
96baa820 8632
6b8edb51
PA
8633void
8634remote_target::check_binary_download (CORE_ADDR addr)
c906108c 8635{
d01949b6 8636 struct remote_state *rs = get_remote_state ();
24b06219 8637
4082afcc 8638 switch (packet_support (PACKET_X))
c906108c 8639 {
96baa820
JM
8640 case PACKET_DISABLE:
8641 break;
8642 case PACKET_ENABLE:
8643 break;
8644 case PACKET_SUPPORT_UNKNOWN:
8645 {
96baa820 8646 char *p;
802188a7 8647
8d64371b 8648 p = rs->buf.data ();
96baa820
JM
8649 *p++ = 'X';
8650 p += hexnumstr (p, (ULONGEST) addr);
8651 *p++ = ',';
8652 p += hexnumstr (p, (ULONGEST) 0);
8653 *p++ = ':';
8654 *p = '\0';
802188a7 8655
8d64371b
TT
8656 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
8657 getpkt (&rs->buf, 0);
c906108c 8658
2e9f7625 8659 if (rs->buf[0] == '\0')
96baa820
JM
8660 {
8661 if (remote_debug)
8662 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8663 "binary downloading NOT "
8664 "supported by target\n");
444abaca 8665 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
8666 }
8667 else
8668 {
8669 if (remote_debug)
8670 fprintf_unfiltered (gdb_stdlog,
64b9b334 8671 "binary downloading supported by target\n");
444abaca 8672 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
8673 }
8674 break;
8675 }
c906108c
SS
8676 }
8677}
8678
124e13d9
SM
8679/* Helper function to resize the payload in order to try to get a good
8680 alignment. We try to write an amount of data such that the next write will
8681 start on an address aligned on REMOTE_ALIGN_WRITES. */
8682
8683static int
8684align_for_efficient_write (int todo, CORE_ADDR memaddr)
8685{
8686 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8687}
8688
c906108c
SS
8689/* Write memory data directly to the remote machine.
8690 This does not inform the data cache; the data cache uses this.
a76d924d 8691 HEADER is the starting part of the packet.
c906108c
SS
8692 MEMADDR is the address in the remote memory space.
8693 MYADDR is the address of the buffer in our space.
124e13d9
SM
8694 LEN_UNITS is the number of addressable units to write.
8695 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
8696 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8697 should send data as binary ('X'), or hex-encoded ('M').
8698
8699 The function creates packet of the form
8700 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8701
124e13d9 8702 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
8703
8704 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8705 are omitted.
8706
9b409511 8707 Return the transferred status, error or OK (an
124e13d9
SM
8708 'enum target_xfer_status' value). Save the number of addressable units
8709 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8710
8711 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8712 exchange between gdb and the stub could look like (?? in place of the
8713 checksum):
8714
8715 -> $m1000,4#??
8716 <- aaaabbbbccccdddd
8717
8718 -> $M1000,3:eeeeffffeeee#??
8719 <- OK
8720
8721 -> $m1000,4#??
8722 <- eeeeffffeeeedddd */
c906108c 8723
6b8edb51
PA
8724target_xfer_status
8725remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8726 const gdb_byte *myaddr,
8727 ULONGEST len_units,
8728 int unit_size,
8729 ULONGEST *xfered_len_units,
8730 char packet_format, int use_length)
c906108c 8731{
6d820c5c 8732 struct remote_state *rs = get_remote_state ();
cfd77fa1 8733 char *p;
a76d924d
DJ
8734 char *plen = NULL;
8735 int plenlen = 0;
124e13d9
SM
8736 int todo_units;
8737 int units_written;
8738 int payload_capacity_bytes;
8739 int payload_length_bytes;
a76d924d
DJ
8740
8741 if (packet_format != 'X' && packet_format != 'M')
8742 internal_error (__FILE__, __LINE__,
9b20d036 8743 _("remote_write_bytes_aux: bad packet format"));
c906108c 8744
124e13d9 8745 if (len_units == 0)
9b409511 8746 return TARGET_XFER_EOF;
b2182ed2 8747
124e13d9 8748 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 8749
6d820c5c
DJ
8750 /* The packet buffer will be large enough for the payload;
8751 get_memory_packet_size ensures this. */
a76d924d 8752 rs->buf[0] = '\0';
c906108c 8753
a257b5bb 8754 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
8755 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8756
124e13d9 8757 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 8758 if (!use_length)
0df8b418 8759 /* The comma won't be used. */
124e13d9
SM
8760 payload_capacity_bytes += 1;
8761 payload_capacity_bytes -= strlen (header);
8762 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 8763
a76d924d 8764 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 8765
8d64371b
TT
8766 strcat (rs->buf.data (), header);
8767 p = rs->buf.data () + strlen (header);
a76d924d
DJ
8768
8769 /* Compute a best guess of the number of bytes actually transfered. */
8770 if (packet_format == 'X')
c906108c 8771 {
23860348 8772 /* Best guess at number of bytes that will fit. */
325fac50
PA
8773 todo_units = std::min (len_units,
8774 (ULONGEST) payload_capacity_bytes / unit_size);
a76d924d 8775 if (use_length)
124e13d9 8776 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50 8777 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
8778 }
8779 else
8780 {
124e13d9 8781 /* Number of bytes that will fit. */
325fac50
PA
8782 todo_units
8783 = std::min (len_units,
8784 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
a76d924d 8785 if (use_length)
124e13d9 8786 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50
PA
8787 todo_units = std::min (todo_units,
8788 (payload_capacity_bytes / unit_size) / 2);
917317f4 8789 }
a76d924d 8790
124e13d9 8791 if (todo_units <= 0)
3de11b2e 8792 internal_error (__FILE__, __LINE__,
405f8e94 8793 _("minimum packet size too small to write data"));
802188a7 8794
6765f3e5
DJ
8795 /* If we already need another packet, then try to align the end
8796 of this packet to a useful boundary. */
124e13d9
SM
8797 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8798 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 8799
a257b5bb 8800 /* Append "<memaddr>". */
917317f4
JM
8801 memaddr = remote_address_masked (memaddr);
8802 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 8803
a76d924d
DJ
8804 if (use_length)
8805 {
8806 /* Append ",". */
8807 *p++ = ',';
802188a7 8808
124e13d9 8809 /* Append the length and retain its location and size. It may need to be
dda83cd7 8810 adjusted once the packet body has been created. */
a76d924d 8811 plen = p;
124e13d9 8812 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
8813 p += plenlen;
8814 }
a257b5bb
AC
8815
8816 /* Append ":". */
917317f4
JM
8817 *p++ = ':';
8818 *p = '\0';
802188a7 8819
a257b5bb 8820 /* Append the packet body. */
a76d924d 8821 if (packet_format == 'X')
917317f4 8822 {
917317f4
JM
8823 /* Binary mode. Send target system values byte by byte, in
8824 increasing byte addresses. Only escape certain critical
8825 characters. */
124e13d9
SM
8826 payload_length_bytes =
8827 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8828 &units_written, payload_capacity_bytes);
6765f3e5 8829
124e13d9 8830 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
8831 a second try to keep the end of the packet aligned. Don't do
8832 this if the packet is tiny. */
124e13d9 8833 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 8834 {
124e13d9
SM
8835 int new_todo_units;
8836
8837 new_todo_units = align_for_efficient_write (units_written, memaddr);
8838
8839 if (new_todo_units != units_written)
8840 payload_length_bytes =
8841 remote_escape_output (myaddr, new_todo_units, unit_size,
8842 (gdb_byte *) p, &units_written,
8843 payload_capacity_bytes);
6765f3e5
DJ
8844 }
8845
124e13d9
SM
8846 p += payload_length_bytes;
8847 if (use_length && units_written < todo_units)
c906108c 8848 {
802188a7 8849 /* Escape chars have filled up the buffer prematurely,
124e13d9 8850 and we have actually sent fewer units than planned.
917317f4
JM
8851 Fix-up the length field of the packet. Use the same
8852 number of characters as before. */
124e13d9
SM
8853 plen += hexnumnstr (plen, (ULONGEST) units_written,
8854 plenlen);
917317f4 8855 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 8856 }
a76d924d
DJ
8857 }
8858 else
8859 {
917317f4
JM
8860 /* Normal mode: Send target system values byte by byte, in
8861 increasing byte addresses. Each byte is encoded as a two hex
8862 value. */
124e13d9
SM
8863 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8864 units_written = todo_units;
c906108c 8865 }
802188a7 8866
8d64371b
TT
8867 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
8868 getpkt (&rs->buf, 0);
802188a7 8869
2e9f7625 8870 if (rs->buf[0] == 'E')
00d84524 8871 return TARGET_XFER_E_IO;
802188a7 8872
124e13d9
SM
8873 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8874 send fewer units than we'd planned. */
8875 *xfered_len_units = (ULONGEST) units_written;
92ffd475 8876 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
8877}
8878
a76d924d
DJ
8879/* Write memory data directly to the remote machine.
8880 This does not inform the data cache; the data cache uses this.
8881 MEMADDR is the address in the remote memory space.
8882 MYADDR is the address of the buffer in our space.
8883 LEN is the number of bytes.
8884
9b409511
YQ
8885 Return the transferred status, error or OK (an
8886 'enum target_xfer_status' value). Save the number of bytes
8887 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 8888
6b8edb51
PA
8889target_xfer_status
8890remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
8891 ULONGEST len, int unit_size,
8892 ULONGEST *xfered_len)
a76d924d 8893{
a121b7c1 8894 const char *packet_format = NULL;
a76d924d
DJ
8895
8896 /* Check whether the target supports binary download. */
8897 check_binary_download (memaddr);
8898
4082afcc 8899 switch (packet_support (PACKET_X))
a76d924d
DJ
8900 {
8901 case PACKET_ENABLE:
8902 packet_format = "X";
8903 break;
8904 case PACKET_DISABLE:
8905 packet_format = "M";
8906 break;
8907 case PACKET_SUPPORT_UNKNOWN:
8908 internal_error (__FILE__, __LINE__,
8909 _("remote_write_bytes: bad internal state"));
8910 default:
8911 internal_error (__FILE__, __LINE__, _("bad switch"));
8912 }
8913
8914 return remote_write_bytes_aux (packet_format,
124e13d9 8915 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 8916 packet_format[0], 1);
a76d924d
DJ
8917}
8918
9217e74e
YQ
8919/* Read memory data directly from the remote machine.
8920 This does not use the data cache; the data cache uses this.
8921 MEMADDR is the address in the remote memory space.
8922 MYADDR is the address of the buffer in our space.
124e13d9
SM
8923 LEN_UNITS is the number of addressable memory units to read..
8924 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
8925
8926 Return the transferred status, error or OK (an
8927 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
8928 transferred in *XFERED_LEN_UNITS.
8929
8930 See the comment of remote_write_bytes_aux for an example of
8931 memory read/write exchange between gdb and the stub. */
9217e74e 8932
6b8edb51
PA
8933target_xfer_status
8934remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
8935 ULONGEST len_units,
8936 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
8937{
8938 struct remote_state *rs = get_remote_state ();
124e13d9 8939 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 8940 char *p;
124e13d9
SM
8941 int todo_units;
8942 int decoded_bytes;
9217e74e 8943
124e13d9 8944 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
8945 /* The packet buffer will be large enough for the payload;
8946 get_memory_packet_size ensures this. */
8947
124e13d9 8948 /* Number of units that will fit. */
325fac50
PA
8949 todo_units = std::min (len_units,
8950 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
8951
8952 /* Construct "m"<memaddr>","<len>". */
8953 memaddr = remote_address_masked (memaddr);
8d64371b 8954 p = rs->buf.data ();
9217e74e
YQ
8955 *p++ = 'm';
8956 p += hexnumstr (p, (ULONGEST) memaddr);
8957 *p++ = ',';
124e13d9 8958 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
8959 *p = '\0';
8960 putpkt (rs->buf);
8d64371b 8961 getpkt (&rs->buf, 0);
9217e74e
YQ
8962 if (rs->buf[0] == 'E'
8963 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8964 && rs->buf[3] == '\0')
8965 return TARGET_XFER_E_IO;
8966 /* Reply describes memory byte by byte, each byte encoded as two hex
8967 characters. */
8d64371b 8968 p = rs->buf.data ();
124e13d9 8969 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 8970 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 8971 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
92ffd475 8972 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9217e74e
YQ
8973}
8974
b55fbac4
YQ
8975/* Using the set of read-only target sections of remote, read live
8976 read-only memory.
8acf9577
YQ
8977
8978 For interface/parameters/return description see target.h,
8979 to_xfer_partial. */
8980
6b8edb51
PA
8981target_xfer_status
8982remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
8983 ULONGEST memaddr,
8984 ULONGEST len,
8985 int unit_size,
8986 ULONGEST *xfered_len)
8acf9577
YQ
8987{
8988 struct target_section *secp;
8acf9577 8989
6b8edb51 8990 secp = target_section_by_addr (this, memaddr);
8acf9577 8991 if (secp != NULL
fd361982 8992 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
8acf9577 8993 {
8acf9577
YQ
8994 ULONGEST memend = memaddr + len;
8995
d7a78e5c
TT
8996 target_section_table *table = target_get_section_table (this);
8997 for (target_section &p : *table)
8acf9577 8998 {
bb2a6777 8999 if (memaddr >= p.addr)
8acf9577 9000 {
bb2a6777 9001 if (memend <= p.endaddr)
8acf9577
YQ
9002 {
9003 /* Entire transfer is within this section. */
124e13d9 9004 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 9005 xfered_len);
8acf9577 9006 }
bb2a6777 9007 else if (memaddr >= p.endaddr)
8acf9577
YQ
9008 {
9009 /* This section ends before the transfer starts. */
9010 continue;
9011 }
9012 else
9013 {
9014 /* This section overlaps the transfer. Just do half. */
bb2a6777 9015 len = p.endaddr - memaddr;
124e13d9 9016 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 9017 xfered_len);
8acf9577
YQ
9018 }
9019 }
9020 }
9021 }
9022
9023 return TARGET_XFER_EOF;
9024}
9025
9217e74e
YQ
9026/* Similar to remote_read_bytes_1, but it reads from the remote stub
9027 first if the requested memory is unavailable in traceframe.
9028 Otherwise, fall back to remote_read_bytes_1. */
c906108c 9029
6b8edb51
PA
9030target_xfer_status
9031remote_target::remote_read_bytes (CORE_ADDR memaddr,
9032 gdb_byte *myaddr, ULONGEST len, int unit_size,
9033 ULONGEST *xfered_len)
c906108c 9034{
6b6aa828 9035 if (len == 0)
96c4f946 9036 return TARGET_XFER_EOF;
b2182ed2 9037
8acf9577
YQ
9038 if (get_traceframe_number () != -1)
9039 {
a79b1bc6 9040 std::vector<mem_range> available;
8acf9577
YQ
9041
9042 /* If we fail to get the set of available memory, then the
9043 target does not support querying traceframe info, and so we
9044 attempt reading from the traceframe anyway (assuming the
9045 target implements the old QTro packet then). */
9046 if (traceframe_available_memory (&available, memaddr, len))
9047 {
a79b1bc6 9048 if (available.empty () || available[0].start != memaddr)
8acf9577
YQ
9049 {
9050 enum target_xfer_status res;
9051
9052 /* Don't read into the traceframe's available
9053 memory. */
a79b1bc6 9054 if (!available.empty ())
8acf9577
YQ
9055 {
9056 LONGEST oldlen = len;
9057
a79b1bc6 9058 len = available[0].start - memaddr;
8acf9577
YQ
9059 gdb_assert (len <= oldlen);
9060 }
9061
8acf9577 9062 /* This goes through the topmost target again. */
6b8edb51 9063 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
124e13d9 9064 len, unit_size, xfered_len);
8acf9577
YQ
9065 if (res == TARGET_XFER_OK)
9066 return TARGET_XFER_OK;
9067 else
9068 {
9069 /* No use trying further, we know some memory starting
9070 at MEMADDR isn't available. */
9071 *xfered_len = len;
92ffd475
PC
9072 return (*xfered_len != 0) ?
9073 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8acf9577
YQ
9074 }
9075 }
9076
9077 /* Don't try to read more than how much is available, in
9078 case the target implements the deprecated QTro packet to
9079 cater for older GDBs (the target's knowledge of read-only
9080 sections may be outdated by now). */
a79b1bc6 9081 len = available[0].length;
8acf9577
YQ
9082 }
9083 }
9084
124e13d9 9085 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 9086}
74531fed 9087
c906108c 9088\f
c906108c 9089
a76d924d
DJ
9090/* Sends a packet with content determined by the printf format string
9091 FORMAT and the remaining arguments, then gets the reply. Returns
9092 whether the packet was a success, a failure, or unknown. */
9093
6b8edb51
PA
9094packet_result
9095remote_target::remote_send_printf (const char *format, ...)
a76d924d
DJ
9096{
9097 struct remote_state *rs = get_remote_state ();
9098 int max_size = get_remote_packet_size ();
a76d924d 9099 va_list ap;
a744cf53 9100
a76d924d
DJ
9101 va_start (ap, format);
9102
9103 rs->buf[0] = '\0';
8d64371b 9104 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
33b031ce
GB
9105
9106 va_end (ap);
9107
9108 if (size >= max_size)
9b20d036 9109 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
9110
9111 if (putpkt (rs->buf) < 0)
9112 error (_("Communication problem with target."));
9113
9114 rs->buf[0] = '\0';
8d64371b 9115 getpkt (&rs->buf, 0);
a76d924d
DJ
9116
9117 return packet_check_result (rs->buf);
9118}
9119
a76d924d
DJ
9120/* Flash writing can take quite some time. We'll set
9121 effectively infinite timeout for flash operations.
9122 In future, we'll need to decide on a better approach. */
9123static const int remote_flash_timeout = 1000;
9124
f6ac5f3d
PA
9125void
9126remote_target::flash_erase (ULONGEST address, LONGEST length)
a76d924d 9127{
f5656ead 9128 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d 9129 enum packet_result ret;
2ec845e7
TT
9130 scoped_restore restore_timeout
9131 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
a76d924d
DJ
9132
9133 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 9134 phex (address, addr_size),
a76d924d
DJ
9135 phex (length, 4));
9136 switch (ret)
9137 {
9138 case PACKET_UNKNOWN:
9139 error (_("Remote target does not support flash erase"));
9140 case PACKET_ERROR:
9141 error (_("Error erasing flash with vFlashErase packet"));
9142 default:
9143 break;
9144 }
a76d924d
DJ
9145}
9146
6b8edb51
PA
9147target_xfer_status
9148remote_target::remote_flash_write (ULONGEST address,
9149 ULONGEST length, ULONGEST *xfered_len,
9150 const gdb_byte *data)
a76d924d 9151{
2ec845e7
TT
9152 scoped_restore restore_timeout
9153 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9154 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9155 xfered_len,'X', 0);
a76d924d
DJ
9156}
9157
f6ac5f3d
PA
9158void
9159remote_target::flash_done ()
a76d924d 9160{
a76d924d 9161 int ret;
a76d924d 9162
2ec845e7
TT
9163 scoped_restore restore_timeout
9164 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9165
a76d924d 9166 ret = remote_send_printf ("vFlashDone");
a76d924d
DJ
9167
9168 switch (ret)
9169 {
9170 case PACKET_UNKNOWN:
9171 error (_("Remote target does not support vFlashDone"));
9172 case PACKET_ERROR:
9173 error (_("Error finishing flash operation"));
9174 default:
9175 break;
9176 }
9177}
9178
f6ac5f3d
PA
9179void
9180remote_target::files_info ()
c906108c
SS
9181{
9182 puts_filtered ("Debugging a target over a serial line.\n");
9183}
9184\f
9185/* Stuff for dealing with the packets which are part of this protocol.
9186 See comment at top of file for details. */
9187
1927e618
PA
9188/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9189 error to higher layers. Called when a serial error is detected.
9190 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
9191 the system error message for errno at function entry and final dot
9192 for output compatibility with throw_perror_with_name. */
1927e618
PA
9193
9194static void
5b6d1e4f 9195unpush_and_perror (remote_target *target, const char *string)
1927e618 9196{
d6cb50a2 9197 int saved_errno = errno;
1927e618 9198
5b6d1e4f 9199 remote_unpush_target (target);
d6cb50a2
JK
9200 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9201 safe_strerror (saved_errno));
1927e618
PA
9202}
9203
048094ac
PA
9204/* Read a single character from the remote end. The current quit
9205 handler is overridden to avoid quitting in the middle of packet
9206 sequence, as that would break communication with the remote server.
9207 See remote_serial_quit_handler for more detail. */
c906108c 9208
6b8edb51
PA
9209int
9210remote_target::readchar (int timeout)
c906108c
SS
9211{
9212 int ch;
5d93a237 9213 struct remote_state *rs = get_remote_state ();
048094ac 9214
2ec845e7 9215 {
6b8edb51
PA
9216 scoped_restore restore_quit_target
9217 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9218 scoped_restore restore_quit
6b8edb51 9219 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
c906108c 9220
2ec845e7 9221 rs->got_ctrlc_during_io = 0;
c906108c 9222
2ec845e7 9223 ch = serial_readchar (rs->remote_desc, timeout);
048094ac 9224
2ec845e7
TT
9225 if (rs->got_ctrlc_during_io)
9226 set_quit_flag ();
9227 }
048094ac 9228
2acceee2 9229 if (ch >= 0)
0876f84a 9230 return ch;
2acceee2
JM
9231
9232 switch ((enum serial_rc) ch)
c906108c
SS
9233 {
9234 case SERIAL_EOF:
5b6d1e4f 9235 remote_unpush_target (this);
598d3636 9236 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 9237 /* no return */
c906108c 9238 case SERIAL_ERROR:
5b6d1e4f
PA
9239 unpush_and_perror (this, _("Remote communication error. "
9240 "Target disconnected."));
2acceee2 9241 /* no return */
c906108c 9242 case SERIAL_TIMEOUT:
2acceee2 9243 break;
c906108c 9244 }
2acceee2 9245 return ch;
c906108c
SS
9246}
9247
c33e31fd 9248/* Wrapper for serial_write that closes the target and throws if
048094ac
PA
9249 writing fails. The current quit handler is overridden to avoid
9250 quitting in the middle of packet sequence, as that would break
9251 communication with the remote server. See
9252 remote_serial_quit_handler for more detail. */
c33e31fd 9253
6b8edb51
PA
9254void
9255remote_target::remote_serial_write (const char *str, int len)
c33e31fd 9256{
5d93a237 9257 struct remote_state *rs = get_remote_state ();
048094ac 9258
6b8edb51
PA
9259 scoped_restore restore_quit_target
9260 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9261 scoped_restore restore_quit
6b8edb51 9262 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
048094ac
PA
9263
9264 rs->got_ctrlc_during_io = 0;
5d93a237
TT
9265
9266 if (serial_write (rs->remote_desc, str, len))
c33e31fd 9267 {
5b6d1e4f
PA
9268 unpush_and_perror (this, _("Remote communication error. "
9269 "Target disconnected."));
c33e31fd 9270 }
048094ac
PA
9271
9272 if (rs->got_ctrlc_during_io)
9273 set_quit_flag ();
c33e31fd
PA
9274}
9275
b3ced9ba
PA
9276/* Return a string representing an escaped version of BUF, of len N.
9277 E.g. \n is converted to \\n, \t to \\t, etc. */
6e5abd65 9278
b3ced9ba 9279static std::string
6e5abd65
PA
9280escape_buffer (const char *buf, int n)
9281{
d7e74731 9282 string_file stb;
6e5abd65 9283
d7e74731
PA
9284 stb.putstrn (buf, n, '\\');
9285 return std::move (stb.string ());
6e5abd65
PA
9286}
9287
c906108c
SS
9288/* Display a null-terminated packet on stdout, for debugging, using C
9289 string notation. */
9290
9291static void
baa336ce 9292print_packet (const char *buf)
c906108c
SS
9293{
9294 puts_filtered ("\"");
43e526b9 9295 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
9296 puts_filtered ("\"");
9297}
9298
9299int
6b8edb51 9300remote_target::putpkt (const char *buf)
c906108c
SS
9301{
9302 return putpkt_binary (buf, strlen (buf));
9303}
9304
6b8edb51
PA
9305/* Wrapper around remote_target::putpkt to avoid exporting
9306 remote_target. */
9307
9308int
9309putpkt (remote_target *remote, const char *buf)
9310{
9311 return remote->putpkt (buf);
9312}
9313
c906108c 9314/* Send a packet to the remote machine, with error checking. The data
23860348 9315 of the packet is in BUF. The string in BUF can be at most
ea9c271d 9316 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
9317 and for a possible /0 if we are debugging (remote_debug) and want
9318 to print the sent packet as a string. */
c906108c 9319
6b8edb51
PA
9320int
9321remote_target::putpkt_binary (const char *buf, int cnt)
c906108c 9322{
2d717e4f 9323 struct remote_state *rs = get_remote_state ();
c906108c
SS
9324 int i;
9325 unsigned char csum = 0;
b80406ac
TT
9326 gdb::def_vector<char> data (cnt + 6);
9327 char *buf2 = data.data ();
085dd6e6 9328
c906108c
SS
9329 int ch;
9330 int tcount = 0;
9331 char *p;
9332
e24a49d8
PA
9333 /* Catch cases like trying to read memory or listing threads while
9334 we're waiting for a stop reply. The remote server wouldn't be
9335 ready to handle this request, so we'd hang and timeout. We don't
9336 have to worry about this in synchronous mode, because in that
9337 case it's not possible to issue a command while the target is
74531fed
PA
9338 running. This is not a problem in non-stop mode, because in that
9339 case, the stub is always ready to process serial input. */
6efcd9a8
PA
9340 if (!target_is_non_stop_p ()
9341 && target_is_async_p ()
9342 && rs->waiting_for_stop_reply)
9597b22a
DE
9343 {
9344 error (_("Cannot execute this command while the target is running.\n"
9345 "Use the \"interrupt\" command to stop the target\n"
9346 "and then try again."));
9347 }
e24a49d8 9348
2d717e4f
DJ
9349 /* We're sending out a new packet. Make sure we don't look at a
9350 stale cached response. */
9351 rs->cached_wait_status = 0;
9352
c906108c
SS
9353 /* Copy the packet into buffer BUF2, encapsulating it
9354 and giving it a checksum. */
9355
c906108c
SS
9356 p = buf2;
9357 *p++ = '$';
9358
9359 for (i = 0; i < cnt; i++)
9360 {
9361 csum += buf[i];
9362 *p++ = buf[i];
9363 }
9364 *p++ = '#';
9365 *p++ = tohex ((csum >> 4) & 0xf);
9366 *p++ = tohex (csum & 0xf);
9367
9368 /* Send it over and over until we get a positive ack. */
9369
9370 while (1)
9371 {
9372 int started_error_output = 0;
9373
9374 if (remote_debug)
9375 {
9376 *p = '\0';
b3ced9ba 9377
6f8976bf 9378 int len = (int) (p - buf2);
6cc8564b
LM
9379 int max_chars;
9380
9381 if (remote_packet_max_chars < 0)
9382 max_chars = len;
9383 else
9384 max_chars = remote_packet_max_chars;
6f8976bf
YQ
9385
9386 std::string str
6cc8564b 9387 = escape_buffer (buf2, std::min (len, max_chars));
6f8976bf
YQ
9388
9389 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
9390
6cc8564b 9391 if (len > max_chars)
567a3e54 9392 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
6cc8564b 9393 len - max_chars);
6f8976bf
YQ
9394
9395 fprintf_unfiltered (gdb_stdlog, "...");
b3ced9ba 9396
0f71a2f6 9397 gdb_flush (gdb_stdlog);
c906108c 9398 }
c33e31fd 9399 remote_serial_write (buf2, p - buf2);
c906108c 9400
a6f3e723
SL
9401 /* If this is a no acks version of the remote protocol, send the
9402 packet and move on. */
9403 if (rs->noack_mode)
dda83cd7 9404 break;
a6f3e723 9405
74531fed
PA
9406 /* Read until either a timeout occurs (-2) or '+' is read.
9407 Handle any notification that arrives in the mean time. */
c906108c
SS
9408 while (1)
9409 {
9410 ch = readchar (remote_timeout);
9411
c5aa993b 9412 if (remote_debug)
c906108c
SS
9413 {
9414 switch (ch)
9415 {
9416 case '+':
1216fa2c 9417 case '-':
c906108c
SS
9418 case SERIAL_TIMEOUT:
9419 case '$':
74531fed 9420 case '%':
c906108c
SS
9421 if (started_error_output)
9422 {
9423 putchar_unfiltered ('\n');
9424 started_error_output = 0;
9425 }
9426 }
9427 }
9428
9429 switch (ch)
9430 {
9431 case '+':
9432 if (remote_debug)
0f71a2f6 9433 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 9434 return 1;
1216fa2c
AC
9435 case '-':
9436 if (remote_debug)
9437 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 9438 /* FALLTHROUGH */
c906108c 9439 case SERIAL_TIMEOUT:
c5aa993b 9440 tcount++;
c906108c 9441 if (tcount > 3)
b80406ac 9442 return 0;
23860348 9443 break; /* Retransmit buffer. */
c906108c
SS
9444 case '$':
9445 {
dda83cd7 9446 if (remote_debug)
2bc416ba 9447 fprintf_unfiltered (gdb_stdlog,
23860348 9448 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
9449 /* It's probably an old response sent because an ACK
9450 was lost. Gobble up the packet and ack it so it
9451 doesn't get retransmitted when we resend this
9452 packet. */
6d820c5c 9453 skip_frame ();
c33e31fd 9454 remote_serial_write ("+", 1);
23860348 9455 continue; /* Now, go look for +. */
c906108c 9456 }
74531fed
PA
9457
9458 case '%':
9459 {
9460 int val;
9461
9462 /* If we got a notification, handle it, and go back to looking
9463 for an ack. */
9464 /* We've found the start of a notification. Now
9465 collect the data. */
8d64371b 9466 val = read_frame (&rs->buf);
74531fed
PA
9467 if (val >= 0)
9468 {
9469 if (remote_debug)
9470 {
8d64371b 9471 std::string str = escape_buffer (rs->buf.data (), val);
6e5abd65 9472
6e5abd65
PA
9473 fprintf_unfiltered (gdb_stdlog,
9474 " Notification received: %s\n",
b3ced9ba 9475 str.c_str ());
74531fed 9476 }
8d64371b 9477 handle_notification (rs->notif_state, rs->buf.data ());
74531fed
PA
9478 /* We're in sync now, rewait for the ack. */
9479 tcount = 0;
9480 }
9481 else
9482 {
9483 if (remote_debug)
9484 {
9485 if (!started_error_output)
9486 {
9487 started_error_output = 1;
9488 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9489 }
9490 fputc_unfiltered (ch & 0177, gdb_stdlog);
8d64371b 9491 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf.data ());
74531fed
PA
9492 }
9493 }
9494 continue;
9495 }
9496 /* fall-through */
c906108c
SS
9497 default:
9498 if (remote_debug)
9499 {
9500 if (!started_error_output)
9501 {
9502 started_error_output = 1;
0f71a2f6 9503 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 9504 }
0f71a2f6 9505 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
9506 }
9507 continue;
9508 }
23860348 9509 break; /* Here to retransmit. */
c906108c
SS
9510 }
9511
9512#if 0
9513 /* This is wrong. If doing a long backtrace, the user should be
dda83cd7
SM
9514 able to get out next time we call QUIT, without anything as
9515 violent as interrupt_query. If we want to provide a way out of
9516 here without getting to the next QUIT, it should be based on
9517 hitting ^C twice as in remote_wait. */
c906108c
SS
9518 if (quit_flag)
9519 {
9520 quit_flag = 0;
9521 interrupt_query ();
9522 }
9523#endif
9524 }
a5c0808e 9525
a6f3e723 9526 return 0;
c906108c
SS
9527}
9528
6d820c5c
DJ
9529/* Come here after finding the start of a frame when we expected an
9530 ack. Do our best to discard the rest of this packet. */
9531
6b8edb51
PA
9532void
9533remote_target::skip_frame ()
6d820c5c
DJ
9534{
9535 int c;
9536
9537 while (1)
9538 {
9539 c = readchar (remote_timeout);
9540 switch (c)
9541 {
9542 case SERIAL_TIMEOUT:
9543 /* Nothing we can do. */
9544 return;
9545 case '#':
9546 /* Discard the two bytes of checksum and stop. */
9547 c = readchar (remote_timeout);
9548 if (c >= 0)
9549 c = readchar (remote_timeout);
9550
9551 return;
9552 case '*': /* Run length encoding. */
9553 /* Discard the repeat count. */
9554 c = readchar (remote_timeout);
9555 if (c < 0)
9556 return;
9557 break;
9558 default:
9559 /* A regular character. */
9560 break;
9561 }
9562 }
9563}
9564
c906108c 9565/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
9566 into *BUF, verifying the checksum, length, and handling run-length
9567 compression. NUL terminate the buffer. If there is not enough room,
8d64371b 9568 expand *BUF.
c906108c 9569
c2d11a7d
JM
9570 Returns -1 on error, number of characters in buffer (ignoring the
9571 trailing NULL) on success. (could be extended to return one of the
23860348 9572 SERIAL status indications). */
c2d11a7d 9573
6b8edb51 9574long
8d64371b 9575remote_target::read_frame (gdb::char_vector *buf_p)
c906108c
SS
9576{
9577 unsigned char csum;
c2d11a7d 9578 long bc;
c906108c 9579 int c;
8d64371b 9580 char *buf = buf_p->data ();
a6f3e723 9581 struct remote_state *rs = get_remote_state ();
c906108c
SS
9582
9583 csum = 0;
c2d11a7d 9584 bc = 0;
c906108c
SS
9585
9586 while (1)
9587 {
9588 c = readchar (remote_timeout);
c906108c
SS
9589 switch (c)
9590 {
9591 case SERIAL_TIMEOUT:
9592 if (remote_debug)
0f71a2f6 9593 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 9594 return -1;
c906108c
SS
9595 case '$':
9596 if (remote_debug)
0f71a2f6
JM
9597 fputs_filtered ("Saw new packet start in middle of old one\n",
9598 gdb_stdlog);
23860348 9599 return -1; /* Start a new packet, count retries. */
c906108c
SS
9600 case '#':
9601 {
9602 unsigned char pktcsum;
e1b09194
AC
9603 int check_0 = 0;
9604 int check_1 = 0;
c906108c 9605
c2d11a7d 9606 buf[bc] = '\0';
c906108c 9607
e1b09194
AC
9608 check_0 = readchar (remote_timeout);
9609 if (check_0 >= 0)
9610 check_1 = readchar (remote_timeout);
802188a7 9611
e1b09194
AC
9612 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9613 {
9614 if (remote_debug)
2bc416ba 9615 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 9616 gdb_stdlog);
e1b09194
AC
9617 return -1;
9618 }
9619 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
9620 {
9621 if (remote_debug)
2bc416ba 9622 fputs_filtered ("Communication error in checksum\n",
23860348 9623 gdb_stdlog);
40e3f985
FN
9624 return -1;
9625 }
c906108c 9626
a6f3e723
SL
9627 /* Don't recompute the checksum; with no ack packets we
9628 don't have any way to indicate a packet retransmission
9629 is necessary. */
9630 if (rs->noack_mode)
9631 return bc;
9632
e1b09194 9633 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 9634 if (csum == pktcsum)
dda83cd7 9635 return bc;
c906108c 9636
c5aa993b 9637 if (remote_debug)
c906108c 9638 {
b3ced9ba 9639 std::string str = escape_buffer (buf, bc);
6e5abd65 9640
6e5abd65 9641 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
9642 "Bad checksum, sentsum=0x%x, "
9643 "csum=0x%x, buf=%s\n",
b3ced9ba 9644 pktcsum, csum, str.c_str ());
c906108c 9645 }
c2d11a7d 9646 /* Number of characters in buffer ignoring trailing
dda83cd7 9647 NULL. */
c2d11a7d 9648 return -1;
c906108c 9649 }
23860348 9650 case '*': /* Run length encoding. */
dda83cd7 9651 {
c2c6d25f 9652 int repeat;
c906108c 9653
a744cf53 9654 csum += c;
b4501125
AC
9655 c = readchar (remote_timeout);
9656 csum += c;
23860348 9657 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 9658
23860348 9659 /* The character before ``*'' is repeated. */
c2d11a7d 9660
6d820c5c 9661 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 9662 {
8d64371b 9663 if (bc + repeat - 1 >= buf_p->size () - 1)
6d820c5c
DJ
9664 {
9665 /* Make some more room in the buffer. */
8d64371b
TT
9666 buf_p->resize (buf_p->size () + repeat);
9667 buf = buf_p->data ();
6d820c5c
DJ
9668 }
9669
c2d11a7d
JM
9670 memset (&buf[bc], buf[bc - 1], repeat);
9671 bc += repeat;
c2c6d25f
JM
9672 continue;
9673 }
9674
c2d11a7d 9675 buf[bc] = '\0';
6d820c5c 9676 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 9677 return -1;
c2c6d25f 9678 }
c906108c 9679 default:
8d64371b 9680 if (bc >= buf_p->size () - 1)
c906108c 9681 {
6d820c5c 9682 /* Make some more room in the buffer. */
8d64371b
TT
9683 buf_p->resize (buf_p->size () * 2);
9684 buf = buf_p->data ();
c906108c
SS
9685 }
9686
6d820c5c
DJ
9687 buf[bc++] = c;
9688 csum += c;
9689 continue;
c906108c
SS
9690 }
9691 }
9692}
9693
ed2b7c17
TT
9694/* Set this to the maximum number of seconds to wait instead of waiting forever
9695 in target_wait(). If this timer times out, then it generates an error and
9696 the command is aborted. This replaces most of the need for timeouts in the
9697 GDB test suite, and makes it possible to distinguish between a hung target
9698 and one with slow communications. */
9699
9700static int watchdog = 0;
9701static void
9702show_watchdog (struct ui_file *file, int from_tty,
9703 struct cmd_list_element *c, const char *value)
9704{
9705 fprintf_filtered (file, _("Watchdog timer is %s.\n"), value);
9706}
9707
c906108c 9708/* Read a packet from the remote machine, with error checking, and
8d64371b
TT
9709 store it in *BUF. Resize *BUF if necessary to hold the result. If
9710 FOREVER, wait forever rather than timing out; this is used (in
9711 synchronous mode) to wait for a target that is is executing user
9712 code to stop. */
d9fcf2fb
JM
9713/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9714 don't have to change all the calls to getpkt to deal with the
9715 return value, because at the moment I don't know what the right
23860348 9716 thing to do it for those. */
6b8edb51 9717
c906108c 9718void
8d64371b 9719remote_target::getpkt (gdb::char_vector *buf, int forever)
d9fcf2fb 9720{
8d64371b 9721 getpkt_sane (buf, forever);
d9fcf2fb
JM
9722}
9723
9724
9725/* Read a packet from the remote machine, with error checking, and
8d64371b
TT
9726 store it in *BUF. Resize *BUF if necessary to hold the result. If
9727 FOREVER, wait forever rather than timing out; this is used (in
9728 synchronous mode) to wait for a target that is is executing user
9729 code to stop. If FOREVER == 0, this function is allowed to time
9730 out gracefully and return an indication of this to the caller.
9731 Otherwise return the number of bytes read. If EXPECTING_NOTIF,
9732 consider receiving a notification enough reason to return to the
9733 caller. *IS_NOTIF is an output boolean that indicates whether *BUF
9734 holds a notification or not (a regular packet). */
74531fed 9735
6b8edb51 9736int
8d64371b 9737remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
6b8edb51
PA
9738 int forever, int expecting_notif,
9739 int *is_notif)
c906108c 9740{
2d717e4f 9741 struct remote_state *rs = get_remote_state ();
c906108c
SS
9742 int c;
9743 int tries;
9744 int timeout;
df4b58fe 9745 int val = -1;
c906108c 9746
2d717e4f
DJ
9747 /* We're reading a new response. Make sure we don't look at a
9748 previously cached response. */
9749 rs->cached_wait_status = 0;
9750
8d64371b 9751 strcpy (buf->data (), "timeout");
c906108c
SS
9752
9753 if (forever)
74531fed
PA
9754 timeout = watchdog > 0 ? watchdog : -1;
9755 else if (expecting_notif)
9756 timeout = 0; /* There should already be a char in the buffer. If
9757 not, bail out. */
c906108c
SS
9758 else
9759 timeout = remote_timeout;
9760
9761#define MAX_TRIES 3
9762
74531fed
PA
9763 /* Process any number of notifications, and then return when
9764 we get a packet. */
9765 for (;;)
c906108c 9766 {
d9c43928 9767 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
9768 times. */
9769 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 9770 {
74531fed
PA
9771 /* This can loop forever if the remote side sends us
9772 characters continuously, but if it pauses, we'll get
9773 SERIAL_TIMEOUT from readchar because of timeout. Then
9774 we'll count that as a retry.
9775
9776 Note that even when forever is set, we will only wait
9777 forever prior to the start of a packet. After that, we
9778 expect characters to arrive at a brisk pace. They should
9779 show up within remote_timeout intervals. */
9780 do
9781 c = readchar (timeout);
9782 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
9783
9784 if (c == SERIAL_TIMEOUT)
9785 {
74531fed
PA
9786 if (expecting_notif)
9787 return -1; /* Don't complain, it's normal to not get
9788 anything in this case. */
9789
23860348 9790 if (forever) /* Watchdog went off? Kill the target. */
c906108c 9791 {
5b6d1e4f 9792 remote_unpush_target (this);
598d3636
JK
9793 throw_error (TARGET_CLOSE_ERROR,
9794 _("Watchdog timeout has expired. "
9795 "Target detached."));
c906108c 9796 }
c906108c 9797 if (remote_debug)
0f71a2f6 9798 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 9799 }
74531fed
PA
9800 else
9801 {
9802 /* We've found the start of a packet or notification.
9803 Now collect the data. */
8d64371b 9804 val = read_frame (buf);
74531fed
PA
9805 if (val >= 0)
9806 break;
9807 }
9808
c33e31fd 9809 remote_serial_write ("-", 1);
c906108c 9810 }
c906108c 9811
74531fed
PA
9812 if (tries > MAX_TRIES)
9813 {
9814 /* We have tried hard enough, and just can't receive the
9815 packet/notification. Give up. */
9816 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 9817
74531fed
PA
9818 /* Skip the ack char if we're in no-ack mode. */
9819 if (!rs->noack_mode)
c33e31fd 9820 remote_serial_write ("+", 1);
74531fed
PA
9821 return -1;
9822 }
c906108c 9823
74531fed
PA
9824 /* If we got an ordinary packet, return that to our caller. */
9825 if (c == '$')
c906108c
SS
9826 {
9827 if (remote_debug)
43e526b9 9828 {
6cc8564b
LM
9829 int max_chars;
9830
9831 if (remote_packet_max_chars < 0)
9832 max_chars = val;
9833 else
9834 max_chars = remote_packet_max_chars;
9835
6f8976bf 9836 std::string str
8d64371b 9837 = escape_buffer (buf->data (),
6cc8564b 9838 std::min (val, max_chars));
6f8976bf
YQ
9839
9840 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9841 str.c_str ());
9842
6cc8564b 9843 if (val > max_chars)
567a3e54 9844 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
6cc8564b 9845 val - max_chars);
6e5abd65 9846
6f8976bf 9847 fprintf_unfiltered (gdb_stdlog, "\n");
43e526b9 9848 }
a6f3e723
SL
9849
9850 /* Skip the ack char if we're in no-ack mode. */
9851 if (!rs->noack_mode)
c33e31fd 9852 remote_serial_write ("+", 1);
fee9eda9
YQ
9853 if (is_notif != NULL)
9854 *is_notif = 0;
0876f84a 9855 return val;
c906108c
SS
9856 }
9857
74531fed
PA
9858 /* If we got a notification, handle it, and go back to looking
9859 for a packet. */
9860 else
9861 {
9862 gdb_assert (c == '%');
9863
9864 if (remote_debug)
9865 {
8d64371b 9866 std::string str = escape_buffer (buf->data (), val);
6e5abd65 9867
6e5abd65
PA
9868 fprintf_unfiltered (gdb_stdlog,
9869 " Notification received: %s\n",
b3ced9ba 9870 str.c_str ());
74531fed 9871 }
fee9eda9
YQ
9872 if (is_notif != NULL)
9873 *is_notif = 1;
c906108c 9874
8d64371b 9875 handle_notification (rs->notif_state, buf->data ());
c906108c 9876
74531fed 9877 /* Notifications require no acknowledgement. */
a6f3e723 9878
74531fed 9879 if (expecting_notif)
fee9eda9 9880 return val;
74531fed
PA
9881 }
9882 }
9883}
9884
6b8edb51 9885int
8d64371b 9886remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
74531fed 9887{
8d64371b 9888 return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
74531fed
PA
9889}
9890
6b8edb51 9891int
8d64371b 9892remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
6b8edb51 9893 int *is_notif)
74531fed 9894{
8d64371b 9895 return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
c906108c 9896}
74531fed 9897
cbb8991c
DB
9898/* Kill any new fork children of process PID that haven't been
9899 processed by follow_fork. */
9900
6b8edb51
PA
9901void
9902remote_target::kill_new_fork_children (int pid)
cbb8991c 9903{
6b8edb51 9904 remote_state *rs = get_remote_state ();
cbb8991c 9905 struct notif_client *notif = &notif_client_stop;
cbb8991c
DB
9906
9907 /* Kill the fork child threads of any threads in process PID
9908 that are stopped at a fork event. */
5b6d1e4f 9909 for (thread_info *thread : all_non_exited_threads (this))
cbb8991c
DB
9910 {
9911 struct target_waitstatus *ws = &thread->pending_follow;
9912
9913 if (is_pending_fork_parent (ws, pid, thread->ptid))
9914 {
953edf2b 9915 int child_pid = ws->value.related_pid.pid ();
cbb8991c
DB
9916 int res;
9917
6b8edb51 9918 res = remote_vkill (child_pid);
cbb8991c
DB
9919 if (res != 0)
9920 error (_("Can't kill fork child process %d"), child_pid);
9921 }
9922 }
9923
9924 /* Check for any pending fork events (not reported or processed yet)
9925 in process PID and kill those fork child threads as well. */
9926 remote_notif_get_pending_events (notif);
953edf2b
TT
9927 for (auto &event : rs->stop_reply_queue)
9928 if (is_pending_fork_parent (&event->ws, pid, event->ptid))
9929 {
9930 int child_pid = event->ws.value.related_pid.pid ();
9931 int res;
9932
9933 res = remote_vkill (child_pid);
9934 if (res != 0)
9935 error (_("Can't kill fork child process %d"), child_pid);
9936 }
cbb8991c
DB
9937}
9938
c906108c 9939\f
8020350c
DB
9940/* Target hook to kill the current inferior. */
9941
f6ac5f3d
PA
9942void
9943remote_target::kill ()
43ff13b4 9944{
8020350c 9945 int res = -1;
e99b03dc 9946 int pid = inferior_ptid.pid ();
8020350c 9947 struct remote_state *rs = get_remote_state ();
0fdf84ca 9948
8020350c 9949 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 9950 {
8020350c
DB
9951 /* If we're stopped while forking and we haven't followed yet,
9952 kill the child task. We need to do this before killing the
9953 parent task because if this is a vfork then the parent will
9954 be sleeping. */
6b8edb51 9955 kill_new_fork_children (pid);
8020350c 9956
6b8edb51 9957 res = remote_vkill (pid);
8020350c 9958 if (res == 0)
0fdf84ca 9959 {
bc1e6c81 9960 target_mourn_inferior (inferior_ptid);
0fdf84ca
PA
9961 return;
9962 }
8020350c 9963 }
0fdf84ca 9964
8020350c
DB
9965 /* If we are in 'target remote' mode and we are killing the only
9966 inferior, then we will tell gdbserver to exit and unpush the
9967 target. */
9968 if (res == -1 && !remote_multi_process_p (rs)
5b6d1e4f 9969 && number_of_live_inferiors (this) == 1)
8020350c
DB
9970 {
9971 remote_kill_k ();
9972
9973 /* We've killed the remote end, we get to mourn it. If we are
9974 not in extended mode, mourning the inferior also unpushes
9975 remote_ops from the target stack, which closes the remote
9976 connection. */
bc1e6c81 9977 target_mourn_inferior (inferior_ptid);
8020350c
DB
9978
9979 return;
0fdf84ca 9980 }
43ff13b4 9981
8020350c 9982 error (_("Can't kill process"));
43ff13b4
JM
9983}
9984
8020350c
DB
9985/* Send a kill request to the target using the 'vKill' packet. */
9986
6b8edb51
PA
9987int
9988remote_target::remote_vkill (int pid)
82f73884 9989{
4082afcc 9990 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
9991 return -1;
9992
6b8edb51
PA
9993 remote_state *rs = get_remote_state ();
9994
82f73884 9995 /* Tell the remote target to detach. */
8d64371b 9996 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
82f73884 9997 putpkt (rs->buf);
8d64371b 9998 getpkt (&rs->buf, 0);
82f73884 9999
4082afcc
PA
10000 switch (packet_ok (rs->buf,
10001 &remote_protocol_packets[PACKET_vKill]))
10002 {
10003 case PACKET_OK:
10004 return 0;
10005 case PACKET_ERROR:
10006 return 1;
10007 case PACKET_UNKNOWN:
10008 return -1;
10009 default:
10010 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
10011 }
82f73884
PA
10012}
10013
8020350c
DB
10014/* Send a kill request to the target using the 'k' packet. */
10015
6b8edb51
PA
10016void
10017remote_target::remote_kill_k ()
82f73884 10018{
8020350c
DB
10019 /* Catch errors so the user can quit from gdb even when we
10020 aren't on speaking terms with the remote system. */
a70b8144 10021 try
82f73884 10022 {
82f73884 10023 putpkt ("k");
82f73884 10024 }
230d2906 10025 catch (const gdb_exception_error &ex)
8020350c
DB
10026 {
10027 if (ex.error == TARGET_CLOSE_ERROR)
10028 {
10029 /* If we got an (EOF) error that caused the target
10030 to go away, then we're done, that's what we wanted.
10031 "k" is susceptible to cause a premature EOF, given
10032 that the remote server isn't actually required to
10033 reply to "k", and it can happen that it doesn't
10034 even get to reply ACK to the "k". */
10035 return;
10036 }
82f73884 10037
8020350c
DB
10038 /* Otherwise, something went wrong. We didn't actually kill
10039 the target. Just propagate the exception, and let the
10040 user or higher layers decide what to do. */
eedc3f4f 10041 throw;
8020350c 10042 }
82f73884
PA
10043}
10044
f6ac5f3d
PA
10045void
10046remote_target::mourn_inferior ()
c906108c 10047{
8020350c 10048 struct remote_state *rs = get_remote_state ();
ce5ce7ed 10049
9607784a
PA
10050 /* We're no longer interested in notification events of an inferior
10051 that exited or was killed/detached. */
10052 discard_pending_stop_replies (current_inferior ());
10053
8020350c 10054 /* In 'target remote' mode with one inferior, we close the connection. */
5b6d1e4f 10055 if (!rs->extended && number_of_live_inferiors (this) <= 1)
8020350c 10056 {
5b6d1e4f 10057 remote_unpush_target (this);
8020350c
DB
10058 return;
10059 }
c906108c 10060
e24a49d8
PA
10061 /* In case we got here due to an error, but we're going to stay
10062 connected. */
10063 rs->waiting_for_stop_reply = 0;
10064
dc1981d7
PA
10065 /* If the current general thread belonged to the process we just
10066 detached from or has exited, the remote side current general
10067 thread becomes undefined. Considering a case like this:
10068
10069 - We just got here due to a detach.
10070 - The process that we're detaching from happens to immediately
10071 report a global breakpoint being hit in non-stop mode, in the
10072 same thread we had selected before.
10073 - GDB attaches to this process again.
10074 - This event happens to be the next event we handle.
10075
10076 GDB would consider that the current general thread didn't need to
10077 be set on the stub side (with Hg), since for all it knew,
10078 GENERAL_THREAD hadn't changed.
10079
10080 Notice that although in all-stop mode, the remote server always
10081 sets the current thread to the thread reporting the stop event,
10082 that doesn't happen in non-stop mode; in non-stop, the stub *must
10083 not* change the current thread when reporting a breakpoint hit,
10084 due to the decoupling of event reporting and event handling.
10085
10086 To keep things simple, we always invalidate our notion of the
10087 current thread. */
47f8a51d 10088 record_currthread (rs, minus_one_ptid);
dc1981d7 10089
8020350c 10090 /* Call common code to mark the inferior as not running. */
48aa3c27 10091 generic_mourn_inferior ();
2d717e4f 10092}
c906108c 10093
57810aa7 10094bool
f6ac5f3d 10095extended_remote_target::supports_disable_randomization ()
03583c20 10096{
4082afcc 10097 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
10098}
10099
6b8edb51
PA
10100void
10101remote_target::extended_remote_disable_randomization (int val)
03583c20
UW
10102{
10103 struct remote_state *rs = get_remote_state ();
10104 char *reply;
10105
8d64371b
TT
10106 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10107 "QDisableRandomization:%x", val);
03583c20 10108 putpkt (rs->buf);
b6bb3468 10109 reply = remote_get_noisy_reply ();
03583c20
UW
10110 if (*reply == '\0')
10111 error (_("Target does not support QDisableRandomization."));
10112 if (strcmp (reply, "OK") != 0)
10113 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10114}
10115
6b8edb51
PA
10116int
10117remote_target::extended_remote_run (const std::string &args)
2d717e4f
DJ
10118{
10119 struct remote_state *rs = get_remote_state ();
2d717e4f 10120 int len;
94585166 10121 const char *remote_exec_file = get_remote_exec_file ();
c906108c 10122
2d717e4f
DJ
10123 /* If the user has disabled vRun support, or we have detected that
10124 support is not available, do not try it. */
4082afcc 10125 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 10126 return -1;
424163ea 10127
8d64371b
TT
10128 strcpy (rs->buf.data (), "vRun;");
10129 len = strlen (rs->buf.data ());
c906108c 10130
2d717e4f
DJ
10131 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10132 error (_("Remote file name too long for run packet"));
8d64371b 10133 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
9f1b45b0 10134 strlen (remote_exec_file));
2d717e4f 10135
7c5ded6a 10136 if (!args.empty ())
2d717e4f 10137 {
2d717e4f 10138 int i;
2d717e4f 10139
773a1edc 10140 gdb_argv argv (args.c_str ());
2d717e4f
DJ
10141 for (i = 0; argv[i] != NULL; i++)
10142 {
10143 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10144 error (_("Argument list too long for run packet"));
10145 rs->buf[len++] = ';';
8d64371b 10146 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
9f1b45b0 10147 strlen (argv[i]));
2d717e4f 10148 }
2d717e4f
DJ
10149 }
10150
10151 rs->buf[len++] = '\0';
10152
10153 putpkt (rs->buf);
8d64371b 10154 getpkt (&rs->buf, 0);
2d717e4f 10155
4082afcc 10156 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 10157 {
4082afcc 10158 case PACKET_OK:
3405876a 10159 /* We have a wait response. All is well. */
2d717e4f 10160 return 0;
4082afcc
PA
10161 case PACKET_UNKNOWN:
10162 return -1;
10163 case PACKET_ERROR:
2d717e4f
DJ
10164 if (remote_exec_file[0] == '\0')
10165 error (_("Running the default executable on the remote target failed; "
10166 "try \"set remote exec-file\"?"));
10167 else
10168 error (_("Running \"%s\" on the remote target failed"),
10169 remote_exec_file);
4082afcc
PA
10170 default:
10171 gdb_assert_not_reached (_("bad switch"));
2d717e4f 10172 }
c906108c
SS
10173}
10174
0a2dde4a
SDJ
10175/* Helper function to send set/unset environment packets. ACTION is
10176 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10177 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10178 sent. */
10179
6b8edb51
PA
10180void
10181remote_target::send_environment_packet (const char *action,
10182 const char *packet,
10183 const char *value)
0a2dde4a 10184{
6b8edb51
PA
10185 remote_state *rs = get_remote_state ();
10186
0a2dde4a
SDJ
10187 /* Convert the environment variable to an hex string, which
10188 is the best format to be transmitted over the wire. */
10189 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10190 strlen (value));
10191
8d64371b 10192 xsnprintf (rs->buf.data (), get_remote_packet_size (),
0a2dde4a
SDJ
10193 "%s:%s", packet, encoded_value.c_str ());
10194
10195 putpkt (rs->buf);
8d64371b
TT
10196 getpkt (&rs->buf, 0);
10197 if (strcmp (rs->buf.data (), "OK") != 0)
0a2dde4a
SDJ
10198 warning (_("Unable to %s environment variable '%s' on remote."),
10199 action, value);
10200}
10201
10202/* Helper function to handle the QEnvironment* packets. */
10203
6b8edb51
PA
10204void
10205remote_target::extended_remote_environment_support ()
0a2dde4a 10206{
6b8edb51
PA
10207 remote_state *rs = get_remote_state ();
10208
0a2dde4a
SDJ
10209 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10210 {
10211 putpkt ("QEnvironmentReset");
8d64371b
TT
10212 getpkt (&rs->buf, 0);
10213 if (strcmp (rs->buf.data (), "OK") != 0)
0a2dde4a
SDJ
10214 warning (_("Unable to reset environment on remote."));
10215 }
10216
10217 gdb_environ *e = &current_inferior ()->environment;
10218
10219 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10220 for (const std::string &el : e->user_set_env ())
6b8edb51 10221 send_environment_packet ("set", "QEnvironmentHexEncoded",
0a2dde4a
SDJ
10222 el.c_str ());
10223
10224 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10225 for (const std::string &el : e->user_unset_env ())
6b8edb51 10226 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
0a2dde4a
SDJ
10227}
10228
bc3b087d
SDJ
10229/* Helper function to set the current working directory for the
10230 inferior in the remote target. */
10231
6b8edb51
PA
10232void
10233remote_target::extended_remote_set_inferior_cwd ()
bc3b087d
SDJ
10234{
10235 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10236 {
10237 const char *inferior_cwd = get_inferior_cwd ();
6b8edb51 10238 remote_state *rs = get_remote_state ();
bc3b087d
SDJ
10239
10240 if (inferior_cwd != NULL)
10241 {
10242 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
10243 strlen (inferior_cwd));
10244
8d64371b 10245 xsnprintf (rs->buf.data (), get_remote_packet_size (),
bc3b087d
SDJ
10246 "QSetWorkingDir:%s", hexpath.c_str ());
10247 }
10248 else
10249 {
10250 /* An empty inferior_cwd means that the user wants us to
10251 reset the remote server's inferior's cwd. */
8d64371b 10252 xsnprintf (rs->buf.data (), get_remote_packet_size (),
bc3b087d
SDJ
10253 "QSetWorkingDir:");
10254 }
10255
10256 putpkt (rs->buf);
8d64371b 10257 getpkt (&rs->buf, 0);
bc3b087d
SDJ
10258 if (packet_ok (rs->buf,
10259 &remote_protocol_packets[PACKET_QSetWorkingDir])
10260 != PACKET_OK)
10261 error (_("\
10262Remote replied unexpectedly while setting the inferior's working\n\
10263directory: %s"),
8d64371b 10264 rs->buf.data ());
bc3b087d
SDJ
10265
10266 }
10267}
10268
2d717e4f
DJ
10269/* In the extended protocol we want to be able to do things like
10270 "run" and have them basically work as expected. So we need
10271 a special create_inferior function. We support changing the
10272 executable file and the command line arguments, but not the
10273 environment. */
10274
f6ac5f3d
PA
10275void
10276extended_remote_target::create_inferior (const char *exec_file,
10277 const std::string &args,
10278 char **env, int from_tty)
43ff13b4 10279{
3405876a
PA
10280 int run_worked;
10281 char *stop_reply;
10282 struct remote_state *rs = get_remote_state ();
94585166 10283 const char *remote_exec_file = get_remote_exec_file ();
3405876a 10284
43ff13b4 10285 /* If running asynchronously, register the target file descriptor
23860348 10286 with the event loop. */
75c99385 10287 if (target_can_async_p ())
6a3753b3 10288 target_async (1);
43ff13b4 10289
03583c20 10290 /* Disable address space randomization if requested (and supported). */
f6ac5f3d 10291 if (supports_disable_randomization ())
03583c20
UW
10292 extended_remote_disable_randomization (disable_randomization);
10293
aefd8b33
SDJ
10294 /* If startup-with-shell is on, we inform gdbserver to start the
10295 remote inferior using a shell. */
10296 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10297 {
8d64371b 10298 xsnprintf (rs->buf.data (), get_remote_packet_size (),
aefd8b33
SDJ
10299 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10300 putpkt (rs->buf);
8d64371b
TT
10301 getpkt (&rs->buf, 0);
10302 if (strcmp (rs->buf.data (), "OK") != 0)
aefd8b33
SDJ
10303 error (_("\
10304Remote replied unexpectedly while setting startup-with-shell: %s"),
8d64371b 10305 rs->buf.data ());
aefd8b33
SDJ
10306 }
10307
6b8edb51 10308 extended_remote_environment_support ();
0a2dde4a 10309
6b8edb51 10310 extended_remote_set_inferior_cwd ();
bc3b087d 10311
43ff13b4 10312 /* Now restart the remote server. */
3405876a
PA
10313 run_worked = extended_remote_run (args) != -1;
10314 if (!run_worked)
2d717e4f
DJ
10315 {
10316 /* vRun was not supported. Fail if we need it to do what the
10317 user requested. */
10318 if (remote_exec_file[0])
10319 error (_("Remote target does not support \"set remote exec-file\""));
7c5ded6a 10320 if (!args.empty ())
65e65158 10321 error (_("Remote target does not support \"set args\" or run ARGS"));
43ff13b4 10322
2d717e4f
DJ
10323 /* Fall back to "R". */
10324 extended_remote_restart ();
10325 }
424163ea 10326
3405876a 10327 /* vRun's success return is a stop reply. */
8d64371b 10328 stop_reply = run_worked ? rs->buf.data () : NULL;
3405876a 10329 add_current_inferior_and_thread (stop_reply);
c0a2216e 10330
2d717e4f
DJ
10331 /* Get updated offsets, if the stub uses qOffsets. */
10332 get_offsets ();
2d717e4f 10333}
c906108c 10334\f
c5aa993b 10335
b775012e
LM
10336/* Given a location's target info BP_TGT and the packet buffer BUF, output
10337 the list of conditions (in agent expression bytecode format), if any, the
10338 target needs to evaluate. The output is placed into the packet buffer
bba74b36 10339 started from BUF and ended at BUF_END. */
b775012e
LM
10340
10341static int
10342remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
10343 struct bp_target_info *bp_tgt, char *buf,
10344 char *buf_end)
b775012e 10345{
3cde5c42 10346 if (bp_tgt->conditions.empty ())
b775012e
LM
10347 return 0;
10348
10349 buf += strlen (buf);
bba74b36 10350 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
10351 buf++;
10352
83621223 10353 /* Send conditions to the target. */
d538e36d 10354 for (agent_expr *aexpr : bp_tgt->conditions)
b775012e 10355 {
bba74b36 10356 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e 10357 buf += strlen (buf);
3cde5c42 10358 for (int i = 0; i < aexpr->len; ++i)
b775012e
LM
10359 buf = pack_hex_byte (buf, aexpr->buf[i]);
10360 *buf = '\0';
10361 }
b775012e
LM
10362 return 0;
10363}
10364
d3ce09f5
SS
10365static void
10366remote_add_target_side_commands (struct gdbarch *gdbarch,
10367 struct bp_target_info *bp_tgt, char *buf)
10368{
3cde5c42 10369 if (bp_tgt->tcommands.empty ())
d3ce09f5
SS
10370 return;
10371
10372 buf += strlen (buf);
10373
10374 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10375 buf += strlen (buf);
10376
10377 /* Concatenate all the agent expressions that are commands into the
10378 cmds parameter. */
df97be55 10379 for (agent_expr *aexpr : bp_tgt->tcommands)
d3ce09f5
SS
10380 {
10381 sprintf (buf, "X%x,", aexpr->len);
10382 buf += strlen (buf);
3cde5c42 10383 for (int i = 0; i < aexpr->len; ++i)
d3ce09f5
SS
10384 buf = pack_hex_byte (buf, aexpr->buf[i]);
10385 *buf = '\0';
10386 }
d3ce09f5
SS
10387}
10388
8181d85f
DJ
10389/* Insert a breakpoint. On targets that have software breakpoint
10390 support, we ask the remote target to do the work; on targets
10391 which don't, we insert a traditional memory breakpoint. */
c906108c 10392
f6ac5f3d
PA
10393int
10394remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10395 struct bp_target_info *bp_tgt)
c906108c 10396{
d471ea57
AC
10397 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10398 If it succeeds, then set the support to PACKET_ENABLE. If it
10399 fails, and the user has explicitly requested the Z support then
23860348 10400 report an error, otherwise, mark it disabled and go on. */
802188a7 10401
4082afcc 10402 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10403 {
0d5ed153 10404 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10405 struct remote_state *rs;
bba74b36 10406 char *p, *endbuf;
4fff2411 10407
28439a30
PA
10408 /* Make sure the remote is pointing at the right process, if
10409 necessary. */
10410 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10411 set_general_process ();
10412
4fff2411 10413 rs = get_remote_state ();
8d64371b
TT
10414 p = rs->buf.data ();
10415 endbuf = p + get_remote_packet_size ();
802188a7 10416
96baa820
JM
10417 *(p++) = 'Z';
10418 *(p++) = '0';
10419 *(p++) = ',';
7c0f6dcc 10420 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 10421 p += hexnumstr (p, addr);
579c6ad9 10422 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10423
f6ac5f3d 10424 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10425 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10426
f6ac5f3d 10427 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10428 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10429
6d820c5c 10430 putpkt (rs->buf);
8d64371b 10431 getpkt (&rs->buf, 0);
96baa820 10432
6d820c5c 10433 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 10434 {
d471ea57
AC
10435 case PACKET_ERROR:
10436 return -1;
10437 case PACKET_OK:
10438 return 0;
10439 case PACKET_UNKNOWN:
10440 break;
96baa820
JM
10441 }
10442 }
c906108c 10443
0000e5cc
PA
10444 /* If this breakpoint has target-side commands but this stub doesn't
10445 support Z0 packets, throw error. */
3cde5c42 10446 if (!bp_tgt->tcommands.empty ())
0000e5cc
PA
10447 throw_error (NOT_SUPPORTED_ERROR, _("\
10448Target doesn't support breakpoints that have target side commands."));
10449
f6ac5f3d 10450 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
c906108c
SS
10451}
10452
f6ac5f3d
PA
10453int
10454remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10455 struct bp_target_info *bp_tgt,
10456 enum remove_bp_reason reason)
c906108c 10457{
8181d85f 10458 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 10459 struct remote_state *rs = get_remote_state ();
96baa820 10460
4082afcc 10461 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10462 {
8d64371b
TT
10463 char *p = rs->buf.data ();
10464 char *endbuf = p + get_remote_packet_size ();
802188a7 10465
28439a30
PA
10466 /* Make sure the remote is pointing at the right process, if
10467 necessary. */
10468 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10469 set_general_process ();
10470
96baa820
JM
10471 *(p++) = 'z';
10472 *(p++) = '0';
10473 *(p++) = ',';
10474
8181d85f
DJ
10475 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10476 p += hexnumstr (p, addr);
579c6ad9 10477 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10478
6d820c5c 10479 putpkt (rs->buf);
8d64371b 10480 getpkt (&rs->buf, 0);
96baa820 10481
6d820c5c 10482 return (rs->buf[0] == 'E');
96baa820
JM
10483 }
10484
f6ac5f3d 10485 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
c906108c
SS
10486}
10487
f486487f 10488static enum Z_packet_type
d471ea57
AC
10489watchpoint_to_Z_packet (int type)
10490{
10491 switch (type)
10492 {
10493 case hw_write:
bb858e6a 10494 return Z_PACKET_WRITE_WP;
d471ea57
AC
10495 break;
10496 case hw_read:
bb858e6a 10497 return Z_PACKET_READ_WP;
d471ea57
AC
10498 break;
10499 case hw_access:
bb858e6a 10500 return Z_PACKET_ACCESS_WP;
d471ea57
AC
10501 break;
10502 default:
8e65ff28 10503 internal_error (__FILE__, __LINE__,
e2e0b3e5 10504 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
10505 }
10506}
10507
f6ac5f3d
PA
10508int
10509remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10510 enum target_hw_bp_type type, struct expression *cond)
96baa820 10511{
d01949b6 10512 struct remote_state *rs = get_remote_state ();
8d64371b 10513 char *endbuf = rs->buf.data () + get_remote_packet_size ();
e514a9d6 10514 char *p;
d471ea57 10515 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 10516
4082afcc 10517 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 10518 return 1;
802188a7 10519
28439a30
PA
10520 /* Make sure the remote is pointing at the right process, if
10521 necessary. */
10522 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10523 set_general_process ();
10524
8d64371b
TT
10525 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10526 p = strchr (rs->buf.data (), '\0');
96baa820
JM
10527 addr = remote_address_masked (addr);
10528 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10529 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 10530
6d820c5c 10531 putpkt (rs->buf);
8d64371b 10532 getpkt (&rs->buf, 0);
96baa820 10533
6d820c5c 10534 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10535 {
10536 case PACKET_ERROR:
d471ea57 10537 return -1;
85d721b8
PA
10538 case PACKET_UNKNOWN:
10539 return 1;
d471ea57
AC
10540 case PACKET_OK:
10541 return 0;
10542 }
8e65ff28 10543 internal_error (__FILE__, __LINE__,
e2e0b3e5 10544 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
10545}
10546
57810aa7 10547bool
f6ac5f3d
PA
10548remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10549 CORE_ADDR start, int length)
283002cf
MR
10550{
10551 CORE_ADDR diff = remote_address_masked (addr - start);
10552
10553 return diff < length;
10554}
10555
d471ea57 10556
f6ac5f3d
PA
10557int
10558remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10559 enum target_hw_bp_type type, struct expression *cond)
96baa820 10560{
d01949b6 10561 struct remote_state *rs = get_remote_state ();
8d64371b 10562 char *endbuf = rs->buf.data () + get_remote_packet_size ();
e514a9d6 10563 char *p;
d471ea57
AC
10564 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10565
4082afcc 10566 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 10567 return -1;
802188a7 10568
28439a30
PA
10569 /* Make sure the remote is pointing at the right process, if
10570 necessary. */
10571 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10572 set_general_process ();
10573
8d64371b
TT
10574 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10575 p = strchr (rs->buf.data (), '\0');
96baa820
JM
10576 addr = remote_address_masked (addr);
10577 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10578 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c 10579 putpkt (rs->buf);
8d64371b 10580 getpkt (&rs->buf, 0);
96baa820 10581
6d820c5c 10582 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10583 {
10584 case PACKET_ERROR:
10585 case PACKET_UNKNOWN:
10586 return -1;
10587 case PACKET_OK:
10588 return 0;
10589 }
8e65ff28 10590 internal_error (__FILE__, __LINE__,
e2e0b3e5 10591 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
10592}
10593
3c3bea1c 10594
60fcc1c3
TT
10595static int remote_hw_watchpoint_limit = -1;
10596static int remote_hw_watchpoint_length_limit = -1;
10597static int remote_hw_breakpoint_limit = -1;
d471ea57 10598
f6ac5f3d
PA
10599int
10600remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
480a3f21
PW
10601{
10602 if (remote_hw_watchpoint_length_limit == 0)
10603 return 0;
10604 else if (remote_hw_watchpoint_length_limit < 0)
10605 return 1;
10606 else if (len <= remote_hw_watchpoint_length_limit)
10607 return 1;
10608 else
10609 return 0;
10610}
10611
f6ac5f3d
PA
10612int
10613remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
96baa820 10614{
3c3bea1c
GS
10615 if (type == bp_hardware_breakpoint)
10616 {
10617 if (remote_hw_breakpoint_limit == 0)
10618 return 0;
501eef12
AC
10619 else if (remote_hw_breakpoint_limit < 0)
10620 return 1;
3c3bea1c
GS
10621 else if (cnt <= remote_hw_breakpoint_limit)
10622 return 1;
10623 }
10624 else
10625 {
10626 if (remote_hw_watchpoint_limit == 0)
10627 return 0;
501eef12
AC
10628 else if (remote_hw_watchpoint_limit < 0)
10629 return 1;
3c3bea1c
GS
10630 else if (ot)
10631 return -1;
10632 else if (cnt <= remote_hw_watchpoint_limit)
10633 return 1;
10634 }
10635 return -1;
10636}
10637
f7e6eed5
PA
10638/* The to_stopped_by_sw_breakpoint method of target remote. */
10639
57810aa7 10640bool
f6ac5f3d 10641remote_target::stopped_by_sw_breakpoint ()
f7e6eed5 10642{
799a2abe 10643 struct thread_info *thread = inferior_thread ();
f7e6eed5 10644
799a2abe 10645 return (thread->priv != NULL
7aabaf9d
SM
10646 && (get_remote_thread_info (thread)->stop_reason
10647 == TARGET_STOPPED_BY_SW_BREAKPOINT));
f7e6eed5
PA
10648}
10649
10650/* The to_supports_stopped_by_sw_breakpoint method of target
10651 remote. */
10652
57810aa7 10653bool
f6ac5f3d 10654remote_target::supports_stopped_by_sw_breakpoint ()
f7e6eed5 10655{
f7e6eed5
PA
10656 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10657}
10658
10659/* The to_stopped_by_hw_breakpoint method of target remote. */
10660
57810aa7 10661bool
f6ac5f3d 10662remote_target::stopped_by_hw_breakpoint ()
f7e6eed5 10663{
799a2abe 10664 struct thread_info *thread = inferior_thread ();
f7e6eed5 10665
799a2abe 10666 return (thread->priv != NULL
7aabaf9d
SM
10667 && (get_remote_thread_info (thread)->stop_reason
10668 == TARGET_STOPPED_BY_HW_BREAKPOINT));
f7e6eed5
PA
10669}
10670
10671/* The to_supports_stopped_by_hw_breakpoint method of target
10672 remote. */
10673
57810aa7 10674bool
f6ac5f3d 10675remote_target::supports_stopped_by_hw_breakpoint ()
f7e6eed5 10676{
f7e6eed5
PA
10677 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10678}
10679
57810aa7 10680bool
f6ac5f3d 10681remote_target::stopped_by_watchpoint ()
3c3bea1c 10682{
799a2abe 10683 struct thread_info *thread = inferior_thread ();
ee154bee 10684
799a2abe 10685 return (thread->priv != NULL
7aabaf9d
SM
10686 && (get_remote_thread_info (thread)->stop_reason
10687 == TARGET_STOPPED_BY_WATCHPOINT));
3c3bea1c
GS
10688}
10689
57810aa7 10690bool
f6ac5f3d 10691remote_target::stopped_data_address (CORE_ADDR *addr_p)
3c3bea1c 10692{
799a2abe 10693 struct thread_info *thread = inferior_thread ();
a744cf53 10694
799a2abe 10695 if (thread->priv != NULL
7aabaf9d
SM
10696 && (get_remote_thread_info (thread)->stop_reason
10697 == TARGET_STOPPED_BY_WATCHPOINT))
4aa7a7f5 10698 {
7aabaf9d 10699 *addr_p = get_remote_thread_info (thread)->watch_data_address;
57810aa7 10700 return true;
4aa7a7f5
JJ
10701 }
10702
57810aa7 10703 return false;
3c3bea1c
GS
10704}
10705
10706
f6ac5f3d
PA
10707int
10708remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10709 struct bp_target_info *bp_tgt)
3c3bea1c 10710{
0d5ed153 10711 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10712 struct remote_state *rs;
bba74b36 10713 char *p, *endbuf;
dd61ec5c 10714 char *message;
3c3bea1c 10715
4082afcc 10716 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10717 return -1;
2bc416ba 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
4fff2411 10724 rs = get_remote_state ();
8d64371b
TT
10725 p = rs->buf.data ();
10726 endbuf = p + get_remote_packet_size ();
4fff2411 10727
96baa820
JM
10728 *(p++) = 'Z';
10729 *(p++) = '1';
10730 *(p++) = ',';
802188a7 10731
0d5ed153 10732 addr = remote_address_masked (addr);
96baa820 10733 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10734 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10735
f6ac5f3d 10736 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10737 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10738
f6ac5f3d 10739 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10740 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10741
6d820c5c 10742 putpkt (rs->buf);
8d64371b 10743 getpkt (&rs->buf, 0);
96baa820 10744
6d820c5c 10745 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10746 {
10747 case PACKET_ERROR:
dd61ec5c 10748 if (rs->buf[1] == '.')
dda83cd7
SM
10749 {
10750 message = strchr (&rs->buf[2], '.');
10751 if (message)
10752 error (_("Remote failure reply: %s"), message + 1);
10753 }
dd61ec5c 10754 return -1;
d471ea57
AC
10755 case PACKET_UNKNOWN:
10756 return -1;
10757 case PACKET_OK:
10758 return 0;
10759 }
8e65ff28 10760 internal_error (__FILE__, __LINE__,
e2e0b3e5 10761 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
10762}
10763
d471ea57 10764
f6ac5f3d
PA
10765int
10766remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10767 struct bp_target_info *bp_tgt)
96baa820 10768{
8181d85f 10769 CORE_ADDR addr;
d01949b6 10770 struct remote_state *rs = get_remote_state ();
8d64371b
TT
10771 char *p = rs->buf.data ();
10772 char *endbuf = p + get_remote_packet_size ();
c8189ed1 10773
4082afcc 10774 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10775 return -1;
802188a7 10776
28439a30
PA
10777 /* Make sure the remote is pointing at the right process, if
10778 necessary. */
10779 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10780 set_general_process ();
10781
96baa820
JM
10782 *(p++) = 'z';
10783 *(p++) = '1';
10784 *(p++) = ',';
802188a7 10785
8181d85f 10786 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 10787 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10788 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10789
6d820c5c 10790 putpkt (rs->buf);
8d64371b 10791 getpkt (&rs->buf, 0);
802188a7 10792
6d820c5c 10793 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10794 {
10795 case PACKET_ERROR:
10796 case PACKET_UNKNOWN:
10797 return -1;
10798 case PACKET_OK:
10799 return 0;
10800 }
8e65ff28 10801 internal_error (__FILE__, __LINE__,
e2e0b3e5 10802 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 10803}
96baa820 10804
4a5e7a5b
PA
10805/* Verify memory using the "qCRC:" request. */
10806
f6ac5f3d
PA
10807int
10808remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
4a5e7a5b
PA
10809{
10810 struct remote_state *rs = get_remote_state ();
10811 unsigned long host_crc, target_crc;
10812 char *tmp;
10813
936d2992
PA
10814 /* It doesn't make sense to use qCRC if the remote target is
10815 connected but not running. */
55f6301a
TT
10816 if (target_has_execution ()
10817 && packet_support (PACKET_qCRC) != PACKET_DISABLE)
936d2992
PA
10818 {
10819 enum packet_result result;
28439a30 10820
936d2992
PA
10821 /* Make sure the remote is pointing at the right process. */
10822 set_general_process ();
4a5e7a5b 10823
936d2992 10824 /* FIXME: assumes lma can fit into long. */
8d64371b 10825 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
936d2992
PA
10826 (long) lma, (long) size);
10827 putpkt (rs->buf);
4a5e7a5b 10828
936d2992
PA
10829 /* Be clever; compute the host_crc before waiting for target
10830 reply. */
10831 host_crc = xcrc32 (data, size, 0xffffffff);
10832
8d64371b 10833 getpkt (&rs->buf, 0);
4a5e7a5b 10834
936d2992
PA
10835 result = packet_ok (rs->buf,
10836 &remote_protocol_packets[PACKET_qCRC]);
10837 if (result == PACKET_ERROR)
10838 return -1;
10839 else if (result == PACKET_OK)
10840 {
10841 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10842 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 10843
936d2992
PA
10844 return (host_crc == target_crc);
10845 }
10846 }
4a5e7a5b 10847
f6ac5f3d 10848 return simple_verify_memory (this, data, lma, size);
4a5e7a5b
PA
10849}
10850
c906108c
SS
10851/* compare-sections command
10852
10853 With no arguments, compares each loadable section in the exec bfd
10854 with the same memory range on the target, and reports mismatches.
4a5e7a5b 10855 Useful for verifying the image on the target against the exec file. */
e514a9d6 10856
c906108c 10857static void
ac88e2de 10858compare_sections_command (const char *args, int from_tty)
c906108c
SS
10859{
10860 asection *s;
ce359b09 10861 const char *sectname;
c906108c
SS
10862 bfd_size_type size;
10863 bfd_vma lma;
10864 int matched = 0;
10865 int mismatched = 0;
4a5e7a5b 10866 int res;
95cf3b38 10867 int read_only = 0;
c906108c 10868
7e10abd1 10869 if (!current_program_space->exec_bfd ())
8a3fe4f8 10870 error (_("command cannot be used without an exec file"));
c906108c 10871
95cf3b38
DT
10872 if (args != NULL && strcmp (args, "-r") == 0)
10873 {
10874 read_only = 1;
10875 args = NULL;
10876 }
10877
7e10abd1 10878 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
c906108c
SS
10879 {
10880 if (!(s->flags & SEC_LOAD))
0df8b418 10881 continue; /* Skip non-loadable section. */
c906108c 10882
95cf3b38
DT
10883 if (read_only && (s->flags & SEC_READONLY) == 0)
10884 continue; /* Skip writeable sections */
10885
fd361982 10886 size = bfd_section_size (s);
c906108c 10887 if (size == 0)
0df8b418 10888 continue; /* Skip zero-length section. */
c906108c 10889
fd361982 10890 sectname = bfd_section_name (s);
c906108c 10891 if (args && strcmp (args, sectname) != 0)
0df8b418 10892 continue; /* Not the section selected by user. */
c906108c 10893
0df8b418 10894 matched = 1; /* Do this section. */
c906108c 10895 lma = s->lma;
c906108c 10896
b80406ac 10897 gdb::byte_vector sectdata (size);
7e10abd1
TT
10898 bfd_get_section_contents (current_program_space->exec_bfd (), s,
10899 sectdata.data (), 0, size);
c906108c 10900
b80406ac 10901 res = target_verify_memory (sectdata.data (), lma, size);
4a5e7a5b
PA
10902
10903 if (res == -1)
5af949e3 10904 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
10905 paddress (target_gdbarch (), lma),
10906 paddress (target_gdbarch (), lma + size));
c906108c 10907
5af949e3 10908 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
10909 paddress (target_gdbarch (), lma),
10910 paddress (target_gdbarch (), lma + size));
4a5e7a5b 10911 if (res)
c906108c
SS
10912 printf_filtered ("matched.\n");
10913 else
c5aa993b
JM
10914 {
10915 printf_filtered ("MIS-MATCHED!\n");
10916 mismatched++;
10917 }
c906108c
SS
10918 }
10919 if (mismatched > 0)
936d2992 10920 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 10921the loaded file\n"));
c906108c 10922 if (args && !matched)
a3f17187 10923 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
10924}
10925
0e7f50da
UW
10926/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10927 into remote target. The number of bytes written to the remote
10928 target is returned, or -1 for error. */
10929
6b8edb51
PA
10930target_xfer_status
10931remote_target::remote_write_qxfer (const char *object_name,
10932 const char *annex, const gdb_byte *writebuf,
10933 ULONGEST offset, LONGEST len,
10934 ULONGEST *xfered_len,
10935 struct packet_config *packet)
0e7f50da
UW
10936{
10937 int i, buf_len;
10938 ULONGEST n;
0e7f50da
UW
10939 struct remote_state *rs = get_remote_state ();
10940 int max_size = get_memory_write_packet_size ();
10941
7cc244de 10942 if (packet_config_support (packet) == PACKET_DISABLE)
2ed4b548 10943 return TARGET_XFER_E_IO;
0e7f50da
UW
10944
10945 /* Insert header. */
8d64371b 10946 i = snprintf (rs->buf.data (), max_size,
0e7f50da
UW
10947 "qXfer:%s:write:%s:%s:",
10948 object_name, annex ? annex : "",
10949 phex_nz (offset, sizeof offset));
10950 max_size -= (i + 1);
10951
10952 /* Escape as much data as fits into rs->buf. */
10953 buf_len = remote_escape_output
8d64371b 10954 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
0e7f50da 10955
8d64371b
TT
10956 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
10957 || getpkt_sane (&rs->buf, 0) < 0
0e7f50da 10958 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10959 return TARGET_XFER_E_IO;
0e7f50da 10960
8d64371b 10961 unpack_varlen_hex (rs->buf.data (), &n);
9b409511
YQ
10962
10963 *xfered_len = n;
92ffd475 10964 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
0e7f50da
UW
10965}
10966
0876f84a
DJ
10967/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10968 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10969 number of bytes read is returned, or 0 for EOF, or -1 for error.
10970 The number of bytes read may be less than LEN without indicating an
10971 EOF. PACKET is checked and updated to indicate whether the remote
10972 target supports this object. */
10973
6b8edb51
PA
10974target_xfer_status
10975remote_target::remote_read_qxfer (const char *object_name,
10976 const char *annex,
10977 gdb_byte *readbuf, ULONGEST offset,
10978 LONGEST len,
10979 ULONGEST *xfered_len,
10980 struct packet_config *packet)
0876f84a 10981{
0876f84a 10982 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
10983 LONGEST i, n, packet_len;
10984
7cc244de 10985 if (packet_config_support (packet) == PACKET_DISABLE)
2ed4b548 10986 return TARGET_XFER_E_IO;
0876f84a
DJ
10987
10988 /* Check whether we've cached an end-of-object packet that matches
10989 this request. */
8e88304f 10990 if (rs->finished_object)
0876f84a 10991 {
8e88304f
TT
10992 if (strcmp (object_name, rs->finished_object) == 0
10993 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10994 && offset == rs->finished_offset)
9b409511
YQ
10995 return TARGET_XFER_EOF;
10996
0876f84a
DJ
10997
10998 /* Otherwise, we're now reading something different. Discard
10999 the cache. */
8e88304f
TT
11000 xfree (rs->finished_object);
11001 xfree (rs->finished_annex);
11002 rs->finished_object = NULL;
11003 rs->finished_annex = NULL;
0876f84a
DJ
11004 }
11005
11006 /* Request only enough to fit in a single packet. The actual data
11007 may not, since we don't know how much of it will need to be escaped;
11008 the target is free to respond with slightly less data. We subtract
11009 five to account for the response type and the protocol frame. */
768adc05 11010 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
8d64371b
TT
11011 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11012 "qXfer:%s:read:%s:%s,%s",
0876f84a
DJ
11013 object_name, annex ? annex : "",
11014 phex_nz (offset, sizeof offset),
11015 phex_nz (n, sizeof n));
11016 i = putpkt (rs->buf);
11017 if (i < 0)
2ed4b548 11018 return TARGET_XFER_E_IO;
0876f84a
DJ
11019
11020 rs->buf[0] = '\0';
8d64371b 11021 packet_len = getpkt_sane (&rs->buf, 0);
0876f84a 11022 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 11023 return TARGET_XFER_E_IO;
0876f84a
DJ
11024
11025 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8d64371b 11026 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
0876f84a
DJ
11027
11028 /* 'm' means there is (or at least might be) more data after this
11029 batch. That does not make sense unless there's at least one byte
11030 of data in this reply. */
11031 if (rs->buf[0] == 'm' && packet_len == 1)
11032 error (_("Remote qXfer reply contained no data."));
11033
11034 /* Got some data. */
8d64371b 11035 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
bc20a4af 11036 packet_len - 1, readbuf, n);
0876f84a
DJ
11037
11038 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
11039 or possibly empty. If we have the final block of a non-empty
11040 object, record this fact to bypass a subsequent partial read. */
11041 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 11042 {
8e88304f
TT
11043 rs->finished_object = xstrdup (object_name);
11044 rs->finished_annex = xstrdup (annex ? annex : "");
11045 rs->finished_offset = offset + i;
0876f84a
DJ
11046 }
11047
9b409511
YQ
11048 if (i == 0)
11049 return TARGET_XFER_EOF;
11050 else
11051 {
11052 *xfered_len = i;
11053 return TARGET_XFER_OK;
11054 }
0876f84a
DJ
11055}
11056
f6ac5f3d
PA
11057enum target_xfer_status
11058remote_target::xfer_partial (enum target_object object,
11059 const char *annex, gdb_byte *readbuf,
11060 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11061 ULONGEST *xfered_len)
c906108c 11062{
82f73884 11063 struct remote_state *rs;
c906108c 11064 int i;
6d820c5c 11065 char *p2;
1e3ff5ad 11066 char query_type;
124e13d9 11067 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 11068
e6e4e701 11069 set_remote_traceframe ();
82f73884
PA
11070 set_general_thread (inferior_ptid);
11071
11072 rs = get_remote_state ();
11073
b2182ed2 11074 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
11075 if (object == TARGET_OBJECT_MEMORY)
11076 {
2d717e4f
DJ
11077 /* If the remote target is connected but not running, we should
11078 pass this request down to a lower stratum (e.g. the executable
11079 file). */
55f6301a 11080 if (!target_has_execution ())
9b409511 11081 return TARGET_XFER_EOF;
2d717e4f 11082
21e3b9b9 11083 if (writebuf != NULL)
124e13d9
SM
11084 return remote_write_bytes (offset, writebuf, len, unit_size,
11085 xfered_len);
21e3b9b9 11086 else
6b8edb51 11087 return remote_read_bytes (offset, readbuf, len, unit_size,
124e13d9 11088 xfered_len);
21e3b9b9
DJ
11089 }
11090
4aa995e1
PA
11091 /* Handle extra signal info using qxfer packets. */
11092 if (object == TARGET_OBJECT_SIGNAL_INFO)
11093 {
11094 if (readbuf)
f6ac5f3d 11095 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
9b409511 11096 xfered_len, &remote_protocol_packets
4aa995e1
PA
11097 [PACKET_qXfer_siginfo_read]);
11098 else
f6ac5f3d 11099 return remote_write_qxfer ("siginfo", annex,
9b409511 11100 writebuf, offset, len, xfered_len,
4aa995e1
PA
11101 &remote_protocol_packets
11102 [PACKET_qXfer_siginfo_write]);
11103 }
11104
0fb4aa4b
PA
11105 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11106 {
11107 if (readbuf)
f6ac5f3d 11108 return remote_read_qxfer ("statictrace", annex,
9b409511 11109 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
11110 &remote_protocol_packets
11111 [PACKET_qXfer_statictrace_read]);
11112 else
2ed4b548 11113 return TARGET_XFER_E_IO;
0fb4aa4b
PA
11114 }
11115
a76d924d
DJ
11116 /* Only handle flash writes. */
11117 if (writebuf != NULL)
11118 {
a76d924d
DJ
11119 switch (object)
11120 {
11121 case TARGET_OBJECT_FLASH:
6b8edb51 11122 return remote_flash_write (offset, len, xfered_len,
9b409511 11123 writebuf);
a76d924d
DJ
11124
11125 default:
2ed4b548 11126 return TARGET_XFER_E_IO;
a76d924d
DJ
11127 }
11128 }
4b8a223f 11129
1e3ff5ad
AC
11130 /* Map pre-existing objects onto letters. DO NOT do this for new
11131 objects!!! Instead specify new query packets. */
11132 switch (object)
c906108c 11133 {
1e3ff5ad
AC
11134 case TARGET_OBJECT_AVR:
11135 query_type = 'R';
11136 break;
802188a7
RM
11137
11138 case TARGET_OBJECT_AUXV:
0876f84a 11139 gdb_assert (annex == NULL);
f6ac5f3d 11140 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
9b409511 11141 xfered_len,
0876f84a 11142 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 11143
23181151
DJ
11144 case TARGET_OBJECT_AVAILABLE_FEATURES:
11145 return remote_read_qxfer
f6ac5f3d 11146 ("features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
11147 &remote_protocol_packets[PACKET_qXfer_features]);
11148
cfa9d6d9
DJ
11149 case TARGET_OBJECT_LIBRARIES:
11150 return remote_read_qxfer
f6ac5f3d 11151 ("libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
11152 &remote_protocol_packets[PACKET_qXfer_libraries]);
11153
2268b414
JK
11154 case TARGET_OBJECT_LIBRARIES_SVR4:
11155 return remote_read_qxfer
f6ac5f3d 11156 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
11157 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
11158
fd79ecee
DJ
11159 case TARGET_OBJECT_MEMORY_MAP:
11160 gdb_assert (annex == NULL);
f6ac5f3d 11161 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
9b409511 11162 xfered_len,
fd79ecee
DJ
11163 &remote_protocol_packets[PACKET_qXfer_memory_map]);
11164
07e059b5
VP
11165 case TARGET_OBJECT_OSDATA:
11166 /* Should only get here if we're connected. */
5d93a237 11167 gdb_assert (rs->remote_desc);
07e059b5 11168 return remote_read_qxfer
f6ac5f3d 11169 ("osdata", annex, readbuf, offset, len, xfered_len,
dda83cd7 11170 &remote_protocol_packets[PACKET_qXfer_osdata]);
07e059b5 11171
dc146f7c
VP
11172 case TARGET_OBJECT_THREADS:
11173 gdb_assert (annex == NULL);
f6ac5f3d 11174 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
9b409511 11175 xfered_len,
dc146f7c
VP
11176 &remote_protocol_packets[PACKET_qXfer_threads]);
11177
b3b9301e
PA
11178 case TARGET_OBJECT_TRACEFRAME_INFO:
11179 gdb_assert (annex == NULL);
11180 return remote_read_qxfer
f6ac5f3d 11181 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 11182 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
11183
11184 case TARGET_OBJECT_FDPIC:
f6ac5f3d 11185 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
9b409511 11186 xfered_len,
78d85199 11187 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
11188
11189 case TARGET_OBJECT_OPENVMS_UIB:
f6ac5f3d 11190 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
9b409511 11191 xfered_len,
169081d0
TG
11192 &remote_protocol_packets[PACKET_qXfer_uib]);
11193
9accd112 11194 case TARGET_OBJECT_BTRACE:
f6ac5f3d 11195 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
9b409511 11196 xfered_len,
dda83cd7 11197 &remote_protocol_packets[PACKET_qXfer_btrace]);
9accd112 11198
f4abbc16 11199 case TARGET_OBJECT_BTRACE_CONF:
f6ac5f3d 11200 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
f4abbc16
MM
11201 len, xfered_len,
11202 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11203
c78fa86a 11204 case TARGET_OBJECT_EXEC_FILE:
f6ac5f3d 11205 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
c78fa86a
GB
11206 len, xfered_len,
11207 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11208
1e3ff5ad 11209 default:
2ed4b548 11210 return TARGET_XFER_E_IO;
c906108c
SS
11211 }
11212
0df8b418 11213 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 11214 large enough let the caller deal with it. */
ea9c271d 11215 if (len < get_remote_packet_size ())
2ed4b548 11216 return TARGET_XFER_E_IO;
ea9c271d 11217 len = get_remote_packet_size ();
1e3ff5ad 11218
23860348 11219 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 11220 if (!rs->remote_desc)
8a3fe4f8 11221 error (_("remote query is only available after target open"));
c906108c 11222
1e3ff5ad 11223 gdb_assert (annex != NULL);
4b8a223f 11224 gdb_assert (readbuf != NULL);
c906108c 11225
8d64371b 11226 p2 = rs->buf.data ();
c906108c
SS
11227 *p2++ = 'q';
11228 *p2++ = query_type;
11229
23860348
MS
11230 /* We used one buffer char for the remote protocol q command and
11231 another for the query type. As the remote protocol encapsulation
11232 uses 4 chars plus one extra in case we are debugging
11233 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11234 string. */
c906108c 11235 i = 0;
ea9c271d 11236 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 11237 {
1e3ff5ad
AC
11238 /* Bad caller may have sent forbidden characters. */
11239 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11240 *p2++ = annex[i];
c906108c
SS
11241 i++;
11242 }
1e3ff5ad
AC
11243 *p2 = '\0';
11244 gdb_assert (annex[i] == '\0');
c906108c 11245
6d820c5c 11246 i = putpkt (rs->buf);
c5aa993b 11247 if (i < 0)
2ed4b548 11248 return TARGET_XFER_E_IO;
c906108c 11249
8d64371b
TT
11250 getpkt (&rs->buf, 0);
11251 strcpy ((char *) readbuf, rs->buf.data ());
c906108c 11252
9b409511 11253 *xfered_len = strlen ((char *) readbuf);
92ffd475 11254 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
11255}
11256
09c98b44
DB
11257/* Implementation of to_get_memory_xfer_limit. */
11258
f6ac5f3d
PA
11259ULONGEST
11260remote_target::get_memory_xfer_limit ()
09c98b44
DB
11261{
11262 return get_memory_write_packet_size ();
11263}
11264
f6ac5f3d
PA
11265int
11266remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11267 const gdb_byte *pattern, ULONGEST pattern_len,
11268 CORE_ADDR *found_addrp)
08388c79 11269{
f5656ead 11270 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
11271 struct remote_state *rs = get_remote_state ();
11272 int max_size = get_memory_write_packet_size ();
11273 struct packet_config *packet =
11274 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
11275 /* Number of packet bytes used to encode the pattern;
11276 this could be more than PATTERN_LEN due to escape characters. */
08388c79 11277 int escaped_pattern_len;
0df8b418 11278 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
11279 int used_pattern_len;
11280 int i;
11281 int found;
11282 ULONGEST found_addr;
11283
4a72de73
TT
11284 auto read_memory = [=] (CORE_ADDR addr, gdb_byte *result, size_t len)
11285 {
11286 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11287 == len);
11288 };
11289
7cc244de
PA
11290 /* Don't go to the target if we don't have to. This is done before
11291 checking packet_config_support to avoid the possibility that a
11292 success for this edge case means the facility works in
11293 general. */
08388c79
DE
11294 if (pattern_len > search_space_len)
11295 return 0;
11296 if (pattern_len == 0)
11297 {
11298 *found_addrp = start_addr;
11299 return 1;
11300 }
11301
11302 /* If we already know the packet isn't supported, fall back to the simple
11303 way of searching memory. */
11304
4082afcc 11305 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
11306 {
11307 /* Target doesn't provided special support, fall back and use the
11308 standard support (copy memory and do the search here). */
4a72de73 11309 return simple_search_memory (read_memory, start_addr, search_space_len,
08388c79
DE
11310 pattern, pattern_len, found_addrp);
11311 }
11312
28439a30
PA
11313 /* Make sure the remote is pointing at the right process. */
11314 set_general_process ();
11315
08388c79 11316 /* Insert header. */
8d64371b 11317 i = snprintf (rs->buf.data (), max_size,
08388c79 11318 "qSearch:memory:%s;%s;",
5af949e3 11319 phex_nz (start_addr, addr_size),
08388c79
DE
11320 phex_nz (search_space_len, sizeof (search_space_len)));
11321 max_size -= (i + 1);
11322
11323 /* Escape as much data as fits into rs->buf. */
11324 escaped_pattern_len =
8d64371b
TT
11325 remote_escape_output (pattern, pattern_len, 1,
11326 (gdb_byte *) rs->buf.data () + i,
08388c79
DE
11327 &used_pattern_len, max_size);
11328
11329 /* Bail if the pattern is too large. */
11330 if (used_pattern_len != pattern_len)
9b20d036 11331 error (_("Pattern is too large to transmit to remote target."));
08388c79 11332
8d64371b
TT
11333 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11334 || getpkt_sane (&rs->buf, 0) < 0
08388c79
DE
11335 || packet_ok (rs->buf, packet) != PACKET_OK)
11336 {
11337 /* The request may not have worked because the command is not
11338 supported. If so, fall back to the simple way. */
7cc244de 11339 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79 11340 {
4a72de73 11341 return simple_search_memory (read_memory, start_addr, search_space_len,
08388c79
DE
11342 pattern, pattern_len, found_addrp);
11343 }
11344 return -1;
11345 }
11346
11347 if (rs->buf[0] == '0')
11348 found = 0;
11349 else if (rs->buf[0] == '1')
11350 {
11351 found = 1;
11352 if (rs->buf[1] != ',')
8d64371b
TT
11353 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11354 unpack_varlen_hex (&rs->buf[2], &found_addr);
08388c79
DE
11355 *found_addrp = found_addr;
11356 }
11357 else
8d64371b 11358 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
08388c79
DE
11359
11360 return found;
11361}
11362
f6ac5f3d
PA
11363void
11364remote_target::rcmd (const char *command, struct ui_file *outbuf)
96baa820 11365{
d01949b6 11366 struct remote_state *rs = get_remote_state ();
8d64371b 11367 char *p = rs->buf.data ();
96baa820 11368
5d93a237 11369 if (!rs->remote_desc)
8a3fe4f8 11370 error (_("remote rcmd is only available after target open"));
96baa820 11371
23860348 11372 /* Send a NULL command across as an empty command. */
7be570e7
JM
11373 if (command == NULL)
11374 command = "";
11375
23860348 11376 /* The query prefix. */
8d64371b
TT
11377 strcpy (rs->buf.data (), "qRcmd,");
11378 p = strchr (rs->buf.data (), '\0');
96baa820 11379
8d64371b 11380 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
3e43a32a 11381 > get_remote_packet_size ())
8a3fe4f8 11382 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 11383
23860348 11384 /* Encode the actual command. */
a30bf1f1 11385 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 11386
6d820c5c 11387 if (putpkt (rs->buf) < 0)
8a3fe4f8 11388 error (_("Communication problem with target."));
96baa820
JM
11389
11390 /* get/display the response */
11391 while (1)
11392 {
2e9f7625
DJ
11393 char *buf;
11394
00bf0b85 11395 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 11396 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 11397 rs->buf[0] = '\0';
8d64371b 11398 if (getpkt_sane (&rs->buf, 0) == -1)
dda83cd7
SM
11399 {
11400 /* Timeout. Continue to (try to) read responses.
11401 This is better than stopping with an error, assuming the stub
11402 is still executing the (long) monitor command.
11403 If needed, the user can interrupt gdb using C-c, obtaining
11404 an effect similar to stop on timeout. */
11405 continue;
11406 }
8d64371b 11407 buf = rs->buf.data ();
96baa820 11408 if (buf[0] == '\0')
8a3fe4f8 11409 error (_("Target does not support this command."));
96baa820
JM
11410 if (buf[0] == 'O' && buf[1] != 'K')
11411 {
23860348 11412 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
11413 continue;
11414 }
11415 if (strcmp (buf, "OK") == 0)
11416 break;
7be570e7
JM
11417 if (strlen (buf) == 3 && buf[0] == 'E'
11418 && isdigit (buf[1]) && isdigit (buf[2]))
11419 {
8a3fe4f8 11420 error (_("Protocol error with Rcmd"));
7be570e7 11421 }
96baa820
JM
11422 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11423 {
11424 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 11425
96baa820
JM
11426 fputc_unfiltered (c, outbuf);
11427 }
11428 break;
11429 }
11430}
11431
f6ac5f3d
PA
11432std::vector<mem_region>
11433remote_target::memory_map ()
fd79ecee 11434{
a664f67e 11435 std::vector<mem_region> result;
9018be22 11436 gdb::optional<gdb::char_vector> text
8b88a78e 11437 = target_read_stralloc (current_top_target (), TARGET_OBJECT_MEMORY_MAP, NULL);
fd79ecee
DJ
11438
11439 if (text)
9018be22 11440 result = parse_memory_map (text->data ());
fd79ecee
DJ
11441
11442 return result;
11443}
11444
c906108c 11445static void
ac88e2de 11446packet_command (const char *args, int from_tty)
c906108c 11447{
6b8edb51 11448 remote_target *remote = get_current_remote_target ();
c906108c 11449
6b8edb51 11450 if (remote == nullptr)
8a3fe4f8 11451 error (_("command can only be used with remote target"));
c906108c 11452
6b8edb51
PA
11453 remote->packet_command (args, from_tty);
11454}
11455
11456void
11457remote_target::packet_command (const char *args, int from_tty)
11458{
c5aa993b 11459 if (!args)
8a3fe4f8 11460 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
11461
11462 puts_filtered ("sending: ");
11463 print_packet (args);
11464 puts_filtered ("\n");
11465 putpkt (args);
11466
6b8edb51
PA
11467 remote_state *rs = get_remote_state ();
11468
8d64371b 11469 getpkt (&rs->buf, 0);
c906108c 11470 puts_filtered ("received: ");
8d64371b 11471 print_packet (rs->buf.data ());
c906108c
SS
11472 puts_filtered ("\n");
11473}
11474
11475#if 0
23860348 11476/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 11477
a14ed312 11478static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 11479
a14ed312 11480static void threadset_test_cmd (char *cmd, int tty);
c906108c 11481
a14ed312 11482static void threadalive_test (char *cmd, int tty);
c906108c 11483
a14ed312 11484static void threadlist_test_cmd (char *cmd, int tty);
c906108c 11485
23860348 11486int get_and_display_threadinfo (threadref *ref);
c906108c 11487
a14ed312 11488static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 11489
23860348 11490static int thread_display_step (threadref *ref, void *context);
c906108c 11491
a14ed312 11492static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 11493
a14ed312 11494static void init_remote_threadtests (void);
c906108c 11495
23860348 11496#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
11497
11498static void
0b39b52e 11499threadset_test_cmd (const char *cmd, int tty)
c906108c
SS
11500{
11501 int sample_thread = SAMPLE_THREAD;
11502
a3f17187 11503 printf_filtered (_("Remote threadset test\n"));
79d7f229 11504 set_general_thread (sample_thread);
c906108c
SS
11505}
11506
11507
11508static void
0b39b52e 11509threadalive_test (const char *cmd, int tty)
c906108c
SS
11510{
11511 int sample_thread = SAMPLE_THREAD;
e99b03dc 11512 int pid = inferior_ptid.pid ();
fd79271b 11513 ptid_t ptid = ptid_t (pid, sample_thread, 0);
c906108c 11514
79d7f229 11515 if (remote_thread_alive (ptid))
c906108c
SS
11516 printf_filtered ("PASS: Thread alive test\n");
11517 else
11518 printf_filtered ("FAIL: Thread alive test\n");
11519}
11520
23860348 11521void output_threadid (char *title, threadref *ref);
c906108c
SS
11522
11523void
fba45db2 11524output_threadid (char *title, threadref *ref)
c906108c
SS
11525{
11526 char hexid[20];
11527
405feb71 11528 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
c906108c
SS
11529 hexid[16] = 0;
11530 printf_filtered ("%s %s\n", title, (&hexid[0]));
11531}
11532
11533static void
0b39b52e 11534threadlist_test_cmd (const char *cmd, int tty)
c906108c
SS
11535{
11536 int startflag = 1;
11537 threadref nextthread;
11538 int done, result_count;
11539 threadref threadlist[3];
11540
11541 printf_filtered ("Remote Threadlist test\n");
11542 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11543 &result_count, &threadlist[0]))
11544 printf_filtered ("FAIL: threadlist test\n");
11545 else
11546 {
11547 threadref *scan = threadlist;
11548 threadref *limit = scan + result_count;
11549
11550 while (scan < limit)
11551 output_threadid (" thread ", scan++);
11552 }
11553}
11554
11555void
fba45db2 11556display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
11557{
11558 output_threadid ("Threadid: ", &info->threadid);
11559 printf_filtered ("Name: %s\n ", info->shortname);
11560 printf_filtered ("State: %s\n", info->display);
11561 printf_filtered ("other: %s\n\n", info->more_display);
11562}
11563
11564int
fba45db2 11565get_and_display_threadinfo (threadref *ref)
c906108c
SS
11566{
11567 int result;
11568 int set;
11569 struct gdb_ext_thread_info threadinfo;
11570
11571 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11572 | TAG_MOREDISPLAY | TAG_DISPLAY;
11573 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11574 display_thread_info (&threadinfo);
11575 return result;
11576}
11577
11578static void
0b39b52e 11579threadinfo_test_cmd (const char *cmd, int tty)
c906108c
SS
11580{
11581 int athread = SAMPLE_THREAD;
11582 threadref thread;
11583 int set;
11584
11585 int_to_threadref (&thread, athread);
11586 printf_filtered ("Remote Threadinfo test\n");
11587 if (!get_and_display_threadinfo (&thread))
11588 printf_filtered ("FAIL cannot get thread info\n");
11589}
11590
11591static int
fba45db2 11592thread_display_step (threadref *ref, void *context)
c906108c
SS
11593{
11594 /* output_threadid(" threadstep ",ref); *//* simple test */
11595 return get_and_display_threadinfo (ref);
11596}
11597
11598static void
0b39b52e 11599threadlist_update_test_cmd (const char *cmd, int tty)
c906108c
SS
11600{
11601 printf_filtered ("Remote Threadlist update test\n");
11602 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11603}
11604
11605static void
11606init_remote_threadtests (void)
11607{
3e43a32a
MS
11608 add_com ("tlist", class_obscure, threadlist_test_cmd,
11609 _("Fetch and print the remote list of "
590042fc 11610 "thread identifiers, one pkt only."));
c906108c 11611 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
590042fc 11612 _("Fetch and display info about one thread."));
c906108c 11613 add_com ("tset", class_obscure, threadset_test_cmd,
590042fc 11614 _("Test setting to a different thread."));
c906108c 11615 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
590042fc 11616 _("Iterate through updating all remote thread info."));
c906108c 11617 add_com ("talive", class_obscure, threadalive_test,
590042fc 11618 _("Remote thread alive test."));
c906108c
SS
11619}
11620
11621#endif /* 0 */
11622
a068643d 11623/* Convert a thread ID to a string. */
f3fb8c85 11624
a068643d 11625std::string
f6ac5f3d 11626remote_target::pid_to_str (ptid_t ptid)
f3fb8c85 11627{
82f73884 11628 struct remote_state *rs = get_remote_state ();
f3fb8c85 11629
d7e15655 11630 if (ptid == null_ptid)
7cee1e54 11631 return normal_pid_to_str (ptid);
0e998d96 11632 else if (ptid.is_pid ())
ecd0ada5
PA
11633 {
11634 /* Printing an inferior target id. */
11635
11636 /* When multi-process extensions are off, there's no way in the
11637 remote protocol to know the remote process id, if there's any
11638 at all. There's one exception --- when we're connected with
11639 target extended-remote, and we manually attached to a process
11640 with "attach PID". We don't record anywhere a flag that
11641 allows us to distinguish that case from the case of
11642 connecting with extended-remote and the stub already being
11643 attached to a process, and reporting yes to qAttached, hence
11644 no smart special casing here. */
11645 if (!remote_multi_process_p (rs))
a068643d 11646 return "Remote target";
ecd0ada5
PA
11647
11648 return normal_pid_to_str (ptid);
82f73884 11649 }
ecd0ada5 11650 else
79d7f229 11651 {
d7e15655 11652 if (magic_null_ptid == ptid)
a068643d 11653 return "Thread <main>";
8020350c 11654 else if (remote_multi_process_p (rs))
e38504b3 11655 if (ptid.lwp () == 0)
de0d863e
DB
11656 return normal_pid_to_str (ptid);
11657 else
a068643d
TT
11658 return string_printf ("Thread %d.%ld",
11659 ptid.pid (), ptid.lwp ());
ecd0ada5 11660 else
a068643d 11661 return string_printf ("Thread %ld", ptid.lwp ());
79d7f229 11662 }
f3fb8c85
MS
11663}
11664
38691318
KB
11665/* Get the address of the thread local variable in OBJFILE which is
11666 stored at OFFSET within the thread local storage for thread PTID. */
11667
f6ac5f3d
PA
11668CORE_ADDR
11669remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11670 CORE_ADDR offset)
38691318 11671{
4082afcc 11672 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
11673 {
11674 struct remote_state *rs = get_remote_state ();
8d64371b
TT
11675 char *p = rs->buf.data ();
11676 char *endp = p + get_remote_packet_size ();
571dd617 11677 enum packet_result result;
38691318
KB
11678
11679 strcpy (p, "qGetTLSAddr:");
11680 p += strlen (p);
82f73884 11681 p = write_ptid (p, endp, ptid);
38691318
KB
11682 *p++ = ',';
11683 p += hexnumstr (p, offset);
11684 *p++ = ',';
11685 p += hexnumstr (p, lm);
11686 *p++ = '\0';
11687
6d820c5c 11688 putpkt (rs->buf);
8d64371b 11689 getpkt (&rs->buf, 0);
3e43a32a
MS
11690 result = packet_ok (rs->buf,
11691 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 11692 if (result == PACKET_OK)
38691318 11693 {
b926417a 11694 ULONGEST addr;
38691318 11695
8d64371b 11696 unpack_varlen_hex (rs->buf.data (), &addr);
b926417a 11697 return addr;
38691318 11698 }
571dd617 11699 else if (result == PACKET_UNKNOWN)
109c3e39
AC
11700 throw_error (TLS_GENERIC_ERROR,
11701 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 11702 else
109c3e39
AC
11703 throw_error (TLS_GENERIC_ERROR,
11704 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
11705 }
11706 else
109c3e39
AC
11707 throw_error (TLS_GENERIC_ERROR,
11708 _("TLS not supported or disabled on this target"));
38691318
KB
11709 /* Not reached. */
11710 return 0;
11711}
11712
711e434b
PM
11713/* Provide thread local base, i.e. Thread Information Block address.
11714 Returns 1 if ptid is found and thread_local_base is non zero. */
11715
57810aa7 11716bool
f6ac5f3d 11717remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
711e434b 11718{
4082afcc 11719 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
11720 {
11721 struct remote_state *rs = get_remote_state ();
8d64371b
TT
11722 char *p = rs->buf.data ();
11723 char *endp = p + get_remote_packet_size ();
711e434b
PM
11724 enum packet_result result;
11725
11726 strcpy (p, "qGetTIBAddr:");
11727 p += strlen (p);
11728 p = write_ptid (p, endp, ptid);
11729 *p++ = '\0';
11730
11731 putpkt (rs->buf);
8d64371b 11732 getpkt (&rs->buf, 0);
711e434b
PM
11733 result = packet_ok (rs->buf,
11734 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11735 if (result == PACKET_OK)
11736 {
b926417a 11737 ULONGEST val;
8d64371b 11738 unpack_varlen_hex (rs->buf.data (), &val);
711e434b 11739 if (addr)
b926417a 11740 *addr = (CORE_ADDR) val;
57810aa7 11741 return true;
711e434b
PM
11742 }
11743 else if (result == PACKET_UNKNOWN)
11744 error (_("Remote target doesn't support qGetTIBAddr packet"));
11745 else
11746 error (_("Remote target failed to process qGetTIBAddr request"));
11747 }
11748 else
11749 error (_("qGetTIBAddr not supported or disabled on this target"));
11750 /* Not reached. */
57810aa7 11751 return false;
711e434b
PM
11752}
11753
29709017
DJ
11754/* Support for inferring a target description based on the current
11755 architecture and the size of a 'g' packet. While the 'g' packet
11756 can have any size (since optional registers can be left off the
11757 end), some sizes are easily recognizable given knowledge of the
11758 approximate architecture. */
11759
11760struct remote_g_packet_guess
11761{
eefce37f
TT
11762 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
11763 : bytes (bytes_),
11764 tdesc (tdesc_)
11765 {
11766 }
11767
29709017
DJ
11768 int bytes;
11769 const struct target_desc *tdesc;
11770};
29709017 11771
eefce37f 11772struct remote_g_packet_data : public allocate_on_obstack
29709017 11773{
eefce37f 11774 std::vector<remote_g_packet_guess> guesses;
29709017
DJ
11775};
11776
11777static struct gdbarch_data *remote_g_packet_data_handle;
11778
11779static void *
11780remote_g_packet_data_init (struct obstack *obstack)
11781{
eefce37f 11782 return new (obstack) remote_g_packet_data;
29709017
DJ
11783}
11784
11785void
11786register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11787 const struct target_desc *tdesc)
11788{
11789 struct remote_g_packet_data *data
19ba03f4
SM
11790 = ((struct remote_g_packet_data *)
11791 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
11792
11793 gdb_assert (tdesc != NULL);
11794
eefce37f
TT
11795 for (const remote_g_packet_guess &guess : data->guesses)
11796 if (guess.bytes == bytes)
29709017 11797 internal_error (__FILE__, __LINE__,
9b20d036 11798 _("Duplicate g packet description added for size %d"),
29709017
DJ
11799 bytes);
11800
eefce37f 11801 data->guesses.emplace_back (bytes, tdesc);
29709017
DJ
11802}
11803
eefce37f
TT
11804/* Return true if remote_read_description would do anything on this target
11805 and architecture, false otherwise. */
d962ef82 11806
eefce37f 11807static bool
d962ef82
DJ
11808remote_read_description_p (struct target_ops *target)
11809{
11810 struct remote_g_packet_data *data
19ba03f4
SM
11811 = ((struct remote_g_packet_data *)
11812 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82 11813
eefce37f 11814 return !data->guesses.empty ();
d962ef82
DJ
11815}
11816
f6ac5f3d
PA
11817const struct target_desc *
11818remote_target::read_description ()
29709017
DJ
11819{
11820 struct remote_g_packet_data *data
19ba03f4
SM
11821 = ((struct remote_g_packet_data *)
11822 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 11823
d962ef82
DJ
11824 /* Do not try this during initial connection, when we do not know
11825 whether there is a running but stopped thread. */
55f6301a 11826 if (!target_has_execution () || inferior_ptid == null_ptid)
b6a8c27b 11827 return beneath ()->read_description ();
d962ef82 11828
eefce37f 11829 if (!data->guesses.empty ())
29709017 11830 {
29709017
DJ
11831 int bytes = send_g_packet ();
11832
eefce37f
TT
11833 for (const remote_g_packet_guess &guess : data->guesses)
11834 if (guess.bytes == bytes)
11835 return guess.tdesc;
29709017
DJ
11836
11837 /* We discard the g packet. A minor optimization would be to
11838 hold on to it, and fill the register cache once we have selected
11839 an architecture, but it's too tricky to do safely. */
11840 }
11841
b6a8c27b 11842 return beneath ()->read_description ();
29709017
DJ
11843}
11844
a6b151f1
DJ
11845/* Remote file transfer support. This is host-initiated I/O, not
11846 target-initiated; for target-initiated, see remote-fileio.c. */
11847
11848/* If *LEFT is at least the length of STRING, copy STRING to
11849 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11850 decrease *LEFT. Otherwise raise an error. */
11851
11852static void
a121b7c1 11853remote_buffer_add_string (char **buffer, int *left, const char *string)
a6b151f1
DJ
11854{
11855 int len = strlen (string);
11856
11857 if (len > *left)
11858 error (_("Packet too long for target."));
11859
11860 memcpy (*buffer, string, len);
11861 *buffer += len;
11862 *left -= len;
11863
11864 /* NUL-terminate the buffer as a convenience, if there is
11865 room. */
11866 if (*left)
11867 **buffer = '\0';
11868}
11869
11870/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11871 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11872 decrease *LEFT. Otherwise raise an error. */
11873
11874static void
11875remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11876 int len)
11877{
11878 if (2 * len > *left)
11879 error (_("Packet too long for target."));
11880
11881 bin2hex (bytes, *buffer, len);
11882 *buffer += 2 * len;
11883 *left -= 2 * len;
11884
11885 /* NUL-terminate the buffer as a convenience, if there is
11886 room. */
11887 if (*left)
11888 **buffer = '\0';
11889}
11890
11891/* If *LEFT is large enough, convert VALUE to hex and add it to
11892 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11893 decrease *LEFT. Otherwise raise an error. */
11894
11895static void
11896remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11897{
11898 int len = hexnumlen (value);
11899
11900 if (len > *left)
11901 error (_("Packet too long for target."));
11902
11903 hexnumstr (*buffer, value);
11904 *buffer += len;
11905 *left -= len;
11906
11907 /* NUL-terminate the buffer as a convenience, if there is
11908 room. */
11909 if (*left)
11910 **buffer = '\0';
11911}
11912
11913/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11914 value, *REMOTE_ERRNO to the remote error number or zero if none
11915 was included, and *ATTACHMENT to point to the start of the annex
11916 if any. The length of the packet isn't needed here; there may
11917 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11918
11919 Return 0 if the packet could be parsed, -1 if it could not. If
11920 -1 is returned, the other variables may not be initialized. */
11921
11922static int
11923remote_hostio_parse_result (char *buffer, int *retcode,
11924 int *remote_errno, char **attachment)
11925{
11926 char *p, *p2;
11927
11928 *remote_errno = 0;
11929 *attachment = NULL;
11930
11931 if (buffer[0] != 'F')
11932 return -1;
11933
11934 errno = 0;
11935 *retcode = strtol (&buffer[1], &p, 16);
11936 if (errno != 0 || p == &buffer[1])
11937 return -1;
11938
11939 /* Check for ",errno". */
11940 if (*p == ',')
11941 {
11942 errno = 0;
11943 *remote_errno = strtol (p + 1, &p2, 16);
11944 if (errno != 0 || p + 1 == p2)
11945 return -1;
11946 p = p2;
11947 }
11948
11949 /* Check for ";attachment". If there is no attachment, the
11950 packet should end here. */
11951 if (*p == ';')
11952 {
11953 *attachment = p + 1;
11954 return 0;
11955 }
11956 else if (*p == '\0')
11957 return 0;
11958 else
11959 return -1;
11960}
11961
11962/* Send a prepared I/O packet to the target and read its response.
11963 The prepared packet is in the global RS->BUF before this function
11964 is called, and the answer is there when we return.
11965
11966 COMMAND_BYTES is the length of the request to send, which may include
11967 binary data. WHICH_PACKET is the packet configuration to check
11968 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11969 is set to the error number and -1 is returned. Otherwise the value
11970 returned by the function is returned.
11971
11972 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11973 attachment is expected; an error will be reported if there's a
11974 mismatch. If one is found, *ATTACHMENT will be set to point into
11975 the packet buffer and *ATTACHMENT_LEN will be set to the
11976 attachment's length. */
11977
6b8edb51
PA
11978int
11979remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
11980 int *remote_errno, char **attachment,
11981 int *attachment_len)
a6b151f1
DJ
11982{
11983 struct remote_state *rs = get_remote_state ();
11984 int ret, bytes_read;
11985 char *attachment_tmp;
11986
20db9c52 11987 if (packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
11988 {
11989 *remote_errno = FILEIO_ENOSYS;
11990 return -1;
11991 }
11992
8d64371b
TT
11993 putpkt_binary (rs->buf.data (), command_bytes);
11994 bytes_read = getpkt_sane (&rs->buf, 0);
a6b151f1
DJ
11995
11996 /* If it timed out, something is wrong. Don't try to parse the
11997 buffer. */
11998 if (bytes_read < 0)
11999 {
12000 *remote_errno = FILEIO_EINVAL;
12001 return -1;
12002 }
12003
12004 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
12005 {
12006 case PACKET_ERROR:
12007 *remote_errno = FILEIO_EINVAL;
12008 return -1;
12009 case PACKET_UNKNOWN:
12010 *remote_errno = FILEIO_ENOSYS;
12011 return -1;
12012 case PACKET_OK:
12013 break;
12014 }
12015
8d64371b 12016 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
a6b151f1
DJ
12017 &attachment_tmp))
12018 {
12019 *remote_errno = FILEIO_EINVAL;
12020 return -1;
12021 }
12022
12023 /* Make sure we saw an attachment if and only if we expected one. */
12024 if ((attachment_tmp == NULL && attachment != NULL)
12025 || (attachment_tmp != NULL && attachment == NULL))
12026 {
12027 *remote_errno = FILEIO_EINVAL;
12028 return -1;
12029 }
12030
12031 /* If an attachment was found, it must point into the packet buffer;
12032 work out how many bytes there were. */
12033 if (attachment_tmp != NULL)
12034 {
12035 *attachment = attachment_tmp;
8d64371b 12036 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
a6b151f1
DJ
12037 }
12038
12039 return ret;
12040}
12041
dd194f6b 12042/* See declaration.h. */
80152258 12043
dd194f6b
PA
12044void
12045readahead_cache::invalidate ()
80152258 12046{
dd194f6b 12047 this->fd = -1;
80152258
PA
12048}
12049
dd194f6b 12050/* See declaration.h. */
80152258 12051
dd194f6b
PA
12052void
12053readahead_cache::invalidate_fd (int fd)
80152258 12054{
dd194f6b
PA
12055 if (this->fd == fd)
12056 this->fd = -1;
80152258
PA
12057}
12058
15a201c8
GB
12059/* Set the filesystem remote_hostio functions that take FILENAME
12060 arguments will use. Return 0 on success, or -1 if an error
12061 occurs (and set *REMOTE_ERRNO). */
12062
6b8edb51
PA
12063int
12064remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12065 int *remote_errno)
15a201c8
GB
12066{
12067 struct remote_state *rs = get_remote_state ();
12068 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
8d64371b 12069 char *p = rs->buf.data ();
15a201c8
GB
12070 int left = get_remote_packet_size () - 1;
12071 char arg[9];
12072 int ret;
12073
12074 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12075 return 0;
12076
12077 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12078 return 0;
12079
12080 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12081
12082 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12083 remote_buffer_add_string (&p, &left, arg);
12084
8d64371b 12085 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
15a201c8
GB
12086 remote_errno, NULL, NULL);
12087
12088 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12089 return 0;
12090
12091 if (ret == 0)
12092 rs->fs_pid = required_pid;
12093
12094 return ret;
12095}
12096
12e2a5fd 12097/* Implementation of to_fileio_open. */
a6b151f1 12098
6b8edb51
PA
12099int
12100remote_target::remote_hostio_open (inferior *inf, const char *filename,
12101 int flags, int mode, int warn_if_slow,
12102 int *remote_errno)
a6b151f1
DJ
12103{
12104 struct remote_state *rs = get_remote_state ();
8d64371b 12105 char *p = rs->buf.data ();
a6b151f1
DJ
12106 int left = get_remote_packet_size () - 1;
12107
4313b8c0
GB
12108 if (warn_if_slow)
12109 {
12110 static int warning_issued = 0;
12111
12112 printf_unfiltered (_("Reading %s from remote target...\n"),
12113 filename);
12114
12115 if (!warning_issued)
12116 {
12117 warning (_("File transfers from remote targets can be slow."
12118 " Use \"set sysroot\" to access files locally"
12119 " instead."));
12120 warning_issued = 1;
12121 }
12122 }
12123
15a201c8
GB
12124 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12125 return -1;
12126
a6b151f1
DJ
12127 remote_buffer_add_string (&p, &left, "vFile:open:");
12128
12129 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12130 strlen (filename));
12131 remote_buffer_add_string (&p, &left, ",");
12132
12133 remote_buffer_add_int (&p, &left, flags);
12134 remote_buffer_add_string (&p, &left, ",");
12135
12136 remote_buffer_add_int (&p, &left, mode);
12137
8d64371b 12138 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
a6b151f1
DJ
12139 remote_errno, NULL, NULL);
12140}
12141
f6ac5f3d
PA
12142int
12143remote_target::fileio_open (struct inferior *inf, const char *filename,
12144 int flags, int mode, int warn_if_slow,
12145 int *remote_errno)
12146{
6b8edb51 12147 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
f6ac5f3d
PA
12148 remote_errno);
12149}
12150
12e2a5fd 12151/* Implementation of to_fileio_pwrite. */
a6b151f1 12152
6b8edb51
PA
12153int
12154remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12155 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
12156{
12157 struct remote_state *rs = get_remote_state ();
8d64371b 12158 char *p = rs->buf.data ();
a6b151f1
DJ
12159 int left = get_remote_packet_size ();
12160 int out_len;
12161
dd194f6b 12162 rs->readahead_cache.invalidate_fd (fd);
80152258 12163
a6b151f1
DJ
12164 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12165
12166 remote_buffer_add_int (&p, &left, fd);
12167 remote_buffer_add_string (&p, &left, ",");
12168
12169 remote_buffer_add_int (&p, &left, offset);
12170 remote_buffer_add_string (&p, &left, ",");
12171
124e13d9 12172 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
8d64371b
TT
12173 (get_remote_packet_size ()
12174 - (p - rs->buf.data ())));
a6b151f1 12175
8d64371b 12176 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
a6b151f1
DJ
12177 remote_errno, NULL, NULL);
12178}
12179
f6ac5f3d
PA
12180int
12181remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12182 ULONGEST offset, int *remote_errno)
12183{
6b8edb51 12184 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
f6ac5f3d
PA
12185}
12186
80152258
PA
12187/* Helper for the implementation of to_fileio_pread. Read the file
12188 from the remote side with vFile:pread. */
a6b151f1 12189
6b8edb51
PA
12190int
12191remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12192 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
12193{
12194 struct remote_state *rs = get_remote_state ();
8d64371b 12195 char *p = rs->buf.data ();
a6b151f1
DJ
12196 char *attachment;
12197 int left = get_remote_packet_size ();
12198 int ret, attachment_len;
12199 int read_len;
12200
12201 remote_buffer_add_string (&p, &left, "vFile:pread:");
12202
12203 remote_buffer_add_int (&p, &left, fd);
12204 remote_buffer_add_string (&p, &left, ",");
12205
12206 remote_buffer_add_int (&p, &left, len);
12207 remote_buffer_add_string (&p, &left, ",");
12208
12209 remote_buffer_add_int (&p, &left, offset);
12210
8d64371b 12211 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
a6b151f1
DJ
12212 remote_errno, &attachment,
12213 &attachment_len);
12214
12215 if (ret < 0)
12216 return ret;
12217
bc20a4af 12218 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
12219 read_buf, len);
12220 if (read_len != ret)
12221 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12222
12223 return ret;
12224}
12225
dd194f6b 12226/* See declaration.h. */
80152258 12227
dd194f6b
PA
12228int
12229readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12230 ULONGEST offset)
80152258 12231{
dd194f6b
PA
12232 if (this->fd == fd
12233 && this->offset <= offset
12234 && offset < this->offset + this->bufsize)
80152258 12235 {
dd194f6b 12236 ULONGEST max = this->offset + this->bufsize;
80152258
PA
12237
12238 if (offset + len > max)
12239 len = max - offset;
12240
dd194f6b 12241 memcpy (read_buf, this->buf + offset - this->offset, len);
80152258
PA
12242 return len;
12243 }
12244
12245 return 0;
12246}
12247
12248/* Implementation of to_fileio_pread. */
12249
6b8edb51
PA
12250int
12251remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12252 ULONGEST offset, int *remote_errno)
80152258
PA
12253{
12254 int ret;
12255 struct remote_state *rs = get_remote_state ();
dd194f6b 12256 readahead_cache *cache = &rs->readahead_cache;
80152258 12257
dd194f6b 12258 ret = cache->pread (fd, read_buf, len, offset);
80152258
PA
12259 if (ret > 0)
12260 {
12261 cache->hit_count++;
12262
12263 if (remote_debug)
12264 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
12265 pulongest (cache->hit_count));
12266 return ret;
12267 }
12268
12269 cache->miss_count++;
12270 if (remote_debug)
12271 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
12272 pulongest (cache->miss_count));
12273
12274 cache->fd = fd;
12275 cache->offset = offset;
12276 cache->bufsize = get_remote_packet_size ();
224c3ddb 12277 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258 12278
6b8edb51 12279 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
80152258
PA
12280 cache->offset, remote_errno);
12281 if (ret <= 0)
12282 {
dd194f6b 12283 cache->invalidate_fd (fd);
80152258
PA
12284 return ret;
12285 }
12286
12287 cache->bufsize = ret;
dd194f6b 12288 return cache->pread (fd, read_buf, len, offset);
80152258
PA
12289}
12290
f6ac5f3d
PA
12291int
12292remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12293 ULONGEST offset, int *remote_errno)
12294{
6b8edb51 12295 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
f6ac5f3d
PA
12296}
12297
12e2a5fd 12298/* Implementation of to_fileio_close. */
a6b151f1 12299
6b8edb51
PA
12300int
12301remote_target::remote_hostio_close (int fd, int *remote_errno)
a6b151f1
DJ
12302{
12303 struct remote_state *rs = get_remote_state ();
8d64371b 12304 char *p = rs->buf.data ();
a6b151f1
DJ
12305 int left = get_remote_packet_size () - 1;
12306
dd194f6b 12307 rs->readahead_cache.invalidate_fd (fd);
80152258 12308
a6b151f1
DJ
12309 remote_buffer_add_string (&p, &left, "vFile:close:");
12310
12311 remote_buffer_add_int (&p, &left, fd);
12312
8d64371b 12313 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
a6b151f1
DJ
12314 remote_errno, NULL, NULL);
12315}
12316
f6ac5f3d
PA
12317int
12318remote_target::fileio_close (int fd, int *remote_errno)
12319{
6b8edb51 12320 return remote_hostio_close (fd, remote_errno);
f6ac5f3d
PA
12321}
12322
12e2a5fd 12323/* Implementation of to_fileio_unlink. */
a6b151f1 12324
6b8edb51
PA
12325int
12326remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12327 int *remote_errno)
a6b151f1
DJ
12328{
12329 struct remote_state *rs = get_remote_state ();
8d64371b 12330 char *p = rs->buf.data ();
a6b151f1
DJ
12331 int left = get_remote_packet_size () - 1;
12332
15a201c8
GB
12333 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12334 return -1;
12335
a6b151f1
DJ
12336 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12337
12338 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12339 strlen (filename));
12340
8d64371b 12341 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
a6b151f1
DJ
12342 remote_errno, NULL, NULL);
12343}
12344
f6ac5f3d
PA
12345int
12346remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12347 int *remote_errno)
12348{
6b8edb51 12349 return remote_hostio_unlink (inf, filename, remote_errno);
f6ac5f3d
PA
12350}
12351
12e2a5fd 12352/* Implementation of to_fileio_readlink. */
b9e7b9c3 12353
f6ac5f3d
PA
12354gdb::optional<std::string>
12355remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12356 int *remote_errno)
b9e7b9c3
UW
12357{
12358 struct remote_state *rs = get_remote_state ();
8d64371b 12359 char *p = rs->buf.data ();
b9e7b9c3
UW
12360 char *attachment;
12361 int left = get_remote_packet_size ();
12362 int len, attachment_len;
12363 int read_len;
b9e7b9c3 12364
15a201c8 12365 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
e0d3522b 12366 return {};
15a201c8 12367
b9e7b9c3
UW
12368 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12369
12370 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12371 strlen (filename));
12372
8d64371b 12373 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
b9e7b9c3
UW
12374 remote_errno, &attachment,
12375 &attachment_len);
12376
12377 if (len < 0)
e0d3522b 12378 return {};
b9e7b9c3 12379
e0d3522b 12380 std::string ret (len, '\0');
b9e7b9c3 12381
bc20a4af 12382 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
e0d3522b 12383 (gdb_byte *) &ret[0], len);
b9e7b9c3
UW
12384 if (read_len != len)
12385 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12386
b9e7b9c3
UW
12387 return ret;
12388}
12389
12e2a5fd 12390/* Implementation of to_fileio_fstat. */
0a93529c 12391
f6ac5f3d
PA
12392int
12393remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
0a93529c
GB
12394{
12395 struct remote_state *rs = get_remote_state ();
8d64371b 12396 char *p = rs->buf.data ();
0a93529c
GB
12397 int left = get_remote_packet_size ();
12398 int attachment_len, ret;
12399 char *attachment;
12400 struct fio_stat fst;
12401 int read_len;
12402
464b0089
GB
12403 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12404
12405 remote_buffer_add_int (&p, &left, fd);
12406
8d64371b 12407 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
464b0089
GB
12408 remote_errno, &attachment,
12409 &attachment_len);
12410 if (ret < 0)
0a93529c 12411 {
464b0089
GB
12412 if (*remote_errno != FILEIO_ENOSYS)
12413 return ret;
12414
0a93529c
GB
12415 /* Strictly we should return -1, ENOSYS here, but when
12416 "set sysroot remote:" was implemented in August 2008
12417 BFD's need for a stat function was sidestepped with
12418 this hack. This was not remedied until March 2015
12419 so we retain the previous behavior to avoid breaking
12420 compatibility.
12421
12422 Note that the memset is a March 2015 addition; older
12423 GDBs set st_size *and nothing else* so the structure
12424 would have garbage in all other fields. This might
12425 break something but retaining the previous behavior
12426 here would be just too wrong. */
12427
12428 memset (st, 0, sizeof (struct stat));
12429 st->st_size = INT_MAX;
12430 return 0;
12431 }
12432
0a93529c
GB
12433 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12434 (gdb_byte *) &fst, sizeof (fst));
12435
12436 if (read_len != ret)
12437 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12438
12439 if (read_len != sizeof (fst))
12440 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12441 read_len, (int) sizeof (fst));
12442
12443 remote_fileio_to_host_stat (&fst, st);
12444
12445 return 0;
12446}
12447
12e2a5fd 12448/* Implementation of to_filesystem_is_local. */
e3dd7556 12449
57810aa7 12450bool
f6ac5f3d 12451remote_target::filesystem_is_local ()
e3dd7556
GB
12452{
12453 /* Valgrind GDB presents itself as a remote target but works
12454 on the local filesystem: it does not implement remote get
12455 and users are not expected to set a sysroot. To handle
12456 this case we treat the remote filesystem as local if the
12457 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12458 does not support vFile:open. */
a3be80c3 12459 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
12460 {
12461 enum packet_support ps = packet_support (PACKET_vFile_open);
12462
12463 if (ps == PACKET_SUPPORT_UNKNOWN)
12464 {
12465 int fd, remote_errno;
12466
12467 /* Try opening a file to probe support. The supplied
12468 filename is irrelevant, we only care about whether
12469 the stub recognizes the packet or not. */
6b8edb51 12470 fd = remote_hostio_open (NULL, "just probing",
4313b8c0 12471 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
12472 &remote_errno);
12473
12474 if (fd >= 0)
6b8edb51 12475 remote_hostio_close (fd, &remote_errno);
e3dd7556
GB
12476
12477 ps = packet_support (PACKET_vFile_open);
12478 }
12479
12480 if (ps == PACKET_DISABLE)
12481 {
12482 static int warning_issued = 0;
12483
12484 if (!warning_issued)
12485 {
12486 warning (_("remote target does not support file"
12487 " transfer, attempting to access files"
12488 " from local filesystem."));
12489 warning_issued = 1;
12490 }
12491
57810aa7 12492 return true;
e3dd7556
GB
12493 }
12494 }
12495
57810aa7 12496 return false;
e3dd7556
GB
12497}
12498
a6b151f1
DJ
12499static int
12500remote_fileio_errno_to_host (int errnum)
12501{
12502 switch (errnum)
12503 {
12504 case FILEIO_EPERM:
dda83cd7 12505 return EPERM;
a6b151f1 12506 case FILEIO_ENOENT:
dda83cd7 12507 return ENOENT;
a6b151f1 12508 case FILEIO_EINTR:
dda83cd7 12509 return EINTR;
a6b151f1 12510 case FILEIO_EIO:
dda83cd7 12511 return EIO;
a6b151f1 12512 case FILEIO_EBADF:
dda83cd7 12513 return EBADF;
a6b151f1 12514 case FILEIO_EACCES:
dda83cd7 12515 return EACCES;
a6b151f1 12516 case FILEIO_EFAULT:
dda83cd7 12517 return EFAULT;
a6b151f1 12518 case FILEIO_EBUSY:
dda83cd7 12519 return EBUSY;
a6b151f1 12520 case FILEIO_EEXIST:
dda83cd7 12521 return EEXIST;
a6b151f1 12522 case FILEIO_ENODEV:
dda83cd7 12523 return ENODEV;
a6b151f1 12524 case FILEIO_ENOTDIR:
dda83cd7 12525 return ENOTDIR;
a6b151f1 12526 case FILEIO_EISDIR:
dda83cd7 12527 return EISDIR;
a6b151f1 12528 case FILEIO_EINVAL:
dda83cd7 12529 return EINVAL;
a6b151f1 12530 case FILEIO_ENFILE:
dda83cd7 12531 return ENFILE;
a6b151f1 12532 case FILEIO_EMFILE:
dda83cd7 12533 return EMFILE;
a6b151f1 12534 case FILEIO_EFBIG:
dda83cd7 12535 return EFBIG;
a6b151f1 12536 case FILEIO_ENOSPC:
dda83cd7 12537 return ENOSPC;
a6b151f1 12538 case FILEIO_ESPIPE:
dda83cd7 12539 return ESPIPE;
a6b151f1 12540 case FILEIO_EROFS:
dda83cd7 12541 return EROFS;
a6b151f1 12542 case FILEIO_ENOSYS:
dda83cd7 12543 return ENOSYS;
a6b151f1 12544 case FILEIO_ENAMETOOLONG:
dda83cd7 12545 return ENAMETOOLONG;
a6b151f1
DJ
12546 }
12547 return -1;
12548}
12549
12550static char *
12551remote_hostio_error (int errnum)
12552{
12553 int host_error = remote_fileio_errno_to_host (errnum);
12554
12555 if (host_error == -1)
12556 error (_("Unknown remote I/O error %d"), errnum);
12557 else
12558 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12559}
12560
440b7aec
PA
12561/* A RAII wrapper around a remote file descriptor. */
12562
12563class scoped_remote_fd
a6b151f1 12564{
440b7aec 12565public:
6b8edb51
PA
12566 scoped_remote_fd (remote_target *remote, int fd)
12567 : m_remote (remote), m_fd (fd)
440b7aec
PA
12568 {
12569 }
a6b151f1 12570
440b7aec
PA
12571 ~scoped_remote_fd ()
12572 {
12573 if (m_fd != -1)
12574 {
12575 try
12576 {
12577 int remote_errno;
6b8edb51 12578 m_remote->remote_hostio_close (m_fd, &remote_errno);
440b7aec
PA
12579 }
12580 catch (...)
12581 {
12582 /* Swallow exception before it escapes the dtor. If
12583 something goes wrong, likely the connection is gone,
12584 and there's nothing else that can be done. */
12585 }
12586 }
12587 }
12588
12589 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12590
12591 /* Release ownership of the file descriptor, and return it. */
88a774b9 12592 ATTRIBUTE_UNUSED_RESULT int release () noexcept
440b7aec
PA
12593 {
12594 int fd = m_fd;
12595 m_fd = -1;
12596 return fd;
12597 }
12598
12599 /* Return the owned file descriptor. */
12600 int get () const noexcept
12601 {
12602 return m_fd;
12603 }
12604
12605private:
6b8edb51
PA
12606 /* The remote target. */
12607 remote_target *m_remote;
12608
440b7aec
PA
12609 /* The owned remote I/O file descriptor. */
12610 int m_fd;
12611};
a6b151f1
DJ
12612
12613void
12614remote_file_put (const char *local_file, const char *remote_file, int from_tty)
6b8edb51
PA
12615{
12616 remote_target *remote = get_current_remote_target ();
12617
12618 if (remote == nullptr)
12619 error (_("command can only be used with remote target"));
12620
12621 remote->remote_file_put (local_file, remote_file, from_tty);
12622}
12623
12624void
12625remote_target::remote_file_put (const char *local_file, const char *remote_file,
12626 int from_tty)
a6b151f1 12627{
440b7aec 12628 int retcode, remote_errno, bytes, io_size;
a6b151f1
DJ
12629 int bytes_in_buffer;
12630 int saw_eof;
12631 ULONGEST offset;
a6b151f1 12632
d419f42d 12633 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
12634 if (file == NULL)
12635 perror_with_name (local_file);
a6b151f1 12636
440b7aec 12637 scoped_remote_fd fd
6b8edb51
PA
12638 (this, remote_hostio_open (NULL,
12639 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12640 | FILEIO_O_TRUNC),
12641 0700, 0, &remote_errno));
440b7aec 12642 if (fd.get () == -1)
a6b151f1
DJ
12643 remote_hostio_error (remote_errno);
12644
12645 /* Send up to this many bytes at once. They won't all fit in the
12646 remote packet limit, so we'll transfer slightly fewer. */
12647 io_size = get_remote_packet_size ();
5ca3b260 12648 gdb::byte_vector buffer (io_size);
a6b151f1 12649
a6b151f1
DJ
12650 bytes_in_buffer = 0;
12651 saw_eof = 0;
12652 offset = 0;
12653 while (bytes_in_buffer || !saw_eof)
12654 {
12655 if (!saw_eof)
12656 {
5ca3b260 12657 bytes = fread (buffer.data () + bytes_in_buffer, 1,
3e43a32a 12658 io_size - bytes_in_buffer,
d419f42d 12659 file.get ());
a6b151f1
DJ
12660 if (bytes == 0)
12661 {
d419f42d 12662 if (ferror (file.get ()))
a6b151f1
DJ
12663 error (_("Error reading %s."), local_file);
12664 else
12665 {
12666 /* EOF. Unless there is something still in the
12667 buffer from the last iteration, we are done. */
12668 saw_eof = 1;
12669 if (bytes_in_buffer == 0)
12670 break;
12671 }
12672 }
12673 }
12674 else
12675 bytes = 0;
12676
12677 bytes += bytes_in_buffer;
12678 bytes_in_buffer = 0;
12679
5ca3b260 12680 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
3e43a32a 12681 offset, &remote_errno);
a6b151f1
DJ
12682
12683 if (retcode < 0)
12684 remote_hostio_error (remote_errno);
12685 else if (retcode == 0)
12686 error (_("Remote write of %d bytes returned 0!"), bytes);
12687 else if (retcode < bytes)
12688 {
12689 /* Short write. Save the rest of the read data for the next
12690 write. */
12691 bytes_in_buffer = bytes - retcode;
5ca3b260 12692 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
a6b151f1
DJ
12693 }
12694
12695 offset += retcode;
12696 }
12697
6b8edb51 12698 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
12699 remote_hostio_error (remote_errno);
12700
12701 if (from_tty)
12702 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
a6b151f1
DJ
12703}
12704
12705void
12706remote_file_get (const char *remote_file, const char *local_file, int from_tty)
6b8edb51
PA
12707{
12708 remote_target *remote = get_current_remote_target ();
12709
12710 if (remote == nullptr)
12711 error (_("command can only be used with remote target"));
12712
12713 remote->remote_file_get (remote_file, local_file, from_tty);
12714}
12715
12716void
12717remote_target::remote_file_get (const char *remote_file, const char *local_file,
12718 int from_tty)
a6b151f1 12719{
440b7aec 12720 int remote_errno, bytes, io_size;
a6b151f1 12721 ULONGEST offset;
a6b151f1 12722
440b7aec 12723 scoped_remote_fd fd
6b8edb51
PA
12724 (this, remote_hostio_open (NULL,
12725 remote_file, FILEIO_O_RDONLY, 0, 0,
12726 &remote_errno));
440b7aec 12727 if (fd.get () == -1)
a6b151f1
DJ
12728 remote_hostio_error (remote_errno);
12729
d419f42d 12730 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
12731 if (file == NULL)
12732 perror_with_name (local_file);
a6b151f1
DJ
12733
12734 /* Send up to this many bytes at once. They won't all fit in the
12735 remote packet limit, so we'll transfer slightly fewer. */
12736 io_size = get_remote_packet_size ();
5ca3b260 12737 gdb::byte_vector buffer (io_size);
a6b151f1 12738
a6b151f1
DJ
12739 offset = 0;
12740 while (1)
12741 {
5ca3b260 12742 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
440b7aec 12743 &remote_errno);
a6b151f1
DJ
12744 if (bytes == 0)
12745 /* Success, but no bytes, means end-of-file. */
12746 break;
12747 if (bytes == -1)
12748 remote_hostio_error (remote_errno);
12749
12750 offset += bytes;
12751
5ca3b260 12752 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
a6b151f1
DJ
12753 if (bytes == 0)
12754 perror_with_name (local_file);
12755 }
12756
6b8edb51 12757 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
12758 remote_hostio_error (remote_errno);
12759
12760 if (from_tty)
12761 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
a6b151f1
DJ
12762}
12763
12764void
12765remote_file_delete (const char *remote_file, int from_tty)
12766{
6b8edb51 12767 remote_target *remote = get_current_remote_target ();
a6b151f1 12768
6b8edb51 12769 if (remote == nullptr)
a6b151f1
DJ
12770 error (_("command can only be used with remote target"));
12771
6b8edb51
PA
12772 remote->remote_file_delete (remote_file, from_tty);
12773}
12774
12775void
12776remote_target::remote_file_delete (const char *remote_file, int from_tty)
12777{
12778 int retcode, remote_errno;
12779
12780 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
a6b151f1
DJ
12781 if (retcode == -1)
12782 remote_hostio_error (remote_errno);
12783
12784 if (from_tty)
12785 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12786}
12787
12788static void
ac88e2de 12789remote_put_command (const char *args, int from_tty)
a6b151f1 12790{
d1a41061
PP
12791 if (args == NULL)
12792 error_no_arg (_("file to put"));
12793
773a1edc 12794 gdb_argv argv (args);
a6b151f1
DJ
12795 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12796 error (_("Invalid parameters to remote put"));
12797
12798 remote_file_put (argv[0], argv[1], from_tty);
a6b151f1
DJ
12799}
12800
12801static void
ac88e2de 12802remote_get_command (const char *args, int from_tty)
a6b151f1 12803{
d1a41061
PP
12804 if (args == NULL)
12805 error_no_arg (_("file to get"));
12806
773a1edc 12807 gdb_argv argv (args);
a6b151f1
DJ
12808 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12809 error (_("Invalid parameters to remote get"));
12810
12811 remote_file_get (argv[0], argv[1], from_tty);
a6b151f1
DJ
12812}
12813
12814static void
ac88e2de 12815remote_delete_command (const char *args, int from_tty)
a6b151f1 12816{
d1a41061
PP
12817 if (args == NULL)
12818 error_no_arg (_("file to delete"));
12819
773a1edc 12820 gdb_argv argv (args);
a6b151f1
DJ
12821 if (argv[0] == NULL || argv[1] != NULL)
12822 error (_("Invalid parameters to remote delete"));
12823
12824 remote_file_delete (argv[0], from_tty);
a6b151f1
DJ
12825}
12826
57810aa7 12827bool
f6ac5f3d 12828remote_target::can_execute_reverse ()
b2175913 12829{
4082afcc
PA
12830 if (packet_support (PACKET_bs) == PACKET_ENABLE
12831 || packet_support (PACKET_bc) == PACKET_ENABLE)
57810aa7 12832 return true;
40ab02ce 12833 else
57810aa7 12834 return false;
b2175913
MS
12835}
12836
57810aa7 12837bool
f6ac5f3d 12838remote_target::supports_non_stop ()
74531fed 12839{
57810aa7 12840 return true;
74531fed
PA
12841}
12842
57810aa7 12843bool
f6ac5f3d 12844remote_target::supports_disable_randomization ()
03583c20
UW
12845{
12846 /* Only supported in extended mode. */
57810aa7 12847 return false;
03583c20
UW
12848}
12849
57810aa7 12850bool
f6ac5f3d 12851remote_target::supports_multi_process ()
8a305172
PA
12852{
12853 struct remote_state *rs = get_remote_state ();
a744cf53 12854
8020350c 12855 return remote_multi_process_p (rs);
8a305172
PA
12856}
12857
70221824 12858static int
f6ac5f3d 12859remote_supports_cond_tracepoints ()
782b2b07 12860{
4082afcc 12861 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
12862}
12863
57810aa7 12864bool
f6ac5f3d 12865remote_target::supports_evaluation_of_breakpoint_conditions ()
3788aec7 12866{
4082afcc 12867 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
12868}
12869
70221824 12870static int
f6ac5f3d 12871remote_supports_fast_tracepoints ()
7a697b8d 12872{
4082afcc 12873 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
12874}
12875
0fb4aa4b 12876static int
f6ac5f3d 12877remote_supports_static_tracepoints ()
0fb4aa4b 12878{
4082afcc 12879 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
12880}
12881
1e4d1764 12882static int
f6ac5f3d 12883remote_supports_install_in_trace ()
1e4d1764 12884{
4082afcc 12885 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
12886}
12887
57810aa7 12888bool
f6ac5f3d 12889remote_target::supports_enable_disable_tracepoint ()
d248b706 12890{
4082afcc
PA
12891 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12892 == PACKET_ENABLE);
d248b706
KY
12893}
12894
57810aa7 12895bool
f6ac5f3d 12896remote_target::supports_string_tracing ()
3065dfb6 12897{
4082afcc 12898 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
12899}
12900
57810aa7 12901bool
f6ac5f3d 12902remote_target::can_run_breakpoint_commands ()
d3ce09f5 12903{
4082afcc 12904 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
12905}
12906
f6ac5f3d
PA
12907void
12908remote_target::trace_init ()
35b1e5cc 12909{
b6bb3468
PA
12910 struct remote_state *rs = get_remote_state ();
12911
35b1e5cc 12912 putpkt ("QTinit");
b6bb3468 12913 remote_get_noisy_reply ();
8d64371b 12914 if (strcmp (rs->buf.data (), "OK") != 0)
35b1e5cc
SS
12915 error (_("Target does not support this command."));
12916}
12917
409873ef
SS
12918/* Recursive routine to walk through command list including loops, and
12919 download packets for each command. */
12920
6b8edb51
PA
12921void
12922remote_target::remote_download_command_source (int num, ULONGEST addr,
12923 struct command_line *cmds)
409873ef
SS
12924{
12925 struct remote_state *rs = get_remote_state ();
12926 struct command_line *cmd;
12927
12928 for (cmd = cmds; cmd; cmd = cmd->next)
12929 {
0df8b418 12930 QUIT; /* Allow user to bail out with ^C. */
8d64371b 12931 strcpy (rs->buf.data (), "QTDPsrc:");
409873ef 12932 encode_source_string (num, addr, "cmd", cmd->line,
8d64371b
TT
12933 rs->buf.data () + strlen (rs->buf.data ()),
12934 rs->buf.size () - strlen (rs->buf.data ()));
409873ef 12935 putpkt (rs->buf);
b6bb3468 12936 remote_get_noisy_reply ();
8d64371b 12937 if (strcmp (rs->buf.data (), "OK"))
409873ef
SS
12938 warning (_("Target does not support source download."));
12939
12940 if (cmd->control_type == while_control
12941 || cmd->control_type == while_stepping_control)
12942 {
12973681 12943 remote_download_command_source (num, addr, cmd->body_list_0.get ());
409873ef 12944
0df8b418 12945 QUIT; /* Allow user to bail out with ^C. */
8d64371b 12946 strcpy (rs->buf.data (), "QTDPsrc:");
409873ef 12947 encode_source_string (num, addr, "cmd", "end",
8d64371b
TT
12948 rs->buf.data () + strlen (rs->buf.data ()),
12949 rs->buf.size () - strlen (rs->buf.data ()));
409873ef 12950 putpkt (rs->buf);
b6bb3468 12951 remote_get_noisy_reply ();
8d64371b 12952 if (strcmp (rs->buf.data (), "OK"))
409873ef
SS
12953 warning (_("Target does not support source download."));
12954 }
12955 }
12956}
12957
f6ac5f3d
PA
12958void
12959remote_target::download_tracepoint (struct bp_location *loc)
35b1e5cc
SS
12960{
12961 CORE_ADDR tpaddr;
409873ef 12962 char addrbuf[40];
b44ec619
SM
12963 std::vector<std::string> tdp_actions;
12964 std::vector<std::string> stepping_actions;
35b1e5cc 12965 char *pkt;
e8ba3115 12966 struct breakpoint *b = loc->owner;
d9b3f62e 12967 struct tracepoint *t = (struct tracepoint *) b;
b6bb3468 12968 struct remote_state *rs = get_remote_state ();
3df3a985 12969 int ret;
ff36536c 12970 const char *err_msg = _("Tracepoint packet too large for target.");
3df3a985
PFC
12971 size_t size_left;
12972
12973 /* We use a buffer other than rs->buf because we'll build strings
12974 across multiple statements, and other statements in between could
12975 modify rs->buf. */
12976 gdb::char_vector buf (get_remote_packet_size ());
35b1e5cc 12977
dc673c81 12978 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
12979
12980 tpaddr = loc->address;
53807e9f 12981 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
3df3a985
PFC
12982 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
12983 b->number, addrbuf, /* address */
12984 (b->enable_state == bp_enabled ? 'E' : 'D'),
12985 t->step_count, t->pass_count);
12986
12987 if (ret < 0 || ret >= buf.size ())
a7f25a84 12988 error ("%s", err_msg);
3df3a985 12989
e8ba3115
YQ
12990 /* Fast tracepoints are mostly handled by the target, but we can
12991 tell the target how big of an instruction block should be moved
12992 around. */
12993 if (b->type == bp_fast_tracepoint)
12994 {
12995 /* Only test for support at download time; we may not know
12996 target capabilities at definition time. */
12997 if (remote_supports_fast_tracepoints ())
35b1e5cc 12998 {
6b940e6a
PL
12999 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13000 NULL))
3df3a985
PFC
13001 {
13002 size_left = buf.size () - strlen (buf.data ());
13003 ret = snprintf (buf.data () + strlen (buf.data ()),
13004 size_left, ":F%x",
13005 gdb_insn_length (loc->gdbarch, tpaddr));
13006
13007 if (ret < 0 || ret >= size_left)
a7f25a84 13008 error ("%s", err_msg);
3df3a985 13009 }
35b1e5cc 13010 else
e8ba3115
YQ
13011 /* If it passed validation at definition but fails now,
13012 something is very wrong. */
13013 internal_error (__FILE__, __LINE__,
13014 _("Fast tracepoint not "
13015 "valid during download"));
35b1e5cc 13016 }
e8ba3115
YQ
13017 else
13018 /* Fast tracepoints are functionally identical to regular
13019 tracepoints, so don't take lack of support as a reason to
13020 give up on the trace run. */
13021 warning (_("Target does not support fast tracepoints, "
13022 "downloading %d as regular tracepoint"), b->number);
13023 }
13024 else if (b->type == bp_static_tracepoint)
13025 {
13026 /* Only test for support at download time; we may not know
13027 target capabilities at definition time. */
13028 if (remote_supports_static_tracepoints ())
0fb4aa4b 13029 {
e8ba3115 13030 struct static_tracepoint_marker marker;
0fb4aa4b 13031
e8ba3115 13032 if (target_static_tracepoint_marker_at (tpaddr, &marker))
3df3a985
PFC
13033 {
13034 size_left = buf.size () - strlen (buf.data ());
13035 ret = snprintf (buf.data () + strlen (buf.data ()),
13036 size_left, ":S");
13037
13038 if (ret < 0 || ret >= size_left)
a7f25a84 13039 error ("%s", err_msg);
3df3a985 13040 }
0fb4aa4b 13041 else
e8ba3115 13042 error (_("Static tracepoint not valid during download"));
0fb4aa4b 13043 }
e8ba3115
YQ
13044 else
13045 /* Fast tracepoints are functionally identical to regular
13046 tracepoints, so don't take lack of support as a reason
13047 to give up on the trace run. */
13048 error (_("Target does not support static tracepoints"));
13049 }
13050 /* If the tracepoint has a conditional, make it into an agent
13051 expression and append to the definition. */
13052 if (loc->cond)
13053 {
13054 /* Only test support at download time, we may not know target
13055 capabilities at definition time. */
13056 if (remote_supports_cond_tracepoints ())
35b1e5cc 13057 {
3df3a985
PFC
13058 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13059 loc->cond.get ());
13060
13061 size_left = buf.size () - strlen (buf.data ());
13062
13063 ret = snprintf (buf.data () + strlen (buf.data ()),
13064 size_left, ":X%x,", aexpr->len);
13065
13066 if (ret < 0 || ret >= size_left)
a7f25a84 13067 error ("%s", err_msg);
3df3a985
PFC
13068
13069 size_left = buf.size () - strlen (buf.data ());
13070
13071 /* Two bytes to encode each aexpr byte, plus the terminating
13072 null byte. */
13073 if (aexpr->len * 2 + 1 > size_left)
a7f25a84 13074 error ("%s", err_msg);
3df3a985
PFC
13075
13076 pkt = buf.data () + strlen (buf.data ());
13077
b44ec619 13078 for (int ndx = 0; ndx < aexpr->len; ++ndx)
e8ba3115
YQ
13079 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13080 *pkt = '\0';
35b1e5cc 13081 }
e8ba3115
YQ
13082 else
13083 warning (_("Target does not support conditional tracepoints, "
13084 "ignoring tp %d cond"), b->number);
13085 }
35b1e5cc 13086
d9b3f62e 13087 if (b->commands || *default_collect)
3df3a985
PFC
13088 {
13089 size_left = buf.size () - strlen (buf.data ());
13090
13091 ret = snprintf (buf.data () + strlen (buf.data ()),
13092 size_left, "-");
13093
13094 if (ret < 0 || ret >= size_left)
a7f25a84 13095 error ("%s", err_msg);
3df3a985
PFC
13096 }
13097
13098 putpkt (buf.data ());
b6bb3468 13099 remote_get_noisy_reply ();
8d64371b 13100 if (strcmp (rs->buf.data (), "OK"))
e8ba3115 13101 error (_("Target does not support tracepoints."));
35b1e5cc 13102
e8ba3115 13103 /* do_single_steps (t); */
b44ec619
SM
13104 for (auto action_it = tdp_actions.begin ();
13105 action_it != tdp_actions.end (); action_it++)
e8ba3115 13106 {
b44ec619
SM
13107 QUIT; /* Allow user to bail out with ^C. */
13108
aa6f3694 13109 bool has_more = ((action_it + 1) != tdp_actions.end ()
b44ec619
SM
13110 || !stepping_actions.empty ());
13111
3df3a985
PFC
13112 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13113 b->number, addrbuf, /* address */
13114 action_it->c_str (),
13115 has_more ? '-' : 0);
13116
13117 if (ret < 0 || ret >= buf.size ())
a7f25a84 13118 error ("%s", err_msg);
3df3a985
PFC
13119
13120 putpkt (buf.data ());
b44ec619 13121 remote_get_noisy_reply ();
8d64371b 13122 if (strcmp (rs->buf.data (), "OK"))
b44ec619 13123 error (_("Error on target while setting tracepoints."));
e8ba3115 13124 }
409873ef 13125
05abfc39
PFC
13126 for (auto action_it = stepping_actions.begin ();
13127 action_it != stepping_actions.end (); action_it++)
13128 {
13129 QUIT; /* Allow user to bail out with ^C. */
13130
13131 bool is_first = action_it == stepping_actions.begin ();
aa6f3694 13132 bool has_more = (action_it + 1) != stepping_actions.end ();
05abfc39 13133
3df3a985
PFC
13134 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13135 b->number, addrbuf, /* address */
13136 is_first ? "S" : "",
13137 action_it->c_str (),
13138 has_more ? "-" : "");
13139
13140 if (ret < 0 || ret >= buf.size ())
a7f25a84 13141 error ("%s", err_msg);
3df3a985
PFC
13142
13143 putpkt (buf.data ());
05abfc39 13144 remote_get_noisy_reply ();
8d64371b 13145 if (strcmp (rs->buf.data (), "OK"))
05abfc39
PFC
13146 error (_("Error on target while setting tracepoints."));
13147 }
b44ec619 13148
4082afcc 13149 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 13150 {
f00aae0f 13151 if (b->location != NULL)
409873ef 13152 {
3df3a985
PFC
13153 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13154
13155 if (ret < 0 || ret >= buf.size ())
a7f25a84 13156 error ("%s", err_msg);
3df3a985 13157
f00aae0f 13158 encode_source_string (b->number, loc->address, "at",
d28cd78a 13159 event_location_to_string (b->location.get ()),
3df3a985
PFC
13160 buf.data () + strlen (buf.data ()),
13161 buf.size () - strlen (buf.data ()));
13162 putpkt (buf.data ());
b6bb3468 13163 remote_get_noisy_reply ();
8d64371b 13164 if (strcmp (rs->buf.data (), "OK"))
e8ba3115 13165 warning (_("Target does not support source download."));
409873ef 13166 }
e8ba3115
YQ
13167 if (b->cond_string)
13168 {
3df3a985
PFC
13169 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13170
13171 if (ret < 0 || ret >= buf.size ())
a7f25a84 13172 error ("%s", err_msg);
3df3a985 13173
e8ba3115 13174 encode_source_string (b->number, loc->address,
3df3a985
PFC
13175 "cond", b->cond_string,
13176 buf.data () + strlen (buf.data ()),
13177 buf.size () - strlen (buf.data ()));
13178 putpkt (buf.data ());
b6bb3468 13179 remote_get_noisy_reply ();
8d64371b 13180 if (strcmp (rs->buf.data (), "OK"))
e8ba3115
YQ
13181 warning (_("Target does not support source download."));
13182 }
13183 remote_download_command_source (b->number, loc->address,
13184 breakpoint_commands (b));
35b1e5cc 13185 }
35b1e5cc
SS
13186}
13187
57810aa7 13188bool
f6ac5f3d 13189remote_target::can_download_tracepoint ()
1e4d1764 13190{
1e51243a
PA
13191 struct remote_state *rs = get_remote_state ();
13192 struct trace_status *ts;
13193 int status;
13194
13195 /* Don't try to install tracepoints until we've relocated our
13196 symbols, and fetched and merged the target's tracepoint list with
13197 ours. */
13198 if (rs->starting_up)
57810aa7 13199 return false;
1e51243a
PA
13200
13201 ts = current_trace_status ();
f6ac5f3d 13202 status = get_trace_status (ts);
1e4d1764
YQ
13203
13204 if (status == -1 || !ts->running_known || !ts->running)
57810aa7 13205 return false;
1e4d1764
YQ
13206
13207 /* If we are in a tracing experiment, but remote stub doesn't support
13208 installing tracepoint in trace, we have to return. */
13209 if (!remote_supports_install_in_trace ())
57810aa7 13210 return false;
1e4d1764 13211
57810aa7 13212 return true;
1e4d1764
YQ
13213}
13214
13215
f6ac5f3d
PA
13216void
13217remote_target::download_trace_state_variable (const trace_state_variable &tsv)
35b1e5cc
SS
13218{
13219 struct remote_state *rs = get_remote_state ();
00bf0b85 13220 char *p;
35b1e5cc 13221
8d64371b 13222 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
c252925c
SM
13223 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13224 tsv.builtin);
8d64371b
TT
13225 p = rs->buf.data () + strlen (rs->buf.data ());
13226 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13227 >= get_remote_packet_size ())
00bf0b85 13228 error (_("Trace state variable name too long for tsv definition packet"));
c252925c 13229 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
00bf0b85 13230 *p++ = '\0';
35b1e5cc 13231 putpkt (rs->buf);
b6bb3468 13232 remote_get_noisy_reply ();
8d64371b 13233 if (rs->buf[0] == '\0')
ad91cd99 13234 error (_("Target does not support this command."));
8d64371b 13235 if (strcmp (rs->buf.data (), "OK") != 0)
ad91cd99 13236 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
13237}
13238
f6ac5f3d
PA
13239void
13240remote_target::enable_tracepoint (struct bp_location *location)
d248b706
KY
13241{
13242 struct remote_state *rs = get_remote_state ();
d248b706 13243
8d64371b 13244 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
53807e9f
TT
13245 location->owner->number,
13246 phex (location->address, sizeof (CORE_ADDR)));
d248b706 13247 putpkt (rs->buf);
b6bb3468 13248 remote_get_noisy_reply ();
8d64371b 13249 if (rs->buf[0] == '\0')
d248b706 13250 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
8d64371b 13251 if (strcmp (rs->buf.data (), "OK") != 0)
d248b706
KY
13252 error (_("Error on target while enabling tracepoint."));
13253}
13254
f6ac5f3d
PA
13255void
13256remote_target::disable_tracepoint (struct bp_location *location)
d248b706
KY
13257{
13258 struct remote_state *rs = get_remote_state ();
d248b706 13259
8d64371b 13260 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
53807e9f
TT
13261 location->owner->number,
13262 phex (location->address, sizeof (CORE_ADDR)));
d248b706 13263 putpkt (rs->buf);
b6bb3468 13264 remote_get_noisy_reply ();
8d64371b 13265 if (rs->buf[0] == '\0')
d248b706 13266 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
8d64371b 13267 if (strcmp (rs->buf.data (), "OK") != 0)
d248b706
KY
13268 error (_("Error on target while disabling tracepoint."));
13269}
13270
f6ac5f3d
PA
13271void
13272remote_target::trace_set_readonly_regions ()
35b1e5cc
SS
13273{
13274 asection *s;
13275 bfd_size_type size;
608bcef2 13276 bfd_vma vma;
35b1e5cc 13277 int anysecs = 0;
c2fa21f1 13278 int offset = 0;
35b1e5cc 13279
7e10abd1 13280 if (!current_program_space->exec_bfd ())
35b1e5cc
SS
13281 return; /* No information to give. */
13282
b6bb3468
PA
13283 struct remote_state *rs = get_remote_state ();
13284
8d64371b
TT
13285 strcpy (rs->buf.data (), "QTro");
13286 offset = strlen (rs->buf.data ());
7e10abd1 13287 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
35b1e5cc
SS
13288 {
13289 char tmp1[40], tmp2[40];
c2fa21f1 13290 int sec_length;
35b1e5cc
SS
13291
13292 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 13293 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
13294 (s->flags & SEC_READONLY) == 0)
13295 continue;
13296
13297 anysecs = 1;
fd361982
AM
13298 vma = bfd_section_vma (s);
13299 size = bfd_section_size (s);
608bcef2
HZ
13300 sprintf_vma (tmp1, vma);
13301 sprintf_vma (tmp2, vma + size);
c2fa21f1 13302 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
8d64371b 13303 if (offset + sec_length + 1 > rs->buf.size ())
c2fa21f1 13304 {
4082afcc 13305 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 13306 warning (_("\
c2fa21f1
HZ
13307Too many sections for read-only sections definition packet."));
13308 break;
13309 }
8d64371b 13310 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
bba74b36 13311 tmp1, tmp2);
c2fa21f1 13312 offset += sec_length;
35b1e5cc
SS
13313 }
13314 if (anysecs)
13315 {
b6bb3468 13316 putpkt (rs->buf);
8d64371b 13317 getpkt (&rs->buf, 0);
35b1e5cc
SS
13318 }
13319}
13320
f6ac5f3d
PA
13321void
13322remote_target::trace_start ()
35b1e5cc 13323{
b6bb3468
PA
13324 struct remote_state *rs = get_remote_state ();
13325
35b1e5cc 13326 putpkt ("QTStart");
b6bb3468 13327 remote_get_noisy_reply ();
8d64371b 13328 if (rs->buf[0] == '\0')
ad91cd99 13329 error (_("Target does not support this command."));
8d64371b
TT
13330 if (strcmp (rs->buf.data (), "OK") != 0)
13331 error (_("Bogus reply from target: %s"), rs->buf.data ());
35b1e5cc
SS
13332}
13333
f6ac5f3d
PA
13334int
13335remote_target::get_trace_status (struct trace_status *ts)
35b1e5cc 13336{
953b98d1 13337 /* Initialize it just to avoid a GCC false warning. */
f652de6f 13338 char *p = NULL;
bd3eecc3 13339 enum packet_result result;
b6bb3468 13340 struct remote_state *rs = get_remote_state ();
bd3eecc3 13341
4082afcc 13342 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 13343 return -1;
a744cf53 13344
7b9a15e1 13345 /* FIXME we need to get register block size some other way. */
5cd63fda 13346 trace_regblock_size
9d6eea31 13347 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
00bf0b85 13348
049dc89b
JK
13349 putpkt ("qTStatus");
13350
a70b8144 13351 try
67f41397 13352 {
b6bb3468 13353 p = remote_get_noisy_reply ();
67f41397 13354 }
230d2906 13355 catch (const gdb_exception_error &ex)
67f41397 13356 {
598d3636
JK
13357 if (ex.error != TARGET_CLOSE_ERROR)
13358 {
13359 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13360 return -1;
13361 }
eedc3f4f 13362 throw;
67f41397 13363 }
00bf0b85 13364
bd3eecc3
PA
13365 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13366
00bf0b85 13367 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 13368 if (result == PACKET_UNKNOWN)
00bf0b85 13369 return -1;
35b1e5cc 13370
00bf0b85 13371 /* We're working with a live target. */
f5911ea1 13372 ts->filename = NULL;
00bf0b85 13373
00bf0b85 13374 if (*p++ != 'T')
8d64371b 13375 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
35b1e5cc 13376
84cebc4a
YQ
13377 /* Function 'parse_trace_status' sets default value of each field of
13378 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
13379 parse_trace_status (p, ts);
13380
13381 return ts->running;
35b1e5cc
SS
13382}
13383
f6ac5f3d
PA
13384void
13385remote_target::get_tracepoint_status (struct breakpoint *bp,
13386 struct uploaded_tp *utp)
f196051f
SS
13387{
13388 struct remote_state *rs = get_remote_state ();
f196051f
SS
13389 char *reply;
13390 struct bp_location *loc;
13391 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 13392 size_t size = get_remote_packet_size ();
f196051f
SS
13393
13394 if (tp)
13395 {
c1fc2657 13396 tp->hit_count = 0;
f196051f 13397 tp->traceframe_usage = 0;
c1fc2657 13398 for (loc = tp->loc; loc; loc = loc->next)
f196051f
SS
13399 {
13400 /* If the tracepoint was never downloaded, don't go asking for
13401 any status. */
13402 if (tp->number_on_target == 0)
13403 continue;
8d64371b 13404 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
bba74b36 13405 phex_nz (loc->address, 0));
f196051f 13406 putpkt (rs->buf);
b6bb3468 13407 reply = remote_get_noisy_reply ();
f196051f
SS
13408 if (reply && *reply)
13409 {
13410 if (*reply == 'V')
13411 parse_tracepoint_status (reply + 1, bp, utp);
13412 }
13413 }
13414 }
13415 else if (utp)
13416 {
13417 utp->hit_count = 0;
13418 utp->traceframe_usage = 0;
8d64371b 13419 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
bba74b36 13420 phex_nz (utp->addr, 0));
f196051f 13421 putpkt (rs->buf);
b6bb3468 13422 reply = remote_get_noisy_reply ();
f196051f
SS
13423 if (reply && *reply)
13424 {
13425 if (*reply == 'V')
13426 parse_tracepoint_status (reply + 1, bp, utp);
13427 }
13428 }
13429}
13430
f6ac5f3d
PA
13431void
13432remote_target::trace_stop ()
35b1e5cc 13433{
b6bb3468
PA
13434 struct remote_state *rs = get_remote_state ();
13435
35b1e5cc 13436 putpkt ("QTStop");
b6bb3468 13437 remote_get_noisy_reply ();
8d64371b 13438 if (rs->buf[0] == '\0')
ad91cd99 13439 error (_("Target does not support this command."));
8d64371b
TT
13440 if (strcmp (rs->buf.data (), "OK") != 0)
13441 error (_("Bogus reply from target: %s"), rs->buf.data ());
35b1e5cc
SS
13442}
13443
f6ac5f3d
PA
13444int
13445remote_target::trace_find (enum trace_find_type type, int num,
13446 CORE_ADDR addr1, CORE_ADDR addr2,
13447 int *tpp)
35b1e5cc
SS
13448{
13449 struct remote_state *rs = get_remote_state ();
8d64371b 13450 char *endbuf = rs->buf.data () + get_remote_packet_size ();
35b1e5cc
SS
13451 char *p, *reply;
13452 int target_frameno = -1, target_tracept = -1;
13453
e6e4e701
PA
13454 /* Lookups other than by absolute frame number depend on the current
13455 trace selected, so make sure it is correct on the remote end
13456 first. */
13457 if (type != tfind_number)
13458 set_remote_traceframe ();
13459
8d64371b 13460 p = rs->buf.data ();
35b1e5cc
SS
13461 strcpy (p, "QTFrame:");
13462 p = strchr (p, '\0');
13463 switch (type)
13464 {
13465 case tfind_number:
bba74b36 13466 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
13467 break;
13468 case tfind_pc:
bba74b36 13469 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
13470 break;
13471 case tfind_tp:
bba74b36 13472 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
13473 break;
13474 case tfind_range:
bba74b36
YQ
13475 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13476 phex_nz (addr2, 0));
35b1e5cc
SS
13477 break;
13478 case tfind_outside:
bba74b36
YQ
13479 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13480 phex_nz (addr2, 0));
35b1e5cc
SS
13481 break;
13482 default:
9b20d036 13483 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
13484 }
13485
13486 putpkt (rs->buf);
b6bb3468 13487 reply = remote_get_noisy_reply ();
ad91cd99
PA
13488 if (*reply == '\0')
13489 error (_("Target does not support this command."));
35b1e5cc
SS
13490
13491 while (reply && *reply)
13492 switch (*reply)
13493 {
13494 case 'F':
f197e0f1
VP
13495 p = ++reply;
13496 target_frameno = (int) strtol (p, &reply, 16);
13497 if (reply == p)
13498 error (_("Unable to parse trace frame number"));
e6e4e701
PA
13499 /* Don't update our remote traceframe number cache on failure
13500 to select a remote traceframe. */
f197e0f1
VP
13501 if (target_frameno == -1)
13502 return -1;
35b1e5cc
SS
13503 break;
13504 case 'T':
f197e0f1
VP
13505 p = ++reply;
13506 target_tracept = (int) strtol (p, &reply, 16);
13507 if (reply == p)
13508 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
13509 break;
13510 case 'O': /* "OK"? */
13511 if (reply[1] == 'K' && reply[2] == '\0')
13512 reply += 2;
13513 else
13514 error (_("Bogus reply from target: %s"), reply);
13515 break;
13516 default:
13517 error (_("Bogus reply from target: %s"), reply);
13518 }
13519 if (tpp)
13520 *tpp = target_tracept;
e6e4e701 13521
262e1174 13522 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
13523 return target_frameno;
13524}
13525
57810aa7 13526bool
f6ac5f3d 13527remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
35b1e5cc
SS
13528{
13529 struct remote_state *rs = get_remote_state ();
13530 char *reply;
13531 ULONGEST uval;
13532
e6e4e701
PA
13533 set_remote_traceframe ();
13534
8d64371b 13535 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc 13536 putpkt (rs->buf);
b6bb3468 13537 reply = remote_get_noisy_reply ();
35b1e5cc
SS
13538 if (reply && *reply)
13539 {
13540 if (*reply == 'V')
13541 {
13542 unpack_varlen_hex (reply + 1, &uval);
13543 *val = (LONGEST) uval;
57810aa7 13544 return true;
35b1e5cc
SS
13545 }
13546 }
57810aa7 13547 return false;
35b1e5cc
SS
13548}
13549
f6ac5f3d
PA
13550int
13551remote_target::save_trace_data (const char *filename)
00bf0b85
SS
13552{
13553 struct remote_state *rs = get_remote_state ();
13554 char *p, *reply;
13555
8d64371b 13556 p = rs->buf.data ();
00bf0b85
SS
13557 strcpy (p, "QTSave:");
13558 p += strlen (p);
8d64371b
TT
13559 if ((p - rs->buf.data ()) + strlen (filename) * 2
13560 >= get_remote_packet_size ())
00bf0b85 13561 error (_("Remote file name too long for trace save packet"));
9f1b45b0 13562 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
13563 *p++ = '\0';
13564 putpkt (rs->buf);
b6bb3468 13565 reply = remote_get_noisy_reply ();
d6c5869f 13566 if (*reply == '\0')
ad91cd99
PA
13567 error (_("Target does not support this command."));
13568 if (strcmp (reply, "OK") != 0)
13569 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
13570 return 0;
13571}
13572
13573/* This is basically a memory transfer, but needs to be its own packet
13574 because we don't know how the target actually organizes its trace
13575 memory, plus we want to be able to ask for as much as possible, but
13576 not be unhappy if we don't get as much as we ask for. */
13577
f6ac5f3d
PA
13578LONGEST
13579remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
13580{
13581 struct remote_state *rs = get_remote_state ();
13582 char *reply;
13583 char *p;
13584 int rslt;
13585
8d64371b 13586 p = rs->buf.data ();
00bf0b85
SS
13587 strcpy (p, "qTBuffer:");
13588 p += strlen (p);
13589 p += hexnumstr (p, offset);
13590 *p++ = ',';
13591 p += hexnumstr (p, len);
13592 *p++ = '\0';
13593
13594 putpkt (rs->buf);
b6bb3468 13595 reply = remote_get_noisy_reply ();
00bf0b85
SS
13596 if (reply && *reply)
13597 {
13598 /* 'l' by itself means we're at the end of the buffer and
13599 there is nothing more to get. */
13600 if (*reply == 'l')
13601 return 0;
13602
13603 /* Convert the reply into binary. Limit the number of bytes to
13604 convert according to our passed-in buffer size, rather than
13605 what was returned in the packet; if the target is
13606 unexpectedly generous and gives us a bigger reply than we
13607 asked for, we don't want to crash. */
b6bb3468 13608 rslt = hex2bin (reply, buf, len);
00bf0b85
SS
13609 return rslt;
13610 }
13611
13612 /* Something went wrong, flag as an error. */
13613 return -1;
13614}
13615
f6ac5f3d
PA
13616void
13617remote_target::set_disconnected_tracing (int val)
35b1e5cc
SS
13618{
13619 struct remote_state *rs = get_remote_state ();
13620
4082afcc 13621 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 13622 {
ad91cd99
PA
13623 char *reply;
13624
8d64371b
TT
13625 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13626 "QTDisconnected:%x", val);
33da3f1c 13627 putpkt (rs->buf);
b6bb3468 13628 reply = remote_get_noisy_reply ();
ad91cd99 13629 if (*reply == '\0')
33da3f1c 13630 error (_("Target does not support this command."));
ad91cd99 13631 if (strcmp (reply, "OK") != 0)
dda83cd7 13632 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
13633 }
13634 else if (val)
13635 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
13636}
13637
f6ac5f3d
PA
13638int
13639remote_target::core_of_thread (ptid_t ptid)
dc146f7c 13640{
5b6d1e4f 13641 thread_info *info = find_thread_ptid (this, ptid);
a744cf53 13642
7aabaf9d
SM
13643 if (info != NULL && info->priv != NULL)
13644 return get_remote_thread_info (info)->core;
13645
dc146f7c
VP
13646 return -1;
13647}
13648
f6ac5f3d
PA
13649void
13650remote_target::set_circular_trace_buffer (int val)
4daf5ac0
SS
13651{
13652 struct remote_state *rs = get_remote_state ();
ad91cd99 13653 char *reply;
4daf5ac0 13654
8d64371b
TT
13655 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13656 "QTBuffer:circular:%x", val);
4daf5ac0 13657 putpkt (rs->buf);
b6bb3468 13658 reply = remote_get_noisy_reply ();
ad91cd99 13659 if (*reply == '\0')
4daf5ac0 13660 error (_("Target does not support this command."));
ad91cd99
PA
13661 if (strcmp (reply, "OK") != 0)
13662 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
13663}
13664
f6ac5f3d
PA
13665traceframe_info_up
13666remote_target::traceframe_info ()
b3b9301e 13667{
9018be22 13668 gdb::optional<gdb::char_vector> text
8b88a78e 13669 = target_read_stralloc (current_top_target (), TARGET_OBJECT_TRACEFRAME_INFO,
b7b030ad 13670 NULL);
9018be22
SM
13671 if (text)
13672 return parse_traceframe_info (text->data ());
b3b9301e
PA
13673
13674 return NULL;
13675}
13676
405f8e94
SS
13677/* Handle the qTMinFTPILen packet. Returns the minimum length of
13678 instruction on which a fast tracepoint may be placed. Returns -1
13679 if the packet is not supported, and 0 if the minimum instruction
13680 length is unknown. */
13681
f6ac5f3d
PA
13682int
13683remote_target::get_min_fast_tracepoint_insn_len ()
405f8e94
SS
13684{
13685 struct remote_state *rs = get_remote_state ();
13686 char *reply;
13687
e886a173
PA
13688 /* If we're not debugging a process yet, the IPA can't be
13689 loaded. */
55f6301a 13690 if (!target_has_execution ())
e886a173
PA
13691 return 0;
13692
13693 /* Make sure the remote is pointing at the right process. */
13694 set_general_process ();
13695
8d64371b 13696 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
405f8e94 13697 putpkt (rs->buf);
b6bb3468 13698 reply = remote_get_noisy_reply ();
405f8e94
SS
13699 if (*reply == '\0')
13700 return -1;
13701 else
13702 {
13703 ULONGEST min_insn_len;
13704
13705 unpack_varlen_hex (reply, &min_insn_len);
13706
13707 return (int) min_insn_len;
13708 }
13709}
13710
f6ac5f3d
PA
13711void
13712remote_target::set_trace_buffer_size (LONGEST val)
f6f899bf 13713{
4082afcc 13714 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
13715 {
13716 struct remote_state *rs = get_remote_state ();
8d64371b
TT
13717 char *buf = rs->buf.data ();
13718 char *endbuf = buf + get_remote_packet_size ();
f6f899bf
HAQ
13719 enum packet_result result;
13720
13721 gdb_assert (val >= 0 || val == -1);
13722 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13723 /* Send -1 as literal "-1" to avoid host size dependency. */
13724 if (val < 0)
13725 {
13726 *buf++ = '-';
dda83cd7 13727 buf += hexnumstr (buf, (ULONGEST) -val);
f6f899bf
HAQ
13728 }
13729 else
13730 buf += hexnumstr (buf, (ULONGEST) val);
13731
13732 putpkt (rs->buf);
b6bb3468 13733 remote_get_noisy_reply ();
f6f899bf
HAQ
13734 result = packet_ok (rs->buf,
13735 &remote_protocol_packets[PACKET_QTBuffer_size]);
13736
13737 if (result != PACKET_OK)
8d64371b 13738 warning (_("Bogus reply from target: %s"), rs->buf.data ());
f6f899bf
HAQ
13739 }
13740}
13741
57810aa7 13742bool
f6ac5f3d
PA
13743remote_target::set_trace_notes (const char *user, const char *notes,
13744 const char *stop_notes)
f196051f
SS
13745{
13746 struct remote_state *rs = get_remote_state ();
13747 char *reply;
8d64371b
TT
13748 char *buf = rs->buf.data ();
13749 char *endbuf = buf + get_remote_packet_size ();
f196051f
SS
13750 int nbytes;
13751
13752 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13753 if (user)
13754 {
13755 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 13756 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
13757 buf += 2 * nbytes;
13758 *buf++ = ';';
13759 }
13760 if (notes)
13761 {
13762 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 13763 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
13764 buf += 2 * nbytes;
13765 *buf++ = ';';
13766 }
13767 if (stop_notes)
13768 {
13769 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 13770 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
13771 buf += 2 * nbytes;
13772 *buf++ = ';';
13773 }
13774 /* Ensure the buffer is terminated. */
13775 *buf = '\0';
13776
13777 putpkt (rs->buf);
b6bb3468 13778 reply = remote_get_noisy_reply ();
f196051f 13779 if (*reply == '\0')
57810aa7 13780 return false;
f196051f
SS
13781
13782 if (strcmp (reply, "OK") != 0)
13783 error (_("Bogus reply from target: %s"), reply);
13784
57810aa7 13785 return true;
f196051f
SS
13786}
13787
57810aa7
PA
13788bool
13789remote_target::use_agent (bool use)
d1feda86 13790{
4082afcc 13791 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
13792 {
13793 struct remote_state *rs = get_remote_state ();
13794
13795 /* If the stub supports QAgent. */
8d64371b 13796 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
d1feda86 13797 putpkt (rs->buf);
8d64371b 13798 getpkt (&rs->buf, 0);
d1feda86 13799
8d64371b 13800 if (strcmp (rs->buf.data (), "OK") == 0)
d1feda86 13801 {
f6ac5f3d 13802 ::use_agent = use;
57810aa7 13803 return true;
d1feda86
YQ
13804 }
13805 }
13806
57810aa7 13807 return false;
d1feda86
YQ
13808}
13809
57810aa7 13810bool
f6ac5f3d 13811remote_target::can_use_agent ()
d1feda86 13812{
4082afcc 13813 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
13814}
13815
9accd112
MM
13816struct btrace_target_info
13817{
13818 /* The ptid of the traced thread. */
13819 ptid_t ptid;
f4abbc16
MM
13820
13821 /* The obtained branch trace configuration. */
13822 struct btrace_config conf;
9accd112
MM
13823};
13824
f4abbc16
MM
13825/* Reset our idea of our target's btrace configuration. */
13826
13827static void
6b8edb51 13828remote_btrace_reset (remote_state *rs)
f4abbc16 13829{
f4abbc16
MM
13830 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13831}
13832
f4abbc16
MM
13833/* Synchronize the configuration with the target. */
13834
6b8edb51
PA
13835void
13836remote_target::btrace_sync_conf (const btrace_config *conf)
f4abbc16 13837{
d33501a5
MM
13838 struct packet_config *packet;
13839 struct remote_state *rs;
13840 char *buf, *pos, *endbuf;
13841
13842 rs = get_remote_state ();
8d64371b 13843 buf = rs->buf.data ();
d33501a5
MM
13844 endbuf = buf + get_remote_packet_size ();
13845
13846 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13847 if (packet_config_support (packet) == PACKET_ENABLE
13848 && conf->bts.size != rs->btrace_config.bts.size)
13849 {
13850 pos = buf;
13851 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
dda83cd7 13852 conf->bts.size);
d33501a5
MM
13853
13854 putpkt (buf);
8d64371b 13855 getpkt (&rs->buf, 0);
d33501a5
MM
13856
13857 if (packet_ok (buf, packet) == PACKET_ERROR)
13858 {
13859 if (buf[0] == 'E' && buf[1] == '.')
13860 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13861 else
13862 error (_("Failed to configure the BTS buffer size."));
13863 }
13864
13865 rs->btrace_config.bts.size = conf->bts.size;
13866 }
b20a6524
MM
13867
13868 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13869 if (packet_config_support (packet) == PACKET_ENABLE
13870 && conf->pt.size != rs->btrace_config.pt.size)
13871 {
13872 pos = buf;
13873 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
dda83cd7 13874 conf->pt.size);
b20a6524
MM
13875
13876 putpkt (buf);
8d64371b 13877 getpkt (&rs->buf, 0);
b20a6524
MM
13878
13879 if (packet_ok (buf, packet) == PACKET_ERROR)
13880 {
13881 if (buf[0] == 'E' && buf[1] == '.')
13882 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13883 else
13884 error (_("Failed to configure the trace buffer size."));
13885 }
13886
13887 rs->btrace_config.pt.size = conf->pt.size;
13888 }
f4abbc16
MM
13889}
13890
13891/* Read the current thread's btrace configuration from the target and
13892 store it into CONF. */
13893
13894static void
13895btrace_read_config (struct btrace_config *conf)
13896{
9018be22 13897 gdb::optional<gdb::char_vector> xml
8b88a78e 13898 = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE_CONF, "");
9018be22
SM
13899 if (xml)
13900 parse_xml_btrace_conf (conf, xml->data ());
f4abbc16
MM
13901}
13902
c0272db5
TW
13903/* Maybe reopen target btrace. */
13904
6b8edb51
PA
13905void
13906remote_target::remote_btrace_maybe_reopen ()
c0272db5
TW
13907{
13908 struct remote_state *rs = get_remote_state ();
c0272db5 13909 int btrace_target_pushed = 0;
15766370 13910#if !defined (HAVE_LIBIPT)
c0272db5 13911 int warned = 0;
15766370 13912#endif
c0272db5 13913
aedbe3bb
CM
13914 /* Don't bother walking the entirety of the remote thread list when
13915 we know the feature isn't supported by the remote. */
13916 if (packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
13917 return;
13918
5ed8105e
PA
13919 scoped_restore_current_thread restore_thread;
13920
5b6d1e4f 13921 for (thread_info *tp : all_non_exited_threads (this))
c0272db5
TW
13922 {
13923 set_general_thread (tp->ptid);
13924
13925 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13926 btrace_read_config (&rs->btrace_config);
13927
13928 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13929 continue;
13930
13931#if !defined (HAVE_LIBIPT)
13932 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13933 {
13934 if (!warned)
13935 {
13936 warned = 1;
c4e12631
MM
13937 warning (_("Target is recording using Intel Processor Trace "
13938 "but support was disabled at compile time."));
c0272db5
TW
13939 }
13940
13941 continue;
13942 }
13943#endif /* !defined (HAVE_LIBIPT) */
13944
13945 /* Push target, once, but before anything else happens. This way our
13946 changes to the threads will be cleaned up by unpushing the target
13947 in case btrace_read_config () throws. */
13948 if (!btrace_target_pushed)
13949 {
13950 btrace_target_pushed = 1;
13951 record_btrace_push_target ();
13952 printf_filtered (_("Target is recording using %s.\n"),
13953 btrace_format_string (rs->btrace_config.format));
13954 }
13955
13956 tp->btrace.target = XCNEW (struct btrace_target_info);
13957 tp->btrace.target->ptid = tp->ptid;
13958 tp->btrace.target->conf = rs->btrace_config;
13959 }
c0272db5
TW
13960}
13961
9accd112
MM
13962/* Enable branch tracing. */
13963
f6ac5f3d
PA
13964struct btrace_target_info *
13965remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
9accd112
MM
13966{
13967 struct btrace_target_info *tinfo = NULL;
b20a6524 13968 struct packet_config *packet = NULL;
9accd112 13969 struct remote_state *rs = get_remote_state ();
8d64371b
TT
13970 char *buf = rs->buf.data ();
13971 char *endbuf = buf + get_remote_packet_size ();
9accd112 13972
b20a6524
MM
13973 switch (conf->format)
13974 {
13975 case BTRACE_FORMAT_BTS:
13976 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13977 break;
13978
13979 case BTRACE_FORMAT_PT:
13980 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13981 break;
13982 }
13983
13984 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13985 error (_("Target does not support branch tracing."));
13986
f4abbc16
MM
13987 btrace_sync_conf (conf);
13988
9accd112
MM
13989 set_general_thread (ptid);
13990
13991 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13992 putpkt (rs->buf);
8d64371b 13993 getpkt (&rs->buf, 0);
9accd112
MM
13994
13995 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13996 {
13997 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13998 error (_("Could not enable branch tracing for %s: %s"),
a068643d 13999 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
9accd112
MM
14000 else
14001 error (_("Could not enable branch tracing for %s."),
a068643d 14002 target_pid_to_str (ptid).c_str ());
9accd112
MM
14003 }
14004
8d749320 14005 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
14006 tinfo->ptid = ptid;
14007
f4abbc16
MM
14008 /* If we fail to read the configuration, we lose some information, but the
14009 tracing itself is not impacted. */
a70b8144 14010 try
492d29ea
PA
14011 {
14012 btrace_read_config (&tinfo->conf);
14013 }
230d2906 14014 catch (const gdb_exception_error &err)
492d29ea
PA
14015 {
14016 if (err.message != NULL)
3d6e9d23 14017 warning ("%s", err.what ());
492d29ea 14018 }
f4abbc16 14019
9accd112
MM
14020 return tinfo;
14021}
14022
14023/* Disable branch tracing. */
14024
f6ac5f3d
PA
14025void
14026remote_target::disable_btrace (struct btrace_target_info *tinfo)
9accd112
MM
14027{
14028 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
14029 struct remote_state *rs = get_remote_state ();
8d64371b
TT
14030 char *buf = rs->buf.data ();
14031 char *endbuf = buf + get_remote_packet_size ();
9accd112 14032
4082afcc 14033 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
14034 error (_("Target does not support branch tracing."));
14035
14036 set_general_thread (tinfo->ptid);
14037
14038 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14039 putpkt (rs->buf);
8d64371b 14040 getpkt (&rs->buf, 0);
9accd112
MM
14041
14042 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14043 {
14044 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14045 error (_("Could not disable branch tracing for %s: %s"),
a068643d 14046 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
9accd112
MM
14047 else
14048 error (_("Could not disable branch tracing for %s."),
a068643d 14049 target_pid_to_str (tinfo->ptid).c_str ());
9accd112
MM
14050 }
14051
14052 xfree (tinfo);
14053}
14054
14055/* Teardown branch tracing. */
14056
f6ac5f3d
PA
14057void
14058remote_target::teardown_btrace (struct btrace_target_info *tinfo)
9accd112
MM
14059{
14060 /* We must not talk to the target during teardown. */
14061 xfree (tinfo);
14062}
14063
14064/* Read the branch trace. */
14065
f6ac5f3d
PA
14066enum btrace_error
14067remote_target::read_btrace (struct btrace_data *btrace,
14068 struct btrace_target_info *tinfo,
14069 enum btrace_read_type type)
9accd112
MM
14070{
14071 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
9accd112 14072 const char *annex;
9accd112 14073
4082afcc 14074 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
14075 error (_("Target does not support branch tracing."));
14076
14077#if !defined(HAVE_LIBEXPAT)
14078 error (_("Cannot process branch tracing result. XML parsing not supported."));
14079#endif
14080
14081 switch (type)
14082 {
864089d2 14083 case BTRACE_READ_ALL:
9accd112
MM
14084 annex = "all";
14085 break;
864089d2 14086 case BTRACE_READ_NEW:
9accd112
MM
14087 annex = "new";
14088 break;
969c39fb
MM
14089 case BTRACE_READ_DELTA:
14090 annex = "delta";
14091 break;
9accd112
MM
14092 default:
14093 internal_error (__FILE__, __LINE__,
14094 _("Bad branch tracing read type: %u."),
14095 (unsigned int) type);
14096 }
14097
9018be22 14098 gdb::optional<gdb::char_vector> xml
8b88a78e 14099 = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE, annex);
9018be22 14100 if (!xml)
969c39fb 14101 return BTRACE_ERR_UNKNOWN;
9accd112 14102
9018be22 14103 parse_xml_btrace (btrace, xml->data ());
9accd112 14104
969c39fb 14105 return BTRACE_ERR_NONE;
9accd112
MM
14106}
14107
f6ac5f3d
PA
14108const struct btrace_config *
14109remote_target::btrace_conf (const struct btrace_target_info *tinfo)
f4abbc16
MM
14110{
14111 return &tinfo->conf;
14112}
14113
57810aa7 14114bool
f6ac5f3d 14115remote_target::augmented_libraries_svr4_read ()
ced63ec0 14116{
4082afcc
PA
14117 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
14118 == PACKET_ENABLE);
ced63ec0
GB
14119}
14120
9dd130a0
TT
14121/* Implementation of to_load. */
14122
f6ac5f3d
PA
14123void
14124remote_target::load (const char *name, int from_tty)
9dd130a0
TT
14125{
14126 generic_load (name, from_tty);
14127}
14128
c78fa86a
GB
14129/* Accepts an integer PID; returns a string representing a file that
14130 can be opened on the remote side to get the symbols for the child
14131 process. Returns NULL if the operation is not supported. */
14132
f6ac5f3d
PA
14133char *
14134remote_target::pid_to_exec_file (int pid)
c78fa86a 14135{
9018be22 14136 static gdb::optional<gdb::char_vector> filename;
835205d0 14137 char *annex = NULL;
c78fa86a
GB
14138
14139 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14140 return NULL;
14141
5b6d1e4f 14142 inferior *inf = find_inferior_pid (this, pid);
835205d0
GB
14143 if (inf == NULL)
14144 internal_error (__FILE__, __LINE__,
14145 _("not currently attached to process %d"), pid);
14146
14147 if (!inf->fake_pid_p)
14148 {
14149 const int annex_size = 9;
14150
224c3ddb 14151 annex = (char *) alloca (annex_size);
835205d0
GB
14152 xsnprintf (annex, annex_size, "%x", pid);
14153 }
14154
8b88a78e 14155 filename = target_read_stralloc (current_top_target (),
c78fa86a
GB
14156 TARGET_OBJECT_EXEC_FILE, annex);
14157
9018be22 14158 return filename ? filename->data () : nullptr;
c78fa86a
GB
14159}
14160
750ce8d1
YQ
14161/* Implement the to_can_do_single_step target_ops method. */
14162
f6ac5f3d
PA
14163int
14164remote_target::can_do_single_step ()
750ce8d1
YQ
14165{
14166 /* We can only tell whether target supports single step or not by
14167 supported s and S vCont actions if the stub supports vContSupported
14168 feature. If the stub doesn't support vContSupported feature,
14169 we have conservatively to think target doesn't supports single
14170 step. */
14171 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14172 {
14173 struct remote_state *rs = get_remote_state ();
14174
14175 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 14176 remote_vcont_probe ();
750ce8d1
YQ
14177
14178 return rs->supports_vCont.s && rs->supports_vCont.S;
14179 }
14180 else
14181 return 0;
14182}
14183
3a00c802
PA
14184/* Implementation of the to_execution_direction method for the remote
14185 target. */
14186
f6ac5f3d
PA
14187enum exec_direction_kind
14188remote_target::execution_direction ()
3a00c802
PA
14189{
14190 struct remote_state *rs = get_remote_state ();
14191
14192 return rs->last_resume_exec_dir;
14193}
14194
f6327dcb
KB
14195/* Return pointer to the thread_info struct which corresponds to
14196 THREAD_HANDLE (having length HANDLE_LEN). */
14197
f6ac5f3d
PA
14198thread_info *
14199remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14200 int handle_len,
14201 inferior *inf)
f6327dcb 14202{
5b6d1e4f 14203 for (thread_info *tp : all_non_exited_threads (this))
f6327dcb 14204 {
7aabaf9d 14205 remote_thread_info *priv = get_remote_thread_info (tp);
f6327dcb
KB
14206
14207 if (tp->inf == inf && priv != NULL)
dda83cd7 14208 {
7aabaf9d 14209 if (handle_len != priv->thread_handle.size ())
f6327dcb 14210 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
dda83cd7 14211 handle_len, priv->thread_handle.size ());
7aabaf9d 14212 if (memcmp (thread_handle, priv->thread_handle.data (),
dda83cd7 14213 handle_len) == 0)
f6327dcb
KB
14214 return tp;
14215 }
14216 }
14217
14218 return NULL;
14219}
14220
3d6c6204
KB
14221gdb::byte_vector
14222remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14223{
14224 remote_thread_info *priv = get_remote_thread_info (tp);
14225 return priv->thread_handle;
14226}
14227
57810aa7 14228bool
f6ac5f3d 14229remote_target::can_async_p ()
6426a772 14230{
5d93a237
TT
14231 struct remote_state *rs = get_remote_state ();
14232
3015c064
SM
14233 /* We don't go async if the user has explicitly prevented it with the
14234 "maint set target-async" command. */
c6ebd6cf 14235 if (!target_async_permitted)
57810aa7 14236 return false;
75c99385 14237
23860348 14238 /* We're async whenever the serial device is. */
5d93a237 14239 return serial_can_async_p (rs->remote_desc);
6426a772
JM
14240}
14241
57810aa7 14242bool
f6ac5f3d 14243remote_target::is_async_p ()
6426a772 14244{
5d93a237
TT
14245 struct remote_state *rs = get_remote_state ();
14246
c6ebd6cf 14247 if (!target_async_permitted)
75c99385 14248 /* We only enable async when the user specifically asks for it. */
57810aa7 14249 return false;
75c99385 14250
23860348 14251 /* We're async whenever the serial device is. */
5d93a237 14252 return serial_is_async_p (rs->remote_desc);
6426a772
JM
14253}
14254
2acceee2
JM
14255/* Pass the SERIAL event on and up to the client. One day this code
14256 will be able to delay notifying the client of an event until the
23860348 14257 point where an entire packet has been received. */
2acceee2 14258
2acceee2
JM
14259static serial_event_ftype remote_async_serial_handler;
14260
6426a772 14261static void
819cc324 14262remote_async_serial_handler (struct serial *scb, void *context)
6426a772 14263{
2acceee2
JM
14264 /* Don't propogate error information up to the client. Instead let
14265 the client find out about the error by querying the target. */
b1a35af2 14266 inferior_event_handler (INF_REG_EVENT);
2acceee2
JM
14267}
14268
74531fed
PA
14269static void
14270remote_async_inferior_event_handler (gdb_client_data data)
14271{
b1a35af2 14272 inferior_event_handler (INF_REG_EVENT);
96118d11
PA
14273
14274 remote_target *remote = (remote_target *) data;
14275 remote_state *rs = remote->get_remote_state ();
14276
14277 /* inferior_event_handler may have consumed an event pending on the
14278 infrun side without calling target_wait on the REMOTE target, or
14279 may have pulled an event out of a different target. Keep trying
14280 for this remote target as long it still has either pending events
14281 or unacknowledged notifications. */
14282
14283 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL
14284 || !rs->stop_reply_queue.empty ())
14285 mark_async_event_handler (rs->remote_async_inferior_event_token);
74531fed
PA
14286}
14287
5b6d1e4f
PA
14288int
14289remote_target::async_wait_fd ()
14290{
14291 struct remote_state *rs = get_remote_state ();
14292 return rs->remote_desc->fd;
14293}
14294
f6ac5f3d
PA
14295void
14296remote_target::async (int enable)
2acceee2 14297{
5d93a237
TT
14298 struct remote_state *rs = get_remote_state ();
14299
6a3753b3 14300 if (enable)
2acceee2 14301 {
88b496c3 14302 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
14303
14304 /* If there are pending events in the stop reply queue tell the
14305 event loop to process them. */
953edf2b 14306 if (!rs->stop_reply_queue.empty ())
6b8edb51 14307 mark_async_event_handler (rs->remote_async_inferior_event_token);
6efcd9a8
PA
14308 /* For simplicity, below we clear the pending events token
14309 without remembering whether it is marked, so here we always
14310 mark it. If there's actually no pending notification to
14311 process, this ends up being a no-op (other than a spurious
14312 event-loop wakeup). */
14313 if (target_is_non_stop_p ())
14314 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
14315 }
14316 else
b7d2e916
PA
14317 {
14318 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
14319 /* If the core is disabling async, it doesn't want to be
14320 disturbed with target events. Clear all async event sources
14321 too. */
6b8edb51 14322 clear_async_event_handler (rs->remote_async_inferior_event_token);
6efcd9a8
PA
14323 if (target_is_non_stop_p ())
14324 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 14325 }
6426a772
JM
14326}
14327
65706a29
PA
14328/* Implementation of the to_thread_events method. */
14329
f6ac5f3d
PA
14330void
14331remote_target::thread_events (int enable)
65706a29
PA
14332{
14333 struct remote_state *rs = get_remote_state ();
14334 size_t size = get_remote_packet_size ();
65706a29
PA
14335
14336 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14337 return;
14338
8d64371b 14339 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
65706a29 14340 putpkt (rs->buf);
8d64371b 14341 getpkt (&rs->buf, 0);
65706a29
PA
14342
14343 switch (packet_ok (rs->buf,
14344 &remote_protocol_packets[PACKET_QThreadEvents]))
14345 {
14346 case PACKET_OK:
8d64371b
TT
14347 if (strcmp (rs->buf.data (), "OK") != 0)
14348 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
65706a29
PA
14349 break;
14350 case PACKET_ERROR:
8d64371b 14351 warning (_("Remote failure reply: %s"), rs->buf.data ());
65706a29
PA
14352 break;
14353 case PACKET_UNKNOWN:
14354 break;
14355 }
14356}
14357
d471ea57 14358static void
981a3fb3 14359show_remote_cmd (const char *args, int from_tty)
d471ea57 14360{
37a105a1 14361 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 14362 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1 14363 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 14364 struct ui_out *uiout = current_uiout;
37a105a1 14365
2e783024 14366 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
37a105a1
DJ
14367 for (; list != NULL; list = list->next)
14368 if (strcmp (list->name, "Z-packet") == 0)
14369 continue;
427c3a89
DJ
14370 else if (list->type == not_set_cmd)
14371 /* Alias commands are exactly like the original, except they
14372 don't have the normal type. */
14373 continue;
14374 else
37a105a1 14375 {
2e783024 14376 ui_out_emit_tuple option_emitter (uiout, "option");
a744cf53 14377
112e8700
SM
14378 uiout->field_string ("name", list->name);
14379 uiout->text (": ");
427c3a89 14380 if (list->type == show_cmd)
f5c4fcd9 14381 do_show_command (NULL, from_tty, list);
427c3a89
DJ
14382 else
14383 cmd_func (list, NULL, from_tty);
37a105a1 14384 }
d471ea57 14385}
5a2468f5 14386
0f71a2f6 14387
23860348 14388/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
14389static void
14390remote_new_objfile (struct objfile *objfile)
14391{
6b8edb51 14392 remote_target *remote = get_current_remote_target ();
5d93a237 14393
6b8edb51
PA
14394 if (remote != NULL) /* Have a remote connection. */
14395 remote->remote_check_symbols ();
dc8acb97
MS
14396}
14397
00bf0b85
SS
14398/* Pull all the tracepoints defined on the target and create local
14399 data structures representing them. We don't want to create real
14400 tracepoints yet, we don't want to mess up the user's existing
14401 collection. */
14402
f6ac5f3d
PA
14403int
14404remote_target::upload_tracepoints (struct uploaded_tp **utpp)
d5551862 14405{
00bf0b85
SS
14406 struct remote_state *rs = get_remote_state ();
14407 char *p;
d5551862 14408
00bf0b85
SS
14409 /* Ask for a first packet of tracepoint definition. */
14410 putpkt ("qTfP");
8d64371b
TT
14411 getpkt (&rs->buf, 0);
14412 p = rs->buf.data ();
00bf0b85 14413 while (*p && *p != 'l')
d5551862 14414 {
00bf0b85
SS
14415 parse_tracepoint_definition (p, utpp);
14416 /* Ask for another packet of tracepoint definition. */
14417 putpkt ("qTsP");
8d64371b
TT
14418 getpkt (&rs->buf, 0);
14419 p = rs->buf.data ();
d5551862 14420 }
00bf0b85 14421 return 0;
d5551862
SS
14422}
14423
f6ac5f3d
PA
14424int
14425remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
d5551862 14426{
00bf0b85 14427 struct remote_state *rs = get_remote_state ();
d5551862 14428 char *p;
d5551862 14429
00bf0b85
SS
14430 /* Ask for a first packet of variable definition. */
14431 putpkt ("qTfV");
8d64371b
TT
14432 getpkt (&rs->buf, 0);
14433 p = rs->buf.data ();
00bf0b85 14434 while (*p && *p != 'l')
d5551862 14435 {
00bf0b85
SS
14436 parse_tsv_definition (p, utsvp);
14437 /* Ask for another packet of variable definition. */
14438 putpkt ("qTsV");
8d64371b
TT
14439 getpkt (&rs->buf, 0);
14440 p = rs->buf.data ();
d5551862 14441 }
00bf0b85 14442 return 0;
d5551862
SS
14443}
14444
c1e36e3e
PA
14445/* The "set/show range-stepping" show hook. */
14446
14447static void
14448show_range_stepping (struct ui_file *file, int from_tty,
14449 struct cmd_list_element *c,
14450 const char *value)
14451{
14452 fprintf_filtered (file,
14453 _("Debugger's willingness to use range stepping "
14454 "is %s.\n"), value);
14455}
14456
6b8edb51
PA
14457/* Return true if the vCont;r action is supported by the remote
14458 stub. */
14459
14460bool
14461remote_target::vcont_r_supported ()
14462{
14463 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14464 remote_vcont_probe ();
14465
14466 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14467 && get_remote_state ()->supports_vCont.r);
14468}
14469
c1e36e3e
PA
14470/* The "set/show range-stepping" set hook. */
14471
14472static void
eb4c3f4a 14473set_range_stepping (const char *ignore_args, int from_tty,
c1e36e3e
PA
14474 struct cmd_list_element *c)
14475{
6b8edb51
PA
14476 /* When enabling, check whether range stepping is actually supported
14477 by the target, and warn if not. */
c1e36e3e
PA
14478 if (use_range_stepping)
14479 {
6b8edb51
PA
14480 remote_target *remote = get_current_remote_target ();
14481 if (remote == NULL
14482 || !remote->vcont_r_supported ())
14483 warning (_("Range stepping is not supported by the current target"));
c1e36e3e
PA
14484 }
14485}
14486
6c265988 14487void _initialize_remote ();
c906108c 14488void
6c265988 14489_initialize_remote ()
c906108c 14490{
9a7071a8 14491 struct cmd_list_element *cmd;
6f937416 14492 const char *cmd_name;
ea9c271d 14493
0f71a2f6 14494 /* architecture specific data */
29709017
DJ
14495 remote_g_packet_data_handle =
14496 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 14497
d9f719f1
PA
14498 add_target (remote_target_info, remote_target::open);
14499 add_target (extended_remote_target_info, extended_remote_target::open);
cce74817 14500
dc8acb97 14501 /* Hook into new objfile notification. */
76727919 14502 gdb::observers::new_objfile.attach (remote_new_objfile);
dc8acb97 14503
c906108c
SS
14504#if 0
14505 init_remote_threadtests ();
14506#endif
14507
23860348 14508 /* set/show remote ... */
d471ea57 14509
0743fc83 14510 add_basic_prefix_cmd ("remote", class_maintenance, _("\
590042fc 14511Remote protocol specific variables.\n\
5a2468f5 14512Configure various remote-protocol specific variables such as\n\
590042fc 14513the packets being used."),
0743fc83
TT
14514 &remote_set_cmdlist, "set remote ",
14515 0 /* allow-unknown */, &setlist);
1bedd215 14516 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
590042fc 14517Remote protocol specific variables.\n\
5a2468f5 14518Configure various remote-protocol specific variables such as\n\
590042fc 14519the packets being used."),
cff3e48b 14520 &remote_show_cmdlist, "show remote ",
23860348 14521 0 /* allow-unknown */, &showlist);
5a2468f5 14522
1a966eab
AC
14523 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14524Compare section data on target to the exec file.\n\
95cf3b38
DT
14525Argument is a single section name (default: all loaded sections).\n\
14526To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
14527 &cmdlist);
14528
1a966eab
AC
14529 add_cmd ("packet", class_maintenance, packet_command, _("\
14530Send an arbitrary packet to a remote target.\n\
c906108c
SS
14531 maintenance packet TEXT\n\
14532If GDB is talking to an inferior via the GDB serial protocol, then\n\
14533this command sends the string TEXT to the inferior, and displays the\n\
14534response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 14535terminating `#' character and checksum."),
c906108c
SS
14536 &maintenancelist);
14537
7915a72c
AC
14538 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14539Set whether to send break if interrupted."), _("\
14540Show whether to send break if interrupted."), _("\
14541If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 14542 set_remotebreak, show_remotebreak,
e707bbc2 14543 &setlist, &showlist);
9a7071a8 14544 cmd_name = "remotebreak";
cf00cd6f 14545 cmd = lookup_cmd (&cmd_name, setlist, "", NULL, -1, 1);
9a7071a8
JB
14546 deprecate_cmd (cmd, "set remote interrupt-sequence");
14547 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
cf00cd6f 14548 cmd = lookup_cmd (&cmd_name, showlist, "", NULL, -1, 1);
9a7071a8
JB
14549 deprecate_cmd (cmd, "show remote interrupt-sequence");
14550
14551 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
14552 interrupt_sequence_modes, &interrupt_sequence_mode,
14553 _("\
9a7071a8
JB
14554Set interrupt sequence to remote target."), _("\
14555Show interrupt sequence to remote target."), _("\
14556Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14557 NULL, show_interrupt_sequence,
14558 &remote_set_cmdlist,
14559 &remote_show_cmdlist);
14560
14561 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14562 &interrupt_on_connect, _("\
590042fc
PW
14563Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
14564Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
9a7071a8
JB
14565If set, interrupt sequence is sent to remote target."),
14566 NULL, NULL,
14567 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 14568
23860348 14569 /* Install commands for configuring memory read/write packets. */
11cf8741 14570
1a966eab
AC
14571 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14572Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 14573 &setlist);
1a966eab
AC
14574 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14575Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
14576 &showlist);
14577 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
14578 set_memory_write_packet_size, _("\
14579Set the maximum number of bytes per memory-write packet.\n\
14580Specify the number of bytes in a packet or 0 (zero) for the\n\
14581default packet size. The actual limit is further reduced\n\
14582dependent on the target. Specify ``fixed'' to disable the\n\
14583further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14584 &remote_set_cmdlist);
14585 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
14586 set_memory_read_packet_size, _("\
14587Set the maximum number of bytes per memory-read packet.\n\
14588Specify the number of bytes in a packet or 0 (zero) for the\n\
14589default packet size. The actual limit is further reduced\n\
14590dependent on the target. Specify ``fixed'' to disable the\n\
14591further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14592 &remote_set_cmdlist);
14593 add_cmd ("memory-write-packet-size", no_class,
14594 show_memory_write_packet_size,
1a966eab 14595 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
14596 &remote_show_cmdlist);
14597 add_cmd ("memory-read-packet-size", no_class,
14598 show_memory_read_packet_size,
1a966eab 14599 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 14600 &remote_show_cmdlist);
c906108c 14601
055303e2 14602 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
14603 &remote_hw_watchpoint_limit, _("\
14604Set the maximum number of target hardware watchpoints."), _("\
14605Show the maximum number of target hardware watchpoints."), _("\
055303e2
AB
14606Specify \"unlimited\" for unlimited hardware watchpoints."),
14607 NULL, show_hardware_watchpoint_limit,
14608 &remote_set_cmdlist,
14609 &remote_show_cmdlist);
14610 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
14611 no_class,
480a3f21
PW
14612 &remote_hw_watchpoint_length_limit, _("\
14613Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14614Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
055303e2
AB
14615Specify \"unlimited\" to allow watchpoints of unlimited size."),
14616 NULL, show_hardware_watchpoint_length_limit,
480a3f21 14617 &remote_set_cmdlist, &remote_show_cmdlist);
055303e2 14618 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
14619 &remote_hw_breakpoint_limit, _("\
14620Set the maximum number of target hardware breakpoints."), _("\
14621Show the maximum number of target hardware breakpoints."), _("\
055303e2
AB
14622Specify \"unlimited\" for unlimited hardware breakpoints."),
14623 NULL, show_hardware_breakpoint_limit,
b3f42336 14624 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 14625
1b493192
PA
14626 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14627 &remote_address_size, _("\
4d28ad1e
AC
14628Set the maximum size of the address (in bits) in a memory packet."), _("\
14629Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
14630 NULL,
14631 NULL, /* FIXME: i18n: */
14632 &setlist, &showlist);
c906108c 14633
ca4f7f8b
PA
14634 init_all_packet_configs ();
14635
444abaca 14636 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 14637 "X", "binary-download", 1);
0f71a2f6 14638
444abaca 14639 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 14640 "vCont", "verbose-resume", 0);
506fb367 14641
89be2091
DJ
14642 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14643 "QPassSignals", "pass-signals", 0);
14644
82075af2
JS
14645 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14646 "QCatchSyscalls", "catch-syscalls", 0);
14647
9b224c5e
PA
14648 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14649 "QProgramSignals", "program-signals", 0);
14650
bc3b087d
SDJ
14651 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14652 "QSetWorkingDir", "set-working-dir", 0);
14653
aefd8b33
SDJ
14654 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14655 "QStartupWithShell", "startup-with-shell", 0);
14656
0a2dde4a
SDJ
14657 add_packet_config_cmd (&remote_protocol_packets
14658 [PACKET_QEnvironmentHexEncoded],
14659 "QEnvironmentHexEncoded", "environment-hex-encoded",
14660 0);
14661
14662 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14663 "QEnvironmentReset", "environment-reset",
14664 0);
14665
14666 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14667 "QEnvironmentUnset", "environment-unset",
14668 0);
14669
444abaca 14670 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 14671 "qSymbol", "symbol-lookup", 0);
dc8acb97 14672
444abaca 14673 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 14674 "P", "set-register", 1);
d471ea57 14675
444abaca 14676 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 14677 "p", "fetch-register", 1);
b96ec7ac 14678
444abaca 14679 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 14680 "Z0", "software-breakpoint", 0);
d471ea57 14681
444abaca 14682 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 14683 "Z1", "hardware-breakpoint", 0);
d471ea57 14684
444abaca 14685 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 14686 "Z2", "write-watchpoint", 0);
d471ea57 14687
444abaca 14688 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 14689 "Z3", "read-watchpoint", 0);
d471ea57 14690
444abaca 14691 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 14692 "Z4", "access-watchpoint", 0);
d471ea57 14693
0876f84a
DJ
14694 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14695 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 14696
c78fa86a
GB
14697 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14698 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14699
23181151
DJ
14700 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14701 "qXfer:features:read", "target-features", 0);
14702
cfa9d6d9
DJ
14703 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14704 "qXfer:libraries:read", "library-info", 0);
14705
2268b414
JK
14706 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14707 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14708
fd79ecee
DJ
14709 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14710 "qXfer:memory-map:read", "memory-map", 0);
14711
07e059b5 14712 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
dda83cd7 14713 "qXfer:osdata:read", "osdata", 0);
07e059b5 14714
dc146f7c
VP
14715 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14716 "qXfer:threads:read", "threads", 0);
14717
4aa995e1 14718 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
dda83cd7 14719 "qXfer:siginfo:read", "read-siginfo-object", 0);
4aa995e1
PA
14720
14721 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
dda83cd7 14722 "qXfer:siginfo:write", "write-siginfo-object", 0);
4aa995e1 14723
b3b9301e
PA
14724 add_packet_config_cmd
14725 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 14726 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 14727
169081d0
TG
14728 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14729 "qXfer:uib:read", "unwind-info-block", 0);
14730
444abaca 14731 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 14732 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
14733 0);
14734
711e434b
PM
14735 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14736 "qGetTIBAddr", "get-thread-information-block-address",
14737 0);
14738
40ab02ce
MS
14739 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14740 "bc", "reverse-continue", 0);
14741
14742 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14743 "bs", "reverse-step", 0);
14744
be2a5f71
DJ
14745 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14746 "qSupported", "supported-packets", 0);
14747
08388c79
DE
14748 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14749 "qSearch:memory", "search-memory", 0);
14750
bd3eecc3
PA
14751 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14752 "qTStatus", "trace-status", 0);
14753
15a201c8
GB
14754 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14755 "vFile:setfs", "hostio-setfs", 0);
14756
a6b151f1
DJ
14757 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14758 "vFile:open", "hostio-open", 0);
14759
14760 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14761 "vFile:pread", "hostio-pread", 0);
14762
14763 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14764 "vFile:pwrite", "hostio-pwrite", 0);
14765
14766 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14767 "vFile:close", "hostio-close", 0);
14768
14769 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14770 "vFile:unlink", "hostio-unlink", 0);
14771
b9e7b9c3
UW
14772 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14773 "vFile:readlink", "hostio-readlink", 0);
14774
0a93529c
GB
14775 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14776 "vFile:fstat", "hostio-fstat", 0);
14777
2d717e4f
DJ
14778 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14779 "vAttach", "attach", 0);
14780
14781 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14782 "vRun", "run", 0);
14783
a6f3e723
SL
14784 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14785 "QStartNoAckMode", "noack", 0);
14786
82f73884
PA
14787 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14788 "vKill", "kill", 0);
14789
0b16c5cf
PA
14790 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14791 "qAttached", "query-attached", 0);
14792
782b2b07 14793 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
14794 "ConditionalTracepoints",
14795 "conditional-tracepoints", 0);
3788aec7
LM
14796
14797 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14798 "ConditionalBreakpoints",
14799 "conditional-breakpoints", 0);
14800
d3ce09f5
SS
14801 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14802 "BreakpointCommands",
14803 "breakpoint-commands", 0);
14804
7a697b8d
SS
14805 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14806 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 14807
409873ef
SS
14808 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14809 "TracepointSource", "TracepointSource", 0);
14810
d914c394
SS
14811 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14812 "QAllow", "allow", 0);
14813
0fb4aa4b
PA
14814 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14815 "StaticTracepoints", "static-tracepoints", 0);
14816
1e4d1764
YQ
14817 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14818 "InstallInTrace", "install-in-trace", 0);
14819
0fb4aa4b 14820 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
dda83cd7 14821 "qXfer:statictrace:read", "read-sdata-object", 0);
0fb4aa4b 14822
78d85199
YQ
14823 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14824 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14825
03583c20
UW
14826 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14827 "QDisableRandomization", "disable-randomization", 0);
14828
d1feda86
YQ
14829 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14830 "QAgent", "agent", 0);
14831
f6f899bf
HAQ
14832 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14833 "QTBuffer:size", "trace-buffer-size", 0);
14834
9accd112
MM
14835 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14836 "Qbtrace:off", "disable-btrace", 0);
14837
14838 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
14839 "Qbtrace:bts", "enable-btrace-bts", 0);
14840
14841 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14842 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
14843
14844 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14845 "qXfer:btrace", "read-btrace", 0);
14846
f4abbc16
MM
14847 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14848 "qXfer:btrace-conf", "read-btrace-conf", 0);
14849
d33501a5
MM
14850 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14851 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14852
73b8c1fd
PA
14853 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14854 "multiprocess-feature", "multiprocess-feature", 0);
14855
f7e6eed5 14856 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
dda83cd7 14857 "swbreak-feature", "swbreak-feature", 0);
f7e6eed5
PA
14858
14859 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
dda83cd7 14860 "hwbreak-feature", "hwbreak-feature", 0);
f7e6eed5 14861
89245bc0
DB
14862 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14863 "fork-event-feature", "fork-event-feature", 0);
14864
14865 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14866 "vfork-event-feature", "vfork-event-feature", 0);
14867
b20a6524
MM
14868 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14869 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14870
750ce8d1
YQ
14871 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14872 "vContSupported", "verbose-resume-supported", 0);
14873
94585166
DB
14874 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14875 "exec-event-feature", "exec-event-feature", 0);
14876
de979965
PA
14877 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14878 "vCtrlC", "ctrl-c", 0);
14879
65706a29
PA
14880 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14881 "QThreadEvents", "thread-events", 0);
14882
f2faf941
PA
14883 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14884 "N stop reply", "no-resumed-stop-reply", 0);
14885
0b736949
DB
14886 /* Assert that we've registered "set remote foo-packet" commands
14887 for all packet configs. */
ca4f7f8b
PA
14888 {
14889 int i;
14890
14891 for (i = 0; i < PACKET_MAX; i++)
14892 {
14893 /* Ideally all configs would have a command associated. Some
14894 still don't though. */
14895 int excepted;
14896
14897 switch (i)
14898 {
14899 case PACKET_QNonStop:
ca4f7f8b
PA
14900 case PACKET_EnableDisableTracepoints_feature:
14901 case PACKET_tracenz_feature:
14902 case PACKET_DisconnectedTracing_feature:
14903 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
14904 case PACKET_qCRC:
14905 /* Additions to this list need to be well justified:
14906 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
14907 excepted = 1;
14908 break;
14909 default:
14910 excepted = 0;
14911 break;
14912 }
14913
14914 /* This catches both forgetting to add a config command, and
14915 forgetting to remove a packet from the exception list. */
14916 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14917 }
14918 }
14919
37a105a1
DJ
14920 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14921 Z sub-packet has its own set and show commands, but users may
14922 have sets to this variable in their .gdbinit files (or in their
14923 documentation). */
e9e68a56 14924 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c 14925 &remote_Z_packet_detect, _("\
590042fc
PW
14926Set use of remote protocol `Z' packets."), _("\
14927Show use of remote protocol `Z' packets."), _("\
3b64bf98 14928When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 14929packets."),
e9e68a56 14930 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
14931 show_remote_protocol_Z_packet_cmd,
14932 /* FIXME: i18n: Use of remote protocol
14933 `Z' packets is %s. */
e9e68a56 14934 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 14935
0743fc83 14936 add_basic_prefix_cmd ("remote", class_files, _("\
590042fc 14937Manipulate files on the remote system.\n\
a6b151f1 14938Transfer files to and from the remote target system."),
0743fc83
TT
14939 &remote_cmdlist, "remote ",
14940 0 /* allow-unknown */, &cmdlist);
a6b151f1
DJ
14941
14942 add_cmd ("put", class_files, remote_put_command,
14943 _("Copy a local file to the remote system."),
14944 &remote_cmdlist);
14945
14946 add_cmd ("get", class_files, remote_get_command,
14947 _("Copy a remote file to the local system."),
14948 &remote_cmdlist);
14949
14950 add_cmd ("delete", class_files, remote_delete_command,
14951 _("Delete a remote file."),
14952 &remote_cmdlist);
14953
2d717e4f 14954 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 14955 &remote_exec_file_var, _("\
590042fc
PW
14956Set the remote pathname for \"run\"."), _("\
14957Show the remote pathname for \"run\"."), NULL,
94585166
DB
14958 set_remote_exec_file,
14959 show_remote_exec_file,
14960 &remote_set_cmdlist,
14961 &remote_show_cmdlist);
2d717e4f 14962
c1e36e3e
PA
14963 add_setshow_boolean_cmd ("range-stepping", class_run,
14964 &use_range_stepping, _("\
14965Enable or disable range stepping."), _("\
14966Show whether target-assisted range stepping is enabled."), _("\
14967If on, and the target supports it, when stepping a source line, GDB\n\
14968tells the target to step the corresponding range of addresses itself instead\n\
14969of issuing multiple single-steps. This speeds up source level\n\
14970stepping. If off, GDB always issues single-steps, even if range\n\
14971stepping is supported by the target. The default is on."),
14972 set_range_stepping,
14973 show_range_stepping,
14974 &setlist,
14975 &showlist);
14976
ed2b7c17
TT
14977 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
14978Set watchdog timer."), _("\
14979Show watchdog timer."), _("\
14980When non-zero, this timeout is used instead of waiting forever for a target\n\
14981to finish a low-level step or continue operation. If the specified amount\n\
14982of time passes without a response from the target, an error occurs."),
14983 NULL,
14984 show_watchdog,
14985 &setlist, &showlist);
14986
6cc8564b
LM
14987 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
14988 &remote_packet_max_chars, _("\
14989Set the maximum number of characters to display for each remote packet."), _("\
14990Show the maximum number of characters to display for each remote packet."), _("\
14991Specify \"unlimited\" to display all the characters."),
14992 NULL, show_remote_packet_max_chars,
14993 &setdebuglist, &showdebuglist);
14994
449092f6 14995 /* Eventually initialize fileio. See fileio.c */
3f4d92eb 14996 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
c906108c 14997}
This page took 4.150193 seconds and 4 git commands to generate.