Minor C++-ification in ravenscar-thread.c
[deliverable/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
42a4f53d 3 Copyright (C) 1988-2019 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"
0747795c
TT
45#include "common/filestuff.h"
46#include "common/rsp-low.h"
6b940e6a 47#include "disasm.h"
f00aae0f 48#include "location.h"
c906108c 49
0747795c 50#include "common/gdb_sys_time.h"
c906108c 51
43ff13b4 52#include "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
6240bebf
MS
59#include "gdbcore.h" /* for exec_bfd */
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"
0747795c 71#include "common/agent.h"
9accd112 72#include "btrace.h"
c0272db5 73#include "record-btrace.h"
325fac50 74#include <algorithm>
2ec845e7 75#include "common/scoped_restore.h"
0747795c 76#include "common/environ.h"
f6327dcb 77#include "common/byte-vector.h"
9d6eea31 78#include <unordered_map>
35b1e5cc 79
f6ac5f3d
PA
80/* The remote target. */
81
d9f719f1
PA
82static const char remote_doc[] = N_("\
83Use a remote computer via a serial line, using a gdb-specific protocol.\n\
84Specify the serial device it is connected to\n\
85(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
86
6b8edb51
PA
87#define OPAQUETHREADBYTES 8
88
89/* a 64 bit opaque identifier */
90typedef unsigned char threadref[OPAQUETHREADBYTES];
91
92struct gdb_ext_thread_info;
93struct threads_listing_context;
94typedef int (*rmt_thread_action) (threadref *ref, void *context);
95struct protocol_feature;
96struct packet_reg;
97
98struct stop_reply;
953edf2b 99static void stop_reply_xfree (struct stop_reply *);
6b8edb51 100
953edf2b
TT
101struct stop_reply_deleter
102{
103 void operator() (stop_reply *r) const
104 {
105 stop_reply_xfree (r);
106 }
107};
108
109typedef std::unique_ptr<stop_reply, stop_reply_deleter> stop_reply_up;
6b8edb51
PA
110
111/* Generic configuration support for packets the stub optionally
112 supports. Allows the user to specify the use of the packet as well
113 as allowing GDB to auto-detect support in the remote stub. */
114
115enum packet_support
116 {
117 PACKET_SUPPORT_UNKNOWN = 0,
118 PACKET_ENABLE,
119 PACKET_DISABLE
120 };
121
122/* Analyze a packet's return value and update the packet config
123 accordingly. */
124
125enum packet_result
126{
127 PACKET_ERROR,
128 PACKET_OK,
129 PACKET_UNKNOWN
130};
131
132struct threads_listing_context;
3c69da40
PA
133
134/* Stub vCont actions support.
135
136 Each field is a boolean flag indicating whether the stub reports
137 support for the corresponding action. */
138
139struct vCont_action_support
140{
141 /* vCont;t */
142 bool t = false;
143
144 /* vCont;r */
145 bool r = false;
146
147 /* vCont;s */
148 bool s = false;
149
150 /* vCont;S */
151 bool S = false;
152};
153
154/* About this many threadisds fit in a packet. */
155
156#define MAXTHREADLISTRESULTS 32
157
158/* Data for the vFile:pread readahead cache. */
159
160struct readahead_cache
161{
162 /* Invalidate the readahead cache. */
163 void invalidate ();
164
165 /* Invalidate the readahead cache if it is holding data for FD. */
166 void invalidate_fd (int fd);
167
168 /* Serve pread from the readahead cache. Returns number of bytes
169 read, or 0 if the request can't be served from the cache. */
170 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
171
172 /* The file descriptor for the file that is being cached. -1 if the
173 cache is invalid. */
174 int fd = -1;
175
176 /* The offset into the file that the cache buffer corresponds
177 to. */
178 ULONGEST offset = 0;
179
180 /* The buffer holding the cache contents. */
181 gdb_byte *buf = nullptr;
182 /* The buffer's size. We try to read as much as fits into a packet
183 at a time. */
184 size_t bufsize = 0;
185
186 /* Cache hit and miss counters. */
187 ULONGEST hit_count = 0;
188 ULONGEST miss_count = 0;
189};
190
191/* Description of the remote protocol for a given architecture. */
192
193struct packet_reg
194{
195 long offset; /* Offset into G packet. */
196 long regnum; /* GDB's internal register number. */
197 LONGEST pnum; /* Remote protocol register number. */
198 int in_g_packet; /* Always part of G packet. */
199 /* long size in bytes; == register_size (target_gdbarch (), regnum);
200 at present. */
201 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
202 at present. */
203};
204
205struct remote_arch_state
206{
207 explicit remote_arch_state (struct gdbarch *gdbarch);
208
209 /* Description of the remote protocol registers. */
210 long sizeof_g_packet;
211
212 /* Description of the remote protocol registers indexed by REGNUM
213 (making an array gdbarch_num_regs in size). */
214 std::unique_ptr<packet_reg[]> regs;
215
216 /* This is the size (in chars) of the first response to the ``g''
217 packet. It is used as a heuristic when determining the maximum
218 size of memory-read and memory-write packets. A target will
219 typically only reserve a buffer large enough to hold the ``g''
220 packet. The size does not include packet overhead (headers and
221 trailers). */
222 long actual_register_packet_size;
223
224 /* This is the maximum size (in chars) of a non read/write packet.
225 It is also used as a cap on the size of read/write packets. */
226 long remote_packet_size;
227};
228
229/* Description of the remote protocol state for the currently
230 connected target. This is per-target state, and independent of the
231 selected architecture. */
232
233class remote_state
234{
235public:
236
237 remote_state ();
238 ~remote_state ();
239
240 /* Get the remote arch state for GDBARCH. */
241 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
242
243public: /* data */
244
245 /* A buffer to use for incoming packets, and its current size. The
246 buffer is grown dynamically for larger incoming packets.
247 Outgoing packets may also be constructed in this buffer.
8d64371b 248 The size of the buffer is always at least REMOTE_PACKET_SIZE;
3c69da40
PA
249 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
250 packets. */
8d64371b 251 gdb::char_vector buf;
3c69da40
PA
252
253 /* True if we're going through initial connection setup (finding out
254 about the remote side's threads, relocating symbols, etc.). */
255 bool starting_up = false;
256
257 /* If we negotiated packet size explicitly (and thus can bypass
258 heuristics for the largest packet size that will not overflow
259 a buffer in the stub), this will be set to that packet size.
260 Otherwise zero, meaning to use the guessed size. */
261 long explicit_packet_size = 0;
262
263 /* remote_wait is normally called when the target is running and
264 waits for a stop reply packet. But sometimes we need to call it
265 when the target is already stopped. We can send a "?" packet
266 and have remote_wait read the response. Or, if we already have
267 the response, we can stash it in BUF and tell remote_wait to
268 skip calling getpkt. This flag is set when BUF contains a
269 stop reply packet and the target is not waiting. */
270 int cached_wait_status = 0;
271
272 /* True, if in no ack mode. That is, neither GDB nor the stub will
273 expect acks from each other. The connection is assumed to be
274 reliable. */
275 bool noack_mode = false;
276
277 /* True if we're connected in extended remote mode. */
278 bool extended = false;
279
280 /* True if we resumed the target and we're waiting for the target to
281 stop. In the mean time, we can't start another command/query.
282 The remote server wouldn't be ready to process it, so we'd
283 timeout waiting for a reply that would never come and eventually
284 we'd close the connection. This can happen in asynchronous mode
285 because we allow GDB commands while the target is running. */
286 bool waiting_for_stop_reply = false;
287
288 /* The status of the stub support for the various vCont actions. */
289 vCont_action_support supports_vCont;
290
291 /* True if the user has pressed Ctrl-C, but the target hasn't
292 responded to that. */
293 bool ctrlc_pending_p = false;
294
295 /* True if we saw a Ctrl-C while reading or writing from/to the
296 remote descriptor. At that point it is not safe to send a remote
297 interrupt packet, so we instead remember we saw the Ctrl-C and
298 process it once we're done with sending/receiving the current
299 packet, which should be shortly. If however that takes too long,
300 and the user presses Ctrl-C again, we offer to disconnect. */
301 bool got_ctrlc_during_io = false;
302
303 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
304 remote_open knows that we don't have a file open when the program
305 starts. */
306 struct serial *remote_desc = nullptr;
307
308 /* These are the threads which we last sent to the remote system. The
309 TID member will be -1 for all or -2 for not sent yet. */
310 ptid_t general_thread = null_ptid;
311 ptid_t continue_thread = null_ptid;
312
313 /* This is the traceframe which we last selected on the remote system.
314 It will be -1 if no traceframe is selected. */
315 int remote_traceframe_number = -1;
316
317 char *last_pass_packet = nullptr;
318
319 /* The last QProgramSignals packet sent to the target. We bypass
320 sending a new program signals list down to the target if the new
321 packet is exactly the same as the last we sent. IOW, we only let
322 the target know about program signals list changes. */
323 char *last_program_signals_packet = nullptr;
324
325 gdb_signal last_sent_signal = GDB_SIGNAL_0;
326
327 bool last_sent_step = false;
328
329 /* The execution direction of the last resume we got. */
330 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
331
332 char *finished_object = nullptr;
333 char *finished_annex = nullptr;
334 ULONGEST finished_offset = 0;
335
336 /* Should we try the 'ThreadInfo' query packet?
337
338 This variable (NOT available to the user: auto-detect only!)
339 determines whether GDB will use the new, simpler "ThreadInfo"
340 query or the older, more complex syntax for thread queries.
341 This is an auto-detect variable (set to true at each connect,
342 and set to false when the target fails to recognize it). */
343 bool use_threadinfo_query = false;
344 bool use_threadextra_query = false;
345
346 threadref echo_nextthread {};
347 threadref nextthread {};
348 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
349
350 /* The state of remote notification. */
351 struct remote_notif_state *notif_state = nullptr;
352
353 /* The branch trace configuration. */
354 struct btrace_config btrace_config {};
355
356 /* The argument to the last "vFile:setfs:" packet we sent, used
357 to avoid sending repeated unnecessary "vFile:setfs:" packets.
358 Initialized to -1 to indicate that no "vFile:setfs:" packet
359 has yet been sent. */
360 int fs_pid = -1;
361
362 /* A readahead cache for vFile:pread. Often, reading a binary
363 involves a sequence of small reads. E.g., when parsing an ELF
364 file. A readahead cache helps mostly the case of remote
365 debugging on a connection with higher latency, due to the
366 request/reply nature of the RSP. We only cache data for a single
367 file descriptor at a time. */
368 struct readahead_cache readahead_cache;
369
370 /* The list of already fetched and acknowledged stop events. This
371 queue is used for notification Stop, and other notifications
372 don't need queue for their events, because the notification
373 events of Stop can't be consumed immediately, so that events
374 should be queued first, and be consumed by remote_wait_{ns,as}
375 one per time. Other notifications can consume their events
376 immediately, so queue is not needed for them. */
953edf2b 377 std::vector<stop_reply_up> stop_reply_queue;
3c69da40
PA
378
379 /* Asynchronous signal handle registered as event loop source for
380 when we have pending events ready to be passed to the core. */
381 struct async_event_handler *remote_async_inferior_event_token = nullptr;
382
383 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
384 ``forever'' still use the normal timeout mechanism. This is
385 currently used by the ASYNC code to guarentee that target reads
386 during the initial connect always time-out. Once getpkt has been
387 modified to return a timeout indication and, in turn
388 remote_wait()/wait_for_inferior() have gained a timeout parameter
389 this can go away. */
390 int wait_forever_enabled_p = 1;
391
392private:
393 /* Mapping of remote protocol data for each gdbarch. Usually there
394 is only one entry here, though we may see more with stubs that
395 support multi-process. */
396 std::unordered_map<struct gdbarch *, remote_arch_state>
397 m_arch_states;
398};
6b8edb51 399
d9f719f1
PA
400static const target_info remote_target_info = {
401 "remote",
402 N_("Remote serial target in gdb-specific protocol"),
403 remote_doc
404};
405
3b3dac9b 406class remote_target : public process_stratum_target
f6ac5f3d
PA
407{
408public:
3b3dac9b 409 remote_target () = default;
6b8edb51 410 ~remote_target () override;
f6ac5f3d 411
d9f719f1
PA
412 const target_info &info () const override
413 { return remote_target_info; }
f6ac5f3d
PA
414
415 thread_control_capabilities get_thread_control_capabilities () override
416 { return tc_schedlock; }
417
d9f719f1
PA
418 /* Open a remote connection. */
419 static void open (const char *, int);
420
f6ac5f3d
PA
421 void close () override;
422
423 void detach (inferior *, int) override;
424 void disconnect (const char *, int) override;
425
426 void commit_resume () override;
427 void resume (ptid_t, int, enum gdb_signal) override;
428 ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
429
430 void fetch_registers (struct regcache *, int) override;
431 void store_registers (struct regcache *, int) override;
432 void prepare_to_store (struct regcache *) override;
433
434 void files_info () override;
435
436 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
437
438 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
439 enum remove_bp_reason) override;
440
441
57810aa7
PA
442 bool stopped_by_sw_breakpoint () override;
443 bool supports_stopped_by_sw_breakpoint () override;
f6ac5f3d 444
57810aa7 445 bool stopped_by_hw_breakpoint () override;
f6ac5f3d 446
57810aa7 447 bool supports_stopped_by_hw_breakpoint () override;
f6ac5f3d 448
57810aa7 449 bool stopped_by_watchpoint () override;
f6ac5f3d 450
57810aa7 451 bool stopped_data_address (CORE_ADDR *) override;
f6ac5f3d 452
57810aa7 453 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
f6ac5f3d
PA
454
455 int can_use_hw_breakpoint (enum bptype, int, int) override;
456
457 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
458
459 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
460
461 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
462
463 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
464 struct expression *) override;
465
466 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
467 struct expression *) override;
468
469 void kill () override;
470
471 void load (const char *, int) override;
472
473 void mourn_inferior () override;
474
adc6a863 475 void pass_signals (gdb::array_view<const unsigned char>) override;
f6ac5f3d
PA
476
477 int set_syscall_catchpoint (int, bool, int,
478 gdb::array_view<const int>) override;
479
adc6a863 480 void program_signals (gdb::array_view<const unsigned char>) override;
f6ac5f3d 481
57810aa7 482 bool thread_alive (ptid_t ptid) override;
f6ac5f3d
PA
483
484 const char *thread_name (struct thread_info *) override;
485
486 void update_thread_list () override;
487
488 const char *pid_to_str (ptid_t) override;
489
490 const char *extra_thread_info (struct thread_info *) override;
491
492 ptid_t get_ada_task_ptid (long lwp, long thread) override;
493
494 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
495 int handle_len,
496 inferior *inf) override;
497
498 void stop (ptid_t) override;
499
500 void interrupt () override;
501
502 void pass_ctrlc () override;
503
504 enum target_xfer_status xfer_partial (enum target_object object,
505 const char *annex,
506 gdb_byte *readbuf,
507 const gdb_byte *writebuf,
508 ULONGEST offset, ULONGEST len,
509 ULONGEST *xfered_len) override;
510
511 ULONGEST get_memory_xfer_limit () override;
512
513 void rcmd (const char *command, struct ui_file *output) override;
514
515 char *pid_to_exec_file (int pid) override;
516
517 void log_command (const char *cmd) override
518 {
519 serial_log_command (this, cmd);
520 }
521
522 CORE_ADDR get_thread_local_address (ptid_t ptid,
523 CORE_ADDR load_module_addr,
524 CORE_ADDR offset) override;
525
57810aa7 526 bool can_execute_reverse () override;
f6ac5f3d
PA
527
528 std::vector<mem_region> memory_map () override;
529
530 void flash_erase (ULONGEST address, LONGEST length) override;
531
532 void flash_done () override;
533
534 const struct target_desc *read_description () override;
535
536 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
537 const gdb_byte *pattern, ULONGEST pattern_len,
538 CORE_ADDR *found_addrp) override;
539
57810aa7 540 bool can_async_p () override;
f6ac5f3d 541
57810aa7 542 bool is_async_p () override;
f6ac5f3d
PA
543
544 void async (int) override;
545
546 void thread_events (int) override;
547
548 int can_do_single_step () override;
549
550 void terminal_inferior () override;
551
552 void terminal_ours () override;
553
57810aa7 554 bool supports_non_stop () override;
f6ac5f3d 555
57810aa7 556 bool supports_multi_process () override;
f6ac5f3d 557
57810aa7 558 bool supports_disable_randomization () override;
f6ac5f3d 559
57810aa7 560 bool filesystem_is_local () override;
f6ac5f3d
PA
561
562
563 int fileio_open (struct inferior *inf, const char *filename,
564 int flags, int mode, int warn_if_slow,
565 int *target_errno) override;
566
567 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
568 ULONGEST offset, int *target_errno) override;
569
570 int fileio_pread (int fd, gdb_byte *read_buf, int len,
571 ULONGEST offset, int *target_errno) override;
572
573 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
574
575 int fileio_close (int fd, int *target_errno) override;
576
577 int fileio_unlink (struct inferior *inf,
578 const char *filename,
579 int *target_errno) override;
580
581 gdb::optional<std::string>
582 fileio_readlink (struct inferior *inf,
583 const char *filename,
584 int *target_errno) override;
585
57810aa7 586 bool supports_enable_disable_tracepoint () override;
f6ac5f3d 587
57810aa7 588 bool supports_string_tracing () override;
f6ac5f3d 589
57810aa7 590 bool supports_evaluation_of_breakpoint_conditions () override;
f6ac5f3d 591
57810aa7 592 bool can_run_breakpoint_commands () override;
f6ac5f3d
PA
593
594 void trace_init () override;
595
596 void download_tracepoint (struct bp_location *location) override;
597
57810aa7 598 bool can_download_tracepoint () override;
f6ac5f3d
PA
599
600 void download_trace_state_variable (const trace_state_variable &tsv) override;
601
602 void enable_tracepoint (struct bp_location *location) override;
603
604 void disable_tracepoint (struct bp_location *location) override;
605
606 void trace_set_readonly_regions () override;
607
608 void trace_start () override;
609
610 int get_trace_status (struct trace_status *ts) override;
611
612 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
613 override;
614
615 void trace_stop () override;
616
617 int trace_find (enum trace_find_type type, int num,
618 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
619
57810aa7 620 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
f6ac5f3d
PA
621
622 int save_trace_data (const char *filename) override;
623
624 int upload_tracepoints (struct uploaded_tp **utpp) override;
625
626 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
627
628 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
629
630 int get_min_fast_tracepoint_insn_len () override;
631
632 void set_disconnected_tracing (int val) override;
633
634 void set_circular_trace_buffer (int val) override;
635
636 void set_trace_buffer_size (LONGEST val) override;
637
57810aa7
PA
638 bool set_trace_notes (const char *user, const char *notes,
639 const char *stopnotes) override;
f6ac5f3d
PA
640
641 int core_of_thread (ptid_t ptid) override;
642
643 int verify_memory (const gdb_byte *data,
644 CORE_ADDR memaddr, ULONGEST size) override;
645
646
57810aa7 647 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
f6ac5f3d
PA
648
649 void set_permissions () override;
650
651 bool static_tracepoint_marker_at (CORE_ADDR,
652 struct static_tracepoint_marker *marker)
653 override;
654
655 std::vector<static_tracepoint_marker>
656 static_tracepoint_markers_by_strid (const char *id) override;
657
658 traceframe_info_up traceframe_info () override;
659
57810aa7
PA
660 bool use_agent (bool use) override;
661 bool can_use_agent () override;
f6ac5f3d
PA
662
663 struct btrace_target_info *enable_btrace (ptid_t ptid,
664 const struct btrace_config *conf) override;
665
666 void disable_btrace (struct btrace_target_info *tinfo) override;
667
668 void teardown_btrace (struct btrace_target_info *tinfo) override;
669
670 enum btrace_error read_btrace (struct btrace_data *data,
671 struct btrace_target_info *btinfo,
672 enum btrace_read_type type) override;
673
674 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
57810aa7 675 bool augmented_libraries_svr4_read () override;
f6ac5f3d
PA
676 int follow_fork (int, int) override;
677 void follow_exec (struct inferior *, char *) override;
678 int insert_fork_catchpoint (int) override;
679 int remove_fork_catchpoint (int) override;
680 int insert_vfork_catchpoint (int) override;
681 int remove_vfork_catchpoint (int) override;
682 int insert_exec_catchpoint (int) override;
683 int remove_exec_catchpoint (int) override;
684 enum exec_direction_kind execution_direction () override;
685
6b8edb51
PA
686public: /* Remote specific methods. */
687
688 void remote_download_command_source (int num, ULONGEST addr,
689 struct command_line *cmds);
690
691 void remote_file_put (const char *local_file, const char *remote_file,
692 int from_tty);
693 void remote_file_get (const char *remote_file, const char *local_file,
694 int from_tty);
695 void remote_file_delete (const char *remote_file, int from_tty);
696
697 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
698 ULONGEST offset, int *remote_errno);
699 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
700 ULONGEST offset, int *remote_errno);
701 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
702 ULONGEST offset, int *remote_errno);
703
704 int remote_hostio_send_command (int command_bytes, int which_packet,
705 int *remote_errno, char **attachment,
706 int *attachment_len);
707 int remote_hostio_set_filesystem (struct inferior *inf,
708 int *remote_errno);
709 /* We should get rid of this and use fileio_open directly. */
710 int remote_hostio_open (struct inferior *inf, const char *filename,
711 int flags, int mode, int warn_if_slow,
712 int *remote_errno);
713 int remote_hostio_close (int fd, int *remote_errno);
714
715 int remote_hostio_unlink (inferior *inf, const char *filename,
716 int *remote_errno);
717
718 struct remote_state *get_remote_state ();
719
720 long get_remote_packet_size (void);
721 long get_memory_packet_size (struct memory_packet_config *config);
722
723 long get_memory_write_packet_size ();
724 long get_memory_read_packet_size ();
725
726 char *append_pending_thread_resumptions (char *p, char *endp,
727 ptid_t ptid);
d9f719f1 728 static void open_1 (const char *name, int from_tty, int extended_p);
f6ac5f3d 729 void start_remote (int from_tty, int extended_p);
00431a78 730 void remote_detach_1 (struct inferior *inf, int from_tty);
6b8edb51
PA
731
732 char *append_resumption (char *p, char *endp,
733 ptid_t ptid, int step, gdb_signal siggnal);
734 int remote_resume_with_vcont (ptid_t ptid, int step,
735 gdb_signal siggnal);
736
737 void add_current_inferior_and_thread (char *wait_status);
738
739 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
740 int options);
741 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
742 int options);
743
744 ptid_t process_stop_reply (struct stop_reply *stop_reply,
745 target_waitstatus *status);
746
747 void remote_notice_new_inferior (ptid_t currthread, int executing);
748
749 void process_initial_stop_replies (int from_tty);
750
00431a78 751 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing);
6b8edb51
PA
752
753 void btrace_sync_conf (const btrace_config *conf);
754
755 void remote_btrace_maybe_reopen ();
756
757 void remove_new_fork_children (threads_listing_context *context);
758 void kill_new_fork_children (int pid);
759 void discard_pending_stop_replies (struct inferior *inf);
760 int stop_reply_queue_length ();
761
762 void check_pending_events_prevent_wildcard_vcont
763 (int *may_global_wildcard_vcont);
764
765 void discard_pending_stop_replies_in_queue ();
766 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
767 struct stop_reply *queued_stop_reply (ptid_t ptid);
768 int peek_stop_reply (ptid_t ptid);
bb277751 769 void remote_parse_stop_reply (const char *buf, stop_reply *event);
6b8edb51
PA
770
771 void remote_stop_ns (ptid_t ptid);
772 void remote_interrupt_as ();
773 void remote_interrupt_ns ();
774
775 char *remote_get_noisy_reply ();
776 int remote_query_attached (int pid);
777 inferior *remote_add_inferior (int fake_pid_p, int pid, int attached,
778 int try_open_exec);
779
780 ptid_t remote_current_thread (ptid_t oldpid);
781 ptid_t get_current_thread (char *wait_status);
782
783 void set_thread (ptid_t ptid, int gen);
784 void set_general_thread (ptid_t ptid);
785 void set_continue_thread (ptid_t ptid);
786 void set_general_process ();
787
788 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
789
790 int remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
791 gdb_ext_thread_info *info);
792 int remote_get_threadinfo (threadref *threadid, int fieldset,
793 gdb_ext_thread_info *info);
794
795 int parse_threadlist_response (char *pkt, int result_limit,
796 threadref *original_echo,
797 threadref *resultlist,
798 int *doneflag);
799 int remote_get_threadlist (int startflag, threadref *nextthread,
800 int result_limit, int *done, int *result_count,
801 threadref *threadlist);
802
803 int remote_threadlist_iterator (rmt_thread_action stepfunction,
804 void *context, int looplimit);
805
806 int remote_get_threads_with_ql (threads_listing_context *context);
807 int remote_get_threads_with_qxfer (threads_listing_context *context);
808 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
809
810 void extended_remote_restart ();
811
812 void get_offsets ();
813
814 void remote_check_symbols ();
815
816 void remote_supported_packet (const struct protocol_feature *feature,
817 enum packet_support support,
818 const char *argument);
819
820 void remote_query_supported ();
821
822 void remote_packet_size (const protocol_feature *feature,
823 packet_support support, const char *value);
824
825 void remote_serial_quit_handler ();
826
827 void remote_detach_pid (int pid);
828
829 void remote_vcont_probe ();
830
831 void remote_resume_with_hc (ptid_t ptid, int step,
832 gdb_signal siggnal);
833
834 void send_interrupt_sequence ();
835 void interrupt_query ();
836
837 void remote_notif_get_pending_events (notif_client *nc);
838
839 int fetch_register_using_p (struct regcache *regcache,
840 packet_reg *reg);
841 int send_g_packet ();
842 void process_g_packet (struct regcache *regcache);
843 void fetch_registers_using_g (struct regcache *regcache);
844 int store_register_using_P (const struct regcache *regcache,
845 packet_reg *reg);
846 void store_registers_using_G (const struct regcache *regcache);
847
848 void set_remote_traceframe ();
849
850 void check_binary_download (CORE_ADDR addr);
851
852 target_xfer_status remote_write_bytes_aux (const char *header,
853 CORE_ADDR memaddr,
854 const gdb_byte *myaddr,
855 ULONGEST len_units,
856 int unit_size,
857 ULONGEST *xfered_len_units,
858 char packet_format,
859 int use_length);
860
861 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
862 const gdb_byte *myaddr, ULONGEST len,
863 int unit_size, ULONGEST *xfered_len);
864
865 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
866 ULONGEST len_units,
867 int unit_size, ULONGEST *xfered_len_units);
868
869 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
870 ULONGEST memaddr,
871 ULONGEST len,
872 int unit_size,
873 ULONGEST *xfered_len);
874
875 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
876 gdb_byte *myaddr, ULONGEST len,
877 int unit_size,
878 ULONGEST *xfered_len);
879
880 packet_result remote_send_printf (const char *format, ...)
881 ATTRIBUTE_PRINTF (2, 3);
882
883 target_xfer_status remote_flash_write (ULONGEST address,
884 ULONGEST length, ULONGEST *xfered_len,
885 const gdb_byte *data);
886
887 int readchar (int timeout);
888
889 void remote_serial_write (const char *str, int len);
890
891 int putpkt (const char *buf);
892 int putpkt_binary (const char *buf, int cnt);
893
8d64371b
TT
894 int putpkt (const gdb::char_vector &buf)
895 {
896 return putpkt (buf.data ());
897 }
898
6b8edb51 899 void skip_frame ();
8d64371b
TT
900 long read_frame (gdb::char_vector *buf_p);
901 void getpkt (gdb::char_vector *buf, int forever);
902 int getpkt_or_notif_sane_1 (gdb::char_vector *buf, int forever,
6b8edb51 903 int expecting_notif, int *is_notif);
8d64371b
TT
904 int getpkt_sane (gdb::char_vector *buf, int forever);
905 int getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
6b8edb51
PA
906 int *is_notif);
907 int remote_vkill (int pid);
908 void remote_kill_k ();
909
910 void extended_remote_disable_randomization (int val);
911 int extended_remote_run (const std::string &args);
912
913 void send_environment_packet (const char *action,
914 const char *packet,
915 const char *value);
916
917 void extended_remote_environment_support ();
3c69da40 918 void extended_remote_set_inferior_cwd ();
80152258 919
3c69da40
PA
920 target_xfer_status remote_write_qxfer (const char *object_name,
921 const char *annex,
922 const gdb_byte *writebuf,
923 ULONGEST offset, LONGEST len,
924 ULONGEST *xfered_len,
925 struct packet_config *packet);
43c3a0e4 926
3c69da40
PA
927 target_xfer_status remote_read_qxfer (const char *object_name,
928 const char *annex,
929 gdb_byte *readbuf, ULONGEST offset,
930 LONGEST len,
931 ULONGEST *xfered_len,
932 struct packet_config *packet);
43c3a0e4 933
3c69da40 934 void push_stop_reply (struct stop_reply *new_event);
43c3a0e4 935
3c69da40 936 bool vcont_r_supported ();
43c3a0e4 937
3c69da40 938 void packet_command (const char *args, int from_tty);
43c3a0e4 939
3c69da40 940private: /* data fields */
43c3a0e4 941
3c69da40
PA
942 /* The remote state. Don't reference this directly. Use the
943 get_remote_state method instead. */
944 remote_state m_remote_state;
43c3a0e4
PA
945};
946
3c69da40
PA
947static const target_info extended_remote_target_info = {
948 "extended-remote",
949 N_("Extended remote serial target in gdb-specific protocol"),
950 remote_doc
951};
ea9c271d 952
3c69da40
PA
953/* Set up the extended remote target by extending the standard remote
954 target and adding to it. */
955
956class extended_remote_target final : public remote_target
ea9c271d 957{
9d6eea31 958public:
3c69da40
PA
959 const target_info &info () const override
960 { return extended_remote_target_info; }
9d6eea31 961
3c69da40
PA
962 /* Open an extended-remote connection. */
963 static void open (const char *, int);
de44f5a7 964
3c69da40
PA
965 bool can_create_inferior () override { return true; }
966 void create_inferior (const char *, const std::string &,
967 char **, int) override;
9d6eea31 968
3c69da40 969 void detach (inferior *, int) override;
9d6eea31 970
3c69da40
PA
971 bool can_attach () override { return true; }
972 void attach (const char *, int) override;
be2a5f71 973
3c69da40
PA
974 void post_attach (int) override;
975 bool supports_disable_randomization () override;
976};
1e51243a 977
3c69da40
PA
978/* Per-program-space data key. */
979static const struct program_space_data *remote_pspace_data;
2d717e4f 980
3c69da40
PA
981/* The variable registered as the control variable used by the
982 remote exec-file commands. While the remote exec-file setting is
983 per-program-space, the set/show machinery uses this as the
984 location of the remote exec-file value. */
985static char *remote_exec_file_var;
a6f3e723 986
3c69da40
PA
987/* The size to align memory write packets, when practical. The protocol
988 does not guarantee any alignment, and gdb will generate short
989 writes and unaligned writes, but even as a best-effort attempt this
990 can improve bulk transfers. For instance, if a write is misaligned
991 relative to the target's data bus, the stub may need to make an extra
992 round trip fetching data from the target. This doesn't make a
993 huge difference, but it's easy to do, so we try to be helpful.
82f73884 994
3c69da40
PA
995 The alignment chosen is arbitrary; usually data bus width is
996 important here, not the possibly larger cache line size. */
997enum { REMOTE_ALIGN_WRITES = 16 };
82f73884 998
3c69da40 999/* Prototypes for local functions. */
74531fed 1000
3c69da40 1001static int hexnumlen (ULONGEST num);
782b2b07 1002
3c69da40 1003static int stubhex (int ch);
5d93a237 1004
3c69da40 1005static int hexnumstr (char *, ULONGEST);
048094ac 1006
3c69da40 1007static int hexnumnstr (char *, ULONGEST, int);
47f8a51d 1008
3c69da40 1009static CORE_ADDR remote_address_masked (CORE_ADDR);
262e1174 1010
3c69da40 1011static void print_packet (const char *);
747dc59d 1012
3c69da40 1013static int stub_unpack_int (char *buff, int fieldlength);
5e4a05c4 1014
3c69da40 1015struct packet_config;
b73be471 1016
3c69da40 1017static void show_packet_config_cmd (struct packet_config *config);
280ceea3 1018
3c69da40
PA
1019static void show_remote_protocol_packet_cmd (struct ui_file *file,
1020 int from_tty,
1021 struct cmd_list_element *c,
1022 const char *value);
8e88304f 1023
3c69da40 1024static ptid_t read_ptid (const char *buf, const char **obuf);
3a00c802 1025
3c69da40 1026static void remote_async_inferior_event_handler (gdb_client_data);
b80fafe3 1027
eefce37f 1028static bool remote_read_description_p (struct target_ops *target);
88b496c3 1029
05be00a8 1030static void remote_console_output (const char *msg);
5965e028 1031
3c69da40 1032static void remote_btrace_reset (remote_state *rs);
f4abbc16 1033
3c69da40 1034static void remote_unpush_and_throw (void);
15a201c8 1035
3c69da40 1036/* For "remote". */
80152258 1037
3c69da40 1038static struct cmd_list_element *remote_cmdlist;
9d6eea31 1039
3c69da40 1040/* For "set remote" and "show remote". */
6b8edb51 1041
3c69da40
PA
1042static struct cmd_list_element *remote_set_cmdlist;
1043static struct cmd_list_element *remote_show_cmdlist;
6b8edb51 1044
3c69da40 1045/* Controls whether GDB is willing to use range stepping. */
6b8edb51 1046
3c69da40
PA
1047static int use_range_stepping = 1;
1048
1049/* The max number of chars in debug output. The rest of chars are
1050 omitted. */
1051
1052#define REMOTE_DEBUG_MAX_CHAR 512
ea9c271d 1053
7aabaf9d
SM
1054/* Private data that we'll store in (struct thread_info)->priv. */
1055struct remote_thread_info : public private_thread_info
dc146f7c 1056{
7aabaf9d
SM
1057 std::string extra;
1058 std::string name;
1059 int core = -1;
799a2abe 1060
f6327dcb
KB
1061 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1062 sequence of bytes. */
7aabaf9d 1063 gdb::byte_vector thread_handle;
f6327dcb 1064
799a2abe 1065 /* Whether the target stopped for a breakpoint/watchpoint. */
7aabaf9d 1066 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
799a2abe
PA
1067
1068 /* This is set to the data address of the access causing the target
1069 to stop for a watchpoint. */
7aabaf9d 1070 CORE_ADDR watch_data_address = 0;
85ad3aaf
PA
1071
1072 /* Fields used by the vCont action coalescing implemented in
1073 remote_resume / remote_commit_resume. remote_resume stores each
1074 thread's last resume request in these fields, so that a later
1075 remote_commit_resume knows which is the proper action for this
1076 thread to include in the vCont packet. */
1077
1078 /* True if the last target_resume call for this thread was a step
1079 request, false if a continue request. */
7aabaf9d 1080 int last_resume_step = 0;
85ad3aaf
PA
1081
1082 /* The signal specified in the last target_resume call for this
1083 thread. */
7aabaf9d 1084 gdb_signal last_resume_sig = GDB_SIGNAL_0;
85ad3aaf
PA
1085
1086 /* Whether this thread was already vCont-resumed on the remote
1087 side. */
7aabaf9d 1088 int vcont_resumed = 0;
dc146f7c
VP
1089};
1090
de44f5a7 1091remote_state::remote_state ()
8d64371b 1092 : buf (400)
de44f5a7 1093{
de44f5a7
PA
1094}
1095
1096remote_state::~remote_state ()
1097{
1098 xfree (this->last_pass_packet);
1099 xfree (this->last_program_signals_packet);
de44f5a7
PA
1100 xfree (this->finished_object);
1101 xfree (this->finished_annex);
cf792862
TT
1102}
1103
35b1e5cc
SS
1104/* Utility: generate error from an incoming stub packet. */
1105static void
1106trace_error (char *buf)
1107{
1108 if (*buf++ != 'E')
1109 return; /* not an error msg */
1110 switch (*buf)
1111 {
1112 case '1': /* malformed packet error */
1113 if (*++buf == '0') /* general case: */
1114 error (_("remote.c: error in outgoing packet."));
1115 else
1116 error (_("remote.c: error in outgoing packet at field #%ld."),
1117 strtol (buf, NULL, 16));
35b1e5cc
SS
1118 default:
1119 error (_("Target returns error code '%s'."), buf);
1120 }
1121}
1122
1123/* Utility: wait for reply from stub, while accepting "O" packets. */
b6bb3468 1124
6b8edb51
PA
1125char *
1126remote_target::remote_get_noisy_reply ()
35b1e5cc 1127{
b6bb3468
PA
1128 struct remote_state *rs = get_remote_state ();
1129
35b1e5cc
SS
1130 do /* Loop on reply from remote stub. */
1131 {
1132 char *buf;
a744cf53 1133
0df8b418 1134 QUIT; /* Allow user to bail out with ^C. */
8d64371b
TT
1135 getpkt (&rs->buf, 0);
1136 buf = rs->buf.data ();
ad91cd99 1137 if (buf[0] == 'E')
35b1e5cc 1138 trace_error (buf);
61012eef 1139 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
1140 {
1141 ULONGEST ul;
1142 CORE_ADDR from, to, org_to;
256642e8 1143 const char *p, *pp;
dde08ee1 1144 int adjusted_size = 0;
7556d4a4 1145 int relocated = 0;
dde08ee1
PA
1146
1147 p = buf + strlen ("qRelocInsn:");
1148 pp = unpack_varlen_hex (p, &ul);
1149 if (*pp != ';')
cb91c06a 1150 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
1151 from = ul;
1152
1153 p = pp + 1;
a9cbf802 1154 unpack_varlen_hex (p, &ul);
dde08ee1
PA
1155 to = ul;
1156
1157 org_to = to;
1158
492d29ea 1159 TRY
dde08ee1 1160 {
f5656ead 1161 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 1162 relocated = 1;
dde08ee1 1163 }
492d29ea 1164 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
1165 {
1166 if (ex.error == MEMORY_ERROR)
1167 {
1168 /* Propagate memory errors silently back to the
1169 target. The stub may have limited the range of
1170 addresses we can write to, for example. */
1171 }
1172 else
1173 {
1174 /* Something unexpectedly bad happened. Be verbose
1175 so we can tell what, and propagate the error back
1176 to the stub, so it doesn't get stuck waiting for
1177 a response. */
1178 exception_fprintf (gdb_stderr, ex,
1179 _("warning: relocating instruction: "));
1180 }
1181 putpkt ("E01");
1182 }
492d29ea 1183 END_CATCH
7556d4a4
PA
1184
1185 if (relocated)
dde08ee1
PA
1186 {
1187 adjusted_size = to - org_to;
1188
8d64371b 1189 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
1190 putpkt (buf);
1191 }
dde08ee1 1192 }
ad91cd99 1193 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
1194 remote_console_output (buf + 1); /* 'O' message from stub */
1195 else
0df8b418 1196 return buf; /* Here's the actual reply. */
35b1e5cc
SS
1197 }
1198 while (1);
1199}
3c3bea1c 1200
9d6eea31
PA
1201struct remote_arch_state *
1202remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
d01949b6 1203{
43c3a0e4
PA
1204 remote_arch_state *rsa;
1205
1206 auto it = this->m_arch_states.find (gdbarch);
1207 if (it == this->m_arch_states.end ())
9d6eea31 1208 {
43c3a0e4
PA
1209 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1210 std::forward_as_tuple (gdbarch),
1211 std::forward_as_tuple (gdbarch));
1212 rsa = &p.first->second;
9d6eea31
PA
1213
1214 /* Make sure that the packet buffer is plenty big enough for
1215 this architecture. */
8d64371b
TT
1216 if (this->buf.size () < rsa->remote_packet_size)
1217 this->buf.resize (2 * rsa->remote_packet_size);
9d6eea31 1218 }
43c3a0e4
PA
1219 else
1220 rsa = &it->second;
1221
1222 return rsa;
d01949b6
AC
1223}
1224
0b83947e
DJ
1225/* Fetch the global remote target state. */
1226
6b8edb51
PA
1227remote_state *
1228remote_target::get_remote_state ()
0b83947e
DJ
1229{
1230 /* Make sure that the remote architecture state has been
1231 initialized, because doing so might reallocate rs->buf. Any
1232 function which calls getpkt also needs to be mindful of changes
1233 to rs->buf, but this call limits the number of places which run
1234 into trouble. */
3c69da40 1235 m_remote_state.get_remote_arch_state (target_gdbarch ());
0b83947e 1236
3c69da40 1237 return &m_remote_state;
0b83947e
DJ
1238}
1239
94585166
DB
1240/* Cleanup routine for the remote module's pspace data. */
1241
1242static void
1243remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
1244{
19ba03f4 1245 char *remote_exec_file = (char *) arg;
94585166
DB
1246
1247 xfree (remote_exec_file);
1248}
1249
1250/* Fetch the remote exec-file from the current program space. */
1251
1252static const char *
1253get_remote_exec_file (void)
1254{
1255 char *remote_exec_file;
1256
19ba03f4
SM
1257 remote_exec_file
1258 = (char *) program_space_data (current_program_space,
1259 remote_pspace_data);
94585166
DB
1260 if (remote_exec_file == NULL)
1261 return "";
1262
1263 return remote_exec_file;
1264}
1265
1266/* Set the remote exec file for PSPACE. */
1267
1268static void
1269set_pspace_remote_exec_file (struct program_space *pspace,
1270 char *remote_exec_file)
1271{
19ba03f4 1272 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
94585166
DB
1273
1274 xfree (old_file);
1275 set_program_space_data (pspace, remote_pspace_data,
1276 xstrdup (remote_exec_file));
1277}
1278
1279/* The "set/show remote exec-file" set command hook. */
1280
1281static void
eb4c3f4a 1282set_remote_exec_file (const char *ignored, int from_tty,
94585166
DB
1283 struct cmd_list_element *c)
1284{
1285 gdb_assert (remote_exec_file_var != NULL);
1286 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
1287}
1288
1289/* The "set/show remote exec-file" show command hook. */
1290
1291static void
1292show_remote_exec_file (struct ui_file *file, int from_tty,
1293 struct cmd_list_element *cmd, const char *value)
1294{
1295 fprintf_filtered (file, "%s\n", remote_exec_file_var);
1296}
1297
74ca34ce
DJ
1298static int
1299compare_pnums (const void *lhs_, const void *rhs_)
1300{
19ba03f4
SM
1301 const struct packet_reg * const *lhs
1302 = (const struct packet_reg * const *) lhs_;
1303 const struct packet_reg * const *rhs
1304 = (const struct packet_reg * const *) rhs_;
74ca34ce
DJ
1305
1306 if ((*lhs)->pnum < (*rhs)->pnum)
1307 return -1;
1308 else if ((*lhs)->pnum == (*rhs)->pnum)
1309 return 0;
1310 else
1311 return 1;
1312}
1313
c21236dc
PA
1314static int
1315map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 1316{
74ca34ce 1317 int regnum, num_remote_regs, offset;
74ca34ce 1318 struct packet_reg **remote_regs;
ea9c271d 1319
4a22f64d 1320 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 1321 {
c21236dc 1322 struct packet_reg *r = &regs[regnum];
baef701f 1323
4a22f64d 1324 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
1325 /* Do not try to fetch zero-sized (placeholder) registers. */
1326 r->pnum = -1;
1327 else
1328 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1329
b323314b 1330 r->regnum = regnum;
74ca34ce
DJ
1331 }
1332
1333 /* Define the g/G packet format as the contents of each register
1334 with a remote protocol number, in order of ascending protocol
1335 number. */
1336
224c3ddb 1337 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 1338 for (num_remote_regs = 0, regnum = 0;
4a22f64d 1339 regnum < gdbarch_num_regs (gdbarch);
f57d151a 1340 regnum++)
c21236dc
PA
1341 if (regs[regnum].pnum != -1)
1342 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 1343
74ca34ce
DJ
1344 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
1345 compare_pnums);
1346
1347 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1348 {
1349 remote_regs[regnum]->in_g_packet = 1;
1350 remote_regs[regnum]->offset = offset;
4a22f64d 1351 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
1352 }
1353
c21236dc
PA
1354 return offset;
1355}
1356
1357/* Given the architecture described by GDBARCH, return the remote
1358 protocol register's number and the register's offset in the g/G
1359 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1360 If the target does not have a mapping for REGNUM, return false,
1361 otherwise, return true. */
1362
1363int
1364remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1365 int *pnum, int *poffset)
1366{
c21236dc
PA
1367 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1368
b80406ac 1369 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
c21236dc 1370
b80406ac 1371 map_regcache_remote_table (gdbarch, regs.data ());
c21236dc
PA
1372
1373 *pnum = regs[regnum].pnum;
1374 *poffset = regs[regnum].offset;
1375
c21236dc
PA
1376 return *pnum != -1;
1377}
1378
9d6eea31 1379remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
c21236dc 1380{
c21236dc
PA
1381 /* Use the architecture to build a regnum<->pnum table, which will be
1382 1:1 unless a feature set specifies otherwise. */
9d6eea31 1383 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
c21236dc 1384
74ca34ce
DJ
1385 /* Record the maximum possible size of the g packet - it may turn out
1386 to be smaller. */
9d6eea31
PA
1387 this->sizeof_g_packet
1388 = map_regcache_remote_table (gdbarch, this->regs.get ());
74ca34ce 1389
0df8b418 1390 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
1391 remote stubs have a hardwired buffer size of 400 bytes
1392 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1393 as the maximum packet-size to ensure that the packet and an extra
1394 NUL character can always fit in the buffer. This stops GDB
1395 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d 1396 already a full buffer (As of 1999-12-04 that was most stubs). */
9d6eea31 1397 this->remote_packet_size = 400 - 1;
d01949b6 1398
ea9c271d 1399 /* This one is filled in when a ``g'' packet is received. */
9d6eea31 1400 this->actual_register_packet_size = 0;
ea9c271d
DJ
1401
1402 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
1403 default, adjust the size accordingly. Remember that each byte is
1404 encoded as two characters. 32 is the overhead for the packet
1405 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 1406 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 1407 little. */
9d6eea31
PA
1408 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1409 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
ea9c271d
DJ
1410}
1411
6b8edb51
PA
1412/* Get a pointer to the current remote target. If not connected to a
1413 remote target, return NULL. */
1414
1415static remote_target *
1416get_current_remote_target ()
1417{
1418 target_ops *proc_target = find_target_at (process_stratum);
1419 return dynamic_cast<remote_target *> (proc_target);
1420}
1421
ea9c271d
DJ
1422/* Return the current allowed size of a remote packet. This is
1423 inferred from the current architecture, and should be used to
1424 limit the length of outgoing packets. */
6b8edb51
PA
1425long
1426remote_target::get_remote_packet_size ()
ea9c271d 1427{
be2a5f71 1428 struct remote_state *rs = get_remote_state ();
9d6eea31 1429 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
ea9c271d 1430
be2a5f71
DJ
1431 if (rs->explicit_packet_size)
1432 return rs->explicit_packet_size;
1433
ea9c271d 1434 return rsa->remote_packet_size;
d01949b6
AC
1435}
1436
ad10f812 1437static struct packet_reg *
5cd63fda
PA
1438packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1439 long regnum)
ad10f812 1440{
5cd63fda 1441 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
b323314b
AC
1442 return NULL;
1443 else
ad10f812 1444 {
ea9c271d 1445 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 1446
b323314b
AC
1447 gdb_assert (r->regnum == regnum);
1448 return r;
ad10f812 1449 }
ad10f812
AC
1450}
1451
1452static struct packet_reg *
5cd63fda
PA
1453packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1454 LONGEST pnum)
ad10f812 1455{
b323314b 1456 int i;
a744cf53 1457
5cd63fda 1458 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
ad10f812 1459 {
ea9c271d 1460 struct packet_reg *r = &rsa->regs[i];
a744cf53 1461
b323314b
AC
1462 if (r->pnum == pnum)
1463 return r;
ad10f812
AC
1464 }
1465 return NULL;
d01949b6
AC
1466}
1467
9a7071a8
JB
1468/* Allow the user to specify what sequence to send to the remote
1469 when he requests a program interruption: Although ^C is usually
1470 what remote systems expect (this is the default, here), it is
1471 sometimes preferable to send a break. On other systems such
1472 as the Linux kernel, a break followed by g, which is Magic SysRq g
1473 is required in order to interrupt the execution. */
1474const char interrupt_sequence_control_c[] = "Ctrl-C";
1475const char interrupt_sequence_break[] = "BREAK";
1476const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 1477static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
1478 {
1479 interrupt_sequence_control_c,
1480 interrupt_sequence_break,
1481 interrupt_sequence_break_g,
1482 NULL
1483 };
1484static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1485
1486static void
1487show_interrupt_sequence (struct ui_file *file, int from_tty,
1488 struct cmd_list_element *c,
1489 const char *value)
1490{
1491 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1492 fprintf_filtered (file,
1493 _("Send the ASCII ETX character (Ctrl-c) "
1494 "to the remote target to interrupt the "
1495 "execution of the program.\n"));
1496 else if (interrupt_sequence_mode == interrupt_sequence_break)
1497 fprintf_filtered (file,
1498 _("send a break signal to the remote target "
1499 "to interrupt the execution of the program.\n"));
1500 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1501 fprintf_filtered (file,
1502 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1503 "the remote target to interrupt the execution "
1504 "of Linux kernel.\n"));
1505 else
1506 internal_error (__FILE__, __LINE__,
1507 _("Invalid value for interrupt_sequence_mode: %s."),
1508 interrupt_sequence_mode);
1509}
6426a772 1510
9a7071a8
JB
1511/* This boolean variable specifies whether interrupt_sequence is sent
1512 to the remote target when gdb connects to it.
1513 This is mostly needed when you debug the Linux kernel: The Linux kernel
1514 expects BREAK g which is Magic SysRq g for connecting gdb. */
1515static int interrupt_on_connect = 0;
c906108c 1516
9a7071a8
JB
1517/* This variable is used to implement the "set/show remotebreak" commands.
1518 Since these commands are now deprecated in favor of "set/show remote
1519 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
1520static int remote_break;
1521
9a7071a8 1522static void
eb4c3f4a 1523set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
9a7071a8
JB
1524{
1525 if (remote_break)
1526 interrupt_sequence_mode = interrupt_sequence_break;
1527 else
1528 interrupt_sequence_mode = interrupt_sequence_control_c;
1529}
1530
1531static void
1532show_remotebreak (struct ui_file *file, int from_tty,
1533 struct cmd_list_element *c,
1534 const char *value)
1535{
1536}
1537
c906108c
SS
1538/* This variable sets the number of bits in an address that are to be
1539 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 1540 leading zeros, the entire address would be sent. This variable
c906108c
SS
1541 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1542 initial implementation of remote.c restricted the address sent in
1543 memory packets to ``host::sizeof long'' bytes - (typically 32
1544 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1545 address was never sent. Since fixing this bug may cause a break in
1546 some remote targets this variable is principly provided to
23860348 1547 facilitate backward compatibility. */
c906108c 1548
883b9c6c 1549static unsigned int remote_address_size;
c906108c 1550
11cf8741 1551\f
11cf8741 1552/* User configurable variables for the number of characters in a
ea9c271d
DJ
1553 memory read/write packet. MIN (rsa->remote_packet_size,
1554 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 1555 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
1556 (speed up transfers). The variables ``preferred_*'' (the user
1557 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 1558 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
1559
1560struct memory_packet_config
1561{
a121b7c1 1562 const char *name;
11cf8741
JM
1563 long size;
1564 int fixed_p;
1565};
1566
cc0be08f
PA
1567/* The default max memory-write-packet-size, when the setting is
1568 "fixed". The 16k is historical. (It came from older GDB's using
1569 alloca for buffers and the knowledge (folklore?) that some hosts
1570 don't cope very well with large alloca calls.) */
1571#define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
a5c0808e
PA
1572
1573/* The minimum remote packet size for memory transfers. Ensures we
1574 can write at least one byte. */
1575#define MIN_MEMORY_PACKET_SIZE 20
1576
cc0be08f
PA
1577/* Get the memory packet size, assuming it is fixed. */
1578
1579static long
1580get_fixed_memory_packet_size (struct memory_packet_config *config)
1581{
1582 gdb_assert (config->fixed_p);
1583
1584 if (config->size <= 0)
1585 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1586 else
1587 return config->size;
1588}
1589
11cf8741
JM
1590/* Compute the current size of a read/write packet. Since this makes
1591 use of ``actual_register_packet_size'' the computation is dynamic. */
1592
6b8edb51
PA
1593long
1594remote_target::get_memory_packet_size (struct memory_packet_config *config)
11cf8741 1595{
d01949b6 1596 struct remote_state *rs = get_remote_state ();
9d6eea31 1597 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
ea9c271d 1598
11cf8741
JM
1599 long what_they_get;
1600 if (config->fixed_p)
cc0be08f 1601 what_they_get = get_fixed_memory_packet_size (config);
11cf8741
JM
1602 else
1603 {
ea9c271d 1604 what_they_get = get_remote_packet_size ();
23860348 1605 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1606 if (config->size > 0
1607 && what_they_get > config->size)
1608 what_they_get = config->size;
be2a5f71
DJ
1609
1610 /* Limit it to the size of the targets ``g'' response unless we have
1611 permission from the stub to use a larger packet size. */
1612 if (rs->explicit_packet_size == 0
1613 && rsa->actual_register_packet_size > 0
1614 && what_they_get > rsa->actual_register_packet_size)
1615 what_they_get = rsa->actual_register_packet_size;
11cf8741 1616 }
a5c0808e
PA
1617 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1618 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1619
1620 /* Make sure there is room in the global buffer for this packet
1621 (including its trailing NUL byte). */
8d64371b
TT
1622 if (rs->buf.size () < what_they_get + 1)
1623 rs->buf.resize (2 * what_they_get);
6d820c5c 1624
11cf8741
JM
1625 return what_they_get;
1626}
1627
0df8b418 1628/* Update the size of a read/write packet. If they user wants
23860348 1629 something really big then do a sanity check. */
11cf8741
JM
1630
1631static void
ac88e2de 1632set_memory_packet_size (const char *args, struct memory_packet_config *config)
11cf8741
JM
1633{
1634 int fixed_p = config->fixed_p;
1635 long size = config->size;
a744cf53 1636
11cf8741 1637 if (args == NULL)
8a3fe4f8 1638 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1639 else if (strcmp (args, "hard") == 0
1640 || strcmp (args, "fixed") == 0)
1641 fixed_p = 1;
1642 else if (strcmp (args, "soft") == 0
1643 || strcmp (args, "limit") == 0)
1644 fixed_p = 0;
1645 else
1646 {
1647 char *end;
a744cf53 1648
11cf8741
JM
1649 size = strtoul (args, &end, 0);
1650 if (args == end)
8a3fe4f8 1651 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1652
1653 /* Instead of explicitly capping the size of a packet to or
1654 disallowing it, the user is allowed to set the size to
1655 something arbitrarily large. */
11cf8741 1656 }
a5c0808e 1657
23860348 1658 /* Extra checks? */
11cf8741
JM
1659 if (fixed_p && !config->fixed_p)
1660 {
cc0be08f
PA
1661 /* So that the query shows the correct value. */
1662 long query_size = (size <= 0
1663 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1664 : size);
1665
e2e0b3e5
AC
1666 if (! query (_("The target may not be able to correctly handle a %s\n"
1667 "of %ld bytes. Change the packet size? "),
cc0be08f 1668 config->name, query_size))
8a3fe4f8 1669 error (_("Packet size not changed."));
11cf8741 1670 }
23860348 1671 /* Update the config. */
11cf8741
JM
1672 config->fixed_p = fixed_p;
1673 config->size = size;
1674}
1675
1676static void
1677show_memory_packet_size (struct memory_packet_config *config)
1678{
cc0be08f
PA
1679 if (config->size == 0)
1680 printf_filtered (_("The %s is 0 (default). "), config->name);
1681 else
1682 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1683 if (config->fixed_p)
a3f17187 1684 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
cc0be08f 1685 get_fixed_memory_packet_size (config));
11cf8741 1686 else
cc0be08f 1687 {
6b8edb51 1688 remote_target *remote = get_current_remote_target ();
cc0be08f 1689
6b8edb51 1690 if (remote != NULL)
cc0be08f 1691 printf_filtered (_("Packets are limited to %ld bytes.\n"),
6b8edb51 1692 remote->get_memory_packet_size (config));
cc0be08f
PA
1693 else
1694 puts_filtered ("The actual limit will be further reduced "
1695 "dependent on the target.\n");
1696 }
11cf8741
JM
1697}
1698
1699static struct memory_packet_config memory_write_packet_config =
1700{
1701 "memory-write-packet-size",
1702};
1703
1704static void
ac88e2de 1705set_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1706{
1707 set_memory_packet_size (args, &memory_write_packet_config);
1708}
1709
1710static void
ac88e2de 1711show_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1712{
1713 show_memory_packet_size (&memory_write_packet_config);
1714}
1715
055303e2
AB
1716/* Show the number of hardware watchpoints that can be used. */
1717
1718static void
1719show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
1720 struct cmd_list_element *c,
1721 const char *value)
1722{
1723 fprintf_filtered (file, _("The maximum number of target hardware "
1724 "watchpoints is %s.\n"), value);
1725}
1726
1727/* Show the length limit (in bytes) for hardware watchpoints. */
1728
1729static void
1730show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
1731 struct cmd_list_element *c,
1732 const char *value)
1733{
1734 fprintf_filtered (file, _("The maximum length (in bytes) of a target "
1735 "hardware watchpoint is %s.\n"), value);
1736}
1737
1738/* Show the number of hardware breakpoints that can be used. */
1739
1740static void
1741show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
1742 struct cmd_list_element *c,
1743 const char *value)
1744{
1745 fprintf_filtered (file, _("The maximum number of target hardware "
1746 "breakpoints is %s.\n"), value);
1747}
1748
6b8edb51
PA
1749long
1750remote_target::get_memory_write_packet_size ()
11cf8741
JM
1751{
1752 return get_memory_packet_size (&memory_write_packet_config);
1753}
1754
1755static struct memory_packet_config memory_read_packet_config =
1756{
1757 "memory-read-packet-size",
1758};
1759
1760static void
ac88e2de 1761set_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1762{
1763 set_memory_packet_size (args, &memory_read_packet_config);
1764}
1765
1766static void
ac88e2de 1767show_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1768{
1769 show_memory_packet_size (&memory_read_packet_config);
1770}
1771
6b8edb51
PA
1772long
1773remote_target::get_memory_read_packet_size ()
11cf8741
JM
1774{
1775 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1776
11cf8741
JM
1777 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1778 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1779 increased beyond this. */
1780 if (size > get_remote_packet_size ())
1781 size = get_remote_packet_size ();
11cf8741
JM
1782 return size;
1783}
1784
11cf8741 1785\f
5a2468f5 1786
5a2468f5
JM
1787struct packet_config
1788 {
bb572ddd
DJ
1789 const char *name;
1790 const char *title;
4082afcc
PA
1791
1792 /* If auto, GDB auto-detects support for this packet or feature,
1793 either through qSupported, or by trying the packet and looking
1794 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1795 packet. If false, the packet is disabled. Configs that don't
1796 have an associated command always have this set to auto. */
7f19b9a2 1797 enum auto_boolean detect;
4082afcc
PA
1798
1799 /* Does the target support this packet? */
5a2468f5
JM
1800 enum packet_support support;
1801 };
1802
4082afcc
PA
1803static enum packet_support packet_config_support (struct packet_config *config);
1804static enum packet_support packet_support (int packet);
5a2468f5
JM
1805
1806static void
fba45db2 1807show_packet_config_cmd (struct packet_config *config)
5a2468f5 1808{
a121b7c1 1809 const char *support = "internal-error";
a744cf53 1810
4082afcc 1811 switch (packet_config_support (config))
5a2468f5
JM
1812 {
1813 case PACKET_ENABLE:
1814 support = "enabled";
1815 break;
1816 case PACKET_DISABLE:
1817 support = "disabled";
1818 break;
1819 case PACKET_SUPPORT_UNKNOWN:
1820 support = "unknown";
1821 break;
1822 }
1823 switch (config->detect)
1824 {
7f19b9a2 1825 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1826 printf_filtered (_("Support for the `%s' packet "
1827 "is auto-detected, currently %s.\n"),
37a105a1 1828 config->name, support);
5a2468f5 1829 break;
7f19b9a2
AC
1830 case AUTO_BOOLEAN_TRUE:
1831 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1832 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1833 config->name, support);
8e248173 1834 break;
5a2468f5
JM
1835 }
1836}
1837
1838static void
bb572ddd
DJ
1839add_packet_config_cmd (struct packet_config *config, const char *name,
1840 const char *title, int legacy)
d471ea57 1841{
5a2468f5
JM
1842 char *set_doc;
1843 char *show_doc;
d471ea57 1844 char *cmd_name;
3ed07be4 1845
5a2468f5
JM
1846 config->name = name;
1847 config->title = title;
b435e160
AC
1848 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1849 name, title);
3e43a32a
MS
1850 show_doc = xstrprintf ("Show current use of remote "
1851 "protocol `%s' (%s) packet",
b435e160 1852 name, title);
d471ea57 1853 /* set/show TITLE-packet {auto,on,off} */
b435e160 1854 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1855 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1856 &config->detect, set_doc,
1857 show_doc, NULL, /* help_doc */
4082afcc 1858 NULL,
bb572ddd
DJ
1859 show_remote_protocol_packet_cmd,
1860 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1861 /* The command code copies the documentation strings. */
1862 xfree (set_doc);
1863 xfree (show_doc);
23860348 1864 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1865 if (legacy)
1866 {
1867 char *legacy_name;
a744cf53 1868
b435e160 1869 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1870 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1871 &remote_set_cmdlist);
d471ea57 1872 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1873 &remote_show_cmdlist);
d471ea57 1874 }
5a2468f5
JM
1875}
1876
d471ea57 1877static enum packet_result
a76d924d 1878packet_check_result (const char *buf)
5a2468f5 1879{
d471ea57 1880 if (buf[0] != '\0')
5a2468f5 1881 {
d471ea57 1882 /* The stub recognized the packet request. Check that the
23860348 1883 operation succeeded. */
a76d924d
DJ
1884 if (buf[0] == 'E'
1885 && isxdigit (buf[1]) && isxdigit (buf[2])
1886 && buf[3] == '\0')
1887 /* "Enn" - definitly an error. */
1888 return PACKET_ERROR;
1889
1890 /* Always treat "E." as an error. This will be used for
1891 more verbose error messages, such as E.memtypes. */
1892 if (buf[0] == 'E' && buf[1] == '.')
1893 return PACKET_ERROR;
1894
1895 /* The packet may or may not be OK. Just assume it is. */
1896 return PACKET_OK;
1897 }
1898 else
1899 /* The stub does not support the packet. */
1900 return PACKET_UNKNOWN;
1901}
1902
8d64371b
TT
1903static enum packet_result
1904packet_check_result (const gdb::char_vector &buf)
1905{
1906 return packet_check_result (buf.data ());
1907}
1908
a76d924d
DJ
1909static enum packet_result
1910packet_ok (const char *buf, struct packet_config *config)
1911{
1912 enum packet_result result;
1913
4082afcc
PA
1914 if (config->detect != AUTO_BOOLEAN_TRUE
1915 && config->support == PACKET_DISABLE)
1916 internal_error (__FILE__, __LINE__,
1917 _("packet_ok: attempt to use a disabled packet"));
1918
a76d924d
DJ
1919 result = packet_check_result (buf);
1920 switch (result)
1921 {
1922 case PACKET_OK:
1923 case PACKET_ERROR:
1924 /* The stub recognized the packet request. */
4082afcc 1925 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1926 {
d471ea57
AC
1927 if (remote_debug)
1928 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1929 "Packet %s (%s) is supported\n",
1930 config->name, config->title);
d471ea57 1931 config->support = PACKET_ENABLE;
d471ea57 1932 }
a76d924d
DJ
1933 break;
1934 case PACKET_UNKNOWN:
23860348 1935 /* The stub does not support the packet. */
4082afcc
PA
1936 if (config->detect == AUTO_BOOLEAN_AUTO
1937 && config->support == PACKET_ENABLE)
d471ea57 1938 {
4082afcc
PA
1939 /* If the stub previously indicated that the packet was
1940 supported then there is a protocol error. */
1941 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1942 config->name, config->title);
1943 }
1944 else if (config->detect == AUTO_BOOLEAN_TRUE)
1945 {
1946 /* The user set it wrong. */
1947 error (_("Enabled packet %s (%s) not recognized by stub"),
1948 config->name, config->title);
d471ea57 1949 }
4082afcc
PA
1950
1951 if (remote_debug)
1952 fprintf_unfiltered (gdb_stdlog,
1953 "Packet %s (%s) is NOT supported\n",
1954 config->name, config->title);
1955 config->support = PACKET_DISABLE;
a76d924d 1956 break;
5a2468f5 1957 }
a76d924d
DJ
1958
1959 return result;
5a2468f5
JM
1960}
1961
8d64371b
TT
1962static enum packet_result
1963packet_ok (const gdb::char_vector &buf, struct packet_config *config)
1964{
1965 return packet_ok (buf.data (), config);
1966}
1967
444abaca
DJ
1968enum {
1969 PACKET_vCont = 0,
1970 PACKET_X,
1971 PACKET_qSymbol,
1972 PACKET_P,
1973 PACKET_p,
1974 PACKET_Z0,
1975 PACKET_Z1,
1976 PACKET_Z2,
1977 PACKET_Z3,
1978 PACKET_Z4,
15a201c8 1979 PACKET_vFile_setfs,
a6b151f1
DJ
1980 PACKET_vFile_open,
1981 PACKET_vFile_pread,
1982 PACKET_vFile_pwrite,
1983 PACKET_vFile_close,
1984 PACKET_vFile_unlink,
b9e7b9c3 1985 PACKET_vFile_readlink,
0a93529c 1986 PACKET_vFile_fstat,
0876f84a 1987 PACKET_qXfer_auxv,
23181151 1988 PACKET_qXfer_features,
c78fa86a 1989 PACKET_qXfer_exec_file,
cfa9d6d9 1990 PACKET_qXfer_libraries,
2268b414 1991 PACKET_qXfer_libraries_svr4,
fd79ecee 1992 PACKET_qXfer_memory_map,
0e7f50da
UW
1993 PACKET_qXfer_spu_read,
1994 PACKET_qXfer_spu_write,
07e059b5 1995 PACKET_qXfer_osdata,
dc146f7c 1996 PACKET_qXfer_threads,
0fb4aa4b 1997 PACKET_qXfer_statictrace_read,
b3b9301e 1998 PACKET_qXfer_traceframe_info,
169081d0 1999 PACKET_qXfer_uib,
711e434b 2000 PACKET_qGetTIBAddr,
444abaca 2001 PACKET_qGetTLSAddr,
be2a5f71 2002 PACKET_qSupported,
bd3eecc3 2003 PACKET_qTStatus,
89be2091 2004 PACKET_QPassSignals,
82075af2 2005 PACKET_QCatchSyscalls,
9b224c5e 2006 PACKET_QProgramSignals,
bc3b087d 2007 PACKET_QSetWorkingDir,
aefd8b33 2008 PACKET_QStartupWithShell,
0a2dde4a
SDJ
2009 PACKET_QEnvironmentHexEncoded,
2010 PACKET_QEnvironmentReset,
2011 PACKET_QEnvironmentUnset,
936d2992 2012 PACKET_qCRC,
08388c79 2013 PACKET_qSearch_memory,
2d717e4f
DJ
2014 PACKET_vAttach,
2015 PACKET_vRun,
a6f3e723 2016 PACKET_QStartNoAckMode,
82f73884 2017 PACKET_vKill,
4aa995e1
PA
2018 PACKET_qXfer_siginfo_read,
2019 PACKET_qXfer_siginfo_write,
0b16c5cf 2020 PACKET_qAttached,
4082afcc
PA
2021
2022 /* Support for conditional tracepoints. */
782b2b07 2023 PACKET_ConditionalTracepoints,
4082afcc
PA
2024
2025 /* Support for target-side breakpoint conditions. */
3788aec7 2026 PACKET_ConditionalBreakpoints,
4082afcc
PA
2027
2028 /* Support for target-side breakpoint commands. */
d3ce09f5 2029 PACKET_BreakpointCommands,
4082afcc
PA
2030
2031 /* Support for fast tracepoints. */
7a697b8d 2032 PACKET_FastTracepoints,
4082afcc
PA
2033
2034 /* Support for static tracepoints. */
0fb4aa4b 2035 PACKET_StaticTracepoints,
4082afcc
PA
2036
2037 /* Support for installing tracepoints while a trace experiment is
2038 running. */
1e4d1764 2039 PACKET_InstallInTrace,
4082afcc 2040
40ab02ce
MS
2041 PACKET_bc,
2042 PACKET_bs,
409873ef 2043 PACKET_TracepointSource,
d914c394 2044 PACKET_QAllow,
78d85199 2045 PACKET_qXfer_fdpic,
03583c20 2046 PACKET_QDisableRandomization,
d1feda86 2047 PACKET_QAgent,
f6f899bf 2048 PACKET_QTBuffer_size,
9accd112
MM
2049 PACKET_Qbtrace_off,
2050 PACKET_Qbtrace_bts,
b20a6524 2051 PACKET_Qbtrace_pt,
9accd112 2052 PACKET_qXfer_btrace,
4082afcc
PA
2053
2054 /* Support for the QNonStop packet. */
2055 PACKET_QNonStop,
2056
65706a29
PA
2057 /* Support for the QThreadEvents packet. */
2058 PACKET_QThreadEvents,
2059
4082afcc
PA
2060 /* Support for multi-process extensions. */
2061 PACKET_multiprocess_feature,
2062
2063 /* Support for enabling and disabling tracepoints while a trace
2064 experiment is running. */
2065 PACKET_EnableDisableTracepoints_feature,
2066
2067 /* Support for collecting strings using the tracenz bytecode. */
2068 PACKET_tracenz_feature,
2069
2070 /* Support for continuing to run a trace experiment while GDB is
2071 disconnected. */
2072 PACKET_DisconnectedTracing_feature,
2073
2074 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2075 PACKET_augmented_libraries_svr4_read_feature,
2076
f4abbc16
MM
2077 /* Support for the qXfer:btrace-conf:read packet. */
2078 PACKET_qXfer_btrace_conf,
2079
d33501a5
MM
2080 /* Support for the Qbtrace-conf:bts:size packet. */
2081 PACKET_Qbtrace_conf_bts_size,
2082
f7e6eed5
PA
2083 /* Support for swbreak+ feature. */
2084 PACKET_swbreak_feature,
2085
2086 /* Support for hwbreak+ feature. */
2087 PACKET_hwbreak_feature,
2088
89245bc0
DB
2089 /* Support for fork events. */
2090 PACKET_fork_event_feature,
2091
2092 /* Support for vfork events. */
2093 PACKET_vfork_event_feature,
2094
b20a6524
MM
2095 /* Support for the Qbtrace-conf:pt:size packet. */
2096 PACKET_Qbtrace_conf_pt_size,
2097
94585166
DB
2098 /* Support for exec events. */
2099 PACKET_exec_event_feature,
2100
750ce8d1
YQ
2101 /* Support for query supported vCont actions. */
2102 PACKET_vContSupported,
2103
de979965
PA
2104 /* Support remote CTRL-C. */
2105 PACKET_vCtrlC,
2106
f2faf941
PA
2107 /* Support TARGET_WAITKIND_NO_RESUMED. */
2108 PACKET_no_resumed,
2109
444abaca
DJ
2110 PACKET_MAX
2111};
506fb367 2112
444abaca 2113static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 2114
f7e6eed5
PA
2115/* Returns the packet's corresponding "set remote foo-packet" command
2116 state. See struct packet_config for more details. */
2117
2118static enum auto_boolean
2119packet_set_cmd_state (int packet)
2120{
2121 return remote_protocol_packets[packet].detect;
2122}
2123
4082afcc
PA
2124/* Returns whether a given packet or feature is supported. This takes
2125 into account the state of the corresponding "set remote foo-packet"
2126 command, which may be used to bypass auto-detection. */
dc8acb97 2127
4082afcc
PA
2128static enum packet_support
2129packet_config_support (struct packet_config *config)
2130{
2131 switch (config->detect)
444abaca 2132 {
4082afcc
PA
2133 case AUTO_BOOLEAN_TRUE:
2134 return PACKET_ENABLE;
2135 case AUTO_BOOLEAN_FALSE:
2136 return PACKET_DISABLE;
2137 case AUTO_BOOLEAN_AUTO:
2138 return config->support;
2139 default:
2140 gdb_assert_not_reached (_("bad switch"));
444abaca 2141 }
4082afcc
PA
2142}
2143
2144/* Same as packet_config_support, but takes the packet's enum value as
2145 argument. */
2146
2147static enum packet_support
2148packet_support (int packet)
2149{
2150 struct packet_config *config = &remote_protocol_packets[packet];
2151
2152 return packet_config_support (config);
dc8acb97
MS
2153}
2154
5a2468f5 2155static void
444abaca
DJ
2156show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2157 struct cmd_list_element *c,
2158 const char *value)
5a2468f5 2159{
444abaca 2160 struct packet_config *packet;
5a2468f5 2161
444abaca
DJ
2162 for (packet = remote_protocol_packets;
2163 packet < &remote_protocol_packets[PACKET_MAX];
2164 packet++)
2165 {
2166 if (&packet->detect == c->var)
2167 {
2168 show_packet_config_cmd (packet);
2169 return;
2170 }
2171 }
9b20d036 2172 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 2173 c->name);
5a2468f5
JM
2174}
2175
d471ea57
AC
2176/* Should we try one of the 'Z' requests? */
2177
2178enum Z_packet_type
2179{
2180 Z_PACKET_SOFTWARE_BP,
2181 Z_PACKET_HARDWARE_BP,
2182 Z_PACKET_WRITE_WP,
2183 Z_PACKET_READ_WP,
2184 Z_PACKET_ACCESS_WP,
2185 NR_Z_PACKET_TYPES
2186};
96baa820 2187
d471ea57 2188/* For compatibility with older distributions. Provide a ``set remote
23860348 2189 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 2190
7f19b9a2 2191static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
2192
2193static void
eb4c3f4a 2194set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
fba45db2 2195 struct cmd_list_element *c)
96baa820 2196{
d471ea57 2197 int i;
a744cf53 2198
d471ea57 2199 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 2200 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
2201}
2202
2203static void
08546159
AC
2204show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2205 struct cmd_list_element *c,
2206 const char *value)
96baa820 2207{
d471ea57 2208 int i;
a744cf53 2209
d471ea57
AC
2210 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2211 {
444abaca 2212 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 2213 }
96baa820
JM
2214}
2215
4082afcc
PA
2216/* Returns true if the multi-process extensions are in effect. */
2217
2218static int
2219remote_multi_process_p (struct remote_state *rs)
2220{
2221 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2222}
2223
de0d863e
DB
2224/* Returns true if fork events are supported. */
2225
2226static int
2227remote_fork_event_p (struct remote_state *rs)
2228{
2229 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2230}
2231
c269dbdb
DB
2232/* Returns true if vfork events are supported. */
2233
2234static int
2235remote_vfork_event_p (struct remote_state *rs)
2236{
2237 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2238}
2239
d46addbb
DB
2240/* Returns true if exec events are supported. */
2241
2242static int
2243remote_exec_event_p (struct remote_state *rs)
2244{
2245 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2246}
2247
cbb8991c
DB
2248/* Insert fork catchpoint target routine. If fork events are enabled
2249 then return success, nothing more to do. */
2250
f6ac5f3d
PA
2251int
2252remote_target::insert_fork_catchpoint (int pid)
cbb8991c
DB
2253{
2254 struct remote_state *rs = get_remote_state ();
2255
2256 return !remote_fork_event_p (rs);
2257}
2258
2259/* Remove fork catchpoint target routine. Nothing to do, just
2260 return success. */
2261
f6ac5f3d
PA
2262int
2263remote_target::remove_fork_catchpoint (int pid)
cbb8991c
DB
2264{
2265 return 0;
2266}
2267
2268/* Insert vfork catchpoint target routine. If vfork events are enabled
2269 then return success, nothing more to do. */
2270
f6ac5f3d
PA
2271int
2272remote_target::insert_vfork_catchpoint (int pid)
cbb8991c
DB
2273{
2274 struct remote_state *rs = get_remote_state ();
2275
2276 return !remote_vfork_event_p (rs);
2277}
2278
2279/* Remove vfork catchpoint target routine. Nothing to do, just
2280 return success. */
2281
f6ac5f3d
PA
2282int
2283remote_target::remove_vfork_catchpoint (int pid)
cbb8991c
DB
2284{
2285 return 0;
2286}
2287
d46addbb
DB
2288/* Insert exec catchpoint target routine. If exec events are
2289 enabled, just return success. */
2290
f6ac5f3d
PA
2291int
2292remote_target::insert_exec_catchpoint (int pid)
d46addbb
DB
2293{
2294 struct remote_state *rs = get_remote_state ();
2295
2296 return !remote_exec_event_p (rs);
2297}
2298
2299/* Remove exec catchpoint target routine. Nothing to do, just
2300 return success. */
2301
f6ac5f3d
PA
2302int
2303remote_target::remove_exec_catchpoint (int pid)
d46addbb
DB
2304{
2305 return 0;
2306}
2307
c906108c
SS
2308\f
2309
79d7f229
PA
2310static ptid_t magic_null_ptid;
2311static ptid_t not_sent_ptid;
2312static ptid_t any_thread_ptid;
2313
0b16c5cf
PA
2314/* Find out if the stub attached to PID (and hence GDB should offer to
2315 detach instead of killing it when bailing out). */
2316
6b8edb51
PA
2317int
2318remote_target::remote_query_attached (int pid)
0b16c5cf
PA
2319{
2320 struct remote_state *rs = get_remote_state ();
bba74b36 2321 size_t size = get_remote_packet_size ();
0b16c5cf 2322
4082afcc 2323 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
2324 return 0;
2325
2326 if (remote_multi_process_p (rs))
8d64371b 2327 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
0b16c5cf 2328 else
8d64371b 2329 xsnprintf (rs->buf.data (), size, "qAttached");
0b16c5cf
PA
2330
2331 putpkt (rs->buf);
8d64371b 2332 getpkt (&rs->buf, 0);
0b16c5cf
PA
2333
2334 switch (packet_ok (rs->buf,
1554e9be 2335 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
2336 {
2337 case PACKET_OK:
8d64371b 2338 if (strcmp (rs->buf.data (), "1") == 0)
0b16c5cf
PA
2339 return 1;
2340 break;
2341 case PACKET_ERROR:
8d64371b 2342 warning (_("Remote failure reply: %s"), rs->buf.data ());
0b16c5cf
PA
2343 break;
2344 case PACKET_UNKNOWN:
2345 break;
2346 }
2347
2348 return 0;
2349}
2350
49c62f2e
PA
2351/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2352 has been invented by GDB, instead of reported by the target. Since
2353 we can be connected to a remote system before before knowing about
2354 any inferior, mark the target with execution when we find the first
2355 inferior. If ATTACHED is 1, then we had just attached to this
2356 inferior. If it is 0, then we just created this inferior. If it
2357 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
2358 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2359 attempt to open this inferior's executable as the main executable
2360 if no main executable is open already. */
1941c569 2361
6b8edb51
PA
2362inferior *
2363remote_target::remote_add_inferior (int fake_pid_p, int pid, int attached,
2364 int try_open_exec)
1941c569 2365{
1941c569
PA
2366 struct inferior *inf;
2367
0b16c5cf
PA
2368 /* Check whether this process we're learning about is to be
2369 considered attached, or if is to be considered to have been
2370 spawned by the stub. */
2371 if (attached == -1)
2372 attached = remote_query_attached (pid);
2373
f5656ead 2374 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
2375 {
2376 /* If the target shares code across all inferiors, then every
2377 attach adds a new inferior. */
2378 inf = add_inferior (pid);
2379
2380 /* ... and every inferior is bound to the same program space.
2381 However, each inferior may still have its own address
2382 space. */
2383 inf->aspace = maybe_new_address_space ();
2384 inf->pspace = current_program_space;
2385 }
2386 else
2387 {
2388 /* In the traditional debugging scenario, there's a 1-1 match
2389 between program/address spaces. We simply bind the inferior
2390 to the program space's address space. */
2391 inf = current_inferior ();
2392 inferior_appeared (inf, pid);
2393 }
1941c569 2394
0b16c5cf 2395 inf->attach_flag = attached;
49c62f2e 2396 inf->fake_pid_p = fake_pid_p;
0b16c5cf 2397
1b6e6f5c
GB
2398 /* If no main executable is currently open then attempt to
2399 open the file that was executed to create this inferior. */
835205d0 2400 if (try_open_exec && get_exec_file (0) == NULL)
bb805577 2401 exec_file_locate_attach (pid, 0, 1);
1b6e6f5c 2402
1941c569
PA
2403 return inf;
2404}
2405
7aabaf9d 2406static remote_thread_info *get_remote_thread_info (thread_info *thread);
00431a78 2407static remote_thread_info *get_remote_thread_info (ptid_t ptid);
85ad3aaf 2408
1941c569
PA
2409/* Add thread PTID to GDB's thread list. Tag it as executing/running
2410 according to RUNNING. */
2411
00431a78 2412thread_info *
6b8edb51 2413remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing)
c906108c 2414{
b7ea362b 2415 struct remote_state *rs = get_remote_state ();
85ad3aaf 2416 struct thread_info *thread;
b7ea362b
PA
2417
2418 /* GDB historically didn't pull threads in the initial connection
2419 setup. If the remote target doesn't even have a concept of
2420 threads (e.g., a bare-metal target), even if internally we
2421 consider that a single-threaded target, mentioning a new thread
2422 might be confusing to the user. Be silent then, preserving the
2423 age old behavior. */
2424 if (rs->starting_up)
85ad3aaf 2425 thread = add_thread_silent (ptid);
b7ea362b 2426 else
85ad3aaf 2427 thread = add_thread (ptid);
1941c569 2428
7aabaf9d 2429 get_remote_thread_info (thread)->vcont_resumed = executing;
0d5b594f 2430 set_executing (ptid, executing);
1941c569 2431 set_running (ptid, running);
00431a78
PA
2432
2433 return thread;
1941c569
PA
2434}
2435
2436/* Come here when we learn about a thread id from the remote target.
2437 It may be the first time we hear about such thread, so take the
2438 opportunity to add it to GDB's thread list. In case this is the
2439 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
2440 GDB's inferior list as well. EXECUTING indicates whether the
2441 thread is (internally) executing or stopped. */
1941c569 2442
6b8edb51
PA
2443void
2444remote_target::remote_notice_new_inferior (ptid_t currthread, int executing)
1941c569 2445{
0d5b594f
PA
2446 /* In non-stop mode, we assume new found threads are (externally)
2447 running until proven otherwise with a stop reply. In all-stop,
2448 we can only get here if all threads are stopped. */
2449 int running = target_is_non_stop_p () ? 1 : 0;
2450
c906108c
SS
2451 /* If this is a new thread, add it to GDB's thread list.
2452 If we leave it up to WFI to do this, bad things will happen. */
82f73884 2453
00431a78
PA
2454 thread_info *tp = find_thread_ptid (currthread);
2455 if (tp != NULL && tp->state == THREAD_EXITED)
82f73884
PA
2456 {
2457 /* We're seeing an event on a thread id we knew had exited.
2458 This has to be a new thread reusing the old id. Add it. */
0d5b594f 2459 remote_add_thread (currthread, running, executing);
82f73884
PA
2460 return;
2461 }
2462
79d7f229 2463 if (!in_thread_list (currthread))
c0a2216e 2464 {
1941c569 2465 struct inferior *inf = NULL;
e99b03dc 2466 int pid = currthread.pid ();
1941c569 2467
0e998d96 2468 if (inferior_ptid.is_pid ()
e99b03dc 2469 && pid == inferior_ptid.pid ())
c0a2216e
PA
2470 {
2471 /* inferior_ptid has no thread member yet. This can happen
2472 with the vAttach -> remote_wait,"TAAthread:" path if the
2473 stub doesn't support qC. This is the first stop reported
2474 after an attach, so this is the main thread. Update the
2475 ptid in the thread list. */
f2907e49 2476 if (in_thread_list (ptid_t (pid)))
bad34192
PA
2477 thread_change_ptid (inferior_ptid, currthread);
2478 else
2479 {
0d5b594f 2480 remote_add_thread (currthread, running, executing);
bad34192
PA
2481 inferior_ptid = currthread;
2482 }
dc146f7c 2483 return;
c0a2216e 2484 }
82f73884 2485
d7e15655 2486 if (magic_null_ptid == inferior_ptid)
c0a2216e
PA
2487 {
2488 /* inferior_ptid is not set yet. This can happen with the
2489 vRun -> remote_wait,"TAAthread:" path if the stub
2490 doesn't support qC. This is the first stop reported
2491 after an attach, so this is the main thread. Update the
2492 ptid in the thread list. */
dc146f7c 2493 thread_change_ptid (inferior_ptid, currthread);
82f73884 2494 return;
c0a2216e 2495 }
82f73884 2496
29c87f7f
PA
2497 /* When connecting to a target remote, or to a target
2498 extended-remote which already was debugging an inferior, we
2499 may not know about it yet. Add it before adding its child
2500 thread, so notifications are emitted in a sensible order. */
e99b03dc 2501 if (find_inferior_pid (currthread.pid ()) == NULL)
49c62f2e
PA
2502 {
2503 struct remote_state *rs = get_remote_state ();
2504 int fake_pid_p = !remote_multi_process_p (rs);
2505
2506 inf = remote_add_inferior (fake_pid_p,
e99b03dc 2507 currthread.pid (), -1, 1);
49c62f2e 2508 }
29c87f7f 2509
82f73884 2510 /* This is really a new thread. Add it. */
00431a78
PA
2511 thread_info *new_thr
2512 = remote_add_thread (currthread, running, executing);
1941c569
PA
2513
2514 /* If we found a new inferior, let the common code do whatever
2515 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
2516 breakpoints), unless we're just setting up an all-stop
2517 connection. */
1941c569 2518 if (inf != NULL)
b7ea362b
PA
2519 {
2520 struct remote_state *rs = get_remote_state ();
2521
6efcd9a8 2522 if (!rs->starting_up)
00431a78 2523 notice_new_inferior (new_thr, executing, 0);
b7ea362b 2524 }
c0a2216e 2525 }
c906108c
SS
2526}
2527
85ad3aaf 2528/* Return THREAD's private thread data, creating it if necessary. */
dc146f7c 2529
7aabaf9d
SM
2530static remote_thread_info *
2531get_remote_thread_info (thread_info *thread)
dc146f7c 2532{
85ad3aaf 2533 gdb_assert (thread != NULL);
dc146f7c 2534
85ad3aaf 2535 if (thread->priv == NULL)
7aabaf9d 2536 thread->priv.reset (new remote_thread_info);
dc146f7c 2537
7aabaf9d 2538 return static_cast<remote_thread_info *> (thread->priv.get ());
85ad3aaf
PA
2539}
2540
7aabaf9d
SM
2541static remote_thread_info *
2542get_remote_thread_info (ptid_t ptid)
85ad3aaf 2543{
00431a78
PA
2544 thread_info *thr = find_thread_ptid (ptid);
2545 return get_remote_thread_info (thr);
dc146f7c
VP
2546}
2547
74531fed
PA
2548/* Call this function as a result of
2549 1) A halt indication (T packet) containing a thread id
2550 2) A direct query of currthread
0df8b418 2551 3) Successful execution of set thread */
74531fed
PA
2552
2553static void
47f8a51d 2554record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 2555{
47f8a51d 2556 rs->general_thread = currthread;
74531fed
PA
2557}
2558
89be2091
DJ
2559/* If 'QPassSignals' is supported, tell the remote stub what signals
2560 it can simply pass through to the inferior without reporting. */
2561
f6ac5f3d 2562void
adc6a863 2563remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
89be2091 2564{
4082afcc 2565 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
2566 {
2567 char *pass_packet, *p;
adc6a863 2568 int count = 0;
747dc59d 2569 struct remote_state *rs = get_remote_state ();
89be2091 2570
adc6a863
PA
2571 gdb_assert (pass_signals.size () < 256);
2572 for (size_t i = 0; i < pass_signals.size (); i++)
89be2091 2573 {
2455069d 2574 if (pass_signals[i])
89be2091
DJ
2575 count++;
2576 }
224c3ddb 2577 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
2578 strcpy (pass_packet, "QPassSignals:");
2579 p = pass_packet + strlen (pass_packet);
adc6a863 2580 for (size_t i = 0; i < pass_signals.size (); i++)
89be2091 2581 {
2455069d 2582 if (pass_signals[i])
89be2091
DJ
2583 {
2584 if (i >= 16)
2585 *p++ = tohex (i >> 4);
2586 *p++ = tohex (i & 15);
2587 if (count)
2588 *p++ = ';';
2589 else
2590 break;
2591 count--;
2592 }
2593 }
2594 *p = 0;
747dc59d 2595 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 2596 {
89be2091 2597 putpkt (pass_packet);
8d64371b 2598 getpkt (&rs->buf, 0);
8dc5b319 2599 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
2600 if (rs->last_pass_packet)
2601 xfree (rs->last_pass_packet);
2602 rs->last_pass_packet = pass_packet;
89be2091
DJ
2603 }
2604 else
2605 xfree (pass_packet);
2606 }
2607}
2608
82075af2
JS
2609/* If 'QCatchSyscalls' is supported, tell the remote stub
2610 to report syscalls to GDB. */
2611
f6ac5f3d
PA
2612int
2613remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2614 gdb::array_view<const int> syscall_counts)
82075af2 2615{
b80406ac 2616 const char *catch_packet;
82075af2
JS
2617 enum packet_result result;
2618 int n_sysno = 0;
2619
2620 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2621 {
2622 /* Not supported. */
2623 return 1;
2624 }
2625
649a140c 2626 if (needed && any_count == 0)
82075af2 2627 {
649a140c
PA
2628 /* Count how many syscalls are to be caught. */
2629 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2630 {
649a140c 2631 if (syscall_counts[i] != 0)
82075af2
JS
2632 n_sysno++;
2633 }
2634 }
2635
2636 if (remote_debug)
2637 {
2638 fprintf_unfiltered (gdb_stdlog,
2639 "remote_set_syscall_catchpoint "
2640 "pid %d needed %d any_count %d n_sysno %d\n",
2641 pid, needed, any_count, n_sysno);
2642 }
2643
1b81856f 2644 std::string built_packet;
82075af2
JS
2645 if (needed)
2646 {
2647 /* Prepare a packet with the sysno list, assuming max 8+1
2648 characters for a sysno. If the resulting packet size is too
2649 big, fallback on the non-selective packet. */
2650 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
1b81856f
PA
2651 built_packet.reserve (maxpktsz);
2652 built_packet = "QCatchSyscalls:1";
649a140c 2653 if (any_count == 0)
82075af2 2654 {
649a140c
PA
2655 /* Add in each syscall to be caught. */
2656 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2657 {
649a140c
PA
2658 if (syscall_counts[i] != 0)
2659 string_appendf (built_packet, ";%zx", i);
82075af2
JS
2660 }
2661 }
1b81856f 2662 if (built_packet.size () > get_remote_packet_size ())
82075af2
JS
2663 {
2664 /* catch_packet too big. Fallback to less efficient
2665 non selective mode, with GDB doing the filtering. */
b80406ac 2666 catch_packet = "QCatchSyscalls:1";
82075af2 2667 }
b80406ac 2668 else
1b81856f 2669 catch_packet = built_packet.c_str ();
82075af2
JS
2670 }
2671 else
b80406ac 2672 catch_packet = "QCatchSyscalls:0";
82075af2 2673
b80406ac 2674 struct remote_state *rs = get_remote_state ();
82075af2 2675
b80406ac 2676 putpkt (catch_packet);
8d64371b 2677 getpkt (&rs->buf, 0);
b80406ac
TT
2678 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2679 if (result == PACKET_OK)
2680 return 0;
2681 else
2682 return -1;
82075af2
JS
2683}
2684
9b224c5e
PA
2685/* If 'QProgramSignals' is supported, tell the remote stub what
2686 signals it should pass through to the inferior when detaching. */
2687
f6ac5f3d 2688void
adc6a863 2689remote_target::program_signals (gdb::array_view<const unsigned char> signals)
9b224c5e 2690{
4082afcc 2691 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
2692 {
2693 char *packet, *p;
adc6a863 2694 int count = 0;
5e4a05c4 2695 struct remote_state *rs = get_remote_state ();
9b224c5e 2696
adc6a863
PA
2697 gdb_assert (signals.size () < 256);
2698 for (size_t i = 0; i < signals.size (); i++)
9b224c5e
PA
2699 {
2700 if (signals[i])
2701 count++;
2702 }
224c3ddb 2703 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2704 strcpy (packet, "QProgramSignals:");
2705 p = packet + strlen (packet);
adc6a863 2706 for (size_t i = 0; i < signals.size (); i++)
9b224c5e
PA
2707 {
2708 if (signal_pass_state (i))
2709 {
2710 if (i >= 16)
2711 *p++ = tohex (i >> 4);
2712 *p++ = tohex (i & 15);
2713 if (count)
2714 *p++ = ';';
2715 else
2716 break;
2717 count--;
2718 }
2719 }
2720 *p = 0;
5e4a05c4
TT
2721 if (!rs->last_program_signals_packet
2722 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2723 {
9b224c5e 2724 putpkt (packet);
8d64371b 2725 getpkt (&rs->buf, 0);
8dc5b319 2726 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2727 xfree (rs->last_program_signals_packet);
2728 rs->last_program_signals_packet = packet;
9b224c5e
PA
2729 }
2730 else
2731 xfree (packet);
2732 }
2733}
2734
79d7f229
PA
2735/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2736 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2737 thread. If GEN is set, set the general thread, if not, then set
2738 the step/continue thread. */
6b8edb51
PA
2739void
2740remote_target::set_thread (ptid_t ptid, int gen)
c906108c 2741{
d01949b6 2742 struct remote_state *rs = get_remote_state ();
47f8a51d 2743 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
8d64371b
TT
2744 char *buf = rs->buf.data ();
2745 char *endbuf = buf + get_remote_packet_size ();
c906108c 2746
d7e15655 2747 if (state == ptid)
c906108c
SS
2748 return;
2749
79d7f229
PA
2750 *buf++ = 'H';
2751 *buf++ = gen ? 'g' : 'c';
d7e15655 2752 if (ptid == magic_null_ptid)
79d7f229 2753 xsnprintf (buf, endbuf - buf, "0");
d7e15655 2754 else if (ptid == any_thread_ptid)
79d7f229 2755 xsnprintf (buf, endbuf - buf, "0");
d7e15655 2756 else if (ptid == minus_one_ptid)
79d7f229
PA
2757 xsnprintf (buf, endbuf - buf, "-1");
2758 else
82f73884 2759 write_ptid (buf, endbuf, ptid);
79d7f229 2760 putpkt (rs->buf);
8d64371b 2761 getpkt (&rs->buf, 0);
c906108c 2762 if (gen)
47f8a51d 2763 rs->general_thread = ptid;
c906108c 2764 else
47f8a51d 2765 rs->continue_thread = ptid;
c906108c 2766}
79d7f229 2767
6b8edb51
PA
2768void
2769remote_target::set_general_thread (ptid_t ptid)
79d7f229
PA
2770{
2771 set_thread (ptid, 1);
2772}
2773
6b8edb51
PA
2774void
2775remote_target::set_continue_thread (ptid_t ptid)
79d7f229
PA
2776{
2777 set_thread (ptid, 0);
2778}
2779
3c9c4b83
PA
2780/* Change the remote current process. Which thread within the process
2781 ends up selected isn't important, as long as it is the same process
2782 as what INFERIOR_PTID points to.
2783
2784 This comes from that fact that there is no explicit notion of
2785 "selected process" in the protocol. The selected process for
2786 general operations is the process the selected general thread
2787 belongs to. */
2788
6b8edb51
PA
2789void
2790remote_target::set_general_process ()
3c9c4b83
PA
2791{
2792 struct remote_state *rs = get_remote_state ();
2793
2794 /* If the remote can't handle multiple processes, don't bother. */
8020350c 2795 if (!remote_multi_process_p (rs))
3c9c4b83
PA
2796 return;
2797
2798 /* We only need to change the remote current thread if it's pointing
2799 at some other process. */
e99b03dc 2800 if (rs->general_thread.pid () != inferior_ptid.pid ())
3c9c4b83
PA
2801 set_general_thread (inferior_ptid);
2802}
2803
c906108c 2804\f
7d1a114c
PA
2805/* Return nonzero if this is the main thread that we made up ourselves
2806 to model non-threaded targets as single-threaded. */
c906108c
SS
2807
2808static int
f6ac5f3d 2809remote_thread_always_alive (ptid_t ptid)
c906108c 2810{
d7e15655 2811 if (ptid == magic_null_ptid)
c0a2216e
PA
2812 /* The main thread is always alive. */
2813 return 1;
2814
e38504b3 2815 if (ptid.pid () != 0 && ptid.lwp () == 0)
c0a2216e
PA
2816 /* The main thread is always alive. This can happen after a
2817 vAttach, if the remote side doesn't support
2818 multi-threading. */
2819 return 1;
2820
7d1a114c
PA
2821 return 0;
2822}
2823
2824/* Return nonzero if the thread PTID is still alive on the remote
2825 system. */
2826
57810aa7 2827bool
f6ac5f3d 2828remote_target::thread_alive (ptid_t ptid)
7d1a114c
PA
2829{
2830 struct remote_state *rs = get_remote_state ();
2831 char *p, *endp;
2832
2833 /* Check if this is a thread that we made up ourselves to model
2834 non-threaded targets as single-threaded. */
f6ac5f3d 2835 if (remote_thread_always_alive (ptid))
7d1a114c
PA
2836 return 1;
2837
8d64371b
TT
2838 p = rs->buf.data ();
2839 endp = p + get_remote_packet_size ();
82f73884
PA
2840
2841 *p++ = 'T';
2842 write_ptid (p, endp, ptid);
2843
2e9f7625 2844 putpkt (rs->buf);
8d64371b 2845 getpkt (&rs->buf, 0);
2e9f7625 2846 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2847}
2848
79efa585
SM
2849/* Return a pointer to a thread name if we know it and NULL otherwise.
2850 The thread_info object owns the memory for the name. */
2851
f6ac5f3d
PA
2852const char *
2853remote_target::thread_name (struct thread_info *info)
79efa585
SM
2854{
2855 if (info->priv != NULL)
a9334058
SM
2856 {
2857 const std::string &name = get_remote_thread_info (info)->name;
2858 return !name.empty () ? name.c_str () : NULL;
2859 }
79efa585
SM
2860
2861 return NULL;
2862}
2863
c906108c
SS
2864/* About these extended threadlist and threadinfo packets. They are
2865 variable length packets but, the fields within them are often fixed
2866 length. They are redundent enough to send over UDP as is the
2867 remote protocol in general. There is a matching unit test module
2868 in libstub. */
2869
23860348 2870/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2871 libstub protocol encoding, and remote.c. It is not particularly
23860348 2872 changable. */
cce74817
JM
2873
2874/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2875 Plan to fix this. */
cce74817 2876
23860348 2877typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2878
9d1f7ab2 2879/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2880 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2881
2882struct gdb_ext_thread_info
c5aa993b 2883 {
23860348 2884 threadref threadid; /* External form of thread reference. */
2bc416ba 2885 int active; /* Has state interesting to GDB?
23860348 2886 regs, stack. */
2bc416ba 2887 char display[256]; /* Brief state display, name,
cedea757 2888 blocked/suspended. */
23860348 2889 char shortname[32]; /* To be used to name threads. */
2bc416ba 2890 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2891 whatever. */
c5aa993b 2892 };
cce74817
JM
2893
2894/* The volume of remote transfers can be limited by submitting
2895 a mask containing bits specifying the desired information.
2896 Use a union of these values as the 'selection' parameter to
0df8b418 2897 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2898
2899#define TAG_THREADID 1
2900#define TAG_EXISTS 2
2901#define TAG_DISPLAY 4
2902#define TAG_THREADNAME 8
c5aa993b 2903#define TAG_MOREDISPLAY 16
cce74817 2904
23860348 2905#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2906
a14ed312 2907static char *unpack_nibble (char *buf, int *val);
cce74817 2908
a14ed312 2909static char *unpack_byte (char *buf, int *value);
cce74817 2910
a14ed312 2911static char *pack_int (char *buf, int value);
cce74817 2912
a14ed312 2913static char *unpack_int (char *buf, int *value);
cce74817 2914
a14ed312 2915static char *unpack_string (char *src, char *dest, int length);
cce74817 2916
23860348 2917static char *pack_threadid (char *pkt, threadref *id);
cce74817 2918
23860348 2919static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2920
23860348 2921void int_to_threadref (threadref *id, int value);
cce74817 2922
23860348 2923static int threadref_to_int (threadref *ref);
cce74817 2924
23860348 2925static void copy_threadref (threadref *dest, threadref *src);
cce74817 2926
23860348 2927static int threadmatch (threadref *dest, threadref *src);
cce74817 2928
2bc416ba 2929static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2930 threadref *id);
cce74817 2931
a14ed312
KB
2932static char *pack_threadlist_request (char *pkt, int startflag,
2933 int threadcount,
23860348 2934 threadref *nextthread);
cce74817 2935
23860348 2936static int remote_newthread_step (threadref *ref, void *context);
cce74817 2937
82f73884
PA
2938
2939/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2940 buffer we're allowed to write to. Returns
2941 BUF+CHARACTERS_WRITTEN. */
2942
6b8edb51
PA
2943char *
2944remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
82f73884
PA
2945{
2946 int pid, tid;
2947 struct remote_state *rs = get_remote_state ();
2948
2949 if (remote_multi_process_p (rs))
2950 {
e99b03dc 2951 pid = ptid.pid ();
82f73884
PA
2952 if (pid < 0)
2953 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2954 else
2955 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2956 }
e38504b3 2957 tid = ptid.lwp ();
82f73884
PA
2958 if (tid < 0)
2959 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2960 else
2961 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2962
2963 return buf;
2964}
2965
256642e8
PA
2966/* Extract a PTID from BUF. If non-null, OBUF is set to one past the
2967 last parsed char. Returns null_ptid if no thread id is found, and
2968 throws an error if the thread id has an invalid format. */
82f73884
PA
2969
2970static ptid_t
256642e8 2971read_ptid (const char *buf, const char **obuf)
82f73884 2972{
256642e8
PA
2973 const char *p = buf;
2974 const char *pp;
82f73884 2975 ULONGEST pid = 0, tid = 0;
82f73884
PA
2976
2977 if (*p == 'p')
2978 {
2979 /* Multi-process ptid. */
2980 pp = unpack_varlen_hex (p + 1, &pid);
2981 if (*pp != '.')
b37520b6 2982 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2983
2984 p = pp;
2985 pp = unpack_varlen_hex (p + 1, &tid);
2986 if (obuf)
2987 *obuf = pp;
fd79271b 2988 return ptid_t (pid, tid, 0);
82f73884
PA
2989 }
2990
2991 /* No multi-process. Just a tid. */
2992 pp = unpack_varlen_hex (p, &tid);
2993
c9f35b34
KB
2994 /* Return null_ptid when no thread id is found. */
2995 if (p == pp)
2996 {
2997 if (obuf)
2998 *obuf = pp;
2999 return null_ptid;
3000 }
3001
82f73884 3002 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
3003 what's in inferior_ptid, unless it's null at this point. If so,
3004 then since there's no way to know the pid of the reported
3005 threads, use the magic number. */
d7e15655 3006 if (inferior_ptid == null_ptid)
e99b03dc 3007 pid = magic_null_ptid.pid ();
ca19bf23 3008 else
e99b03dc 3009 pid = inferior_ptid.pid ();
82f73884
PA
3010
3011 if (obuf)
3012 *obuf = pp;
fd79271b 3013 return ptid_t (pid, tid, 0);
82f73884
PA
3014}
3015
c906108c 3016static int
fba45db2 3017stubhex (int ch)
c906108c
SS
3018{
3019 if (ch >= 'a' && ch <= 'f')
3020 return ch - 'a' + 10;
3021 if (ch >= '0' && ch <= '9')
3022 return ch - '0';
3023 if (ch >= 'A' && ch <= 'F')
3024 return ch - 'A' + 10;
3025 return -1;
3026}
3027
3028static int
fba45db2 3029stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
3030{
3031 int nibble;
3032 int retval = 0;
3033
3034 while (fieldlength)
3035 {
3036 nibble = stubhex (*buff++);
3037 retval |= nibble;
3038 fieldlength--;
3039 if (fieldlength)
3040 retval = retval << 4;
3041 }
3042 return retval;
3043}
3044
c906108c 3045static char *
fba45db2 3046unpack_nibble (char *buf, int *val)
c906108c 3047{
b7589f7d 3048 *val = fromhex (*buf++);
c906108c
SS
3049 return buf;
3050}
3051
c906108c 3052static char *
fba45db2 3053unpack_byte (char *buf, int *value)
c906108c
SS
3054{
3055 *value = stub_unpack_int (buf, 2);
3056 return buf + 2;
3057}
3058
3059static char *
fba45db2 3060pack_int (char *buf, int value)
c906108c
SS
3061{
3062 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3063 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3064 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3065 buf = pack_hex_byte (buf, (value & 0xff));
3066 return buf;
3067}
3068
3069static char *
fba45db2 3070unpack_int (char *buf, int *value)
c906108c
SS
3071{
3072 *value = stub_unpack_int (buf, 8);
3073 return buf + 8;
3074}
3075
23860348 3076#if 0 /* Currently unused, uncomment when needed. */
a14ed312 3077static char *pack_string (char *pkt, char *string);
c906108c
SS
3078
3079static char *
fba45db2 3080pack_string (char *pkt, char *string)
c906108c
SS
3081{
3082 char ch;
3083 int len;
3084
3085 len = strlen (string);
3086 if (len > 200)
23860348 3087 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
3088 pkt = pack_hex_byte (pkt, len);
3089 while (len-- > 0)
3090 {
3091 ch = *string++;
3092 if ((ch == '\0') || (ch == '#'))
23860348 3093 ch = '*'; /* Protect encapsulation. */
c906108c
SS
3094 *pkt++ = ch;
3095 }
3096 return pkt;
3097}
3098#endif /* 0 (unused) */
3099
3100static char *
fba45db2 3101unpack_string (char *src, char *dest, int length)
c906108c
SS
3102{
3103 while (length--)
3104 *dest++ = *src++;
3105 *dest = '\0';
3106 return src;
3107}
3108
3109static char *
fba45db2 3110pack_threadid (char *pkt, threadref *id)
c906108c
SS
3111{
3112 char *limit;
3113 unsigned char *altid;
3114
3115 altid = (unsigned char *) id;
3116 limit = pkt + BUF_THREAD_ID_SIZE;
3117 while (pkt < limit)
3118 pkt = pack_hex_byte (pkt, *altid++);
3119 return pkt;
3120}
3121
3122
3123static char *
fba45db2 3124unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
3125{
3126 char *altref;
3127 char *limit = inbuf + BUF_THREAD_ID_SIZE;
3128 int x, y;
3129
3130 altref = (char *) id;
3131
3132 while (inbuf < limit)
3133 {
3134 x = stubhex (*inbuf++);
3135 y = stubhex (*inbuf++);
3136 *altref++ = (x << 4) | y;
3137 }
3138 return inbuf;
3139}
3140
3141/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 3142 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
3143 to use 64bit thread references internally. This is an adapter
3144 function. */
3145
3146void
fba45db2 3147int_to_threadref (threadref *id, int value)
c906108c
SS
3148{
3149 unsigned char *scan;
3150
3151 scan = (unsigned char *) id;
3152 {
3153 int i = 4;
3154 while (i--)
3155 *scan++ = 0;
3156 }
3157 *scan++ = (value >> 24) & 0xff;
3158 *scan++ = (value >> 16) & 0xff;
3159 *scan++ = (value >> 8) & 0xff;
3160 *scan++ = (value & 0xff);
3161}
3162
3163static int
fba45db2 3164threadref_to_int (threadref *ref)
c906108c
SS
3165{
3166 int i, value = 0;
3167 unsigned char *scan;
3168
cfd77fa1 3169 scan = *ref;
c906108c
SS
3170 scan += 4;
3171 i = 4;
3172 while (i-- > 0)
3173 value = (value << 8) | ((*scan++) & 0xff);
3174 return value;
3175}
3176
3177static void
fba45db2 3178copy_threadref (threadref *dest, threadref *src)
c906108c
SS
3179{
3180 int i;
3181 unsigned char *csrc, *cdest;
3182
3183 csrc = (unsigned char *) src;
3184 cdest = (unsigned char *) dest;
3185 i = 8;
3186 while (i--)
3187 *cdest++ = *csrc++;
3188}
3189
3190static int
fba45db2 3191threadmatch (threadref *dest, threadref *src)
c906108c 3192{
23860348 3193 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
3194#if 0
3195 unsigned char *srcp, *destp;
3196 int i, result;
3197 srcp = (char *) src;
3198 destp = (char *) dest;
3199
3200 result = 1;
3201 while (i-- > 0)
3202 result &= (*srcp++ == *destp++) ? 1 : 0;
3203 return result;
3204#endif
3205 return 1;
3206}
3207
3208/*
c5aa993b
JM
3209 threadid:1, # always request threadid
3210 context_exists:2,
3211 display:4,
3212 unique_name:8,
3213 more_display:16
3214 */
c906108c
SS
3215
3216/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3217
3218static char *
fba45db2 3219pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 3220{
23860348
MS
3221 *pkt++ = 'q'; /* Info Query */
3222 *pkt++ = 'P'; /* process or thread info */
3223 pkt = pack_int (pkt, mode); /* mode */
c906108c 3224 pkt = pack_threadid (pkt, id); /* threadid */
23860348 3225 *pkt = '\0'; /* terminate */
c906108c
SS
3226 return pkt;
3227}
3228
23860348 3229/* These values tag the fields in a thread info response packet. */
c906108c 3230/* Tagging the fields allows us to request specific fields and to
23860348 3231 add more fields as time goes by. */
c906108c 3232
23860348 3233#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 3234#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 3235 fetch registers and its stack? */
c5aa993b 3236#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 3237#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 3238#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 3239 the process. */
c906108c 3240
6b8edb51
PA
3241int
3242remote_target::remote_unpack_thread_info_response (char *pkt,
3243 threadref *expectedref,
3244 gdb_ext_thread_info *info)
c906108c 3245{
d01949b6 3246 struct remote_state *rs = get_remote_state ();
c906108c 3247 int mask, length;
cfd77fa1 3248 int tag;
c906108c 3249 threadref ref;
8d64371b 3250 char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
c906108c
SS
3251 int retval = 1;
3252
23860348 3253 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
3254 info->active = 0;
3255 info->display[0] = '\0';
3256 info->shortname[0] = '\0';
3257 info->more_display[0] = '\0';
3258
23860348
MS
3259 /* Assume the characters indicating the packet type have been
3260 stripped. */
c906108c
SS
3261 pkt = unpack_int (pkt, &mask); /* arg mask */
3262 pkt = unpack_threadid (pkt, &ref);
3263
3264 if (mask == 0)
8a3fe4f8 3265 warning (_("Incomplete response to threadinfo request."));
c906108c 3266 if (!threadmatch (&ref, expectedref))
23860348 3267 { /* This is an answer to a different request. */
8a3fe4f8 3268 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
3269 return 0;
3270 }
3271 copy_threadref (&info->threadid, &ref);
3272
23860348 3273 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 3274
23860348
MS
3275 /* Packets are terminated with nulls. */
3276 while ((pkt < limit) && mask && *pkt)
c906108c
SS
3277 {
3278 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
3279 pkt = unpack_byte (pkt, &length); /* length */
3280 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 3281 {
8a3fe4f8 3282 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
3283 retval = 0;
3284 break;
3285 }
3286 if (tag == TAG_THREADID)
3287 {
3288 if (length != 16)
3289 {
8a3fe4f8 3290 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
3291 retval = 0;
3292 break;
3293 }
3294 pkt = unpack_threadid (pkt, &ref);
3295 mask = mask & ~TAG_THREADID;
3296 continue;
3297 }
3298 if (tag == TAG_EXISTS)
3299 {
3300 info->active = stub_unpack_int (pkt, length);
3301 pkt += length;
3302 mask = mask & ~(TAG_EXISTS);
3303 if (length > 8)
3304 {
8a3fe4f8 3305 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
3306 retval = 0;
3307 break;
3308 }
3309 continue;
3310 }
3311 if (tag == TAG_THREADNAME)
3312 {
3313 pkt = unpack_string (pkt, &info->shortname[0], length);
3314 mask = mask & ~TAG_THREADNAME;
3315 continue;
3316 }
3317 if (tag == TAG_DISPLAY)
3318 {
3319 pkt = unpack_string (pkt, &info->display[0], length);
3320 mask = mask & ~TAG_DISPLAY;
3321 continue;
3322 }
3323 if (tag == TAG_MOREDISPLAY)
3324 {
3325 pkt = unpack_string (pkt, &info->more_display[0], length);
3326 mask = mask & ~TAG_MOREDISPLAY;
3327 continue;
3328 }
8a3fe4f8 3329 warning (_("ERROR RMT: unknown thread info tag."));
23860348 3330 break; /* Not a tag we know about. */
c906108c
SS
3331 }
3332 return retval;
3333}
3334
6b8edb51
PA
3335int
3336remote_target::remote_get_threadinfo (threadref *threadid,
3337 int fieldset,
3338 gdb_ext_thread_info *info)
c906108c 3339{
d01949b6 3340 struct remote_state *rs = get_remote_state ();
c906108c 3341 int result;
c906108c 3342
8d64371b 3343 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
2e9f7625 3344 putpkt (rs->buf);
8d64371b 3345 getpkt (&rs->buf, 0);
3084dd77
PA
3346
3347 if (rs->buf[0] == '\0')
3348 return 0;
3349
8d64371b 3350 result = remote_unpack_thread_info_response (&rs->buf[2],
23860348 3351 threadid, info);
c906108c
SS
3352 return result;
3353}
3354
c906108c
SS
3355/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3356
3357static char *
fba45db2
KB
3358pack_threadlist_request (char *pkt, int startflag, int threadcount,
3359 threadref *nextthread)
c906108c
SS
3360{
3361 *pkt++ = 'q'; /* info query packet */
3362 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 3363 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
3364 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3365 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3366 *pkt = '\0';
3367 return pkt;
3368}
3369
3370/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3371
6b8edb51
PA
3372int
3373remote_target::parse_threadlist_response (char *pkt, int result_limit,
3374 threadref *original_echo,
3375 threadref *resultlist,
3376 int *doneflag)
c906108c 3377{
d01949b6 3378 struct remote_state *rs = get_remote_state ();
c906108c
SS
3379 char *limit;
3380 int count, resultcount, done;
3381
3382 resultcount = 0;
3383 /* Assume the 'q' and 'M chars have been stripped. */
8d64371b 3384 limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
23860348 3385 /* done parse past here */
c906108c
SS
3386 pkt = unpack_byte (pkt, &count); /* count field */
3387 pkt = unpack_nibble (pkt, &done);
3388 /* The first threadid is the argument threadid. */
3389 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3390 while ((count-- > 0) && (pkt < limit))
3391 {
3392 pkt = unpack_threadid (pkt, resultlist++);
3393 if (resultcount++ >= result_limit)
3394 break;
3395 }
3396 if (doneflag)
3397 *doneflag = done;
3398 return resultcount;
3399}
3400
6dc54d91
PA
3401/* Fetch the next batch of threads from the remote. Returns -1 if the
3402 qL packet is not supported, 0 on error and 1 on success. */
3403
6b8edb51
PA
3404int
3405remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3406 int result_limit, int *done, int *result_count,
3407 threadref *threadlist)
c906108c 3408{
d01949b6 3409 struct remote_state *rs = get_remote_state ();
c906108c
SS
3410 int result = 1;
3411
23860348 3412 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
3413 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3414 >= get_remote_packet_size ())
ea9c271d 3415 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 3416
8d64371b
TT
3417 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3418 nextthread);
6d820c5c 3419 putpkt (rs->buf);
8d64371b
TT
3420 getpkt (&rs->buf, 0);
3421 if (rs->buf[0] == '\0')
6dc54d91
PA
3422 {
3423 /* Packet not supported. */
3424 return -1;
3425 }
3426
3427 *result_count =
8d64371b 3428 parse_threadlist_response (&rs->buf[2], result_limit,
6dc54d91 3429 &rs->echo_nextthread, threadlist, done);
c906108c 3430
0d031856 3431 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 3432 {
23860348
MS
3433 /* FIXME: This is a good reason to drop the packet. */
3434 /* Possably, there is a duplicate response. */
c906108c
SS
3435 /* Possabilities :
3436 retransmit immediatly - race conditions
3437 retransmit after timeout - yes
3438 exit
3439 wait for packet, then exit
3440 */
8a3fe4f8 3441 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 3442 return 0; /* I choose simply exiting. */
c906108c
SS
3443 }
3444 if (*result_count <= 0)
3445 {
3446 if (*done != 1)
3447 {
8a3fe4f8 3448 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
3449 result = 0;
3450 }
3451 return result; /* break; */
3452 }
3453 if (*result_count > result_limit)
3454 {
3455 *result_count = 0;
8a3fe4f8 3456 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
3457 return 0;
3458 }
3459 return result;
3460}
3461
6dc54d91
PA
3462/* Fetch the list of remote threads, with the qL packet, and call
3463 STEPFUNCTION for each thread found. Stops iterating and returns 1
3464 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3465 STEPFUNCTION returns false. If the packet is not supported,
3466 returns -1. */
c906108c 3467
6b8edb51
PA
3468int
3469remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3470 void *context, int looplimit)
c906108c 3471{
0d031856 3472 struct remote_state *rs = get_remote_state ();
c906108c
SS
3473 int done, i, result_count;
3474 int startflag = 1;
3475 int result = 1;
3476 int loopcount = 0;
c906108c
SS
3477
3478 done = 0;
3479 while (!done)
3480 {
3481 if (loopcount++ > looplimit)
3482 {
3483 result = 0;
8a3fe4f8 3484 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
3485 break;
3486 }
6dc54d91
PA
3487 result = remote_get_threadlist (startflag, &rs->nextthread,
3488 MAXTHREADLISTRESULTS,
3489 &done, &result_count,
3490 rs->resultthreadlist);
3491 if (result <= 0)
3492 break;
23860348 3493 /* Clear for later iterations. */
c906108c
SS
3494 startflag = 0;
3495 /* Setup to resume next batch of thread references, set nextthread. */
3496 if (result_count >= 1)
0d031856
TT
3497 copy_threadref (&rs->nextthread,
3498 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
3499 i = 0;
3500 while (result_count--)
6dc54d91
PA
3501 {
3502 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3503 {
3504 result = 0;
3505 break;
3506 }
3507 }
c906108c
SS
3508 }
3509 return result;
3510}
3511
6dc54d91
PA
3512/* A thread found on the remote target. */
3513
21fe1c75 3514struct thread_item
6dc54d91 3515{
21fe1c75
SM
3516 explicit thread_item (ptid_t ptid_)
3517 : ptid (ptid_)
3518 {}
3519
3520 thread_item (thread_item &&other) = default;
3521 thread_item &operator= (thread_item &&other) = default;
3522
3523 DISABLE_COPY_AND_ASSIGN (thread_item);
3524
6dc54d91
PA
3525 /* The thread's PTID. */
3526 ptid_t ptid;
3527
21fe1c75
SM
3528 /* The thread's extra info. */
3529 std::string extra;
6dc54d91 3530
21fe1c75
SM
3531 /* The thread's name. */
3532 std::string name;
79efa585 3533
6dc54d91 3534 /* The core the thread was running on. -1 if not known. */
21fe1c75 3535 int core = -1;
f6327dcb
KB
3536
3537 /* The thread handle associated with the thread. */
21fe1c75 3538 gdb::byte_vector thread_handle;
21fe1c75 3539};
6dc54d91
PA
3540
3541/* Context passed around to the various methods listing remote
3542 threads. As new threads are found, they're added to the ITEMS
3543 vector. */
3544
3545struct threads_listing_context
3546{
21fe1c75
SM
3547 /* Return true if this object contains an entry for a thread with ptid
3548 PTID. */
6dc54d91 3549
21fe1c75
SM
3550 bool contains_thread (ptid_t ptid) const
3551 {
3552 auto match_ptid = [&] (const thread_item &item)
3553 {
3554 return item.ptid == ptid;
3555 };
80134cf5 3556
21fe1c75
SM
3557 auto it = std::find_if (this->items.begin (),
3558 this->items.end (),
3559 match_ptid);
80134cf5 3560
21fe1c75
SM
3561 return it != this->items.end ();
3562 }
80134cf5 3563
21fe1c75 3564 /* Remove the thread with ptid PTID. */
80134cf5 3565
21fe1c75
SM
3566 void remove_thread (ptid_t ptid)
3567 {
3568 auto match_ptid = [&] (const thread_item &item)
3569 {
3570 return item.ptid == ptid;
3571 };
cbb8991c 3572
21fe1c75
SM
3573 auto it = std::remove_if (this->items.begin (),
3574 this->items.end (),
3575 match_ptid);
cbb8991c 3576
21fe1c75
SM
3577 if (it != this->items.end ())
3578 this->items.erase (it);
3579 }
3580
3581 /* The threads found on the remote target. */
3582 std::vector<thread_item> items;
3583};
cbb8991c 3584
c906108c 3585static int
6dc54d91 3586remote_newthread_step (threadref *ref, void *data)
c906108c 3587{
19ba03f4
SM
3588 struct threads_listing_context *context
3589 = (struct threads_listing_context *) data;
21fe1c75
SM
3590 int pid = inferior_ptid.pid ();
3591 int lwp = threadref_to_int (ref);
3592 ptid_t ptid (pid, lwp);
6dc54d91 3593
21fe1c75 3594 context->items.emplace_back (ptid);
6dc54d91 3595
c906108c
SS
3596 return 1; /* continue iterator */
3597}
3598
3599#define CRAZY_MAX_THREADS 1000
3600
6b8edb51
PA
3601ptid_t
3602remote_target::remote_current_thread (ptid_t oldpid)
c906108c 3603{
d01949b6 3604 struct remote_state *rs = get_remote_state ();
c906108c
SS
3605
3606 putpkt ("qC");
8d64371b 3607 getpkt (&rs->buf, 0);
2e9f7625 3608 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34 3609 {
256642e8 3610 const char *obuf;
c9f35b34
KB
3611 ptid_t result;
3612
3613 result = read_ptid (&rs->buf[2], &obuf);
3614 if (*obuf != '\0' && remote_debug)
3615 fprintf_unfiltered (gdb_stdlog,
3616 "warning: garbage in qC reply\n");
3617
3618 return result;
3619 }
c906108c
SS
3620 else
3621 return oldpid;
3622}
3623
6dc54d91 3624/* List remote threads using the deprecated qL packet. */
cce74817 3625
6b8edb51
PA
3626int
3627remote_target::remote_get_threads_with_ql (threads_listing_context *context)
c906108c 3628{
6dc54d91
PA
3629 if (remote_threadlist_iterator (remote_newthread_step, context,
3630 CRAZY_MAX_THREADS) >= 0)
3631 return 1;
3632
3633 return 0;
c906108c
SS
3634}
3635
dc146f7c
VP
3636#if defined(HAVE_LIBEXPAT)
3637
dc146f7c
VP
3638static void
3639start_thread (struct gdb_xml_parser *parser,
3640 const struct gdb_xml_element *element,
4d0fdd9b
SM
3641 void *user_data,
3642 std::vector<gdb_xml_value> &attributes)
dc146f7c 3643{
19ba03f4
SM
3644 struct threads_listing_context *data
3645 = (struct threads_listing_context *) user_data;
3d2c1d41 3646 struct gdb_xml_value *attr;
dc146f7c 3647
4d0fdd9b 3648 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
21fe1c75
SM
3649 ptid_t ptid = read_ptid (id, NULL);
3650
3651 data->items.emplace_back (ptid);
3652 thread_item &item = data->items.back ();
dc146f7c 3653
3d2c1d41
PA
3654 attr = xml_find_attribute (attributes, "core");
3655 if (attr != NULL)
4d0fdd9b 3656 item.core = *(ULONGEST *) attr->value.get ();
dc146f7c 3657
79efa585 3658 attr = xml_find_attribute (attributes, "name");
21fe1c75 3659 if (attr != NULL)
4d0fdd9b 3660 item.name = (const char *) attr->value.get ();
79efa585 3661
f6327dcb
KB
3662 attr = xml_find_attribute (attributes, "handle");
3663 if (attr != NULL)
4d0fdd9b 3664 item.thread_handle = hex2bin ((const char *) attr->value.get ());
dc146f7c
VP
3665}
3666
3667static void
3668end_thread (struct gdb_xml_parser *parser,
3669 const struct gdb_xml_element *element,
3670 void *user_data, const char *body_text)
3671{
19ba03f4
SM
3672 struct threads_listing_context *data
3673 = (struct threads_listing_context *) user_data;
dc146f7c 3674
21fe1c75
SM
3675 if (body_text != NULL && *body_text != '\0')
3676 data->items.back ().extra = body_text;
dc146f7c
VP
3677}
3678
3679const struct gdb_xml_attribute thread_attributes[] = {
3680 { "id", GDB_XML_AF_NONE, NULL, NULL },
3681 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3682 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
f6327dcb 3683 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3684 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3685};
3686
3687const struct gdb_xml_element thread_children[] = {
3688 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3689};
3690
3691const struct gdb_xml_element threads_children[] = {
3692 { "thread", thread_attributes, thread_children,
3693 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3694 start_thread, end_thread },
3695 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3696};
3697
3698const struct gdb_xml_element threads_elements[] = {
3699 { "threads", NULL, threads_children,
3700 GDB_XML_EF_NONE, NULL, NULL },
3701 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3702};
3703
3704#endif
3705
6dc54d91 3706/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3707
6b8edb51
PA
3708int
3709remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
0f71a2f6 3710{
dc146f7c 3711#if defined(HAVE_LIBEXPAT)
4082afcc 3712 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3713 {
9018be22 3714 gdb::optional<gdb::char_vector> xml
6b8edb51 3715 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
efc0eabd 3716
9018be22 3717 if (xml && (*xml)[0] != '\0')
dc146f7c 3718 {
6dc54d91 3719 gdb_xml_parse_quick (_("threads"), "threads.dtd",
9018be22 3720 threads_elements, xml->data (), context);
dc146f7c
VP
3721 }
3722
6dc54d91 3723 return 1;
dc146f7c
VP
3724 }
3725#endif
3726
6dc54d91
PA
3727 return 0;
3728}
3729
3730/* List remote threads using qfThreadInfo/qsThreadInfo. */
3731
6b8edb51
PA
3732int
3733remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
6dc54d91
PA
3734{
3735 struct remote_state *rs = get_remote_state ();
3736
b80fafe3 3737 if (rs->use_threadinfo_query)
9d1f7ab2 3738 {
256642e8 3739 const char *bufp;
6dc54d91 3740
9d1f7ab2 3741 putpkt ("qfThreadInfo");
8d64371b
TT
3742 getpkt (&rs->buf, 0);
3743 bufp = rs->buf.data ();
9d1f7ab2 3744 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3745 {
9d1f7ab2
MS
3746 while (*bufp++ == 'm') /* reply contains one or more TID */
3747 {
3748 do
3749 {
21fe1c75
SM
3750 ptid_t ptid = read_ptid (bufp, &bufp);
3751 context->items.emplace_back (ptid);
9d1f7ab2
MS
3752 }
3753 while (*bufp++ == ','); /* comma-separated list */
3754 putpkt ("qsThreadInfo");
8d64371b
TT
3755 getpkt (&rs->buf, 0);
3756 bufp = rs->buf.data ();
9d1f7ab2 3757 }
6dc54d91
PA
3758 return 1;
3759 }
3760 else
3761 {
3762 /* Packet not recognized. */
3763 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3764 }
3765 }
3766
6dc54d91
PA
3767 return 0;
3768}
3769
e8032dde 3770/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3771 targets. */
3772
f6ac5f3d
PA
3773void
3774remote_target::update_thread_list ()
6dc54d91 3775{
6dc54d91 3776 struct threads_listing_context context;
ab970af1 3777 int got_list = 0;
e8032dde 3778
6dc54d91
PA
3779 /* We have a few different mechanisms to fetch the thread list. Try
3780 them all, starting with the most preferred one first, falling
3781 back to older methods. */
6b8edb51
PA
3782 if (remote_get_threads_with_qxfer (&context)
3783 || remote_get_threads_with_qthreadinfo (&context)
3784 || remote_get_threads_with_ql (&context))
6dc54d91 3785 {
ab970af1
PA
3786 got_list = 1;
3787
21fe1c75 3788 if (context.items.empty ()
f6ac5f3d 3789 && remote_thread_always_alive (inferior_ptid))
7d1a114c
PA
3790 {
3791 /* Some targets don't really support threads, but still
3792 reply an (empty) thread list in response to the thread
3793 listing packets, instead of replying "packet not
3794 supported". Exit early so we don't delete the main
3795 thread. */
7d1a114c
PA
3796 return;
3797 }
3798
ab970af1
PA
3799 /* CONTEXT now holds the current thread list on the remote
3800 target end. Delete GDB-side threads no longer found on the
3801 target. */
08036331 3802 for (thread_info *tp : all_threads_safe ())
cbb8991c 3803 {
21fe1c75 3804 if (!context.contains_thread (tp->ptid))
ab970af1
PA
3805 {
3806 /* Not found. */
00431a78 3807 delete_thread (tp);
ab970af1 3808 }
cbb8991c
DB
3809 }
3810
3811 /* Remove any unreported fork child threads from CONTEXT so
3812 that we don't interfere with follow fork, which is where
3813 creation of such threads is handled. */
3814 remove_new_fork_children (&context);
74531fed 3815
ab970af1 3816 /* And now add threads we don't know about yet to our list. */
21fe1c75 3817 for (thread_item &item : context.items)
6dc54d91 3818 {
21fe1c75 3819 if (item.ptid != null_ptid)
6dc54d91 3820 {
6dc54d91 3821 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
3822 executing until proven otherwise with a stop reply.
3823 In all-stop, we can only get here if all threads are
6dc54d91 3824 stopped. */
0d5b594f 3825 int executing = target_is_non_stop_p () ? 1 : 0;
6dc54d91 3826
21fe1c75 3827 remote_notice_new_inferior (item.ptid, executing);
6dc54d91 3828
08036331 3829 thread_info *tp = find_thread_ptid (item.ptid);
00431a78 3830 remote_thread_info *info = get_remote_thread_info (tp);
21fe1c75 3831 info->core = item.core;
7aabaf9d
SM
3832 info->extra = std::move (item.extra);
3833 info->name = std::move (item.name);
3834 info->thread_handle = std::move (item.thread_handle);
6dc54d91
PA
3835 }
3836 }
3837 }
3838
ab970af1
PA
3839 if (!got_list)
3840 {
3841 /* If no thread listing method is supported, then query whether
3842 each known thread is alive, one by one, with the T packet.
3843 If the target doesn't support threads at all, then this is a
3844 no-op. See remote_thread_alive. */
3845 prune_threads ();
3846 }
9d1f7ab2
MS
3847}
3848
802188a7 3849/*
9d1f7ab2
MS
3850 * Collect a descriptive string about the given thread.
3851 * The target may say anything it wants to about the thread
3852 * (typically info about its blocked / runnable state, name, etc.).
3853 * This string will appear in the info threads display.
802188a7 3854 *
9d1f7ab2
MS
3855 * Optional: targets are not required to implement this function.
3856 */
3857
f6ac5f3d
PA
3858const char *
3859remote_target::extra_thread_info (thread_info *tp)
9d1f7ab2 3860{
d01949b6 3861 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3862 int set;
3863 threadref id;
3864 struct gdb_ext_thread_info threadinfo;
9d1f7ab2 3865
5d93a237 3866 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3867 internal_error (__FILE__, __LINE__,
e2e0b3e5 3868 _("remote_threads_extra_info"));
9d1f7ab2 3869
d7e15655 3870 if (tp->ptid == magic_null_ptid
e38504b3 3871 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
60e569b9
PA
3872 /* This is the main thread which was added by GDB. The remote
3873 server doesn't know about it. */
3874 return NULL;
3875
c76a8ea3
PA
3876 std::string &extra = get_remote_thread_info (tp)->extra;
3877
3878 /* If already have cached info, use it. */
3879 if (!extra.empty ())
3880 return extra.c_str ();
3881
4082afcc 3882 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3883 {
c76a8ea3
PA
3884 /* If we're using qXfer:threads:read, then the extra info is
3885 included in the XML. So if we didn't have anything cached,
3886 it's because there's really no extra info. */
3887 return NULL;
dc146f7c
VP
3888 }
3889
b80fafe3 3890 if (rs->use_threadextra_query)
9d1f7ab2 3891 {
8d64371b
TT
3892 char *b = rs->buf.data ();
3893 char *endb = b + get_remote_packet_size ();
82f73884
PA
3894
3895 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3896 b += strlen (b);
3897 write_ptid (b, endb, tp->ptid);
3898
2e9f7625 3899 putpkt (rs->buf);
8d64371b 3900 getpkt (&rs->buf, 0);
2e9f7625 3901 if (rs->buf[0] != 0)
9d1f7ab2 3902 {
8d64371b
TT
3903 extra.resize (strlen (rs->buf.data ()) / 2);
3904 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
c76a8ea3 3905 return extra.c_str ();
9d1f7ab2 3906 }
0f71a2f6 3907 }
9d1f7ab2
MS
3908
3909 /* If the above query fails, fall back to the old method. */
b80fafe3 3910 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3911 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3912 | TAG_MOREDISPLAY | TAG_DISPLAY;
e38504b3 3913 int_to_threadref (&id, tp->ptid.lwp ());
9d1f7ab2
MS
3914 if (remote_get_threadinfo (&id, set, &threadinfo))
3915 if (threadinfo.active)
0f71a2f6 3916 {
9d1f7ab2 3917 if (*threadinfo.shortname)
c76a8ea3 3918 string_appendf (extra, " Name: %s", threadinfo.shortname);
9d1f7ab2 3919 if (*threadinfo.display)
c76a8ea3
PA
3920 {
3921 if (!extra.empty ())
3922 extra += ',';
3923 string_appendf (extra, " State: %s", threadinfo.display);
3924 }
9d1f7ab2 3925 if (*threadinfo.more_display)
c5aa993b 3926 {
c76a8ea3
PA
3927 if (!extra.empty ())
3928 extra += ',';
3929 string_appendf (extra, " Priority: %s", threadinfo.more_display);
c5aa993b 3930 }
c76a8ea3 3931 return extra.c_str ();
0f71a2f6 3932 }
9d1f7ab2 3933 return NULL;
0f71a2f6 3934}
c906108c 3935\f
c5aa993b 3936
f6ac5f3d
PA
3937bool
3938remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3939 struct static_tracepoint_marker *marker)
0fb4aa4b
PA
3940{
3941 struct remote_state *rs = get_remote_state ();
8d64371b 3942 char *p = rs->buf.data ();
0fb4aa4b 3943
bba74b36 3944 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3945 p += strlen (p);
3946 p += hexnumstr (p, addr);
3947 putpkt (rs->buf);
8d64371b
TT
3948 getpkt (&rs->buf, 0);
3949 p = rs->buf.data ();
0fb4aa4b
PA
3950
3951 if (*p == 'E')
3952 error (_("Remote failure reply: %s"), p);
3953
3954 if (*p++ == 'm')
3955 {
256642e8 3956 parse_static_tracepoint_marker_definition (p, NULL, marker);
5d9310c4 3957 return true;
0fb4aa4b
PA
3958 }
3959
5d9310c4 3960 return false;
0fb4aa4b
PA
3961}
3962
f6ac5f3d
PA
3963std::vector<static_tracepoint_marker>
3964remote_target::static_tracepoint_markers_by_strid (const char *strid)
0fb4aa4b
PA
3965{
3966 struct remote_state *rs = get_remote_state ();
5d9310c4 3967 std::vector<static_tracepoint_marker> markers;
256642e8 3968 const char *p;
5d9310c4 3969 static_tracepoint_marker marker;
0fb4aa4b
PA
3970
3971 /* Ask for a first packet of static tracepoint marker
3972 definition. */
3973 putpkt ("qTfSTM");
8d64371b
TT
3974 getpkt (&rs->buf, 0);
3975 p = rs->buf.data ();
0fb4aa4b
PA
3976 if (*p == 'E')
3977 error (_("Remote failure reply: %s"), p);
3978
0fb4aa4b
PA
3979 while (*p++ == 'm')
3980 {
0fb4aa4b
PA
3981 do
3982 {
5d9310c4 3983 parse_static_tracepoint_marker_definition (p, &p, &marker);
0fb4aa4b 3984
5d9310c4
SM
3985 if (strid == NULL || marker.str_id == strid)
3986 markers.push_back (std::move (marker));
0fb4aa4b
PA
3987 }
3988 while (*p++ == ','); /* comma-separated list */
3989 /* Ask for another packet of static tracepoint definition. */
3990 putpkt ("qTsSTM");
8d64371b
TT
3991 getpkt (&rs->buf, 0);
3992 p = rs->buf.data ();
0fb4aa4b
PA
3993 }
3994
0fb4aa4b
PA
3995 return markers;
3996}
3997
3998\f
10760264
JB
3999/* Implement the to_get_ada_task_ptid function for the remote targets. */
4000
f6ac5f3d
PA
4001ptid_t
4002remote_target::get_ada_task_ptid (long lwp, long thread)
10760264 4003{
e99b03dc 4004 return ptid_t (inferior_ptid.pid (), lwp, 0);
10760264
JB
4005}
4006\f
4007
24b06219 4008/* Restart the remote side; this is an extended protocol operation. */
c906108c 4009
6b8edb51
PA
4010void
4011remote_target::extended_remote_restart ()
c906108c 4012{
d01949b6 4013 struct remote_state *rs = get_remote_state ();
c906108c
SS
4014
4015 /* Send the restart command; for reasons I don't understand the
4016 remote side really expects a number after the "R". */
8d64371b 4017 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
6d820c5c 4018 putpkt (rs->buf);
c906108c 4019
ad9a8f3f 4020 remote_fileio_reset ();
c906108c
SS
4021}
4022\f
4023/* Clean up connection to a remote debugger. */
4024
f6ac5f3d
PA
4025void
4026remote_target::close ()
c906108c 4027{
048094ac 4028 /* Make sure we leave stdin registered in the event loop. */
f6ac5f3d 4029 terminal_ours ();
ce5ce7ed 4030
ce5ce7ed 4031 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
4032 of all the inferiors and their threads we were controlling.
4033 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
4034 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 4035 inferior_ptid = null_ptid;
f67fd822 4036 discard_all_inferiors ();
ce5ce7ed 4037
6b8edb51
PA
4038 trace_reset_local_state ();
4039
4040 delete this;
4041}
4042
4043remote_target::~remote_target ()
4044{
4045 struct remote_state *rs = get_remote_state ();
4046
4047 /* Check for NULL because we may get here with a partially
4048 constructed target/connection. */
4049 if (rs->remote_desc == nullptr)
4050 return;
4051
4052 serial_close (rs->remote_desc);
4053
4054 /* We are destroying the remote target, so we should discard
f48ff2a7 4055 everything of this target. */
6b8edb51 4056 discard_pending_stop_replies_in_queue ();
74531fed 4057
6b8edb51
PA
4058 if (rs->remote_async_inferior_event_token)
4059 delete_async_event_handler (&rs->remote_async_inferior_event_token);
722247f1 4060
5965e028 4061 remote_notif_state_xfree (rs->notif_state);
c906108c
SS
4062}
4063
23860348 4064/* Query the remote side for the text, data and bss offsets. */
c906108c 4065
6b8edb51
PA
4066void
4067remote_target::get_offsets ()
c906108c 4068{
d01949b6 4069 struct remote_state *rs = get_remote_state ();
2e9f7625 4070 char *buf;
085dd6e6 4071 char *ptr;
31d99776
DJ
4072 int lose, num_segments = 0, do_sections, do_segments;
4073 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 4074 struct section_offsets *offs;
31d99776
DJ
4075 struct symfile_segment_data *data;
4076
4077 if (symfile_objfile == NULL)
4078 return;
c906108c
SS
4079
4080 putpkt ("qOffsets");
8d64371b
TT
4081 getpkt (&rs->buf, 0);
4082 buf = rs->buf.data ();
c906108c
SS
4083
4084 if (buf[0] == '\000')
4085 return; /* Return silently. Stub doesn't support
23860348 4086 this command. */
c906108c
SS
4087 if (buf[0] == 'E')
4088 {
8a3fe4f8 4089 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
4090 return;
4091 }
4092
4093 /* Pick up each field in turn. This used to be done with scanf, but
4094 scanf will make trouble if CORE_ADDR size doesn't match
4095 conversion directives correctly. The following code will work
4096 with any size of CORE_ADDR. */
4097 text_addr = data_addr = bss_addr = 0;
4098 ptr = buf;
4099 lose = 0;
4100
61012eef 4101 if (startswith (ptr, "Text="))
c906108c
SS
4102 {
4103 ptr += 5;
4104 /* Don't use strtol, could lose on big values. */
4105 while (*ptr && *ptr != ';')
4106 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 4107
61012eef 4108 if (startswith (ptr, ";Data="))
31d99776
DJ
4109 {
4110 ptr += 6;
4111 while (*ptr && *ptr != ';')
4112 data_addr = (data_addr << 4) + fromhex (*ptr++);
4113 }
4114 else
4115 lose = 1;
4116
61012eef 4117 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
4118 {
4119 ptr += 5;
4120 while (*ptr && *ptr != ';')
4121 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 4122
31d99776
DJ
4123 if (bss_addr != data_addr)
4124 warning (_("Target reported unsupported offsets: %s"), buf);
4125 }
4126 else
4127 lose = 1;
4128 }
61012eef 4129 else if (startswith (ptr, "TextSeg="))
c906108c 4130 {
31d99776
DJ
4131 ptr += 8;
4132 /* Don't use strtol, could lose on big values. */
c906108c 4133 while (*ptr && *ptr != ';')
31d99776
DJ
4134 text_addr = (text_addr << 4) + fromhex (*ptr++);
4135 num_segments = 1;
4136
61012eef 4137 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
4138 {
4139 ptr += 9;
4140 while (*ptr && *ptr != ';')
4141 data_addr = (data_addr << 4) + fromhex (*ptr++);
4142 num_segments++;
4143 }
c906108c
SS
4144 }
4145 else
4146 lose = 1;
4147
4148 if (lose)
8a3fe4f8 4149 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
4150 else if (*ptr != '\0')
4151 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 4152
802188a7 4153 offs = ((struct section_offsets *)
a39a16c4 4154 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 4155 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 4156 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 4157
31d99776
DJ
4158 data = get_symfile_segment_data (symfile_objfile->obfd);
4159 do_segments = (data != NULL);
4160 do_sections = num_segments == 0;
c906108c 4161
28c32713 4162 if (num_segments > 0)
31d99776 4163 {
31d99776
DJ
4164 segments[0] = text_addr;
4165 segments[1] = data_addr;
4166 }
28c32713
JB
4167 /* If we have two segments, we can still try to relocate everything
4168 by assuming that the .text and .data offsets apply to the whole
4169 text and data segments. Convert the offsets given in the packet
4170 to base addresses for symfile_map_offsets_to_segments. */
4171 else if (data && data->num_segments == 2)
4172 {
4173 segments[0] = data->segment_bases[0] + text_addr;
4174 segments[1] = data->segment_bases[1] + data_addr;
4175 num_segments = 2;
4176 }
8d385431
DJ
4177 /* If the object file has only one segment, assume that it is text
4178 rather than data; main programs with no writable data are rare,
4179 but programs with no code are useless. Of course the code might
4180 have ended up in the data segment... to detect that we would need
4181 the permissions here. */
4182 else if (data && data->num_segments == 1)
4183 {
4184 segments[0] = data->segment_bases[0] + text_addr;
4185 num_segments = 1;
4186 }
28c32713
JB
4187 /* There's no way to relocate by segment. */
4188 else
4189 do_segments = 0;
31d99776
DJ
4190
4191 if (do_segments)
4192 {
4193 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
4194 offs, num_segments, segments);
4195
4196 if (ret == 0 && !do_sections)
3e43a32a
MS
4197 error (_("Can not handle qOffsets TextSeg "
4198 "response with this symbol file"));
31d99776
DJ
4199
4200 if (ret > 0)
4201 do_sections = 0;
4202 }
c906108c 4203
9ef895d6
DJ
4204 if (data)
4205 free_symfile_segment_data (data);
31d99776
DJ
4206
4207 if (do_sections)
4208 {
4209 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
4210
3e43a32a
MS
4211 /* This is a temporary kludge to force data and bss to use the
4212 same offsets because that's what nlmconv does now. The real
4213 solution requires changes to the stub and remote.c that I
4214 don't have time to do right now. */
31d99776
DJ
4215
4216 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
4217 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
4218 }
c906108c
SS
4219
4220 objfile_relocate (symfile_objfile, offs);
4221}
4222
9a7071a8 4223/* Send interrupt_sequence to remote target. */
6b8edb51
PA
4224
4225void
4226remote_target::send_interrupt_sequence ()
9a7071a8 4227{
5d93a237
TT
4228 struct remote_state *rs = get_remote_state ();
4229
9a7071a8 4230 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 4231 remote_serial_write ("\x03", 1);
9a7071a8 4232 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 4233 serial_send_break (rs->remote_desc);
9a7071a8
JB
4234 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4235 {
5d93a237 4236 serial_send_break (rs->remote_desc);
c33e31fd 4237 remote_serial_write ("g", 1);
9a7071a8
JB
4238 }
4239 else
4240 internal_error (__FILE__, __LINE__,
4241 _("Invalid value for interrupt_sequence_mode: %s."),
4242 interrupt_sequence_mode);
4243}
4244
3405876a
PA
4245
4246/* If STOP_REPLY is a T stop reply, look for the "thread" register,
4247 and extract the PTID. Returns NULL_PTID if not found. */
4248
4249static ptid_t
4250stop_reply_extract_thread (char *stop_reply)
4251{
4252 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4253 {
256642e8 4254 const char *p;
3405876a
PA
4255
4256 /* Txx r:val ; r:val (...) */
4257 p = &stop_reply[3];
4258
4259 /* Look for "register" named "thread". */
4260 while (*p != '\0')
4261 {
256642e8 4262 const char *p1;
3405876a
PA
4263
4264 p1 = strchr (p, ':');
4265 if (p1 == NULL)
4266 return null_ptid;
4267
4268 if (strncmp (p, "thread", p1 - p) == 0)
4269 return read_ptid (++p1, &p);
4270
4271 p1 = strchr (p, ';');
4272 if (p1 == NULL)
4273 return null_ptid;
4274 p1++;
4275
4276 p = p1;
4277 }
4278 }
4279
4280 return null_ptid;
4281}
4282
b7ea362b
PA
4283/* Determine the remote side's current thread. If we have a stop
4284 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4285 "thread" register we can extract the current thread from. If not,
4286 ask the remote which is the current thread with qC. The former
4287 method avoids a roundtrip. */
4288
6b8edb51
PA
4289ptid_t
4290remote_target::get_current_thread (char *wait_status)
b7ea362b 4291{
6a49a997 4292 ptid_t ptid = null_ptid;
b7ea362b
PA
4293
4294 /* Note we don't use remote_parse_stop_reply as that makes use of
4295 the target architecture, which we haven't yet fully determined at
4296 this point. */
4297 if (wait_status != NULL)
4298 ptid = stop_reply_extract_thread (wait_status);
d7e15655 4299 if (ptid == null_ptid)
b7ea362b
PA
4300 ptid = remote_current_thread (inferior_ptid);
4301
4302 return ptid;
4303}
4304
49c62f2e
PA
4305/* Query the remote target for which is the current thread/process,
4306 add it to our tables, and update INFERIOR_PTID. The caller is
4307 responsible for setting the state such that the remote end is ready
3405876a
PA
4308 to return the current thread.
4309
4310 This function is called after handling the '?' or 'vRun' packets,
4311 whose response is a stop reply from which we can also try
4312 extracting the thread. If the target doesn't support the explicit
4313 qC query, we infer the current thread from that stop reply, passed
4314 in in WAIT_STATUS, which may be NULL. */
49c62f2e 4315
6b8edb51
PA
4316void
4317remote_target::add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
4318{
4319 struct remote_state *rs = get_remote_state ();
4320 int fake_pid_p = 0;
49c62f2e
PA
4321
4322 inferior_ptid = null_ptid;
4323
b7ea362b 4324 /* Now, if we have thread information, update inferior_ptid. */
87215ad1 4325 ptid_t curr_ptid = get_current_thread (wait_status);
3405876a 4326
87215ad1 4327 if (curr_ptid != null_ptid)
49c62f2e
PA
4328 {
4329 if (!remote_multi_process_p (rs))
4330 fake_pid_p = 1;
49c62f2e
PA
4331 }
4332 else
4333 {
4334 /* Without this, some commands which require an active target
4335 (such as kill) won't work. This variable serves (at least)
4336 double duty as both the pid of the target process (if it has
4337 such), and as a flag indicating that a target is active. */
87215ad1 4338 curr_ptid = magic_null_ptid;
49c62f2e
PA
4339 fake_pid_p = 1;
4340 }
4341
e99b03dc 4342 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
49c62f2e 4343
87215ad1
SDJ
4344 /* Add the main thread and switch to it. Don't try reading
4345 registers yet, since we haven't fetched the target description
4346 yet. */
4347 thread_info *tp = add_thread_silent (curr_ptid);
4348 switch_to_thread_no_regs (tp);
49c62f2e
PA
4349}
4350
6efcd9a8
PA
4351/* Print info about a thread that was found already stopped on
4352 connection. */
4353
4354static void
4355print_one_stopped_thread (struct thread_info *thread)
4356{
4357 struct target_waitstatus *ws = &thread->suspend.waitstatus;
4358
00431a78 4359 switch_to_thread (thread);
f2ffa92b 4360 thread->suspend.stop_pc = get_frame_pc (get_current_frame ());
6efcd9a8
PA
4361 set_current_sal_from_frame (get_current_frame ());
4362
4363 thread->suspend.waitstatus_pending_p = 0;
4364
4365 if (ws->kind == TARGET_WAITKIND_STOPPED)
4366 {
4367 enum gdb_signal sig = ws->value.sig;
4368
4369 if (signal_print_state (sig))
76727919 4370 gdb::observers::signal_received.notify (sig);
6efcd9a8 4371 }
76727919 4372 gdb::observers::normal_stop.notify (NULL, 1);
6efcd9a8
PA
4373}
4374
221e1a37
PA
4375/* Process all initial stop replies the remote side sent in response
4376 to the ? packet. These indicate threads that were already stopped
4377 on initial connection. We mark these threads as stopped and print
4378 their current frame before giving the user the prompt. */
4379
6b8edb51
PA
4380void
4381remote_target::process_initial_stop_replies (int from_tty)
221e1a37
PA
4382{
4383 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
4384 struct thread_info *selected = NULL;
4385 struct thread_info *lowest_stopped = NULL;
4386 struct thread_info *first = NULL;
221e1a37
PA
4387
4388 /* Consume the initial pending events. */
4389 while (pending_stop_replies-- > 0)
4390 {
4391 ptid_t waiton_ptid = minus_one_ptid;
4392 ptid_t event_ptid;
4393 struct target_waitstatus ws;
4394 int ignore_event = 0;
4395
4396 memset (&ws, 0, sizeof (ws));
4397 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4398 if (remote_debug)
4399 print_target_wait_results (waiton_ptid, event_ptid, &ws);
4400
4401 switch (ws.kind)
4402 {
4403 case TARGET_WAITKIND_IGNORE:
4404 case TARGET_WAITKIND_NO_RESUMED:
4405 case TARGET_WAITKIND_SIGNALLED:
4406 case TARGET_WAITKIND_EXITED:
4407 /* We shouldn't see these, but if we do, just ignore. */
4408 if (remote_debug)
4409 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4410 ignore_event = 1;
4411 break;
4412
4413 case TARGET_WAITKIND_EXECD:
4414 xfree (ws.value.execd_pathname);
4415 break;
4416 default:
4417 break;
4418 }
4419
4420 if (ignore_event)
4421 continue;
4422
b926417a 4423 struct thread_info *evthread = find_thread_ptid (event_ptid);
221e1a37
PA
4424
4425 if (ws.kind == TARGET_WAITKIND_STOPPED)
4426 {
4427 enum gdb_signal sig = ws.value.sig;
4428
4429 /* Stubs traditionally report SIGTRAP as initial signal,
4430 instead of signal 0. Suppress it. */
4431 if (sig == GDB_SIGNAL_TRAP)
4432 sig = GDB_SIGNAL_0;
b926417a 4433 evthread->suspend.stop_signal = sig;
6efcd9a8
PA
4434 ws.value.sig = sig;
4435 }
221e1a37 4436
b926417a 4437 evthread->suspend.waitstatus = ws;
6efcd9a8
PA
4438
4439 if (ws.kind != TARGET_WAITKIND_STOPPED
4440 || ws.value.sig != GDB_SIGNAL_0)
b926417a 4441 evthread->suspend.waitstatus_pending_p = 1;
6efcd9a8
PA
4442
4443 set_executing (event_ptid, 0);
4444 set_running (event_ptid, 0);
b926417a 4445 get_remote_thread_info (evthread)->vcont_resumed = 0;
6efcd9a8
PA
4446 }
4447
4448 /* "Notice" the new inferiors before anything related to
4449 registers/memory. */
08036331 4450 for (inferior *inf : all_non_exited_inferiors ())
6efcd9a8 4451 {
6efcd9a8
PA
4452 inf->needs_setup = 1;
4453
4454 if (non_stop)
4455 {
08036331 4456 thread_info *thread = any_live_thread_of_inferior (inf);
00431a78 4457 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
6efcd9a8
PA
4458 from_tty);
4459 }
4460 }
4461
4462 /* If all-stop on top of non-stop, pause all threads. Note this
4463 records the threads' stop pc, so must be done after "noticing"
4464 the inferiors. */
4465 if (!non_stop)
4466 {
4467 stop_all_threads ();
4468
4469 /* If all threads of an inferior were already stopped, we
4470 haven't setup the inferior yet. */
08036331 4471 for (inferior *inf : all_non_exited_inferiors ())
6efcd9a8 4472 {
6efcd9a8
PA
4473 if (inf->needs_setup)
4474 {
08036331 4475 thread_info *thread = any_live_thread_of_inferior (inf);
6efcd9a8
PA
4476 switch_to_thread_no_regs (thread);
4477 setup_inferior (0);
4478 }
4479 }
221e1a37 4480 }
6efcd9a8
PA
4481
4482 /* Now go over all threads that are stopped, and print their current
4483 frame. If all-stop, then if there's a signalled thread, pick
4484 that as current. */
08036331 4485 for (thread_info *thread : all_non_exited_threads ())
6efcd9a8 4486 {
6efcd9a8
PA
4487 if (first == NULL)
4488 first = thread;
4489
4490 if (!non_stop)
00431a78 4491 thread->set_running (false);
6efcd9a8
PA
4492 else if (thread->state != THREAD_STOPPED)
4493 continue;
4494
6efcd9a8
PA
4495 if (selected == NULL
4496 && thread->suspend.waitstatus_pending_p)
4497 selected = thread;
4498
5d5658a1
PA
4499 if (lowest_stopped == NULL
4500 || thread->inf->num < lowest_stopped->inf->num
4501 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
4502 lowest_stopped = thread;
4503
4504 if (non_stop)
4505 print_one_stopped_thread (thread);
4506 }
4507
4508 /* In all-stop, we only print the status of one thread, and leave
4509 others with their status pending. */
4510 if (!non_stop)
4511 {
08036331 4512 thread_info *thread = selected;
6efcd9a8
PA
4513 if (thread == NULL)
4514 thread = lowest_stopped;
4515 if (thread == NULL)
4516 thread = first;
4517
4518 print_one_stopped_thread (thread);
4519 }
4520
4521 /* For "info program". */
08036331 4522 thread_info *thread = inferior_thread ();
6efcd9a8
PA
4523 if (thread->state == THREAD_STOPPED)
4524 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
4525}
4526
048094ac
PA
4527/* Start the remote connection and sync state. */
4528
f6ac5f3d
PA
4529void
4530remote_target::start_remote (int from_tty, int extended_p)
c906108c 4531{
c8d104ad
PA
4532 struct remote_state *rs = get_remote_state ();
4533 struct packet_config *noack_config;
2d717e4f 4534 char *wait_status = NULL;
8621d6a9 4535
048094ac
PA
4536 /* Signal other parts that we're going through the initial setup,
4537 and so things may not be stable yet. E.g., we don't try to
4538 install tracepoints until we've relocated symbols. Also, a
4539 Ctrl-C before we're connected and synced up can't interrupt the
4540 target. Instead, it offers to drop the (potentially wedged)
4541 connection. */
4542 rs->starting_up = 1;
4543
522002f9 4544 QUIT;
c906108c 4545
9a7071a8
JB
4546 if (interrupt_on_connect)
4547 send_interrupt_sequence ();
4548
57e12211 4549 /* Ack any packet which the remote side has already sent. */
048094ac 4550 remote_serial_write ("+", 1);
1e51243a 4551
c8d104ad
PA
4552 /* The first packet we send to the target is the optional "supported
4553 packets" request. If the target can answer this, it will tell us
4554 which later probes to skip. */
4555 remote_query_supported ();
4556
d914c394 4557 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 4558 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
f6ac5f3d 4559 set_permissions ();
d914c394 4560
57809e5e
JK
4561 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4562 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4563 as a reply to known packet. For packet "vFile:setfs:" it is an
4564 invalid reply and GDB would return error in
4565 remote_hostio_set_filesystem, making remote files access impossible.
4566 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4567 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4568 {
4569 const char v_mustreplyempty[] = "vMustReplyEmpty";
4570
4571 putpkt (v_mustreplyempty);
8d64371b
TT
4572 getpkt (&rs->buf, 0);
4573 if (strcmp (rs->buf.data (), "OK") == 0)
57809e5e 4574 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
8d64371b 4575 else if (strcmp (rs->buf.data (), "") != 0)
57809e5e 4576 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
8d64371b 4577 rs->buf.data ());
57809e5e
JK
4578 }
4579
c8d104ad
PA
4580 /* Next, we possibly activate noack mode.
4581
4582 If the QStartNoAckMode packet configuration is set to AUTO,
4583 enable noack mode if the stub reported a wish for it with
4584 qSupported.
4585
4586 If set to TRUE, then enable noack mode even if the stub didn't
4587 report it in qSupported. If the stub doesn't reply OK, the
4588 session ends with an error.
4589
4590 If FALSE, then don't activate noack mode, regardless of what the
4591 stub claimed should be the default with qSupported. */
4592
4593 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 4594 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
4595 {
4596 putpkt ("QStartNoAckMode");
8d64371b 4597 getpkt (&rs->buf, 0);
c8d104ad
PA
4598 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4599 rs->noack_mode = 1;
4600 }
4601
04bd08de 4602 if (extended_p)
5fe04517
PA
4603 {
4604 /* Tell the remote that we are using the extended protocol. */
4605 putpkt ("!");
8d64371b 4606 getpkt (&rs->buf, 0);
5fe04517
PA
4607 }
4608
9b224c5e
PA
4609 /* Let the target know which signals it is allowed to pass down to
4610 the program. */
4611 update_signals_program_target ();
4612
d962ef82
DJ
4613 /* Next, if the target can specify a description, read it. We do
4614 this before anything involving memory or registers. */
4615 target_find_description ();
4616
6c95b8df
PA
4617 /* Next, now that we know something about the target, update the
4618 address spaces in the program spaces. */
4619 update_address_spaces ();
4620
50c71eaf
PA
4621 /* On OSs where the list of libraries is global to all
4622 processes, we fetch them early. */
f5656ead 4623 if (gdbarch_has_global_solist (target_gdbarch ()))
e696b3ad 4624 solib_add (NULL, from_tty, auto_solib_add);
50c71eaf 4625
6efcd9a8 4626 if (target_is_non_stop_p ())
74531fed 4627 {
4082afcc 4628 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
4629 error (_("Non-stop mode requested, but remote "
4630 "does not support non-stop"));
74531fed
PA
4631
4632 putpkt ("QNonStop:1");
8d64371b 4633 getpkt (&rs->buf, 0);
74531fed 4634
8d64371b
TT
4635 if (strcmp (rs->buf.data (), "OK") != 0)
4636 error (_("Remote refused setting non-stop mode with: %s"),
4637 rs->buf.data ());
74531fed
PA
4638
4639 /* Find about threads and processes the stub is already
4640 controlling. We default to adding them in the running state.
4641 The '?' query below will then tell us about which threads are
4642 stopped. */
f6ac5f3d 4643 this->update_thread_list ();
74531fed 4644 }
4082afcc 4645 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4646 {
4647 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4648 Request it explicitly. */
74531fed 4649 putpkt ("QNonStop:0");
8d64371b 4650 getpkt (&rs->buf, 0);
74531fed 4651
8d64371b
TT
4652 if (strcmp (rs->buf.data (), "OK") != 0)
4653 error (_("Remote refused setting all-stop mode with: %s"),
4654 rs->buf.data ());
74531fed
PA
4655 }
4656
a0743c90
YQ
4657 /* Upload TSVs regardless of whether the target is running or not. The
4658 remote stub, such as GDBserver, may have some predefined or builtin
4659 TSVs, even if the target is not running. */
f6ac5f3d 4660 if (get_trace_status (current_trace_status ()) != -1)
a0743c90
YQ
4661 {
4662 struct uploaded_tsv *uploaded_tsvs = NULL;
4663
f6ac5f3d 4664 upload_trace_state_variables (&uploaded_tsvs);
a0743c90
YQ
4665 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4666 }
4667
2d717e4f
DJ
4668 /* Check whether the target is running now. */
4669 putpkt ("?");
8d64371b 4670 getpkt (&rs->buf, 0);
2d717e4f 4671
6efcd9a8 4672 if (!target_is_non_stop_p ())
2d717e4f 4673 {
74531fed 4674 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4675 {
04bd08de 4676 if (!extended_p)
74531fed 4677 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4678
4679 /* We're connected, but not running. Drop out before we
4680 call start_remote. */
e278ad5b 4681 rs->starting_up = 0;
c35b1492 4682 return;
2d717e4f
DJ
4683 }
4684 else
74531fed 4685 {
74531fed 4686 /* Save the reply for later. */
8d64371b
TT
4687 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
4688 strcpy (wait_status, rs->buf.data ());
74531fed
PA
4689 }
4690
b7ea362b 4691 /* Fetch thread list. */
e8032dde 4692 target_update_thread_list ();
b7ea362b 4693
74531fed
PA
4694 /* Let the stub know that we want it to return the thread. */
4695 set_continue_thread (minus_one_ptid);
4696
b7ea362b
PA
4697 if (thread_count () == 0)
4698 {
4699 /* Target has no concept of threads at all. GDB treats
4700 non-threaded target as single-threaded; add a main
4701 thread. */
4702 add_current_inferior_and_thread (wait_status);
4703 }
4704 else
4705 {
4706 /* We have thread information; select the thread the target
4707 says should be current. If we're reconnecting to a
4708 multi-threaded program, this will ideally be the thread
4709 that last reported an event before GDB disconnected. */
4710 inferior_ptid = get_current_thread (wait_status);
d7e15655 4711 if (inferior_ptid == null_ptid)
b7ea362b
PA
4712 {
4713 /* Odd... The target was able to list threads, but not
4714 tell us which thread was current (no "thread"
4715 register in T stop reply?). Just pick the first
4716 thread in the thread list then. */
c9f35b34
KB
4717
4718 if (remote_debug)
4719 fprintf_unfiltered (gdb_stdlog,
4720 "warning: couldn't determine remote "
4721 "current thread; picking first in list.\n");
4722
08036331 4723 inferior_ptid = inferior_list->thread_list->ptid;
b7ea362b
PA
4724 }
4725 }
74531fed 4726
6e586cc5
YQ
4727 /* init_wait_for_inferior should be called before get_offsets in order
4728 to manage `inserted' flag in bp loc in a correct state.
4729 breakpoint_init_inferior, called from init_wait_for_inferior, set
4730 `inserted' flag to 0, while before breakpoint_re_set, called from
4731 start_remote, set `inserted' flag to 1. In the initialization of
4732 inferior, breakpoint_init_inferior should be called first, and then
4733 breakpoint_re_set can be called. If this order is broken, state of
4734 `inserted' flag is wrong, and cause some problems on breakpoint
4735 manipulation. */
4736 init_wait_for_inferior ();
4737
74531fed
PA
4738 get_offsets (); /* Get text, data & bss offsets. */
4739
d962ef82
DJ
4740 /* If we could not find a description using qXfer, and we know
4741 how to do it some other way, try again. This is not
4742 supported for non-stop; it could be, but it is tricky if
4743 there are no stopped threads when we connect. */
f6ac5f3d 4744 if (remote_read_description_p (this)
f5656ead 4745 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4746 {
4747 target_clear_description ();
4748 target_find_description ();
4749 }
4750
74531fed
PA
4751 /* Use the previously fetched status. */
4752 gdb_assert (wait_status != NULL);
8d64371b 4753 strcpy (rs->buf.data (), wait_status);
74531fed
PA
4754 rs->cached_wait_status = 1;
4755
f6ac5f3d 4756 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4757 }
4758 else
4759 {
68c97600
PA
4760 /* Clear WFI global state. Do this before finding about new
4761 threads and inferiors, and setting the current inferior.
4762 Otherwise we would clear the proceed status of the current
4763 inferior when we want its stop_soon state to be preserved
4764 (see notice_new_inferior). */
4765 init_wait_for_inferior ();
4766
74531fed
PA
4767 /* In non-stop, we will either get an "OK", meaning that there
4768 are no stopped threads at this time; or, a regular stop
4769 reply. In the latter case, there may be more than one thread
4770 stopped --- we pull them all out using the vStopped
4771 mechanism. */
8d64371b 4772 if (strcmp (rs->buf.data (), "OK") != 0)
74531fed 4773 {
722247f1 4774 struct notif_client *notif = &notif_client_stop;
2d717e4f 4775
722247f1
YQ
4776 /* remote_notif_get_pending_replies acks this one, and gets
4777 the rest out. */
f48ff2a7 4778 rs->notif_state->pending_event[notif_client_stop.id]
8d64371b 4779 = remote_notif_parse (this, notif, rs->buf.data ());
722247f1 4780 remote_notif_get_pending_events (notif);
74531fed 4781 }
2d717e4f 4782
74531fed
PA
4783 if (thread_count () == 0)
4784 {
04bd08de 4785 if (!extended_p)
74531fed 4786 error (_("The target is not running (try extended-remote?)"));
82f73884 4787
c35b1492
PA
4788 /* We're connected, but not running. Drop out before we
4789 call start_remote. */
e278ad5b 4790 rs->starting_up = 0;
c35b1492
PA
4791 return;
4792 }
74531fed 4793
74531fed
PA
4794 /* In non-stop mode, any cached wait status will be stored in
4795 the stop reply queue. */
4796 gdb_assert (wait_status == NULL);
f0223081 4797
2455069d 4798 /* Report all signals during attach/startup. */
adc6a863 4799 pass_signals ({});
221e1a37
PA
4800
4801 /* If there are already stopped threads, mark them stopped and
4802 report their stops before giving the prompt to the user. */
6efcd9a8 4803 process_initial_stop_replies (from_tty);
221e1a37
PA
4804
4805 if (target_can_async_p ())
4806 target_async (1);
74531fed 4807 }
c8d104ad 4808
c8d104ad
PA
4809 /* If we connected to a live target, do some additional setup. */
4810 if (target_has_execution)
4811 {
f4ccffad 4812 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4813 remote_check_symbols ();
c8d104ad 4814 }
50c71eaf 4815
d5551862
SS
4816 /* Possibly the target has been engaged in a trace run started
4817 previously; find out where things are at. */
f6ac5f3d 4818 if (get_trace_status (current_trace_status ()) != -1)
d5551862 4819 {
00bf0b85 4820 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4821
00bf0b85
SS
4822 if (current_trace_status ()->running)
4823 printf_filtered (_("Trace is already running on the target.\n"));
4824
f6ac5f3d 4825 upload_tracepoints (&uploaded_tps);
00bf0b85
SS
4826
4827 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4828 }
4829
c0272db5
TW
4830 /* Possibly the target has been engaged in a btrace record started
4831 previously; find out where things are at. */
4832 remote_btrace_maybe_reopen ();
4833
1e51243a
PA
4834 /* The thread and inferior lists are now synchronized with the
4835 target, our symbols have been relocated, and we're merged the
4836 target's tracepoints with ours. We're done with basic start
4837 up. */
4838 rs->starting_up = 0;
4839
a25a5a45
PA
4840 /* Maybe breakpoints are global and need to be inserted now. */
4841 if (breakpoints_should_be_inserted_now ())
50c71eaf 4842 insert_breakpoints ();
c906108c
SS
4843}
4844
4845/* Open a connection to a remote debugger.
4846 NAME is the filename used for communication. */
4847
f6ac5f3d
PA
4848void
4849remote_target::open (const char *name, int from_tty)
c906108c 4850{
f6ac5f3d 4851 open_1 (name, from_tty, 0);
43ff13b4
JM
4852}
4853
c906108c
SS
4854/* Open a connection to a remote debugger using the extended
4855 remote gdb protocol. NAME is the filename used for communication. */
4856
f6ac5f3d
PA
4857void
4858extended_remote_target::open (const char *name, int from_tty)
c906108c 4859{
f6ac5f3d 4860 open_1 (name, from_tty, 1 /*extended_p */);
43ff13b4
JM
4861}
4862
ca4f7f8b
PA
4863/* Reset all packets back to "unknown support". Called when opening a
4864 new connection to a remote target. */
c906108c 4865
d471ea57 4866static void
ca4f7f8b 4867reset_all_packet_configs_support (void)
d471ea57
AC
4868{
4869 int i;
a744cf53 4870
444abaca 4871 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4872 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4873}
4874
ca4f7f8b
PA
4875/* Initialize all packet configs. */
4876
4877static void
4878init_all_packet_configs (void)
4879{
4880 int i;
4881
4882 for (i = 0; i < PACKET_MAX; i++)
4883 {
4884 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4885 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4886 }
4887}
4888
23860348 4889/* Symbol look-up. */
dc8acb97 4890
6b8edb51
PA
4891void
4892remote_target::remote_check_symbols ()
dc8acb97 4893{
8d64371b 4894 char *tmp;
dc8acb97
MS
4895 int end;
4896
63154eca
PA
4897 /* The remote side has no concept of inferiors that aren't running
4898 yet, it only knows about running processes. If we're connected
4899 but our current inferior is not running, we should not invite the
4900 remote target to request symbol lookups related to its
4901 (unrelated) current process. */
4902 if (!target_has_execution)
4903 return;
4904
4082afcc 4905 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4906 return;
4907
63154eca
PA
4908 /* Make sure the remote is pointing at the right process. Note
4909 there's no way to select "no process". */
3c9c4b83
PA
4910 set_general_process ();
4911
6d820c5c
DJ
4912 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4913 because we need both at the same time. */
66644cd3 4914 gdb::char_vector msg (get_remote_packet_size ());
8d64371b 4915 gdb::char_vector reply (get_remote_packet_size ());
6d820c5c 4916
23860348 4917 /* Invite target to request symbol lookups. */
dc8acb97
MS
4918
4919 putpkt ("qSymbol::");
8d64371b 4920 getpkt (&reply, 0);
28170b88 4921 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
dc8acb97 4922
8d64371b 4923 while (startswith (reply.data (), "qSymbol:"))
dc8acb97 4924 {
77e371c0
TT
4925 struct bound_minimal_symbol sym;
4926
dc8acb97 4927 tmp = &reply[8];
66644cd3
AB
4928 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
4929 strlen (tmp) / 2);
dc8acb97 4930 msg[end] = '\0';
66644cd3 4931 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
3b7344d5 4932 if (sym.minsym == NULL)
66644cd3
AB
4933 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
4934 &reply[8]);
dc8acb97 4935 else
2bbe3cc1 4936 {
f5656ead 4937 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4938 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4939
4940 /* If this is a function address, return the start of code
4941 instead of any data function descriptor. */
f5656ead 4942 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1 4943 sym_addr,
8b88a78e 4944 current_top_target ());
2bbe3cc1 4945
66644cd3 4946 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4947 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1 4948 }
66644cd3
AB
4949
4950 putpkt (msg.data ());
8d64371b 4951 getpkt (&reply, 0);
dc8acb97
MS
4952 }
4953}
4954
9db8d71f 4955static struct serial *
baa336ce 4956remote_serial_open (const char *name)
9db8d71f
DJ
4957{
4958 static int udp_warning = 0;
4959
4960 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4961 of in ser-tcp.c, because it is the remote protocol assuming that the
4962 serial connection is reliable and not the serial connection promising
4963 to be. */
61012eef 4964 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4965 {
3e43a32a
MS
4966 warning (_("The remote protocol may be unreliable over UDP.\n"
4967 "Some events may be lost, rendering further debugging "
4968 "impossible."));
9db8d71f
DJ
4969 udp_warning = 1;
4970 }
4971
4972 return serial_open (name);
4973}
4974
d914c394
SS
4975/* Inform the target of our permission settings. The permission flags
4976 work without this, but if the target knows the settings, it can do
4977 a couple things. First, it can add its own check, to catch cases
4978 that somehow manage to get by the permissions checks in target
4979 methods. Second, if the target is wired to disallow particular
4980 settings (for instance, a system in the field that is not set up to
4981 be able to stop at a breakpoint), it can object to any unavailable
4982 permissions. */
4983
4984void
f6ac5f3d 4985remote_target::set_permissions ()
d914c394
SS
4986{
4987 struct remote_state *rs = get_remote_state ();
4988
8d64371b 4989 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
bba74b36
YQ
4990 "WriteReg:%x;WriteMem:%x;"
4991 "InsertBreak:%x;InsertTrace:%x;"
4992 "InsertFastTrace:%x;Stop:%x",
4993 may_write_registers, may_write_memory,
4994 may_insert_breakpoints, may_insert_tracepoints,
4995 may_insert_fast_tracepoints, may_stop);
d914c394 4996 putpkt (rs->buf);
8d64371b 4997 getpkt (&rs->buf, 0);
d914c394
SS
4998
4999 /* If the target didn't like the packet, warn the user. Do not try
5000 to undo the user's settings, that would just be maddening. */
8d64371b
TT
5001 if (strcmp (rs->buf.data (), "OK") != 0)
5002 warning (_("Remote refused setting permissions with: %s"),
5003 rs->buf.data ());
d914c394
SS
5004}
5005
be2a5f71
DJ
5006/* This type describes each known response to the qSupported
5007 packet. */
5008struct protocol_feature
5009{
5010 /* The name of this protocol feature. */
5011 const char *name;
5012
5013 /* The default for this protocol feature. */
5014 enum packet_support default_support;
5015
5016 /* The function to call when this feature is reported, or after
5017 qSupported processing if the feature is not supported.
5018 The first argument points to this structure. The second
5019 argument indicates whether the packet requested support be
5020 enabled, disabled, or probed (or the default, if this function
5021 is being called at the end of processing and this feature was
5022 not reported). The third argument may be NULL; if not NULL, it
5023 is a NUL-terminated string taken from the packet following
5024 this feature's name and an equals sign. */
6b8edb51
PA
5025 void (*func) (remote_target *remote, const struct protocol_feature *,
5026 enum packet_support, const char *);
be2a5f71
DJ
5027
5028 /* The corresponding packet for this feature. Only used if
5029 FUNC is remote_supported_packet. */
5030 int packet;
5031};
5032
be2a5f71 5033static void
6b8edb51
PA
5034remote_supported_packet (remote_target *remote,
5035 const struct protocol_feature *feature,
be2a5f71
DJ
5036 enum packet_support support,
5037 const char *argument)
5038{
5039 if (argument)
5040 {
5041 warning (_("Remote qSupported response supplied an unexpected value for"
5042 " \"%s\"."), feature->name);
5043 return;
5044 }
5045
4082afcc 5046 remote_protocol_packets[feature->packet].support = support;
be2a5f71 5047}
be2a5f71 5048
6b8edb51
PA
5049void
5050remote_target::remote_packet_size (const protocol_feature *feature,
5051 enum packet_support support, const char *value)
be2a5f71
DJ
5052{
5053 struct remote_state *rs = get_remote_state ();
5054
5055 int packet_size;
5056 char *value_end;
5057
5058 if (support != PACKET_ENABLE)
5059 return;
5060
5061 if (value == NULL || *value == '\0')
5062 {
5063 warning (_("Remote target reported \"%s\" without a size."),
5064 feature->name);
5065 return;
5066 }
5067
5068 errno = 0;
5069 packet_size = strtol (value, &value_end, 16);
5070 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5071 {
5072 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5073 feature->name, value);
5074 return;
5075 }
5076
be2a5f71
DJ
5077 /* Record the new maximum packet size. */
5078 rs->explicit_packet_size = packet_size;
5079}
5080
6b8edb51
PA
5081void
5082remote_packet_size (remote_target *remote, const protocol_feature *feature,
5083 enum packet_support support, const char *value)
5084{
5085 remote->remote_packet_size (feature, support, value);
5086}
5087
dc473cfb 5088static const struct protocol_feature remote_protocol_features[] = {
0876f84a 5089 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 5090 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 5091 PACKET_qXfer_auxv },
c78fa86a
GB
5092 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5093 PACKET_qXfer_exec_file },
23181151
DJ
5094 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5095 PACKET_qXfer_features },
cfa9d6d9
DJ
5096 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5097 PACKET_qXfer_libraries },
2268b414
JK
5098 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5099 PACKET_qXfer_libraries_svr4 },
ced63ec0 5100 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 5101 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 5102 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 5103 PACKET_qXfer_memory_map },
4de6483e
UW
5104 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
5105 PACKET_qXfer_spu_read },
5106 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
5107 PACKET_qXfer_spu_write },
07e059b5
VP
5108 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5109 PACKET_qXfer_osdata },
dc146f7c
VP
5110 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5111 PACKET_qXfer_threads },
b3b9301e
PA
5112 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5113 PACKET_qXfer_traceframe_info },
89be2091
DJ
5114 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5115 PACKET_QPassSignals },
82075af2
JS
5116 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5117 PACKET_QCatchSyscalls },
9b224c5e
PA
5118 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5119 PACKET_QProgramSignals },
bc3b087d
SDJ
5120 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5121 PACKET_QSetWorkingDir },
aefd8b33
SDJ
5122 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5123 PACKET_QStartupWithShell },
0a2dde4a
SDJ
5124 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5125 PACKET_QEnvironmentHexEncoded },
5126 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5127 PACKET_QEnvironmentReset },
5128 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5129 PACKET_QEnvironmentUnset },
a6f3e723
SL
5130 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5131 PACKET_QStartNoAckMode },
4082afcc
PA
5132 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5133 PACKET_multiprocess_feature },
5134 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
5135 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5136 PACKET_qXfer_siginfo_read },
5137 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5138 PACKET_qXfer_siginfo_write },
4082afcc 5139 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 5140 PACKET_ConditionalTracepoints },
4082afcc 5141 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 5142 PACKET_ConditionalBreakpoints },
4082afcc 5143 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 5144 PACKET_BreakpointCommands },
4082afcc 5145 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 5146 PACKET_FastTracepoints },
4082afcc 5147 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 5148 PACKET_StaticTracepoints },
4082afcc 5149 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 5150 PACKET_InstallInTrace},
4082afcc
PA
5151 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5152 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
5153 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5154 PACKET_bc },
5155 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5156 PACKET_bs },
409873ef
SS
5157 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5158 PACKET_TracepointSource },
d914c394
SS
5159 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5160 PACKET_QAllow },
4082afcc
PA
5161 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5162 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
5163 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5164 PACKET_qXfer_fdpic },
169081d0
TG
5165 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5166 PACKET_qXfer_uib },
03583c20
UW
5167 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5168 PACKET_QDisableRandomization },
d1feda86 5169 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
5170 { "QTBuffer:size", PACKET_DISABLE,
5171 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 5172 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
5173 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5174 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 5175 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 5176 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
5177 PACKET_qXfer_btrace },
5178 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
5179 PACKET_qXfer_btrace_conf },
5180 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
5181 PACKET_Qbtrace_conf_bts_size },
5182 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 5183 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
5184 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5185 PACKET_fork_event_feature },
5186 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5187 PACKET_vfork_event_feature },
94585166
DB
5188 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5189 PACKET_exec_event_feature },
b20a6524 5190 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 5191 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
5192 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5193 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 5194 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
be2a5f71
DJ
5195};
5196
c8d5aac9
L
5197static char *remote_support_xml;
5198
5199/* Register string appended to "xmlRegisters=" in qSupported query. */
5200
5201void
6e39997a 5202register_remote_support_xml (const char *xml)
c8d5aac9
L
5203{
5204#if defined(HAVE_LIBEXPAT)
5205 if (remote_support_xml == NULL)
c4f7c687 5206 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
5207 else
5208 {
5209 char *copy = xstrdup (remote_support_xml + 13);
5210 char *p = strtok (copy, ",");
5211
5212 do
5213 {
5214 if (strcmp (p, xml) == 0)
5215 {
5216 /* already there */
5217 xfree (copy);
5218 return;
5219 }
5220 }
5221 while ((p = strtok (NULL, ",")) != NULL);
5222 xfree (copy);
5223
94b0dee1
PA
5224 remote_support_xml = reconcat (remote_support_xml,
5225 remote_support_xml, ",", xml,
5226 (char *) NULL);
c8d5aac9
L
5227 }
5228#endif
5229}
5230
69b6ecb0
TT
5231static void
5232remote_query_supported_append (std::string *msg, const char *append)
c8d5aac9 5233{
69b6ecb0
TT
5234 if (!msg->empty ())
5235 msg->append (";");
5236 msg->append (append);
c8d5aac9
L
5237}
5238
6b8edb51
PA
5239void
5240remote_target::remote_query_supported ()
be2a5f71
DJ
5241{
5242 struct remote_state *rs = get_remote_state ();
5243 char *next;
5244 int i;
5245 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5246
5247 /* The packet support flags are handled differently for this packet
5248 than for most others. We treat an error, a disabled packet, and
5249 an empty response identically: any features which must be reported
5250 to be used will be automatically disabled. An empty buffer
5251 accomplishes this, since that is also the representation for a list
5252 containing no features. */
5253
5254 rs->buf[0] = 0;
4082afcc 5255 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 5256 {
69b6ecb0 5257 std::string q;
c8d5aac9 5258
73b8c1fd 5259 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5260 remote_query_supported_append (&q, "multiprocess+");
c8d5aac9 5261
f7e6eed5 5262 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5263 remote_query_supported_append (&q, "swbreak+");
f7e6eed5 5264 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5265 remote_query_supported_append (&q, "hwbreak+");
f7e6eed5 5266
69b6ecb0 5267 remote_query_supported_append (&q, "qRelocInsn+");
dde08ee1 5268
8020350c
DB
5269 if (packet_set_cmd_state (PACKET_fork_event_feature)
5270 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5271 remote_query_supported_append (&q, "fork-events+");
8020350c
DB
5272 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5273 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5274 remote_query_supported_append (&q, "vfork-events+");
8020350c
DB
5275 if (packet_set_cmd_state (PACKET_exec_event_feature)
5276 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5277 remote_query_supported_append (&q, "exec-events+");
89245bc0 5278
750ce8d1 5279 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5280 remote_query_supported_append (&q, "vContSupported+");
750ce8d1 5281
65706a29 5282 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5283 remote_query_supported_append (&q, "QThreadEvents+");
65706a29 5284
f2faf941 5285 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5286 remote_query_supported_append (&q, "no-resumed+");
f2faf941 5287
b35d5edb
PA
5288 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5289 the qSupported:xmlRegisters=i386 handling. */
7cc244de
PA
5290 if (remote_support_xml != NULL
5291 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
69b6ecb0 5292 remote_query_supported_append (&q, remote_support_xml);
82f73884 5293
69b6ecb0
TT
5294 q = "qSupported:" + q;
5295 putpkt (q.c_str ());
94b0dee1 5296
8d64371b 5297 getpkt (&rs->buf, 0);
be2a5f71
DJ
5298
5299 /* If an error occured, warn, but do not return - just reset the
5300 buffer to empty and go on to disable features. */
5301 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5302 == PACKET_ERROR)
5303 {
8d64371b 5304 warning (_("Remote failure reply: %s"), rs->buf.data ());
be2a5f71
DJ
5305 rs->buf[0] = 0;
5306 }
5307 }
5308
5309 memset (seen, 0, sizeof (seen));
5310
8d64371b 5311 next = rs->buf.data ();
be2a5f71
DJ
5312 while (*next)
5313 {
5314 enum packet_support is_supported;
5315 char *p, *end, *name_end, *value;
5316
5317 /* First separate out this item from the rest of the packet. If
5318 there's another item after this, we overwrite the separator
5319 (terminated strings are much easier to work with). */
5320 p = next;
5321 end = strchr (p, ';');
5322 if (end == NULL)
5323 {
5324 end = p + strlen (p);
5325 next = end;
5326 }
5327 else
5328 {
89be2091
DJ
5329 *end = '\0';
5330 next = end + 1;
5331
be2a5f71
DJ
5332 if (end == p)
5333 {
5334 warning (_("empty item in \"qSupported\" response"));
5335 continue;
5336 }
be2a5f71
DJ
5337 }
5338
5339 name_end = strchr (p, '=');
5340 if (name_end)
5341 {
5342 /* This is a name=value entry. */
5343 is_supported = PACKET_ENABLE;
5344 value = name_end + 1;
5345 *name_end = '\0';
5346 }
5347 else
5348 {
5349 value = NULL;
5350 switch (end[-1])
5351 {
5352 case '+':
5353 is_supported = PACKET_ENABLE;
5354 break;
5355
5356 case '-':
5357 is_supported = PACKET_DISABLE;
5358 break;
5359
5360 case '?':
5361 is_supported = PACKET_SUPPORT_UNKNOWN;
5362 break;
5363
5364 default:
3e43a32a
MS
5365 warning (_("unrecognized item \"%s\" "
5366 "in \"qSupported\" response"), p);
be2a5f71
DJ
5367 continue;
5368 }
5369 end[-1] = '\0';
5370 }
5371
5372 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5373 if (strcmp (remote_protocol_features[i].name, p) == 0)
5374 {
5375 const struct protocol_feature *feature;
5376
5377 seen[i] = 1;
5378 feature = &remote_protocol_features[i];
6b8edb51 5379 feature->func (this, feature, is_supported, value);
be2a5f71
DJ
5380 break;
5381 }
5382 }
5383
5384 /* If we increased the packet size, make sure to increase the global
5385 buffer size also. We delay this until after parsing the entire
5386 qSupported packet, because this is the same buffer we were
5387 parsing. */
8d64371b
TT
5388 if (rs->buf.size () < rs->explicit_packet_size)
5389 rs->buf.resize (rs->explicit_packet_size);
be2a5f71
DJ
5390
5391 /* Handle the defaults for unmentioned features. */
5392 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5393 if (!seen[i])
5394 {
5395 const struct protocol_feature *feature;
5396
5397 feature = &remote_protocol_features[i];
6b8edb51 5398 feature->func (this, feature, feature->default_support, NULL);
be2a5f71
DJ
5399 }
5400}
5401
048094ac
PA
5402/* Serial QUIT handler for the remote serial descriptor.
5403
5404 Defers handling a Ctrl-C until we're done with the current
5405 command/response packet sequence, unless:
5406
5407 - We're setting up the connection. Don't send a remote interrupt
5408 request, as we're not fully synced yet. Quit immediately
5409 instead.
5410
5411 - The target has been resumed in the foreground
223ffa71 5412 (target_terminal::is_ours is false) with a synchronous resume
048094ac
PA
5413 packet, and we're blocked waiting for the stop reply, thus a
5414 Ctrl-C should be immediately sent to the target.
5415
5416 - We get a second Ctrl-C while still within the same serial read or
5417 write. In that case the serial is seemingly wedged --- offer to
5418 quit/disconnect.
5419
5420 - We see a second Ctrl-C without target response, after having
5421 previously interrupted the target. In that case the target/stub
5422 is probably wedged --- offer to quit/disconnect.
5423*/
5424
6b8edb51
PA
5425void
5426remote_target::remote_serial_quit_handler ()
048094ac
PA
5427{
5428 struct remote_state *rs = get_remote_state ();
5429
5430 if (check_quit_flag ())
5431 {
5432 /* If we're starting up, we're not fully synced yet. Quit
5433 immediately. */
5434 if (rs->starting_up)
5435 quit ();
5436 else if (rs->got_ctrlc_during_io)
5437 {
5438 if (query (_("The target is not responding to GDB commands.\n"
5439 "Stop debugging it? ")))
5440 remote_unpush_and_throw ();
5441 }
5442 /* If ^C has already been sent once, offer to disconnect. */
223ffa71 5443 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
048094ac
PA
5444 interrupt_query ();
5445 /* All-stop protocol, and blocked waiting for stop reply. Send
5446 an interrupt request. */
223ffa71 5447 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
e671cd59 5448 target_interrupt ();
048094ac
PA
5449 else
5450 rs->got_ctrlc_during_io = 1;
5451 }
5452}
5453
6b8edb51
PA
5454/* The remote_target that is current while the quit handler is
5455 overridden with remote_serial_quit_handler. */
5456static remote_target *curr_quit_handler_target;
5457
5458static void
5459remote_serial_quit_handler ()
5460{
5461 curr_quit_handler_target->remote_serial_quit_handler ();
5462}
5463
78a095c3
JK
5464/* Remove any of the remote.c targets from target stack. Upper targets depend
5465 on it so remove them first. */
5466
5467static void
5468remote_unpush_target (void)
5469{
915ef8b1 5470 pop_all_targets_at_and_above (process_stratum);
78a095c3 5471}
be2a5f71 5472
048094ac
PA
5473static void
5474remote_unpush_and_throw (void)
5475{
5476 remote_unpush_target ();
5477 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5478}
5479
f6ac5f3d
PA
5480void
5481remote_target::open_1 (const char *name, int from_tty, int extended_p)
c906108c 5482{
6b8edb51 5483 remote_target *curr_remote = get_current_remote_target ();
a6f3e723 5484
c906108c 5485 if (name == 0)
8a3fe4f8 5486 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 5487 "serial device is attached to the remote system\n"
8a3fe4f8 5488 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 5489
2d717e4f 5490 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
5491 Ask this question first, before target_preopen has a chance to kill
5492 anything. */
6b8edb51 5493 if (curr_remote != NULL && !have_inferiors ())
2d717e4f 5494 {
78a095c3
JK
5495 if (from_tty
5496 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
5497 error (_("Still connected."));
5498 }
5499
78a095c3 5500 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
5501 target_preopen (from_tty);
5502
ad9a8f3f 5503 remote_fileio_reset ();
1dd41f16
NS
5504 reopen_exec_file ();
5505 reread_symbols ();
5506
6b8edb51
PA
5507 remote_target *remote
5508 = (extended_p ? new extended_remote_target () : new remote_target ());
5509 target_ops_up target_holder (remote);
5510
5511 remote_state *rs = remote->get_remote_state ();
5512
5513 /* See FIXME above. */
5514 if (!target_async_permitted)
5515 rs->wait_forever_enabled_p = 1;
5516
5d93a237
TT
5517 rs->remote_desc = remote_serial_open (name);
5518 if (!rs->remote_desc)
c906108c
SS
5519 perror_with_name (name);
5520
5521 if (baud_rate != -1)
5522 {
5d93a237 5523 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 5524 {
9b74d5d3
KB
5525 /* The requested speed could not be set. Error out to
5526 top level after closing remote_desc. Take care to
5527 set remote_desc to NULL to avoid closing remote_desc
5528 more than once. */
5d93a237
TT
5529 serial_close (rs->remote_desc);
5530 rs->remote_desc = NULL;
c906108c
SS
5531 perror_with_name (name);
5532 }
5533 }
5534
236af5e3 5535 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 5536 serial_raw (rs->remote_desc);
c906108c
SS
5537
5538 /* If there is something sitting in the buffer we might take it as a
5539 response to a command, which would be bad. */
5d93a237 5540 serial_flush_input (rs->remote_desc);
c906108c
SS
5541
5542 if (from_tty)
5543 {
5544 puts_filtered ("Remote debugging using ");
5545 puts_filtered (name);
5546 puts_filtered ("\n");
5547 }
d9f719f1 5548
6b8edb51
PA
5549 /* Switch to using the remote target now. */
5550 push_target (remote);
5551 /* The target stack owns the target now. */
5552 target_holder.release ();
c906108c 5553
74531fed 5554 /* Register extra event sources in the event loop. */
6b8edb51 5555 rs->remote_async_inferior_event_token
74531fed 5556 = create_async_event_handler (remote_async_inferior_event_handler,
6b8edb51
PA
5557 remote);
5558 rs->notif_state = remote_notif_state_allocate (remote);
74531fed 5559
be2a5f71
DJ
5560 /* Reset the target state; these things will be queried either by
5561 remote_query_supported or as they are needed. */
ca4f7f8b 5562 reset_all_packet_configs_support ();
74531fed 5563 rs->cached_wait_status = 0;
be2a5f71 5564 rs->explicit_packet_size = 0;
a6f3e723 5565 rs->noack_mode = 0;
82f73884 5566 rs->extended = extended_p;
e24a49d8 5567 rs->waiting_for_stop_reply = 0;
3a29589a 5568 rs->ctrlc_pending_p = 0;
048094ac 5569 rs->got_ctrlc_during_io = 0;
802188a7 5570
47f8a51d
TT
5571 rs->general_thread = not_sent_ptid;
5572 rs->continue_thread = not_sent_ptid;
262e1174 5573 rs->remote_traceframe_number = -1;
c906108c 5574
3a00c802
PA
5575 rs->last_resume_exec_dir = EXEC_FORWARD;
5576
9d1f7ab2 5577 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
5578 rs->use_threadinfo_query = 1;
5579 rs->use_threadextra_query = 1;
9d1f7ab2 5580
dd194f6b 5581 rs->readahead_cache.invalidate ();
80152258 5582
c6ebd6cf 5583 if (target_async_permitted)
92d1e331 5584 {
92d1e331
DJ
5585 /* FIXME: cagney/1999-09-23: During the initial connection it is
5586 assumed that the target is already ready and able to respond to
0df8b418 5587 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 5588 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 5589 around this. Eventually a mechanism that allows
92d1e331 5590 wait_for_inferior() to expect/get timeouts will be
23860348 5591 implemented. */
6b8edb51 5592 rs->wait_forever_enabled_p = 0;
92d1e331
DJ
5593 }
5594
23860348 5595 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 5596 no_shared_libraries (NULL, 0);
f78f6cf1 5597
36918e70 5598 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
5599 target (we'd otherwise be in an inconsistent state) and then
5600 propogate the error on up the exception chain. This ensures that
5601 the caller doesn't stumble along blindly assuming that the
5602 function succeeded. The CLI doesn't have this problem but other
5603 UI's, such as MI do.
36918e70
AC
5604
5605 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5606 this function should return an error indication letting the
ce2826aa 5607 caller restore the previous state. Unfortunately the command
36918e70
AC
5608 ``target remote'' is directly wired to this function making that
5609 impossible. On a positive note, the CLI side of this problem has
5610 been fixed - the function set_cmd_context() makes it possible for
5611 all the ``target ....'' commands to share a common callback
5612 function. See cli-dump.c. */
109c3e39 5613 {
2d717e4f 5614
492d29ea 5615 TRY
04bd08de 5616 {
6b8edb51 5617 remote->start_remote (from_tty, extended_p);
04bd08de 5618 }
492d29ea 5619 CATCH (ex, RETURN_MASK_ALL)
109c3e39 5620 {
c8d104ad
PA
5621 /* Pop the partially set up target - unless something else did
5622 already before throwing the exception. */
6b8edb51 5623 if (ex.error != TARGET_CLOSE_ERROR)
78a095c3 5624 remote_unpush_target ();
109c3e39
AC
5625 throw_exception (ex);
5626 }
492d29ea 5627 END_CATCH
109c3e39 5628 }
c906108c 5629
6b8edb51 5630 remote_btrace_reset (rs);
f4abbc16 5631
c6ebd6cf 5632 if (target_async_permitted)
6b8edb51 5633 rs->wait_forever_enabled_p = 1;
43ff13b4
JM
5634}
5635
de0d863e
DB
5636/* Detach the specified process. */
5637
6b8edb51
PA
5638void
5639remote_target::remote_detach_pid (int pid)
de0d863e
DB
5640{
5641 struct remote_state *rs = get_remote_state ();
5642
4c7333b3
PA
5643 /* This should not be necessary, but the handling for D;PID in
5644 GDBserver versions prior to 8.2 incorrectly assumes that the
5645 selected process points to the same process we're detaching,
5646 leading to misbehavior (and possibly GDBserver crashing) when it
5647 does not. Since it's easy and cheap, work around it by forcing
5648 GDBserver to select GDB's current process. */
5649 set_general_process ();
5650
de0d863e 5651 if (remote_multi_process_p (rs))
8d64371b 5652 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
de0d863e 5653 else
8d64371b 5654 strcpy (rs->buf.data (), "D");
de0d863e
DB
5655
5656 putpkt (rs->buf);
8d64371b 5657 getpkt (&rs->buf, 0);
de0d863e
DB
5658
5659 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5660 ;
5661 else if (rs->buf[0] == '\0')
5662 error (_("Remote doesn't know how to detach"));
5663 else
5664 error (_("Can't detach process."));
5665}
5666
5667/* This detaches a program to which we previously attached, using
5668 inferior_ptid to identify the process. After this is done, GDB
5669 can be used to debug some other program. We better not have left
5670 any breakpoints in the target program or it'll die when it hits
5671 one. */
c906108c 5672
6b8edb51 5673void
00431a78 5674remote_target::remote_detach_1 (inferior *inf, int from_tty)
c906108c 5675{
e99b03dc 5676 int pid = inferior_ptid.pid ();
d01949b6 5677 struct remote_state *rs = get_remote_state ();
de0d863e 5678 int is_fork_parent;
c906108c 5679
2d717e4f
DJ
5680 if (!target_has_execution)
5681 error (_("No process to detach from."));
5682
0f48b757 5683 target_announce_detach (from_tty);
7cee1e54 5684
c906108c 5685 /* Tell the remote target to detach. */
de0d863e 5686 remote_detach_pid (pid);
82f73884 5687
8020350c
DB
5688 /* Exit only if this is the only active inferior. */
5689 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
7cee1e54 5690 puts_filtered (_("Ending remote debugging.\n"));
82f73884 5691
00431a78
PA
5692 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5693
de0d863e
DB
5694 /* Check to see if we are detaching a fork parent. Note that if we
5695 are detaching a fork child, tp == NULL. */
5696 is_fork_parent = (tp != NULL
5697 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5698
5699 /* If doing detach-on-fork, we don't mourn, because that will delete
5700 breakpoints that should be available for the followed inferior. */
5701 if (!is_fork_parent)
f67c0c91 5702 {
249b5733
PA
5703 /* Save the pid as a string before mourning, since that will
5704 unpush the remote target, and we need the string after. */
f2907e49 5705 std::string infpid = target_pid_to_str (ptid_t (pid));
f67c0c91
SDJ
5706
5707 target_mourn_inferior (inferior_ptid);
5708 if (print_inferior_events)
5709 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5710 inf->num, infpid.c_str ());
5711 }
de0d863e
DB
5712 else
5713 {
5714 inferior_ptid = null_ptid;
00431a78 5715 detach_inferior (current_inferior ());
de0d863e 5716 }
2d717e4f
DJ
5717}
5718
f6ac5f3d
PA
5719void
5720remote_target::detach (inferior *inf, int from_tty)
2d717e4f 5721{
00431a78 5722 remote_detach_1 (inf, from_tty);
2d717e4f
DJ
5723}
5724
f6ac5f3d
PA
5725void
5726extended_remote_target::detach (inferior *inf, int from_tty)
2d717e4f 5727{
00431a78 5728 remote_detach_1 (inf, from_tty);
de0d863e
DB
5729}
5730
5731/* Target follow-fork function for remote targets. On entry, and
5732 at return, the current inferior is the fork parent.
5733
5734 Note that although this is currently only used for extended-remote,
5735 it is named remote_follow_fork in anticipation of using it for the
5736 remote target as well. */
5737
f6ac5f3d
PA
5738int
5739remote_target::follow_fork (int follow_child, int detach_fork)
de0d863e
DB
5740{
5741 struct remote_state *rs = get_remote_state ();
c269dbdb 5742 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5743
c269dbdb
DB
5744 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5745 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5746 {
5747 /* When following the parent and detaching the child, we detach
5748 the child here. For the case of following the child and
5749 detaching the parent, the detach is done in the target-
5750 independent follow fork code in infrun.c. We can't use
5751 target_detach when detaching an unfollowed child because
5752 the client side doesn't know anything about the child. */
5753 if (detach_fork && !follow_child)
5754 {
5755 /* Detach the fork child. */
5756 ptid_t child_ptid;
5757 pid_t child_pid;
5758
5759 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
e99b03dc 5760 child_pid = child_ptid.pid ();
de0d863e
DB
5761
5762 remote_detach_pid (child_pid);
de0d863e
DB
5763 }
5764 }
5765 return 0;
c906108c
SS
5766}
5767
94585166
DB
5768/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5769 in the program space of the new inferior. On entry and at return the
5770 current inferior is the exec'ing inferior. INF is the new exec'd
5771 inferior, which may be the same as the exec'ing inferior unless
5772 follow-exec-mode is "new". */
5773
f6ac5f3d
PA
5774void
5775remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
94585166
DB
5776{
5777 /* We know that this is a target file name, so if it has the "target:"
5778 prefix we strip it off before saving it in the program space. */
5779 if (is_target_filename (execd_pathname))
5780 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5781
5782 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5783}
5784
6ad8ae5c
DJ
5785/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5786
f6ac5f3d
PA
5787void
5788remote_target::disconnect (const char *args, int from_tty)
43ff13b4 5789{
43ff13b4 5790 if (args)
2d717e4f 5791 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5792
8020350c
DB
5793 /* Make sure we unpush even the extended remote targets. Calling
5794 target_mourn_inferior won't unpush, and remote_mourn won't
5795 unpush if there is more than one inferior left. */
f6ac5f3d 5796 unpush_target (this);
8020350c 5797 generic_mourn_inferior ();
2d717e4f 5798
43ff13b4
JM
5799 if (from_tty)
5800 puts_filtered ("Ending remote debugging.\n");
5801}
5802
2d717e4f
DJ
5803/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5804 be chatty about it. */
5805
f6ac5f3d
PA
5806void
5807extended_remote_target::attach (const char *args, int from_tty)
2d717e4f
DJ
5808{
5809 struct remote_state *rs = get_remote_state ();
be86555c 5810 int pid;
96ef3384 5811 char *wait_status = NULL;
2d717e4f 5812
74164c56 5813 pid = parse_pid_to_attach (args);
2d717e4f 5814
74164c56
JK
5815 /* Remote PID can be freely equal to getpid, do not check it here the same
5816 way as in other targets. */
2d717e4f 5817
4082afcc 5818 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5819 error (_("This target does not support attaching to a process"));
5820
7cee1e54
PA
5821 if (from_tty)
5822 {
5823 char *exec_file = get_exec_file (0);
5824
5825 if (exec_file)
5826 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
f2907e49 5827 target_pid_to_str (ptid_t (pid)));
7cee1e54
PA
5828 else
5829 printf_unfiltered (_("Attaching to %s\n"),
f2907e49 5830 target_pid_to_str (ptid_t (pid)));
7cee1e54
PA
5831
5832 gdb_flush (gdb_stdout);
5833 }
5834
8d64371b 5835 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f 5836 putpkt (rs->buf);
8d64371b 5837 getpkt (&rs->buf, 0);
2d717e4f 5838
4082afcc
PA
5839 switch (packet_ok (rs->buf,
5840 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5841 {
4082afcc 5842 case PACKET_OK:
6efcd9a8 5843 if (!target_is_non_stop_p ())
74531fed
PA
5844 {
5845 /* Save the reply for later. */
8d64371b
TT
5846 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
5847 strcpy (wait_status, rs->buf.data ());
74531fed 5848 }
8d64371b 5849 else if (strcmp (rs->buf.data (), "OK") != 0)
74531fed 5850 error (_("Attaching to %s failed with: %s"),
f2907e49 5851 target_pid_to_str (ptid_t (pid)),
8d64371b 5852 rs->buf.data ());
4082afcc
PA
5853 break;
5854 case PACKET_UNKNOWN:
5855 error (_("This target does not support attaching to a process"));
5856 default:
5857 error (_("Attaching to %s failed"),
f2907e49 5858 target_pid_to_str (ptid_t (pid)));
2d717e4f 5859 }
2d717e4f 5860
1b6e6f5c 5861 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 5862
f2907e49 5863 inferior_ptid = ptid_t (pid);
79d7f229 5864
6efcd9a8 5865 if (target_is_non_stop_p ())
bad34192
PA
5866 {
5867 struct thread_info *thread;
79d7f229 5868
bad34192 5869 /* Get list of threads. */
f6ac5f3d 5870 update_thread_list ();
82f73884 5871
00431a78 5872 thread = first_thread_of_inferior (current_inferior ());
bad34192
PA
5873 if (thread)
5874 inferior_ptid = thread->ptid;
5875 else
f2907e49 5876 inferior_ptid = ptid_t (pid);
bad34192
PA
5877
5878 /* Invalidate our notion of the remote current thread. */
47f8a51d 5879 record_currthread (rs, minus_one_ptid);
bad34192 5880 }
74531fed 5881 else
bad34192
PA
5882 {
5883 /* Now, if we have thread information, update inferior_ptid. */
5884 inferior_ptid = remote_current_thread (inferior_ptid);
5885
5886 /* Add the main thread to the thread list. */
00aecdcf
PA
5887 thread_info *thr = add_thread_silent (inferior_ptid);
5888 /* Don't consider the thread stopped until we've processed the
5889 saved stop reply. */
5890 set_executing (thr->ptid, true);
bad34192 5891 }
c0a2216e 5892
96ef3384
UW
5893 /* Next, if the target can specify a description, read it. We do
5894 this before anything involving memory or registers. */
5895 target_find_description ();
5896
6efcd9a8 5897 if (!target_is_non_stop_p ())
74531fed
PA
5898 {
5899 /* Use the previously fetched status. */
5900 gdb_assert (wait_status != NULL);
5901
5902 if (target_can_async_p ())
5903 {
722247f1 5904 struct notif_event *reply
6b8edb51 5905 = remote_notif_parse (this, &notif_client_stop, wait_status);
74531fed 5906
722247f1 5907 push_stop_reply ((struct stop_reply *) reply);
74531fed 5908
6a3753b3 5909 target_async (1);
74531fed
PA
5910 }
5911 else
5912 {
5913 gdb_assert (wait_status != NULL);
8d64371b 5914 strcpy (rs->buf.data (), wait_status);
74531fed
PA
5915 rs->cached_wait_status = 1;
5916 }
5917 }
5918 else
5919 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5920}
5921
b9c1d481
AS
5922/* Implementation of the to_post_attach method. */
5923
f6ac5f3d
PA
5924void
5925extended_remote_target::post_attach (int pid)
b9c1d481 5926{
6efcd9a8
PA
5927 /* Get text, data & bss offsets. */
5928 get_offsets ();
5929
b9c1d481
AS
5930 /* In certain cases GDB might not have had the chance to start
5931 symbol lookup up until now. This could happen if the debugged
5932 binary is not using shared libraries, the vsyscall page is not
5933 present (on Linux) and the binary itself hadn't changed since the
5934 debugging process was started. */
5935 if (symfile_objfile != NULL)
5936 remote_check_symbols();
5937}
5938
c906108c 5939\f
506fb367
DJ
5940/* Check for the availability of vCont. This function should also check
5941 the response. */
c906108c 5942
6b8edb51
PA
5943void
5944remote_target::remote_vcont_probe ()
c906108c 5945{
6b8edb51 5946 remote_state *rs = get_remote_state ();
2e9f7625 5947 char *buf;
6d820c5c 5948
8d64371b 5949 strcpy (rs->buf.data (), "vCont?");
2e9f7625 5950 putpkt (rs->buf);
8d64371b
TT
5951 getpkt (&rs->buf, 0);
5952 buf = rs->buf.data ();
c906108c 5953
506fb367 5954 /* Make sure that the features we assume are supported. */
61012eef 5955 if (startswith (buf, "vCont"))
506fb367
DJ
5956 {
5957 char *p = &buf[5];
750ce8d1 5958 int support_c, support_C;
506fb367 5959
750ce8d1
YQ
5960 rs->supports_vCont.s = 0;
5961 rs->supports_vCont.S = 0;
506fb367
DJ
5962 support_c = 0;
5963 support_C = 0;
d458bd84 5964 rs->supports_vCont.t = 0;
c1e36e3e 5965 rs->supports_vCont.r = 0;
506fb367
DJ
5966 while (p && *p == ';')
5967 {
5968 p++;
5969 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5970 rs->supports_vCont.s = 1;
506fb367 5971 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5972 rs->supports_vCont.S = 1;
506fb367
DJ
5973 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5974 support_c = 1;
5975 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5976 support_C = 1;
74531fed 5977 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5978 rs->supports_vCont.t = 1;
c1e36e3e
PA
5979 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5980 rs->supports_vCont.r = 1;
506fb367
DJ
5981
5982 p = strchr (p, ';');
5983 }
c906108c 5984
750ce8d1
YQ
5985 /* If c, and C are not all supported, we can't use vCont. Clearing
5986 BUF will make packet_ok disable the packet. */
5987 if (!support_c || !support_C)
506fb367
DJ
5988 buf[0] = 0;
5989 }
c906108c 5990
8d64371b 5991 packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 5992}
c906108c 5993
0d8f58ca
PA
5994/* Helper function for building "vCont" resumptions. Write a
5995 resumption to P. ENDP points to one-passed-the-end of the buffer
5996 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5997 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5998 resumed thread should be single-stepped and/or signalled. If PTID
5999 equals minus_one_ptid, then all threads are resumed; if PTID
6000 represents a process, then all threads of the process are resumed;
6001 the thread to be stepped and/or signalled is given in the global
6002 INFERIOR_PTID. */
6003
6b8edb51
PA
6004char *
6005remote_target::append_resumption (char *p, char *endp,
6006 ptid_t ptid, int step, gdb_signal siggnal)
0d8f58ca
PA
6007{
6008 struct remote_state *rs = get_remote_state ();
6009
a493e3e2 6010 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 6011 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
6012 else if (step
6013 /* GDB is willing to range step. */
6014 && use_range_stepping
6015 /* Target supports range stepping. */
6016 && rs->supports_vCont.r
6017 /* We don't currently support range stepping multiple
6018 threads with a wildcard (though the protocol allows it,
6019 so stubs shouldn't make an active effort to forbid
6020 it). */
0e998d96 6021 && !(remote_multi_process_p (rs) && ptid.is_pid ()))
c1e36e3e
PA
6022 {
6023 struct thread_info *tp;
6024
d7e15655 6025 if (ptid == minus_one_ptid)
c1e36e3e
PA
6026 {
6027 /* If we don't know about the target thread's tid, then
6028 we're resuming magic_null_ptid (see caller). */
6029 tp = find_thread_ptid (magic_null_ptid);
6030 }
6031 else
6032 tp = find_thread_ptid (ptid);
6033 gdb_assert (tp != NULL);
6034
6035 if (tp->control.may_range_step)
6036 {
6037 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6038
6039 p += xsnprintf (p, endp - p, ";r%s,%s",
6040 phex_nz (tp->control.step_range_start,
6041 addr_size),
6042 phex_nz (tp->control.step_range_end,
6043 addr_size));
6044 }
6045 else
6046 p += xsnprintf (p, endp - p, ";s");
6047 }
0d8f58ca
PA
6048 else if (step)
6049 p += xsnprintf (p, endp - p, ";s");
a493e3e2 6050 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
6051 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6052 else
6053 p += xsnprintf (p, endp - p, ";c");
6054
0e998d96 6055 if (remote_multi_process_p (rs) && ptid.is_pid ())
0d8f58ca
PA
6056 {
6057 ptid_t nptid;
6058
6059 /* All (-1) threads of process. */
e99b03dc 6060 nptid = ptid_t (ptid.pid (), -1, 0);
0d8f58ca
PA
6061
6062 p += xsnprintf (p, endp - p, ":");
6063 p = write_ptid (p, endp, nptid);
6064 }
d7e15655 6065 else if (ptid != minus_one_ptid)
0d8f58ca
PA
6066 {
6067 p += xsnprintf (p, endp - p, ":");
6068 p = write_ptid (p, endp, ptid);
6069 }
6070
6071 return p;
6072}
6073
799a2abe
PA
6074/* Clear the thread's private info on resume. */
6075
6076static void
6077resume_clear_thread_private_info (struct thread_info *thread)
6078{
6079 if (thread->priv != NULL)
6080 {
7aabaf9d
SM
6081 remote_thread_info *priv = get_remote_thread_info (thread);
6082
6083 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6084 priv->watch_data_address = 0;
799a2abe
PA
6085 }
6086}
6087
e5ef252a
PA
6088/* Append a vCont continue-with-signal action for threads that have a
6089 non-zero stop signal. */
6090
6b8edb51
PA
6091char *
6092remote_target::append_pending_thread_resumptions (char *p, char *endp,
6093 ptid_t ptid)
e5ef252a 6094{
08036331
PA
6095 for (thread_info *thread : all_non_exited_threads (ptid))
6096 if (inferior_ptid != thread->ptid
70509625 6097 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
6098 {
6099 p = append_resumption (p, endp, thread->ptid,
6100 0, thread->suspend.stop_signal);
6101 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 6102 resume_clear_thread_private_info (thread);
e5ef252a
PA
6103 }
6104
6105 return p;
6106}
6107
7b68ffbb
PA
6108/* Set the target running, using the packets that use Hc
6109 (c/s/C/S). */
6110
6b8edb51
PA
6111void
6112remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6113 gdb_signal siggnal)
7b68ffbb
PA
6114{
6115 struct remote_state *rs = get_remote_state ();
7b68ffbb
PA
6116 char *buf;
6117
6118 rs->last_sent_signal = siggnal;
6119 rs->last_sent_step = step;
6120
6121 /* The c/s/C/S resume packets use Hc, so set the continue
6122 thread. */
d7e15655 6123 if (ptid == minus_one_ptid)
7b68ffbb
PA
6124 set_continue_thread (any_thread_ptid);
6125 else
6126 set_continue_thread (ptid);
6127
08036331 6128 for (thread_info *thread : all_non_exited_threads ())
7b68ffbb
PA
6129 resume_clear_thread_private_info (thread);
6130
8d64371b 6131 buf = rs->buf.data ();
6b8edb51 6132 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6133 {
6134 /* We don't pass signals to the target in reverse exec mode. */
6135 if (info_verbose && siggnal != GDB_SIGNAL_0)
6136 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6137 siggnal);
6138
6139 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6140 error (_("Remote reverse-step not supported."));
6141 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6142 error (_("Remote reverse-continue not supported."));
6143
6144 strcpy (buf, step ? "bs" : "bc");
6145 }
6146 else if (siggnal != GDB_SIGNAL_0)
6147 {
6148 buf[0] = step ? 'S' : 'C';
6149 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6150 buf[2] = tohex (((int) siggnal) & 0xf);
6151 buf[3] = '\0';
6152 }
6153 else
6154 strcpy (buf, step ? "s" : "c");
6155
6156 putpkt (buf);
6157}
6158
506fb367
DJ
6159/* Resume the remote inferior by using a "vCont" packet. The thread
6160 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
6161 resumed thread should be single-stepped and/or signalled. If PTID
6162 equals minus_one_ptid, then all threads are resumed; the thread to
6163 be stepped and/or signalled is given in the global INFERIOR_PTID.
6164 This function returns non-zero iff it resumes the inferior.
44eaed12 6165
7b68ffbb
PA
6166 This function issues a strict subset of all possible vCont commands
6167 at the moment. */
44eaed12 6168
6b8edb51
PA
6169int
6170remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6171 enum gdb_signal siggnal)
506fb367
DJ
6172{
6173 struct remote_state *rs = get_remote_state ();
82f73884
PA
6174 char *p;
6175 char *endp;
44eaed12 6176
7b68ffbb 6177 /* No reverse execution actions defined for vCont. */
6b8edb51 6178 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6179 return 0;
6180
4082afcc 6181 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 6182 remote_vcont_probe ();
44eaed12 6183
4082afcc 6184 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 6185 return 0;
44eaed12 6186
8d64371b
TT
6187 p = rs->buf.data ();
6188 endp = p + get_remote_packet_size ();
82f73884 6189
506fb367
DJ
6190 /* If we could generate a wider range of packets, we'd have to worry
6191 about overflowing BUF. Should there be a generic
6192 "multi-part-packet" packet? */
6193
0d8f58ca
PA
6194 p += xsnprintf (p, endp - p, "vCont");
6195
d7e15655 6196 if (ptid == magic_null_ptid)
c906108c 6197 {
79d7f229
PA
6198 /* MAGIC_NULL_PTID means that we don't have any active threads,
6199 so we don't have any TID numbers the inferior will
6200 understand. Make sure to only send forms that do not specify
6201 a TID. */
a9cbf802 6202 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 6203 }
d7e15655 6204 else if (ptid == minus_one_ptid || ptid.is_pid ())
506fb367 6205 {
0d8f58ca
PA
6206 /* Resume all threads (of all processes, or of a single
6207 process), with preference for INFERIOR_PTID. This assumes
6208 inferior_ptid belongs to the set of all threads we are about
6209 to resume. */
a493e3e2 6210 if (step || siggnal != GDB_SIGNAL_0)
82f73884 6211 {
0d8f58ca
PA
6212 /* Step inferior_ptid, with or without signal. */
6213 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 6214 }
0d8f58ca 6215
e5ef252a
PA
6216 /* Also pass down any pending signaled resumption for other
6217 threads not the current. */
6218 p = append_pending_thread_resumptions (p, endp, ptid);
6219
0d8f58ca 6220 /* And continue others without a signal. */
a493e3e2 6221 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
6222 }
6223 else
506fb367
DJ
6224 {
6225 /* Scheduler locking; resume only PTID. */
a9cbf802 6226 append_resumption (p, endp, ptid, step, siggnal);
506fb367 6227 }
c906108c 6228
8d64371b 6229 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
82f73884 6230 putpkt (rs->buf);
506fb367 6231
6efcd9a8 6232 if (target_is_non_stop_p ())
74531fed
PA
6233 {
6234 /* In non-stop, the stub replies to vCont with "OK". The stop
6235 reply will be reported asynchronously by means of a `%Stop'
6236 notification. */
8d64371b
TT
6237 getpkt (&rs->buf, 0);
6238 if (strcmp (rs->buf.data (), "OK") != 0)
6239 error (_("Unexpected vCont reply in non-stop mode: %s"),
6240 rs->buf.data ());
74531fed
PA
6241 }
6242
506fb367 6243 return 1;
c906108c 6244}
43ff13b4 6245
506fb367
DJ
6246/* Tell the remote machine to resume. */
6247
f6ac5f3d
PA
6248void
6249remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 6250{
d01949b6 6251 struct remote_state *rs = get_remote_state ();
43ff13b4 6252
85ad3aaf
PA
6253 /* When connected in non-stop mode, the core resumes threads
6254 individually. Resuming remote threads directly in target_resume
6255 would thus result in sending one packet per thread. Instead, to
6256 minimize roundtrip latency, here we just store the resume
6257 request; the actual remote resumption will be done in
6258 target_commit_resume / remote_commit_resume, where we'll be able
6259 to do vCont action coalescing. */
f6ac5f3d 6260 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
85ad3aaf 6261 {
7aabaf9d 6262 remote_thread_info *remote_thr;
85ad3aaf 6263
d7e15655 6264 if (minus_one_ptid == ptid || ptid.is_pid ())
7aabaf9d 6265 remote_thr = get_remote_thread_info (inferior_ptid);
85ad3aaf 6266 else
7aabaf9d
SM
6267 remote_thr = get_remote_thread_info (ptid);
6268
85ad3aaf
PA
6269 remote_thr->last_resume_step = step;
6270 remote_thr->last_resume_sig = siggnal;
6271 return;
6272 }
6273
722247f1
YQ
6274 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6275 (explained in remote-notif.c:handle_notification) so
6276 remote_notif_process is not called. We need find a place where
6277 it is safe to start a 'vNotif' sequence. It is good to do it
6278 before resuming inferior, because inferior was stopped and no RSP
6279 traffic at that moment. */
6efcd9a8 6280 if (!target_is_non_stop_p ())
5965e028 6281 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 6282
f6ac5f3d 6283 rs->last_resume_exec_dir = ::execution_direction;
3a00c802 6284
7b68ffbb
PA
6285 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6286 if (!remote_resume_with_vcont (ptid, step, siggnal))
6b8edb51 6287 remote_resume_with_hc (ptid, step, siggnal);
43ff13b4 6288
2acceee2 6289 /* We are about to start executing the inferior, let's register it
0df8b418
MS
6290 with the event loop. NOTE: this is the one place where all the
6291 execution commands end up. We could alternatively do this in each
23860348 6292 of the execution commands in infcmd.c. */
2acceee2
JM
6293 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6294 into infcmd.c in order to allow inferior function calls to work
23860348 6295 NOT asynchronously. */
362646f5 6296 if (target_can_async_p ())
6a3753b3 6297 target_async (1);
e24a49d8
PA
6298
6299 /* We've just told the target to resume. The remote server will
6300 wait for the inferior to stop, and then send a stop reply. In
6301 the mean time, we can't start another command/query ourselves
74531fed
PA
6302 because the stub wouldn't be ready to process it. This applies
6303 only to the base all-stop protocol, however. In non-stop (which
6304 only supports vCont), the stub replies with an "OK", and is
6305 immediate able to process further serial input. */
6efcd9a8 6306 if (!target_is_non_stop_p ())
74531fed 6307 rs->waiting_for_stop_reply = 1;
43ff13b4 6308}
85ad3aaf 6309
85ad3aaf
PA
6310static int is_pending_fork_parent_thread (struct thread_info *thread);
6311
6312/* Private per-inferior info for target remote processes. */
6313
089354bb 6314struct remote_inferior : public private_inferior
85ad3aaf
PA
6315{
6316 /* Whether we can send a wildcard vCont for this process. */
089354bb 6317 bool may_wildcard_vcont = true;
85ad3aaf
PA
6318};
6319
089354bb
SM
6320/* Get the remote private inferior data associated to INF. */
6321
6322static remote_inferior *
6323get_remote_inferior (inferior *inf)
6324{
6325 if (inf->priv == NULL)
6326 inf->priv.reset (new remote_inferior);
6327
6328 return static_cast<remote_inferior *> (inf->priv.get ());
6329}
6330
f5db4863 6331/* Class used to track the construction of a vCont packet in the
85ad3aaf
PA
6332 outgoing packet buffer. This is used to send multiple vCont
6333 packets if we have more actions than would fit a single packet. */
6334
f5db4863 6335class vcont_builder
85ad3aaf 6336{
f5db4863 6337public:
6b8edb51
PA
6338 explicit vcont_builder (remote_target *remote)
6339 : m_remote (remote)
f5db4863
PA
6340 {
6341 restart ();
6342 }
6343
6344 void flush ();
6345 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6346
6347private:
6348 void restart ();
6349
6b8edb51
PA
6350 /* The remote target. */
6351 remote_target *m_remote;
6352
85ad3aaf
PA
6353 /* Pointer to the first action. P points here if no action has been
6354 appended yet. */
f5db4863 6355 char *m_first_action;
85ad3aaf
PA
6356
6357 /* Where the next action will be appended. */
f5db4863 6358 char *m_p;
85ad3aaf
PA
6359
6360 /* The end of the buffer. Must never write past this. */
f5db4863 6361 char *m_endp;
85ad3aaf
PA
6362};
6363
6364/* Prepare the outgoing buffer for a new vCont packet. */
6365
f5db4863
PA
6366void
6367vcont_builder::restart ()
85ad3aaf 6368{
6b8edb51 6369 struct remote_state *rs = m_remote->get_remote_state ();
85ad3aaf 6370
8d64371b
TT
6371 m_p = rs->buf.data ();
6372 m_endp = m_p + m_remote->get_remote_packet_size ();
f5db4863
PA
6373 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6374 m_first_action = m_p;
85ad3aaf
PA
6375}
6376
6377/* If the vCont packet being built has any action, send it to the
6378 remote end. */
6379
f5db4863
PA
6380void
6381vcont_builder::flush ()
85ad3aaf
PA
6382{
6383 struct remote_state *rs;
6384
f5db4863 6385 if (m_p == m_first_action)
85ad3aaf
PA
6386 return;
6387
6b8edb51
PA
6388 rs = m_remote->get_remote_state ();
6389 m_remote->putpkt (rs->buf);
8d64371b
TT
6390 m_remote->getpkt (&rs->buf, 0);
6391 if (strcmp (rs->buf.data (), "OK") != 0)
6392 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
85ad3aaf
PA
6393}
6394
6395/* The largest action is range-stepping, with its two addresses. This
6396 is more than sufficient. If a new, bigger action is created, it'll
6397 quickly trigger a failed assertion in append_resumption (and we'll
6398 just bump this). */
6399#define MAX_ACTION_SIZE 200
6400
6401/* Append a new vCont action in the outgoing packet being built. If
6402 the action doesn't fit the packet along with previous actions, push
6403 what we've got so far to the remote end and start over a new vCont
6404 packet (with the new action). */
6405
f5db4863
PA
6406void
6407vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
85ad3aaf
PA
6408{
6409 char buf[MAX_ACTION_SIZE + 1];
85ad3aaf 6410
6b8edb51
PA
6411 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6412 ptid, step, siggnal);
85ad3aaf
PA
6413
6414 /* Check whether this new action would fit in the vCont packet along
6415 with previous actions. If not, send what we've got so far and
6416 start a new vCont packet. */
f5db4863
PA
6417 size_t rsize = endp - buf;
6418 if (rsize > m_endp - m_p)
85ad3aaf 6419 {
f5db4863
PA
6420 flush ();
6421 restart ();
85ad3aaf
PA
6422
6423 /* Should now fit. */
f5db4863 6424 gdb_assert (rsize <= m_endp - m_p);
85ad3aaf
PA
6425 }
6426
f5db4863
PA
6427 memcpy (m_p, buf, rsize);
6428 m_p += rsize;
6429 *m_p = '\0';
85ad3aaf
PA
6430}
6431
6432/* to_commit_resume implementation. */
6433
f6ac5f3d
PA
6434void
6435remote_target::commit_resume ()
85ad3aaf 6436{
85ad3aaf
PA
6437 int any_process_wildcard;
6438 int may_global_wildcard_vcont;
85ad3aaf
PA
6439
6440 /* If connected in all-stop mode, we'd send the remote resume
6441 request directly from remote_resume. Likewise if
6442 reverse-debugging, as there are no defined vCont actions for
6443 reverse execution. */
f6ac5f3d 6444 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
85ad3aaf
PA
6445 return;
6446
6447 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6448 instead of resuming all threads of each process individually.
6449 However, if any thread of a process must remain halted, we can't
6450 send wildcard resumes and must send one action per thread.
6451
6452 Care must be taken to not resume threads/processes the server
6453 side already told us are stopped, but the core doesn't know about
6454 yet, because the events are still in the vStopped notification
6455 queue. For example:
6456
6457 #1 => vCont s:p1.1;c
6458 #2 <= OK
6459 #3 <= %Stopped T05 p1.1
6460 #4 => vStopped
6461 #5 <= T05 p1.2
6462 #6 => vStopped
6463 #7 <= OK
6464 #8 (infrun handles the stop for p1.1 and continues stepping)
6465 #9 => vCont s:p1.1;c
6466
6467 The last vCont above would resume thread p1.2 by mistake, because
6468 the server has no idea that the event for p1.2 had not been
6469 handled yet.
6470
6471 The server side must similarly ignore resume actions for the
6472 thread that has a pending %Stopped notification (and any other
6473 threads with events pending), until GDB acks the notification
6474 with vStopped. Otherwise, e.g., the following case is
6475 mishandled:
6476
6477 #1 => g (or any other packet)
6478 #2 <= [registers]
6479 #3 <= %Stopped T05 p1.2
6480 #4 => vCont s:p1.1;c
6481 #5 <= OK
6482
6483 Above, the server must not resume thread p1.2. GDB can't know
6484 that p1.2 stopped until it acks the %Stopped notification, and
6485 since from GDB's perspective all threads should be running, it
6486 sends a "c" action.
6487
6488 Finally, special care must also be given to handling fork/vfork
6489 events. A (v)fork event actually tells us that two processes
6490 stopped -- the parent and the child. Until we follow the fork,
6491 we must not resume the child. Therefore, if we have a pending
6492 fork follow, we must not send a global wildcard resume action
6493 (vCont;c). We can still send process-wide wildcards though. */
6494
6495 /* Start by assuming a global wildcard (vCont;c) is possible. */
6496 may_global_wildcard_vcont = 1;
6497
6498 /* And assume every process is individually wildcard-able too. */
08036331 6499 for (inferior *inf : all_non_exited_inferiors ())
85ad3aaf 6500 {
089354bb
SM
6501 remote_inferior *priv = get_remote_inferior (inf);
6502
6503 priv->may_wildcard_vcont = true;
85ad3aaf
PA
6504 }
6505
6506 /* Check for any pending events (not reported or processed yet) and
6507 disable process and global wildcard resumes appropriately. */
6508 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6509
08036331 6510 for (thread_info *tp : all_non_exited_threads ())
85ad3aaf
PA
6511 {
6512 /* If a thread of a process is not meant to be resumed, then we
6513 can't wildcard that process. */
6514 if (!tp->executing)
6515 {
089354bb 6516 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
85ad3aaf
PA
6517
6518 /* And if we can't wildcard a process, we can't wildcard
6519 everything either. */
6520 may_global_wildcard_vcont = 0;
6521 continue;
6522 }
6523
6524 /* If a thread is the parent of an unfollowed fork, then we
6525 can't do a global wildcard, as that would resume the fork
6526 child. */
6527 if (is_pending_fork_parent_thread (tp))
6528 may_global_wildcard_vcont = 0;
6529 }
6530
6531 /* Now let's build the vCont packet(s). Actions must be appended
6532 from narrower to wider scopes (thread -> process -> global). If
6533 we end up with too many actions for a single packet vcont_builder
6534 flushes the current vCont packet to the remote side and starts a
6535 new one. */
6b8edb51 6536 struct vcont_builder vcont_builder (this);
85ad3aaf
PA
6537
6538 /* Threads first. */
08036331 6539 for (thread_info *tp : all_non_exited_threads ())
85ad3aaf 6540 {
7aabaf9d 6541 remote_thread_info *remote_thr = get_remote_thread_info (tp);
85ad3aaf
PA
6542
6543 if (!tp->executing || remote_thr->vcont_resumed)
6544 continue;
6545
6546 gdb_assert (!thread_is_in_step_over_chain (tp));
6547
6548 if (!remote_thr->last_resume_step
6549 && remote_thr->last_resume_sig == GDB_SIGNAL_0
089354bb 6550 && get_remote_inferior (tp->inf)->may_wildcard_vcont)
85ad3aaf
PA
6551 {
6552 /* We'll send a wildcard resume instead. */
6553 remote_thr->vcont_resumed = 1;
6554 continue;
6555 }
6556
f5db4863 6557 vcont_builder.push_action (tp->ptid,
85ad3aaf
PA
6558 remote_thr->last_resume_step,
6559 remote_thr->last_resume_sig);
6560 remote_thr->vcont_resumed = 1;
6561 }
6562
6563 /* Now check whether we can send any process-wide wildcard. This is
6564 to avoid sending a global wildcard in the case nothing is
6565 supposed to be resumed. */
6566 any_process_wildcard = 0;
6567
08036331 6568 for (inferior *inf : all_non_exited_inferiors ())
85ad3aaf 6569 {
089354bb 6570 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf
PA
6571 {
6572 any_process_wildcard = 1;
6573 break;
6574 }
6575 }
6576
6577 if (any_process_wildcard)
6578 {
6579 /* If all processes are wildcard-able, then send a single "c"
6580 action, otherwise, send an "all (-1) threads of process"
6581 continue action for each running process, if any. */
6582 if (may_global_wildcard_vcont)
6583 {
f5db4863
PA
6584 vcont_builder.push_action (minus_one_ptid,
6585 false, GDB_SIGNAL_0);
85ad3aaf
PA
6586 }
6587 else
6588 {
08036331 6589 for (inferior *inf : all_non_exited_inferiors ())
85ad3aaf 6590 {
089354bb 6591 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf 6592 {
f2907e49 6593 vcont_builder.push_action (ptid_t (inf->pid),
f5db4863 6594 false, GDB_SIGNAL_0);
85ad3aaf
PA
6595 }
6596 }
6597 }
6598 }
6599
f5db4863 6600 vcont_builder.flush ();
85ad3aaf
PA
6601}
6602
c906108c 6603\f
43ff13b4 6604
74531fed
PA
6605/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6606 thread, all threads of a remote process, or all threads of all
6607 processes. */
6608
6b8edb51
PA
6609void
6610remote_target::remote_stop_ns (ptid_t ptid)
74531fed
PA
6611{
6612 struct remote_state *rs = get_remote_state ();
8d64371b
TT
6613 char *p = rs->buf.data ();
6614 char *endp = p + get_remote_packet_size ();
74531fed 6615
4082afcc 6616 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 6617 remote_vcont_probe ();
74531fed 6618
d458bd84 6619 if (!rs->supports_vCont.t)
74531fed
PA
6620 error (_("Remote server does not support stopping threads"));
6621
d7e15655 6622 if (ptid == minus_one_ptid
0e998d96 6623 || (!remote_multi_process_p (rs) && ptid.is_pid ()))
74531fed
PA
6624 p += xsnprintf (p, endp - p, "vCont;t");
6625 else
6626 {
6627 ptid_t nptid;
6628
74531fed
PA
6629 p += xsnprintf (p, endp - p, "vCont;t:");
6630
0e998d96 6631 if (ptid.is_pid ())
74531fed 6632 /* All (-1) threads of process. */
e99b03dc 6633 nptid = ptid_t (ptid.pid (), -1, 0);
74531fed
PA
6634 else
6635 {
6636 /* Small optimization: if we already have a stop reply for
6637 this thread, no use in telling the stub we want this
6638 stopped. */
6639 if (peek_stop_reply (ptid))
6640 return;
6641
6642 nptid = ptid;
6643 }
6644
a9cbf802 6645 write_ptid (p, endp, nptid);
74531fed
PA
6646 }
6647
6648 /* In non-stop, we get an immediate OK reply. The stop reply will
6649 come in asynchronously by notification. */
6650 putpkt (rs->buf);
8d64371b
TT
6651 getpkt (&rs->buf, 0);
6652 if (strcmp (rs->buf.data (), "OK") != 0)
6653 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid),
6654 rs->buf.data ());
74531fed
PA
6655}
6656
bfedc46a
PA
6657/* All-stop version of target_interrupt. Sends a break or a ^C to
6658 interrupt the remote target. It is undefined which thread of which
6659 process reports the interrupt. */
74531fed 6660
6b8edb51
PA
6661void
6662remote_target::remote_interrupt_as ()
74531fed
PA
6663{
6664 struct remote_state *rs = get_remote_state ();
6665
3a29589a
DJ
6666 rs->ctrlc_pending_p = 1;
6667
74531fed
PA
6668 /* If the inferior is stopped already, but the core didn't know
6669 about it yet, just ignore the request. The cached wait status
6670 will be collected in remote_wait. */
6671 if (rs->cached_wait_status)
6672 return;
6673
9a7071a8
JB
6674 /* Send interrupt_sequence to remote target. */
6675 send_interrupt_sequence ();
74531fed
PA
6676}
6677
de979965
PA
6678/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6679 the remote target. It is undefined which thread of which process
e42de8c7
PA
6680 reports the interrupt. Throws an error if the packet is not
6681 supported by the server. */
de979965 6682
6b8edb51
PA
6683void
6684remote_target::remote_interrupt_ns ()
de979965
PA
6685{
6686 struct remote_state *rs = get_remote_state ();
8d64371b
TT
6687 char *p = rs->buf.data ();
6688 char *endp = p + get_remote_packet_size ();
de979965
PA
6689
6690 xsnprintf (p, endp - p, "vCtrlC");
6691
6692 /* In non-stop, we get an immediate OK reply. The stop reply will
6693 come in asynchronously by notification. */
6694 putpkt (rs->buf);
8d64371b 6695 getpkt (&rs->buf, 0);
de979965
PA
6696
6697 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6698 {
6699 case PACKET_OK:
6700 break;
6701 case PACKET_UNKNOWN:
e42de8c7 6702 error (_("No support for interrupting the remote target."));
de979965 6703 case PACKET_ERROR:
8d64371b 6704 error (_("Interrupting target failed: %s"), rs->buf.data ());
de979965 6705 }
de979965
PA
6706}
6707
bfedc46a 6708/* Implement the to_stop function for the remote targets. */
74531fed 6709
f6ac5f3d
PA
6710void
6711remote_target::stop (ptid_t ptid)
c906108c 6712{
7a292a7a 6713 if (remote_debug)
0f71a2f6 6714 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 6715
6efcd9a8 6716 if (target_is_non_stop_p ())
74531fed 6717 remote_stop_ns (ptid);
c906108c 6718 else
bfedc46a
PA
6719 {
6720 /* We don't currently have a way to transparently pause the
6721 remote target in all-stop mode. Interrupt it instead. */
de979965 6722 remote_interrupt_as ();
bfedc46a
PA
6723 }
6724}
6725
6726/* Implement the to_interrupt function for the remote targets. */
6727
f6ac5f3d
PA
6728void
6729remote_target::interrupt ()
bfedc46a
PA
6730{
6731 if (remote_debug)
6732 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6733
e42de8c7
PA
6734 if (target_is_non_stop_p ())
6735 remote_interrupt_ns ();
bfedc46a 6736 else
e42de8c7 6737 remote_interrupt_as ();
c906108c
SS
6738}
6739
93692b58
PA
6740/* Implement the to_pass_ctrlc function for the remote targets. */
6741
f6ac5f3d
PA
6742void
6743remote_target::pass_ctrlc ()
93692b58
PA
6744{
6745 struct remote_state *rs = get_remote_state ();
6746
6747 if (remote_debug)
6748 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6749
6750 /* If we're starting up, we're not fully synced yet. Quit
6751 immediately. */
6752 if (rs->starting_up)
6753 quit ();
6754 /* If ^C has already been sent once, offer to disconnect. */
6755 else if (rs->ctrlc_pending_p)
6756 interrupt_query ();
6757 else
e671cd59 6758 target_interrupt ();
93692b58
PA
6759}
6760
c906108c
SS
6761/* Ask the user what to do when an interrupt is received. */
6762
6b8edb51
PA
6763void
6764remote_target::interrupt_query ()
c906108c 6765{
abc56d60 6766 struct remote_state *rs = get_remote_state ();
c906108c 6767
abc56d60 6768 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 6769 {
abc56d60
PA
6770 if (query (_("The target is not responding to interrupt requests.\n"
6771 "Stop debugging it? ")))
74531fed 6772 {
78a095c3 6773 remote_unpush_target ();
abc56d60 6774 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
6775 }
6776 }
abc56d60
PA
6777 else
6778 {
6779 if (query (_("Interrupted while waiting for the program.\n"
6780 "Give up waiting? ")))
6781 quit ();
6782 }
c906108c
SS
6783}
6784
6426a772
JM
6785/* Enable/disable target terminal ownership. Most targets can use
6786 terminal groups to control terminal ownership. Remote targets are
6787 different in that explicit transfer of ownership to/from GDB/target
23860348 6788 is required. */
6426a772 6789
f6ac5f3d
PA
6790void
6791remote_target::terminal_inferior ()
6426a772 6792{
6426a772
JM
6793 /* NOTE: At this point we could also register our selves as the
6794 recipient of all input. Any characters typed could then be
23860348 6795 passed on down to the target. */
6426a772
JM
6796}
6797
f6ac5f3d
PA
6798void
6799remote_target::terminal_ours ()
6426a772 6800{
6426a772
JM
6801}
6802
176a6961 6803static void
05be00a8 6804remote_console_output (const char *msg)
c906108c 6805{
05be00a8 6806 const char *p;
c906108c 6807
c5aa993b 6808 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
6809 {
6810 char tb[2];
6811 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 6812
c906108c
SS
6813 tb[0] = c;
6814 tb[1] = 0;
43ff13b4 6815 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 6816 }
00db5b94
PA
6817 gdb_flush (gdb_stdtarg);
6818}
74531fed 6819
74531fed
PA
6820DEF_VEC_O(cached_reg_t);
6821
722247f1 6822typedef struct stop_reply
74531fed 6823{
722247f1 6824 struct notif_event base;
74531fed 6825
722247f1 6826 /* The identifier of the thread about this event */
74531fed
PA
6827 ptid_t ptid;
6828
340e3c99 6829 /* The remote state this event is associated with. When the remote
bcc75809
YQ
6830 connection, represented by a remote_state object, is closed,
6831 all the associated stop_reply events should be released. */
6832 struct remote_state *rs;
6833
74531fed
PA
6834 struct target_waitstatus ws;
6835
5cd63fda
PA
6836 /* The architecture associated with the expedited registers. */
6837 gdbarch *arch;
6838
15148d6a
PA
6839 /* Expedited registers. This makes remote debugging a bit more
6840 efficient for those targets that provide critical registers as
6841 part of their normal status mechanism (as another roundtrip to
6842 fetch them is avoided). */
74531fed
PA
6843 VEC(cached_reg_t) *regcache;
6844
f7e6eed5
PA
6845 enum target_stop_reason stop_reason;
6846
74531fed
PA
6847 CORE_ADDR watch_data_address;
6848
dc146f7c 6849 int core;
722247f1 6850} *stop_reply_p;
a744cf53 6851
74531fed
PA
6852static void
6853stop_reply_xfree (struct stop_reply *r)
6854{
f48ff2a7 6855 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
6856}
6857
221e1a37
PA
6858/* Return the length of the stop reply queue. */
6859
6b8edb51
PA
6860int
6861remote_target::stop_reply_queue_length ()
221e1a37 6862{
6b8edb51 6863 remote_state *rs = get_remote_state ();
953edf2b 6864 return rs->stop_reply_queue.size ();
221e1a37
PA
6865}
6866
6b8edb51
PA
6867void
6868remote_notif_stop_parse (remote_target *remote,
bb277751 6869 struct notif_client *self, const char *buf,
722247f1
YQ
6870 struct notif_event *event)
6871{
6b8edb51 6872 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
722247f1
YQ
6873}
6874
6875static void
6b8edb51 6876remote_notif_stop_ack (remote_target *remote,
bb277751 6877 struct notif_client *self, const char *buf,
722247f1
YQ
6878 struct notif_event *event)
6879{
6880 struct stop_reply *stop_reply = (struct stop_reply *) event;
6881
6882 /* acknowledge */
6b8edb51 6883 putpkt (remote, self->ack_command);
722247f1
YQ
6884
6885 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6b8edb51 6886 {
722247f1
YQ
6887 /* We got an unknown stop reply. */
6888 error (_("Unknown stop reply"));
6b8edb51 6889 }
722247f1 6890
6b8edb51 6891 remote->push_stop_reply (stop_reply);
722247f1
YQ
6892}
6893
6894static int
6b8edb51
PA
6895remote_notif_stop_can_get_pending_events (remote_target *remote,
6896 struct notif_client *self)
722247f1
YQ
6897{
6898 /* We can't get pending events in remote_notif_process for
6899 notification stop, and we have to do this in remote_wait_ns
6900 instead. If we fetch all queued events from stub, remote stub
6901 may exit and we have no chance to process them back in
6902 remote_wait_ns. */
6b8edb51
PA
6903 remote_state *rs = remote->get_remote_state ();
6904 mark_async_event_handler (rs->remote_async_inferior_event_token);
722247f1
YQ
6905 return 0;
6906}
6907
6908static void
6909stop_reply_dtr (struct notif_event *event)
6910{
6911 struct stop_reply *r = (struct stop_reply *) event;
d1dff226
AH
6912 cached_reg_t *reg;
6913 int ix;
6914
6915 for (ix = 0;
6916 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6917 ix++)
6918 xfree (reg->data);
722247f1
YQ
6919
6920 VEC_free (cached_reg_t, r->regcache);
6921}
6922
6923static struct notif_event *
6924remote_notif_stop_alloc_reply (void)
6925{
8d749320
SM
6926 /* We cast to a pointer to the "base class". */
6927 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
6928
6929 r->dtr = stop_reply_dtr;
6930
6931 return r;
6932}
6933
6934/* A client of notification Stop. */
6935
6936struct notif_client notif_client_stop =
6937{
6938 "Stop",
6939 "vStopped",
6940 remote_notif_stop_parse,
6941 remote_notif_stop_ack,
6942 remote_notif_stop_can_get_pending_events,
6943 remote_notif_stop_alloc_reply,
f48ff2a7 6944 REMOTE_NOTIF_STOP,
722247f1
YQ
6945};
6946
85ad3aaf 6947/* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
cbb8991c
DB
6948 the pid of the process that owns the threads we want to check, or
6949 -1 if we want to check all threads. */
6950
6951static int
6952is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6953 ptid_t thread_ptid)
6954{
6955 if (ws->kind == TARGET_WAITKIND_FORKED
6956 || ws->kind == TARGET_WAITKIND_VFORKED)
6957 {
e99b03dc 6958 if (event_pid == -1 || event_pid == thread_ptid.pid ())
cbb8991c
DB
6959 return 1;
6960 }
6961
6962 return 0;
6963}
6964
85ad3aaf
PA
6965/* Return the thread's pending status used to determine whether the
6966 thread is a fork parent stopped at a fork event. */
6967
6968static struct target_waitstatus *
6969thread_pending_fork_status (struct thread_info *thread)
6970{
6971 if (thread->suspend.waitstatus_pending_p)
6972 return &thread->suspend.waitstatus;
6973 else
6974 return &thread->pending_follow;
6975}
6976
6977/* Determine if THREAD is a pending fork parent thread. */
6978
6979static int
6980is_pending_fork_parent_thread (struct thread_info *thread)
6981{
6982 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6983 int pid = -1;
6984
6985 return is_pending_fork_parent (ws, pid, thread->ptid);
6986}
6987
cbb8991c
DB
6988/* If CONTEXT contains any fork child threads that have not been
6989 reported yet, remove them from the CONTEXT list. If such a
6990 thread exists it is because we are stopped at a fork catchpoint
6991 and have not yet called follow_fork, which will set up the
6992 host-side data structures for the new process. */
6993
6b8edb51
PA
6994void
6995remote_target::remove_new_fork_children (threads_listing_context *context)
cbb8991c 6996{
cbb8991c
DB
6997 int pid = -1;
6998 struct notif_client *notif = &notif_client_stop;
cbb8991c
DB
6999
7000 /* For any threads stopped at a fork event, remove the corresponding
7001 fork child threads from the CONTEXT list. */
08036331 7002 for (thread_info *thread : all_non_exited_threads ())
cbb8991c 7003 {
85ad3aaf 7004 struct target_waitstatus *ws = thread_pending_fork_status (thread);
cbb8991c
DB
7005
7006 if (is_pending_fork_parent (ws, pid, thread->ptid))
21fe1c75 7007 context->remove_thread (ws->value.related_pid);
cbb8991c
DB
7008 }
7009
7010 /* Check for any pending fork events (not reported or processed yet)
7011 in process PID and remove those fork child threads from the
7012 CONTEXT list as well. */
7013 remote_notif_get_pending_events (notif);
953edf2b
TT
7014 for (auto &event : get_remote_state ()->stop_reply_queue)
7015 if (event->ws.kind == TARGET_WAITKIND_FORKED
7016 || event->ws.kind == TARGET_WAITKIND_VFORKED
7017 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
7018 context->remove_thread (event->ws.value.related_pid);
85ad3aaf
PA
7019}
7020
7021/* Check whether any event pending in the vStopped queue would prevent
7022 a global or process wildcard vCont action. Clear
7023 *may_global_wildcard if we can't do a global wildcard (vCont;c),
7024 and clear the event inferior's may_wildcard_vcont flag if we can't
7025 do a process-wide wildcard resume (vCont;c:pPID.-1). */
7026
6b8edb51
PA
7027void
7028remote_target::check_pending_events_prevent_wildcard_vcont
7029 (int *may_global_wildcard)
85ad3aaf
PA
7030{
7031 struct notif_client *notif = &notif_client_stop;
7032
7033 remote_notif_get_pending_events (notif);
953edf2b
TT
7034 for (auto &event : get_remote_state ()->stop_reply_queue)
7035 {
7036 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
7037 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
7038 continue;
85ad3aaf 7039
953edf2b
TT
7040 if (event->ws.kind == TARGET_WAITKIND_FORKED
7041 || event->ws.kind == TARGET_WAITKIND_VFORKED)
7042 *may_global_wildcard = 0;
722247f1 7043
953edf2b 7044 struct inferior *inf = find_inferior_ptid (event->ptid);
722247f1 7045
953edf2b
TT
7046 /* This may be the first time we heard about this process.
7047 Regardless, we must not do a global wildcard resume, otherwise
7048 we'd resume this process too. */
7049 *may_global_wildcard = 0;
7050 if (inf != NULL)
7051 get_remote_inferior (inf)->may_wildcard_vcont = false;
722247f1 7052 }
722247f1
YQ
7053}
7054
f48ff2a7 7055/* Discard all pending stop replies of inferior INF. */
c906108c 7056
6b8edb51
PA
7057void
7058remote_target::discard_pending_stop_replies (struct inferior *inf)
c906108c 7059{
f48ff2a7
YQ
7060 struct stop_reply *reply;
7061 struct remote_state *rs = get_remote_state ();
7062 struct remote_notif_state *rns = rs->notif_state;
7063
7064 /* This function can be notified when an inferior exists. When the
7065 target is not remote, the notification state is NULL. */
7066 if (rs->remote_desc == NULL)
7067 return;
7068
7069 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 7070
74531fed 7071 /* Discard the in-flight notification. */
e99b03dc 7072 if (reply != NULL && reply->ptid.pid () == inf->pid)
74531fed 7073 {
722247f1 7074 stop_reply_xfree (reply);
f48ff2a7 7075 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 7076 }
c906108c 7077
74531fed
PA
7078 /* Discard the stop replies we have already pulled with
7079 vStopped. */
953edf2b
TT
7080 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7081 rs->stop_reply_queue.end (),
7082 [=] (const stop_reply_up &event)
7083 {
7084 return event->ptid.pid () == inf->pid;
7085 });
7086 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
bcc75809
YQ
7087}
7088
7089/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7 7090
6b8edb51
PA
7091void
7092remote_target::discard_pending_stop_replies_in_queue ()
f48ff2a7 7093{
6b8edb51 7094 remote_state *rs = get_remote_state ();
f48ff2a7 7095
f48ff2a7
YQ
7096 /* Discard the stop replies we have already pulled with
7097 vStopped. */
953edf2b
TT
7098 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7099 rs->stop_reply_queue.end (),
7100 [=] (const stop_reply_up &event)
7101 {
7102 return event->rs == rs;
7103 });
7104 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
74531fed 7105}
43ff13b4 7106
722247f1
YQ
7107/* Remove the first reply in 'stop_reply_queue' which matches
7108 PTID. */
2e9f7625 7109
6b8edb51
PA
7110struct stop_reply *
7111remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 7112{
953edf2b 7113 remote_state *rs = get_remote_state ();
722247f1 7114
953edf2b
TT
7115 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7116 rs->stop_reply_queue.end (),
7117 [=] (const stop_reply_up &event)
7118 {
7119 return event->ptid.matches (ptid);
7120 });
7121 struct stop_reply *result;
7122 if (iter == rs->stop_reply_queue.end ())
7123 result = nullptr;
7124 else
7125 {
7126 result = iter->release ();
7127 rs->stop_reply_queue.erase (iter);
7128 }
722247f1 7129
722247f1
YQ
7130 if (notif_debug)
7131 fprintf_unfiltered (gdb_stdlog,
7132 "notif: discard queued event: 'Stop' in %s\n",
7133 target_pid_to_str (ptid));
a744cf53 7134
953edf2b 7135 return result;
74531fed 7136}
75c99385 7137
74531fed
PA
7138/* Look for a queued stop reply belonging to PTID. If one is found,
7139 remove it from the queue, and return it. Returns NULL if none is
7140 found. If there are still queued events left to process, tell the
7141 event loop to get back to target_wait soon. */
e24a49d8 7142
6b8edb51
PA
7143struct stop_reply *
7144remote_target::queued_stop_reply (ptid_t ptid)
74531fed 7145{
953edf2b 7146 remote_state *rs = get_remote_state ();
722247f1 7147 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 7148
953edf2b 7149 if (!rs->stop_reply_queue.empty ())
6b8edb51 7150 {
6b8edb51
PA
7151 /* There's still at least an event left. */
7152 mark_async_event_handler (rs->remote_async_inferior_event_token);
7153 }
74531fed 7154
722247f1 7155 return r;
74531fed
PA
7156}
7157
7158/* Push a fully parsed stop reply in the stop reply queue. Since we
7159 know that we now have at least one queued event left to pass to the
7160 core side, tell the event loop to get back to target_wait soon. */
7161
6b8edb51
PA
7162void
7163remote_target::push_stop_reply (struct stop_reply *new_event)
74531fed 7164{
6b8edb51 7165 remote_state *rs = get_remote_state ();
953edf2b 7166 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
74531fed 7167
722247f1
YQ
7168 if (notif_debug)
7169 fprintf_unfiltered (gdb_stdlog,
7170 "notif: push 'Stop' %s to queue %d\n",
7171 target_pid_to_str (new_event->ptid),
953edf2b 7172 int (rs->stop_reply_queue.size ()));
74531fed 7173
6b8edb51 7174 mark_async_event_handler (rs->remote_async_inferior_event_token);
74531fed
PA
7175}
7176
7177/* Returns true if we have a stop reply for PTID. */
7178
6b8edb51
PA
7179int
7180remote_target::peek_stop_reply (ptid_t ptid)
74531fed 7181{
6b8edb51 7182 remote_state *rs = get_remote_state ();
953edf2b
TT
7183 for (auto &event : rs->stop_reply_queue)
7184 if (ptid == event->ptid
7185 && event->ws.kind == TARGET_WAITKIND_STOPPED)
7186 return 1;
7187 return 0;
74531fed
PA
7188}
7189
26d56a93
SL
7190/* Helper for remote_parse_stop_reply. Return nonzero if the substring
7191 starting with P and ending with PEND matches PREFIX. */
7192
7193static int
7194strprefix (const char *p, const char *pend, const char *prefix)
7195{
7196 for ( ; p < pend; p++, prefix++)
7197 if (*p != *prefix)
7198 return 0;
7199 return *prefix == '\0';
7200}
7201
74531fed
PA
7202/* Parse the stop reply in BUF. Either the function succeeds, and the
7203 result is stored in EVENT, or throws an error. */
7204
6b8edb51 7205void
bb277751 7206remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
74531fed 7207{
5cd63fda 7208 remote_arch_state *rsa = NULL;
74531fed 7209 ULONGEST addr;
256642e8 7210 const char *p;
94585166 7211 int skipregs = 0;
74531fed
PA
7212
7213 event->ptid = null_ptid;
bcc75809 7214 event->rs = get_remote_state ();
74531fed
PA
7215 event->ws.kind = TARGET_WAITKIND_IGNORE;
7216 event->ws.value.integer = 0;
f7e6eed5 7217 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 7218 event->regcache = NULL;
dc146f7c 7219 event->core = -1;
74531fed
PA
7220
7221 switch (buf[0])
7222 {
7223 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
7224 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7225 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7226 ss = signal number
7227 n... = register number
7228 r... = register contents
7229 */
7230
7231 p = &buf[3]; /* after Txx */
7232 while (*p)
7233 {
256642e8 7234 const char *p1;
cea39f65 7235 int fieldsize;
43ff13b4 7236
1f10ba14
PA
7237 p1 = strchr (p, ':');
7238 if (p1 == NULL)
7239 error (_("Malformed packet(a) (missing colon): %s\n\
7240Packet: '%s'\n"),
7241 p, buf);
7242 if (p == p1)
7243 error (_("Malformed packet(a) (missing register number): %s\n\
7244Packet: '%s'\n"),
7245 p, buf);
3c3bea1c 7246
1f10ba14
PA
7247 /* Some "registers" are actually extended stop information.
7248 Note if you're adding a new entry here: GDB 7.9 and
7249 earlier assume that all register "numbers" that start
7250 with an hex digit are real register numbers. Make sure
7251 the server only sends such a packet if it knows the
7252 client understands it. */
c8e38a49 7253
26d56a93 7254 if (strprefix (p, p1, "thread"))
1f10ba14 7255 event->ptid = read_ptid (++p1, &p);
82075af2
JS
7256 else if (strprefix (p, p1, "syscall_entry"))
7257 {
7258 ULONGEST sysno;
7259
7260 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7261 p = unpack_varlen_hex (++p1, &sysno);
7262 event->ws.value.syscall_number = (int) sysno;
7263 }
7264 else if (strprefix (p, p1, "syscall_return"))
7265 {
7266 ULONGEST sysno;
7267
7268 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7269 p = unpack_varlen_hex (++p1, &sysno);
7270 event->ws.value.syscall_number = (int) sysno;
7271 }
26d56a93
SL
7272 else if (strprefix (p, p1, "watch")
7273 || strprefix (p, p1, "rwatch")
7274 || strprefix (p, p1, "awatch"))
cea39f65 7275 {
f7e6eed5 7276 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
7277 p = unpack_varlen_hex (++p1, &addr);
7278 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 7279 }
26d56a93 7280 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
7281 {
7282 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7283
7284 /* Make sure the stub doesn't forget to indicate support
7285 with qSupported. */
7286 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7287 error (_("Unexpected swbreak stop reason"));
7288
7289 /* The value part is documented as "must be empty",
7290 though we ignore it, in case we ever decide to make
7291 use of it in a backward compatible way. */
8424cc97 7292 p = strchrnul (p1 + 1, ';');
f7e6eed5 7293 }
26d56a93 7294 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
7295 {
7296 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7297
7298 /* Make sure the stub doesn't forget to indicate support
7299 with qSupported. */
7300 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7301 error (_("Unexpected hwbreak stop reason"));
7302
7303 /* See above. */
8424cc97 7304 p = strchrnul (p1 + 1, ';');
f7e6eed5 7305 }
26d56a93 7306 else if (strprefix (p, p1, "library"))
cea39f65 7307 {
1f10ba14 7308 event->ws.kind = TARGET_WAITKIND_LOADED;
8424cc97 7309 p = strchrnul (p1 + 1, ';');
1f10ba14 7310 }
26d56a93 7311 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
7312 {
7313 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7314 /* p1 will indicate "begin" or "end", but it makes
7315 no difference for now, so ignore it. */
8424cc97 7316 p = strchrnul (p1 + 1, ';');
1f10ba14 7317 }
26d56a93 7318 else if (strprefix (p, p1, "core"))
1f10ba14
PA
7319 {
7320 ULONGEST c;
a744cf53 7321
1f10ba14
PA
7322 p = unpack_varlen_hex (++p1, &c);
7323 event->core = c;
cea39f65 7324 }
26d56a93 7325 else if (strprefix (p, p1, "fork"))
de0d863e
DB
7326 {
7327 event->ws.value.related_pid = read_ptid (++p1, &p);
7328 event->ws.kind = TARGET_WAITKIND_FORKED;
7329 }
26d56a93 7330 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
7331 {
7332 event->ws.value.related_pid = read_ptid (++p1, &p);
7333 event->ws.kind = TARGET_WAITKIND_VFORKED;
7334 }
26d56a93 7335 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
7336 {
7337 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
8424cc97 7338 p = strchrnul (p1 + 1, ';');
c269dbdb 7339 }
6ab24463 7340 else if (strprefix (p, p1, "exec"))
94585166
DB
7341 {
7342 ULONGEST ignored;
94585166
DB
7343 int pathlen;
7344
7345 /* Determine the length of the execd pathname. */
7346 p = unpack_varlen_hex (++p1, &ignored);
7347 pathlen = (p - p1) / 2;
7348
7349 /* Save the pathname for event reporting and for
7350 the next run command. */
b671c7fb
TS
7351 char *pathname = (char *) xmalloc (pathlen + 1);
7352 struct cleanup *old_chain = make_cleanup (xfree, pathname);
94585166
DB
7353 hex2bin (p1, (gdb_byte *) pathname, pathlen);
7354 pathname[pathlen] = '\0';
b671c7fb 7355 discard_cleanups (old_chain);
94585166
DB
7356
7357 /* This is freed during event handling. */
b671c7fb 7358 event->ws.value.execd_pathname = pathname;
94585166
DB
7359 event->ws.kind = TARGET_WAITKIND_EXECD;
7360
7361 /* Skip the registers included in this packet, since
7362 they may be for an architecture different from the
7363 one used by the original program. */
7364 skipregs = 1;
7365 }
65706a29
PA
7366 else if (strprefix (p, p1, "create"))
7367 {
7368 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
8424cc97 7369 p = strchrnul (p1 + 1, ';');
65706a29 7370 }
cea39f65
MS
7371 else
7372 {
1f10ba14 7373 ULONGEST pnum;
256642e8 7374 const char *p_temp;
1f10ba14 7375
94585166
DB
7376 if (skipregs)
7377 {
8424cc97 7378 p = strchrnul (p1 + 1, ';');
94585166
DB
7379 p++;
7380 continue;
7381 }
7382
1f10ba14
PA
7383 /* Maybe a real ``P'' register number. */
7384 p_temp = unpack_varlen_hex (p, &pnum);
7385 /* If the first invalid character is the colon, we got a
7386 register number. Otherwise, it's an unknown stop
7387 reason. */
7388 if (p_temp == p1)
7389 {
5cd63fda
PA
7390 /* If we haven't parsed the event's thread yet, find
7391 it now, in order to find the architecture of the
7392 reported expedited registers. */
7393 if (event->ptid == null_ptid)
7394 {
7395 const char *thr = strstr (p1 + 1, ";thread:");
7396 if (thr != NULL)
7397 event->ptid = read_ptid (thr + strlen (";thread:"),
7398 NULL);
7399 else
3cada740
PA
7400 {
7401 /* Either the current thread hasn't changed,
7402 or the inferior is not multi-threaded.
7403 The event must be for the thread we last
7404 set as (or learned as being) current. */
7405 event->ptid = event->rs->general_thread;
7406 }
5cd63fda
PA
7407 }
7408
7409 if (rsa == NULL)
7410 {
7411 inferior *inf = (event->ptid == null_ptid
7412 ? NULL
7413 : find_inferior_ptid (event->ptid));
7414 /* If this is the first time we learn anything
7415 about this process, skip the registers
7416 included in this packet, since we don't yet
7417 know which architecture to use to parse them.
7418 We'll determine the architecture later when
7419 we process the stop reply and retrieve the
7420 target description, via
7421 remote_notice_new_inferior ->
7422 post_create_inferior. */
7423 if (inf == NULL)
7424 {
7425 p = strchrnul (p1 + 1, ';');
7426 p++;
7427 continue;
7428 }
7429
7430 event->arch = inf->gdbarch;
9d6eea31 7431 rsa = event->rs->get_remote_arch_state (event->arch);
5cd63fda
PA
7432 }
7433
7434 packet_reg *reg
7435 = packet_reg_from_pnum (event->arch, rsa, pnum);
1f10ba14 7436 cached_reg_t cached_reg;
43ff13b4 7437
1f10ba14
PA
7438 if (reg == NULL)
7439 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 7440Packet: '%s'\n"),
1f10ba14 7441 hex_string (pnum), p, buf);
c8e38a49 7442
1f10ba14 7443 cached_reg.num = reg->regnum;
d1dff226 7444 cached_reg.data = (gdb_byte *)
5cd63fda 7445 xmalloc (register_size (event->arch, reg->regnum));
4100683b 7446
1f10ba14
PA
7447 p = p1 + 1;
7448 fieldsize = hex2bin (p, cached_reg.data,
5cd63fda 7449 register_size (event->arch, reg->regnum));
1f10ba14 7450 p += 2 * fieldsize;
5cd63fda 7451 if (fieldsize < register_size (event->arch, reg->regnum))
1f10ba14 7452 warning (_("Remote reply is too short: %s"), buf);
74531fed 7453
1f10ba14
PA
7454 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7455 }
7456 else
7457 {
7458 /* Not a number. Silently skip unknown optional
7459 info. */
8424cc97 7460 p = strchrnul (p1 + 1, ';');
1f10ba14 7461 }
cea39f65 7462 }
c8e38a49 7463
cea39f65
MS
7464 if (*p != ';')
7465 error (_("Remote register badly formatted: %s\nhere: %s"),
7466 buf, p);
7467 ++p;
7468 }
5b5596ff
PA
7469
7470 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7471 break;
7472
c8e38a49
PA
7473 /* fall through */
7474 case 'S': /* Old style status, just signal only. */
3a09da41
PA
7475 {
7476 int sig;
7477
7478 event->ws.kind = TARGET_WAITKIND_STOPPED;
7479 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7480 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7481 event->ws.value.sig = (enum gdb_signal) sig;
7482 else
7483 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7484 }
c8e38a49 7485 break;
65706a29
PA
7486 case 'w': /* Thread exited. */
7487 {
65706a29
PA
7488 ULONGEST value;
7489
7490 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7491 p = unpack_varlen_hex (&buf[1], &value);
7492 event->ws.value.integer = value;
7493 if (*p != ';')
7494 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 7495 event->ptid = read_ptid (++p, NULL);
65706a29
PA
7496 break;
7497 }
c8e38a49
PA
7498 case 'W': /* Target exited. */
7499 case 'X':
7500 {
c8e38a49
PA
7501 int pid;
7502 ULONGEST value;
82f73884 7503
c8e38a49
PA
7504 /* GDB used to accept only 2 hex chars here. Stubs should
7505 only send more if they detect GDB supports multi-process
7506 support. */
7507 p = unpack_varlen_hex (&buf[1], &value);
82f73884 7508
c8e38a49
PA
7509 if (buf[0] == 'W')
7510 {
7511 /* The remote process exited. */
74531fed
PA
7512 event->ws.kind = TARGET_WAITKIND_EXITED;
7513 event->ws.value.integer = value;
c8e38a49
PA
7514 }
7515 else
7516 {
7517 /* The remote process exited with a signal. */
74531fed 7518 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
7519 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7520 event->ws.value.sig = (enum gdb_signal) value;
7521 else
7522 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 7523 }
82f73884 7524
c8e38a49 7525 /* If no process is specified, assume inferior_ptid. */
e99b03dc 7526 pid = inferior_ptid.pid ();
c8e38a49
PA
7527 if (*p == '\0')
7528 ;
7529 else if (*p == ';')
7530 {
7531 p++;
7532
0b24eb2d 7533 if (*p == '\0')
82f73884 7534 ;
61012eef 7535 else if (startswith (p, "process:"))
82f73884 7536 {
c8e38a49 7537 ULONGEST upid;
a744cf53 7538
c8e38a49
PA
7539 p += sizeof ("process:") - 1;
7540 unpack_varlen_hex (p, &upid);
7541 pid = upid;
82f73884
PA
7542 }
7543 else
7544 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 7545 }
c8e38a49
PA
7546 else
7547 error (_("unknown stop reply packet: %s"), buf);
f2907e49 7548 event->ptid = ptid_t (pid);
74531fed
PA
7549 }
7550 break;
f2faf941
PA
7551 case 'N':
7552 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7553 event->ptid = minus_one_ptid;
7554 break;
74531fed
PA
7555 }
7556
d7e15655 7557 if (target_is_non_stop_p () && event->ptid == null_ptid)
74531fed
PA
7558 error (_("No process or thread specified in stop reply: %s"), buf);
7559}
7560
722247f1
YQ
7561/* When the stub wants to tell GDB about a new notification reply, it
7562 sends a notification (%Stop, for example). Those can come it at
7563 any time, hence, we have to make sure that any pending
7564 putpkt/getpkt sequence we're making is finished, before querying
7565 the stub for more events with the corresponding ack command
7566 (vStopped, for example). E.g., if we started a vStopped sequence
7567 immediately upon receiving the notification, something like this
7568 could happen:
74531fed
PA
7569
7570 1.1) --> Hg 1
7571 1.2) <-- OK
7572 1.3) --> g
7573 1.4) <-- %Stop
7574 1.5) --> vStopped
7575 1.6) <-- (registers reply to step #1.3)
7576
7577 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7578 query.
7579
796cb314 7580 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
7581 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7582 doing whatever we were doing:
7583
7584 2.1) --> Hg 1
7585 2.2) <-- OK
7586 2.3) --> g
7587 2.4) <-- %Stop
7588 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7589 2.5) <-- (registers reply to step #2.3)
7590
7591 Eventualy after step #2.5, we return to the event loop, which
7592 notices there's an event on the
7593 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7594 associated callback --- the function below. At this point, we're
7595 always safe to start a vStopped sequence. :
7596
7597 2.6) --> vStopped
7598 2.7) <-- T05 thread:2
7599 2.8) --> vStopped
7600 2.9) --> OK
7601*/
7602
722247f1 7603void
6b8edb51 7604remote_target::remote_notif_get_pending_events (notif_client *nc)
74531fed
PA
7605{
7606 struct remote_state *rs = get_remote_state ();
74531fed 7607
f48ff2a7 7608 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 7609 {
722247f1
YQ
7610 if (notif_debug)
7611 fprintf_unfiltered (gdb_stdlog,
7612 "notif: process: '%s' ack pending event\n",
7613 nc->name);
74531fed 7614
722247f1 7615 /* acknowledge */
8d64371b
TT
7616 nc->ack (this, nc, rs->buf.data (),
7617 rs->notif_state->pending_event[nc->id]);
f48ff2a7 7618 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
7619
7620 while (1)
7621 {
8d64371b
TT
7622 getpkt (&rs->buf, 0);
7623 if (strcmp (rs->buf.data (), "OK") == 0)
74531fed
PA
7624 break;
7625 else
8d64371b 7626 remote_notif_ack (this, nc, rs->buf.data ());
74531fed
PA
7627 }
7628 }
722247f1
YQ
7629 else
7630 {
7631 if (notif_debug)
7632 fprintf_unfiltered (gdb_stdlog,
7633 "notif: process: '%s' no pending reply\n",
7634 nc->name);
7635 }
74531fed
PA
7636}
7637
6b8edb51
PA
7638/* Wrapper around remote_target::remote_notif_get_pending_events to
7639 avoid having to export the whole remote_target class. */
7640
7641void
7642remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7643{
7644 remote->remote_notif_get_pending_events (nc);
7645}
7646
74531fed
PA
7647/* Called when it is decided that STOP_REPLY holds the info of the
7648 event that is to be returned to the core. This function always
7649 destroys STOP_REPLY. */
7650
6b8edb51
PA
7651ptid_t
7652remote_target::process_stop_reply (struct stop_reply *stop_reply,
7653 struct target_waitstatus *status)
74531fed
PA
7654{
7655 ptid_t ptid;
7656
7657 *status = stop_reply->ws;
7658 ptid = stop_reply->ptid;
7659
7660 /* If no thread/process was reported by the stub, assume the current
7661 inferior. */
d7e15655 7662 if (ptid == null_ptid)
74531fed
PA
7663 ptid = inferior_ptid;
7664
5f3563ea 7665 if (status->kind != TARGET_WAITKIND_EXITED
f2faf941
PA
7666 && status->kind != TARGET_WAITKIND_SIGNALLED
7667 && status->kind != TARGET_WAITKIND_NO_RESUMED)
74531fed 7668 {
5f3563ea
PA
7669 /* Expedited registers. */
7670 if (stop_reply->regcache)
7671 {
217f1f79 7672 struct regcache *regcache
5cd63fda 7673 = get_thread_arch_regcache (ptid, stop_reply->arch);
5f3563ea
PA
7674 cached_reg_t *reg;
7675 int ix;
7676
7677 for (ix = 0;
d1dff226 7678 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
5f3563ea 7679 ix++)
d1dff226 7680 {
73e1c03f 7681 regcache->raw_supply (reg->num, reg->data);
d1dff226
AH
7682 xfree (reg->data);
7683 }
7684
5f3563ea
PA
7685 VEC_free (cached_reg_t, stop_reply->regcache);
7686 }
74531fed 7687
1941c569 7688 remote_notice_new_inferior (ptid, 0);
7aabaf9d 7689 remote_thread_info *remote_thr = get_remote_thread_info (ptid);
799a2abe
PA
7690 remote_thr->core = stop_reply->core;
7691 remote_thr->stop_reason = stop_reply->stop_reason;
7692 remote_thr->watch_data_address = stop_reply->watch_data_address;
85ad3aaf 7693 remote_thr->vcont_resumed = 0;
74531fed
PA
7694 }
7695
74531fed
PA
7696 stop_reply_xfree (stop_reply);
7697 return ptid;
7698}
7699
7700/* The non-stop mode version of target_wait. */
7701
6b8edb51
PA
7702ptid_t
7703remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
7704{
7705 struct remote_state *rs = get_remote_state ();
74531fed
PA
7706 struct stop_reply *stop_reply;
7707 int ret;
fee9eda9 7708 int is_notif = 0;
74531fed
PA
7709
7710 /* If in non-stop mode, get out of getpkt even if a
7711 notification is received. */
7712
8d64371b 7713 ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
74531fed
PA
7714 while (1)
7715 {
fee9eda9 7716 if (ret != -1 && !is_notif)
74531fed
PA
7717 switch (rs->buf[0])
7718 {
7719 case 'E': /* Error of some sort. */
7720 /* We're out of sync with the target now. Did it continue
7721 or not? We can't tell which thread it was in non-stop,
7722 so just ignore this. */
8d64371b 7723 warning (_("Remote failure reply: %s"), rs->buf.data ());
74531fed
PA
7724 break;
7725 case 'O': /* Console output. */
8d64371b 7726 remote_console_output (&rs->buf[1]);
74531fed
PA
7727 break;
7728 default:
8d64371b 7729 warning (_("Invalid remote reply: %s"), rs->buf.data ());
74531fed
PA
7730 break;
7731 }
7732
7733 /* Acknowledge a pending stop reply that may have arrived in the
7734 mean time. */
f48ff2a7 7735 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 7736 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
7737
7738 /* If indeed we noticed a stop reply, we're done. */
7739 stop_reply = queued_stop_reply (ptid);
7740 if (stop_reply != NULL)
7741 return process_stop_reply (stop_reply, status);
7742
47608cb1 7743 /* Still no event. If we're just polling for an event, then
74531fed 7744 return to the event loop. */
47608cb1 7745 if (options & TARGET_WNOHANG)
74531fed
PA
7746 {
7747 status->kind = TARGET_WAITKIND_IGNORE;
7748 return minus_one_ptid;
7749 }
7750
47608cb1 7751 /* Otherwise do a blocking wait. */
8d64371b 7752 ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
74531fed
PA
7753 }
7754}
7755
7756/* Wait until the remote machine stops, then return, storing status in
7757 STATUS just as `wait' would. */
7758
6b8edb51
PA
7759ptid_t
7760remote_target::wait_as (ptid_t ptid, target_waitstatus *status, int options)
74531fed
PA
7761{
7762 struct remote_state *rs = get_remote_state ();
74531fed 7763 ptid_t event_ptid = null_ptid;
cea39f65 7764 char *buf;
74531fed
PA
7765 struct stop_reply *stop_reply;
7766
47608cb1
PA
7767 again:
7768
74531fed
PA
7769 status->kind = TARGET_WAITKIND_IGNORE;
7770 status->value.integer = 0;
7771
7772 stop_reply = queued_stop_reply (ptid);
7773 if (stop_reply != NULL)
7774 return process_stop_reply (stop_reply, status);
7775
7776 if (rs->cached_wait_status)
7777 /* Use the cached wait status, but only once. */
7778 rs->cached_wait_status = 0;
7779 else
7780 {
7781 int ret;
722247f1 7782 int is_notif;
567420d1 7783 int forever = ((options & TARGET_WNOHANG) == 0
6b8edb51 7784 && rs->wait_forever_enabled_p);
567420d1
PA
7785
7786 if (!rs->waiting_for_stop_reply)
7787 {
7788 status->kind = TARGET_WAITKIND_NO_RESUMED;
7789 return minus_one_ptid;
7790 }
74531fed 7791
74531fed
PA
7792 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7793 _never_ wait for ever -> test on target_is_async_p().
7794 However, before we do that we need to ensure that the caller
7795 knows how to take the target into/out of async mode. */
8d64371b 7796 ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
722247f1
YQ
7797
7798 /* GDB gets a notification. Return to core as this event is
7799 not interesting. */
7800 if (ret != -1 && is_notif)
7801 return minus_one_ptid;
567420d1
PA
7802
7803 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7804 return minus_one_ptid;
74531fed
PA
7805 }
7806
8d64371b 7807 buf = rs->buf.data ();
74531fed 7808
3a29589a
DJ
7809 /* Assume that the target has acknowledged Ctrl-C unless we receive
7810 an 'F' or 'O' packet. */
7811 if (buf[0] != 'F' && buf[0] != 'O')
7812 rs->ctrlc_pending_p = 0;
7813
74531fed
PA
7814 switch (buf[0])
7815 {
7816 case 'E': /* Error of some sort. */
7817 /* We're out of sync with the target now. Did it continue or
7818 not? Not is more likely, so report a stop. */
29090fb6
LM
7819 rs->waiting_for_stop_reply = 0;
7820
74531fed
PA
7821 warning (_("Remote failure reply: %s"), buf);
7822 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 7823 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
7824 break;
7825 case 'F': /* File-I/O request. */
e42e5352
YQ
7826 /* GDB may access the inferior memory while handling the File-I/O
7827 request, but we don't want GDB accessing memory while waiting
7828 for a stop reply. See the comments in putpkt_binary. Set
7829 waiting_for_stop_reply to 0 temporarily. */
7830 rs->waiting_for_stop_reply = 0;
6b8edb51 7831 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
3a29589a 7832 rs->ctrlc_pending_p = 0;
e42e5352
YQ
7833 /* GDB handled the File-I/O request, and the target is running
7834 again. Keep waiting for events. */
7835 rs->waiting_for_stop_reply = 1;
74531fed 7836 break;
f2faf941 7837 case 'N': case 'T': case 'S': case 'X': case 'W':
74531fed 7838 {
29090fb6
LM
7839 /* There is a stop reply to handle. */
7840 rs->waiting_for_stop_reply = 0;
7841
7842 stop_reply
6b8edb51
PA
7843 = (struct stop_reply *) remote_notif_parse (this,
7844 &notif_client_stop,
8d64371b 7845 rs->buf.data ());
74531fed 7846
74531fed 7847 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
7848 break;
7849 }
7850 case 'O': /* Console output. */
7851 remote_console_output (buf + 1);
c8e38a49
PA
7852 break;
7853 case '\0':
b73be471 7854 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
7855 {
7856 /* Zero length reply means that we tried 'S' or 'C' and the
7857 remote system doesn't support it. */
223ffa71 7858 target_terminal::ours_for_output ();
c8e38a49
PA
7859 printf_filtered
7860 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
7861 gdb_signal_to_name (rs->last_sent_signal));
7862 rs->last_sent_signal = GDB_SIGNAL_0;
223ffa71 7863 target_terminal::inferior ();
c8e38a49 7864
f5c4fcd9
TT
7865 strcpy (buf, rs->last_sent_step ? "s" : "c");
7866 putpkt (buf);
c8e38a49 7867 break;
43ff13b4 7868 }
86a73007 7869 /* fallthrough */
c8e38a49
PA
7870 default:
7871 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 7872 break;
43ff13b4 7873 }
c8e38a49 7874
f2faf941
PA
7875 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7876 return minus_one_ptid;
7877 else if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
7878 {
7879 /* Nothing interesting happened. If we're doing a non-blocking
7880 poll, we're done. Otherwise, go back to waiting. */
7881 if (options & TARGET_WNOHANG)
7882 return minus_one_ptid;
7883 else
7884 goto again;
7885 }
74531fed
PA
7886 else if (status->kind != TARGET_WAITKIND_EXITED
7887 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884 7888 {
d7e15655 7889 if (event_ptid != null_ptid)
47f8a51d 7890 record_currthread (rs, event_ptid);
82f73884
PA
7891 else
7892 event_ptid = inferior_ptid;
43ff13b4 7893 }
74531fed
PA
7894 else
7895 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 7896 record_currthread (rs, minus_one_ptid);
79d7f229 7897
82f73884 7898 return event_ptid;
43ff13b4
JM
7899}
7900
74531fed
PA
7901/* Wait until the remote machine stops, then return, storing status in
7902 STATUS just as `wait' would. */
7903
f6ac5f3d
PA
7904ptid_t
7905remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
7906{
7907 ptid_t event_ptid;
7908
6efcd9a8 7909 if (target_is_non_stop_p ())
6b8edb51 7910 event_ptid = wait_ns (ptid, status, options);
74531fed 7911 else
6b8edb51 7912 event_ptid = wait_as (ptid, status, options);
c8e38a49 7913
d9d41e78 7914 if (target_is_async_p ())
c8e38a49 7915 {
6b8edb51
PA
7916 remote_state *rs = get_remote_state ();
7917
74531fed
PA
7918 /* If there are are events left in the queue tell the event loop
7919 to return here. */
953edf2b 7920 if (!rs->stop_reply_queue.empty ())
6b8edb51 7921 mark_async_event_handler (rs->remote_async_inferior_event_token);
c8e38a49 7922 }
c8e38a49
PA
7923
7924 return event_ptid;
7925}
7926
74ca34ce 7927/* Fetch a single register using a 'p' packet. */
c906108c 7928
6b8edb51
PA
7929int
7930remote_target::fetch_register_using_p (struct regcache *regcache,
7931 packet_reg *reg)
b96ec7ac 7932{
ac7936df 7933 struct gdbarch *gdbarch = regcache->arch ();
b96ec7ac 7934 struct remote_state *rs = get_remote_state ();
2e9f7625 7935 char *buf, *p;
9890e433 7936 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
b96ec7ac
AC
7937 int i;
7938
4082afcc 7939 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
7940 return 0;
7941
7942 if (reg->pnum == -1)
7943 return 0;
7944
8d64371b 7945 p = rs->buf.data ();
fcad0fa4 7946 *p++ = 'p';
74ca34ce 7947 p += hexnumstr (p, reg->pnum);
fcad0fa4 7948 *p++ = '\0';
1f4437a4 7949 putpkt (rs->buf);
8d64371b 7950 getpkt (&rs->buf, 0);
3f9a994c 7951
8d64371b 7952 buf = rs->buf.data ();
2e9f7625 7953
8d64371b 7954 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_p]))
74ca34ce
DJ
7955 {
7956 case PACKET_OK:
7957 break;
7958 case PACKET_UNKNOWN:
7959 return 0;
7960 case PACKET_ERROR:
27a9c0bf 7961 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
ac7936df 7962 gdbarch_register_name (regcache->arch (),
27a9c0bf
MS
7963 reg->regnum),
7964 buf);
74ca34ce 7965 }
3f9a994c
JB
7966
7967 /* If this register is unfetchable, tell the regcache. */
7968 if (buf[0] == 'x')
8480adf2 7969 {
73e1c03f 7970 regcache->raw_supply (reg->regnum, NULL);
8480adf2 7971 return 1;
b96ec7ac 7972 }
b96ec7ac 7973
3f9a994c
JB
7974 /* Otherwise, parse and supply the value. */
7975 p = buf;
7976 i = 0;
7977 while (p[0] != 0)
7978 {
7979 if (p[1] == 0)
74ca34ce 7980 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
7981
7982 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7983 p += 2;
7984 }
73e1c03f 7985 regcache->raw_supply (reg->regnum, regp);
3f9a994c 7986 return 1;
b96ec7ac
AC
7987}
7988
74ca34ce
DJ
7989/* Fetch the registers included in the target's 'g' packet. */
7990
6b8edb51
PA
7991int
7992remote_target::send_g_packet ()
c906108c 7993{
d01949b6 7994 struct remote_state *rs = get_remote_state ();
cea39f65 7995 int buf_len;
c906108c 7996
8d64371b 7997 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
b75abf5b 7998 putpkt (rs->buf);
8d64371b 7999 getpkt (&rs->buf, 0);
b75abf5b
AK
8000 if (packet_check_result (rs->buf) == PACKET_ERROR)
8001 error (_("Could not read registers; remote failure reply '%s'"),
8d64371b 8002 rs->buf.data ());
c906108c 8003
29709017
DJ
8004 /* We can get out of synch in various cases. If the first character
8005 in the buffer is not a hex character, assume that has happened
8006 and try to fetch another packet to read. */
8007 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8008 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8009 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8010 && rs->buf[0] != 'x') /* New: unavailable register value. */
8011 {
8012 if (remote_debug)
8013 fprintf_unfiltered (gdb_stdlog,
8014 "Bad register packet; fetching a new packet\n");
8d64371b 8015 getpkt (&rs->buf, 0);
29709017
DJ
8016 }
8017
8d64371b 8018 buf_len = strlen (rs->buf.data ());
74ca34ce
DJ
8019
8020 /* Sanity check the received packet. */
8021 if (buf_len % 2 != 0)
8d64371b 8022 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
29709017
DJ
8023
8024 return buf_len / 2;
8025}
8026
6b8edb51
PA
8027void
8028remote_target::process_g_packet (struct regcache *regcache)
29709017 8029{
ac7936df 8030 struct gdbarch *gdbarch = regcache->arch ();
29709017 8031 struct remote_state *rs = get_remote_state ();
9d6eea31 8032 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
29709017
DJ
8033 int i, buf_len;
8034 char *p;
8035 char *regs;
8036
8d64371b 8037 buf_len = strlen (rs->buf.data ());
29709017
DJ
8038
8039 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce 8040 if (buf_len > 2 * rsa->sizeof_g_packet)
fc809827 8041 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8d64371b
TT
8042 "bytes): %s"),
8043 rsa->sizeof_g_packet, buf_len / 2,
8044 rs->buf.data ());
74ca34ce
DJ
8045
8046 /* Save the size of the packet sent to us by the target. It is used
8047 as a heuristic when determining the max size of packets that the
8048 target can safely receive. */
8049 if (rsa->actual_register_packet_size == 0)
8050 rsa->actual_register_packet_size = buf_len;
8051
8052 /* If this is smaller than we guessed the 'g' packet would be,
8053 update our records. A 'g' reply that doesn't include a register's
8054 value implies either that the register is not available, or that
8055 the 'p' packet must be used. */
8056 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 8057 {
9dc193c3 8058 long sizeof_g_packet = buf_len / 2;
74ca34ce 8059
4a22f64d 8060 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 8061 {
9dc193c3
LF
8062 long offset = rsa->regs[i].offset;
8063 long reg_size = register_size (gdbarch, i);
8064
74ca34ce
DJ
8065 if (rsa->regs[i].pnum == -1)
8066 continue;
8067
9dc193c3 8068 if (offset >= sizeof_g_packet)
74ca34ce 8069 rsa->regs[i].in_g_packet = 0;
9dc193c3
LF
8070 else if (offset + reg_size > sizeof_g_packet)
8071 error (_("Truncated register %d in remote 'g' packet"), i);
b96ec7ac 8072 else
74ca34ce 8073 rsa->regs[i].in_g_packet = 1;
b96ec7ac 8074 }
9dc193c3
LF
8075
8076 /* Looks valid enough, we can assume this is the correct length
8077 for a 'g' packet. It's important not to adjust
8078 rsa->sizeof_g_packet if we have truncated registers otherwise
8079 this "if" won't be run the next time the method is called
8080 with a packet of the same size and one of the internal errors
8081 below will trigger instead. */
8082 rsa->sizeof_g_packet = sizeof_g_packet;
74ca34ce 8083 }
b323314b 8084
224c3ddb 8085 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
8086
8087 /* Unimplemented registers read as all bits zero. */
ea9c271d 8088 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 8089
c906108c
SS
8090 /* Reply describes registers byte by byte, each byte encoded as two
8091 hex characters. Suck them all up, then supply them to the
8092 register cacheing/storage mechanism. */
8093
8d64371b 8094 p = rs->buf.data ();
ea9c271d 8095 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 8096 {
74ca34ce
DJ
8097 if (p[0] == 0 || p[1] == 0)
8098 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8099 internal_error (__FILE__, __LINE__,
9b20d036 8100 _("unexpected end of 'g' packet reply"));
74ca34ce 8101
c906108c 8102 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 8103 regs[i] = 0; /* 'x' */
c906108c
SS
8104 else
8105 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8106 p += 2;
8107 }
8108
a744cf53
MS
8109 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8110 {
8111 struct packet_reg *r = &rsa->regs[i];
9dc193c3 8112 long reg_size = register_size (gdbarch, i);
a744cf53
MS
8113
8114 if (r->in_g_packet)
8115 {
8d64371b 8116 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
a744cf53
MS
8117 /* This shouldn't happen - we adjusted in_g_packet above. */
8118 internal_error (__FILE__, __LINE__,
9b20d036 8119 _("unexpected end of 'g' packet reply"));
a744cf53
MS
8120 else if (rs->buf[r->offset * 2] == 'x')
8121 {
8d64371b 8122 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
a744cf53
MS
8123 /* The register isn't available, mark it as such (at
8124 the same time setting the value to zero). */
73e1c03f 8125 regcache->raw_supply (r->regnum, NULL);
a744cf53
MS
8126 }
8127 else
73e1c03f 8128 regcache->raw_supply (r->regnum, regs + r->offset);
a744cf53
MS
8129 }
8130 }
c906108c
SS
8131}
8132
6b8edb51
PA
8133void
8134remote_target::fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
8135{
8136 send_g_packet ();
56be3814 8137 process_g_packet (regcache);
29709017
DJ
8138}
8139
e6e4e701
PA
8140/* Make the remote selected traceframe match GDB's selected
8141 traceframe. */
8142
6b8edb51
PA
8143void
8144remote_target::set_remote_traceframe ()
e6e4e701
PA
8145{
8146 int newnum;
262e1174 8147 struct remote_state *rs = get_remote_state ();
e6e4e701 8148
262e1174 8149 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
8150 return;
8151
8152 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 8153 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
8154
8155 newnum = target_trace_find (tfind_number,
8156 get_traceframe_number (), 0, 0, NULL);
8157
8158 /* Should not happen. If it does, all bets are off. */
8159 if (newnum != get_traceframe_number ())
8160 warning (_("could not set remote traceframe"));
8161}
8162
f6ac5f3d
PA
8163void
8164remote_target::fetch_registers (struct regcache *regcache, int regnum)
74ca34ce 8165{
ac7936df 8166 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8167 struct remote_state *rs = get_remote_state ();
8168 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8169 int i;
8170
e6e4e701 8171 set_remote_traceframe ();
222312d3 8172 set_general_thread (regcache->ptid ());
74ca34ce
DJ
8173
8174 if (regnum >= 0)
8175 {
5cd63fda 8176 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8177
74ca34ce
DJ
8178 gdb_assert (reg != NULL);
8179
8180 /* If this register might be in the 'g' packet, try that first -
8181 we are likely to read more than one register. If this is the
8182 first 'g' packet, we might be overly optimistic about its
8183 contents, so fall back to 'p'. */
8184 if (reg->in_g_packet)
8185 {
56be3814 8186 fetch_registers_using_g (regcache);
74ca34ce
DJ
8187 if (reg->in_g_packet)
8188 return;
8189 }
8190
56be3814 8191 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
8192 return;
8193
8194 /* This register is not available. */
73e1c03f 8195 regcache->raw_supply (reg->regnum, NULL);
74ca34ce
DJ
8196
8197 return;
8198 }
8199
56be3814 8200 fetch_registers_using_g (regcache);
74ca34ce 8201
5cd63fda 8202 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8203 if (!rsa->regs[i].in_g_packet)
56be3814 8204 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
8205 {
8206 /* This register is not available. */
73e1c03f 8207 regcache->raw_supply (i, NULL);
74ca34ce
DJ
8208 }
8209}
8210
c906108c
SS
8211/* Prepare to store registers. Since we may send them all (using a
8212 'G' request), we have to read out the ones we don't want to change
8213 first. */
8214
f6ac5f3d
PA
8215void
8216remote_target::prepare_to_store (struct regcache *regcache)
c906108c 8217{
9d6eea31
PA
8218 struct remote_state *rs = get_remote_state ();
8219 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cf0e1e0d 8220 int i;
cf0e1e0d 8221
c906108c 8222 /* Make sure the entire registers array is valid. */
4082afcc 8223 switch (packet_support (PACKET_P))
5a2468f5
JM
8224 {
8225 case PACKET_DISABLE:
8226 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 8227 /* Make sure all the necessary registers are cached. */
ac7936df 8228 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
ea9c271d 8229 if (rsa->regs[i].in_g_packet)
0b47d985 8230 regcache->raw_update (rsa->regs[i].regnum);
5a2468f5
JM
8231 break;
8232 case PACKET_ENABLE:
8233 break;
8234 }
8235}
8236
ad10f812 8237/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 8238 packet was not recognized. */
5a2468f5 8239
6b8edb51
PA
8240int
8241remote_target::store_register_using_P (const struct regcache *regcache,
8242 packet_reg *reg)
5a2468f5 8243{
ac7936df 8244 struct gdbarch *gdbarch = regcache->arch ();
d01949b6 8245 struct remote_state *rs = get_remote_state ();
5a2468f5 8246 /* Try storing a single register. */
8d64371b 8247 char *buf = rs->buf.data ();
9890e433 8248 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
5a2468f5 8249 char *p;
5a2468f5 8250
4082afcc 8251 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
8252 return 0;
8253
8254 if (reg->pnum == -1)
8255 return 0;
8256
ea9c271d 8257 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 8258 p = buf + strlen (buf);
34a79281 8259 regcache->raw_collect (reg->regnum, regp);
4a22f64d 8260 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4 8261 putpkt (rs->buf);
8d64371b 8262 getpkt (&rs->buf, 0);
5a2468f5 8263
74ca34ce
DJ
8264 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8265 {
8266 case PACKET_OK:
8267 return 1;
8268 case PACKET_ERROR:
27a9c0bf 8269 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8d64371b 8270 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
74ca34ce
DJ
8271 case PACKET_UNKNOWN:
8272 return 0;
8273 default:
8274 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8275 }
c906108c
SS
8276}
8277
23860348
MS
8278/* Store register REGNUM, or all registers if REGNUM == -1, from the
8279 contents of the register cache buffer. FIXME: ignores errors. */
c906108c 8280
6b8edb51
PA
8281void
8282remote_target::store_registers_using_G (const struct regcache *regcache)
c906108c 8283{
d01949b6 8284 struct remote_state *rs = get_remote_state ();
9d6eea31 8285 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cfd77fa1 8286 gdb_byte *regs;
c906108c
SS
8287 char *p;
8288
193cb69f
AC
8289 /* Extract all the registers in the regcache copying them into a
8290 local buffer. */
8291 {
b323314b 8292 int i;
a744cf53 8293
224c3ddb 8294 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 8295 memset (regs, 0, rsa->sizeof_g_packet);
ac7936df 8296 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
193cb69f 8297 {
ea9c271d 8298 struct packet_reg *r = &rsa->regs[i];
a744cf53 8299
b323314b 8300 if (r->in_g_packet)
34a79281 8301 regcache->raw_collect (r->regnum, regs + r->offset);
193cb69f
AC
8302 }
8303 }
c906108c
SS
8304
8305 /* Command describes registers byte by byte,
8306 each byte encoded as two hex characters. */
8d64371b 8307 p = rs->buf.data ();
193cb69f 8308 *p++ = 'G';
74ca34ce 8309 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4 8310 putpkt (rs->buf);
8d64371b 8311 getpkt (&rs->buf, 0);
1f4437a4 8312 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf 8313 error (_("Could not write registers; remote failure reply '%s'"),
8d64371b 8314 rs->buf.data ());
c906108c 8315}
74ca34ce
DJ
8316
8317/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8318 of the register cache buffer. FIXME: ignores errors. */
8319
f6ac5f3d
PA
8320void
8321remote_target::store_registers (struct regcache *regcache, int regnum)
74ca34ce 8322{
5cd63fda 8323 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8324 struct remote_state *rs = get_remote_state ();
8325 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8326 int i;
8327
e6e4e701 8328 set_remote_traceframe ();
222312d3 8329 set_general_thread (regcache->ptid ());
74ca34ce
DJ
8330
8331 if (regnum >= 0)
8332 {
5cd63fda 8333 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8334
74ca34ce
DJ
8335 gdb_assert (reg != NULL);
8336
8337 /* Always prefer to store registers using the 'P' packet if
8338 possible; we often change only a small number of registers.
8339 Sometimes we change a larger number; we'd need help from a
8340 higher layer to know to use 'G'. */
56be3814 8341 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
8342 return;
8343
8344 /* For now, don't complain if we have no way to write the
8345 register. GDB loses track of unavailable registers too
8346 easily. Some day, this may be an error. We don't have
0df8b418 8347 any way to read the register, either... */
74ca34ce
DJ
8348 if (!reg->in_g_packet)
8349 return;
8350
56be3814 8351 store_registers_using_G (regcache);
74ca34ce
DJ
8352 return;
8353 }
8354
56be3814 8355 store_registers_using_G (regcache);
74ca34ce 8356
5cd63fda 8357 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8358 if (!rsa->regs[i].in_g_packet)
56be3814 8359 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
8360 /* See above for why we do not issue an error here. */
8361 continue;
8362}
c906108c
SS
8363\f
8364
8365/* Return the number of hex digits in num. */
8366
8367static int
fba45db2 8368hexnumlen (ULONGEST num)
c906108c
SS
8369{
8370 int i;
8371
8372 for (i = 0; num != 0; i++)
8373 num >>= 4;
8374
325fac50 8375 return std::max (i, 1);
c906108c
SS
8376}
8377
2df3850c 8378/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
8379
8380static int
fba45db2 8381hexnumstr (char *buf, ULONGEST num)
c906108c 8382{
c906108c 8383 int len = hexnumlen (num);
a744cf53 8384
2df3850c
JM
8385 return hexnumnstr (buf, num, len);
8386}
8387
c906108c 8388
2df3850c 8389/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 8390
2df3850c 8391static int
fba45db2 8392hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
8393{
8394 int i;
8395
8396 buf[width] = '\0';
8397
8398 for (i = width - 1; i >= 0; i--)
c906108c 8399 {
c5aa993b 8400 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
8401 num >>= 4;
8402 }
8403
2df3850c 8404 return width;
c906108c
SS
8405}
8406
23860348 8407/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
8408
8409static CORE_ADDR
fba45db2 8410remote_address_masked (CORE_ADDR addr)
c906108c 8411{
883b9c6c 8412 unsigned int address_size = remote_address_size;
a744cf53 8413
911c95a5
UW
8414 /* If "remoteaddresssize" was not set, default to target address size. */
8415 if (!address_size)
f5656ead 8416 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
8417
8418 if (address_size > 0
8419 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
8420 {
8421 /* Only create a mask when that mask can safely be constructed
23860348 8422 in a ULONGEST variable. */
c906108c 8423 ULONGEST mask = 1;
a744cf53 8424
911c95a5 8425 mask = (mask << address_size) - 1;
c906108c
SS
8426 addr &= mask;
8427 }
8428 return addr;
8429}
8430
8431/* Determine whether the remote target supports binary downloading.
8432 This is accomplished by sending a no-op memory write of zero length
8433 to the target at the specified address. It does not suffice to send
23860348
MS
8434 the whole packet, since many stubs strip the eighth bit and
8435 subsequently compute a wrong checksum, which causes real havoc with
8436 remote_write_bytes.
7a292a7a 8437
96baa820 8438 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 8439 clean. In cases like this, the user should clear "remote
23860348 8440 X-packet". */
96baa820 8441
6b8edb51
PA
8442void
8443remote_target::check_binary_download (CORE_ADDR addr)
c906108c 8444{
d01949b6 8445 struct remote_state *rs = get_remote_state ();
24b06219 8446
4082afcc 8447 switch (packet_support (PACKET_X))
c906108c 8448 {
96baa820
JM
8449 case PACKET_DISABLE:
8450 break;
8451 case PACKET_ENABLE:
8452 break;
8453 case PACKET_SUPPORT_UNKNOWN:
8454 {
96baa820 8455 char *p;
802188a7 8456
8d64371b 8457 p = rs->buf.data ();
96baa820
JM
8458 *p++ = 'X';
8459 p += hexnumstr (p, (ULONGEST) addr);
8460 *p++ = ',';
8461 p += hexnumstr (p, (ULONGEST) 0);
8462 *p++ = ':';
8463 *p = '\0';
802188a7 8464
8d64371b
TT
8465 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
8466 getpkt (&rs->buf, 0);
c906108c 8467
2e9f7625 8468 if (rs->buf[0] == '\0')
96baa820
JM
8469 {
8470 if (remote_debug)
8471 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8472 "binary downloading NOT "
8473 "supported by target\n");
444abaca 8474 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
8475 }
8476 else
8477 {
8478 if (remote_debug)
8479 fprintf_unfiltered (gdb_stdlog,
64b9b334 8480 "binary downloading supported by target\n");
444abaca 8481 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
8482 }
8483 break;
8484 }
c906108c
SS
8485 }
8486}
8487
124e13d9
SM
8488/* Helper function to resize the payload in order to try to get a good
8489 alignment. We try to write an amount of data such that the next write will
8490 start on an address aligned on REMOTE_ALIGN_WRITES. */
8491
8492static int
8493align_for_efficient_write (int todo, CORE_ADDR memaddr)
8494{
8495 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8496}
8497
c906108c
SS
8498/* Write memory data directly to the remote machine.
8499 This does not inform the data cache; the data cache uses this.
a76d924d 8500 HEADER is the starting part of the packet.
c906108c
SS
8501 MEMADDR is the address in the remote memory space.
8502 MYADDR is the address of the buffer in our space.
124e13d9
SM
8503 LEN_UNITS is the number of addressable units to write.
8504 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
8505 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8506 should send data as binary ('X'), or hex-encoded ('M').
8507
8508 The function creates packet of the form
8509 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8510
124e13d9 8511 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
8512
8513 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8514 are omitted.
8515
9b409511 8516 Return the transferred status, error or OK (an
124e13d9
SM
8517 'enum target_xfer_status' value). Save the number of addressable units
8518 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8519
8520 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8521 exchange between gdb and the stub could look like (?? in place of the
8522 checksum):
8523
8524 -> $m1000,4#??
8525 <- aaaabbbbccccdddd
8526
8527 -> $M1000,3:eeeeffffeeee#??
8528 <- OK
8529
8530 -> $m1000,4#??
8531 <- eeeeffffeeeedddd */
c906108c 8532
6b8edb51
PA
8533target_xfer_status
8534remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8535 const gdb_byte *myaddr,
8536 ULONGEST len_units,
8537 int unit_size,
8538 ULONGEST *xfered_len_units,
8539 char packet_format, int use_length)
c906108c 8540{
6d820c5c 8541 struct remote_state *rs = get_remote_state ();
cfd77fa1 8542 char *p;
a76d924d
DJ
8543 char *plen = NULL;
8544 int plenlen = 0;
124e13d9
SM
8545 int todo_units;
8546 int units_written;
8547 int payload_capacity_bytes;
8548 int payload_length_bytes;
a76d924d
DJ
8549
8550 if (packet_format != 'X' && packet_format != 'M')
8551 internal_error (__FILE__, __LINE__,
9b20d036 8552 _("remote_write_bytes_aux: bad packet format"));
c906108c 8553
124e13d9 8554 if (len_units == 0)
9b409511 8555 return TARGET_XFER_EOF;
b2182ed2 8556
124e13d9 8557 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 8558
6d820c5c
DJ
8559 /* The packet buffer will be large enough for the payload;
8560 get_memory_packet_size ensures this. */
a76d924d 8561 rs->buf[0] = '\0';
c906108c 8562
a257b5bb 8563 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
8564 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8565
124e13d9 8566 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 8567 if (!use_length)
0df8b418 8568 /* The comma won't be used. */
124e13d9
SM
8569 payload_capacity_bytes += 1;
8570 payload_capacity_bytes -= strlen (header);
8571 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 8572
a76d924d 8573 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 8574
8d64371b
TT
8575 strcat (rs->buf.data (), header);
8576 p = rs->buf.data () + strlen (header);
a76d924d
DJ
8577
8578 /* Compute a best guess of the number of bytes actually transfered. */
8579 if (packet_format == 'X')
c906108c 8580 {
23860348 8581 /* Best guess at number of bytes that will fit. */
325fac50
PA
8582 todo_units = std::min (len_units,
8583 (ULONGEST) payload_capacity_bytes / unit_size);
a76d924d 8584 if (use_length)
124e13d9 8585 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50 8586 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
8587 }
8588 else
8589 {
124e13d9 8590 /* Number of bytes that will fit. */
325fac50
PA
8591 todo_units
8592 = std::min (len_units,
8593 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
a76d924d 8594 if (use_length)
124e13d9 8595 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50
PA
8596 todo_units = std::min (todo_units,
8597 (payload_capacity_bytes / unit_size) / 2);
917317f4 8598 }
a76d924d 8599
124e13d9 8600 if (todo_units <= 0)
3de11b2e 8601 internal_error (__FILE__, __LINE__,
405f8e94 8602 _("minimum packet size too small to write data"));
802188a7 8603
6765f3e5
DJ
8604 /* If we already need another packet, then try to align the end
8605 of this packet to a useful boundary. */
124e13d9
SM
8606 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8607 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 8608
a257b5bb 8609 /* Append "<memaddr>". */
917317f4
JM
8610 memaddr = remote_address_masked (memaddr);
8611 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 8612
a76d924d
DJ
8613 if (use_length)
8614 {
8615 /* Append ",". */
8616 *p++ = ',';
802188a7 8617
124e13d9
SM
8618 /* Append the length and retain its location and size. It may need to be
8619 adjusted once the packet body has been created. */
a76d924d 8620 plen = p;
124e13d9 8621 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
8622 p += plenlen;
8623 }
a257b5bb
AC
8624
8625 /* Append ":". */
917317f4
JM
8626 *p++ = ':';
8627 *p = '\0';
802188a7 8628
a257b5bb 8629 /* Append the packet body. */
a76d924d 8630 if (packet_format == 'X')
917317f4 8631 {
917317f4
JM
8632 /* Binary mode. Send target system values byte by byte, in
8633 increasing byte addresses. Only escape certain critical
8634 characters. */
124e13d9
SM
8635 payload_length_bytes =
8636 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8637 &units_written, payload_capacity_bytes);
6765f3e5 8638
124e13d9 8639 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
8640 a second try to keep the end of the packet aligned. Don't do
8641 this if the packet is tiny. */
124e13d9 8642 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 8643 {
124e13d9
SM
8644 int new_todo_units;
8645
8646 new_todo_units = align_for_efficient_write (units_written, memaddr);
8647
8648 if (new_todo_units != units_written)
8649 payload_length_bytes =
8650 remote_escape_output (myaddr, new_todo_units, unit_size,
8651 (gdb_byte *) p, &units_written,
8652 payload_capacity_bytes);
6765f3e5
DJ
8653 }
8654
124e13d9
SM
8655 p += payload_length_bytes;
8656 if (use_length && units_written < todo_units)
c906108c 8657 {
802188a7 8658 /* Escape chars have filled up the buffer prematurely,
124e13d9 8659 and we have actually sent fewer units than planned.
917317f4
JM
8660 Fix-up the length field of the packet. Use the same
8661 number of characters as before. */
124e13d9
SM
8662 plen += hexnumnstr (plen, (ULONGEST) units_written,
8663 plenlen);
917317f4 8664 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 8665 }
a76d924d
DJ
8666 }
8667 else
8668 {
917317f4
JM
8669 /* Normal mode: Send target system values byte by byte, in
8670 increasing byte addresses. Each byte is encoded as a two hex
8671 value. */
124e13d9
SM
8672 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8673 units_written = todo_units;
c906108c 8674 }
802188a7 8675
8d64371b
TT
8676 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
8677 getpkt (&rs->buf, 0);
802188a7 8678
2e9f7625 8679 if (rs->buf[0] == 'E')
00d84524 8680 return TARGET_XFER_E_IO;
802188a7 8681
124e13d9
SM
8682 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8683 send fewer units than we'd planned. */
8684 *xfered_len_units = (ULONGEST) units_written;
92ffd475 8685 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
8686}
8687
a76d924d
DJ
8688/* Write memory data directly to the remote machine.
8689 This does not inform the data cache; the data cache uses this.
8690 MEMADDR is the address in the remote memory space.
8691 MYADDR is the address of the buffer in our space.
8692 LEN is the number of bytes.
8693
9b409511
YQ
8694 Return the transferred status, error or OK (an
8695 'enum target_xfer_status' value). Save the number of bytes
8696 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 8697
6b8edb51
PA
8698target_xfer_status
8699remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
8700 ULONGEST len, int unit_size,
8701 ULONGEST *xfered_len)
a76d924d 8702{
a121b7c1 8703 const char *packet_format = NULL;
a76d924d
DJ
8704
8705 /* Check whether the target supports binary download. */
8706 check_binary_download (memaddr);
8707
4082afcc 8708 switch (packet_support (PACKET_X))
a76d924d
DJ
8709 {
8710 case PACKET_ENABLE:
8711 packet_format = "X";
8712 break;
8713 case PACKET_DISABLE:
8714 packet_format = "M";
8715 break;
8716 case PACKET_SUPPORT_UNKNOWN:
8717 internal_error (__FILE__, __LINE__,
8718 _("remote_write_bytes: bad internal state"));
8719 default:
8720 internal_error (__FILE__, __LINE__, _("bad switch"));
8721 }
8722
8723 return remote_write_bytes_aux (packet_format,
124e13d9 8724 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 8725 packet_format[0], 1);
a76d924d
DJ
8726}
8727
9217e74e
YQ
8728/* Read memory data directly from the remote machine.
8729 This does not use the data cache; the data cache uses this.
8730 MEMADDR is the address in the remote memory space.
8731 MYADDR is the address of the buffer in our space.
124e13d9
SM
8732 LEN_UNITS is the number of addressable memory units to read..
8733 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
8734
8735 Return the transferred status, error or OK (an
8736 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
8737 transferred in *XFERED_LEN_UNITS.
8738
8739 See the comment of remote_write_bytes_aux for an example of
8740 memory read/write exchange between gdb and the stub. */
9217e74e 8741
6b8edb51
PA
8742target_xfer_status
8743remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
8744 ULONGEST len_units,
8745 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
8746{
8747 struct remote_state *rs = get_remote_state ();
124e13d9 8748 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 8749 char *p;
124e13d9
SM
8750 int todo_units;
8751 int decoded_bytes;
9217e74e 8752
124e13d9 8753 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
8754 /* The packet buffer will be large enough for the payload;
8755 get_memory_packet_size ensures this. */
8756
124e13d9 8757 /* Number of units that will fit. */
325fac50
PA
8758 todo_units = std::min (len_units,
8759 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
8760
8761 /* Construct "m"<memaddr>","<len>". */
8762 memaddr = remote_address_masked (memaddr);
8d64371b 8763 p = rs->buf.data ();
9217e74e
YQ
8764 *p++ = 'm';
8765 p += hexnumstr (p, (ULONGEST) memaddr);
8766 *p++ = ',';
124e13d9 8767 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
8768 *p = '\0';
8769 putpkt (rs->buf);
8d64371b 8770 getpkt (&rs->buf, 0);
9217e74e
YQ
8771 if (rs->buf[0] == 'E'
8772 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8773 && rs->buf[3] == '\0')
8774 return TARGET_XFER_E_IO;
8775 /* Reply describes memory byte by byte, each byte encoded as two hex
8776 characters. */
8d64371b 8777 p = rs->buf.data ();
124e13d9 8778 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 8779 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 8780 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
92ffd475 8781 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9217e74e
YQ
8782}
8783
b55fbac4
YQ
8784/* Using the set of read-only target sections of remote, read live
8785 read-only memory.
8acf9577
YQ
8786
8787 For interface/parameters/return description see target.h,
8788 to_xfer_partial. */
8789
6b8edb51
PA
8790target_xfer_status
8791remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
8792 ULONGEST memaddr,
8793 ULONGEST len,
8794 int unit_size,
8795 ULONGEST *xfered_len)
8acf9577
YQ
8796{
8797 struct target_section *secp;
8798 struct target_section_table *table;
8799
6b8edb51 8800 secp = target_section_by_addr (this, memaddr);
8acf9577
YQ
8801 if (secp != NULL
8802 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8803 secp->the_bfd_section)
8804 & SEC_READONLY))
8805 {
8806 struct target_section *p;
8807 ULONGEST memend = memaddr + len;
8808
6b8edb51 8809 table = target_get_section_table (this);
8acf9577
YQ
8810
8811 for (p = table->sections; p < table->sections_end; p++)
8812 {
8813 if (memaddr >= p->addr)
8814 {
8815 if (memend <= p->endaddr)
8816 {
8817 /* Entire transfer is within this section. */
124e13d9 8818 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8819 xfered_len);
8acf9577
YQ
8820 }
8821 else if (memaddr >= p->endaddr)
8822 {
8823 /* This section ends before the transfer starts. */
8824 continue;
8825 }
8826 else
8827 {
8828 /* This section overlaps the transfer. Just do half. */
8829 len = p->endaddr - memaddr;
124e13d9 8830 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8831 xfered_len);
8acf9577
YQ
8832 }
8833 }
8834 }
8835 }
8836
8837 return TARGET_XFER_EOF;
8838}
8839
9217e74e
YQ
8840/* Similar to remote_read_bytes_1, but it reads from the remote stub
8841 first if the requested memory is unavailable in traceframe.
8842 Otherwise, fall back to remote_read_bytes_1. */
c906108c 8843
6b8edb51
PA
8844target_xfer_status
8845remote_target::remote_read_bytes (CORE_ADDR memaddr,
8846 gdb_byte *myaddr, ULONGEST len, int unit_size,
8847 ULONGEST *xfered_len)
c906108c 8848{
6b6aa828 8849 if (len == 0)
96c4f946 8850 return TARGET_XFER_EOF;
b2182ed2 8851
8acf9577
YQ
8852 if (get_traceframe_number () != -1)
8853 {
a79b1bc6 8854 std::vector<mem_range> available;
8acf9577
YQ
8855
8856 /* If we fail to get the set of available memory, then the
8857 target does not support querying traceframe info, and so we
8858 attempt reading from the traceframe anyway (assuming the
8859 target implements the old QTro packet then). */
8860 if (traceframe_available_memory (&available, memaddr, len))
8861 {
a79b1bc6 8862 if (available.empty () || available[0].start != memaddr)
8acf9577
YQ
8863 {
8864 enum target_xfer_status res;
8865
8866 /* Don't read into the traceframe's available
8867 memory. */
a79b1bc6 8868 if (!available.empty ())
8acf9577
YQ
8869 {
8870 LONGEST oldlen = len;
8871
a79b1bc6 8872 len = available[0].start - memaddr;
8acf9577
YQ
8873 gdb_assert (len <= oldlen);
8874 }
8875
8acf9577 8876 /* This goes through the topmost target again. */
6b8edb51 8877 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
124e13d9 8878 len, unit_size, xfered_len);
8acf9577
YQ
8879 if (res == TARGET_XFER_OK)
8880 return TARGET_XFER_OK;
8881 else
8882 {
8883 /* No use trying further, we know some memory starting
8884 at MEMADDR isn't available. */
8885 *xfered_len = len;
92ffd475
PC
8886 return (*xfered_len != 0) ?
8887 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8acf9577
YQ
8888 }
8889 }
8890
8891 /* Don't try to read more than how much is available, in
8892 case the target implements the deprecated QTro packet to
8893 cater for older GDBs (the target's knowledge of read-only
8894 sections may be outdated by now). */
a79b1bc6 8895 len = available[0].length;
8acf9577
YQ
8896 }
8897 }
8898
124e13d9 8899 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 8900}
74531fed 8901
c906108c 8902\f
c906108c 8903
a76d924d
DJ
8904/* Sends a packet with content determined by the printf format string
8905 FORMAT and the remaining arguments, then gets the reply. Returns
8906 whether the packet was a success, a failure, or unknown. */
8907
6b8edb51
PA
8908packet_result
8909remote_target::remote_send_printf (const char *format, ...)
a76d924d
DJ
8910{
8911 struct remote_state *rs = get_remote_state ();
8912 int max_size = get_remote_packet_size ();
a76d924d 8913 va_list ap;
a744cf53 8914
a76d924d
DJ
8915 va_start (ap, format);
8916
8917 rs->buf[0] = '\0';
8d64371b 8918 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
33b031ce
GB
8919
8920 va_end (ap);
8921
8922 if (size >= max_size)
9b20d036 8923 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
8924
8925 if (putpkt (rs->buf) < 0)
8926 error (_("Communication problem with target."));
8927
8928 rs->buf[0] = '\0';
8d64371b 8929 getpkt (&rs->buf, 0);
a76d924d
DJ
8930
8931 return packet_check_result (rs->buf);
8932}
8933
a76d924d
DJ
8934/* Flash writing can take quite some time. We'll set
8935 effectively infinite timeout for flash operations.
8936 In future, we'll need to decide on a better approach. */
8937static const int remote_flash_timeout = 1000;
8938
f6ac5f3d
PA
8939void
8940remote_target::flash_erase (ULONGEST address, LONGEST length)
a76d924d 8941{
f5656ead 8942 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d 8943 enum packet_result ret;
2ec845e7
TT
8944 scoped_restore restore_timeout
8945 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
a76d924d
DJ
8946
8947 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 8948 phex (address, addr_size),
a76d924d
DJ
8949 phex (length, 4));
8950 switch (ret)
8951 {
8952 case PACKET_UNKNOWN:
8953 error (_("Remote target does not support flash erase"));
8954 case PACKET_ERROR:
8955 error (_("Error erasing flash with vFlashErase packet"));
8956 default:
8957 break;
8958 }
a76d924d
DJ
8959}
8960
6b8edb51
PA
8961target_xfer_status
8962remote_target::remote_flash_write (ULONGEST address,
8963 ULONGEST length, ULONGEST *xfered_len,
8964 const gdb_byte *data)
a76d924d 8965{
2ec845e7
TT
8966 scoped_restore restore_timeout
8967 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8968 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8969 xfered_len,'X', 0);
a76d924d
DJ
8970}
8971
f6ac5f3d
PA
8972void
8973remote_target::flash_done ()
a76d924d 8974{
a76d924d 8975 int ret;
a76d924d 8976
2ec845e7
TT
8977 scoped_restore restore_timeout
8978 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8979
a76d924d 8980 ret = remote_send_printf ("vFlashDone");
a76d924d
DJ
8981
8982 switch (ret)
8983 {
8984 case PACKET_UNKNOWN:
8985 error (_("Remote target does not support vFlashDone"));
8986 case PACKET_ERROR:
8987 error (_("Error finishing flash operation"));
8988 default:
8989 break;
8990 }
8991}
8992
f6ac5f3d
PA
8993void
8994remote_target::files_info ()
c906108c
SS
8995{
8996 puts_filtered ("Debugging a target over a serial line.\n");
8997}
8998\f
8999/* Stuff for dealing with the packets which are part of this protocol.
9000 See comment at top of file for details. */
9001
1927e618
PA
9002/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9003 error to higher layers. Called when a serial error is detected.
9004 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
9005 the system error message for errno at function entry and final dot
9006 for output compatibility with throw_perror_with_name. */
1927e618
PA
9007
9008static void
9009unpush_and_perror (const char *string)
9010{
d6cb50a2 9011 int saved_errno = errno;
1927e618
PA
9012
9013 remote_unpush_target ();
d6cb50a2
JK
9014 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9015 safe_strerror (saved_errno));
1927e618
PA
9016}
9017
048094ac
PA
9018/* Read a single character from the remote end. The current quit
9019 handler is overridden to avoid quitting in the middle of packet
9020 sequence, as that would break communication with the remote server.
9021 See remote_serial_quit_handler for more detail. */
c906108c 9022
6b8edb51
PA
9023int
9024remote_target::readchar (int timeout)
c906108c
SS
9025{
9026 int ch;
5d93a237 9027 struct remote_state *rs = get_remote_state ();
048094ac 9028
2ec845e7 9029 {
6b8edb51
PA
9030 scoped_restore restore_quit_target
9031 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9032 scoped_restore restore_quit
6b8edb51 9033 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
c906108c 9034
2ec845e7 9035 rs->got_ctrlc_during_io = 0;
c906108c 9036
2ec845e7 9037 ch = serial_readchar (rs->remote_desc, timeout);
048094ac 9038
2ec845e7
TT
9039 if (rs->got_ctrlc_during_io)
9040 set_quit_flag ();
9041 }
048094ac 9042
2acceee2 9043 if (ch >= 0)
0876f84a 9044 return ch;
2acceee2
JM
9045
9046 switch ((enum serial_rc) ch)
c906108c
SS
9047 {
9048 case SERIAL_EOF:
78a095c3 9049 remote_unpush_target ();
598d3636 9050 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 9051 /* no return */
c906108c 9052 case SERIAL_ERROR:
1927e618
PA
9053 unpush_and_perror (_("Remote communication error. "
9054 "Target disconnected."));
2acceee2 9055 /* no return */
c906108c 9056 case SERIAL_TIMEOUT:
2acceee2 9057 break;
c906108c 9058 }
2acceee2 9059 return ch;
c906108c
SS
9060}
9061
c33e31fd 9062/* Wrapper for serial_write that closes the target and throws if
048094ac
PA
9063 writing fails. The current quit handler is overridden to avoid
9064 quitting in the middle of packet sequence, as that would break
9065 communication with the remote server. See
9066 remote_serial_quit_handler for more detail. */
c33e31fd 9067
6b8edb51
PA
9068void
9069remote_target::remote_serial_write (const char *str, int len)
c33e31fd 9070{
5d93a237 9071 struct remote_state *rs = get_remote_state ();
048094ac 9072
6b8edb51
PA
9073 scoped_restore restore_quit_target
9074 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9075 scoped_restore restore_quit
6b8edb51 9076 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
048094ac
PA
9077
9078 rs->got_ctrlc_during_io = 0;
5d93a237
TT
9079
9080 if (serial_write (rs->remote_desc, str, len))
c33e31fd 9081 {
1927e618
PA
9082 unpush_and_perror (_("Remote communication error. "
9083 "Target disconnected."));
c33e31fd 9084 }
048094ac
PA
9085
9086 if (rs->got_ctrlc_during_io)
9087 set_quit_flag ();
c33e31fd
PA
9088}
9089
b3ced9ba
PA
9090/* Return a string representing an escaped version of BUF, of len N.
9091 E.g. \n is converted to \\n, \t to \\t, etc. */
6e5abd65 9092
b3ced9ba 9093static std::string
6e5abd65
PA
9094escape_buffer (const char *buf, int n)
9095{
d7e74731 9096 string_file stb;
6e5abd65 9097
d7e74731
PA
9098 stb.putstrn (buf, n, '\\');
9099 return std::move (stb.string ());
6e5abd65
PA
9100}
9101
c906108c
SS
9102/* Display a null-terminated packet on stdout, for debugging, using C
9103 string notation. */
9104
9105static void
baa336ce 9106print_packet (const char *buf)
c906108c
SS
9107{
9108 puts_filtered ("\"");
43e526b9 9109 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
9110 puts_filtered ("\"");
9111}
9112
9113int
6b8edb51 9114remote_target::putpkt (const char *buf)
c906108c
SS
9115{
9116 return putpkt_binary (buf, strlen (buf));
9117}
9118
6b8edb51
PA
9119/* Wrapper around remote_target::putpkt to avoid exporting
9120 remote_target. */
9121
9122int
9123putpkt (remote_target *remote, const char *buf)
9124{
9125 return remote->putpkt (buf);
9126}
9127
c906108c 9128/* Send a packet to the remote machine, with error checking. The data
23860348 9129 of the packet is in BUF. The string in BUF can be at most
ea9c271d 9130 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
9131 and for a possible /0 if we are debugging (remote_debug) and want
9132 to print the sent packet as a string. */
c906108c 9133
6b8edb51
PA
9134int
9135remote_target::putpkt_binary (const char *buf, int cnt)
c906108c 9136{
2d717e4f 9137 struct remote_state *rs = get_remote_state ();
c906108c
SS
9138 int i;
9139 unsigned char csum = 0;
b80406ac
TT
9140 gdb::def_vector<char> data (cnt + 6);
9141 char *buf2 = data.data ();
085dd6e6 9142
c906108c
SS
9143 int ch;
9144 int tcount = 0;
9145 char *p;
9146
e24a49d8
PA
9147 /* Catch cases like trying to read memory or listing threads while
9148 we're waiting for a stop reply. The remote server wouldn't be
9149 ready to handle this request, so we'd hang and timeout. We don't
9150 have to worry about this in synchronous mode, because in that
9151 case it's not possible to issue a command while the target is
74531fed
PA
9152 running. This is not a problem in non-stop mode, because in that
9153 case, the stub is always ready to process serial input. */
6efcd9a8
PA
9154 if (!target_is_non_stop_p ()
9155 && target_is_async_p ()
9156 && rs->waiting_for_stop_reply)
9597b22a
DE
9157 {
9158 error (_("Cannot execute this command while the target is running.\n"
9159 "Use the \"interrupt\" command to stop the target\n"
9160 "and then try again."));
9161 }
e24a49d8 9162
2d717e4f
DJ
9163 /* We're sending out a new packet. Make sure we don't look at a
9164 stale cached response. */
9165 rs->cached_wait_status = 0;
9166
c906108c
SS
9167 /* Copy the packet into buffer BUF2, encapsulating it
9168 and giving it a checksum. */
9169
c906108c
SS
9170 p = buf2;
9171 *p++ = '$';
9172
9173 for (i = 0; i < cnt; i++)
9174 {
9175 csum += buf[i];
9176 *p++ = buf[i];
9177 }
9178 *p++ = '#';
9179 *p++ = tohex ((csum >> 4) & 0xf);
9180 *p++ = tohex (csum & 0xf);
9181
9182 /* Send it over and over until we get a positive ack. */
9183
9184 while (1)
9185 {
9186 int started_error_output = 0;
9187
9188 if (remote_debug)
9189 {
9190 *p = '\0';
b3ced9ba 9191
6f8976bf
YQ
9192 int len = (int) (p - buf2);
9193
9194 std::string str
9195 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
9196
9197 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
9198
567a3e54
SM
9199 if (len > REMOTE_DEBUG_MAX_CHAR)
9200 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9201 len - REMOTE_DEBUG_MAX_CHAR);
6f8976bf
YQ
9202
9203 fprintf_unfiltered (gdb_stdlog, "...");
b3ced9ba 9204
0f71a2f6 9205 gdb_flush (gdb_stdlog);
c906108c 9206 }
c33e31fd 9207 remote_serial_write (buf2, p - buf2);
c906108c 9208
a6f3e723
SL
9209 /* If this is a no acks version of the remote protocol, send the
9210 packet and move on. */
9211 if (rs->noack_mode)
9212 break;
9213
74531fed
PA
9214 /* Read until either a timeout occurs (-2) or '+' is read.
9215 Handle any notification that arrives in the mean time. */
c906108c
SS
9216 while (1)
9217 {
9218 ch = readchar (remote_timeout);
9219
c5aa993b 9220 if (remote_debug)
c906108c
SS
9221 {
9222 switch (ch)
9223 {
9224 case '+':
1216fa2c 9225 case '-':
c906108c
SS
9226 case SERIAL_TIMEOUT:
9227 case '$':
74531fed 9228 case '%':
c906108c
SS
9229 if (started_error_output)
9230 {
9231 putchar_unfiltered ('\n');
9232 started_error_output = 0;
9233 }
9234 }
9235 }
9236
9237 switch (ch)
9238 {
9239 case '+':
9240 if (remote_debug)
0f71a2f6 9241 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 9242 return 1;
1216fa2c
AC
9243 case '-':
9244 if (remote_debug)
9245 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 9246 /* FALLTHROUGH */
c906108c 9247 case SERIAL_TIMEOUT:
c5aa993b 9248 tcount++;
c906108c 9249 if (tcount > 3)
b80406ac 9250 return 0;
23860348 9251 break; /* Retransmit buffer. */
c906108c
SS
9252 case '$':
9253 {
40e3f985 9254 if (remote_debug)
2bc416ba 9255 fprintf_unfiltered (gdb_stdlog,
23860348 9256 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
9257 /* It's probably an old response sent because an ACK
9258 was lost. Gobble up the packet and ack it so it
9259 doesn't get retransmitted when we resend this
9260 packet. */
6d820c5c 9261 skip_frame ();
c33e31fd 9262 remote_serial_write ("+", 1);
23860348 9263 continue; /* Now, go look for +. */
c906108c 9264 }
74531fed
PA
9265
9266 case '%':
9267 {
9268 int val;
9269
9270 /* If we got a notification, handle it, and go back to looking
9271 for an ack. */
9272 /* We've found the start of a notification. Now
9273 collect the data. */
8d64371b 9274 val = read_frame (&rs->buf);
74531fed
PA
9275 if (val >= 0)
9276 {
9277 if (remote_debug)
9278 {
8d64371b 9279 std::string str = escape_buffer (rs->buf.data (), val);
6e5abd65 9280
6e5abd65
PA
9281 fprintf_unfiltered (gdb_stdlog,
9282 " Notification received: %s\n",
b3ced9ba 9283 str.c_str ());
74531fed 9284 }
8d64371b 9285 handle_notification (rs->notif_state, rs->buf.data ());
74531fed
PA
9286 /* We're in sync now, rewait for the ack. */
9287 tcount = 0;
9288 }
9289 else
9290 {
9291 if (remote_debug)
9292 {
9293 if (!started_error_output)
9294 {
9295 started_error_output = 1;
9296 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9297 }
9298 fputc_unfiltered (ch & 0177, gdb_stdlog);
8d64371b 9299 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf.data ());
74531fed
PA
9300 }
9301 }
9302 continue;
9303 }
9304 /* fall-through */
c906108c
SS
9305 default:
9306 if (remote_debug)
9307 {
9308 if (!started_error_output)
9309 {
9310 started_error_output = 1;
0f71a2f6 9311 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 9312 }
0f71a2f6 9313 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
9314 }
9315 continue;
9316 }
23860348 9317 break; /* Here to retransmit. */
c906108c
SS
9318 }
9319
9320#if 0
9321 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
9322 able to get out next time we call QUIT, without anything as
9323 violent as interrupt_query. If we want to provide a way out of
9324 here without getting to the next QUIT, it should be based on
9325 hitting ^C twice as in remote_wait. */
c906108c
SS
9326 if (quit_flag)
9327 {
9328 quit_flag = 0;
9329 interrupt_query ();
9330 }
9331#endif
9332 }
a5c0808e 9333
a6f3e723 9334 return 0;
c906108c
SS
9335}
9336
6d820c5c
DJ
9337/* Come here after finding the start of a frame when we expected an
9338 ack. Do our best to discard the rest of this packet. */
9339
6b8edb51
PA
9340void
9341remote_target::skip_frame ()
6d820c5c
DJ
9342{
9343 int c;
9344
9345 while (1)
9346 {
9347 c = readchar (remote_timeout);
9348 switch (c)
9349 {
9350 case SERIAL_TIMEOUT:
9351 /* Nothing we can do. */
9352 return;
9353 case '#':
9354 /* Discard the two bytes of checksum and stop. */
9355 c = readchar (remote_timeout);
9356 if (c >= 0)
9357 c = readchar (remote_timeout);
9358
9359 return;
9360 case '*': /* Run length encoding. */
9361 /* Discard the repeat count. */
9362 c = readchar (remote_timeout);
9363 if (c < 0)
9364 return;
9365 break;
9366 default:
9367 /* A regular character. */
9368 break;
9369 }
9370 }
9371}
9372
c906108c 9373/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
9374 into *BUF, verifying the checksum, length, and handling run-length
9375 compression. NUL terminate the buffer. If there is not enough room,
8d64371b 9376 expand *BUF.
c906108c 9377
c2d11a7d
JM
9378 Returns -1 on error, number of characters in buffer (ignoring the
9379 trailing NULL) on success. (could be extended to return one of the
23860348 9380 SERIAL status indications). */
c2d11a7d 9381
6b8edb51 9382long
8d64371b 9383remote_target::read_frame (gdb::char_vector *buf_p)
c906108c
SS
9384{
9385 unsigned char csum;
c2d11a7d 9386 long bc;
c906108c 9387 int c;
8d64371b 9388 char *buf = buf_p->data ();
a6f3e723 9389 struct remote_state *rs = get_remote_state ();
c906108c
SS
9390
9391 csum = 0;
c2d11a7d 9392 bc = 0;
c906108c
SS
9393
9394 while (1)
9395 {
9396 c = readchar (remote_timeout);
c906108c
SS
9397 switch (c)
9398 {
9399 case SERIAL_TIMEOUT:
9400 if (remote_debug)
0f71a2f6 9401 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 9402 return -1;
c906108c
SS
9403 case '$':
9404 if (remote_debug)
0f71a2f6
JM
9405 fputs_filtered ("Saw new packet start in middle of old one\n",
9406 gdb_stdlog);
23860348 9407 return -1; /* Start a new packet, count retries. */
c906108c
SS
9408 case '#':
9409 {
9410 unsigned char pktcsum;
e1b09194
AC
9411 int check_0 = 0;
9412 int check_1 = 0;
c906108c 9413
c2d11a7d 9414 buf[bc] = '\0';
c906108c 9415
e1b09194
AC
9416 check_0 = readchar (remote_timeout);
9417 if (check_0 >= 0)
9418 check_1 = readchar (remote_timeout);
802188a7 9419
e1b09194
AC
9420 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9421 {
9422 if (remote_debug)
2bc416ba 9423 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 9424 gdb_stdlog);
e1b09194
AC
9425 return -1;
9426 }
9427 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
9428 {
9429 if (remote_debug)
2bc416ba 9430 fputs_filtered ("Communication error in checksum\n",
23860348 9431 gdb_stdlog);
40e3f985
FN
9432 return -1;
9433 }
c906108c 9434
a6f3e723
SL
9435 /* Don't recompute the checksum; with no ack packets we
9436 don't have any way to indicate a packet retransmission
9437 is necessary. */
9438 if (rs->noack_mode)
9439 return bc;
9440
e1b09194 9441 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 9442 if (csum == pktcsum)
c2d11a7d 9443 return bc;
c906108c 9444
c5aa993b 9445 if (remote_debug)
c906108c 9446 {
b3ced9ba 9447 std::string str = escape_buffer (buf, bc);
6e5abd65 9448
6e5abd65 9449 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
9450 "Bad checksum, sentsum=0x%x, "
9451 "csum=0x%x, buf=%s\n",
b3ced9ba 9452 pktcsum, csum, str.c_str ());
c906108c 9453 }
c2d11a7d 9454 /* Number of characters in buffer ignoring trailing
23860348 9455 NULL. */
c2d11a7d 9456 return -1;
c906108c 9457 }
23860348 9458 case '*': /* Run length encoding. */
c2c6d25f
JM
9459 {
9460 int repeat;
c906108c 9461
a744cf53 9462 csum += c;
b4501125
AC
9463 c = readchar (remote_timeout);
9464 csum += c;
23860348 9465 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 9466
23860348 9467 /* The character before ``*'' is repeated. */
c2d11a7d 9468
6d820c5c 9469 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 9470 {
8d64371b 9471 if (bc + repeat - 1 >= buf_p->size () - 1)
6d820c5c
DJ
9472 {
9473 /* Make some more room in the buffer. */
8d64371b
TT
9474 buf_p->resize (buf_p->size () + repeat);
9475 buf = buf_p->data ();
6d820c5c
DJ
9476 }
9477
c2d11a7d
JM
9478 memset (&buf[bc], buf[bc - 1], repeat);
9479 bc += repeat;
c2c6d25f
JM
9480 continue;
9481 }
9482
c2d11a7d 9483 buf[bc] = '\0';
6d820c5c 9484 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 9485 return -1;
c2c6d25f 9486 }
c906108c 9487 default:
8d64371b 9488 if (bc >= buf_p->size () - 1)
c906108c 9489 {
6d820c5c 9490 /* Make some more room in the buffer. */
8d64371b
TT
9491 buf_p->resize (buf_p->size () * 2);
9492 buf = buf_p->data ();
c906108c
SS
9493 }
9494
6d820c5c
DJ
9495 buf[bc++] = c;
9496 csum += c;
9497 continue;
c906108c
SS
9498 }
9499 }
9500}
9501
9502/* Read a packet from the remote machine, with error checking, and
8d64371b
TT
9503 store it in *BUF. Resize *BUF if necessary to hold the result. If
9504 FOREVER, wait forever rather than timing out; this is used (in
9505 synchronous mode) to wait for a target that is is executing user
9506 code to stop. */
d9fcf2fb
JM
9507/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9508 don't have to change all the calls to getpkt to deal with the
9509 return value, because at the moment I don't know what the right
23860348 9510 thing to do it for those. */
6b8edb51 9511
c906108c 9512void
8d64371b 9513remote_target::getpkt (gdb::char_vector *buf, int forever)
d9fcf2fb 9514{
8d64371b 9515 getpkt_sane (buf, forever);
d9fcf2fb
JM
9516}
9517
9518
9519/* Read a packet from the remote machine, with error checking, and
8d64371b
TT
9520 store it in *BUF. Resize *BUF if necessary to hold the result. If
9521 FOREVER, wait forever rather than timing out; this is used (in
9522 synchronous mode) to wait for a target that is is executing user
9523 code to stop. If FOREVER == 0, this function is allowed to time
9524 out gracefully and return an indication of this to the caller.
9525 Otherwise return the number of bytes read. If EXPECTING_NOTIF,
9526 consider receiving a notification enough reason to return to the
9527 caller. *IS_NOTIF is an output boolean that indicates whether *BUF
9528 holds a notification or not (a regular packet). */
74531fed 9529
6b8edb51 9530int
8d64371b 9531remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
6b8edb51
PA
9532 int forever, int expecting_notif,
9533 int *is_notif)
c906108c 9534{
2d717e4f 9535 struct remote_state *rs = get_remote_state ();
c906108c
SS
9536 int c;
9537 int tries;
9538 int timeout;
df4b58fe 9539 int val = -1;
c906108c 9540
2d717e4f
DJ
9541 /* We're reading a new response. Make sure we don't look at a
9542 previously cached response. */
9543 rs->cached_wait_status = 0;
9544
8d64371b 9545 strcpy (buf->data (), "timeout");
c906108c
SS
9546
9547 if (forever)
74531fed
PA
9548 timeout = watchdog > 0 ? watchdog : -1;
9549 else if (expecting_notif)
9550 timeout = 0; /* There should already be a char in the buffer. If
9551 not, bail out. */
c906108c
SS
9552 else
9553 timeout = remote_timeout;
9554
9555#define MAX_TRIES 3
9556
74531fed
PA
9557 /* Process any number of notifications, and then return when
9558 we get a packet. */
9559 for (;;)
c906108c 9560 {
d9c43928 9561 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
9562 times. */
9563 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 9564 {
74531fed
PA
9565 /* This can loop forever if the remote side sends us
9566 characters continuously, but if it pauses, we'll get
9567 SERIAL_TIMEOUT from readchar because of timeout. Then
9568 we'll count that as a retry.
9569
9570 Note that even when forever is set, we will only wait
9571 forever prior to the start of a packet. After that, we
9572 expect characters to arrive at a brisk pace. They should
9573 show up within remote_timeout intervals. */
9574 do
9575 c = readchar (timeout);
9576 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
9577
9578 if (c == SERIAL_TIMEOUT)
9579 {
74531fed
PA
9580 if (expecting_notif)
9581 return -1; /* Don't complain, it's normal to not get
9582 anything in this case. */
9583
23860348 9584 if (forever) /* Watchdog went off? Kill the target. */
c906108c 9585 {
78a095c3 9586 remote_unpush_target ();
598d3636
JK
9587 throw_error (TARGET_CLOSE_ERROR,
9588 _("Watchdog timeout has expired. "
9589 "Target detached."));
c906108c 9590 }
c906108c 9591 if (remote_debug)
0f71a2f6 9592 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 9593 }
74531fed
PA
9594 else
9595 {
9596 /* We've found the start of a packet or notification.
9597 Now collect the data. */
8d64371b 9598 val = read_frame (buf);
74531fed
PA
9599 if (val >= 0)
9600 break;
9601 }
9602
c33e31fd 9603 remote_serial_write ("-", 1);
c906108c 9604 }
c906108c 9605
74531fed
PA
9606 if (tries > MAX_TRIES)
9607 {
9608 /* We have tried hard enough, and just can't receive the
9609 packet/notification. Give up. */
9610 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 9611
74531fed
PA
9612 /* Skip the ack char if we're in no-ack mode. */
9613 if (!rs->noack_mode)
c33e31fd 9614 remote_serial_write ("+", 1);
74531fed
PA
9615 return -1;
9616 }
c906108c 9617
74531fed
PA
9618 /* If we got an ordinary packet, return that to our caller. */
9619 if (c == '$')
c906108c
SS
9620 {
9621 if (remote_debug)
43e526b9 9622 {
6f8976bf 9623 std::string str
8d64371b 9624 = escape_buffer (buf->data (),
6f8976bf
YQ
9625 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9626
9627 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9628 str.c_str ());
9629
567a3e54
SM
9630 if (val > REMOTE_DEBUG_MAX_CHAR)
9631 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9632 val - REMOTE_DEBUG_MAX_CHAR);
6e5abd65 9633
6f8976bf 9634 fprintf_unfiltered (gdb_stdlog, "\n");
43e526b9 9635 }
a6f3e723
SL
9636
9637 /* Skip the ack char if we're in no-ack mode. */
9638 if (!rs->noack_mode)
c33e31fd 9639 remote_serial_write ("+", 1);
fee9eda9
YQ
9640 if (is_notif != NULL)
9641 *is_notif = 0;
0876f84a 9642 return val;
c906108c
SS
9643 }
9644
74531fed
PA
9645 /* If we got a notification, handle it, and go back to looking
9646 for a packet. */
9647 else
9648 {
9649 gdb_assert (c == '%');
9650
9651 if (remote_debug)
9652 {
8d64371b 9653 std::string str = escape_buffer (buf->data (), val);
6e5abd65 9654
6e5abd65
PA
9655 fprintf_unfiltered (gdb_stdlog,
9656 " Notification received: %s\n",
b3ced9ba 9657 str.c_str ());
74531fed 9658 }
fee9eda9
YQ
9659 if (is_notif != NULL)
9660 *is_notif = 1;
c906108c 9661
8d64371b 9662 handle_notification (rs->notif_state, buf->data ());
c906108c 9663
74531fed 9664 /* Notifications require no acknowledgement. */
a6f3e723 9665
74531fed 9666 if (expecting_notif)
fee9eda9 9667 return val;
74531fed
PA
9668 }
9669 }
9670}
9671
6b8edb51 9672int
8d64371b 9673remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
74531fed 9674{
8d64371b 9675 return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
74531fed
PA
9676}
9677
6b8edb51 9678int
8d64371b 9679remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
6b8edb51 9680 int *is_notif)
74531fed 9681{
8d64371b 9682 return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
c906108c 9683}
74531fed 9684
cbb8991c
DB
9685/* Kill any new fork children of process PID that haven't been
9686 processed by follow_fork. */
9687
6b8edb51
PA
9688void
9689remote_target::kill_new_fork_children (int pid)
cbb8991c 9690{
6b8edb51 9691 remote_state *rs = get_remote_state ();
cbb8991c 9692 struct notif_client *notif = &notif_client_stop;
cbb8991c
DB
9693
9694 /* Kill the fork child threads of any threads in process PID
9695 that are stopped at a fork event. */
08036331 9696 for (thread_info *thread : all_non_exited_threads ())
cbb8991c
DB
9697 {
9698 struct target_waitstatus *ws = &thread->pending_follow;
9699
9700 if (is_pending_fork_parent (ws, pid, thread->ptid))
9701 {
953edf2b 9702 int child_pid = ws->value.related_pid.pid ();
cbb8991c
DB
9703 int res;
9704
6b8edb51 9705 res = remote_vkill (child_pid);
cbb8991c
DB
9706 if (res != 0)
9707 error (_("Can't kill fork child process %d"), child_pid);
9708 }
9709 }
9710
9711 /* Check for any pending fork events (not reported or processed yet)
9712 in process PID and kill those fork child threads as well. */
9713 remote_notif_get_pending_events (notif);
953edf2b
TT
9714 for (auto &event : rs->stop_reply_queue)
9715 if (is_pending_fork_parent (&event->ws, pid, event->ptid))
9716 {
9717 int child_pid = event->ws.value.related_pid.pid ();
9718 int res;
9719
9720 res = remote_vkill (child_pid);
9721 if (res != 0)
9722 error (_("Can't kill fork child process %d"), child_pid);
9723 }
cbb8991c
DB
9724}
9725
c906108c 9726\f
8020350c
DB
9727/* Target hook to kill the current inferior. */
9728
f6ac5f3d
PA
9729void
9730remote_target::kill ()
43ff13b4 9731{
8020350c 9732 int res = -1;
e99b03dc 9733 int pid = inferior_ptid.pid ();
8020350c 9734 struct remote_state *rs = get_remote_state ();
0fdf84ca 9735
8020350c 9736 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 9737 {
8020350c
DB
9738 /* If we're stopped while forking and we haven't followed yet,
9739 kill the child task. We need to do this before killing the
9740 parent task because if this is a vfork then the parent will
9741 be sleeping. */
6b8edb51 9742 kill_new_fork_children (pid);
8020350c 9743
6b8edb51 9744 res = remote_vkill (pid);
8020350c 9745 if (res == 0)
0fdf84ca 9746 {
bc1e6c81 9747 target_mourn_inferior (inferior_ptid);
0fdf84ca
PA
9748 return;
9749 }
8020350c 9750 }
0fdf84ca 9751
8020350c
DB
9752 /* If we are in 'target remote' mode and we are killing the only
9753 inferior, then we will tell gdbserver to exit and unpush the
9754 target. */
9755 if (res == -1 && !remote_multi_process_p (rs)
9756 && number_of_live_inferiors () == 1)
9757 {
9758 remote_kill_k ();
9759
9760 /* We've killed the remote end, we get to mourn it. If we are
9761 not in extended mode, mourning the inferior also unpushes
9762 remote_ops from the target stack, which closes the remote
9763 connection. */
bc1e6c81 9764 target_mourn_inferior (inferior_ptid);
8020350c
DB
9765
9766 return;
0fdf84ca 9767 }
43ff13b4 9768
8020350c 9769 error (_("Can't kill process"));
43ff13b4
JM
9770}
9771
8020350c
DB
9772/* Send a kill request to the target using the 'vKill' packet. */
9773
6b8edb51
PA
9774int
9775remote_target::remote_vkill (int pid)
82f73884 9776{
4082afcc 9777 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
9778 return -1;
9779
6b8edb51
PA
9780 remote_state *rs = get_remote_state ();
9781
82f73884 9782 /* Tell the remote target to detach. */
8d64371b 9783 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
82f73884 9784 putpkt (rs->buf);
8d64371b 9785 getpkt (&rs->buf, 0);
82f73884 9786
4082afcc
PA
9787 switch (packet_ok (rs->buf,
9788 &remote_protocol_packets[PACKET_vKill]))
9789 {
9790 case PACKET_OK:
9791 return 0;
9792 case PACKET_ERROR:
9793 return 1;
9794 case PACKET_UNKNOWN:
9795 return -1;
9796 default:
9797 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9798 }
82f73884
PA
9799}
9800
8020350c
DB
9801/* Send a kill request to the target using the 'k' packet. */
9802
6b8edb51
PA
9803void
9804remote_target::remote_kill_k ()
82f73884 9805{
8020350c
DB
9806 /* Catch errors so the user can quit from gdb even when we
9807 aren't on speaking terms with the remote system. */
9808 TRY
82f73884 9809 {
82f73884 9810 putpkt ("k");
82f73884 9811 }
8020350c
DB
9812 CATCH (ex, RETURN_MASK_ERROR)
9813 {
9814 if (ex.error == TARGET_CLOSE_ERROR)
9815 {
9816 /* If we got an (EOF) error that caused the target
9817 to go away, then we're done, that's what we wanted.
9818 "k" is susceptible to cause a premature EOF, given
9819 that the remote server isn't actually required to
9820 reply to "k", and it can happen that it doesn't
9821 even get to reply ACK to the "k". */
9822 return;
9823 }
82f73884 9824
8020350c
DB
9825 /* Otherwise, something went wrong. We didn't actually kill
9826 the target. Just propagate the exception, and let the
9827 user or higher layers decide what to do. */
9828 throw_exception (ex);
9829 }
9830 END_CATCH
82f73884
PA
9831}
9832
f6ac5f3d
PA
9833void
9834remote_target::mourn_inferior ()
c906108c 9835{
8020350c 9836 struct remote_state *rs = get_remote_state ();
ce5ce7ed 9837
9607784a
PA
9838 /* We're no longer interested in notification events of an inferior
9839 that exited or was killed/detached. */
9840 discard_pending_stop_replies (current_inferior ());
9841
8020350c
DB
9842 /* In 'target remote' mode with one inferior, we close the connection. */
9843 if (!rs->extended && number_of_live_inferiors () <= 1)
9844 {
f6ac5f3d 9845 unpush_target (this);
c906108c 9846
8020350c
DB
9847 /* remote_close takes care of doing most of the clean up. */
9848 generic_mourn_inferior ();
9849 return;
9850 }
c906108c 9851
e24a49d8
PA
9852 /* In case we got here due to an error, but we're going to stay
9853 connected. */
9854 rs->waiting_for_stop_reply = 0;
9855
dc1981d7
PA
9856 /* If the current general thread belonged to the process we just
9857 detached from or has exited, the remote side current general
9858 thread becomes undefined. Considering a case like this:
9859
9860 - We just got here due to a detach.
9861 - The process that we're detaching from happens to immediately
9862 report a global breakpoint being hit in non-stop mode, in the
9863 same thread we had selected before.
9864 - GDB attaches to this process again.
9865 - This event happens to be the next event we handle.
9866
9867 GDB would consider that the current general thread didn't need to
9868 be set on the stub side (with Hg), since for all it knew,
9869 GENERAL_THREAD hadn't changed.
9870
9871 Notice that although in all-stop mode, the remote server always
9872 sets the current thread to the thread reporting the stop event,
9873 that doesn't happen in non-stop mode; in non-stop, the stub *must
9874 not* change the current thread when reporting a breakpoint hit,
9875 due to the decoupling of event reporting and event handling.
9876
9877 To keep things simple, we always invalidate our notion of the
9878 current thread. */
47f8a51d 9879 record_currthread (rs, minus_one_ptid);
dc1981d7 9880
8020350c 9881 /* Call common code to mark the inferior as not running. */
48aa3c27
PA
9882 generic_mourn_inferior ();
9883
d729566a 9884 if (!have_inferiors ())
2d717e4f 9885 {
82f73884
PA
9886 if (!remote_multi_process_p (rs))
9887 {
9888 /* Check whether the target is running now - some remote stubs
9889 automatically restart after kill. */
9890 putpkt ("?");
8d64371b 9891 getpkt (&rs->buf, 0);
82f73884
PA
9892
9893 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9894 {
3e43a32a
MS
9895 /* Assume that the target has been restarted. Set
9896 inferior_ptid so that bits of core GDB realizes
9897 there's something here, e.g., so that the user can
9898 say "kill" again. */
82f73884
PA
9899 inferior_ptid = magic_null_ptid;
9900 }
82f73884 9901 }
2d717e4f
DJ
9902 }
9903}
c906108c 9904
57810aa7 9905bool
f6ac5f3d 9906extended_remote_target::supports_disable_randomization ()
03583c20 9907{
4082afcc 9908 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
9909}
9910
6b8edb51
PA
9911void
9912remote_target::extended_remote_disable_randomization (int val)
03583c20
UW
9913{
9914 struct remote_state *rs = get_remote_state ();
9915 char *reply;
9916
8d64371b
TT
9917 xsnprintf (rs->buf.data (), get_remote_packet_size (),
9918 "QDisableRandomization:%x", val);
03583c20 9919 putpkt (rs->buf);
b6bb3468 9920 reply = remote_get_noisy_reply ();
03583c20
UW
9921 if (*reply == '\0')
9922 error (_("Target does not support QDisableRandomization."));
9923 if (strcmp (reply, "OK") != 0)
9924 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9925}
9926
6b8edb51
PA
9927int
9928remote_target::extended_remote_run (const std::string &args)
2d717e4f
DJ
9929{
9930 struct remote_state *rs = get_remote_state ();
2d717e4f 9931 int len;
94585166 9932 const char *remote_exec_file = get_remote_exec_file ();
c906108c 9933
2d717e4f
DJ
9934 /* If the user has disabled vRun support, or we have detected that
9935 support is not available, do not try it. */
4082afcc 9936 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 9937 return -1;
424163ea 9938
8d64371b
TT
9939 strcpy (rs->buf.data (), "vRun;");
9940 len = strlen (rs->buf.data ());
c906108c 9941
2d717e4f
DJ
9942 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9943 error (_("Remote file name too long for run packet"));
8d64371b 9944 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
9f1b45b0 9945 strlen (remote_exec_file));
2d717e4f 9946
7c5ded6a 9947 if (!args.empty ())
2d717e4f 9948 {
2d717e4f 9949 int i;
2d717e4f 9950
773a1edc 9951 gdb_argv argv (args.c_str ());
2d717e4f
DJ
9952 for (i = 0; argv[i] != NULL; i++)
9953 {
9954 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9955 error (_("Argument list too long for run packet"));
9956 rs->buf[len++] = ';';
8d64371b 9957 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
9f1b45b0 9958 strlen (argv[i]));
2d717e4f 9959 }
2d717e4f
DJ
9960 }
9961
9962 rs->buf[len++] = '\0';
9963
9964 putpkt (rs->buf);
8d64371b 9965 getpkt (&rs->buf, 0);
2d717e4f 9966
4082afcc 9967 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 9968 {
4082afcc 9969 case PACKET_OK:
3405876a 9970 /* We have a wait response. All is well. */
2d717e4f 9971 return 0;
4082afcc
PA
9972 case PACKET_UNKNOWN:
9973 return -1;
9974 case PACKET_ERROR:
2d717e4f
DJ
9975 if (remote_exec_file[0] == '\0')
9976 error (_("Running the default executable on the remote target failed; "
9977 "try \"set remote exec-file\"?"));
9978 else
9979 error (_("Running \"%s\" on the remote target failed"),
9980 remote_exec_file);
4082afcc
PA
9981 default:
9982 gdb_assert_not_reached (_("bad switch"));
2d717e4f 9983 }
c906108c
SS
9984}
9985
0a2dde4a
SDJ
9986/* Helper function to send set/unset environment packets. ACTION is
9987 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
9988 or "QEnvironmentUnsetVariable". VALUE is the variable to be
9989 sent. */
9990
6b8edb51
PA
9991void
9992remote_target::send_environment_packet (const char *action,
9993 const char *packet,
9994 const char *value)
0a2dde4a 9995{
6b8edb51
PA
9996 remote_state *rs = get_remote_state ();
9997
0a2dde4a
SDJ
9998 /* Convert the environment variable to an hex string, which
9999 is the best format to be transmitted over the wire. */
10000 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10001 strlen (value));
10002
8d64371b 10003 xsnprintf (rs->buf.data (), get_remote_packet_size (),
0a2dde4a
SDJ
10004 "%s:%s", packet, encoded_value.c_str ());
10005
10006 putpkt (rs->buf);
8d64371b
TT
10007 getpkt (&rs->buf, 0);
10008 if (strcmp (rs->buf.data (), "OK") != 0)
0a2dde4a
SDJ
10009 warning (_("Unable to %s environment variable '%s' on remote."),
10010 action, value);
10011}
10012
10013/* Helper function to handle the QEnvironment* packets. */
10014
6b8edb51
PA
10015void
10016remote_target::extended_remote_environment_support ()
0a2dde4a 10017{
6b8edb51
PA
10018 remote_state *rs = get_remote_state ();
10019
0a2dde4a
SDJ
10020 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10021 {
10022 putpkt ("QEnvironmentReset");
8d64371b
TT
10023 getpkt (&rs->buf, 0);
10024 if (strcmp (rs->buf.data (), "OK") != 0)
0a2dde4a
SDJ
10025 warning (_("Unable to reset environment on remote."));
10026 }
10027
10028 gdb_environ *e = &current_inferior ()->environment;
10029
10030 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10031 for (const std::string &el : e->user_set_env ())
6b8edb51 10032 send_environment_packet ("set", "QEnvironmentHexEncoded",
0a2dde4a
SDJ
10033 el.c_str ());
10034
10035 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10036 for (const std::string &el : e->user_unset_env ())
6b8edb51 10037 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
0a2dde4a
SDJ
10038}
10039
bc3b087d
SDJ
10040/* Helper function to set the current working directory for the
10041 inferior in the remote target. */
10042
6b8edb51
PA
10043void
10044remote_target::extended_remote_set_inferior_cwd ()
bc3b087d
SDJ
10045{
10046 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10047 {
10048 const char *inferior_cwd = get_inferior_cwd ();
6b8edb51 10049 remote_state *rs = get_remote_state ();
bc3b087d
SDJ
10050
10051 if (inferior_cwd != NULL)
10052 {
10053 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
10054 strlen (inferior_cwd));
10055
8d64371b 10056 xsnprintf (rs->buf.data (), get_remote_packet_size (),
bc3b087d
SDJ
10057 "QSetWorkingDir:%s", hexpath.c_str ());
10058 }
10059 else
10060 {
10061 /* An empty inferior_cwd means that the user wants us to
10062 reset the remote server's inferior's cwd. */
8d64371b 10063 xsnprintf (rs->buf.data (), get_remote_packet_size (),
bc3b087d
SDJ
10064 "QSetWorkingDir:");
10065 }
10066
10067 putpkt (rs->buf);
8d64371b 10068 getpkt (&rs->buf, 0);
bc3b087d
SDJ
10069 if (packet_ok (rs->buf,
10070 &remote_protocol_packets[PACKET_QSetWorkingDir])
10071 != PACKET_OK)
10072 error (_("\
10073Remote replied unexpectedly while setting the inferior's working\n\
10074directory: %s"),
8d64371b 10075 rs->buf.data ());
bc3b087d
SDJ
10076
10077 }
10078}
10079
2d717e4f
DJ
10080/* In the extended protocol we want to be able to do things like
10081 "run" and have them basically work as expected. So we need
10082 a special create_inferior function. We support changing the
10083 executable file and the command line arguments, but not the
10084 environment. */
10085
f6ac5f3d
PA
10086void
10087extended_remote_target::create_inferior (const char *exec_file,
10088 const std::string &args,
10089 char **env, int from_tty)
43ff13b4 10090{
3405876a
PA
10091 int run_worked;
10092 char *stop_reply;
10093 struct remote_state *rs = get_remote_state ();
94585166 10094 const char *remote_exec_file = get_remote_exec_file ();
3405876a 10095
43ff13b4 10096 /* If running asynchronously, register the target file descriptor
23860348 10097 with the event loop. */
75c99385 10098 if (target_can_async_p ())
6a3753b3 10099 target_async (1);
43ff13b4 10100
03583c20 10101 /* Disable address space randomization if requested (and supported). */
f6ac5f3d 10102 if (supports_disable_randomization ())
03583c20
UW
10103 extended_remote_disable_randomization (disable_randomization);
10104
aefd8b33
SDJ
10105 /* If startup-with-shell is on, we inform gdbserver to start the
10106 remote inferior using a shell. */
10107 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10108 {
8d64371b 10109 xsnprintf (rs->buf.data (), get_remote_packet_size (),
aefd8b33
SDJ
10110 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10111 putpkt (rs->buf);
8d64371b
TT
10112 getpkt (&rs->buf, 0);
10113 if (strcmp (rs->buf.data (), "OK") != 0)
aefd8b33
SDJ
10114 error (_("\
10115Remote replied unexpectedly while setting startup-with-shell: %s"),
8d64371b 10116 rs->buf.data ());
aefd8b33
SDJ
10117 }
10118
6b8edb51 10119 extended_remote_environment_support ();
0a2dde4a 10120
6b8edb51 10121 extended_remote_set_inferior_cwd ();
bc3b087d 10122
43ff13b4 10123 /* Now restart the remote server. */
3405876a
PA
10124 run_worked = extended_remote_run (args) != -1;
10125 if (!run_worked)
2d717e4f
DJ
10126 {
10127 /* vRun was not supported. Fail if we need it to do what the
10128 user requested. */
10129 if (remote_exec_file[0])
10130 error (_("Remote target does not support \"set remote exec-file\""));
7c5ded6a 10131 if (!args.empty ())
65e65158 10132 error (_("Remote target does not support \"set args\" or run ARGS"));
43ff13b4 10133
2d717e4f
DJ
10134 /* Fall back to "R". */
10135 extended_remote_restart ();
10136 }
424163ea 10137
3405876a 10138 /* vRun's success return is a stop reply. */
8d64371b 10139 stop_reply = run_worked ? rs->buf.data () : NULL;
3405876a 10140 add_current_inferior_and_thread (stop_reply);
c0a2216e 10141
2d717e4f
DJ
10142 /* Get updated offsets, if the stub uses qOffsets. */
10143 get_offsets ();
2d717e4f 10144}
c906108c 10145\f
c5aa993b 10146
b775012e
LM
10147/* Given a location's target info BP_TGT and the packet buffer BUF, output
10148 the list of conditions (in agent expression bytecode format), if any, the
10149 target needs to evaluate. The output is placed into the packet buffer
bba74b36 10150 started from BUF and ended at BUF_END. */
b775012e
LM
10151
10152static int
10153remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
10154 struct bp_target_info *bp_tgt, char *buf,
10155 char *buf_end)
b775012e 10156{
3cde5c42 10157 if (bp_tgt->conditions.empty ())
b775012e
LM
10158 return 0;
10159
10160 buf += strlen (buf);
bba74b36 10161 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
10162 buf++;
10163
83621223 10164 /* Send conditions to the target. */
d538e36d 10165 for (agent_expr *aexpr : bp_tgt->conditions)
b775012e 10166 {
bba74b36 10167 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e 10168 buf += strlen (buf);
3cde5c42 10169 for (int i = 0; i < aexpr->len; ++i)
b775012e
LM
10170 buf = pack_hex_byte (buf, aexpr->buf[i]);
10171 *buf = '\0';
10172 }
b775012e
LM
10173 return 0;
10174}
10175
d3ce09f5
SS
10176static void
10177remote_add_target_side_commands (struct gdbarch *gdbarch,
10178 struct bp_target_info *bp_tgt, char *buf)
10179{
3cde5c42 10180 if (bp_tgt->tcommands.empty ())
d3ce09f5
SS
10181 return;
10182
10183 buf += strlen (buf);
10184
10185 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10186 buf += strlen (buf);
10187
10188 /* Concatenate all the agent expressions that are commands into the
10189 cmds parameter. */
df97be55 10190 for (agent_expr *aexpr : bp_tgt->tcommands)
d3ce09f5
SS
10191 {
10192 sprintf (buf, "X%x,", aexpr->len);
10193 buf += strlen (buf);
3cde5c42 10194 for (int i = 0; i < aexpr->len; ++i)
d3ce09f5
SS
10195 buf = pack_hex_byte (buf, aexpr->buf[i]);
10196 *buf = '\0';
10197 }
d3ce09f5
SS
10198}
10199
8181d85f
DJ
10200/* Insert a breakpoint. On targets that have software breakpoint
10201 support, we ask the remote target to do the work; on targets
10202 which don't, we insert a traditional memory breakpoint. */
c906108c 10203
f6ac5f3d
PA
10204int
10205remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10206 struct bp_target_info *bp_tgt)
c906108c 10207{
d471ea57
AC
10208 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10209 If it succeeds, then set the support to PACKET_ENABLE. If it
10210 fails, and the user has explicitly requested the Z support then
23860348 10211 report an error, otherwise, mark it disabled and go on. */
802188a7 10212
4082afcc 10213 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10214 {
0d5ed153 10215 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10216 struct remote_state *rs;
bba74b36 10217 char *p, *endbuf;
4fff2411 10218
28439a30
PA
10219 /* Make sure the remote is pointing at the right process, if
10220 necessary. */
10221 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10222 set_general_process ();
10223
4fff2411 10224 rs = get_remote_state ();
8d64371b
TT
10225 p = rs->buf.data ();
10226 endbuf = p + get_remote_packet_size ();
802188a7 10227
96baa820
JM
10228 *(p++) = 'Z';
10229 *(p++) = '0';
10230 *(p++) = ',';
7c0f6dcc 10231 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 10232 p += hexnumstr (p, addr);
579c6ad9 10233 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10234
f6ac5f3d 10235 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10236 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10237
f6ac5f3d 10238 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10239 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10240
6d820c5c 10241 putpkt (rs->buf);
8d64371b 10242 getpkt (&rs->buf, 0);
96baa820 10243
6d820c5c 10244 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 10245 {
d471ea57
AC
10246 case PACKET_ERROR:
10247 return -1;
10248 case PACKET_OK:
10249 return 0;
10250 case PACKET_UNKNOWN:
10251 break;
96baa820
JM
10252 }
10253 }
c906108c 10254
0000e5cc
PA
10255 /* If this breakpoint has target-side commands but this stub doesn't
10256 support Z0 packets, throw error. */
3cde5c42 10257 if (!bp_tgt->tcommands.empty ())
0000e5cc
PA
10258 throw_error (NOT_SUPPORTED_ERROR, _("\
10259Target doesn't support breakpoints that have target side commands."));
10260
f6ac5f3d 10261 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
c906108c
SS
10262}
10263
f6ac5f3d
PA
10264int
10265remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10266 struct bp_target_info *bp_tgt,
10267 enum remove_bp_reason reason)
c906108c 10268{
8181d85f 10269 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 10270 struct remote_state *rs = get_remote_state ();
96baa820 10271
4082afcc 10272 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10273 {
8d64371b
TT
10274 char *p = rs->buf.data ();
10275 char *endbuf = p + get_remote_packet_size ();
802188a7 10276
28439a30
PA
10277 /* Make sure the remote is pointing at the right process, if
10278 necessary. */
10279 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10280 set_general_process ();
10281
96baa820
JM
10282 *(p++) = 'z';
10283 *(p++) = '0';
10284 *(p++) = ',';
10285
8181d85f
DJ
10286 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10287 p += hexnumstr (p, addr);
579c6ad9 10288 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10289
6d820c5c 10290 putpkt (rs->buf);
8d64371b 10291 getpkt (&rs->buf, 0);
96baa820 10292
6d820c5c 10293 return (rs->buf[0] == 'E');
96baa820
JM
10294 }
10295
f6ac5f3d 10296 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
c906108c
SS
10297}
10298
f486487f 10299static enum Z_packet_type
d471ea57
AC
10300watchpoint_to_Z_packet (int type)
10301{
10302 switch (type)
10303 {
10304 case hw_write:
bb858e6a 10305 return Z_PACKET_WRITE_WP;
d471ea57
AC
10306 break;
10307 case hw_read:
bb858e6a 10308 return Z_PACKET_READ_WP;
d471ea57
AC
10309 break;
10310 case hw_access:
bb858e6a 10311 return Z_PACKET_ACCESS_WP;
d471ea57
AC
10312 break;
10313 default:
8e65ff28 10314 internal_error (__FILE__, __LINE__,
e2e0b3e5 10315 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
10316 }
10317}
10318
f6ac5f3d
PA
10319int
10320remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10321 enum target_hw_bp_type type, struct expression *cond)
96baa820 10322{
d01949b6 10323 struct remote_state *rs = get_remote_state ();
8d64371b 10324 char *endbuf = rs->buf.data () + get_remote_packet_size ();
e514a9d6 10325 char *p;
d471ea57 10326 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 10327
4082afcc 10328 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 10329 return 1;
802188a7 10330
28439a30
PA
10331 /* Make sure the remote is pointing at the right process, if
10332 necessary. */
10333 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10334 set_general_process ();
10335
8d64371b
TT
10336 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10337 p = strchr (rs->buf.data (), '\0');
96baa820
JM
10338 addr = remote_address_masked (addr);
10339 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10340 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 10341
6d820c5c 10342 putpkt (rs->buf);
8d64371b 10343 getpkt (&rs->buf, 0);
96baa820 10344
6d820c5c 10345 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10346 {
10347 case PACKET_ERROR:
d471ea57 10348 return -1;
85d721b8
PA
10349 case PACKET_UNKNOWN:
10350 return 1;
d471ea57
AC
10351 case PACKET_OK:
10352 return 0;
10353 }
8e65ff28 10354 internal_error (__FILE__, __LINE__,
e2e0b3e5 10355 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
10356}
10357
57810aa7 10358bool
f6ac5f3d
PA
10359remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10360 CORE_ADDR start, int length)
283002cf
MR
10361{
10362 CORE_ADDR diff = remote_address_masked (addr - start);
10363
10364 return diff < length;
10365}
10366
d471ea57 10367
f6ac5f3d
PA
10368int
10369remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10370 enum target_hw_bp_type type, struct expression *cond)
96baa820 10371{
d01949b6 10372 struct remote_state *rs = get_remote_state ();
8d64371b 10373 char *endbuf = rs->buf.data () + get_remote_packet_size ();
e514a9d6 10374 char *p;
d471ea57
AC
10375 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10376
4082afcc 10377 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 10378 return -1;
802188a7 10379
28439a30
PA
10380 /* Make sure the remote is pointing at the right process, if
10381 necessary. */
10382 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10383 set_general_process ();
10384
8d64371b
TT
10385 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10386 p = strchr (rs->buf.data (), '\0');
96baa820
JM
10387 addr = remote_address_masked (addr);
10388 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10389 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c 10390 putpkt (rs->buf);
8d64371b 10391 getpkt (&rs->buf, 0);
96baa820 10392
6d820c5c 10393 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10394 {
10395 case PACKET_ERROR:
10396 case PACKET_UNKNOWN:
10397 return -1;
10398 case PACKET_OK:
10399 return 0;
10400 }
8e65ff28 10401 internal_error (__FILE__, __LINE__,
e2e0b3e5 10402 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
10403}
10404
3c3bea1c 10405
501eef12 10406int remote_hw_watchpoint_limit = -1;
480a3f21 10407int remote_hw_watchpoint_length_limit = -1;
501eef12 10408int remote_hw_breakpoint_limit = -1;
d471ea57 10409
f6ac5f3d
PA
10410int
10411remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
480a3f21
PW
10412{
10413 if (remote_hw_watchpoint_length_limit == 0)
10414 return 0;
10415 else if (remote_hw_watchpoint_length_limit < 0)
10416 return 1;
10417 else if (len <= remote_hw_watchpoint_length_limit)
10418 return 1;
10419 else
10420 return 0;
10421}
10422
f6ac5f3d
PA
10423int
10424remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
96baa820 10425{
3c3bea1c
GS
10426 if (type == bp_hardware_breakpoint)
10427 {
10428 if (remote_hw_breakpoint_limit == 0)
10429 return 0;
501eef12
AC
10430 else if (remote_hw_breakpoint_limit < 0)
10431 return 1;
3c3bea1c
GS
10432 else if (cnt <= remote_hw_breakpoint_limit)
10433 return 1;
10434 }
10435 else
10436 {
10437 if (remote_hw_watchpoint_limit == 0)
10438 return 0;
501eef12
AC
10439 else if (remote_hw_watchpoint_limit < 0)
10440 return 1;
3c3bea1c
GS
10441 else if (ot)
10442 return -1;
10443 else if (cnt <= remote_hw_watchpoint_limit)
10444 return 1;
10445 }
10446 return -1;
10447}
10448
f7e6eed5
PA
10449/* The to_stopped_by_sw_breakpoint method of target remote. */
10450
57810aa7 10451bool
f6ac5f3d 10452remote_target::stopped_by_sw_breakpoint ()
f7e6eed5 10453{
799a2abe 10454 struct thread_info *thread = inferior_thread ();
f7e6eed5 10455
799a2abe 10456 return (thread->priv != NULL
7aabaf9d
SM
10457 && (get_remote_thread_info (thread)->stop_reason
10458 == TARGET_STOPPED_BY_SW_BREAKPOINT));
f7e6eed5
PA
10459}
10460
10461/* The to_supports_stopped_by_sw_breakpoint method of target
10462 remote. */
10463
57810aa7 10464bool
f6ac5f3d 10465remote_target::supports_stopped_by_sw_breakpoint ()
f7e6eed5 10466{
f7e6eed5
PA
10467 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10468}
10469
10470/* The to_stopped_by_hw_breakpoint method of target remote. */
10471
57810aa7 10472bool
f6ac5f3d 10473remote_target::stopped_by_hw_breakpoint ()
f7e6eed5 10474{
799a2abe 10475 struct thread_info *thread = inferior_thread ();
f7e6eed5 10476
799a2abe 10477 return (thread->priv != NULL
7aabaf9d
SM
10478 && (get_remote_thread_info (thread)->stop_reason
10479 == TARGET_STOPPED_BY_HW_BREAKPOINT));
f7e6eed5
PA
10480}
10481
10482/* The to_supports_stopped_by_hw_breakpoint method of target
10483 remote. */
10484
57810aa7 10485bool
f6ac5f3d 10486remote_target::supports_stopped_by_hw_breakpoint ()
f7e6eed5 10487{
f7e6eed5
PA
10488 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10489}
10490
57810aa7 10491bool
f6ac5f3d 10492remote_target::stopped_by_watchpoint ()
3c3bea1c 10493{
799a2abe 10494 struct thread_info *thread = inferior_thread ();
ee154bee 10495
799a2abe 10496 return (thread->priv != NULL
7aabaf9d
SM
10497 && (get_remote_thread_info (thread)->stop_reason
10498 == TARGET_STOPPED_BY_WATCHPOINT));
3c3bea1c
GS
10499}
10500
57810aa7 10501bool
f6ac5f3d 10502remote_target::stopped_data_address (CORE_ADDR *addr_p)
3c3bea1c 10503{
799a2abe 10504 struct thread_info *thread = inferior_thread ();
a744cf53 10505
799a2abe 10506 if (thread->priv != NULL
7aabaf9d
SM
10507 && (get_remote_thread_info (thread)->stop_reason
10508 == TARGET_STOPPED_BY_WATCHPOINT))
4aa7a7f5 10509 {
7aabaf9d 10510 *addr_p = get_remote_thread_info (thread)->watch_data_address;
57810aa7 10511 return true;
4aa7a7f5
JJ
10512 }
10513
57810aa7 10514 return false;
3c3bea1c
GS
10515}
10516
10517
f6ac5f3d
PA
10518int
10519remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10520 struct bp_target_info *bp_tgt)
3c3bea1c 10521{
0d5ed153 10522 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10523 struct remote_state *rs;
bba74b36 10524 char *p, *endbuf;
dd61ec5c 10525 char *message;
3c3bea1c 10526
4082afcc 10527 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10528 return -1;
2bc416ba 10529
28439a30
PA
10530 /* Make sure the remote is pointing at the right process, if
10531 necessary. */
10532 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10533 set_general_process ();
10534
4fff2411 10535 rs = get_remote_state ();
8d64371b
TT
10536 p = rs->buf.data ();
10537 endbuf = p + get_remote_packet_size ();
4fff2411 10538
96baa820
JM
10539 *(p++) = 'Z';
10540 *(p++) = '1';
10541 *(p++) = ',';
802188a7 10542
0d5ed153 10543 addr = remote_address_masked (addr);
96baa820 10544 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10545 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10546
f6ac5f3d 10547 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10548 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10549
f6ac5f3d 10550 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10551 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10552
6d820c5c 10553 putpkt (rs->buf);
8d64371b 10554 getpkt (&rs->buf, 0);
96baa820 10555
6d820c5c 10556 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10557 {
10558 case PACKET_ERROR:
dd61ec5c
MW
10559 if (rs->buf[1] == '.')
10560 {
8d64371b 10561 message = strchr (&rs->buf[2], '.');
dd61ec5c 10562 if (message)
0316657e 10563 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
10564 }
10565 return -1;
d471ea57
AC
10566 case PACKET_UNKNOWN:
10567 return -1;
10568 case PACKET_OK:
10569 return 0;
10570 }
8e65ff28 10571 internal_error (__FILE__, __LINE__,
e2e0b3e5 10572 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
10573}
10574
d471ea57 10575
f6ac5f3d
PA
10576int
10577remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10578 struct bp_target_info *bp_tgt)
96baa820 10579{
8181d85f 10580 CORE_ADDR addr;
d01949b6 10581 struct remote_state *rs = get_remote_state ();
8d64371b
TT
10582 char *p = rs->buf.data ();
10583 char *endbuf = p + get_remote_packet_size ();
c8189ed1 10584
4082afcc 10585 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10586 return -1;
802188a7 10587
28439a30
PA
10588 /* Make sure the remote is pointing at the right process, if
10589 necessary. */
10590 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10591 set_general_process ();
10592
96baa820
JM
10593 *(p++) = 'z';
10594 *(p++) = '1';
10595 *(p++) = ',';
802188a7 10596
8181d85f 10597 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 10598 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10599 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10600
6d820c5c 10601 putpkt (rs->buf);
8d64371b 10602 getpkt (&rs->buf, 0);
802188a7 10603
6d820c5c 10604 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10605 {
10606 case PACKET_ERROR:
10607 case PACKET_UNKNOWN:
10608 return -1;
10609 case PACKET_OK:
10610 return 0;
10611 }
8e65ff28 10612 internal_error (__FILE__, __LINE__,
e2e0b3e5 10613 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 10614}
96baa820 10615
4a5e7a5b
PA
10616/* Verify memory using the "qCRC:" request. */
10617
f6ac5f3d
PA
10618int
10619remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
4a5e7a5b
PA
10620{
10621 struct remote_state *rs = get_remote_state ();
10622 unsigned long host_crc, target_crc;
10623 char *tmp;
10624
936d2992
PA
10625 /* It doesn't make sense to use qCRC if the remote target is
10626 connected but not running. */
10627 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10628 {
10629 enum packet_result result;
28439a30 10630
936d2992
PA
10631 /* Make sure the remote is pointing at the right process. */
10632 set_general_process ();
4a5e7a5b 10633
936d2992 10634 /* FIXME: assumes lma can fit into long. */
8d64371b 10635 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
936d2992
PA
10636 (long) lma, (long) size);
10637 putpkt (rs->buf);
4a5e7a5b 10638
936d2992
PA
10639 /* Be clever; compute the host_crc before waiting for target
10640 reply. */
10641 host_crc = xcrc32 (data, size, 0xffffffff);
10642
8d64371b 10643 getpkt (&rs->buf, 0);
4a5e7a5b 10644
936d2992
PA
10645 result = packet_ok (rs->buf,
10646 &remote_protocol_packets[PACKET_qCRC]);
10647 if (result == PACKET_ERROR)
10648 return -1;
10649 else if (result == PACKET_OK)
10650 {
10651 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10652 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 10653
936d2992
PA
10654 return (host_crc == target_crc);
10655 }
10656 }
4a5e7a5b 10657
f6ac5f3d 10658 return simple_verify_memory (this, data, lma, size);
4a5e7a5b
PA
10659}
10660
c906108c
SS
10661/* compare-sections command
10662
10663 With no arguments, compares each loadable section in the exec bfd
10664 with the same memory range on the target, and reports mismatches.
4a5e7a5b 10665 Useful for verifying the image on the target against the exec file. */
e514a9d6 10666
c906108c 10667static void
ac88e2de 10668compare_sections_command (const char *args, int from_tty)
c906108c
SS
10669{
10670 asection *s;
ce359b09 10671 const char *sectname;
c906108c
SS
10672 bfd_size_type size;
10673 bfd_vma lma;
10674 int matched = 0;
10675 int mismatched = 0;
4a5e7a5b 10676 int res;
95cf3b38 10677 int read_only = 0;
c906108c
SS
10678
10679 if (!exec_bfd)
8a3fe4f8 10680 error (_("command cannot be used without an exec file"));
c906108c 10681
95cf3b38
DT
10682 if (args != NULL && strcmp (args, "-r") == 0)
10683 {
10684 read_only = 1;
10685 args = NULL;
10686 }
10687
c5aa993b 10688 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
10689 {
10690 if (!(s->flags & SEC_LOAD))
0df8b418 10691 continue; /* Skip non-loadable section. */
c906108c 10692
95cf3b38
DT
10693 if (read_only && (s->flags & SEC_READONLY) == 0)
10694 continue; /* Skip writeable sections */
10695
2c500098 10696 size = bfd_get_section_size (s);
c906108c 10697 if (size == 0)
0df8b418 10698 continue; /* Skip zero-length section. */
c906108c 10699
ce359b09 10700 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 10701 if (args && strcmp (args, sectname) != 0)
0df8b418 10702 continue; /* Not the section selected by user. */
c906108c 10703
0df8b418 10704 matched = 1; /* Do this section. */
c906108c 10705 lma = s->lma;
c906108c 10706
b80406ac
TT
10707 gdb::byte_vector sectdata (size);
10708 bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
c906108c 10709
b80406ac 10710 res = target_verify_memory (sectdata.data (), lma, size);
4a5e7a5b
PA
10711
10712 if (res == -1)
5af949e3 10713 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
10714 paddress (target_gdbarch (), lma),
10715 paddress (target_gdbarch (), lma + size));
c906108c 10716
5af949e3 10717 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
10718 paddress (target_gdbarch (), lma),
10719 paddress (target_gdbarch (), lma + size));
4a5e7a5b 10720 if (res)
c906108c
SS
10721 printf_filtered ("matched.\n");
10722 else
c5aa993b
JM
10723 {
10724 printf_filtered ("MIS-MATCHED!\n");
10725 mismatched++;
10726 }
c906108c
SS
10727 }
10728 if (mismatched > 0)
936d2992 10729 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 10730the loaded file\n"));
c906108c 10731 if (args && !matched)
a3f17187 10732 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
10733}
10734
0e7f50da
UW
10735/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10736 into remote target. The number of bytes written to the remote
10737 target is returned, or -1 for error. */
10738
6b8edb51
PA
10739target_xfer_status
10740remote_target::remote_write_qxfer (const char *object_name,
10741 const char *annex, const gdb_byte *writebuf,
10742 ULONGEST offset, LONGEST len,
10743 ULONGEST *xfered_len,
10744 struct packet_config *packet)
0e7f50da
UW
10745{
10746 int i, buf_len;
10747 ULONGEST n;
0e7f50da
UW
10748 struct remote_state *rs = get_remote_state ();
10749 int max_size = get_memory_write_packet_size ();
10750
7cc244de 10751 if (packet_config_support (packet) == PACKET_DISABLE)
2ed4b548 10752 return TARGET_XFER_E_IO;
0e7f50da
UW
10753
10754 /* Insert header. */
8d64371b 10755 i = snprintf (rs->buf.data (), max_size,
0e7f50da
UW
10756 "qXfer:%s:write:%s:%s:",
10757 object_name, annex ? annex : "",
10758 phex_nz (offset, sizeof offset));
10759 max_size -= (i + 1);
10760
10761 /* Escape as much data as fits into rs->buf. */
10762 buf_len = remote_escape_output
8d64371b 10763 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
0e7f50da 10764
8d64371b
TT
10765 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
10766 || getpkt_sane (&rs->buf, 0) < 0
0e7f50da 10767 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10768 return TARGET_XFER_E_IO;
0e7f50da 10769
8d64371b 10770 unpack_varlen_hex (rs->buf.data (), &n);
9b409511
YQ
10771
10772 *xfered_len = n;
92ffd475 10773 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
0e7f50da
UW
10774}
10775
0876f84a
DJ
10776/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10777 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10778 number of bytes read is returned, or 0 for EOF, or -1 for error.
10779 The number of bytes read may be less than LEN without indicating an
10780 EOF. PACKET is checked and updated to indicate whether the remote
10781 target supports this object. */
10782
6b8edb51
PA
10783target_xfer_status
10784remote_target::remote_read_qxfer (const char *object_name,
10785 const char *annex,
10786 gdb_byte *readbuf, ULONGEST offset,
10787 LONGEST len,
10788 ULONGEST *xfered_len,
10789 struct packet_config *packet)
0876f84a 10790{
0876f84a 10791 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
10792 LONGEST i, n, packet_len;
10793
7cc244de 10794 if (packet_config_support (packet) == PACKET_DISABLE)
2ed4b548 10795 return TARGET_XFER_E_IO;
0876f84a
DJ
10796
10797 /* Check whether we've cached an end-of-object packet that matches
10798 this request. */
8e88304f 10799 if (rs->finished_object)
0876f84a 10800 {
8e88304f
TT
10801 if (strcmp (object_name, rs->finished_object) == 0
10802 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10803 && offset == rs->finished_offset)
9b409511
YQ
10804 return TARGET_XFER_EOF;
10805
0876f84a
DJ
10806
10807 /* Otherwise, we're now reading something different. Discard
10808 the cache. */
8e88304f
TT
10809 xfree (rs->finished_object);
10810 xfree (rs->finished_annex);
10811 rs->finished_object = NULL;
10812 rs->finished_annex = NULL;
0876f84a
DJ
10813 }
10814
10815 /* Request only enough to fit in a single packet. The actual data
10816 may not, since we don't know how much of it will need to be escaped;
10817 the target is free to respond with slightly less data. We subtract
10818 five to account for the response type and the protocol frame. */
768adc05 10819 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
8d64371b
TT
10820 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
10821 "qXfer:%s:read:%s:%s,%s",
0876f84a
DJ
10822 object_name, annex ? annex : "",
10823 phex_nz (offset, sizeof offset),
10824 phex_nz (n, sizeof n));
10825 i = putpkt (rs->buf);
10826 if (i < 0)
2ed4b548 10827 return TARGET_XFER_E_IO;
0876f84a
DJ
10828
10829 rs->buf[0] = '\0';
8d64371b 10830 packet_len = getpkt_sane (&rs->buf, 0);
0876f84a 10831 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10832 return TARGET_XFER_E_IO;
0876f84a
DJ
10833
10834 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8d64371b 10835 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
0876f84a
DJ
10836
10837 /* 'm' means there is (or at least might be) more data after this
10838 batch. That does not make sense unless there's at least one byte
10839 of data in this reply. */
10840 if (rs->buf[0] == 'm' && packet_len == 1)
10841 error (_("Remote qXfer reply contained no data."));
10842
10843 /* Got some data. */
8d64371b 10844 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
bc20a4af 10845 packet_len - 1, readbuf, n);
0876f84a
DJ
10846
10847 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
10848 or possibly empty. If we have the final block of a non-empty
10849 object, record this fact to bypass a subsequent partial read. */
10850 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 10851 {
8e88304f
TT
10852 rs->finished_object = xstrdup (object_name);
10853 rs->finished_annex = xstrdup (annex ? annex : "");
10854 rs->finished_offset = offset + i;
0876f84a
DJ
10855 }
10856
9b409511
YQ
10857 if (i == 0)
10858 return TARGET_XFER_EOF;
10859 else
10860 {
10861 *xfered_len = i;
10862 return TARGET_XFER_OK;
10863 }
0876f84a
DJ
10864}
10865
f6ac5f3d
PA
10866enum target_xfer_status
10867remote_target::xfer_partial (enum target_object object,
10868 const char *annex, gdb_byte *readbuf,
10869 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10870 ULONGEST *xfered_len)
c906108c 10871{
82f73884 10872 struct remote_state *rs;
c906108c 10873 int i;
6d820c5c 10874 char *p2;
1e3ff5ad 10875 char query_type;
124e13d9 10876 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 10877
e6e4e701 10878 set_remote_traceframe ();
82f73884
PA
10879 set_general_thread (inferior_ptid);
10880
10881 rs = get_remote_state ();
10882
b2182ed2 10883 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
10884 if (object == TARGET_OBJECT_MEMORY)
10885 {
2d717e4f
DJ
10886 /* If the remote target is connected but not running, we should
10887 pass this request down to a lower stratum (e.g. the executable
10888 file). */
10889 if (!target_has_execution)
9b409511 10890 return TARGET_XFER_EOF;
2d717e4f 10891
21e3b9b9 10892 if (writebuf != NULL)
124e13d9
SM
10893 return remote_write_bytes (offset, writebuf, len, unit_size,
10894 xfered_len);
21e3b9b9 10895 else
6b8edb51 10896 return remote_read_bytes (offset, readbuf, len, unit_size,
124e13d9 10897 xfered_len);
21e3b9b9
DJ
10898 }
10899
0df8b418 10900 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
10901 if (object == TARGET_OBJECT_SPU)
10902 {
10903 if (readbuf)
f6ac5f3d 10904 return remote_read_qxfer ("spu", annex, readbuf, offset, len,
9b409511
YQ
10905 xfered_len, &remote_protocol_packets
10906 [PACKET_qXfer_spu_read]);
0e7f50da 10907 else
f6ac5f3d 10908 return remote_write_qxfer ("spu", annex, writebuf, offset, len,
9b409511
YQ
10909 xfered_len, &remote_protocol_packets
10910 [PACKET_qXfer_spu_write]);
0e7f50da
UW
10911 }
10912
4aa995e1
PA
10913 /* Handle extra signal info using qxfer packets. */
10914 if (object == TARGET_OBJECT_SIGNAL_INFO)
10915 {
10916 if (readbuf)
f6ac5f3d 10917 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
9b409511 10918 xfered_len, &remote_protocol_packets
4aa995e1
PA
10919 [PACKET_qXfer_siginfo_read]);
10920 else
f6ac5f3d 10921 return remote_write_qxfer ("siginfo", annex,
9b409511 10922 writebuf, offset, len, xfered_len,
4aa995e1
PA
10923 &remote_protocol_packets
10924 [PACKET_qXfer_siginfo_write]);
10925 }
10926
0fb4aa4b
PA
10927 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10928 {
10929 if (readbuf)
f6ac5f3d 10930 return remote_read_qxfer ("statictrace", annex,
9b409511 10931 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
10932 &remote_protocol_packets
10933 [PACKET_qXfer_statictrace_read]);
10934 else
2ed4b548 10935 return TARGET_XFER_E_IO;
0fb4aa4b
PA
10936 }
10937
a76d924d
DJ
10938 /* Only handle flash writes. */
10939 if (writebuf != NULL)
10940 {
a76d924d
DJ
10941 switch (object)
10942 {
10943 case TARGET_OBJECT_FLASH:
6b8edb51 10944 return remote_flash_write (offset, len, xfered_len,
9b409511 10945 writebuf);
a76d924d
DJ
10946
10947 default:
2ed4b548 10948 return TARGET_XFER_E_IO;
a76d924d
DJ
10949 }
10950 }
4b8a223f 10951
1e3ff5ad
AC
10952 /* Map pre-existing objects onto letters. DO NOT do this for new
10953 objects!!! Instead specify new query packets. */
10954 switch (object)
c906108c 10955 {
1e3ff5ad
AC
10956 case TARGET_OBJECT_AVR:
10957 query_type = 'R';
10958 break;
802188a7
RM
10959
10960 case TARGET_OBJECT_AUXV:
0876f84a 10961 gdb_assert (annex == NULL);
f6ac5f3d 10962 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
9b409511 10963 xfered_len,
0876f84a 10964 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 10965
23181151
DJ
10966 case TARGET_OBJECT_AVAILABLE_FEATURES:
10967 return remote_read_qxfer
f6ac5f3d 10968 ("features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
10969 &remote_protocol_packets[PACKET_qXfer_features]);
10970
cfa9d6d9
DJ
10971 case TARGET_OBJECT_LIBRARIES:
10972 return remote_read_qxfer
f6ac5f3d 10973 ("libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
10974 &remote_protocol_packets[PACKET_qXfer_libraries]);
10975
2268b414
JK
10976 case TARGET_OBJECT_LIBRARIES_SVR4:
10977 return remote_read_qxfer
f6ac5f3d 10978 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
10979 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10980
fd79ecee
DJ
10981 case TARGET_OBJECT_MEMORY_MAP:
10982 gdb_assert (annex == NULL);
f6ac5f3d 10983 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
9b409511 10984 xfered_len,
fd79ecee
DJ
10985 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10986
07e059b5
VP
10987 case TARGET_OBJECT_OSDATA:
10988 /* Should only get here if we're connected. */
5d93a237 10989 gdb_assert (rs->remote_desc);
07e059b5 10990 return remote_read_qxfer
f6ac5f3d 10991 ("osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
10992 &remote_protocol_packets[PACKET_qXfer_osdata]);
10993
dc146f7c
VP
10994 case TARGET_OBJECT_THREADS:
10995 gdb_assert (annex == NULL);
f6ac5f3d 10996 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
9b409511 10997 xfered_len,
dc146f7c
VP
10998 &remote_protocol_packets[PACKET_qXfer_threads]);
10999
b3b9301e
PA
11000 case TARGET_OBJECT_TRACEFRAME_INFO:
11001 gdb_assert (annex == NULL);
11002 return remote_read_qxfer
f6ac5f3d 11003 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 11004 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
11005
11006 case TARGET_OBJECT_FDPIC:
f6ac5f3d 11007 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
9b409511 11008 xfered_len,
78d85199 11009 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
11010
11011 case TARGET_OBJECT_OPENVMS_UIB:
f6ac5f3d 11012 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
9b409511 11013 xfered_len,
169081d0
TG
11014 &remote_protocol_packets[PACKET_qXfer_uib]);
11015
9accd112 11016 case TARGET_OBJECT_BTRACE:
f6ac5f3d 11017 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
9b409511 11018 xfered_len,
9accd112
MM
11019 &remote_protocol_packets[PACKET_qXfer_btrace]);
11020
f4abbc16 11021 case TARGET_OBJECT_BTRACE_CONF:
f6ac5f3d 11022 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
f4abbc16
MM
11023 len, xfered_len,
11024 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11025
c78fa86a 11026 case TARGET_OBJECT_EXEC_FILE:
f6ac5f3d 11027 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
c78fa86a
GB
11028 len, xfered_len,
11029 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11030
1e3ff5ad 11031 default:
2ed4b548 11032 return TARGET_XFER_E_IO;
c906108c
SS
11033 }
11034
0df8b418 11035 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 11036 large enough let the caller deal with it. */
ea9c271d 11037 if (len < get_remote_packet_size ())
2ed4b548 11038 return TARGET_XFER_E_IO;
ea9c271d 11039 len = get_remote_packet_size ();
1e3ff5ad 11040
23860348 11041 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 11042 if (!rs->remote_desc)
8a3fe4f8 11043 error (_("remote query is only available after target open"));
c906108c 11044
1e3ff5ad 11045 gdb_assert (annex != NULL);
4b8a223f 11046 gdb_assert (readbuf != NULL);
c906108c 11047
8d64371b 11048 p2 = rs->buf.data ();
c906108c
SS
11049 *p2++ = 'q';
11050 *p2++ = query_type;
11051
23860348
MS
11052 /* We used one buffer char for the remote protocol q command and
11053 another for the query type. As the remote protocol encapsulation
11054 uses 4 chars plus one extra in case we are debugging
11055 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11056 string. */
c906108c 11057 i = 0;
ea9c271d 11058 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 11059 {
1e3ff5ad
AC
11060 /* Bad caller may have sent forbidden characters. */
11061 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11062 *p2++ = annex[i];
c906108c
SS
11063 i++;
11064 }
1e3ff5ad
AC
11065 *p2 = '\0';
11066 gdb_assert (annex[i] == '\0');
c906108c 11067
6d820c5c 11068 i = putpkt (rs->buf);
c5aa993b 11069 if (i < 0)
2ed4b548 11070 return TARGET_XFER_E_IO;
c906108c 11071
8d64371b
TT
11072 getpkt (&rs->buf, 0);
11073 strcpy ((char *) readbuf, rs->buf.data ());
c906108c 11074
9b409511 11075 *xfered_len = strlen ((char *) readbuf);
92ffd475 11076 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
11077}
11078
09c98b44
DB
11079/* Implementation of to_get_memory_xfer_limit. */
11080
f6ac5f3d
PA
11081ULONGEST
11082remote_target::get_memory_xfer_limit ()
09c98b44
DB
11083{
11084 return get_memory_write_packet_size ();
11085}
11086
f6ac5f3d
PA
11087int
11088remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11089 const gdb_byte *pattern, ULONGEST pattern_len,
11090 CORE_ADDR *found_addrp)
08388c79 11091{
f5656ead 11092 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
11093 struct remote_state *rs = get_remote_state ();
11094 int max_size = get_memory_write_packet_size ();
11095 struct packet_config *packet =
11096 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
11097 /* Number of packet bytes used to encode the pattern;
11098 this could be more than PATTERN_LEN due to escape characters. */
08388c79 11099 int escaped_pattern_len;
0df8b418 11100 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
11101 int used_pattern_len;
11102 int i;
11103 int found;
11104 ULONGEST found_addr;
11105
7cc244de
PA
11106 /* Don't go to the target if we don't have to. This is done before
11107 checking packet_config_support to avoid the possibility that a
11108 success for this edge case means the facility works in
11109 general. */
08388c79
DE
11110 if (pattern_len > search_space_len)
11111 return 0;
11112 if (pattern_len == 0)
11113 {
11114 *found_addrp = start_addr;
11115 return 1;
11116 }
11117
11118 /* If we already know the packet isn't supported, fall back to the simple
11119 way of searching memory. */
11120
4082afcc 11121 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
11122 {
11123 /* Target doesn't provided special support, fall back and use the
11124 standard support (copy memory and do the search here). */
f6ac5f3d 11125 return simple_search_memory (this, start_addr, search_space_len,
08388c79
DE
11126 pattern, pattern_len, found_addrp);
11127 }
11128
28439a30
PA
11129 /* Make sure the remote is pointing at the right process. */
11130 set_general_process ();
11131
08388c79 11132 /* Insert header. */
8d64371b 11133 i = snprintf (rs->buf.data (), max_size,
08388c79 11134 "qSearch:memory:%s;%s;",
5af949e3 11135 phex_nz (start_addr, addr_size),
08388c79
DE
11136 phex_nz (search_space_len, sizeof (search_space_len)));
11137 max_size -= (i + 1);
11138
11139 /* Escape as much data as fits into rs->buf. */
11140 escaped_pattern_len =
8d64371b
TT
11141 remote_escape_output (pattern, pattern_len, 1,
11142 (gdb_byte *) rs->buf.data () + i,
08388c79
DE
11143 &used_pattern_len, max_size);
11144
11145 /* Bail if the pattern is too large. */
11146 if (used_pattern_len != pattern_len)
9b20d036 11147 error (_("Pattern is too large to transmit to remote target."));
08388c79 11148
8d64371b
TT
11149 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11150 || getpkt_sane (&rs->buf, 0) < 0
08388c79
DE
11151 || packet_ok (rs->buf, packet) != PACKET_OK)
11152 {
11153 /* The request may not have worked because the command is not
11154 supported. If so, fall back to the simple way. */
7cc244de 11155 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79 11156 {
f6ac5f3d 11157 return simple_search_memory (this, start_addr, search_space_len,
08388c79
DE
11158 pattern, pattern_len, found_addrp);
11159 }
11160 return -1;
11161 }
11162
11163 if (rs->buf[0] == '0')
11164 found = 0;
11165 else if (rs->buf[0] == '1')
11166 {
11167 found = 1;
11168 if (rs->buf[1] != ',')
8d64371b
TT
11169 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11170 unpack_varlen_hex (&rs->buf[2], &found_addr);
08388c79
DE
11171 *found_addrp = found_addr;
11172 }
11173 else
8d64371b 11174 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
08388c79
DE
11175
11176 return found;
11177}
11178
f6ac5f3d
PA
11179void
11180remote_target::rcmd (const char *command, struct ui_file *outbuf)
96baa820 11181{
d01949b6 11182 struct remote_state *rs = get_remote_state ();
8d64371b 11183 char *p = rs->buf.data ();
96baa820 11184
5d93a237 11185 if (!rs->remote_desc)
8a3fe4f8 11186 error (_("remote rcmd is only available after target open"));
96baa820 11187
23860348 11188 /* Send a NULL command across as an empty command. */
7be570e7
JM
11189 if (command == NULL)
11190 command = "";
11191
23860348 11192 /* The query prefix. */
8d64371b
TT
11193 strcpy (rs->buf.data (), "qRcmd,");
11194 p = strchr (rs->buf.data (), '\0');
96baa820 11195
8d64371b 11196 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
3e43a32a 11197 > get_remote_packet_size ())
8a3fe4f8 11198 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 11199
23860348 11200 /* Encode the actual command. */
a30bf1f1 11201 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 11202
6d820c5c 11203 if (putpkt (rs->buf) < 0)
8a3fe4f8 11204 error (_("Communication problem with target."));
96baa820
JM
11205
11206 /* get/display the response */
11207 while (1)
11208 {
2e9f7625
DJ
11209 char *buf;
11210
00bf0b85 11211 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 11212 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 11213 rs->buf[0] = '\0';
8d64371b 11214 if (getpkt_sane (&rs->buf, 0) == -1)
5b37825d
PW
11215 {
11216 /* Timeout. Continue to (try to) read responses.
11217 This is better than stopping with an error, assuming the stub
11218 is still executing the (long) monitor command.
11219 If needed, the user can interrupt gdb using C-c, obtaining
11220 an effect similar to stop on timeout. */
11221 continue;
11222 }
8d64371b 11223 buf = rs->buf.data ();
96baa820 11224 if (buf[0] == '\0')
8a3fe4f8 11225 error (_("Target does not support this command."));
96baa820
JM
11226 if (buf[0] == 'O' && buf[1] != 'K')
11227 {
23860348 11228 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
11229 continue;
11230 }
11231 if (strcmp (buf, "OK") == 0)
11232 break;
7be570e7
JM
11233 if (strlen (buf) == 3 && buf[0] == 'E'
11234 && isdigit (buf[1]) && isdigit (buf[2]))
11235 {
8a3fe4f8 11236 error (_("Protocol error with Rcmd"));
7be570e7 11237 }
96baa820
JM
11238 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11239 {
11240 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 11241
96baa820
JM
11242 fputc_unfiltered (c, outbuf);
11243 }
11244 break;
11245 }
11246}
11247
f6ac5f3d
PA
11248std::vector<mem_region>
11249remote_target::memory_map ()
fd79ecee 11250{
a664f67e 11251 std::vector<mem_region> result;
9018be22 11252 gdb::optional<gdb::char_vector> text
8b88a78e 11253 = target_read_stralloc (current_top_target (), TARGET_OBJECT_MEMORY_MAP, NULL);
fd79ecee
DJ
11254
11255 if (text)
9018be22 11256 result = parse_memory_map (text->data ());
fd79ecee
DJ
11257
11258 return result;
11259}
11260
c906108c 11261static void
ac88e2de 11262packet_command (const char *args, int from_tty)
c906108c 11263{
6b8edb51 11264 remote_target *remote = get_current_remote_target ();
c906108c 11265
6b8edb51 11266 if (remote == nullptr)
8a3fe4f8 11267 error (_("command can only be used with remote target"));
c906108c 11268
6b8edb51
PA
11269 remote->packet_command (args, from_tty);
11270}
11271
11272void
11273remote_target::packet_command (const char *args, int from_tty)
11274{
c5aa993b 11275 if (!args)
8a3fe4f8 11276 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
11277
11278 puts_filtered ("sending: ");
11279 print_packet (args);
11280 puts_filtered ("\n");
11281 putpkt (args);
11282
6b8edb51
PA
11283 remote_state *rs = get_remote_state ();
11284
8d64371b 11285 getpkt (&rs->buf, 0);
c906108c 11286 puts_filtered ("received: ");
8d64371b 11287 print_packet (rs->buf.data ());
c906108c
SS
11288 puts_filtered ("\n");
11289}
11290
11291#if 0
23860348 11292/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 11293
a14ed312 11294static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 11295
a14ed312 11296static void threadset_test_cmd (char *cmd, int tty);
c906108c 11297
a14ed312 11298static void threadalive_test (char *cmd, int tty);
c906108c 11299
a14ed312 11300static void threadlist_test_cmd (char *cmd, int tty);
c906108c 11301
23860348 11302int get_and_display_threadinfo (threadref *ref);
c906108c 11303
a14ed312 11304static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 11305
23860348 11306static int thread_display_step (threadref *ref, void *context);
c906108c 11307
a14ed312 11308static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 11309
a14ed312 11310static void init_remote_threadtests (void);
c906108c 11311
23860348 11312#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
11313
11314static void
0b39b52e 11315threadset_test_cmd (const char *cmd, int tty)
c906108c
SS
11316{
11317 int sample_thread = SAMPLE_THREAD;
11318
a3f17187 11319 printf_filtered (_("Remote threadset test\n"));
79d7f229 11320 set_general_thread (sample_thread);
c906108c
SS
11321}
11322
11323
11324static void
0b39b52e 11325threadalive_test (const char *cmd, int tty)
c906108c
SS
11326{
11327 int sample_thread = SAMPLE_THREAD;
e99b03dc 11328 int pid = inferior_ptid.pid ();
fd79271b 11329 ptid_t ptid = ptid_t (pid, sample_thread, 0);
c906108c 11330
79d7f229 11331 if (remote_thread_alive (ptid))
c906108c
SS
11332 printf_filtered ("PASS: Thread alive test\n");
11333 else
11334 printf_filtered ("FAIL: Thread alive test\n");
11335}
11336
23860348 11337void output_threadid (char *title, threadref *ref);
c906108c
SS
11338
11339void
fba45db2 11340output_threadid (char *title, threadref *ref)
c906108c
SS
11341{
11342 char hexid[20];
11343
23860348 11344 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
11345 hexid[16] = 0;
11346 printf_filtered ("%s %s\n", title, (&hexid[0]));
11347}
11348
11349static void
0b39b52e 11350threadlist_test_cmd (const char *cmd, int tty)
c906108c
SS
11351{
11352 int startflag = 1;
11353 threadref nextthread;
11354 int done, result_count;
11355 threadref threadlist[3];
11356
11357 printf_filtered ("Remote Threadlist test\n");
11358 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11359 &result_count, &threadlist[0]))
11360 printf_filtered ("FAIL: threadlist test\n");
11361 else
11362 {
11363 threadref *scan = threadlist;
11364 threadref *limit = scan + result_count;
11365
11366 while (scan < limit)
11367 output_threadid (" thread ", scan++);
11368 }
11369}
11370
11371void
fba45db2 11372display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
11373{
11374 output_threadid ("Threadid: ", &info->threadid);
11375 printf_filtered ("Name: %s\n ", info->shortname);
11376 printf_filtered ("State: %s\n", info->display);
11377 printf_filtered ("other: %s\n\n", info->more_display);
11378}
11379
11380int
fba45db2 11381get_and_display_threadinfo (threadref *ref)
c906108c
SS
11382{
11383 int result;
11384 int set;
11385 struct gdb_ext_thread_info threadinfo;
11386
11387 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11388 | TAG_MOREDISPLAY | TAG_DISPLAY;
11389 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11390 display_thread_info (&threadinfo);
11391 return result;
11392}
11393
11394static void
0b39b52e 11395threadinfo_test_cmd (const char *cmd, int tty)
c906108c
SS
11396{
11397 int athread = SAMPLE_THREAD;
11398 threadref thread;
11399 int set;
11400
11401 int_to_threadref (&thread, athread);
11402 printf_filtered ("Remote Threadinfo test\n");
11403 if (!get_and_display_threadinfo (&thread))
11404 printf_filtered ("FAIL cannot get thread info\n");
11405}
11406
11407static int
fba45db2 11408thread_display_step (threadref *ref, void *context)
c906108c
SS
11409{
11410 /* output_threadid(" threadstep ",ref); *//* simple test */
11411 return get_and_display_threadinfo (ref);
11412}
11413
11414static void
0b39b52e 11415threadlist_update_test_cmd (const char *cmd, int tty)
c906108c
SS
11416{
11417 printf_filtered ("Remote Threadlist update test\n");
11418 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11419}
11420
11421static void
11422init_remote_threadtests (void)
11423{
3e43a32a
MS
11424 add_com ("tlist", class_obscure, threadlist_test_cmd,
11425 _("Fetch and print the remote list of "
11426 "thread identifiers, one pkt only"));
c906108c 11427 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 11428 _("Fetch and display info about one thread"));
c906108c 11429 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 11430 _("Test setting to a different thread"));
c906108c 11431 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 11432 _("Iterate through updating all remote thread info"));
c906108c 11433 add_com ("talive", class_obscure, threadalive_test,
1bedd215 11434 _(" Remote thread alive test "));
c906108c
SS
11435}
11436
11437#endif /* 0 */
11438
f3fb8c85
MS
11439/* Convert a thread ID to a string. Returns the string in a static
11440 buffer. */
11441
f6ac5f3d
PA
11442const char *
11443remote_target::pid_to_str (ptid_t ptid)
f3fb8c85 11444{
79d7f229 11445 static char buf[64];
82f73884 11446 struct remote_state *rs = get_remote_state ();
f3fb8c85 11447
d7e15655 11448 if (ptid == null_ptid)
7cee1e54 11449 return normal_pid_to_str (ptid);
0e998d96 11450 else if (ptid.is_pid ())
ecd0ada5
PA
11451 {
11452 /* Printing an inferior target id. */
11453
11454 /* When multi-process extensions are off, there's no way in the
11455 remote protocol to know the remote process id, if there's any
11456 at all. There's one exception --- when we're connected with
11457 target extended-remote, and we manually attached to a process
11458 with "attach PID". We don't record anywhere a flag that
11459 allows us to distinguish that case from the case of
11460 connecting with extended-remote and the stub already being
11461 attached to a process, and reporting yes to qAttached, hence
11462 no smart special casing here. */
11463 if (!remote_multi_process_p (rs))
11464 {
11465 xsnprintf (buf, sizeof buf, "Remote target");
11466 return buf;
11467 }
11468
11469 return normal_pid_to_str (ptid);
82f73884 11470 }
ecd0ada5 11471 else
79d7f229 11472 {
d7e15655 11473 if (magic_null_ptid == ptid)
ecd0ada5 11474 xsnprintf (buf, sizeof buf, "Thread <main>");
8020350c 11475 else if (remote_multi_process_p (rs))
e38504b3 11476 if (ptid.lwp () == 0)
de0d863e
DB
11477 return normal_pid_to_str (ptid);
11478 else
11479 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
e38504b3 11480 ptid.pid (), ptid.lwp ());
ecd0ada5
PA
11481 else
11482 xsnprintf (buf, sizeof buf, "Thread %ld",
e38504b3 11483 ptid.lwp ());
79d7f229
PA
11484 return buf;
11485 }
f3fb8c85
MS
11486}
11487
38691318
KB
11488/* Get the address of the thread local variable in OBJFILE which is
11489 stored at OFFSET within the thread local storage for thread PTID. */
11490
f6ac5f3d
PA
11491CORE_ADDR
11492remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11493 CORE_ADDR offset)
38691318 11494{
4082afcc 11495 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
11496 {
11497 struct remote_state *rs = get_remote_state ();
8d64371b
TT
11498 char *p = rs->buf.data ();
11499 char *endp = p + get_remote_packet_size ();
571dd617 11500 enum packet_result result;
38691318
KB
11501
11502 strcpy (p, "qGetTLSAddr:");
11503 p += strlen (p);
82f73884 11504 p = write_ptid (p, endp, ptid);
38691318
KB
11505 *p++ = ',';
11506 p += hexnumstr (p, offset);
11507 *p++ = ',';
11508 p += hexnumstr (p, lm);
11509 *p++ = '\0';
11510
6d820c5c 11511 putpkt (rs->buf);
8d64371b 11512 getpkt (&rs->buf, 0);
3e43a32a
MS
11513 result = packet_ok (rs->buf,
11514 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 11515 if (result == PACKET_OK)
38691318 11516 {
b926417a 11517 ULONGEST addr;
38691318 11518
8d64371b 11519 unpack_varlen_hex (rs->buf.data (), &addr);
b926417a 11520 return addr;
38691318 11521 }
571dd617 11522 else if (result == PACKET_UNKNOWN)
109c3e39
AC
11523 throw_error (TLS_GENERIC_ERROR,
11524 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 11525 else
109c3e39
AC
11526 throw_error (TLS_GENERIC_ERROR,
11527 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
11528 }
11529 else
109c3e39
AC
11530 throw_error (TLS_GENERIC_ERROR,
11531 _("TLS not supported or disabled on this target"));
38691318
KB
11532 /* Not reached. */
11533 return 0;
11534}
11535
711e434b
PM
11536/* Provide thread local base, i.e. Thread Information Block address.
11537 Returns 1 if ptid is found and thread_local_base is non zero. */
11538
57810aa7 11539bool
f6ac5f3d 11540remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
711e434b 11541{
4082afcc 11542 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
11543 {
11544 struct remote_state *rs = get_remote_state ();
8d64371b
TT
11545 char *p = rs->buf.data ();
11546 char *endp = p + get_remote_packet_size ();
711e434b
PM
11547 enum packet_result result;
11548
11549 strcpy (p, "qGetTIBAddr:");
11550 p += strlen (p);
11551 p = write_ptid (p, endp, ptid);
11552 *p++ = '\0';
11553
11554 putpkt (rs->buf);
8d64371b 11555 getpkt (&rs->buf, 0);
711e434b
PM
11556 result = packet_ok (rs->buf,
11557 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11558 if (result == PACKET_OK)
11559 {
b926417a 11560 ULONGEST val;
8d64371b 11561 unpack_varlen_hex (rs->buf.data (), &val);
711e434b 11562 if (addr)
b926417a 11563 *addr = (CORE_ADDR) val;
57810aa7 11564 return true;
711e434b
PM
11565 }
11566 else if (result == PACKET_UNKNOWN)
11567 error (_("Remote target doesn't support qGetTIBAddr packet"));
11568 else
11569 error (_("Remote target failed to process qGetTIBAddr request"));
11570 }
11571 else
11572 error (_("qGetTIBAddr not supported or disabled on this target"));
11573 /* Not reached. */
57810aa7 11574 return false;
711e434b
PM
11575}
11576
29709017
DJ
11577/* Support for inferring a target description based on the current
11578 architecture and the size of a 'g' packet. While the 'g' packet
11579 can have any size (since optional registers can be left off the
11580 end), some sizes are easily recognizable given knowledge of the
11581 approximate architecture. */
11582
11583struct remote_g_packet_guess
11584{
eefce37f
TT
11585 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
11586 : bytes (bytes_),
11587 tdesc (tdesc_)
11588 {
11589 }
11590
29709017
DJ
11591 int bytes;
11592 const struct target_desc *tdesc;
11593};
29709017 11594
eefce37f 11595struct remote_g_packet_data : public allocate_on_obstack
29709017 11596{
eefce37f 11597 std::vector<remote_g_packet_guess> guesses;
29709017
DJ
11598};
11599
11600static struct gdbarch_data *remote_g_packet_data_handle;
11601
11602static void *
11603remote_g_packet_data_init (struct obstack *obstack)
11604{
eefce37f 11605 return new (obstack) remote_g_packet_data;
29709017
DJ
11606}
11607
11608void
11609register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11610 const struct target_desc *tdesc)
11611{
11612 struct remote_g_packet_data *data
19ba03f4
SM
11613 = ((struct remote_g_packet_data *)
11614 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
11615
11616 gdb_assert (tdesc != NULL);
11617
eefce37f
TT
11618 for (const remote_g_packet_guess &guess : data->guesses)
11619 if (guess.bytes == bytes)
29709017 11620 internal_error (__FILE__, __LINE__,
9b20d036 11621 _("Duplicate g packet description added for size %d"),
29709017
DJ
11622 bytes);
11623
eefce37f 11624 data->guesses.emplace_back (bytes, tdesc);
29709017
DJ
11625}
11626
eefce37f
TT
11627/* Return true if remote_read_description would do anything on this target
11628 and architecture, false otherwise. */
d962ef82 11629
eefce37f 11630static bool
d962ef82
DJ
11631remote_read_description_p (struct target_ops *target)
11632{
11633 struct remote_g_packet_data *data
19ba03f4
SM
11634 = ((struct remote_g_packet_data *)
11635 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82 11636
eefce37f 11637 return !data->guesses.empty ();
d962ef82
DJ
11638}
11639
f6ac5f3d
PA
11640const struct target_desc *
11641remote_target::read_description ()
29709017
DJ
11642{
11643 struct remote_g_packet_data *data
19ba03f4
SM
11644 = ((struct remote_g_packet_data *)
11645 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 11646
d962ef82
DJ
11647 /* Do not try this during initial connection, when we do not know
11648 whether there is a running but stopped thread. */
d7e15655 11649 if (!target_has_execution || inferior_ptid == null_ptid)
b6a8c27b 11650 return beneath ()->read_description ();
d962ef82 11651
eefce37f 11652 if (!data->guesses.empty ())
29709017 11653 {
29709017
DJ
11654 int bytes = send_g_packet ();
11655
eefce37f
TT
11656 for (const remote_g_packet_guess &guess : data->guesses)
11657 if (guess.bytes == bytes)
11658 return guess.tdesc;
29709017
DJ
11659
11660 /* We discard the g packet. A minor optimization would be to
11661 hold on to it, and fill the register cache once we have selected
11662 an architecture, but it's too tricky to do safely. */
11663 }
11664
b6a8c27b 11665 return beneath ()->read_description ();
29709017
DJ
11666}
11667
a6b151f1
DJ
11668/* Remote file transfer support. This is host-initiated I/O, not
11669 target-initiated; for target-initiated, see remote-fileio.c. */
11670
11671/* If *LEFT is at least the length of STRING, copy STRING to
11672 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11673 decrease *LEFT. Otherwise raise an error. */
11674
11675static void
a121b7c1 11676remote_buffer_add_string (char **buffer, int *left, const char *string)
a6b151f1
DJ
11677{
11678 int len = strlen (string);
11679
11680 if (len > *left)
11681 error (_("Packet too long for target."));
11682
11683 memcpy (*buffer, string, len);
11684 *buffer += len;
11685 *left -= len;
11686
11687 /* NUL-terminate the buffer as a convenience, if there is
11688 room. */
11689 if (*left)
11690 **buffer = '\0';
11691}
11692
11693/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11694 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11695 decrease *LEFT. Otherwise raise an error. */
11696
11697static void
11698remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11699 int len)
11700{
11701 if (2 * len > *left)
11702 error (_("Packet too long for target."));
11703
11704 bin2hex (bytes, *buffer, len);
11705 *buffer += 2 * len;
11706 *left -= 2 * len;
11707
11708 /* NUL-terminate the buffer as a convenience, if there is
11709 room. */
11710 if (*left)
11711 **buffer = '\0';
11712}
11713
11714/* If *LEFT is large enough, convert VALUE to hex and add it to
11715 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11716 decrease *LEFT. Otherwise raise an error. */
11717
11718static void
11719remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11720{
11721 int len = hexnumlen (value);
11722
11723 if (len > *left)
11724 error (_("Packet too long for target."));
11725
11726 hexnumstr (*buffer, value);
11727 *buffer += len;
11728 *left -= len;
11729
11730 /* NUL-terminate the buffer as a convenience, if there is
11731 room. */
11732 if (*left)
11733 **buffer = '\0';
11734}
11735
11736/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11737 value, *REMOTE_ERRNO to the remote error number or zero if none
11738 was included, and *ATTACHMENT to point to the start of the annex
11739 if any. The length of the packet isn't needed here; there may
11740 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11741
11742 Return 0 if the packet could be parsed, -1 if it could not. If
11743 -1 is returned, the other variables may not be initialized. */
11744
11745static int
11746remote_hostio_parse_result (char *buffer, int *retcode,
11747 int *remote_errno, char **attachment)
11748{
11749 char *p, *p2;
11750
11751 *remote_errno = 0;
11752 *attachment = NULL;
11753
11754 if (buffer[0] != 'F')
11755 return -1;
11756
11757 errno = 0;
11758 *retcode = strtol (&buffer[1], &p, 16);
11759 if (errno != 0 || p == &buffer[1])
11760 return -1;
11761
11762 /* Check for ",errno". */
11763 if (*p == ',')
11764 {
11765 errno = 0;
11766 *remote_errno = strtol (p + 1, &p2, 16);
11767 if (errno != 0 || p + 1 == p2)
11768 return -1;
11769 p = p2;
11770 }
11771
11772 /* Check for ";attachment". If there is no attachment, the
11773 packet should end here. */
11774 if (*p == ';')
11775 {
11776 *attachment = p + 1;
11777 return 0;
11778 }
11779 else if (*p == '\0')
11780 return 0;
11781 else
11782 return -1;
11783}
11784
11785/* Send a prepared I/O packet to the target and read its response.
11786 The prepared packet is in the global RS->BUF before this function
11787 is called, and the answer is there when we return.
11788
11789 COMMAND_BYTES is the length of the request to send, which may include
11790 binary data. WHICH_PACKET is the packet configuration to check
11791 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11792 is set to the error number and -1 is returned. Otherwise the value
11793 returned by the function is returned.
11794
11795 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11796 attachment is expected; an error will be reported if there's a
11797 mismatch. If one is found, *ATTACHMENT will be set to point into
11798 the packet buffer and *ATTACHMENT_LEN will be set to the
11799 attachment's length. */
11800
6b8edb51
PA
11801int
11802remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
11803 int *remote_errno, char **attachment,
11804 int *attachment_len)
a6b151f1
DJ
11805{
11806 struct remote_state *rs = get_remote_state ();
11807 int ret, bytes_read;
11808 char *attachment_tmp;
11809
20db9c52 11810 if (packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
11811 {
11812 *remote_errno = FILEIO_ENOSYS;
11813 return -1;
11814 }
11815
8d64371b
TT
11816 putpkt_binary (rs->buf.data (), command_bytes);
11817 bytes_read = getpkt_sane (&rs->buf, 0);
a6b151f1
DJ
11818
11819 /* If it timed out, something is wrong. Don't try to parse the
11820 buffer. */
11821 if (bytes_read < 0)
11822 {
11823 *remote_errno = FILEIO_EINVAL;
11824 return -1;
11825 }
11826
11827 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11828 {
11829 case PACKET_ERROR:
11830 *remote_errno = FILEIO_EINVAL;
11831 return -1;
11832 case PACKET_UNKNOWN:
11833 *remote_errno = FILEIO_ENOSYS;
11834 return -1;
11835 case PACKET_OK:
11836 break;
11837 }
11838
8d64371b 11839 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
a6b151f1
DJ
11840 &attachment_tmp))
11841 {
11842 *remote_errno = FILEIO_EINVAL;
11843 return -1;
11844 }
11845
11846 /* Make sure we saw an attachment if and only if we expected one. */
11847 if ((attachment_tmp == NULL && attachment != NULL)
11848 || (attachment_tmp != NULL && attachment == NULL))
11849 {
11850 *remote_errno = FILEIO_EINVAL;
11851 return -1;
11852 }
11853
11854 /* If an attachment was found, it must point into the packet buffer;
11855 work out how many bytes there were. */
11856 if (attachment_tmp != NULL)
11857 {
11858 *attachment = attachment_tmp;
8d64371b 11859 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
a6b151f1
DJ
11860 }
11861
11862 return ret;
11863}
11864
dd194f6b 11865/* See declaration.h. */
80152258 11866
dd194f6b
PA
11867void
11868readahead_cache::invalidate ()
80152258 11869{
dd194f6b 11870 this->fd = -1;
80152258
PA
11871}
11872
dd194f6b 11873/* See declaration.h. */
80152258 11874
dd194f6b
PA
11875void
11876readahead_cache::invalidate_fd (int fd)
80152258 11877{
dd194f6b
PA
11878 if (this->fd == fd)
11879 this->fd = -1;
80152258
PA
11880}
11881
15a201c8
GB
11882/* Set the filesystem remote_hostio functions that take FILENAME
11883 arguments will use. Return 0 on success, or -1 if an error
11884 occurs (and set *REMOTE_ERRNO). */
11885
6b8edb51
PA
11886int
11887remote_target::remote_hostio_set_filesystem (struct inferior *inf,
11888 int *remote_errno)
15a201c8
GB
11889{
11890 struct remote_state *rs = get_remote_state ();
11891 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
8d64371b 11892 char *p = rs->buf.data ();
15a201c8
GB
11893 int left = get_remote_packet_size () - 1;
11894 char arg[9];
11895 int ret;
11896
11897 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11898 return 0;
11899
11900 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11901 return 0;
11902
11903 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11904
11905 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11906 remote_buffer_add_string (&p, &left, arg);
11907
8d64371b 11908 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
15a201c8
GB
11909 remote_errno, NULL, NULL);
11910
11911 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11912 return 0;
11913
11914 if (ret == 0)
11915 rs->fs_pid = required_pid;
11916
11917 return ret;
11918}
11919
12e2a5fd 11920/* Implementation of to_fileio_open. */
a6b151f1 11921
6b8edb51
PA
11922int
11923remote_target::remote_hostio_open (inferior *inf, const char *filename,
11924 int flags, int mode, int warn_if_slow,
11925 int *remote_errno)
a6b151f1
DJ
11926{
11927 struct remote_state *rs = get_remote_state ();
8d64371b 11928 char *p = rs->buf.data ();
a6b151f1
DJ
11929 int left = get_remote_packet_size () - 1;
11930
4313b8c0
GB
11931 if (warn_if_slow)
11932 {
11933 static int warning_issued = 0;
11934
11935 printf_unfiltered (_("Reading %s from remote target...\n"),
11936 filename);
11937
11938 if (!warning_issued)
11939 {
11940 warning (_("File transfers from remote targets can be slow."
11941 " Use \"set sysroot\" to access files locally"
11942 " instead."));
11943 warning_issued = 1;
11944 }
11945 }
11946
15a201c8
GB
11947 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11948 return -1;
11949
a6b151f1
DJ
11950 remote_buffer_add_string (&p, &left, "vFile:open:");
11951
11952 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11953 strlen (filename));
11954 remote_buffer_add_string (&p, &left, ",");
11955
11956 remote_buffer_add_int (&p, &left, flags);
11957 remote_buffer_add_string (&p, &left, ",");
11958
11959 remote_buffer_add_int (&p, &left, mode);
11960
8d64371b 11961 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
a6b151f1
DJ
11962 remote_errno, NULL, NULL);
11963}
11964
f6ac5f3d
PA
11965int
11966remote_target::fileio_open (struct inferior *inf, const char *filename,
11967 int flags, int mode, int warn_if_slow,
11968 int *remote_errno)
11969{
6b8edb51 11970 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
f6ac5f3d
PA
11971 remote_errno);
11972}
11973
12e2a5fd 11974/* Implementation of to_fileio_pwrite. */
a6b151f1 11975
6b8edb51
PA
11976int
11977remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
11978 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
11979{
11980 struct remote_state *rs = get_remote_state ();
8d64371b 11981 char *p = rs->buf.data ();
a6b151f1
DJ
11982 int left = get_remote_packet_size ();
11983 int out_len;
11984
dd194f6b 11985 rs->readahead_cache.invalidate_fd (fd);
80152258 11986
a6b151f1
DJ
11987 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11988
11989 remote_buffer_add_int (&p, &left, fd);
11990 remote_buffer_add_string (&p, &left, ",");
11991
11992 remote_buffer_add_int (&p, &left, offset);
11993 remote_buffer_add_string (&p, &left, ",");
11994
124e13d9 11995 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
8d64371b
TT
11996 (get_remote_packet_size ()
11997 - (p - rs->buf.data ())));
a6b151f1 11998
8d64371b 11999 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
a6b151f1
DJ
12000 remote_errno, NULL, NULL);
12001}
12002
f6ac5f3d
PA
12003int
12004remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12005 ULONGEST offset, int *remote_errno)
12006{
6b8edb51 12007 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
f6ac5f3d
PA
12008}
12009
80152258
PA
12010/* Helper for the implementation of to_fileio_pread. Read the file
12011 from the remote side with vFile:pread. */
a6b151f1 12012
6b8edb51
PA
12013int
12014remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12015 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
12016{
12017 struct remote_state *rs = get_remote_state ();
8d64371b 12018 char *p = rs->buf.data ();
a6b151f1
DJ
12019 char *attachment;
12020 int left = get_remote_packet_size ();
12021 int ret, attachment_len;
12022 int read_len;
12023
12024 remote_buffer_add_string (&p, &left, "vFile:pread:");
12025
12026 remote_buffer_add_int (&p, &left, fd);
12027 remote_buffer_add_string (&p, &left, ",");
12028
12029 remote_buffer_add_int (&p, &left, len);
12030 remote_buffer_add_string (&p, &left, ",");
12031
12032 remote_buffer_add_int (&p, &left, offset);
12033
8d64371b 12034 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
a6b151f1
DJ
12035 remote_errno, &attachment,
12036 &attachment_len);
12037
12038 if (ret < 0)
12039 return ret;
12040
bc20a4af 12041 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
12042 read_buf, len);
12043 if (read_len != ret)
12044 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12045
12046 return ret;
12047}
12048
dd194f6b 12049/* See declaration.h. */
80152258 12050
dd194f6b
PA
12051int
12052readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12053 ULONGEST offset)
80152258 12054{
dd194f6b
PA
12055 if (this->fd == fd
12056 && this->offset <= offset
12057 && offset < this->offset + this->bufsize)
80152258 12058 {
dd194f6b 12059 ULONGEST max = this->offset + this->bufsize;
80152258
PA
12060
12061 if (offset + len > max)
12062 len = max - offset;
12063
dd194f6b 12064 memcpy (read_buf, this->buf + offset - this->offset, len);
80152258
PA
12065 return len;
12066 }
12067
12068 return 0;
12069}
12070
12071/* Implementation of to_fileio_pread. */
12072
6b8edb51
PA
12073int
12074remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12075 ULONGEST offset, int *remote_errno)
80152258
PA
12076{
12077 int ret;
12078 struct remote_state *rs = get_remote_state ();
dd194f6b 12079 readahead_cache *cache = &rs->readahead_cache;
80152258 12080
dd194f6b 12081 ret = cache->pread (fd, read_buf, len, offset);
80152258
PA
12082 if (ret > 0)
12083 {
12084 cache->hit_count++;
12085
12086 if (remote_debug)
12087 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
12088 pulongest (cache->hit_count));
12089 return ret;
12090 }
12091
12092 cache->miss_count++;
12093 if (remote_debug)
12094 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
12095 pulongest (cache->miss_count));
12096
12097 cache->fd = fd;
12098 cache->offset = offset;
12099 cache->bufsize = get_remote_packet_size ();
224c3ddb 12100 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258 12101
6b8edb51 12102 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
80152258
PA
12103 cache->offset, remote_errno);
12104 if (ret <= 0)
12105 {
dd194f6b 12106 cache->invalidate_fd (fd);
80152258
PA
12107 return ret;
12108 }
12109
12110 cache->bufsize = ret;
dd194f6b 12111 return cache->pread (fd, read_buf, len, offset);
80152258
PA
12112}
12113
f6ac5f3d
PA
12114int
12115remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12116 ULONGEST offset, int *remote_errno)
12117{
6b8edb51 12118 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
f6ac5f3d
PA
12119}
12120
12e2a5fd 12121/* Implementation of to_fileio_close. */
a6b151f1 12122
6b8edb51
PA
12123int
12124remote_target::remote_hostio_close (int fd, int *remote_errno)
a6b151f1
DJ
12125{
12126 struct remote_state *rs = get_remote_state ();
8d64371b 12127 char *p = rs->buf.data ();
a6b151f1
DJ
12128 int left = get_remote_packet_size () - 1;
12129
dd194f6b 12130 rs->readahead_cache.invalidate_fd (fd);
80152258 12131
a6b151f1
DJ
12132 remote_buffer_add_string (&p, &left, "vFile:close:");
12133
12134 remote_buffer_add_int (&p, &left, fd);
12135
8d64371b 12136 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
a6b151f1
DJ
12137 remote_errno, NULL, NULL);
12138}
12139
f6ac5f3d
PA
12140int
12141remote_target::fileio_close (int fd, int *remote_errno)
12142{
6b8edb51 12143 return remote_hostio_close (fd, remote_errno);
f6ac5f3d
PA
12144}
12145
12e2a5fd 12146/* Implementation of to_fileio_unlink. */
a6b151f1 12147
6b8edb51
PA
12148int
12149remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12150 int *remote_errno)
a6b151f1
DJ
12151{
12152 struct remote_state *rs = get_remote_state ();
8d64371b 12153 char *p = rs->buf.data ();
a6b151f1
DJ
12154 int left = get_remote_packet_size () - 1;
12155
15a201c8
GB
12156 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12157 return -1;
12158
a6b151f1
DJ
12159 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12160
12161 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12162 strlen (filename));
12163
8d64371b 12164 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
a6b151f1
DJ
12165 remote_errno, NULL, NULL);
12166}
12167
f6ac5f3d
PA
12168int
12169remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12170 int *remote_errno)
12171{
6b8edb51 12172 return remote_hostio_unlink (inf, filename, remote_errno);
f6ac5f3d
PA
12173}
12174
12e2a5fd 12175/* Implementation of to_fileio_readlink. */
b9e7b9c3 12176
f6ac5f3d
PA
12177gdb::optional<std::string>
12178remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12179 int *remote_errno)
b9e7b9c3
UW
12180{
12181 struct remote_state *rs = get_remote_state ();
8d64371b 12182 char *p = rs->buf.data ();
b9e7b9c3
UW
12183 char *attachment;
12184 int left = get_remote_packet_size ();
12185 int len, attachment_len;
12186 int read_len;
b9e7b9c3 12187
15a201c8 12188 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
e0d3522b 12189 return {};
15a201c8 12190
b9e7b9c3
UW
12191 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12192
12193 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12194 strlen (filename));
12195
8d64371b 12196 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
b9e7b9c3
UW
12197 remote_errno, &attachment,
12198 &attachment_len);
12199
12200 if (len < 0)
e0d3522b 12201 return {};
b9e7b9c3 12202
e0d3522b 12203 std::string ret (len, '\0');
b9e7b9c3 12204
bc20a4af 12205 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
e0d3522b 12206 (gdb_byte *) &ret[0], len);
b9e7b9c3
UW
12207 if (read_len != len)
12208 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12209
b9e7b9c3
UW
12210 return ret;
12211}
12212
12e2a5fd 12213/* Implementation of to_fileio_fstat. */
0a93529c 12214
f6ac5f3d
PA
12215int
12216remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
0a93529c
GB
12217{
12218 struct remote_state *rs = get_remote_state ();
8d64371b 12219 char *p = rs->buf.data ();
0a93529c
GB
12220 int left = get_remote_packet_size ();
12221 int attachment_len, ret;
12222 char *attachment;
12223 struct fio_stat fst;
12224 int read_len;
12225
464b0089
GB
12226 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12227
12228 remote_buffer_add_int (&p, &left, fd);
12229
8d64371b 12230 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
464b0089
GB
12231 remote_errno, &attachment,
12232 &attachment_len);
12233 if (ret < 0)
0a93529c 12234 {
464b0089
GB
12235 if (*remote_errno != FILEIO_ENOSYS)
12236 return ret;
12237
0a93529c
GB
12238 /* Strictly we should return -1, ENOSYS here, but when
12239 "set sysroot remote:" was implemented in August 2008
12240 BFD's need for a stat function was sidestepped with
12241 this hack. This was not remedied until March 2015
12242 so we retain the previous behavior to avoid breaking
12243 compatibility.
12244
12245 Note that the memset is a March 2015 addition; older
12246 GDBs set st_size *and nothing else* so the structure
12247 would have garbage in all other fields. This might
12248 break something but retaining the previous behavior
12249 here would be just too wrong. */
12250
12251 memset (st, 0, sizeof (struct stat));
12252 st->st_size = INT_MAX;
12253 return 0;
12254 }
12255
0a93529c
GB
12256 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12257 (gdb_byte *) &fst, sizeof (fst));
12258
12259 if (read_len != ret)
12260 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12261
12262 if (read_len != sizeof (fst))
12263 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12264 read_len, (int) sizeof (fst));
12265
12266 remote_fileio_to_host_stat (&fst, st);
12267
12268 return 0;
12269}
12270
12e2a5fd 12271/* Implementation of to_filesystem_is_local. */
e3dd7556 12272
57810aa7 12273bool
f6ac5f3d 12274remote_target::filesystem_is_local ()
e3dd7556
GB
12275{
12276 /* Valgrind GDB presents itself as a remote target but works
12277 on the local filesystem: it does not implement remote get
12278 and users are not expected to set a sysroot. To handle
12279 this case we treat the remote filesystem as local if the
12280 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12281 does not support vFile:open. */
a3be80c3 12282 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
12283 {
12284 enum packet_support ps = packet_support (PACKET_vFile_open);
12285
12286 if (ps == PACKET_SUPPORT_UNKNOWN)
12287 {
12288 int fd, remote_errno;
12289
12290 /* Try opening a file to probe support. The supplied
12291 filename is irrelevant, we only care about whether
12292 the stub recognizes the packet or not. */
6b8edb51 12293 fd = remote_hostio_open (NULL, "just probing",
4313b8c0 12294 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
12295 &remote_errno);
12296
12297 if (fd >= 0)
6b8edb51 12298 remote_hostio_close (fd, &remote_errno);
e3dd7556
GB
12299
12300 ps = packet_support (PACKET_vFile_open);
12301 }
12302
12303 if (ps == PACKET_DISABLE)
12304 {
12305 static int warning_issued = 0;
12306
12307 if (!warning_issued)
12308 {
12309 warning (_("remote target does not support file"
12310 " transfer, attempting to access files"
12311 " from local filesystem."));
12312 warning_issued = 1;
12313 }
12314
57810aa7 12315 return true;
e3dd7556
GB
12316 }
12317 }
12318
57810aa7 12319 return false;
e3dd7556
GB
12320}
12321
a6b151f1
DJ
12322static int
12323remote_fileio_errno_to_host (int errnum)
12324{
12325 switch (errnum)
12326 {
12327 case FILEIO_EPERM:
12328 return EPERM;
12329 case FILEIO_ENOENT:
12330 return ENOENT;
12331 case FILEIO_EINTR:
12332 return EINTR;
12333 case FILEIO_EIO:
12334 return EIO;
12335 case FILEIO_EBADF:
12336 return EBADF;
12337 case FILEIO_EACCES:
12338 return EACCES;
12339 case FILEIO_EFAULT:
12340 return EFAULT;
12341 case FILEIO_EBUSY:
12342 return EBUSY;
12343 case FILEIO_EEXIST:
12344 return EEXIST;
12345 case FILEIO_ENODEV:
12346 return ENODEV;
12347 case FILEIO_ENOTDIR:
12348 return ENOTDIR;
12349 case FILEIO_EISDIR:
12350 return EISDIR;
12351 case FILEIO_EINVAL:
12352 return EINVAL;
12353 case FILEIO_ENFILE:
12354 return ENFILE;
12355 case FILEIO_EMFILE:
12356 return EMFILE;
12357 case FILEIO_EFBIG:
12358 return EFBIG;
12359 case FILEIO_ENOSPC:
12360 return ENOSPC;
12361 case FILEIO_ESPIPE:
12362 return ESPIPE;
12363 case FILEIO_EROFS:
12364 return EROFS;
12365 case FILEIO_ENOSYS:
12366 return ENOSYS;
12367 case FILEIO_ENAMETOOLONG:
12368 return ENAMETOOLONG;
12369 }
12370 return -1;
12371}
12372
12373static char *
12374remote_hostio_error (int errnum)
12375{
12376 int host_error = remote_fileio_errno_to_host (errnum);
12377
12378 if (host_error == -1)
12379 error (_("Unknown remote I/O error %d"), errnum);
12380 else
12381 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12382}
12383
440b7aec
PA
12384/* A RAII wrapper around a remote file descriptor. */
12385
12386class scoped_remote_fd
a6b151f1 12387{
440b7aec 12388public:
6b8edb51
PA
12389 scoped_remote_fd (remote_target *remote, int fd)
12390 : m_remote (remote), m_fd (fd)
440b7aec
PA
12391 {
12392 }
a6b151f1 12393
440b7aec
PA
12394 ~scoped_remote_fd ()
12395 {
12396 if (m_fd != -1)
12397 {
12398 try
12399 {
12400 int remote_errno;
6b8edb51 12401 m_remote->remote_hostio_close (m_fd, &remote_errno);
440b7aec
PA
12402 }
12403 catch (...)
12404 {
12405 /* Swallow exception before it escapes the dtor. If
12406 something goes wrong, likely the connection is gone,
12407 and there's nothing else that can be done. */
12408 }
12409 }
12410 }
12411
12412 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12413
12414 /* Release ownership of the file descriptor, and return it. */
12415 int release () noexcept
12416 {
12417 int fd = m_fd;
12418 m_fd = -1;
12419 return fd;
12420 }
12421
12422 /* Return the owned file descriptor. */
12423 int get () const noexcept
12424 {
12425 return m_fd;
12426 }
12427
12428private:
6b8edb51
PA
12429 /* The remote target. */
12430 remote_target *m_remote;
12431
440b7aec
PA
12432 /* The owned remote I/O file descriptor. */
12433 int m_fd;
12434};
a6b151f1
DJ
12435
12436void
12437remote_file_put (const char *local_file, const char *remote_file, int from_tty)
6b8edb51
PA
12438{
12439 remote_target *remote = get_current_remote_target ();
12440
12441 if (remote == nullptr)
12442 error (_("command can only be used with remote target"));
12443
12444 remote->remote_file_put (local_file, remote_file, from_tty);
12445}
12446
12447void
12448remote_target::remote_file_put (const char *local_file, const char *remote_file,
12449 int from_tty)
a6b151f1 12450{
440b7aec 12451 int retcode, remote_errno, bytes, io_size;
a6b151f1
DJ
12452 int bytes_in_buffer;
12453 int saw_eof;
12454 ULONGEST offset;
a6b151f1 12455
d419f42d 12456 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
12457 if (file == NULL)
12458 perror_with_name (local_file);
a6b151f1 12459
440b7aec 12460 scoped_remote_fd fd
6b8edb51
PA
12461 (this, remote_hostio_open (NULL,
12462 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12463 | FILEIO_O_TRUNC),
12464 0700, 0, &remote_errno));
440b7aec 12465 if (fd.get () == -1)
a6b151f1
DJ
12466 remote_hostio_error (remote_errno);
12467
12468 /* Send up to this many bytes at once. They won't all fit in the
12469 remote packet limit, so we'll transfer slightly fewer. */
12470 io_size = get_remote_packet_size ();
5ca3b260 12471 gdb::byte_vector buffer (io_size);
a6b151f1 12472
a6b151f1
DJ
12473 bytes_in_buffer = 0;
12474 saw_eof = 0;
12475 offset = 0;
12476 while (bytes_in_buffer || !saw_eof)
12477 {
12478 if (!saw_eof)
12479 {
5ca3b260 12480 bytes = fread (buffer.data () + bytes_in_buffer, 1,
3e43a32a 12481 io_size - bytes_in_buffer,
d419f42d 12482 file.get ());
a6b151f1
DJ
12483 if (bytes == 0)
12484 {
d419f42d 12485 if (ferror (file.get ()))
a6b151f1
DJ
12486 error (_("Error reading %s."), local_file);
12487 else
12488 {
12489 /* EOF. Unless there is something still in the
12490 buffer from the last iteration, we are done. */
12491 saw_eof = 1;
12492 if (bytes_in_buffer == 0)
12493 break;
12494 }
12495 }
12496 }
12497 else
12498 bytes = 0;
12499
12500 bytes += bytes_in_buffer;
12501 bytes_in_buffer = 0;
12502
5ca3b260 12503 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
3e43a32a 12504 offset, &remote_errno);
a6b151f1
DJ
12505
12506 if (retcode < 0)
12507 remote_hostio_error (remote_errno);
12508 else if (retcode == 0)
12509 error (_("Remote write of %d bytes returned 0!"), bytes);
12510 else if (retcode < bytes)
12511 {
12512 /* Short write. Save the rest of the read data for the next
12513 write. */
12514 bytes_in_buffer = bytes - retcode;
5ca3b260 12515 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
a6b151f1
DJ
12516 }
12517
12518 offset += retcode;
12519 }
12520
6b8edb51 12521 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
12522 remote_hostio_error (remote_errno);
12523
12524 if (from_tty)
12525 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
a6b151f1
DJ
12526}
12527
12528void
12529remote_file_get (const char *remote_file, const char *local_file, int from_tty)
6b8edb51
PA
12530{
12531 remote_target *remote = get_current_remote_target ();
12532
12533 if (remote == nullptr)
12534 error (_("command can only be used with remote target"));
12535
12536 remote->remote_file_get (remote_file, local_file, from_tty);
12537}
12538
12539void
12540remote_target::remote_file_get (const char *remote_file, const char *local_file,
12541 int from_tty)
a6b151f1 12542{
440b7aec 12543 int remote_errno, bytes, io_size;
a6b151f1 12544 ULONGEST offset;
a6b151f1 12545
440b7aec 12546 scoped_remote_fd fd
6b8edb51
PA
12547 (this, remote_hostio_open (NULL,
12548 remote_file, FILEIO_O_RDONLY, 0, 0,
12549 &remote_errno));
440b7aec 12550 if (fd.get () == -1)
a6b151f1
DJ
12551 remote_hostio_error (remote_errno);
12552
d419f42d 12553 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
12554 if (file == NULL)
12555 perror_with_name (local_file);
a6b151f1
DJ
12556
12557 /* Send up to this many bytes at once. They won't all fit in the
12558 remote packet limit, so we'll transfer slightly fewer. */
12559 io_size = get_remote_packet_size ();
5ca3b260 12560 gdb::byte_vector buffer (io_size);
a6b151f1 12561
a6b151f1
DJ
12562 offset = 0;
12563 while (1)
12564 {
5ca3b260 12565 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
440b7aec 12566 &remote_errno);
a6b151f1
DJ
12567 if (bytes == 0)
12568 /* Success, but no bytes, means end-of-file. */
12569 break;
12570 if (bytes == -1)
12571 remote_hostio_error (remote_errno);
12572
12573 offset += bytes;
12574
5ca3b260 12575 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
a6b151f1
DJ
12576 if (bytes == 0)
12577 perror_with_name (local_file);
12578 }
12579
6b8edb51 12580 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
12581 remote_hostio_error (remote_errno);
12582
12583 if (from_tty)
12584 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
a6b151f1
DJ
12585}
12586
12587void
12588remote_file_delete (const char *remote_file, int from_tty)
12589{
6b8edb51 12590 remote_target *remote = get_current_remote_target ();
a6b151f1 12591
6b8edb51 12592 if (remote == nullptr)
a6b151f1
DJ
12593 error (_("command can only be used with remote target"));
12594
6b8edb51
PA
12595 remote->remote_file_delete (remote_file, from_tty);
12596}
12597
12598void
12599remote_target::remote_file_delete (const char *remote_file, int from_tty)
12600{
12601 int retcode, remote_errno;
12602
12603 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
a6b151f1
DJ
12604 if (retcode == -1)
12605 remote_hostio_error (remote_errno);
12606
12607 if (from_tty)
12608 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12609}
12610
12611static void
ac88e2de 12612remote_put_command (const char *args, int from_tty)
a6b151f1 12613{
d1a41061
PP
12614 if (args == NULL)
12615 error_no_arg (_("file to put"));
12616
773a1edc 12617 gdb_argv argv (args);
a6b151f1
DJ
12618 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12619 error (_("Invalid parameters to remote put"));
12620
12621 remote_file_put (argv[0], argv[1], from_tty);
a6b151f1
DJ
12622}
12623
12624static void
ac88e2de 12625remote_get_command (const char *args, int from_tty)
a6b151f1 12626{
d1a41061
PP
12627 if (args == NULL)
12628 error_no_arg (_("file to get"));
12629
773a1edc 12630 gdb_argv argv (args);
a6b151f1
DJ
12631 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12632 error (_("Invalid parameters to remote get"));
12633
12634 remote_file_get (argv[0], argv[1], from_tty);
a6b151f1
DJ
12635}
12636
12637static void
ac88e2de 12638remote_delete_command (const char *args, int from_tty)
a6b151f1 12639{
d1a41061
PP
12640 if (args == NULL)
12641 error_no_arg (_("file to delete"));
12642
773a1edc 12643 gdb_argv argv (args);
a6b151f1
DJ
12644 if (argv[0] == NULL || argv[1] != NULL)
12645 error (_("Invalid parameters to remote delete"));
12646
12647 remote_file_delete (argv[0], from_tty);
a6b151f1
DJ
12648}
12649
12650static void
981a3fb3 12651remote_command (const char *args, int from_tty)
a6b151f1 12652{
635c7e8a 12653 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
12654}
12655
57810aa7 12656bool
f6ac5f3d 12657remote_target::can_execute_reverse ()
b2175913 12658{
4082afcc
PA
12659 if (packet_support (PACKET_bs) == PACKET_ENABLE
12660 || packet_support (PACKET_bc) == PACKET_ENABLE)
57810aa7 12661 return true;
40ab02ce 12662 else
57810aa7 12663 return false;
b2175913
MS
12664}
12665
57810aa7 12666bool
f6ac5f3d 12667remote_target::supports_non_stop ()
74531fed 12668{
57810aa7 12669 return true;
74531fed
PA
12670}
12671
57810aa7 12672bool
f6ac5f3d 12673remote_target::supports_disable_randomization ()
03583c20
UW
12674{
12675 /* Only supported in extended mode. */
57810aa7 12676 return false;
03583c20
UW
12677}
12678
57810aa7 12679bool
f6ac5f3d 12680remote_target::supports_multi_process ()
8a305172
PA
12681{
12682 struct remote_state *rs = get_remote_state ();
a744cf53 12683
8020350c 12684 return remote_multi_process_p (rs);
8a305172
PA
12685}
12686
70221824 12687static int
f6ac5f3d 12688remote_supports_cond_tracepoints ()
782b2b07 12689{
4082afcc 12690 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
12691}
12692
57810aa7 12693bool
f6ac5f3d 12694remote_target::supports_evaluation_of_breakpoint_conditions ()
3788aec7 12695{
4082afcc 12696 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
12697}
12698
70221824 12699static int
f6ac5f3d 12700remote_supports_fast_tracepoints ()
7a697b8d 12701{
4082afcc 12702 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
12703}
12704
0fb4aa4b 12705static int
f6ac5f3d 12706remote_supports_static_tracepoints ()
0fb4aa4b 12707{
4082afcc 12708 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
12709}
12710
1e4d1764 12711static int
f6ac5f3d 12712remote_supports_install_in_trace ()
1e4d1764 12713{
4082afcc 12714 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
12715}
12716
57810aa7 12717bool
f6ac5f3d 12718remote_target::supports_enable_disable_tracepoint ()
d248b706 12719{
4082afcc
PA
12720 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12721 == PACKET_ENABLE);
d248b706
KY
12722}
12723
57810aa7 12724bool
f6ac5f3d 12725remote_target::supports_string_tracing ()
3065dfb6 12726{
4082afcc 12727 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
12728}
12729
57810aa7 12730bool
f6ac5f3d 12731remote_target::can_run_breakpoint_commands ()
d3ce09f5 12732{
4082afcc 12733 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
12734}
12735
f6ac5f3d
PA
12736void
12737remote_target::trace_init ()
35b1e5cc 12738{
b6bb3468
PA
12739 struct remote_state *rs = get_remote_state ();
12740
35b1e5cc 12741 putpkt ("QTinit");
b6bb3468 12742 remote_get_noisy_reply ();
8d64371b 12743 if (strcmp (rs->buf.data (), "OK") != 0)
35b1e5cc
SS
12744 error (_("Target does not support this command."));
12745}
12746
409873ef
SS
12747/* Recursive routine to walk through command list including loops, and
12748 download packets for each command. */
12749
6b8edb51
PA
12750void
12751remote_target::remote_download_command_source (int num, ULONGEST addr,
12752 struct command_line *cmds)
409873ef
SS
12753{
12754 struct remote_state *rs = get_remote_state ();
12755 struct command_line *cmd;
12756
12757 for (cmd = cmds; cmd; cmd = cmd->next)
12758 {
0df8b418 12759 QUIT; /* Allow user to bail out with ^C. */
8d64371b 12760 strcpy (rs->buf.data (), "QTDPsrc:");
409873ef 12761 encode_source_string (num, addr, "cmd", cmd->line,
8d64371b
TT
12762 rs->buf.data () + strlen (rs->buf.data ()),
12763 rs->buf.size () - strlen (rs->buf.data ()));
409873ef 12764 putpkt (rs->buf);
b6bb3468 12765 remote_get_noisy_reply ();
8d64371b 12766 if (strcmp (rs->buf.data (), "OK"))
409873ef
SS
12767 warning (_("Target does not support source download."));
12768
12769 if (cmd->control_type == while_control
12770 || cmd->control_type == while_stepping_control)
12771 {
12973681 12772 remote_download_command_source (num, addr, cmd->body_list_0.get ());
409873ef 12773
0df8b418 12774 QUIT; /* Allow user to bail out with ^C. */
8d64371b 12775 strcpy (rs->buf.data (), "QTDPsrc:");
409873ef 12776 encode_source_string (num, addr, "cmd", "end",
8d64371b
TT
12777 rs->buf.data () + strlen (rs->buf.data ()),
12778 rs->buf.size () - strlen (rs->buf.data ()));
409873ef 12779 putpkt (rs->buf);
b6bb3468 12780 remote_get_noisy_reply ();
8d64371b 12781 if (strcmp (rs->buf.data (), "OK"))
409873ef
SS
12782 warning (_("Target does not support source download."));
12783 }
12784 }
12785}
12786
f6ac5f3d
PA
12787void
12788remote_target::download_tracepoint (struct bp_location *loc)
35b1e5cc
SS
12789{
12790 CORE_ADDR tpaddr;
409873ef 12791 char addrbuf[40];
b44ec619
SM
12792 std::vector<std::string> tdp_actions;
12793 std::vector<std::string> stepping_actions;
35b1e5cc 12794 char *pkt;
e8ba3115 12795 struct breakpoint *b = loc->owner;
d9b3f62e 12796 struct tracepoint *t = (struct tracepoint *) b;
b6bb3468 12797 struct remote_state *rs = get_remote_state ();
3df3a985 12798 int ret;
ff36536c 12799 const char *err_msg = _("Tracepoint packet too large for target.");
3df3a985
PFC
12800 size_t size_left;
12801
12802 /* We use a buffer other than rs->buf because we'll build strings
12803 across multiple statements, and other statements in between could
12804 modify rs->buf. */
12805 gdb::char_vector buf (get_remote_packet_size ());
35b1e5cc 12806
dc673c81 12807 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
12808
12809 tpaddr = loc->address;
12810 sprintf_vma (addrbuf, tpaddr);
3df3a985
PFC
12811 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
12812 b->number, addrbuf, /* address */
12813 (b->enable_state == bp_enabled ? 'E' : 'D'),
12814 t->step_count, t->pass_count);
12815
12816 if (ret < 0 || ret >= buf.size ())
a7f25a84 12817 error ("%s", err_msg);
3df3a985 12818
e8ba3115
YQ
12819 /* Fast tracepoints are mostly handled by the target, but we can
12820 tell the target how big of an instruction block should be moved
12821 around. */
12822 if (b->type == bp_fast_tracepoint)
12823 {
12824 /* Only test for support at download time; we may not know
12825 target capabilities at definition time. */
12826 if (remote_supports_fast_tracepoints ())
35b1e5cc 12827 {
6b940e6a
PL
12828 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12829 NULL))
3df3a985
PFC
12830 {
12831 size_left = buf.size () - strlen (buf.data ());
12832 ret = snprintf (buf.data () + strlen (buf.data ()),
12833 size_left, ":F%x",
12834 gdb_insn_length (loc->gdbarch, tpaddr));
12835
12836 if (ret < 0 || ret >= size_left)
a7f25a84 12837 error ("%s", err_msg);
3df3a985 12838 }
35b1e5cc 12839 else
e8ba3115
YQ
12840 /* If it passed validation at definition but fails now,
12841 something is very wrong. */
12842 internal_error (__FILE__, __LINE__,
12843 _("Fast tracepoint not "
12844 "valid during download"));
35b1e5cc 12845 }
e8ba3115
YQ
12846 else
12847 /* Fast tracepoints are functionally identical to regular
12848 tracepoints, so don't take lack of support as a reason to
12849 give up on the trace run. */
12850 warning (_("Target does not support fast tracepoints, "
12851 "downloading %d as regular tracepoint"), b->number);
12852 }
12853 else if (b->type == bp_static_tracepoint)
12854 {
12855 /* Only test for support at download time; we may not know
12856 target capabilities at definition time. */
12857 if (remote_supports_static_tracepoints ())
0fb4aa4b 12858 {
e8ba3115 12859 struct static_tracepoint_marker marker;
0fb4aa4b 12860
e8ba3115 12861 if (target_static_tracepoint_marker_at (tpaddr, &marker))
3df3a985
PFC
12862 {
12863 size_left = buf.size () - strlen (buf.data ());
12864 ret = snprintf (buf.data () + strlen (buf.data ()),
12865 size_left, ":S");
12866
12867 if (ret < 0 || ret >= size_left)
a7f25a84 12868 error ("%s", err_msg);
3df3a985 12869 }
0fb4aa4b 12870 else
e8ba3115 12871 error (_("Static tracepoint not valid during download"));
0fb4aa4b 12872 }
e8ba3115
YQ
12873 else
12874 /* Fast tracepoints are functionally identical to regular
12875 tracepoints, so don't take lack of support as a reason
12876 to give up on the trace run. */
12877 error (_("Target does not support static tracepoints"));
12878 }
12879 /* If the tracepoint has a conditional, make it into an agent
12880 expression and append to the definition. */
12881 if (loc->cond)
12882 {
12883 /* Only test support at download time, we may not know target
12884 capabilities at definition time. */
12885 if (remote_supports_cond_tracepoints ())
35b1e5cc 12886 {
3df3a985
PFC
12887 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
12888 loc->cond.get ());
12889
12890 size_left = buf.size () - strlen (buf.data ());
12891
12892 ret = snprintf (buf.data () + strlen (buf.data ()),
12893 size_left, ":X%x,", aexpr->len);
12894
12895 if (ret < 0 || ret >= size_left)
a7f25a84 12896 error ("%s", err_msg);
3df3a985
PFC
12897
12898 size_left = buf.size () - strlen (buf.data ());
12899
12900 /* Two bytes to encode each aexpr byte, plus the terminating
12901 null byte. */
12902 if (aexpr->len * 2 + 1 > size_left)
a7f25a84 12903 error ("%s", err_msg);
3df3a985
PFC
12904
12905 pkt = buf.data () + strlen (buf.data ());
12906
b44ec619 12907 for (int ndx = 0; ndx < aexpr->len; ++ndx)
e8ba3115
YQ
12908 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12909 *pkt = '\0';
35b1e5cc 12910 }
e8ba3115
YQ
12911 else
12912 warning (_("Target does not support conditional tracepoints, "
12913 "ignoring tp %d cond"), b->number);
12914 }
35b1e5cc 12915
d9b3f62e 12916 if (b->commands || *default_collect)
3df3a985
PFC
12917 {
12918 size_left = buf.size () - strlen (buf.data ());
12919
12920 ret = snprintf (buf.data () + strlen (buf.data ()),
12921 size_left, "-");
12922
12923 if (ret < 0 || ret >= size_left)
a7f25a84 12924 error ("%s", err_msg);
3df3a985
PFC
12925 }
12926
12927 putpkt (buf.data ());
b6bb3468 12928 remote_get_noisy_reply ();
8d64371b 12929 if (strcmp (rs->buf.data (), "OK"))
e8ba3115 12930 error (_("Target does not support tracepoints."));
35b1e5cc 12931
e8ba3115 12932 /* do_single_steps (t); */
b44ec619
SM
12933 for (auto action_it = tdp_actions.begin ();
12934 action_it != tdp_actions.end (); action_it++)
e8ba3115 12935 {
b44ec619
SM
12936 QUIT; /* Allow user to bail out with ^C. */
12937
aa6f3694 12938 bool has_more = ((action_it + 1) != tdp_actions.end ()
b44ec619
SM
12939 || !stepping_actions.empty ());
12940
3df3a985
PFC
12941 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
12942 b->number, addrbuf, /* address */
12943 action_it->c_str (),
12944 has_more ? '-' : 0);
12945
12946 if (ret < 0 || ret >= buf.size ())
a7f25a84 12947 error ("%s", err_msg);
3df3a985
PFC
12948
12949 putpkt (buf.data ());
b44ec619 12950 remote_get_noisy_reply ();
8d64371b 12951 if (strcmp (rs->buf.data (), "OK"))
b44ec619 12952 error (_("Error on target while setting tracepoints."));
e8ba3115 12953 }
409873ef 12954
05abfc39
PFC
12955 for (auto action_it = stepping_actions.begin ();
12956 action_it != stepping_actions.end (); action_it++)
12957 {
12958 QUIT; /* Allow user to bail out with ^C. */
12959
12960 bool is_first = action_it == stepping_actions.begin ();
aa6f3694 12961 bool has_more = (action_it + 1) != stepping_actions.end ();
05abfc39 12962
3df3a985
PFC
12963 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
12964 b->number, addrbuf, /* address */
12965 is_first ? "S" : "",
12966 action_it->c_str (),
12967 has_more ? "-" : "");
12968
12969 if (ret < 0 || ret >= buf.size ())
a7f25a84 12970 error ("%s", err_msg);
3df3a985
PFC
12971
12972 putpkt (buf.data ());
05abfc39 12973 remote_get_noisy_reply ();
8d64371b 12974 if (strcmp (rs->buf.data (), "OK"))
05abfc39
PFC
12975 error (_("Error on target while setting tracepoints."));
12976 }
b44ec619 12977
4082afcc 12978 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 12979 {
f00aae0f 12980 if (b->location != NULL)
409873ef 12981 {
3df3a985
PFC
12982 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
12983
12984 if (ret < 0 || ret >= buf.size ())
a7f25a84 12985 error ("%s", err_msg);
3df3a985 12986
f00aae0f 12987 encode_source_string (b->number, loc->address, "at",
d28cd78a 12988 event_location_to_string (b->location.get ()),
3df3a985
PFC
12989 buf.data () + strlen (buf.data ()),
12990 buf.size () - strlen (buf.data ()));
12991 putpkt (buf.data ());
b6bb3468 12992 remote_get_noisy_reply ();
8d64371b 12993 if (strcmp (rs->buf.data (), "OK"))
e8ba3115 12994 warning (_("Target does not support source download."));
409873ef 12995 }
e8ba3115
YQ
12996 if (b->cond_string)
12997 {
3df3a985
PFC
12998 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
12999
13000 if (ret < 0 || ret >= buf.size ())
a7f25a84 13001 error ("%s", err_msg);
3df3a985 13002
e8ba3115 13003 encode_source_string (b->number, loc->address,
3df3a985
PFC
13004 "cond", b->cond_string,
13005 buf.data () + strlen (buf.data ()),
13006 buf.size () - strlen (buf.data ()));
13007 putpkt (buf.data ());
b6bb3468 13008 remote_get_noisy_reply ();
8d64371b 13009 if (strcmp (rs->buf.data (), "OK"))
e8ba3115
YQ
13010 warning (_("Target does not support source download."));
13011 }
13012 remote_download_command_source (b->number, loc->address,
13013 breakpoint_commands (b));
35b1e5cc 13014 }
35b1e5cc
SS
13015}
13016
57810aa7 13017bool
f6ac5f3d 13018remote_target::can_download_tracepoint ()
1e4d1764 13019{
1e51243a
PA
13020 struct remote_state *rs = get_remote_state ();
13021 struct trace_status *ts;
13022 int status;
13023
13024 /* Don't try to install tracepoints until we've relocated our
13025 symbols, and fetched and merged the target's tracepoint list with
13026 ours. */
13027 if (rs->starting_up)
57810aa7 13028 return false;
1e51243a
PA
13029
13030 ts = current_trace_status ();
f6ac5f3d 13031 status = get_trace_status (ts);
1e4d1764
YQ
13032
13033 if (status == -1 || !ts->running_known || !ts->running)
57810aa7 13034 return false;
1e4d1764
YQ
13035
13036 /* If we are in a tracing experiment, but remote stub doesn't support
13037 installing tracepoint in trace, we have to return. */
13038 if (!remote_supports_install_in_trace ())
57810aa7 13039 return false;
1e4d1764 13040
57810aa7 13041 return true;
1e4d1764
YQ
13042}
13043
13044
f6ac5f3d
PA
13045void
13046remote_target::download_trace_state_variable (const trace_state_variable &tsv)
35b1e5cc
SS
13047{
13048 struct remote_state *rs = get_remote_state ();
00bf0b85 13049 char *p;
35b1e5cc 13050
8d64371b 13051 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
c252925c
SM
13052 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13053 tsv.builtin);
8d64371b
TT
13054 p = rs->buf.data () + strlen (rs->buf.data ());
13055 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13056 >= get_remote_packet_size ())
00bf0b85 13057 error (_("Trace state variable name too long for tsv definition packet"));
c252925c 13058 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
00bf0b85 13059 *p++ = '\0';
35b1e5cc 13060 putpkt (rs->buf);
b6bb3468 13061 remote_get_noisy_reply ();
8d64371b 13062 if (rs->buf[0] == '\0')
ad91cd99 13063 error (_("Target does not support this command."));
8d64371b 13064 if (strcmp (rs->buf.data (), "OK") != 0)
ad91cd99 13065 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
13066}
13067
f6ac5f3d
PA
13068void
13069remote_target::enable_tracepoint (struct bp_location *location)
d248b706
KY
13070{
13071 struct remote_state *rs = get_remote_state ();
13072 char addr_buf[40];
13073
13074 sprintf_vma (addr_buf, location->address);
8d64371b 13075 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
bba74b36 13076 location->owner->number, addr_buf);
d248b706 13077 putpkt (rs->buf);
b6bb3468 13078 remote_get_noisy_reply ();
8d64371b 13079 if (rs->buf[0] == '\0')
d248b706 13080 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
8d64371b 13081 if (strcmp (rs->buf.data (), "OK") != 0)
d248b706
KY
13082 error (_("Error on target while enabling tracepoint."));
13083}
13084
f6ac5f3d
PA
13085void
13086remote_target::disable_tracepoint (struct bp_location *location)
d248b706
KY
13087{
13088 struct remote_state *rs = get_remote_state ();
13089 char addr_buf[40];
13090
13091 sprintf_vma (addr_buf, location->address);
8d64371b 13092 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
bba74b36 13093 location->owner->number, addr_buf);
d248b706 13094 putpkt (rs->buf);
b6bb3468 13095 remote_get_noisy_reply ();
8d64371b 13096 if (rs->buf[0] == '\0')
d248b706 13097 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
8d64371b 13098 if (strcmp (rs->buf.data (), "OK") != 0)
d248b706
KY
13099 error (_("Error on target while disabling tracepoint."));
13100}
13101
f6ac5f3d
PA
13102void
13103remote_target::trace_set_readonly_regions ()
35b1e5cc
SS
13104{
13105 asection *s;
81b9b86e 13106 bfd *abfd = NULL;
35b1e5cc 13107 bfd_size_type size;
608bcef2 13108 bfd_vma vma;
35b1e5cc 13109 int anysecs = 0;
c2fa21f1 13110 int offset = 0;
35b1e5cc
SS
13111
13112 if (!exec_bfd)
13113 return; /* No information to give. */
13114
b6bb3468
PA
13115 struct remote_state *rs = get_remote_state ();
13116
8d64371b
TT
13117 strcpy (rs->buf.data (), "QTro");
13118 offset = strlen (rs->buf.data ());
35b1e5cc
SS
13119 for (s = exec_bfd->sections; s; s = s->next)
13120 {
13121 char tmp1[40], tmp2[40];
c2fa21f1 13122 int sec_length;
35b1e5cc
SS
13123
13124 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 13125 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
13126 (s->flags & SEC_READONLY) == 0)
13127 continue;
13128
13129 anysecs = 1;
81b9b86e 13130 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 13131 size = bfd_get_section_size (s);
608bcef2
HZ
13132 sprintf_vma (tmp1, vma);
13133 sprintf_vma (tmp2, vma + size);
c2fa21f1 13134 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
8d64371b 13135 if (offset + sec_length + 1 > rs->buf.size ())
c2fa21f1 13136 {
4082afcc 13137 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 13138 warning (_("\
c2fa21f1
HZ
13139Too many sections for read-only sections definition packet."));
13140 break;
13141 }
8d64371b 13142 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
bba74b36 13143 tmp1, tmp2);
c2fa21f1 13144 offset += sec_length;
35b1e5cc
SS
13145 }
13146 if (anysecs)
13147 {
b6bb3468 13148 putpkt (rs->buf);
8d64371b 13149 getpkt (&rs->buf, 0);
35b1e5cc
SS
13150 }
13151}
13152
f6ac5f3d
PA
13153void
13154remote_target::trace_start ()
35b1e5cc 13155{
b6bb3468
PA
13156 struct remote_state *rs = get_remote_state ();
13157
35b1e5cc 13158 putpkt ("QTStart");
b6bb3468 13159 remote_get_noisy_reply ();
8d64371b 13160 if (rs->buf[0] == '\0')
ad91cd99 13161 error (_("Target does not support this command."));
8d64371b
TT
13162 if (strcmp (rs->buf.data (), "OK") != 0)
13163 error (_("Bogus reply from target: %s"), rs->buf.data ());
35b1e5cc
SS
13164}
13165
f6ac5f3d
PA
13166int
13167remote_target::get_trace_status (struct trace_status *ts)
35b1e5cc 13168{
953b98d1 13169 /* Initialize it just to avoid a GCC false warning. */
f652de6f 13170 char *p = NULL;
0df8b418 13171 /* FIXME we need to get register block size some other way. */
00bf0b85 13172 extern int trace_regblock_size;
bd3eecc3 13173 enum packet_result result;
b6bb3468 13174 struct remote_state *rs = get_remote_state ();
bd3eecc3 13175
4082afcc 13176 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 13177 return -1;
a744cf53 13178
5cd63fda 13179 trace_regblock_size
9d6eea31 13180 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
00bf0b85 13181
049dc89b
JK
13182 putpkt ("qTStatus");
13183
492d29ea 13184 TRY
67f41397 13185 {
b6bb3468 13186 p = remote_get_noisy_reply ();
67f41397 13187 }
492d29ea 13188 CATCH (ex, RETURN_MASK_ERROR)
67f41397 13189 {
598d3636
JK
13190 if (ex.error != TARGET_CLOSE_ERROR)
13191 {
13192 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13193 return -1;
13194 }
13195 throw_exception (ex);
67f41397 13196 }
492d29ea 13197 END_CATCH
00bf0b85 13198
bd3eecc3
PA
13199 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13200
00bf0b85 13201 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 13202 if (result == PACKET_UNKNOWN)
00bf0b85 13203 return -1;
35b1e5cc 13204
00bf0b85 13205 /* We're working with a live target. */
f5911ea1 13206 ts->filename = NULL;
00bf0b85 13207
00bf0b85 13208 if (*p++ != 'T')
8d64371b 13209 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
35b1e5cc 13210
84cebc4a
YQ
13211 /* Function 'parse_trace_status' sets default value of each field of
13212 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
13213 parse_trace_status (p, ts);
13214
13215 return ts->running;
35b1e5cc
SS
13216}
13217
f6ac5f3d
PA
13218void
13219remote_target::get_tracepoint_status (struct breakpoint *bp,
13220 struct uploaded_tp *utp)
f196051f
SS
13221{
13222 struct remote_state *rs = get_remote_state ();
f196051f
SS
13223 char *reply;
13224 struct bp_location *loc;
13225 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 13226 size_t size = get_remote_packet_size ();
f196051f
SS
13227
13228 if (tp)
13229 {
c1fc2657 13230 tp->hit_count = 0;
f196051f 13231 tp->traceframe_usage = 0;
c1fc2657 13232 for (loc = tp->loc; loc; loc = loc->next)
f196051f
SS
13233 {
13234 /* If the tracepoint was never downloaded, don't go asking for
13235 any status. */
13236 if (tp->number_on_target == 0)
13237 continue;
8d64371b 13238 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
bba74b36 13239 phex_nz (loc->address, 0));
f196051f 13240 putpkt (rs->buf);
b6bb3468 13241 reply = remote_get_noisy_reply ();
f196051f
SS
13242 if (reply && *reply)
13243 {
13244 if (*reply == 'V')
13245 parse_tracepoint_status (reply + 1, bp, utp);
13246 }
13247 }
13248 }
13249 else if (utp)
13250 {
13251 utp->hit_count = 0;
13252 utp->traceframe_usage = 0;
8d64371b 13253 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
bba74b36 13254 phex_nz (utp->addr, 0));
f196051f 13255 putpkt (rs->buf);
b6bb3468 13256 reply = remote_get_noisy_reply ();
f196051f
SS
13257 if (reply && *reply)
13258 {
13259 if (*reply == 'V')
13260 parse_tracepoint_status (reply + 1, bp, utp);
13261 }
13262 }
13263}
13264
f6ac5f3d
PA
13265void
13266remote_target::trace_stop ()
35b1e5cc 13267{
b6bb3468
PA
13268 struct remote_state *rs = get_remote_state ();
13269
35b1e5cc 13270 putpkt ("QTStop");
b6bb3468 13271 remote_get_noisy_reply ();
8d64371b 13272 if (rs->buf[0] == '\0')
ad91cd99 13273 error (_("Target does not support this command."));
8d64371b
TT
13274 if (strcmp (rs->buf.data (), "OK") != 0)
13275 error (_("Bogus reply from target: %s"), rs->buf.data ());
35b1e5cc
SS
13276}
13277
f6ac5f3d
PA
13278int
13279remote_target::trace_find (enum trace_find_type type, int num,
13280 CORE_ADDR addr1, CORE_ADDR addr2,
13281 int *tpp)
35b1e5cc
SS
13282{
13283 struct remote_state *rs = get_remote_state ();
8d64371b 13284 char *endbuf = rs->buf.data () + get_remote_packet_size ();
35b1e5cc
SS
13285 char *p, *reply;
13286 int target_frameno = -1, target_tracept = -1;
13287
e6e4e701
PA
13288 /* Lookups other than by absolute frame number depend on the current
13289 trace selected, so make sure it is correct on the remote end
13290 first. */
13291 if (type != tfind_number)
13292 set_remote_traceframe ();
13293
8d64371b 13294 p = rs->buf.data ();
35b1e5cc
SS
13295 strcpy (p, "QTFrame:");
13296 p = strchr (p, '\0');
13297 switch (type)
13298 {
13299 case tfind_number:
bba74b36 13300 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
13301 break;
13302 case tfind_pc:
bba74b36 13303 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
13304 break;
13305 case tfind_tp:
bba74b36 13306 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
13307 break;
13308 case tfind_range:
bba74b36
YQ
13309 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13310 phex_nz (addr2, 0));
35b1e5cc
SS
13311 break;
13312 case tfind_outside:
bba74b36
YQ
13313 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13314 phex_nz (addr2, 0));
35b1e5cc
SS
13315 break;
13316 default:
9b20d036 13317 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
13318 }
13319
13320 putpkt (rs->buf);
b6bb3468 13321 reply = remote_get_noisy_reply ();
ad91cd99
PA
13322 if (*reply == '\0')
13323 error (_("Target does not support this command."));
35b1e5cc
SS
13324
13325 while (reply && *reply)
13326 switch (*reply)
13327 {
13328 case 'F':
f197e0f1
VP
13329 p = ++reply;
13330 target_frameno = (int) strtol (p, &reply, 16);
13331 if (reply == p)
13332 error (_("Unable to parse trace frame number"));
e6e4e701
PA
13333 /* Don't update our remote traceframe number cache on failure
13334 to select a remote traceframe. */
f197e0f1
VP
13335 if (target_frameno == -1)
13336 return -1;
35b1e5cc
SS
13337 break;
13338 case 'T':
f197e0f1
VP
13339 p = ++reply;
13340 target_tracept = (int) strtol (p, &reply, 16);
13341 if (reply == p)
13342 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
13343 break;
13344 case 'O': /* "OK"? */
13345 if (reply[1] == 'K' && reply[2] == '\0')
13346 reply += 2;
13347 else
13348 error (_("Bogus reply from target: %s"), reply);
13349 break;
13350 default:
13351 error (_("Bogus reply from target: %s"), reply);
13352 }
13353 if (tpp)
13354 *tpp = target_tracept;
e6e4e701 13355
262e1174 13356 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
13357 return target_frameno;
13358}
13359
57810aa7 13360bool
f6ac5f3d 13361remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
35b1e5cc
SS
13362{
13363 struct remote_state *rs = get_remote_state ();
13364 char *reply;
13365 ULONGEST uval;
13366
e6e4e701
PA
13367 set_remote_traceframe ();
13368
8d64371b 13369 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc 13370 putpkt (rs->buf);
b6bb3468 13371 reply = remote_get_noisy_reply ();
35b1e5cc
SS
13372 if (reply && *reply)
13373 {
13374 if (*reply == 'V')
13375 {
13376 unpack_varlen_hex (reply + 1, &uval);
13377 *val = (LONGEST) uval;
57810aa7 13378 return true;
35b1e5cc
SS
13379 }
13380 }
57810aa7 13381 return false;
35b1e5cc
SS
13382}
13383
f6ac5f3d
PA
13384int
13385remote_target::save_trace_data (const char *filename)
00bf0b85
SS
13386{
13387 struct remote_state *rs = get_remote_state ();
13388 char *p, *reply;
13389
8d64371b 13390 p = rs->buf.data ();
00bf0b85
SS
13391 strcpy (p, "QTSave:");
13392 p += strlen (p);
8d64371b
TT
13393 if ((p - rs->buf.data ()) + strlen (filename) * 2
13394 >= get_remote_packet_size ())
00bf0b85 13395 error (_("Remote file name too long for trace save packet"));
9f1b45b0 13396 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
13397 *p++ = '\0';
13398 putpkt (rs->buf);
b6bb3468 13399 reply = remote_get_noisy_reply ();
d6c5869f 13400 if (*reply == '\0')
ad91cd99
PA
13401 error (_("Target does not support this command."));
13402 if (strcmp (reply, "OK") != 0)
13403 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
13404 return 0;
13405}
13406
13407/* This is basically a memory transfer, but needs to be its own packet
13408 because we don't know how the target actually organizes its trace
13409 memory, plus we want to be able to ask for as much as possible, but
13410 not be unhappy if we don't get as much as we ask for. */
13411
f6ac5f3d
PA
13412LONGEST
13413remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
13414{
13415 struct remote_state *rs = get_remote_state ();
13416 char *reply;
13417 char *p;
13418 int rslt;
13419
8d64371b 13420 p = rs->buf.data ();
00bf0b85
SS
13421 strcpy (p, "qTBuffer:");
13422 p += strlen (p);
13423 p += hexnumstr (p, offset);
13424 *p++ = ',';
13425 p += hexnumstr (p, len);
13426 *p++ = '\0';
13427
13428 putpkt (rs->buf);
b6bb3468 13429 reply = remote_get_noisy_reply ();
00bf0b85
SS
13430 if (reply && *reply)
13431 {
13432 /* 'l' by itself means we're at the end of the buffer and
13433 there is nothing more to get. */
13434 if (*reply == 'l')
13435 return 0;
13436
13437 /* Convert the reply into binary. Limit the number of bytes to
13438 convert according to our passed-in buffer size, rather than
13439 what was returned in the packet; if the target is
13440 unexpectedly generous and gives us a bigger reply than we
13441 asked for, we don't want to crash. */
b6bb3468 13442 rslt = hex2bin (reply, buf, len);
00bf0b85
SS
13443 return rslt;
13444 }
13445
13446 /* Something went wrong, flag as an error. */
13447 return -1;
13448}
13449
f6ac5f3d
PA
13450void
13451remote_target::set_disconnected_tracing (int val)
35b1e5cc
SS
13452{
13453 struct remote_state *rs = get_remote_state ();
13454
4082afcc 13455 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 13456 {
ad91cd99
PA
13457 char *reply;
13458
8d64371b
TT
13459 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13460 "QTDisconnected:%x", val);
33da3f1c 13461 putpkt (rs->buf);
b6bb3468 13462 reply = remote_get_noisy_reply ();
ad91cd99 13463 if (*reply == '\0')
33da3f1c 13464 error (_("Target does not support this command."));
ad91cd99
PA
13465 if (strcmp (reply, "OK") != 0)
13466 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
13467 }
13468 else if (val)
13469 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
13470}
13471
f6ac5f3d
PA
13472int
13473remote_target::core_of_thread (ptid_t ptid)
dc146f7c
VP
13474{
13475 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 13476
7aabaf9d
SM
13477 if (info != NULL && info->priv != NULL)
13478 return get_remote_thread_info (info)->core;
13479
dc146f7c
VP
13480 return -1;
13481}
13482
f6ac5f3d
PA
13483void
13484remote_target::set_circular_trace_buffer (int val)
4daf5ac0
SS
13485{
13486 struct remote_state *rs = get_remote_state ();
ad91cd99 13487 char *reply;
4daf5ac0 13488
8d64371b
TT
13489 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13490 "QTBuffer:circular:%x", val);
4daf5ac0 13491 putpkt (rs->buf);
b6bb3468 13492 reply = remote_get_noisy_reply ();
ad91cd99 13493 if (*reply == '\0')
4daf5ac0 13494 error (_("Target does not support this command."));
ad91cd99
PA
13495 if (strcmp (reply, "OK") != 0)
13496 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
13497}
13498
f6ac5f3d
PA
13499traceframe_info_up
13500remote_target::traceframe_info ()
b3b9301e 13501{
9018be22 13502 gdb::optional<gdb::char_vector> text
8b88a78e 13503 = target_read_stralloc (current_top_target (), TARGET_OBJECT_TRACEFRAME_INFO,
b7b030ad 13504 NULL);
9018be22
SM
13505 if (text)
13506 return parse_traceframe_info (text->data ());
b3b9301e
PA
13507
13508 return NULL;
13509}
13510
405f8e94
SS
13511/* Handle the qTMinFTPILen packet. Returns the minimum length of
13512 instruction on which a fast tracepoint may be placed. Returns -1
13513 if the packet is not supported, and 0 if the minimum instruction
13514 length is unknown. */
13515
f6ac5f3d
PA
13516int
13517remote_target::get_min_fast_tracepoint_insn_len ()
405f8e94
SS
13518{
13519 struct remote_state *rs = get_remote_state ();
13520 char *reply;
13521
e886a173
PA
13522 /* If we're not debugging a process yet, the IPA can't be
13523 loaded. */
13524 if (!target_has_execution)
13525 return 0;
13526
13527 /* Make sure the remote is pointing at the right process. */
13528 set_general_process ();
13529
8d64371b 13530 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
405f8e94 13531 putpkt (rs->buf);
b6bb3468 13532 reply = remote_get_noisy_reply ();
405f8e94
SS
13533 if (*reply == '\0')
13534 return -1;
13535 else
13536 {
13537 ULONGEST min_insn_len;
13538
13539 unpack_varlen_hex (reply, &min_insn_len);
13540
13541 return (int) min_insn_len;
13542 }
13543}
13544
f6ac5f3d
PA
13545void
13546remote_target::set_trace_buffer_size (LONGEST val)
f6f899bf 13547{
4082afcc 13548 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
13549 {
13550 struct remote_state *rs = get_remote_state ();
8d64371b
TT
13551 char *buf = rs->buf.data ();
13552 char *endbuf = buf + get_remote_packet_size ();
f6f899bf
HAQ
13553 enum packet_result result;
13554
13555 gdb_assert (val >= 0 || val == -1);
13556 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13557 /* Send -1 as literal "-1" to avoid host size dependency. */
13558 if (val < 0)
13559 {
13560 *buf++ = '-';
13561 buf += hexnumstr (buf, (ULONGEST) -val);
13562 }
13563 else
13564 buf += hexnumstr (buf, (ULONGEST) val);
13565
13566 putpkt (rs->buf);
b6bb3468 13567 remote_get_noisy_reply ();
f6f899bf
HAQ
13568 result = packet_ok (rs->buf,
13569 &remote_protocol_packets[PACKET_QTBuffer_size]);
13570
13571 if (result != PACKET_OK)
8d64371b 13572 warning (_("Bogus reply from target: %s"), rs->buf.data ());
f6f899bf
HAQ
13573 }
13574}
13575
57810aa7 13576bool
f6ac5f3d
PA
13577remote_target::set_trace_notes (const char *user, const char *notes,
13578 const char *stop_notes)
f196051f
SS
13579{
13580 struct remote_state *rs = get_remote_state ();
13581 char *reply;
8d64371b
TT
13582 char *buf = rs->buf.data ();
13583 char *endbuf = buf + get_remote_packet_size ();
f196051f
SS
13584 int nbytes;
13585
13586 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13587 if (user)
13588 {
13589 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 13590 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
13591 buf += 2 * nbytes;
13592 *buf++ = ';';
13593 }
13594 if (notes)
13595 {
13596 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 13597 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
13598 buf += 2 * nbytes;
13599 *buf++ = ';';
13600 }
13601 if (stop_notes)
13602 {
13603 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 13604 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
13605 buf += 2 * nbytes;
13606 *buf++ = ';';
13607 }
13608 /* Ensure the buffer is terminated. */
13609 *buf = '\0';
13610
13611 putpkt (rs->buf);
b6bb3468 13612 reply = remote_get_noisy_reply ();
f196051f 13613 if (*reply == '\0')
57810aa7 13614 return false;
f196051f
SS
13615
13616 if (strcmp (reply, "OK") != 0)
13617 error (_("Bogus reply from target: %s"), reply);
13618
57810aa7 13619 return true;
f196051f
SS
13620}
13621
57810aa7
PA
13622bool
13623remote_target::use_agent (bool use)
d1feda86 13624{
4082afcc 13625 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
13626 {
13627 struct remote_state *rs = get_remote_state ();
13628
13629 /* If the stub supports QAgent. */
8d64371b 13630 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
d1feda86 13631 putpkt (rs->buf);
8d64371b 13632 getpkt (&rs->buf, 0);
d1feda86 13633
8d64371b 13634 if (strcmp (rs->buf.data (), "OK") == 0)
d1feda86 13635 {
f6ac5f3d 13636 ::use_agent = use;
57810aa7 13637 return true;
d1feda86
YQ
13638 }
13639 }
13640
57810aa7 13641 return false;
d1feda86
YQ
13642}
13643
57810aa7 13644bool
f6ac5f3d 13645remote_target::can_use_agent ()
d1feda86 13646{
4082afcc 13647 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
13648}
13649
9accd112
MM
13650struct btrace_target_info
13651{
13652 /* The ptid of the traced thread. */
13653 ptid_t ptid;
f4abbc16
MM
13654
13655 /* The obtained branch trace configuration. */
13656 struct btrace_config conf;
9accd112
MM
13657};
13658
f4abbc16
MM
13659/* Reset our idea of our target's btrace configuration. */
13660
13661static void
6b8edb51 13662remote_btrace_reset (remote_state *rs)
f4abbc16 13663{
f4abbc16
MM
13664 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13665}
13666
f4abbc16
MM
13667/* Synchronize the configuration with the target. */
13668
6b8edb51
PA
13669void
13670remote_target::btrace_sync_conf (const btrace_config *conf)
f4abbc16 13671{
d33501a5
MM
13672 struct packet_config *packet;
13673 struct remote_state *rs;
13674 char *buf, *pos, *endbuf;
13675
13676 rs = get_remote_state ();
8d64371b 13677 buf = rs->buf.data ();
d33501a5
MM
13678 endbuf = buf + get_remote_packet_size ();
13679
13680 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13681 if (packet_config_support (packet) == PACKET_ENABLE
13682 && conf->bts.size != rs->btrace_config.bts.size)
13683 {
13684 pos = buf;
13685 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13686 conf->bts.size);
13687
13688 putpkt (buf);
8d64371b 13689 getpkt (&rs->buf, 0);
d33501a5
MM
13690
13691 if (packet_ok (buf, packet) == PACKET_ERROR)
13692 {
13693 if (buf[0] == 'E' && buf[1] == '.')
13694 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13695 else
13696 error (_("Failed to configure the BTS buffer size."));
13697 }
13698
13699 rs->btrace_config.bts.size = conf->bts.size;
13700 }
b20a6524
MM
13701
13702 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13703 if (packet_config_support (packet) == PACKET_ENABLE
13704 && conf->pt.size != rs->btrace_config.pt.size)
13705 {
13706 pos = buf;
13707 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13708 conf->pt.size);
13709
13710 putpkt (buf);
8d64371b 13711 getpkt (&rs->buf, 0);
b20a6524
MM
13712
13713 if (packet_ok (buf, packet) == PACKET_ERROR)
13714 {
13715 if (buf[0] == 'E' && buf[1] == '.')
13716 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13717 else
13718 error (_("Failed to configure the trace buffer size."));
13719 }
13720
13721 rs->btrace_config.pt.size = conf->pt.size;
13722 }
f4abbc16
MM
13723}
13724
13725/* Read the current thread's btrace configuration from the target and
13726 store it into CONF. */
13727
13728static void
13729btrace_read_config (struct btrace_config *conf)
13730{
9018be22 13731 gdb::optional<gdb::char_vector> xml
8b88a78e 13732 = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE_CONF, "");
9018be22
SM
13733 if (xml)
13734 parse_xml_btrace_conf (conf, xml->data ());
f4abbc16
MM
13735}
13736
c0272db5
TW
13737/* Maybe reopen target btrace. */
13738
6b8edb51
PA
13739void
13740remote_target::remote_btrace_maybe_reopen ()
c0272db5
TW
13741{
13742 struct remote_state *rs = get_remote_state ();
c0272db5 13743 int btrace_target_pushed = 0;
15766370 13744#if !defined (HAVE_LIBIPT)
c0272db5 13745 int warned = 0;
15766370 13746#endif
c0272db5 13747
5ed8105e
PA
13748 scoped_restore_current_thread restore_thread;
13749
08036331 13750 for (thread_info *tp : all_non_exited_threads ())
c0272db5
TW
13751 {
13752 set_general_thread (tp->ptid);
13753
13754 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13755 btrace_read_config (&rs->btrace_config);
13756
13757 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13758 continue;
13759
13760#if !defined (HAVE_LIBIPT)
13761 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13762 {
13763 if (!warned)
13764 {
13765 warned = 1;
c4e12631
MM
13766 warning (_("Target is recording using Intel Processor Trace "
13767 "but support was disabled at compile time."));
c0272db5
TW
13768 }
13769
13770 continue;
13771 }
13772#endif /* !defined (HAVE_LIBIPT) */
13773
13774 /* Push target, once, but before anything else happens. This way our
13775 changes to the threads will be cleaned up by unpushing the target
13776 in case btrace_read_config () throws. */
13777 if (!btrace_target_pushed)
13778 {
13779 btrace_target_pushed = 1;
13780 record_btrace_push_target ();
13781 printf_filtered (_("Target is recording using %s.\n"),
13782 btrace_format_string (rs->btrace_config.format));
13783 }
13784
13785 tp->btrace.target = XCNEW (struct btrace_target_info);
13786 tp->btrace.target->ptid = tp->ptid;
13787 tp->btrace.target->conf = rs->btrace_config;
13788 }
c0272db5
TW
13789}
13790
9accd112
MM
13791/* Enable branch tracing. */
13792
f6ac5f3d
PA
13793struct btrace_target_info *
13794remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
9accd112
MM
13795{
13796 struct btrace_target_info *tinfo = NULL;
b20a6524 13797 struct packet_config *packet = NULL;
9accd112 13798 struct remote_state *rs = get_remote_state ();
8d64371b
TT
13799 char *buf = rs->buf.data ();
13800 char *endbuf = buf + get_remote_packet_size ();
9accd112 13801
b20a6524
MM
13802 switch (conf->format)
13803 {
13804 case BTRACE_FORMAT_BTS:
13805 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13806 break;
13807
13808 case BTRACE_FORMAT_PT:
13809 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13810 break;
13811 }
13812
13813 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13814 error (_("Target does not support branch tracing."));
13815
f4abbc16
MM
13816 btrace_sync_conf (conf);
13817
9accd112
MM
13818 set_general_thread (ptid);
13819
13820 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13821 putpkt (rs->buf);
8d64371b 13822 getpkt (&rs->buf, 0);
9accd112
MM
13823
13824 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13825 {
13826 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13827 error (_("Could not enable branch tracing for %s: %s"),
8d64371b 13828 target_pid_to_str (ptid), &rs->buf[2]);
9accd112
MM
13829 else
13830 error (_("Could not enable branch tracing for %s."),
13831 target_pid_to_str (ptid));
13832 }
13833
8d749320 13834 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
13835 tinfo->ptid = ptid;
13836
f4abbc16
MM
13837 /* If we fail to read the configuration, we lose some information, but the
13838 tracing itself is not impacted. */
492d29ea
PA
13839 TRY
13840 {
13841 btrace_read_config (&tinfo->conf);
13842 }
13843 CATCH (err, RETURN_MASK_ERROR)
13844 {
13845 if (err.message != NULL)
13846 warning ("%s", err.message);
13847 }
13848 END_CATCH
f4abbc16 13849
9accd112
MM
13850 return tinfo;
13851}
13852
13853/* Disable branch tracing. */
13854
f6ac5f3d
PA
13855void
13856remote_target::disable_btrace (struct btrace_target_info *tinfo)
9accd112
MM
13857{
13858 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13859 struct remote_state *rs = get_remote_state ();
8d64371b
TT
13860 char *buf = rs->buf.data ();
13861 char *endbuf = buf + get_remote_packet_size ();
9accd112 13862
4082afcc 13863 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13864 error (_("Target does not support branch tracing."));
13865
13866 set_general_thread (tinfo->ptid);
13867
13868 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13869 putpkt (rs->buf);
8d64371b 13870 getpkt (&rs->buf, 0);
9accd112
MM
13871
13872 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13873 {
13874 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13875 error (_("Could not disable branch tracing for %s: %s"),
8d64371b 13876 target_pid_to_str (tinfo->ptid), &rs->buf[2]);
9accd112
MM
13877 else
13878 error (_("Could not disable branch tracing for %s."),
13879 target_pid_to_str (tinfo->ptid));
13880 }
13881
13882 xfree (tinfo);
13883}
13884
13885/* Teardown branch tracing. */
13886
f6ac5f3d
PA
13887void
13888remote_target::teardown_btrace (struct btrace_target_info *tinfo)
9accd112
MM
13889{
13890 /* We must not talk to the target during teardown. */
13891 xfree (tinfo);
13892}
13893
13894/* Read the branch trace. */
13895
f6ac5f3d
PA
13896enum btrace_error
13897remote_target::read_btrace (struct btrace_data *btrace,
13898 struct btrace_target_info *tinfo,
13899 enum btrace_read_type type)
9accd112
MM
13900{
13901 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
9accd112 13902 const char *annex;
9accd112 13903
4082afcc 13904 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13905 error (_("Target does not support branch tracing."));
13906
13907#if !defined(HAVE_LIBEXPAT)
13908 error (_("Cannot process branch tracing result. XML parsing not supported."));
13909#endif
13910
13911 switch (type)
13912 {
864089d2 13913 case BTRACE_READ_ALL:
9accd112
MM
13914 annex = "all";
13915 break;
864089d2 13916 case BTRACE_READ_NEW:
9accd112
MM
13917 annex = "new";
13918 break;
969c39fb
MM
13919 case BTRACE_READ_DELTA:
13920 annex = "delta";
13921 break;
9accd112
MM
13922 default:
13923 internal_error (__FILE__, __LINE__,
13924 _("Bad branch tracing read type: %u."),
13925 (unsigned int) type);
13926 }
13927
9018be22 13928 gdb::optional<gdb::char_vector> xml
8b88a78e 13929 = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE, annex);
9018be22 13930 if (!xml)
969c39fb 13931 return BTRACE_ERR_UNKNOWN;
9accd112 13932
9018be22 13933 parse_xml_btrace (btrace, xml->data ());
9accd112 13934
969c39fb 13935 return BTRACE_ERR_NONE;
9accd112
MM
13936}
13937
f6ac5f3d
PA
13938const struct btrace_config *
13939remote_target::btrace_conf (const struct btrace_target_info *tinfo)
f4abbc16
MM
13940{
13941 return &tinfo->conf;
13942}
13943
57810aa7 13944bool
f6ac5f3d 13945remote_target::augmented_libraries_svr4_read ()
ced63ec0 13946{
4082afcc
PA
13947 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13948 == PACKET_ENABLE);
ced63ec0
GB
13949}
13950
9dd130a0
TT
13951/* Implementation of to_load. */
13952
f6ac5f3d
PA
13953void
13954remote_target::load (const char *name, int from_tty)
9dd130a0
TT
13955{
13956 generic_load (name, from_tty);
13957}
13958
c78fa86a
GB
13959/* Accepts an integer PID; returns a string representing a file that
13960 can be opened on the remote side to get the symbols for the child
13961 process. Returns NULL if the operation is not supported. */
13962
f6ac5f3d
PA
13963char *
13964remote_target::pid_to_exec_file (int pid)
c78fa86a 13965{
9018be22 13966 static gdb::optional<gdb::char_vector> filename;
835205d0
GB
13967 struct inferior *inf;
13968 char *annex = NULL;
c78fa86a
GB
13969
13970 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13971 return NULL;
13972
835205d0
GB
13973 inf = find_inferior_pid (pid);
13974 if (inf == NULL)
13975 internal_error (__FILE__, __LINE__,
13976 _("not currently attached to process %d"), pid);
13977
13978 if (!inf->fake_pid_p)
13979 {
13980 const int annex_size = 9;
13981
224c3ddb 13982 annex = (char *) alloca (annex_size);
835205d0
GB
13983 xsnprintf (annex, annex_size, "%x", pid);
13984 }
13985
8b88a78e 13986 filename = target_read_stralloc (current_top_target (),
c78fa86a
GB
13987 TARGET_OBJECT_EXEC_FILE, annex);
13988
9018be22 13989 return filename ? filename->data () : nullptr;
c78fa86a
GB
13990}
13991
750ce8d1
YQ
13992/* Implement the to_can_do_single_step target_ops method. */
13993
f6ac5f3d
PA
13994int
13995remote_target::can_do_single_step ()
750ce8d1
YQ
13996{
13997 /* We can only tell whether target supports single step or not by
13998 supported s and S vCont actions if the stub supports vContSupported
13999 feature. If the stub doesn't support vContSupported feature,
14000 we have conservatively to think target doesn't supports single
14001 step. */
14002 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14003 {
14004 struct remote_state *rs = get_remote_state ();
14005
14006 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 14007 remote_vcont_probe ();
750ce8d1
YQ
14008
14009 return rs->supports_vCont.s && rs->supports_vCont.S;
14010 }
14011 else
14012 return 0;
14013}
14014
3a00c802
PA
14015/* Implementation of the to_execution_direction method for the remote
14016 target. */
14017
f6ac5f3d
PA
14018enum exec_direction_kind
14019remote_target::execution_direction ()
3a00c802
PA
14020{
14021 struct remote_state *rs = get_remote_state ();
14022
14023 return rs->last_resume_exec_dir;
14024}
14025
f6327dcb
KB
14026/* Return pointer to the thread_info struct which corresponds to
14027 THREAD_HANDLE (having length HANDLE_LEN). */
14028
f6ac5f3d
PA
14029thread_info *
14030remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14031 int handle_len,
14032 inferior *inf)
f6327dcb 14033{
08036331 14034 for (thread_info *tp : all_non_exited_threads ())
f6327dcb 14035 {
7aabaf9d 14036 remote_thread_info *priv = get_remote_thread_info (tp);
f6327dcb
KB
14037
14038 if (tp->inf == inf && priv != NULL)
14039 {
7aabaf9d 14040 if (handle_len != priv->thread_handle.size ())
f6327dcb 14041 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
7aabaf9d
SM
14042 handle_len, priv->thread_handle.size ());
14043 if (memcmp (thread_handle, priv->thread_handle.data (),
f6327dcb
KB
14044 handle_len) == 0)
14045 return tp;
14046 }
14047 }
14048
14049 return NULL;
14050}
14051
57810aa7 14052bool
f6ac5f3d 14053remote_target::can_async_p ()
6426a772 14054{
5d93a237
TT
14055 struct remote_state *rs = get_remote_state ();
14056
3015c064
SM
14057 /* We don't go async if the user has explicitly prevented it with the
14058 "maint set target-async" command. */
c6ebd6cf 14059 if (!target_async_permitted)
57810aa7 14060 return false;
75c99385 14061
23860348 14062 /* We're async whenever the serial device is. */
5d93a237 14063 return serial_can_async_p (rs->remote_desc);
6426a772
JM
14064}
14065
57810aa7 14066bool
f6ac5f3d 14067remote_target::is_async_p ()
6426a772 14068{
5d93a237
TT
14069 struct remote_state *rs = get_remote_state ();
14070
c6ebd6cf 14071 if (!target_async_permitted)
75c99385 14072 /* We only enable async when the user specifically asks for it. */
57810aa7 14073 return false;
75c99385 14074
23860348 14075 /* We're async whenever the serial device is. */
5d93a237 14076 return serial_is_async_p (rs->remote_desc);
6426a772
JM
14077}
14078
2acceee2
JM
14079/* Pass the SERIAL event on and up to the client. One day this code
14080 will be able to delay notifying the client of an event until the
23860348 14081 point where an entire packet has been received. */
2acceee2 14082
2acceee2
JM
14083static serial_event_ftype remote_async_serial_handler;
14084
6426a772 14085static void
819cc324 14086remote_async_serial_handler (struct serial *scb, void *context)
6426a772 14087{
2acceee2
JM
14088 /* Don't propogate error information up to the client. Instead let
14089 the client find out about the error by querying the target. */
6a3753b3 14090 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
14091}
14092
74531fed
PA
14093static void
14094remote_async_inferior_event_handler (gdb_client_data data)
14095{
6b8edb51 14096 inferior_event_handler (INF_REG_EVENT, data);
74531fed
PA
14097}
14098
f6ac5f3d
PA
14099void
14100remote_target::async (int enable)
2acceee2 14101{
5d93a237
TT
14102 struct remote_state *rs = get_remote_state ();
14103
6a3753b3 14104 if (enable)
2acceee2 14105 {
88b496c3 14106 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
14107
14108 /* If there are pending events in the stop reply queue tell the
14109 event loop to process them. */
953edf2b 14110 if (!rs->stop_reply_queue.empty ())
6b8edb51 14111 mark_async_event_handler (rs->remote_async_inferior_event_token);
6efcd9a8
PA
14112 /* For simplicity, below we clear the pending events token
14113 without remembering whether it is marked, so here we always
14114 mark it. If there's actually no pending notification to
14115 process, this ends up being a no-op (other than a spurious
14116 event-loop wakeup). */
14117 if (target_is_non_stop_p ())
14118 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
14119 }
14120 else
b7d2e916
PA
14121 {
14122 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
14123 /* If the core is disabling async, it doesn't want to be
14124 disturbed with target events. Clear all async event sources
14125 too. */
6b8edb51 14126 clear_async_event_handler (rs->remote_async_inferior_event_token);
6efcd9a8
PA
14127 if (target_is_non_stop_p ())
14128 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 14129 }
6426a772
JM
14130}
14131
65706a29
PA
14132/* Implementation of the to_thread_events method. */
14133
f6ac5f3d
PA
14134void
14135remote_target::thread_events (int enable)
65706a29
PA
14136{
14137 struct remote_state *rs = get_remote_state ();
14138 size_t size = get_remote_packet_size ();
65706a29
PA
14139
14140 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14141 return;
14142
8d64371b 14143 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
65706a29 14144 putpkt (rs->buf);
8d64371b 14145 getpkt (&rs->buf, 0);
65706a29
PA
14146
14147 switch (packet_ok (rs->buf,
14148 &remote_protocol_packets[PACKET_QThreadEvents]))
14149 {
14150 case PACKET_OK:
8d64371b
TT
14151 if (strcmp (rs->buf.data (), "OK") != 0)
14152 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
65706a29
PA
14153 break;
14154 case PACKET_ERROR:
8d64371b 14155 warning (_("Remote failure reply: %s"), rs->buf.data ());
65706a29
PA
14156 break;
14157 case PACKET_UNKNOWN:
14158 break;
14159 }
14160}
14161
5a2468f5 14162static void
981a3fb3 14163set_remote_cmd (const char *args, int from_tty)
5a2468f5 14164{
635c7e8a 14165 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
14166}
14167
d471ea57 14168static void
981a3fb3 14169show_remote_cmd (const char *args, int from_tty)
d471ea57 14170{
37a105a1 14171 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 14172 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1 14173 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 14174 struct ui_out *uiout = current_uiout;
37a105a1 14175
2e783024 14176 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
37a105a1
DJ
14177 for (; list != NULL; list = list->next)
14178 if (strcmp (list->name, "Z-packet") == 0)
14179 continue;
427c3a89
DJ
14180 else if (list->type == not_set_cmd)
14181 /* Alias commands are exactly like the original, except they
14182 don't have the normal type. */
14183 continue;
14184 else
37a105a1 14185 {
2e783024 14186 ui_out_emit_tuple option_emitter (uiout, "option");
a744cf53 14187
112e8700
SM
14188 uiout->field_string ("name", list->name);
14189 uiout->text (": ");
427c3a89 14190 if (list->type == show_cmd)
f5c4fcd9 14191 do_show_command (NULL, from_tty, list);
427c3a89
DJ
14192 else
14193 cmd_func (list, NULL, from_tty);
37a105a1 14194 }
d471ea57 14195}
5a2468f5 14196
0f71a2f6 14197
23860348 14198/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
14199static void
14200remote_new_objfile (struct objfile *objfile)
14201{
6b8edb51 14202 remote_target *remote = get_current_remote_target ();
5d93a237 14203
6b8edb51
PA
14204 if (remote != NULL) /* Have a remote connection. */
14205 remote->remote_check_symbols ();
dc8acb97
MS
14206}
14207
00bf0b85
SS
14208/* Pull all the tracepoints defined on the target and create local
14209 data structures representing them. We don't want to create real
14210 tracepoints yet, we don't want to mess up the user's existing
14211 collection. */
14212
f6ac5f3d
PA
14213int
14214remote_target::upload_tracepoints (struct uploaded_tp **utpp)
d5551862 14215{
00bf0b85
SS
14216 struct remote_state *rs = get_remote_state ();
14217 char *p;
d5551862 14218
00bf0b85
SS
14219 /* Ask for a first packet of tracepoint definition. */
14220 putpkt ("qTfP");
8d64371b
TT
14221 getpkt (&rs->buf, 0);
14222 p = rs->buf.data ();
00bf0b85 14223 while (*p && *p != 'l')
d5551862 14224 {
00bf0b85
SS
14225 parse_tracepoint_definition (p, utpp);
14226 /* Ask for another packet of tracepoint definition. */
14227 putpkt ("qTsP");
8d64371b
TT
14228 getpkt (&rs->buf, 0);
14229 p = rs->buf.data ();
d5551862 14230 }
00bf0b85 14231 return 0;
d5551862
SS
14232}
14233
f6ac5f3d
PA
14234int
14235remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
d5551862 14236{
00bf0b85 14237 struct remote_state *rs = get_remote_state ();
d5551862 14238 char *p;
d5551862 14239
00bf0b85
SS
14240 /* Ask for a first packet of variable definition. */
14241 putpkt ("qTfV");
8d64371b
TT
14242 getpkt (&rs->buf, 0);
14243 p = rs->buf.data ();
00bf0b85 14244 while (*p && *p != 'l')
d5551862 14245 {
00bf0b85
SS
14246 parse_tsv_definition (p, utsvp);
14247 /* Ask for another packet of variable definition. */
14248 putpkt ("qTsV");
8d64371b
TT
14249 getpkt (&rs->buf, 0);
14250 p = rs->buf.data ();
d5551862 14251 }
00bf0b85 14252 return 0;
d5551862
SS
14253}
14254
c1e36e3e
PA
14255/* The "set/show range-stepping" show hook. */
14256
14257static void
14258show_range_stepping (struct ui_file *file, int from_tty,
14259 struct cmd_list_element *c,
14260 const char *value)
14261{
14262 fprintf_filtered (file,
14263 _("Debugger's willingness to use range stepping "
14264 "is %s.\n"), value);
14265}
14266
6b8edb51
PA
14267/* Return true if the vCont;r action is supported by the remote
14268 stub. */
14269
14270bool
14271remote_target::vcont_r_supported ()
14272{
14273 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14274 remote_vcont_probe ();
14275
14276 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14277 && get_remote_state ()->supports_vCont.r);
14278}
14279
c1e36e3e
PA
14280/* The "set/show range-stepping" set hook. */
14281
14282static void
eb4c3f4a 14283set_range_stepping (const char *ignore_args, int from_tty,
c1e36e3e
PA
14284 struct cmd_list_element *c)
14285{
6b8edb51
PA
14286 /* When enabling, check whether range stepping is actually supported
14287 by the target, and warn if not. */
c1e36e3e
PA
14288 if (use_range_stepping)
14289 {
6b8edb51
PA
14290 remote_target *remote = get_current_remote_target ();
14291 if (remote == NULL
14292 || !remote->vcont_r_supported ())
14293 warning (_("Range stepping is not supported by the current target"));
c1e36e3e
PA
14294 }
14295}
14296
c906108c 14297void
fba45db2 14298_initialize_remote (void)
c906108c 14299{
9a7071a8 14300 struct cmd_list_element *cmd;
6f937416 14301 const char *cmd_name;
ea9c271d 14302
0f71a2f6 14303 /* architecture specific data */
29709017
DJ
14304 remote_g_packet_data_handle =
14305 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 14306
94585166
DB
14307 remote_pspace_data
14308 = register_program_space_data_with_cleanup (NULL,
14309 remote_pspace_data_cleanup);
14310
d9f719f1
PA
14311 add_target (remote_target_info, remote_target::open);
14312 add_target (extended_remote_target_info, extended_remote_target::open);
cce74817 14313
dc8acb97 14314 /* Hook into new objfile notification. */
76727919 14315 gdb::observers::new_objfile.attach (remote_new_objfile);
dc8acb97 14316
c906108c
SS
14317#if 0
14318 init_remote_threadtests ();
14319#endif
14320
23860348 14321 /* set/show remote ... */
d471ea57 14322
1bedd215 14323 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
14324Remote protocol specific variables\n\
14325Configure various remote-protocol specific variables such as\n\
1bedd215 14326the packets being used"),
cff3e48b 14327 &remote_set_cmdlist, "set remote ",
23860348 14328 0 /* allow-unknown */, &setlist);
1bedd215 14329 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
14330Remote protocol specific variables\n\
14331Configure various remote-protocol specific variables such as\n\
1bedd215 14332the packets being used"),
cff3e48b 14333 &remote_show_cmdlist, "show remote ",
23860348 14334 0 /* allow-unknown */, &showlist);
5a2468f5 14335
1a966eab
AC
14336 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14337Compare section data on target to the exec file.\n\
95cf3b38
DT
14338Argument is a single section name (default: all loaded sections).\n\
14339To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
14340 &cmdlist);
14341
1a966eab
AC
14342 add_cmd ("packet", class_maintenance, packet_command, _("\
14343Send an arbitrary packet to a remote target.\n\
c906108c
SS
14344 maintenance packet TEXT\n\
14345If GDB is talking to an inferior via the GDB serial protocol, then\n\
14346this command sends the string TEXT to the inferior, and displays the\n\
14347response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 14348terminating `#' character and checksum."),
c906108c
SS
14349 &maintenancelist);
14350
7915a72c
AC
14351 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14352Set whether to send break if interrupted."), _("\
14353Show whether to send break if interrupted."), _("\
14354If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 14355 set_remotebreak, show_remotebreak,
e707bbc2 14356 &setlist, &showlist);
9a7071a8
JB
14357 cmd_name = "remotebreak";
14358 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14359 deprecate_cmd (cmd, "set remote interrupt-sequence");
14360 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14361 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14362 deprecate_cmd (cmd, "show remote interrupt-sequence");
14363
14364 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
14365 interrupt_sequence_modes, &interrupt_sequence_mode,
14366 _("\
9a7071a8
JB
14367Set interrupt sequence to remote target."), _("\
14368Show interrupt sequence to remote target."), _("\
14369Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14370 NULL, show_interrupt_sequence,
14371 &remote_set_cmdlist,
14372 &remote_show_cmdlist);
14373
14374 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14375 &interrupt_on_connect, _("\
14376Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14377Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14378If set, interrupt sequence is sent to remote target."),
14379 NULL, NULL,
14380 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 14381
23860348 14382 /* Install commands for configuring memory read/write packets. */
11cf8741 14383
1a966eab
AC
14384 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14385Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 14386 &setlist);
1a966eab
AC
14387 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14388Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
14389 &showlist);
14390 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
14391 set_memory_write_packet_size, _("\
14392Set the maximum number of bytes per memory-write packet.\n\
14393Specify the number of bytes in a packet or 0 (zero) for the\n\
14394default packet size. The actual limit is further reduced\n\
14395dependent on the target. Specify ``fixed'' to disable the\n\
14396further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14397 &remote_set_cmdlist);
14398 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
14399 set_memory_read_packet_size, _("\
14400Set the maximum number of bytes per memory-read packet.\n\
14401Specify the number of bytes in a packet or 0 (zero) for the\n\
14402default packet size. The actual limit is further reduced\n\
14403dependent on the target. Specify ``fixed'' to disable the\n\
14404further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14405 &remote_set_cmdlist);
14406 add_cmd ("memory-write-packet-size", no_class,
14407 show_memory_write_packet_size,
1a966eab 14408 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
14409 &remote_show_cmdlist);
14410 add_cmd ("memory-read-packet-size", no_class,
14411 show_memory_read_packet_size,
1a966eab 14412 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 14413 &remote_show_cmdlist);
c906108c 14414
055303e2 14415 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
14416 &remote_hw_watchpoint_limit, _("\
14417Set the maximum number of target hardware watchpoints."), _("\
14418Show the maximum number of target hardware watchpoints."), _("\
055303e2
AB
14419Specify \"unlimited\" for unlimited hardware watchpoints."),
14420 NULL, show_hardware_watchpoint_limit,
14421 &remote_set_cmdlist,
14422 &remote_show_cmdlist);
14423 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
14424 no_class,
480a3f21
PW
14425 &remote_hw_watchpoint_length_limit, _("\
14426Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14427Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
055303e2
AB
14428Specify \"unlimited\" to allow watchpoints of unlimited size."),
14429 NULL, show_hardware_watchpoint_length_limit,
480a3f21 14430 &remote_set_cmdlist, &remote_show_cmdlist);
055303e2 14431 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
14432 &remote_hw_breakpoint_limit, _("\
14433Set the maximum number of target hardware breakpoints."), _("\
14434Show the maximum number of target hardware breakpoints."), _("\
055303e2
AB
14435Specify \"unlimited\" for unlimited hardware breakpoints."),
14436 NULL, show_hardware_breakpoint_limit,
b3f42336 14437 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 14438
1b493192
PA
14439 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14440 &remote_address_size, _("\
4d28ad1e
AC
14441Set the maximum size of the address (in bits) in a memory packet."), _("\
14442Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
14443 NULL,
14444 NULL, /* FIXME: i18n: */
14445 &setlist, &showlist);
c906108c 14446
ca4f7f8b
PA
14447 init_all_packet_configs ();
14448
444abaca 14449 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 14450 "X", "binary-download", 1);
0f71a2f6 14451
444abaca 14452 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 14453 "vCont", "verbose-resume", 0);
506fb367 14454
89be2091
DJ
14455 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14456 "QPassSignals", "pass-signals", 0);
14457
82075af2
JS
14458 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14459 "QCatchSyscalls", "catch-syscalls", 0);
14460
9b224c5e
PA
14461 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14462 "QProgramSignals", "program-signals", 0);
14463
bc3b087d
SDJ
14464 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14465 "QSetWorkingDir", "set-working-dir", 0);
14466
aefd8b33
SDJ
14467 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14468 "QStartupWithShell", "startup-with-shell", 0);
14469
0a2dde4a
SDJ
14470 add_packet_config_cmd (&remote_protocol_packets
14471 [PACKET_QEnvironmentHexEncoded],
14472 "QEnvironmentHexEncoded", "environment-hex-encoded",
14473 0);
14474
14475 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14476 "QEnvironmentReset", "environment-reset",
14477 0);
14478
14479 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14480 "QEnvironmentUnset", "environment-unset",
14481 0);
14482
444abaca 14483 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 14484 "qSymbol", "symbol-lookup", 0);
dc8acb97 14485
444abaca 14486 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 14487 "P", "set-register", 1);
d471ea57 14488
444abaca 14489 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 14490 "p", "fetch-register", 1);
b96ec7ac 14491
444abaca 14492 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 14493 "Z0", "software-breakpoint", 0);
d471ea57 14494
444abaca 14495 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 14496 "Z1", "hardware-breakpoint", 0);
d471ea57 14497
444abaca 14498 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 14499 "Z2", "write-watchpoint", 0);
d471ea57 14500
444abaca 14501 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 14502 "Z3", "read-watchpoint", 0);
d471ea57 14503
444abaca 14504 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 14505 "Z4", "access-watchpoint", 0);
d471ea57 14506
0876f84a
DJ
14507 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14508 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 14509
c78fa86a
GB
14510 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14511 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14512
23181151
DJ
14513 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14514 "qXfer:features:read", "target-features", 0);
14515
cfa9d6d9
DJ
14516 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14517 "qXfer:libraries:read", "library-info", 0);
14518
2268b414
JK
14519 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14520 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14521
fd79ecee
DJ
14522 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14523 "qXfer:memory-map:read", "memory-map", 0);
14524
0e7f50da
UW
14525 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14526 "qXfer:spu:read", "read-spu-object", 0);
14527
14528 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14529 "qXfer:spu:write", "write-spu-object", 0);
14530
07e059b5
VP
14531 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14532 "qXfer:osdata:read", "osdata", 0);
14533
dc146f7c
VP
14534 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14535 "qXfer:threads:read", "threads", 0);
14536
4aa995e1
PA
14537 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14538 "qXfer:siginfo:read", "read-siginfo-object", 0);
14539
14540 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14541 "qXfer:siginfo:write", "write-siginfo-object", 0);
14542
b3b9301e
PA
14543 add_packet_config_cmd
14544 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 14545 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 14546
169081d0
TG
14547 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14548 "qXfer:uib:read", "unwind-info-block", 0);
14549
444abaca 14550 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 14551 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
14552 0);
14553
711e434b
PM
14554 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14555 "qGetTIBAddr", "get-thread-information-block-address",
14556 0);
14557
40ab02ce
MS
14558 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14559 "bc", "reverse-continue", 0);
14560
14561 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14562 "bs", "reverse-step", 0);
14563
be2a5f71
DJ
14564 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14565 "qSupported", "supported-packets", 0);
14566
08388c79
DE
14567 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14568 "qSearch:memory", "search-memory", 0);
14569
bd3eecc3
PA
14570 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14571 "qTStatus", "trace-status", 0);
14572
15a201c8
GB
14573 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14574 "vFile:setfs", "hostio-setfs", 0);
14575
a6b151f1
DJ
14576 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14577 "vFile:open", "hostio-open", 0);
14578
14579 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14580 "vFile:pread", "hostio-pread", 0);
14581
14582 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14583 "vFile:pwrite", "hostio-pwrite", 0);
14584
14585 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14586 "vFile:close", "hostio-close", 0);
14587
14588 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14589 "vFile:unlink", "hostio-unlink", 0);
14590
b9e7b9c3
UW
14591 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14592 "vFile:readlink", "hostio-readlink", 0);
14593
0a93529c
GB
14594 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14595 "vFile:fstat", "hostio-fstat", 0);
14596
2d717e4f
DJ
14597 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14598 "vAttach", "attach", 0);
14599
14600 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14601 "vRun", "run", 0);
14602
a6f3e723
SL
14603 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14604 "QStartNoAckMode", "noack", 0);
14605
82f73884
PA
14606 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14607 "vKill", "kill", 0);
14608
0b16c5cf
PA
14609 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14610 "qAttached", "query-attached", 0);
14611
782b2b07 14612 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
14613 "ConditionalTracepoints",
14614 "conditional-tracepoints", 0);
3788aec7
LM
14615
14616 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14617 "ConditionalBreakpoints",
14618 "conditional-breakpoints", 0);
14619
d3ce09f5
SS
14620 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14621 "BreakpointCommands",
14622 "breakpoint-commands", 0);
14623
7a697b8d
SS
14624 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14625 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 14626
409873ef
SS
14627 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14628 "TracepointSource", "TracepointSource", 0);
14629
d914c394
SS
14630 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14631 "QAllow", "allow", 0);
14632
0fb4aa4b
PA
14633 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14634 "StaticTracepoints", "static-tracepoints", 0);
14635
1e4d1764
YQ
14636 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14637 "InstallInTrace", "install-in-trace", 0);
14638
0fb4aa4b
PA
14639 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14640 "qXfer:statictrace:read", "read-sdata-object", 0);
14641
78d85199
YQ
14642 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14643 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14644
03583c20
UW
14645 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14646 "QDisableRandomization", "disable-randomization", 0);
14647
d1feda86
YQ
14648 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14649 "QAgent", "agent", 0);
14650
f6f899bf
HAQ
14651 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14652 "QTBuffer:size", "trace-buffer-size", 0);
14653
9accd112
MM
14654 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14655 "Qbtrace:off", "disable-btrace", 0);
14656
14657 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
14658 "Qbtrace:bts", "enable-btrace-bts", 0);
14659
14660 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14661 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
14662
14663 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14664 "qXfer:btrace", "read-btrace", 0);
14665
f4abbc16
MM
14666 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14667 "qXfer:btrace-conf", "read-btrace-conf", 0);
14668
d33501a5
MM
14669 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14670 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14671
73b8c1fd
PA
14672 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14673 "multiprocess-feature", "multiprocess-feature", 0);
14674
f7e6eed5
PA
14675 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14676 "swbreak-feature", "swbreak-feature", 0);
14677
14678 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14679 "hwbreak-feature", "hwbreak-feature", 0);
14680
89245bc0
DB
14681 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14682 "fork-event-feature", "fork-event-feature", 0);
14683
14684 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14685 "vfork-event-feature", "vfork-event-feature", 0);
14686
b20a6524
MM
14687 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14688 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14689
750ce8d1
YQ
14690 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14691 "vContSupported", "verbose-resume-supported", 0);
14692
94585166
DB
14693 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14694 "exec-event-feature", "exec-event-feature", 0);
14695
de979965
PA
14696 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14697 "vCtrlC", "ctrl-c", 0);
14698
65706a29
PA
14699 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14700 "QThreadEvents", "thread-events", 0);
14701
f2faf941
PA
14702 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14703 "N stop reply", "no-resumed-stop-reply", 0);
14704
0b736949
DB
14705 /* Assert that we've registered "set remote foo-packet" commands
14706 for all packet configs. */
ca4f7f8b
PA
14707 {
14708 int i;
14709
14710 for (i = 0; i < PACKET_MAX; i++)
14711 {
14712 /* Ideally all configs would have a command associated. Some
14713 still don't though. */
14714 int excepted;
14715
14716 switch (i)
14717 {
14718 case PACKET_QNonStop:
ca4f7f8b
PA
14719 case PACKET_EnableDisableTracepoints_feature:
14720 case PACKET_tracenz_feature:
14721 case PACKET_DisconnectedTracing_feature:
14722 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
14723 case PACKET_qCRC:
14724 /* Additions to this list need to be well justified:
14725 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
14726 excepted = 1;
14727 break;
14728 default:
14729 excepted = 0;
14730 break;
14731 }
14732
14733 /* This catches both forgetting to add a config command, and
14734 forgetting to remove a packet from the exception list. */
14735 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14736 }
14737 }
14738
37a105a1
DJ
14739 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14740 Z sub-packet has its own set and show commands, but users may
14741 have sets to this variable in their .gdbinit files (or in their
14742 documentation). */
e9e68a56 14743 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
14744 &remote_Z_packet_detect, _("\
14745Set use of remote protocol `Z' packets"), _("\
14746Show use of remote protocol `Z' packets "), _("\
3b64bf98 14747When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 14748packets."),
e9e68a56 14749 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
14750 show_remote_protocol_Z_packet_cmd,
14751 /* FIXME: i18n: Use of remote protocol
14752 `Z' packets is %s. */
e9e68a56 14753 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 14754
a6b151f1
DJ
14755 add_prefix_cmd ("remote", class_files, remote_command, _("\
14756Manipulate files on the remote system\n\
14757Transfer files to and from the remote target system."),
14758 &remote_cmdlist, "remote ",
14759 0 /* allow-unknown */, &cmdlist);
14760
14761 add_cmd ("put", class_files, remote_put_command,
14762 _("Copy a local file to the remote system."),
14763 &remote_cmdlist);
14764
14765 add_cmd ("get", class_files, remote_get_command,
14766 _("Copy a remote file to the local system."),
14767 &remote_cmdlist);
14768
14769 add_cmd ("delete", class_files, remote_delete_command,
14770 _("Delete a remote file."),
14771 &remote_cmdlist);
14772
2d717e4f 14773 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 14774 &remote_exec_file_var, _("\
2d717e4f 14775Set the remote pathname for \"run\""), _("\
94585166
DB
14776Show the remote pathname for \"run\""), NULL,
14777 set_remote_exec_file,
14778 show_remote_exec_file,
14779 &remote_set_cmdlist,
14780 &remote_show_cmdlist);
2d717e4f 14781
c1e36e3e
PA
14782 add_setshow_boolean_cmd ("range-stepping", class_run,
14783 &use_range_stepping, _("\
14784Enable or disable range stepping."), _("\
14785Show whether target-assisted range stepping is enabled."), _("\
14786If on, and the target supports it, when stepping a source line, GDB\n\
14787tells the target to step the corresponding range of addresses itself instead\n\
14788of issuing multiple single-steps. This speeds up source level\n\
14789stepping. If off, GDB always issues single-steps, even if range\n\
14790stepping is supported by the target. The default is on."),
14791 set_range_stepping,
14792 show_range_stepping,
14793 &setlist,
14794 &showlist);
14795
449092f6
CV
14796 /* Eventually initialize fileio. See fileio.c */
14797 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 14798
ba348170 14799 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 14800 special ptids with it set to != 0. */
fd79271b
TT
14801 magic_null_ptid = ptid_t (42000, -1, 1);
14802 not_sent_ptid = ptid_t (42000, -2, 1);
14803 any_thread_ptid = ptid_t (42000, 0, 1);
c906108c 14804}
This page took 5.056052 seconds and 4 git commands to generate.