GDBserver: Don't assume a current process in D;PID implementation (PR gdb/23377)
[deliverable/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
e2882c85 3 Copyright (C) 1988-2018 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"
c5aa993b 30/*#include "terminal.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"
614c279d 45#include "filestuff.h"
9c3d6531 46#include "rsp-low.h"
6b940e6a 47#include "disasm.h"
f00aae0f 48#include "location.h"
c906108c 49
438e1e42 50#include "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"
d1feda86 71#include "agent.h"
9accd112 72#include "btrace.h"
c0272db5 73#include "record-btrace.h"
325fac50 74#include <algorithm>
2ec845e7 75#include "common/scoped_restore.h"
0a2dde4a 76#include "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.
248 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
249 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
250 packets. */
251 char *buf;
252 long buf_size;
253
254 /* True if we're going through initial connection setup (finding out
255 about the remote side's threads, relocating symbols, etc.). */
256 bool starting_up = false;
257
258 /* If we negotiated packet size explicitly (and thus can bypass
259 heuristics for the largest packet size that will not overflow
260 a buffer in the stub), this will be set to that packet size.
261 Otherwise zero, meaning to use the guessed size. */
262 long explicit_packet_size = 0;
263
264 /* remote_wait is normally called when the target is running and
265 waits for a stop reply packet. But sometimes we need to call it
266 when the target is already stopped. We can send a "?" packet
267 and have remote_wait read the response. Or, if we already have
268 the response, we can stash it in BUF and tell remote_wait to
269 skip calling getpkt. This flag is set when BUF contains a
270 stop reply packet and the target is not waiting. */
271 int cached_wait_status = 0;
272
273 /* True, if in no ack mode. That is, neither GDB nor the stub will
274 expect acks from each other. The connection is assumed to be
275 reliable. */
276 bool noack_mode = false;
277
278 /* True if we're connected in extended remote mode. */
279 bool extended = false;
280
281 /* True if we resumed the target and we're waiting for the target to
282 stop. In the mean time, we can't start another command/query.
283 The remote server wouldn't be ready to process it, so we'd
284 timeout waiting for a reply that would never come and eventually
285 we'd close the connection. This can happen in asynchronous mode
286 because we allow GDB commands while the target is running. */
287 bool waiting_for_stop_reply = false;
288
289 /* The status of the stub support for the various vCont actions. */
290 vCont_action_support supports_vCont;
291
292 /* True if the user has pressed Ctrl-C, but the target hasn't
293 responded to that. */
294 bool ctrlc_pending_p = false;
295
296 /* True if we saw a Ctrl-C while reading or writing from/to the
297 remote descriptor. At that point it is not safe to send a remote
298 interrupt packet, so we instead remember we saw the Ctrl-C and
299 process it once we're done with sending/receiving the current
300 packet, which should be shortly. If however that takes too long,
301 and the user presses Ctrl-C again, we offer to disconnect. */
302 bool got_ctrlc_during_io = false;
303
304 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
305 remote_open knows that we don't have a file open when the program
306 starts. */
307 struct serial *remote_desc = nullptr;
308
309 /* These are the threads which we last sent to the remote system. The
310 TID member will be -1 for all or -2 for not sent yet. */
311 ptid_t general_thread = null_ptid;
312 ptid_t continue_thread = null_ptid;
313
314 /* This is the traceframe which we last selected on the remote system.
315 It will be -1 if no traceframe is selected. */
316 int remote_traceframe_number = -1;
317
318 char *last_pass_packet = nullptr;
319
320 /* The last QProgramSignals packet sent to the target. We bypass
321 sending a new program signals list down to the target if the new
322 packet is exactly the same as the last we sent. IOW, we only let
323 the target know about program signals list changes. */
324 char *last_program_signals_packet = nullptr;
325
326 gdb_signal last_sent_signal = GDB_SIGNAL_0;
327
328 bool last_sent_step = false;
329
330 /* The execution direction of the last resume we got. */
331 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
332
333 char *finished_object = nullptr;
334 char *finished_annex = nullptr;
335 ULONGEST finished_offset = 0;
336
337 /* Should we try the 'ThreadInfo' query packet?
338
339 This variable (NOT available to the user: auto-detect only!)
340 determines whether GDB will use the new, simpler "ThreadInfo"
341 query or the older, more complex syntax for thread queries.
342 This is an auto-detect variable (set to true at each connect,
343 and set to false when the target fails to recognize it). */
344 bool use_threadinfo_query = false;
345 bool use_threadextra_query = false;
346
347 threadref echo_nextthread {};
348 threadref nextthread {};
349 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
350
351 /* The state of remote notification. */
352 struct remote_notif_state *notif_state = nullptr;
353
354 /* The branch trace configuration. */
355 struct btrace_config btrace_config {};
356
357 /* The argument to the last "vFile:setfs:" packet we sent, used
358 to avoid sending repeated unnecessary "vFile:setfs:" packets.
359 Initialized to -1 to indicate that no "vFile:setfs:" packet
360 has yet been sent. */
361 int fs_pid = -1;
362
363 /* A readahead cache for vFile:pread. Often, reading a binary
364 involves a sequence of small reads. E.g., when parsing an ELF
365 file. A readahead cache helps mostly the case of remote
366 debugging on a connection with higher latency, due to the
367 request/reply nature of the RSP. We only cache data for a single
368 file descriptor at a time. */
369 struct readahead_cache readahead_cache;
370
371 /* The list of already fetched and acknowledged stop events. This
372 queue is used for notification Stop, and other notifications
373 don't need queue for their events, because the notification
374 events of Stop can't be consumed immediately, so that events
375 should be queued first, and be consumed by remote_wait_{ns,as}
376 one per time. Other notifications can consume their events
377 immediately, so queue is not needed for them. */
953edf2b 378 std::vector<stop_reply_up> stop_reply_queue;
3c69da40
PA
379
380 /* Asynchronous signal handle registered as event loop source for
381 when we have pending events ready to be passed to the core. */
382 struct async_event_handler *remote_async_inferior_event_token = nullptr;
383
384 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
385 ``forever'' still use the normal timeout mechanism. This is
386 currently used by the ASYNC code to guarentee that target reads
387 during the initial connect always time-out. Once getpkt has been
388 modified to return a timeout indication and, in turn
389 remote_wait()/wait_for_inferior() have gained a timeout parameter
390 this can go away. */
391 int wait_forever_enabled_p = 1;
392
393private:
394 /* Mapping of remote protocol data for each gdbarch. Usually there
395 is only one entry here, though we may see more with stubs that
396 support multi-process. */
397 std::unordered_map<struct gdbarch *, remote_arch_state>
398 m_arch_states;
399};
6b8edb51 400
d9f719f1
PA
401static const target_info remote_target_info = {
402 "remote",
403 N_("Remote serial target in gdb-specific protocol"),
404 remote_doc
405};
406
f6ac5f3d
PA
407class remote_target : public target_ops
408{
409public:
410 remote_target ()
411 {
412 to_stratum = process_stratum;
413 }
6b8edb51 414 ~remote_target () override;
f6ac5f3d 415
d9f719f1
PA
416 const target_info &info () const override
417 { return remote_target_info; }
f6ac5f3d
PA
418
419 thread_control_capabilities get_thread_control_capabilities () override
420 { return tc_schedlock; }
421
d9f719f1
PA
422 /* Open a remote connection. */
423 static void open (const char *, int);
424
f6ac5f3d
PA
425 void close () override;
426
427 void detach (inferior *, int) override;
428 void disconnect (const char *, int) override;
429
430 void commit_resume () override;
431 void resume (ptid_t, int, enum gdb_signal) override;
432 ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
433
434 void fetch_registers (struct regcache *, int) override;
435 void store_registers (struct regcache *, int) override;
436 void prepare_to_store (struct regcache *) override;
437
438 void files_info () override;
439
440 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
441
442 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
443 enum remove_bp_reason) override;
444
445
57810aa7
PA
446 bool stopped_by_sw_breakpoint () override;
447 bool supports_stopped_by_sw_breakpoint () override;
f6ac5f3d 448
57810aa7 449 bool stopped_by_hw_breakpoint () override;
f6ac5f3d 450
57810aa7 451 bool supports_stopped_by_hw_breakpoint () override;
f6ac5f3d 452
57810aa7 453 bool stopped_by_watchpoint () override;
f6ac5f3d 454
57810aa7 455 bool stopped_data_address (CORE_ADDR *) override;
f6ac5f3d 456
57810aa7 457 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
f6ac5f3d
PA
458
459 int can_use_hw_breakpoint (enum bptype, int, int) override;
460
461 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
462
463 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
464
465 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
466
467 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
468 struct expression *) override;
469
470 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
471 struct expression *) override;
472
473 void kill () override;
474
475 void load (const char *, int) override;
476
477 void mourn_inferior () override;
478
479 void pass_signals (int, unsigned char *) override;
480
481 int set_syscall_catchpoint (int, bool, int,
482 gdb::array_view<const int>) override;
483
484 void program_signals (int, unsigned char *) override;
485
57810aa7 486 bool thread_alive (ptid_t ptid) override;
f6ac5f3d
PA
487
488 const char *thread_name (struct thread_info *) override;
489
490 void update_thread_list () override;
491
492 const char *pid_to_str (ptid_t) override;
493
494 const char *extra_thread_info (struct thread_info *) override;
495
496 ptid_t get_ada_task_ptid (long lwp, long thread) override;
497
498 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
499 int handle_len,
500 inferior *inf) override;
501
502 void stop (ptid_t) override;
503
504 void interrupt () override;
505
506 void pass_ctrlc () override;
507
508 enum target_xfer_status xfer_partial (enum target_object object,
509 const char *annex,
510 gdb_byte *readbuf,
511 const gdb_byte *writebuf,
512 ULONGEST offset, ULONGEST len,
513 ULONGEST *xfered_len) override;
514
515 ULONGEST get_memory_xfer_limit () override;
516
517 void rcmd (const char *command, struct ui_file *output) override;
518
519 char *pid_to_exec_file (int pid) override;
520
521 void log_command (const char *cmd) override
522 {
523 serial_log_command (this, cmd);
524 }
525
526 CORE_ADDR get_thread_local_address (ptid_t ptid,
527 CORE_ADDR load_module_addr,
528 CORE_ADDR offset) override;
529
57810aa7
PA
530 bool has_all_memory () override { return default_child_has_all_memory (); }
531 bool has_memory () override { return default_child_has_memory (); }
532 bool has_stack () override { return default_child_has_stack (); }
533 bool has_registers () override { return default_child_has_registers (); }
534 bool has_execution (ptid_t ptid) override { return default_child_has_execution (ptid); }
f6ac5f3d 535
57810aa7 536 bool can_execute_reverse () override;
f6ac5f3d
PA
537
538 std::vector<mem_region> memory_map () override;
539
540 void flash_erase (ULONGEST address, LONGEST length) override;
541
542 void flash_done () override;
543
544 const struct target_desc *read_description () override;
545
546 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
547 const gdb_byte *pattern, ULONGEST pattern_len,
548 CORE_ADDR *found_addrp) override;
549
57810aa7 550 bool can_async_p () override;
f6ac5f3d 551
57810aa7 552 bool is_async_p () override;
f6ac5f3d
PA
553
554 void async (int) override;
555
556 void thread_events (int) override;
557
558 int can_do_single_step () override;
559
560 void terminal_inferior () override;
561
562 void terminal_ours () override;
563
57810aa7 564 bool supports_non_stop () override;
f6ac5f3d 565
57810aa7 566 bool supports_multi_process () override;
f6ac5f3d 567
57810aa7 568 bool supports_disable_randomization () override;
f6ac5f3d 569
57810aa7 570 bool filesystem_is_local () override;
f6ac5f3d
PA
571
572
573 int fileio_open (struct inferior *inf, const char *filename,
574 int flags, int mode, int warn_if_slow,
575 int *target_errno) override;
576
577 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
578 ULONGEST offset, int *target_errno) override;
579
580 int fileio_pread (int fd, gdb_byte *read_buf, int len,
581 ULONGEST offset, int *target_errno) override;
582
583 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
584
585 int fileio_close (int fd, int *target_errno) override;
586
587 int fileio_unlink (struct inferior *inf,
588 const char *filename,
589 int *target_errno) override;
590
591 gdb::optional<std::string>
592 fileio_readlink (struct inferior *inf,
593 const char *filename,
594 int *target_errno) override;
595
57810aa7 596 bool supports_enable_disable_tracepoint () override;
f6ac5f3d 597
57810aa7 598 bool supports_string_tracing () override;
f6ac5f3d 599
57810aa7 600 bool supports_evaluation_of_breakpoint_conditions () override;
f6ac5f3d 601
57810aa7 602 bool can_run_breakpoint_commands () override;
f6ac5f3d
PA
603
604 void trace_init () override;
605
606 void download_tracepoint (struct bp_location *location) override;
607
57810aa7 608 bool can_download_tracepoint () override;
f6ac5f3d
PA
609
610 void download_trace_state_variable (const trace_state_variable &tsv) override;
611
612 void enable_tracepoint (struct bp_location *location) override;
613
614 void disable_tracepoint (struct bp_location *location) override;
615
616 void trace_set_readonly_regions () override;
617
618 void trace_start () override;
619
620 int get_trace_status (struct trace_status *ts) override;
621
622 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
623 override;
624
625 void trace_stop () override;
626
627 int trace_find (enum trace_find_type type, int num,
628 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
629
57810aa7 630 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
f6ac5f3d
PA
631
632 int save_trace_data (const char *filename) override;
633
634 int upload_tracepoints (struct uploaded_tp **utpp) override;
635
636 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
637
638 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
639
640 int get_min_fast_tracepoint_insn_len () override;
641
642 void set_disconnected_tracing (int val) override;
643
644 void set_circular_trace_buffer (int val) override;
645
646 void set_trace_buffer_size (LONGEST val) override;
647
57810aa7
PA
648 bool set_trace_notes (const char *user, const char *notes,
649 const char *stopnotes) override;
f6ac5f3d
PA
650
651 int core_of_thread (ptid_t ptid) override;
652
653 int verify_memory (const gdb_byte *data,
654 CORE_ADDR memaddr, ULONGEST size) override;
655
656
57810aa7 657 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
f6ac5f3d
PA
658
659 void set_permissions () override;
660
661 bool static_tracepoint_marker_at (CORE_ADDR,
662 struct static_tracepoint_marker *marker)
663 override;
664
665 std::vector<static_tracepoint_marker>
666 static_tracepoint_markers_by_strid (const char *id) override;
667
668 traceframe_info_up traceframe_info () override;
669
57810aa7
PA
670 bool use_agent (bool use) override;
671 bool can_use_agent () override;
f6ac5f3d
PA
672
673 struct btrace_target_info *enable_btrace (ptid_t ptid,
674 const struct btrace_config *conf) override;
675
676 void disable_btrace (struct btrace_target_info *tinfo) override;
677
678 void teardown_btrace (struct btrace_target_info *tinfo) override;
679
680 enum btrace_error read_btrace (struct btrace_data *data,
681 struct btrace_target_info *btinfo,
682 enum btrace_read_type type) override;
683
684 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
57810aa7 685 bool augmented_libraries_svr4_read () override;
f6ac5f3d
PA
686 int follow_fork (int, int) override;
687 void follow_exec (struct inferior *, char *) override;
688 int insert_fork_catchpoint (int) override;
689 int remove_fork_catchpoint (int) override;
690 int insert_vfork_catchpoint (int) override;
691 int remove_vfork_catchpoint (int) override;
692 int insert_exec_catchpoint (int) override;
693 int remove_exec_catchpoint (int) override;
694 enum exec_direction_kind execution_direction () override;
695
6b8edb51
PA
696public: /* Remote specific methods. */
697
698 void remote_download_command_source (int num, ULONGEST addr,
699 struct command_line *cmds);
700
701 void remote_file_put (const char *local_file, const char *remote_file,
702 int from_tty);
703 void remote_file_get (const char *remote_file, const char *local_file,
704 int from_tty);
705 void remote_file_delete (const char *remote_file, int from_tty);
706
707 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
708 ULONGEST offset, int *remote_errno);
709 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
710 ULONGEST offset, int *remote_errno);
711 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
712 ULONGEST offset, int *remote_errno);
713
714 int remote_hostio_send_command (int command_bytes, int which_packet,
715 int *remote_errno, char **attachment,
716 int *attachment_len);
717 int remote_hostio_set_filesystem (struct inferior *inf,
718 int *remote_errno);
719 /* We should get rid of this and use fileio_open directly. */
720 int remote_hostio_open (struct inferior *inf, const char *filename,
721 int flags, int mode, int warn_if_slow,
722 int *remote_errno);
723 int remote_hostio_close (int fd, int *remote_errno);
724
725 int remote_hostio_unlink (inferior *inf, const char *filename,
726 int *remote_errno);
727
728 struct remote_state *get_remote_state ();
729
730 long get_remote_packet_size (void);
731 long get_memory_packet_size (struct memory_packet_config *config);
732
733 long get_memory_write_packet_size ();
734 long get_memory_read_packet_size ();
735
736 char *append_pending_thread_resumptions (char *p, char *endp,
737 ptid_t ptid);
d9f719f1 738 static void open_1 (const char *name, int from_tty, int extended_p);
f6ac5f3d 739 void start_remote (int from_tty, int extended_p);
00431a78 740 void remote_detach_1 (struct inferior *inf, int from_tty);
6b8edb51
PA
741
742 char *append_resumption (char *p, char *endp,
743 ptid_t ptid, int step, gdb_signal siggnal);
744 int remote_resume_with_vcont (ptid_t ptid, int step,
745 gdb_signal siggnal);
746
747 void add_current_inferior_and_thread (char *wait_status);
748
749 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
750 int options);
751 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
752 int options);
753
754 ptid_t process_stop_reply (struct stop_reply *stop_reply,
755 target_waitstatus *status);
756
757 void remote_notice_new_inferior (ptid_t currthread, int executing);
758
759 void process_initial_stop_replies (int from_tty);
760
00431a78 761 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing);
6b8edb51
PA
762
763 void btrace_sync_conf (const btrace_config *conf);
764
765 void remote_btrace_maybe_reopen ();
766
767 void remove_new_fork_children (threads_listing_context *context);
768 void kill_new_fork_children (int pid);
769 void discard_pending_stop_replies (struct inferior *inf);
770 int stop_reply_queue_length ();
771
772 void check_pending_events_prevent_wildcard_vcont
773 (int *may_global_wildcard_vcont);
774
775 void discard_pending_stop_replies_in_queue ();
776 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
777 struct stop_reply *queued_stop_reply (ptid_t ptid);
778 int peek_stop_reply (ptid_t ptid);
779 void remote_parse_stop_reply (char *buf, stop_reply *event);
780
781 void remote_stop_ns (ptid_t ptid);
782 void remote_interrupt_as ();
783 void remote_interrupt_ns ();
784
785 char *remote_get_noisy_reply ();
786 int remote_query_attached (int pid);
787 inferior *remote_add_inferior (int fake_pid_p, int pid, int attached,
788 int try_open_exec);
789
790 ptid_t remote_current_thread (ptid_t oldpid);
791 ptid_t get_current_thread (char *wait_status);
792
793 void set_thread (ptid_t ptid, int gen);
794 void set_general_thread (ptid_t ptid);
795 void set_continue_thread (ptid_t ptid);
796 void set_general_process ();
797
798 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
799
800 int remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
801 gdb_ext_thread_info *info);
802 int remote_get_threadinfo (threadref *threadid, int fieldset,
803 gdb_ext_thread_info *info);
804
805 int parse_threadlist_response (char *pkt, int result_limit,
806 threadref *original_echo,
807 threadref *resultlist,
808 int *doneflag);
809 int remote_get_threadlist (int startflag, threadref *nextthread,
810 int result_limit, int *done, int *result_count,
811 threadref *threadlist);
812
813 int remote_threadlist_iterator (rmt_thread_action stepfunction,
814 void *context, int looplimit);
815
816 int remote_get_threads_with_ql (threads_listing_context *context);
817 int remote_get_threads_with_qxfer (threads_listing_context *context);
818 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
819
820 void extended_remote_restart ();
821
822 void get_offsets ();
823
824 void remote_check_symbols ();
825
826 void remote_supported_packet (const struct protocol_feature *feature,
827 enum packet_support support,
828 const char *argument);
829
830 void remote_query_supported ();
831
832 void remote_packet_size (const protocol_feature *feature,
833 packet_support support, const char *value);
834
835 void remote_serial_quit_handler ();
836
837 void remote_detach_pid (int pid);
838
839 void remote_vcont_probe ();
840
841 void remote_resume_with_hc (ptid_t ptid, int step,
842 gdb_signal siggnal);
843
844 void send_interrupt_sequence ();
845 void interrupt_query ();
846
847 void remote_notif_get_pending_events (notif_client *nc);
848
849 int fetch_register_using_p (struct regcache *regcache,
850 packet_reg *reg);
851 int send_g_packet ();
852 void process_g_packet (struct regcache *regcache);
853 void fetch_registers_using_g (struct regcache *regcache);
854 int store_register_using_P (const struct regcache *regcache,
855 packet_reg *reg);
856 void store_registers_using_G (const struct regcache *regcache);
857
858 void set_remote_traceframe ();
859
860 void check_binary_download (CORE_ADDR addr);
861
862 target_xfer_status remote_write_bytes_aux (const char *header,
863 CORE_ADDR memaddr,
864 const gdb_byte *myaddr,
865 ULONGEST len_units,
866 int unit_size,
867 ULONGEST *xfered_len_units,
868 char packet_format,
869 int use_length);
870
871 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
872 const gdb_byte *myaddr, ULONGEST len,
873 int unit_size, ULONGEST *xfered_len);
874
875 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
876 ULONGEST len_units,
877 int unit_size, ULONGEST *xfered_len_units);
878
879 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
880 ULONGEST memaddr,
881 ULONGEST len,
882 int unit_size,
883 ULONGEST *xfered_len);
884
885 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
886 gdb_byte *myaddr, ULONGEST len,
887 int unit_size,
888 ULONGEST *xfered_len);
889
890 packet_result remote_send_printf (const char *format, ...)
891 ATTRIBUTE_PRINTF (2, 3);
892
893 target_xfer_status remote_flash_write (ULONGEST address,
894 ULONGEST length, ULONGEST *xfered_len,
895 const gdb_byte *data);
896
897 int readchar (int timeout);
898
899 void remote_serial_write (const char *str, int len);
900
901 int putpkt (const char *buf);
902 int putpkt_binary (const char *buf, int cnt);
903
904 void skip_frame ();
905 long read_frame (char **buf_p, long *sizeof_buf);
906 void getpkt (char **buf, long *sizeof_buf, int forever);
907 int getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
908 int expecting_notif, int *is_notif);
909 int getpkt_sane (char **buf, long *sizeof_buf, int forever);
910 int getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
911 int *is_notif);
912 int remote_vkill (int pid);
913 void remote_kill_k ();
914
915 void extended_remote_disable_randomization (int val);
916 int extended_remote_run (const std::string &args);
917
918 void send_environment_packet (const char *action,
919 const char *packet,
920 const char *value);
921
922 void extended_remote_environment_support ();
3c69da40 923 void extended_remote_set_inferior_cwd ();
80152258 924
3c69da40
PA
925 target_xfer_status remote_write_qxfer (const char *object_name,
926 const char *annex,
927 const gdb_byte *writebuf,
928 ULONGEST offset, LONGEST len,
929 ULONGEST *xfered_len,
930 struct packet_config *packet);
43c3a0e4 931
3c69da40
PA
932 target_xfer_status remote_read_qxfer (const char *object_name,
933 const char *annex,
934 gdb_byte *readbuf, ULONGEST offset,
935 LONGEST len,
936 ULONGEST *xfered_len,
937 struct packet_config *packet);
43c3a0e4 938
3c69da40 939 void push_stop_reply (struct stop_reply *new_event);
43c3a0e4 940
3c69da40 941 bool vcont_r_supported ();
43c3a0e4 942
3c69da40 943 void packet_command (const char *args, int from_tty);
43c3a0e4 944
3c69da40 945private: /* data fields */
43c3a0e4 946
3c69da40
PA
947 /* The remote state. Don't reference this directly. Use the
948 get_remote_state method instead. */
949 remote_state m_remote_state;
43c3a0e4
PA
950};
951
3c69da40
PA
952static const target_info extended_remote_target_info = {
953 "extended-remote",
954 N_("Extended remote serial target in gdb-specific protocol"),
955 remote_doc
956};
ea9c271d 957
3c69da40
PA
958/* Set up the extended remote target by extending the standard remote
959 target and adding to it. */
960
961class extended_remote_target final : public remote_target
ea9c271d 962{
9d6eea31 963public:
3c69da40
PA
964 const target_info &info () const override
965 { return extended_remote_target_info; }
9d6eea31 966
3c69da40
PA
967 /* Open an extended-remote connection. */
968 static void open (const char *, int);
de44f5a7 969
3c69da40
PA
970 bool can_create_inferior () override { return true; }
971 void create_inferior (const char *, const std::string &,
972 char **, int) override;
9d6eea31 973
3c69da40 974 void detach (inferior *, int) override;
9d6eea31 975
3c69da40
PA
976 bool can_attach () override { return true; }
977 void attach (const char *, int) override;
be2a5f71 978
3c69da40
PA
979 void post_attach (int) override;
980 bool supports_disable_randomization () override;
981};
1e51243a 982
3c69da40
PA
983/* Per-program-space data key. */
984static const struct program_space_data *remote_pspace_data;
2d717e4f 985
3c69da40
PA
986/* The variable registered as the control variable used by the
987 remote exec-file commands. While the remote exec-file setting is
988 per-program-space, the set/show machinery uses this as the
989 location of the remote exec-file value. */
990static char *remote_exec_file_var;
a6f3e723 991
3c69da40
PA
992/* The size to align memory write packets, when practical. The protocol
993 does not guarantee any alignment, and gdb will generate short
994 writes and unaligned writes, but even as a best-effort attempt this
995 can improve bulk transfers. For instance, if a write is misaligned
996 relative to the target's data bus, the stub may need to make an extra
997 round trip fetching data from the target. This doesn't make a
998 huge difference, but it's easy to do, so we try to be helpful.
82f73884 999
3c69da40
PA
1000 The alignment chosen is arbitrary; usually data bus width is
1001 important here, not the possibly larger cache line size. */
1002enum { REMOTE_ALIGN_WRITES = 16 };
82f73884 1003
3c69da40 1004/* Prototypes for local functions. */
74531fed 1005
3c69da40 1006static int hexnumlen (ULONGEST num);
782b2b07 1007
3c69da40 1008static int stubhex (int ch);
5d93a237 1009
3c69da40 1010static int hexnumstr (char *, ULONGEST);
048094ac 1011
3c69da40 1012static int hexnumnstr (char *, ULONGEST, int);
47f8a51d 1013
3c69da40 1014static CORE_ADDR remote_address_masked (CORE_ADDR);
262e1174 1015
3c69da40 1016static void print_packet (const char *);
747dc59d 1017
3c69da40 1018static int stub_unpack_int (char *buff, int fieldlength);
5e4a05c4 1019
3c69da40 1020struct packet_config;
b73be471 1021
3c69da40 1022static void show_packet_config_cmd (struct packet_config *config);
280ceea3 1023
3c69da40
PA
1024static void show_remote_protocol_packet_cmd (struct ui_file *file,
1025 int from_tty,
1026 struct cmd_list_element *c,
1027 const char *value);
8e88304f 1028
3c69da40 1029static ptid_t read_ptid (const char *buf, const char **obuf);
3a00c802 1030
3c69da40 1031static void remote_async_inferior_event_handler (gdb_client_data);
b80fafe3 1032
3c69da40 1033static int remote_read_description_p (struct target_ops *target);
88b496c3 1034
3c69da40 1035static void remote_console_output (char *msg);
5965e028 1036
3c69da40 1037static void remote_btrace_reset (remote_state *rs);
f4abbc16 1038
3c69da40 1039static void remote_unpush_and_throw (void);
15a201c8 1040
3c69da40 1041/* For "remote". */
80152258 1042
3c69da40 1043static struct cmd_list_element *remote_cmdlist;
9d6eea31 1044
3c69da40 1045/* For "set remote" and "show remote". */
6b8edb51 1046
3c69da40
PA
1047static struct cmd_list_element *remote_set_cmdlist;
1048static struct cmd_list_element *remote_show_cmdlist;
6b8edb51 1049
3c69da40 1050/* Controls whether GDB is willing to use range stepping. */
6b8edb51 1051
3c69da40
PA
1052static int use_range_stepping = 1;
1053
1054/* The max number of chars in debug output. The rest of chars are
1055 omitted. */
1056
1057#define REMOTE_DEBUG_MAX_CHAR 512
ea9c271d 1058
7aabaf9d
SM
1059/* Private data that we'll store in (struct thread_info)->priv. */
1060struct remote_thread_info : public private_thread_info
dc146f7c 1061{
7aabaf9d
SM
1062 std::string extra;
1063 std::string name;
1064 int core = -1;
799a2abe 1065
f6327dcb
KB
1066 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1067 sequence of bytes. */
7aabaf9d 1068 gdb::byte_vector thread_handle;
f6327dcb 1069
799a2abe 1070 /* Whether the target stopped for a breakpoint/watchpoint. */
7aabaf9d 1071 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
799a2abe
PA
1072
1073 /* This is set to the data address of the access causing the target
1074 to stop for a watchpoint. */
7aabaf9d 1075 CORE_ADDR watch_data_address = 0;
85ad3aaf
PA
1076
1077 /* Fields used by the vCont action coalescing implemented in
1078 remote_resume / remote_commit_resume. remote_resume stores each
1079 thread's last resume request in these fields, so that a later
1080 remote_commit_resume knows which is the proper action for this
1081 thread to include in the vCont packet. */
1082
1083 /* True if the last target_resume call for this thread was a step
1084 request, false if a continue request. */
7aabaf9d 1085 int last_resume_step = 0;
85ad3aaf
PA
1086
1087 /* The signal specified in the last target_resume call for this
1088 thread. */
7aabaf9d 1089 gdb_signal last_resume_sig = GDB_SIGNAL_0;
85ad3aaf
PA
1090
1091 /* Whether this thread was already vCont-resumed on the remote
1092 side. */
7aabaf9d 1093 int vcont_resumed = 0;
dc146f7c
VP
1094};
1095
de44f5a7
PA
1096remote_state::remote_state ()
1097{
1098 /* The default buffer size is unimportant; it will be expanded
1099 whenever a larger buffer is needed. */
1100 this->buf_size = 400;
1101 this->buf = (char *) xmalloc (this->buf_size);
1102}
1103
1104remote_state::~remote_state ()
1105{
1106 xfree (this->last_pass_packet);
1107 xfree (this->last_program_signals_packet);
1108 xfree (this->buf);
1109 xfree (this->finished_object);
1110 xfree (this->finished_annex);
cf792862
TT
1111}
1112
35b1e5cc
SS
1113/* Utility: generate error from an incoming stub packet. */
1114static void
1115trace_error (char *buf)
1116{
1117 if (*buf++ != 'E')
1118 return; /* not an error msg */
1119 switch (*buf)
1120 {
1121 case '1': /* malformed packet error */
1122 if (*++buf == '0') /* general case: */
1123 error (_("remote.c: error in outgoing packet."));
1124 else
1125 error (_("remote.c: error in outgoing packet at field #%ld."),
1126 strtol (buf, NULL, 16));
35b1e5cc
SS
1127 default:
1128 error (_("Target returns error code '%s'."), buf);
1129 }
1130}
1131
1132/* Utility: wait for reply from stub, while accepting "O" packets. */
b6bb3468 1133
6b8edb51
PA
1134char *
1135remote_target::remote_get_noisy_reply ()
35b1e5cc 1136{
b6bb3468
PA
1137 struct remote_state *rs = get_remote_state ();
1138
35b1e5cc
SS
1139 do /* Loop on reply from remote stub. */
1140 {
1141 char *buf;
a744cf53 1142
0df8b418 1143 QUIT; /* Allow user to bail out with ^C. */
b6bb3468
PA
1144 getpkt (&rs->buf, &rs->buf_size, 0);
1145 buf = rs->buf;
ad91cd99 1146 if (buf[0] == 'E')
35b1e5cc 1147 trace_error (buf);
61012eef 1148 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
1149 {
1150 ULONGEST ul;
1151 CORE_ADDR from, to, org_to;
256642e8 1152 const char *p, *pp;
dde08ee1 1153 int adjusted_size = 0;
7556d4a4 1154 int relocated = 0;
dde08ee1
PA
1155
1156 p = buf + strlen ("qRelocInsn:");
1157 pp = unpack_varlen_hex (p, &ul);
1158 if (*pp != ';')
cb91c06a 1159 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
1160 from = ul;
1161
1162 p = pp + 1;
a9cbf802 1163 unpack_varlen_hex (p, &ul);
dde08ee1
PA
1164 to = ul;
1165
1166 org_to = to;
1167
492d29ea 1168 TRY
dde08ee1 1169 {
f5656ead 1170 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 1171 relocated = 1;
dde08ee1 1172 }
492d29ea 1173 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
1174 {
1175 if (ex.error == MEMORY_ERROR)
1176 {
1177 /* Propagate memory errors silently back to the
1178 target. The stub may have limited the range of
1179 addresses we can write to, for example. */
1180 }
1181 else
1182 {
1183 /* Something unexpectedly bad happened. Be verbose
1184 so we can tell what, and propagate the error back
1185 to the stub, so it doesn't get stuck waiting for
1186 a response. */
1187 exception_fprintf (gdb_stderr, ex,
1188 _("warning: relocating instruction: "));
1189 }
1190 putpkt ("E01");
1191 }
492d29ea 1192 END_CATCH
7556d4a4
PA
1193
1194 if (relocated)
dde08ee1
PA
1195 {
1196 adjusted_size = to - org_to;
1197
b6bb3468 1198 xsnprintf (buf, rs->buf_size, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
1199 putpkt (buf);
1200 }
dde08ee1 1201 }
ad91cd99 1202 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
1203 remote_console_output (buf + 1); /* 'O' message from stub */
1204 else
0df8b418 1205 return buf; /* Here's the actual reply. */
35b1e5cc
SS
1206 }
1207 while (1);
1208}
3c3bea1c 1209
9d6eea31
PA
1210struct remote_arch_state *
1211remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
d01949b6 1212{
43c3a0e4
PA
1213 remote_arch_state *rsa;
1214
1215 auto it = this->m_arch_states.find (gdbarch);
1216 if (it == this->m_arch_states.end ())
9d6eea31 1217 {
43c3a0e4
PA
1218 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1219 std::forward_as_tuple (gdbarch),
1220 std::forward_as_tuple (gdbarch));
1221 rsa = &p.first->second;
9d6eea31
PA
1222
1223 /* Make sure that the packet buffer is plenty big enough for
1224 this architecture. */
1225 if (this->buf_size < rsa->remote_packet_size)
1226 {
1227 this->buf_size = 2 * rsa->remote_packet_size;
1228 this->buf = (char *) xrealloc (this->buf, this->buf_size);
1229 }
1230 }
43c3a0e4
PA
1231 else
1232 rsa = &it->second;
1233
1234 return rsa;
d01949b6
AC
1235}
1236
0b83947e
DJ
1237/* Fetch the global remote target state. */
1238
6b8edb51
PA
1239remote_state *
1240remote_target::get_remote_state ()
0b83947e
DJ
1241{
1242 /* Make sure that the remote architecture state has been
1243 initialized, because doing so might reallocate rs->buf. Any
1244 function which calls getpkt also needs to be mindful of changes
1245 to rs->buf, but this call limits the number of places which run
1246 into trouble. */
3c69da40 1247 m_remote_state.get_remote_arch_state (target_gdbarch ());
0b83947e 1248
3c69da40 1249 return &m_remote_state;
0b83947e
DJ
1250}
1251
94585166
DB
1252/* Cleanup routine for the remote module's pspace data. */
1253
1254static void
1255remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
1256{
19ba03f4 1257 char *remote_exec_file = (char *) arg;
94585166
DB
1258
1259 xfree (remote_exec_file);
1260}
1261
1262/* Fetch the remote exec-file from the current program space. */
1263
1264static const char *
1265get_remote_exec_file (void)
1266{
1267 char *remote_exec_file;
1268
19ba03f4
SM
1269 remote_exec_file
1270 = (char *) program_space_data (current_program_space,
1271 remote_pspace_data);
94585166
DB
1272 if (remote_exec_file == NULL)
1273 return "";
1274
1275 return remote_exec_file;
1276}
1277
1278/* Set the remote exec file for PSPACE. */
1279
1280static void
1281set_pspace_remote_exec_file (struct program_space *pspace,
1282 char *remote_exec_file)
1283{
19ba03f4 1284 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
94585166
DB
1285
1286 xfree (old_file);
1287 set_program_space_data (pspace, remote_pspace_data,
1288 xstrdup (remote_exec_file));
1289}
1290
1291/* The "set/show remote exec-file" set command hook. */
1292
1293static void
eb4c3f4a 1294set_remote_exec_file (const char *ignored, int from_tty,
94585166
DB
1295 struct cmd_list_element *c)
1296{
1297 gdb_assert (remote_exec_file_var != NULL);
1298 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
1299}
1300
1301/* The "set/show remote exec-file" show command hook. */
1302
1303static void
1304show_remote_exec_file (struct ui_file *file, int from_tty,
1305 struct cmd_list_element *cmd, const char *value)
1306{
1307 fprintf_filtered (file, "%s\n", remote_exec_file_var);
1308}
1309
74ca34ce
DJ
1310static int
1311compare_pnums (const void *lhs_, const void *rhs_)
1312{
19ba03f4
SM
1313 const struct packet_reg * const *lhs
1314 = (const struct packet_reg * const *) lhs_;
1315 const struct packet_reg * const *rhs
1316 = (const struct packet_reg * const *) rhs_;
74ca34ce
DJ
1317
1318 if ((*lhs)->pnum < (*rhs)->pnum)
1319 return -1;
1320 else if ((*lhs)->pnum == (*rhs)->pnum)
1321 return 0;
1322 else
1323 return 1;
1324}
1325
c21236dc
PA
1326static int
1327map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 1328{
74ca34ce 1329 int regnum, num_remote_regs, offset;
74ca34ce 1330 struct packet_reg **remote_regs;
ea9c271d 1331
4a22f64d 1332 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 1333 {
c21236dc 1334 struct packet_reg *r = &regs[regnum];
baef701f 1335
4a22f64d 1336 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
1337 /* Do not try to fetch zero-sized (placeholder) registers. */
1338 r->pnum = -1;
1339 else
1340 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1341
b323314b 1342 r->regnum = regnum;
74ca34ce
DJ
1343 }
1344
1345 /* Define the g/G packet format as the contents of each register
1346 with a remote protocol number, in order of ascending protocol
1347 number. */
1348
224c3ddb 1349 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 1350 for (num_remote_regs = 0, regnum = 0;
4a22f64d 1351 regnum < gdbarch_num_regs (gdbarch);
f57d151a 1352 regnum++)
c21236dc
PA
1353 if (regs[regnum].pnum != -1)
1354 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 1355
74ca34ce
DJ
1356 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
1357 compare_pnums);
1358
1359 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1360 {
1361 remote_regs[regnum]->in_g_packet = 1;
1362 remote_regs[regnum]->offset = offset;
4a22f64d 1363 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
1364 }
1365
c21236dc
PA
1366 return offset;
1367}
1368
1369/* Given the architecture described by GDBARCH, return the remote
1370 protocol register's number and the register's offset in the g/G
1371 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1372 If the target does not have a mapping for REGNUM, return false,
1373 otherwise, return true. */
1374
1375int
1376remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1377 int *pnum, int *poffset)
1378{
c21236dc
PA
1379 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1380
b80406ac 1381 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
c21236dc 1382
b80406ac 1383 map_regcache_remote_table (gdbarch, regs.data ());
c21236dc
PA
1384
1385 *pnum = regs[regnum].pnum;
1386 *poffset = regs[regnum].offset;
1387
c21236dc
PA
1388 return *pnum != -1;
1389}
1390
9d6eea31 1391remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
c21236dc 1392{
c21236dc
PA
1393 /* Use the architecture to build a regnum<->pnum table, which will be
1394 1:1 unless a feature set specifies otherwise. */
9d6eea31 1395 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
c21236dc 1396
74ca34ce
DJ
1397 /* Record the maximum possible size of the g packet - it may turn out
1398 to be smaller. */
9d6eea31
PA
1399 this->sizeof_g_packet
1400 = map_regcache_remote_table (gdbarch, this->regs.get ());
74ca34ce 1401
0df8b418 1402 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
1403 remote stubs have a hardwired buffer size of 400 bytes
1404 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1405 as the maximum packet-size to ensure that the packet and an extra
1406 NUL character can always fit in the buffer. This stops GDB
1407 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d 1408 already a full buffer (As of 1999-12-04 that was most stubs). */
9d6eea31 1409 this->remote_packet_size = 400 - 1;
d01949b6 1410
ea9c271d 1411 /* This one is filled in when a ``g'' packet is received. */
9d6eea31 1412 this->actual_register_packet_size = 0;
ea9c271d
DJ
1413
1414 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
1415 default, adjust the size accordingly. Remember that each byte is
1416 encoded as two characters. 32 is the overhead for the packet
1417 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 1418 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 1419 little. */
9d6eea31
PA
1420 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1421 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
ea9c271d
DJ
1422}
1423
6b8edb51
PA
1424/* Get a pointer to the current remote target. If not connected to a
1425 remote target, return NULL. */
1426
1427static remote_target *
1428get_current_remote_target ()
1429{
1430 target_ops *proc_target = find_target_at (process_stratum);
1431 return dynamic_cast<remote_target *> (proc_target);
1432}
1433
ea9c271d
DJ
1434/* Return the current allowed size of a remote packet. This is
1435 inferred from the current architecture, and should be used to
1436 limit the length of outgoing packets. */
6b8edb51
PA
1437long
1438remote_target::get_remote_packet_size ()
ea9c271d 1439{
be2a5f71 1440 struct remote_state *rs = get_remote_state ();
9d6eea31 1441 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
ea9c271d 1442
be2a5f71
DJ
1443 if (rs->explicit_packet_size)
1444 return rs->explicit_packet_size;
1445
ea9c271d 1446 return rsa->remote_packet_size;
d01949b6
AC
1447}
1448
ad10f812 1449static struct packet_reg *
5cd63fda
PA
1450packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1451 long regnum)
ad10f812 1452{
5cd63fda 1453 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
b323314b
AC
1454 return NULL;
1455 else
ad10f812 1456 {
ea9c271d 1457 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 1458
b323314b
AC
1459 gdb_assert (r->regnum == regnum);
1460 return r;
ad10f812 1461 }
ad10f812
AC
1462}
1463
1464static struct packet_reg *
5cd63fda
PA
1465packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1466 LONGEST pnum)
ad10f812 1467{
b323314b 1468 int i;
a744cf53 1469
5cd63fda 1470 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
ad10f812 1471 {
ea9c271d 1472 struct packet_reg *r = &rsa->regs[i];
a744cf53 1473
b323314b
AC
1474 if (r->pnum == pnum)
1475 return r;
ad10f812
AC
1476 }
1477 return NULL;
d01949b6
AC
1478}
1479
9a7071a8
JB
1480/* Allow the user to specify what sequence to send to the remote
1481 when he requests a program interruption: Although ^C is usually
1482 what remote systems expect (this is the default, here), it is
1483 sometimes preferable to send a break. On other systems such
1484 as the Linux kernel, a break followed by g, which is Magic SysRq g
1485 is required in order to interrupt the execution. */
1486const char interrupt_sequence_control_c[] = "Ctrl-C";
1487const char interrupt_sequence_break[] = "BREAK";
1488const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 1489static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
1490 {
1491 interrupt_sequence_control_c,
1492 interrupt_sequence_break,
1493 interrupt_sequence_break_g,
1494 NULL
1495 };
1496static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1497
1498static void
1499show_interrupt_sequence (struct ui_file *file, int from_tty,
1500 struct cmd_list_element *c,
1501 const char *value)
1502{
1503 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1504 fprintf_filtered (file,
1505 _("Send the ASCII ETX character (Ctrl-c) "
1506 "to the remote target to interrupt the "
1507 "execution of the program.\n"));
1508 else if (interrupt_sequence_mode == interrupt_sequence_break)
1509 fprintf_filtered (file,
1510 _("send a break signal to the remote target "
1511 "to interrupt the execution of the program.\n"));
1512 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1513 fprintf_filtered (file,
1514 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1515 "the remote target to interrupt the execution "
1516 "of Linux kernel.\n"));
1517 else
1518 internal_error (__FILE__, __LINE__,
1519 _("Invalid value for interrupt_sequence_mode: %s."),
1520 interrupt_sequence_mode);
1521}
6426a772 1522
9a7071a8
JB
1523/* This boolean variable specifies whether interrupt_sequence is sent
1524 to the remote target when gdb connects to it.
1525 This is mostly needed when you debug the Linux kernel: The Linux kernel
1526 expects BREAK g which is Magic SysRq g for connecting gdb. */
1527static int interrupt_on_connect = 0;
c906108c 1528
9a7071a8
JB
1529/* This variable is used to implement the "set/show remotebreak" commands.
1530 Since these commands are now deprecated in favor of "set/show remote
1531 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
1532static int remote_break;
1533
9a7071a8 1534static void
eb4c3f4a 1535set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
9a7071a8
JB
1536{
1537 if (remote_break)
1538 interrupt_sequence_mode = interrupt_sequence_break;
1539 else
1540 interrupt_sequence_mode = interrupt_sequence_control_c;
1541}
1542
1543static void
1544show_remotebreak (struct ui_file *file, int from_tty,
1545 struct cmd_list_element *c,
1546 const char *value)
1547{
1548}
1549
c906108c
SS
1550/* This variable sets the number of bits in an address that are to be
1551 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 1552 leading zeros, the entire address would be sent. This variable
c906108c
SS
1553 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1554 initial implementation of remote.c restricted the address sent in
1555 memory packets to ``host::sizeof long'' bytes - (typically 32
1556 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1557 address was never sent. Since fixing this bug may cause a break in
1558 some remote targets this variable is principly provided to
23860348 1559 facilitate backward compatibility. */
c906108c 1560
883b9c6c 1561static unsigned int remote_address_size;
c906108c 1562
11cf8741 1563\f
11cf8741 1564/* User configurable variables for the number of characters in a
ea9c271d
DJ
1565 memory read/write packet. MIN (rsa->remote_packet_size,
1566 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 1567 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
1568 (speed up transfers). The variables ``preferred_*'' (the user
1569 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 1570 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
1571
1572struct memory_packet_config
1573{
a121b7c1 1574 const char *name;
11cf8741
JM
1575 long size;
1576 int fixed_p;
1577};
1578
cc0be08f
PA
1579/* The default max memory-write-packet-size, when the setting is
1580 "fixed". The 16k is historical. (It came from older GDB's using
1581 alloca for buffers and the knowledge (folklore?) that some hosts
1582 don't cope very well with large alloca calls.) */
1583#define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
a5c0808e
PA
1584
1585/* The minimum remote packet size for memory transfers. Ensures we
1586 can write at least one byte. */
1587#define MIN_MEMORY_PACKET_SIZE 20
1588
cc0be08f
PA
1589/* Get the memory packet size, assuming it is fixed. */
1590
1591static long
1592get_fixed_memory_packet_size (struct memory_packet_config *config)
1593{
1594 gdb_assert (config->fixed_p);
1595
1596 if (config->size <= 0)
1597 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1598 else
1599 return config->size;
1600}
1601
11cf8741
JM
1602/* Compute the current size of a read/write packet. Since this makes
1603 use of ``actual_register_packet_size'' the computation is dynamic. */
1604
6b8edb51
PA
1605long
1606remote_target::get_memory_packet_size (struct memory_packet_config *config)
11cf8741 1607{
d01949b6 1608 struct remote_state *rs = get_remote_state ();
9d6eea31 1609 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
ea9c271d 1610
11cf8741
JM
1611 long what_they_get;
1612 if (config->fixed_p)
cc0be08f 1613 what_they_get = get_fixed_memory_packet_size (config);
11cf8741
JM
1614 else
1615 {
ea9c271d 1616 what_they_get = get_remote_packet_size ();
23860348 1617 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1618 if (config->size > 0
1619 && what_they_get > config->size)
1620 what_they_get = config->size;
be2a5f71
DJ
1621
1622 /* Limit it to the size of the targets ``g'' response unless we have
1623 permission from the stub to use a larger packet size. */
1624 if (rs->explicit_packet_size == 0
1625 && rsa->actual_register_packet_size > 0
1626 && what_they_get > rsa->actual_register_packet_size)
1627 what_they_get = rsa->actual_register_packet_size;
11cf8741 1628 }
a5c0808e
PA
1629 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1630 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1631
1632 /* Make sure there is room in the global buffer for this packet
1633 (including its trailing NUL byte). */
1634 if (rs->buf_size < what_they_get + 1)
1635 {
1636 rs->buf_size = 2 * what_they_get;
224c3ddb 1637 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
6d820c5c
DJ
1638 }
1639
11cf8741
JM
1640 return what_they_get;
1641}
1642
0df8b418 1643/* Update the size of a read/write packet. If they user wants
23860348 1644 something really big then do a sanity check. */
11cf8741
JM
1645
1646static void
ac88e2de 1647set_memory_packet_size (const char *args, struct memory_packet_config *config)
11cf8741
JM
1648{
1649 int fixed_p = config->fixed_p;
1650 long size = config->size;
a744cf53 1651
11cf8741 1652 if (args == NULL)
8a3fe4f8 1653 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1654 else if (strcmp (args, "hard") == 0
1655 || strcmp (args, "fixed") == 0)
1656 fixed_p = 1;
1657 else if (strcmp (args, "soft") == 0
1658 || strcmp (args, "limit") == 0)
1659 fixed_p = 0;
1660 else
1661 {
1662 char *end;
a744cf53 1663
11cf8741
JM
1664 size = strtoul (args, &end, 0);
1665 if (args == end)
8a3fe4f8 1666 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1667
1668 /* Instead of explicitly capping the size of a packet to or
1669 disallowing it, the user is allowed to set the size to
1670 something arbitrarily large. */
11cf8741 1671 }
a5c0808e 1672
23860348 1673 /* Extra checks? */
11cf8741
JM
1674 if (fixed_p && !config->fixed_p)
1675 {
cc0be08f
PA
1676 /* So that the query shows the correct value. */
1677 long query_size = (size <= 0
1678 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1679 : size);
1680
e2e0b3e5
AC
1681 if (! query (_("The target may not be able to correctly handle a %s\n"
1682 "of %ld bytes. Change the packet size? "),
cc0be08f 1683 config->name, query_size))
8a3fe4f8 1684 error (_("Packet size not changed."));
11cf8741 1685 }
23860348 1686 /* Update the config. */
11cf8741
JM
1687 config->fixed_p = fixed_p;
1688 config->size = size;
1689}
1690
1691static void
1692show_memory_packet_size (struct memory_packet_config *config)
1693{
cc0be08f
PA
1694 if (config->size == 0)
1695 printf_filtered (_("The %s is 0 (default). "), config->name);
1696 else
1697 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1698 if (config->fixed_p)
a3f17187 1699 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
cc0be08f 1700 get_fixed_memory_packet_size (config));
11cf8741 1701 else
cc0be08f 1702 {
6b8edb51 1703 remote_target *remote = get_current_remote_target ();
cc0be08f 1704
6b8edb51 1705 if (remote != NULL)
cc0be08f 1706 printf_filtered (_("Packets are limited to %ld bytes.\n"),
6b8edb51 1707 remote->get_memory_packet_size (config));
cc0be08f
PA
1708 else
1709 puts_filtered ("The actual limit will be further reduced "
1710 "dependent on the target.\n");
1711 }
11cf8741
JM
1712}
1713
1714static struct memory_packet_config memory_write_packet_config =
1715{
1716 "memory-write-packet-size",
1717};
1718
1719static void
ac88e2de 1720set_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1721{
1722 set_memory_packet_size (args, &memory_write_packet_config);
1723}
1724
1725static void
ac88e2de 1726show_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1727{
1728 show_memory_packet_size (&memory_write_packet_config);
1729}
1730
055303e2
AB
1731/* Show the number of hardware watchpoints that can be used. */
1732
1733static void
1734show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
1735 struct cmd_list_element *c,
1736 const char *value)
1737{
1738 fprintf_filtered (file, _("The maximum number of target hardware "
1739 "watchpoints is %s.\n"), value);
1740}
1741
1742/* Show the length limit (in bytes) for hardware watchpoints. */
1743
1744static void
1745show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
1746 struct cmd_list_element *c,
1747 const char *value)
1748{
1749 fprintf_filtered (file, _("The maximum length (in bytes) of a target "
1750 "hardware watchpoint is %s.\n"), value);
1751}
1752
1753/* Show the number of hardware breakpoints that can be used. */
1754
1755static void
1756show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
1757 struct cmd_list_element *c,
1758 const char *value)
1759{
1760 fprintf_filtered (file, _("The maximum number of target hardware "
1761 "breakpoints is %s.\n"), value);
1762}
1763
6b8edb51
PA
1764long
1765remote_target::get_memory_write_packet_size ()
11cf8741
JM
1766{
1767 return get_memory_packet_size (&memory_write_packet_config);
1768}
1769
1770static struct memory_packet_config memory_read_packet_config =
1771{
1772 "memory-read-packet-size",
1773};
1774
1775static void
ac88e2de 1776set_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1777{
1778 set_memory_packet_size (args, &memory_read_packet_config);
1779}
1780
1781static void
ac88e2de 1782show_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1783{
1784 show_memory_packet_size (&memory_read_packet_config);
1785}
1786
6b8edb51
PA
1787long
1788remote_target::get_memory_read_packet_size ()
11cf8741
JM
1789{
1790 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1791
11cf8741
JM
1792 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1793 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1794 increased beyond this. */
1795 if (size > get_remote_packet_size ())
1796 size = get_remote_packet_size ();
11cf8741
JM
1797 return size;
1798}
1799
11cf8741 1800\f
5a2468f5 1801
5a2468f5
JM
1802struct packet_config
1803 {
bb572ddd
DJ
1804 const char *name;
1805 const char *title;
4082afcc
PA
1806
1807 /* If auto, GDB auto-detects support for this packet or feature,
1808 either through qSupported, or by trying the packet and looking
1809 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1810 packet. If false, the packet is disabled. Configs that don't
1811 have an associated command always have this set to auto. */
7f19b9a2 1812 enum auto_boolean detect;
4082afcc
PA
1813
1814 /* Does the target support this packet? */
5a2468f5
JM
1815 enum packet_support support;
1816 };
1817
4082afcc
PA
1818static enum packet_support packet_config_support (struct packet_config *config);
1819static enum packet_support packet_support (int packet);
5a2468f5
JM
1820
1821static void
fba45db2 1822show_packet_config_cmd (struct packet_config *config)
5a2468f5 1823{
a121b7c1 1824 const char *support = "internal-error";
a744cf53 1825
4082afcc 1826 switch (packet_config_support (config))
5a2468f5
JM
1827 {
1828 case PACKET_ENABLE:
1829 support = "enabled";
1830 break;
1831 case PACKET_DISABLE:
1832 support = "disabled";
1833 break;
1834 case PACKET_SUPPORT_UNKNOWN:
1835 support = "unknown";
1836 break;
1837 }
1838 switch (config->detect)
1839 {
7f19b9a2 1840 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1841 printf_filtered (_("Support for the `%s' packet "
1842 "is auto-detected, currently %s.\n"),
37a105a1 1843 config->name, support);
5a2468f5 1844 break;
7f19b9a2
AC
1845 case AUTO_BOOLEAN_TRUE:
1846 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1847 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1848 config->name, support);
8e248173 1849 break;
5a2468f5
JM
1850 }
1851}
1852
1853static void
bb572ddd
DJ
1854add_packet_config_cmd (struct packet_config *config, const char *name,
1855 const char *title, int legacy)
d471ea57 1856{
5a2468f5
JM
1857 char *set_doc;
1858 char *show_doc;
d471ea57 1859 char *cmd_name;
3ed07be4 1860
5a2468f5
JM
1861 config->name = name;
1862 config->title = title;
b435e160
AC
1863 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1864 name, title);
3e43a32a
MS
1865 show_doc = xstrprintf ("Show current use of remote "
1866 "protocol `%s' (%s) packet",
b435e160 1867 name, title);
d471ea57 1868 /* set/show TITLE-packet {auto,on,off} */
b435e160 1869 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1870 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1871 &config->detect, set_doc,
1872 show_doc, NULL, /* help_doc */
4082afcc 1873 NULL,
bb572ddd
DJ
1874 show_remote_protocol_packet_cmd,
1875 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1876 /* The command code copies the documentation strings. */
1877 xfree (set_doc);
1878 xfree (show_doc);
23860348 1879 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1880 if (legacy)
1881 {
1882 char *legacy_name;
a744cf53 1883
b435e160 1884 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1885 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1886 &remote_set_cmdlist);
d471ea57 1887 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1888 &remote_show_cmdlist);
d471ea57 1889 }
5a2468f5
JM
1890}
1891
d471ea57 1892static enum packet_result
a76d924d 1893packet_check_result (const char *buf)
5a2468f5 1894{
d471ea57 1895 if (buf[0] != '\0')
5a2468f5 1896 {
d471ea57 1897 /* The stub recognized the packet request. Check that the
23860348 1898 operation succeeded. */
a76d924d
DJ
1899 if (buf[0] == 'E'
1900 && isxdigit (buf[1]) && isxdigit (buf[2])
1901 && buf[3] == '\0')
1902 /* "Enn" - definitly an error. */
1903 return PACKET_ERROR;
1904
1905 /* Always treat "E." as an error. This will be used for
1906 more verbose error messages, such as E.memtypes. */
1907 if (buf[0] == 'E' && buf[1] == '.')
1908 return PACKET_ERROR;
1909
1910 /* The packet may or may not be OK. Just assume it is. */
1911 return PACKET_OK;
1912 }
1913 else
1914 /* The stub does not support the packet. */
1915 return PACKET_UNKNOWN;
1916}
1917
1918static enum packet_result
1919packet_ok (const char *buf, struct packet_config *config)
1920{
1921 enum packet_result result;
1922
4082afcc
PA
1923 if (config->detect != AUTO_BOOLEAN_TRUE
1924 && config->support == PACKET_DISABLE)
1925 internal_error (__FILE__, __LINE__,
1926 _("packet_ok: attempt to use a disabled packet"));
1927
a76d924d
DJ
1928 result = packet_check_result (buf);
1929 switch (result)
1930 {
1931 case PACKET_OK:
1932 case PACKET_ERROR:
1933 /* The stub recognized the packet request. */
4082afcc 1934 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1935 {
d471ea57
AC
1936 if (remote_debug)
1937 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1938 "Packet %s (%s) is supported\n",
1939 config->name, config->title);
d471ea57 1940 config->support = PACKET_ENABLE;
d471ea57 1941 }
a76d924d
DJ
1942 break;
1943 case PACKET_UNKNOWN:
23860348 1944 /* The stub does not support the packet. */
4082afcc
PA
1945 if (config->detect == AUTO_BOOLEAN_AUTO
1946 && config->support == PACKET_ENABLE)
d471ea57 1947 {
4082afcc
PA
1948 /* If the stub previously indicated that the packet was
1949 supported then there is a protocol error. */
1950 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1951 config->name, config->title);
1952 }
1953 else if (config->detect == AUTO_BOOLEAN_TRUE)
1954 {
1955 /* The user set it wrong. */
1956 error (_("Enabled packet %s (%s) not recognized by stub"),
1957 config->name, config->title);
d471ea57 1958 }
4082afcc
PA
1959
1960 if (remote_debug)
1961 fprintf_unfiltered (gdb_stdlog,
1962 "Packet %s (%s) is NOT supported\n",
1963 config->name, config->title);
1964 config->support = PACKET_DISABLE;
a76d924d 1965 break;
5a2468f5 1966 }
a76d924d
DJ
1967
1968 return result;
5a2468f5
JM
1969}
1970
444abaca
DJ
1971enum {
1972 PACKET_vCont = 0,
1973 PACKET_X,
1974 PACKET_qSymbol,
1975 PACKET_P,
1976 PACKET_p,
1977 PACKET_Z0,
1978 PACKET_Z1,
1979 PACKET_Z2,
1980 PACKET_Z3,
1981 PACKET_Z4,
15a201c8 1982 PACKET_vFile_setfs,
a6b151f1
DJ
1983 PACKET_vFile_open,
1984 PACKET_vFile_pread,
1985 PACKET_vFile_pwrite,
1986 PACKET_vFile_close,
1987 PACKET_vFile_unlink,
b9e7b9c3 1988 PACKET_vFile_readlink,
0a93529c 1989 PACKET_vFile_fstat,
0876f84a 1990 PACKET_qXfer_auxv,
23181151 1991 PACKET_qXfer_features,
c78fa86a 1992 PACKET_qXfer_exec_file,
cfa9d6d9 1993 PACKET_qXfer_libraries,
2268b414 1994 PACKET_qXfer_libraries_svr4,
fd79ecee 1995 PACKET_qXfer_memory_map,
0e7f50da
UW
1996 PACKET_qXfer_spu_read,
1997 PACKET_qXfer_spu_write,
07e059b5 1998 PACKET_qXfer_osdata,
dc146f7c 1999 PACKET_qXfer_threads,
0fb4aa4b 2000 PACKET_qXfer_statictrace_read,
b3b9301e 2001 PACKET_qXfer_traceframe_info,
169081d0 2002 PACKET_qXfer_uib,
711e434b 2003 PACKET_qGetTIBAddr,
444abaca 2004 PACKET_qGetTLSAddr,
be2a5f71 2005 PACKET_qSupported,
bd3eecc3 2006 PACKET_qTStatus,
89be2091 2007 PACKET_QPassSignals,
82075af2 2008 PACKET_QCatchSyscalls,
9b224c5e 2009 PACKET_QProgramSignals,
bc3b087d 2010 PACKET_QSetWorkingDir,
aefd8b33 2011 PACKET_QStartupWithShell,
0a2dde4a
SDJ
2012 PACKET_QEnvironmentHexEncoded,
2013 PACKET_QEnvironmentReset,
2014 PACKET_QEnvironmentUnset,
936d2992 2015 PACKET_qCRC,
08388c79 2016 PACKET_qSearch_memory,
2d717e4f
DJ
2017 PACKET_vAttach,
2018 PACKET_vRun,
a6f3e723 2019 PACKET_QStartNoAckMode,
82f73884 2020 PACKET_vKill,
4aa995e1
PA
2021 PACKET_qXfer_siginfo_read,
2022 PACKET_qXfer_siginfo_write,
0b16c5cf 2023 PACKET_qAttached,
4082afcc
PA
2024
2025 /* Support for conditional tracepoints. */
782b2b07 2026 PACKET_ConditionalTracepoints,
4082afcc
PA
2027
2028 /* Support for target-side breakpoint conditions. */
3788aec7 2029 PACKET_ConditionalBreakpoints,
4082afcc
PA
2030
2031 /* Support for target-side breakpoint commands. */
d3ce09f5 2032 PACKET_BreakpointCommands,
4082afcc
PA
2033
2034 /* Support for fast tracepoints. */
7a697b8d 2035 PACKET_FastTracepoints,
4082afcc
PA
2036
2037 /* Support for static tracepoints. */
0fb4aa4b 2038 PACKET_StaticTracepoints,
4082afcc
PA
2039
2040 /* Support for installing tracepoints while a trace experiment is
2041 running. */
1e4d1764 2042 PACKET_InstallInTrace,
4082afcc 2043
40ab02ce
MS
2044 PACKET_bc,
2045 PACKET_bs,
409873ef 2046 PACKET_TracepointSource,
d914c394 2047 PACKET_QAllow,
78d85199 2048 PACKET_qXfer_fdpic,
03583c20 2049 PACKET_QDisableRandomization,
d1feda86 2050 PACKET_QAgent,
f6f899bf 2051 PACKET_QTBuffer_size,
9accd112
MM
2052 PACKET_Qbtrace_off,
2053 PACKET_Qbtrace_bts,
b20a6524 2054 PACKET_Qbtrace_pt,
9accd112 2055 PACKET_qXfer_btrace,
4082afcc
PA
2056
2057 /* Support for the QNonStop packet. */
2058 PACKET_QNonStop,
2059
65706a29
PA
2060 /* Support for the QThreadEvents packet. */
2061 PACKET_QThreadEvents,
2062
4082afcc
PA
2063 /* Support for multi-process extensions. */
2064 PACKET_multiprocess_feature,
2065
2066 /* Support for enabling and disabling tracepoints while a trace
2067 experiment is running. */
2068 PACKET_EnableDisableTracepoints_feature,
2069
2070 /* Support for collecting strings using the tracenz bytecode. */
2071 PACKET_tracenz_feature,
2072
2073 /* Support for continuing to run a trace experiment while GDB is
2074 disconnected. */
2075 PACKET_DisconnectedTracing_feature,
2076
2077 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2078 PACKET_augmented_libraries_svr4_read_feature,
2079
f4abbc16
MM
2080 /* Support for the qXfer:btrace-conf:read packet. */
2081 PACKET_qXfer_btrace_conf,
2082
d33501a5
MM
2083 /* Support for the Qbtrace-conf:bts:size packet. */
2084 PACKET_Qbtrace_conf_bts_size,
2085
f7e6eed5
PA
2086 /* Support for swbreak+ feature. */
2087 PACKET_swbreak_feature,
2088
2089 /* Support for hwbreak+ feature. */
2090 PACKET_hwbreak_feature,
2091
89245bc0
DB
2092 /* Support for fork events. */
2093 PACKET_fork_event_feature,
2094
2095 /* Support for vfork events. */
2096 PACKET_vfork_event_feature,
2097
b20a6524
MM
2098 /* Support for the Qbtrace-conf:pt:size packet. */
2099 PACKET_Qbtrace_conf_pt_size,
2100
94585166
DB
2101 /* Support for exec events. */
2102 PACKET_exec_event_feature,
2103
750ce8d1
YQ
2104 /* Support for query supported vCont actions. */
2105 PACKET_vContSupported,
2106
de979965
PA
2107 /* Support remote CTRL-C. */
2108 PACKET_vCtrlC,
2109
f2faf941
PA
2110 /* Support TARGET_WAITKIND_NO_RESUMED. */
2111 PACKET_no_resumed,
2112
444abaca
DJ
2113 PACKET_MAX
2114};
506fb367 2115
444abaca 2116static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 2117
f7e6eed5
PA
2118/* Returns the packet's corresponding "set remote foo-packet" command
2119 state. See struct packet_config for more details. */
2120
2121static enum auto_boolean
2122packet_set_cmd_state (int packet)
2123{
2124 return remote_protocol_packets[packet].detect;
2125}
2126
4082afcc
PA
2127/* Returns whether a given packet or feature is supported. This takes
2128 into account the state of the corresponding "set remote foo-packet"
2129 command, which may be used to bypass auto-detection. */
dc8acb97 2130
4082afcc
PA
2131static enum packet_support
2132packet_config_support (struct packet_config *config)
2133{
2134 switch (config->detect)
444abaca 2135 {
4082afcc
PA
2136 case AUTO_BOOLEAN_TRUE:
2137 return PACKET_ENABLE;
2138 case AUTO_BOOLEAN_FALSE:
2139 return PACKET_DISABLE;
2140 case AUTO_BOOLEAN_AUTO:
2141 return config->support;
2142 default:
2143 gdb_assert_not_reached (_("bad switch"));
444abaca 2144 }
4082afcc
PA
2145}
2146
2147/* Same as packet_config_support, but takes the packet's enum value as
2148 argument. */
2149
2150static enum packet_support
2151packet_support (int packet)
2152{
2153 struct packet_config *config = &remote_protocol_packets[packet];
2154
2155 return packet_config_support (config);
dc8acb97
MS
2156}
2157
5a2468f5 2158static void
444abaca
DJ
2159show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2160 struct cmd_list_element *c,
2161 const char *value)
5a2468f5 2162{
444abaca 2163 struct packet_config *packet;
5a2468f5 2164
444abaca
DJ
2165 for (packet = remote_protocol_packets;
2166 packet < &remote_protocol_packets[PACKET_MAX];
2167 packet++)
2168 {
2169 if (&packet->detect == c->var)
2170 {
2171 show_packet_config_cmd (packet);
2172 return;
2173 }
2174 }
9b20d036 2175 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 2176 c->name);
5a2468f5
JM
2177}
2178
d471ea57
AC
2179/* Should we try one of the 'Z' requests? */
2180
2181enum Z_packet_type
2182{
2183 Z_PACKET_SOFTWARE_BP,
2184 Z_PACKET_HARDWARE_BP,
2185 Z_PACKET_WRITE_WP,
2186 Z_PACKET_READ_WP,
2187 Z_PACKET_ACCESS_WP,
2188 NR_Z_PACKET_TYPES
2189};
96baa820 2190
d471ea57 2191/* For compatibility with older distributions. Provide a ``set remote
23860348 2192 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 2193
7f19b9a2 2194static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
2195
2196static void
eb4c3f4a 2197set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
fba45db2 2198 struct cmd_list_element *c)
96baa820 2199{
d471ea57 2200 int i;
a744cf53 2201
d471ea57 2202 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 2203 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
2204}
2205
2206static void
08546159
AC
2207show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2208 struct cmd_list_element *c,
2209 const char *value)
96baa820 2210{
d471ea57 2211 int i;
a744cf53 2212
d471ea57
AC
2213 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2214 {
444abaca 2215 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 2216 }
96baa820
JM
2217}
2218
4082afcc
PA
2219/* Returns true if the multi-process extensions are in effect. */
2220
2221static int
2222remote_multi_process_p (struct remote_state *rs)
2223{
2224 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2225}
2226
de0d863e
DB
2227/* Returns true if fork events are supported. */
2228
2229static int
2230remote_fork_event_p (struct remote_state *rs)
2231{
2232 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2233}
2234
c269dbdb
DB
2235/* Returns true if vfork events are supported. */
2236
2237static int
2238remote_vfork_event_p (struct remote_state *rs)
2239{
2240 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2241}
2242
d46addbb
DB
2243/* Returns true if exec events are supported. */
2244
2245static int
2246remote_exec_event_p (struct remote_state *rs)
2247{
2248 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2249}
2250
cbb8991c
DB
2251/* Insert fork catchpoint target routine. If fork events are enabled
2252 then return success, nothing more to do. */
2253
f6ac5f3d
PA
2254int
2255remote_target::insert_fork_catchpoint (int pid)
cbb8991c
DB
2256{
2257 struct remote_state *rs = get_remote_state ();
2258
2259 return !remote_fork_event_p (rs);
2260}
2261
2262/* Remove fork catchpoint target routine. Nothing to do, just
2263 return success. */
2264
f6ac5f3d
PA
2265int
2266remote_target::remove_fork_catchpoint (int pid)
cbb8991c
DB
2267{
2268 return 0;
2269}
2270
2271/* Insert vfork catchpoint target routine. If vfork events are enabled
2272 then return success, nothing more to do. */
2273
f6ac5f3d
PA
2274int
2275remote_target::insert_vfork_catchpoint (int pid)
cbb8991c
DB
2276{
2277 struct remote_state *rs = get_remote_state ();
2278
2279 return !remote_vfork_event_p (rs);
2280}
2281
2282/* Remove vfork catchpoint target routine. Nothing to do, just
2283 return success. */
2284
f6ac5f3d
PA
2285int
2286remote_target::remove_vfork_catchpoint (int pid)
cbb8991c
DB
2287{
2288 return 0;
2289}
2290
d46addbb
DB
2291/* Insert exec catchpoint target routine. If exec events are
2292 enabled, just return success. */
2293
f6ac5f3d
PA
2294int
2295remote_target::insert_exec_catchpoint (int pid)
d46addbb
DB
2296{
2297 struct remote_state *rs = get_remote_state ();
2298
2299 return !remote_exec_event_p (rs);
2300}
2301
2302/* Remove exec catchpoint target routine. Nothing to do, just
2303 return success. */
2304
f6ac5f3d
PA
2305int
2306remote_target::remove_exec_catchpoint (int pid)
d46addbb
DB
2307{
2308 return 0;
2309}
2310
c906108c
SS
2311\f
2312
79d7f229
PA
2313static ptid_t magic_null_ptid;
2314static ptid_t not_sent_ptid;
2315static ptid_t any_thread_ptid;
2316
0b16c5cf
PA
2317/* Find out if the stub attached to PID (and hence GDB should offer to
2318 detach instead of killing it when bailing out). */
2319
6b8edb51
PA
2320int
2321remote_target::remote_query_attached (int pid)
0b16c5cf
PA
2322{
2323 struct remote_state *rs = get_remote_state ();
bba74b36 2324 size_t size = get_remote_packet_size ();
0b16c5cf 2325
4082afcc 2326 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
2327 return 0;
2328
2329 if (remote_multi_process_p (rs))
bba74b36 2330 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 2331 else
bba74b36 2332 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
2333
2334 putpkt (rs->buf);
2335 getpkt (&rs->buf, &rs->buf_size, 0);
2336
2337 switch (packet_ok (rs->buf,
1554e9be 2338 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
2339 {
2340 case PACKET_OK:
2341 if (strcmp (rs->buf, "1") == 0)
2342 return 1;
2343 break;
2344 case PACKET_ERROR:
2345 warning (_("Remote failure reply: %s"), rs->buf);
2346 break;
2347 case PACKET_UNKNOWN:
2348 break;
2349 }
2350
2351 return 0;
2352}
2353
49c62f2e
PA
2354/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2355 has been invented by GDB, instead of reported by the target. Since
2356 we can be connected to a remote system before before knowing about
2357 any inferior, mark the target with execution when we find the first
2358 inferior. If ATTACHED is 1, then we had just attached to this
2359 inferior. If it is 0, then we just created this inferior. If it
2360 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
2361 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2362 attempt to open this inferior's executable as the main executable
2363 if no main executable is open already. */
1941c569 2364
6b8edb51
PA
2365inferior *
2366remote_target::remote_add_inferior (int fake_pid_p, int pid, int attached,
2367 int try_open_exec)
1941c569 2368{
1941c569
PA
2369 struct inferior *inf;
2370
0b16c5cf
PA
2371 /* Check whether this process we're learning about is to be
2372 considered attached, or if is to be considered to have been
2373 spawned by the stub. */
2374 if (attached == -1)
2375 attached = remote_query_attached (pid);
2376
f5656ead 2377 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
2378 {
2379 /* If the target shares code across all inferiors, then every
2380 attach adds a new inferior. */
2381 inf = add_inferior (pid);
2382
2383 /* ... and every inferior is bound to the same program space.
2384 However, each inferior may still have its own address
2385 space. */
2386 inf->aspace = maybe_new_address_space ();
2387 inf->pspace = current_program_space;
2388 }
2389 else
2390 {
2391 /* In the traditional debugging scenario, there's a 1-1 match
2392 between program/address spaces. We simply bind the inferior
2393 to the program space's address space. */
2394 inf = current_inferior ();
2395 inferior_appeared (inf, pid);
2396 }
1941c569 2397
0b16c5cf 2398 inf->attach_flag = attached;
49c62f2e 2399 inf->fake_pid_p = fake_pid_p;
0b16c5cf 2400
1b6e6f5c
GB
2401 /* If no main executable is currently open then attempt to
2402 open the file that was executed to create this inferior. */
835205d0 2403 if (try_open_exec && get_exec_file (0) == NULL)
bb805577 2404 exec_file_locate_attach (pid, 0, 1);
1b6e6f5c 2405
1941c569
PA
2406 return inf;
2407}
2408
7aabaf9d 2409static remote_thread_info *get_remote_thread_info (thread_info *thread);
00431a78 2410static remote_thread_info *get_remote_thread_info (ptid_t ptid);
85ad3aaf 2411
1941c569
PA
2412/* Add thread PTID to GDB's thread list. Tag it as executing/running
2413 according to RUNNING. */
2414
00431a78 2415thread_info *
6b8edb51 2416remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing)
c906108c 2417{
b7ea362b 2418 struct remote_state *rs = get_remote_state ();
85ad3aaf 2419 struct thread_info *thread;
b7ea362b
PA
2420
2421 /* GDB historically didn't pull threads in the initial connection
2422 setup. If the remote target doesn't even have a concept of
2423 threads (e.g., a bare-metal target), even if internally we
2424 consider that a single-threaded target, mentioning a new thread
2425 might be confusing to the user. Be silent then, preserving the
2426 age old behavior. */
2427 if (rs->starting_up)
85ad3aaf 2428 thread = add_thread_silent (ptid);
b7ea362b 2429 else
85ad3aaf 2430 thread = add_thread (ptid);
1941c569 2431
7aabaf9d 2432 get_remote_thread_info (thread)->vcont_resumed = executing;
0d5b594f 2433 set_executing (ptid, executing);
1941c569 2434 set_running (ptid, running);
00431a78
PA
2435
2436 return thread;
1941c569
PA
2437}
2438
2439/* Come here when we learn about a thread id from the remote target.
2440 It may be the first time we hear about such thread, so take the
2441 opportunity to add it to GDB's thread list. In case this is the
2442 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
2443 GDB's inferior list as well. EXECUTING indicates whether the
2444 thread is (internally) executing or stopped. */
1941c569 2445
6b8edb51
PA
2446void
2447remote_target::remote_notice_new_inferior (ptid_t currthread, int executing)
1941c569 2448{
0d5b594f
PA
2449 /* In non-stop mode, we assume new found threads are (externally)
2450 running until proven otherwise with a stop reply. In all-stop,
2451 we can only get here if all threads are stopped. */
2452 int running = target_is_non_stop_p () ? 1 : 0;
2453
c906108c
SS
2454 /* If this is a new thread, add it to GDB's thread list.
2455 If we leave it up to WFI to do this, bad things will happen. */
82f73884 2456
00431a78
PA
2457 thread_info *tp = find_thread_ptid (currthread);
2458 if (tp != NULL && tp->state == THREAD_EXITED)
82f73884
PA
2459 {
2460 /* We're seeing an event on a thread id we knew had exited.
2461 This has to be a new thread reusing the old id. Add it. */
0d5b594f 2462 remote_add_thread (currthread, running, executing);
82f73884
PA
2463 return;
2464 }
2465
79d7f229 2466 if (!in_thread_list (currthread))
c0a2216e 2467 {
1941c569 2468 struct inferior *inf = NULL;
e99b03dc 2469 int pid = currthread.pid ();
1941c569 2470
0e998d96 2471 if (inferior_ptid.is_pid ()
e99b03dc 2472 && pid == inferior_ptid.pid ())
c0a2216e
PA
2473 {
2474 /* inferior_ptid has no thread member yet. This can happen
2475 with the vAttach -> remote_wait,"TAAthread:" path if the
2476 stub doesn't support qC. This is the first stop reported
2477 after an attach, so this is the main thread. Update the
2478 ptid in the thread list. */
f2907e49 2479 if (in_thread_list (ptid_t (pid)))
bad34192
PA
2480 thread_change_ptid (inferior_ptid, currthread);
2481 else
2482 {
0d5b594f 2483 remote_add_thread (currthread, running, executing);
bad34192
PA
2484 inferior_ptid = currthread;
2485 }
dc146f7c 2486 return;
c0a2216e 2487 }
82f73884 2488
d7e15655 2489 if (magic_null_ptid == inferior_ptid)
c0a2216e
PA
2490 {
2491 /* inferior_ptid is not set yet. This can happen with the
2492 vRun -> remote_wait,"TAAthread:" path if the stub
2493 doesn't support qC. This is the first stop reported
2494 after an attach, so this is the main thread. Update the
2495 ptid in the thread list. */
dc146f7c 2496 thread_change_ptid (inferior_ptid, currthread);
82f73884 2497 return;
c0a2216e 2498 }
82f73884 2499
29c87f7f
PA
2500 /* When connecting to a target remote, or to a target
2501 extended-remote which already was debugging an inferior, we
2502 may not know about it yet. Add it before adding its child
2503 thread, so notifications are emitted in a sensible order. */
e99b03dc 2504 if (find_inferior_pid (currthread.pid ()) == NULL)
49c62f2e
PA
2505 {
2506 struct remote_state *rs = get_remote_state ();
2507 int fake_pid_p = !remote_multi_process_p (rs);
2508
2509 inf = remote_add_inferior (fake_pid_p,
e99b03dc 2510 currthread.pid (), -1, 1);
49c62f2e 2511 }
29c87f7f 2512
82f73884 2513 /* This is really a new thread. Add it. */
00431a78
PA
2514 thread_info *new_thr
2515 = remote_add_thread (currthread, running, executing);
1941c569
PA
2516
2517 /* If we found a new inferior, let the common code do whatever
2518 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
2519 breakpoints), unless we're just setting up an all-stop
2520 connection. */
1941c569 2521 if (inf != NULL)
b7ea362b
PA
2522 {
2523 struct remote_state *rs = get_remote_state ();
2524
6efcd9a8 2525 if (!rs->starting_up)
00431a78 2526 notice_new_inferior (new_thr, executing, 0);
b7ea362b 2527 }
c0a2216e 2528 }
c906108c
SS
2529}
2530
85ad3aaf 2531/* Return THREAD's private thread data, creating it if necessary. */
dc146f7c 2532
7aabaf9d
SM
2533static remote_thread_info *
2534get_remote_thread_info (thread_info *thread)
dc146f7c 2535{
85ad3aaf 2536 gdb_assert (thread != NULL);
dc146f7c 2537
85ad3aaf 2538 if (thread->priv == NULL)
7aabaf9d 2539 thread->priv.reset (new remote_thread_info);
dc146f7c 2540
7aabaf9d 2541 return static_cast<remote_thread_info *> (thread->priv.get ());
85ad3aaf
PA
2542}
2543
7aabaf9d
SM
2544static remote_thread_info *
2545get_remote_thread_info (ptid_t ptid)
85ad3aaf 2546{
00431a78
PA
2547 thread_info *thr = find_thread_ptid (ptid);
2548 return get_remote_thread_info (thr);
dc146f7c
VP
2549}
2550
74531fed
PA
2551/* Call this function as a result of
2552 1) A halt indication (T packet) containing a thread id
2553 2) A direct query of currthread
0df8b418 2554 3) Successful execution of set thread */
74531fed
PA
2555
2556static void
47f8a51d 2557record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 2558{
47f8a51d 2559 rs->general_thread = currthread;
74531fed
PA
2560}
2561
89be2091
DJ
2562/* If 'QPassSignals' is supported, tell the remote stub what signals
2563 it can simply pass through to the inferior without reporting. */
2564
f6ac5f3d
PA
2565void
2566remote_target::pass_signals (int numsigs, unsigned char *pass_signals)
89be2091 2567{
4082afcc 2568 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
2569 {
2570 char *pass_packet, *p;
89be2091 2571 int count = 0, i;
747dc59d 2572 struct remote_state *rs = get_remote_state ();
89be2091
DJ
2573
2574 gdb_assert (numsigs < 256);
2575 for (i = 0; i < numsigs; i++)
2576 {
2455069d 2577 if (pass_signals[i])
89be2091
DJ
2578 count++;
2579 }
224c3ddb 2580 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
2581 strcpy (pass_packet, "QPassSignals:");
2582 p = pass_packet + strlen (pass_packet);
2583 for (i = 0; i < numsigs; i++)
2584 {
2455069d 2585 if (pass_signals[i])
89be2091
DJ
2586 {
2587 if (i >= 16)
2588 *p++ = tohex (i >> 4);
2589 *p++ = tohex (i & 15);
2590 if (count)
2591 *p++ = ';';
2592 else
2593 break;
2594 count--;
2595 }
2596 }
2597 *p = 0;
747dc59d 2598 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 2599 {
89be2091
DJ
2600 putpkt (pass_packet);
2601 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2602 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
2603 if (rs->last_pass_packet)
2604 xfree (rs->last_pass_packet);
2605 rs->last_pass_packet = pass_packet;
89be2091
DJ
2606 }
2607 else
2608 xfree (pass_packet);
2609 }
2610}
2611
82075af2
JS
2612/* If 'QCatchSyscalls' is supported, tell the remote stub
2613 to report syscalls to GDB. */
2614
f6ac5f3d
PA
2615int
2616remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2617 gdb::array_view<const int> syscall_counts)
82075af2 2618{
b80406ac 2619 const char *catch_packet;
82075af2
JS
2620 enum packet_result result;
2621 int n_sysno = 0;
2622
2623 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2624 {
2625 /* Not supported. */
2626 return 1;
2627 }
2628
649a140c 2629 if (needed && any_count == 0)
82075af2 2630 {
649a140c
PA
2631 /* Count how many syscalls are to be caught. */
2632 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2633 {
649a140c 2634 if (syscall_counts[i] != 0)
82075af2
JS
2635 n_sysno++;
2636 }
2637 }
2638
2639 if (remote_debug)
2640 {
2641 fprintf_unfiltered (gdb_stdlog,
2642 "remote_set_syscall_catchpoint "
2643 "pid %d needed %d any_count %d n_sysno %d\n",
2644 pid, needed, any_count, n_sysno);
2645 }
2646
1b81856f 2647 std::string built_packet;
82075af2
JS
2648 if (needed)
2649 {
2650 /* Prepare a packet with the sysno list, assuming max 8+1
2651 characters for a sysno. If the resulting packet size is too
2652 big, fallback on the non-selective packet. */
2653 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
1b81856f
PA
2654 built_packet.reserve (maxpktsz);
2655 built_packet = "QCatchSyscalls:1";
649a140c 2656 if (any_count == 0)
82075af2 2657 {
649a140c
PA
2658 /* Add in each syscall to be caught. */
2659 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2660 {
649a140c
PA
2661 if (syscall_counts[i] != 0)
2662 string_appendf (built_packet, ";%zx", i);
82075af2
JS
2663 }
2664 }
1b81856f 2665 if (built_packet.size () > get_remote_packet_size ())
82075af2
JS
2666 {
2667 /* catch_packet too big. Fallback to less efficient
2668 non selective mode, with GDB doing the filtering. */
b80406ac 2669 catch_packet = "QCatchSyscalls:1";
82075af2 2670 }
b80406ac 2671 else
1b81856f 2672 catch_packet = built_packet.c_str ();
82075af2
JS
2673 }
2674 else
b80406ac 2675 catch_packet = "QCatchSyscalls:0";
82075af2 2676
b80406ac 2677 struct remote_state *rs = get_remote_state ();
82075af2 2678
b80406ac
TT
2679 putpkt (catch_packet);
2680 getpkt (&rs->buf, &rs->buf_size, 0);
2681 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2682 if (result == PACKET_OK)
2683 return 0;
2684 else
2685 return -1;
82075af2
JS
2686}
2687
9b224c5e
PA
2688/* If 'QProgramSignals' is supported, tell the remote stub what
2689 signals it should pass through to the inferior when detaching. */
2690
f6ac5f3d
PA
2691void
2692remote_target::program_signals (int numsigs, unsigned char *signals)
9b224c5e 2693{
4082afcc 2694 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
2695 {
2696 char *packet, *p;
2697 int count = 0, i;
5e4a05c4 2698 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
2699
2700 gdb_assert (numsigs < 256);
2701 for (i = 0; i < numsigs; i++)
2702 {
2703 if (signals[i])
2704 count++;
2705 }
224c3ddb 2706 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2707 strcpy (packet, "QProgramSignals:");
2708 p = packet + strlen (packet);
2709 for (i = 0; i < numsigs; i++)
2710 {
2711 if (signal_pass_state (i))
2712 {
2713 if (i >= 16)
2714 *p++ = tohex (i >> 4);
2715 *p++ = tohex (i & 15);
2716 if (count)
2717 *p++ = ';';
2718 else
2719 break;
2720 count--;
2721 }
2722 }
2723 *p = 0;
5e4a05c4
TT
2724 if (!rs->last_program_signals_packet
2725 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2726 {
9b224c5e
PA
2727 putpkt (packet);
2728 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2729 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2730 xfree (rs->last_program_signals_packet);
2731 rs->last_program_signals_packet = packet;
9b224c5e
PA
2732 }
2733 else
2734 xfree (packet);
2735 }
2736}
2737
79d7f229
PA
2738/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2739 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2740 thread. If GEN is set, set the general thread, if not, then set
2741 the step/continue thread. */
6b8edb51
PA
2742void
2743remote_target::set_thread (ptid_t ptid, int gen)
c906108c 2744{
d01949b6 2745 struct remote_state *rs = get_remote_state ();
47f8a51d 2746 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 2747 char *buf = rs->buf;
79d7f229 2748 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 2749
d7e15655 2750 if (state == ptid)
c906108c
SS
2751 return;
2752
79d7f229
PA
2753 *buf++ = 'H';
2754 *buf++ = gen ? 'g' : 'c';
d7e15655 2755 if (ptid == magic_null_ptid)
79d7f229 2756 xsnprintf (buf, endbuf - buf, "0");
d7e15655 2757 else if (ptid == any_thread_ptid)
79d7f229 2758 xsnprintf (buf, endbuf - buf, "0");
d7e15655 2759 else if (ptid == minus_one_ptid)
79d7f229
PA
2760 xsnprintf (buf, endbuf - buf, "-1");
2761 else
82f73884 2762 write_ptid (buf, endbuf, ptid);
79d7f229 2763 putpkt (rs->buf);
6d820c5c 2764 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2765 if (gen)
47f8a51d 2766 rs->general_thread = ptid;
c906108c 2767 else
47f8a51d 2768 rs->continue_thread = ptid;
c906108c 2769}
79d7f229 2770
6b8edb51
PA
2771void
2772remote_target::set_general_thread (ptid_t ptid)
79d7f229
PA
2773{
2774 set_thread (ptid, 1);
2775}
2776
6b8edb51
PA
2777void
2778remote_target::set_continue_thread (ptid_t ptid)
79d7f229
PA
2779{
2780 set_thread (ptid, 0);
2781}
2782
3c9c4b83
PA
2783/* Change the remote current process. Which thread within the process
2784 ends up selected isn't important, as long as it is the same process
2785 as what INFERIOR_PTID points to.
2786
2787 This comes from that fact that there is no explicit notion of
2788 "selected process" in the protocol. The selected process for
2789 general operations is the process the selected general thread
2790 belongs to. */
2791
6b8edb51
PA
2792void
2793remote_target::set_general_process ()
3c9c4b83
PA
2794{
2795 struct remote_state *rs = get_remote_state ();
2796
2797 /* If the remote can't handle multiple processes, don't bother. */
8020350c 2798 if (!remote_multi_process_p (rs))
3c9c4b83
PA
2799 return;
2800
2801 /* We only need to change the remote current thread if it's pointing
2802 at some other process. */
e99b03dc 2803 if (rs->general_thread.pid () != inferior_ptid.pid ())
3c9c4b83
PA
2804 set_general_thread (inferior_ptid);
2805}
2806
c906108c 2807\f
7d1a114c
PA
2808/* Return nonzero if this is the main thread that we made up ourselves
2809 to model non-threaded targets as single-threaded. */
c906108c
SS
2810
2811static int
f6ac5f3d 2812remote_thread_always_alive (ptid_t ptid)
c906108c 2813{
d7e15655 2814 if (ptid == magic_null_ptid)
c0a2216e
PA
2815 /* The main thread is always alive. */
2816 return 1;
2817
e38504b3 2818 if (ptid.pid () != 0 && ptid.lwp () == 0)
c0a2216e
PA
2819 /* The main thread is always alive. This can happen after a
2820 vAttach, if the remote side doesn't support
2821 multi-threading. */
2822 return 1;
2823
7d1a114c
PA
2824 return 0;
2825}
2826
2827/* Return nonzero if the thread PTID is still alive on the remote
2828 system. */
2829
57810aa7 2830bool
f6ac5f3d 2831remote_target::thread_alive (ptid_t ptid)
7d1a114c
PA
2832{
2833 struct remote_state *rs = get_remote_state ();
2834 char *p, *endp;
2835
2836 /* Check if this is a thread that we made up ourselves to model
2837 non-threaded targets as single-threaded. */
f6ac5f3d 2838 if (remote_thread_always_alive (ptid))
7d1a114c
PA
2839 return 1;
2840
82f73884
PA
2841 p = rs->buf;
2842 endp = rs->buf + get_remote_packet_size ();
2843
2844 *p++ = 'T';
2845 write_ptid (p, endp, ptid);
2846
2e9f7625 2847 putpkt (rs->buf);
6d820c5c 2848 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2849 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2850}
2851
79efa585
SM
2852/* Return a pointer to a thread name if we know it and NULL otherwise.
2853 The thread_info object owns the memory for the name. */
2854
f6ac5f3d
PA
2855const char *
2856remote_target::thread_name (struct thread_info *info)
79efa585
SM
2857{
2858 if (info->priv != NULL)
a9334058
SM
2859 {
2860 const std::string &name = get_remote_thread_info (info)->name;
2861 return !name.empty () ? name.c_str () : NULL;
2862 }
79efa585
SM
2863
2864 return NULL;
2865}
2866
c906108c
SS
2867/* About these extended threadlist and threadinfo packets. They are
2868 variable length packets but, the fields within them are often fixed
2869 length. They are redundent enough to send over UDP as is the
2870 remote protocol in general. There is a matching unit test module
2871 in libstub. */
2872
23860348 2873/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2874 libstub protocol encoding, and remote.c. It is not particularly
23860348 2875 changable. */
cce74817
JM
2876
2877/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2878 Plan to fix this. */
cce74817 2879
23860348 2880typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2881
9d1f7ab2 2882/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2883 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2884
2885struct gdb_ext_thread_info
c5aa993b 2886 {
23860348 2887 threadref threadid; /* External form of thread reference. */
2bc416ba 2888 int active; /* Has state interesting to GDB?
23860348 2889 regs, stack. */
2bc416ba 2890 char display[256]; /* Brief state display, name,
cedea757 2891 blocked/suspended. */
23860348 2892 char shortname[32]; /* To be used to name threads. */
2bc416ba 2893 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2894 whatever. */
c5aa993b 2895 };
cce74817
JM
2896
2897/* The volume of remote transfers can be limited by submitting
2898 a mask containing bits specifying the desired information.
2899 Use a union of these values as the 'selection' parameter to
0df8b418 2900 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2901
2902#define TAG_THREADID 1
2903#define TAG_EXISTS 2
2904#define TAG_DISPLAY 4
2905#define TAG_THREADNAME 8
c5aa993b 2906#define TAG_MOREDISPLAY 16
cce74817 2907
23860348 2908#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2909
a14ed312 2910static char *unpack_nibble (char *buf, int *val);
cce74817 2911
a14ed312 2912static char *unpack_byte (char *buf, int *value);
cce74817 2913
a14ed312 2914static char *pack_int (char *buf, int value);
cce74817 2915
a14ed312 2916static char *unpack_int (char *buf, int *value);
cce74817 2917
a14ed312 2918static char *unpack_string (char *src, char *dest, int length);
cce74817 2919
23860348 2920static char *pack_threadid (char *pkt, threadref *id);
cce74817 2921
23860348 2922static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2923
23860348 2924void int_to_threadref (threadref *id, int value);
cce74817 2925
23860348 2926static int threadref_to_int (threadref *ref);
cce74817 2927
23860348 2928static void copy_threadref (threadref *dest, threadref *src);
cce74817 2929
23860348 2930static int threadmatch (threadref *dest, threadref *src);
cce74817 2931
2bc416ba 2932static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2933 threadref *id);
cce74817 2934
a14ed312
KB
2935static char *pack_threadlist_request (char *pkt, int startflag,
2936 int threadcount,
23860348 2937 threadref *nextthread);
cce74817 2938
23860348 2939static int remote_newthread_step (threadref *ref, void *context);
cce74817 2940
82f73884
PA
2941
2942/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2943 buffer we're allowed to write to. Returns
2944 BUF+CHARACTERS_WRITTEN. */
2945
6b8edb51
PA
2946char *
2947remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
82f73884
PA
2948{
2949 int pid, tid;
2950 struct remote_state *rs = get_remote_state ();
2951
2952 if (remote_multi_process_p (rs))
2953 {
e99b03dc 2954 pid = ptid.pid ();
82f73884
PA
2955 if (pid < 0)
2956 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2957 else
2958 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2959 }
e38504b3 2960 tid = ptid.lwp ();
82f73884
PA
2961 if (tid < 0)
2962 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2963 else
2964 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2965
2966 return buf;
2967}
2968
256642e8
PA
2969/* Extract a PTID from BUF. If non-null, OBUF is set to one past the
2970 last parsed char. Returns null_ptid if no thread id is found, and
2971 throws an error if the thread id has an invalid format. */
82f73884
PA
2972
2973static ptid_t
256642e8 2974read_ptid (const char *buf, const char **obuf)
82f73884 2975{
256642e8
PA
2976 const char *p = buf;
2977 const char *pp;
82f73884 2978 ULONGEST pid = 0, tid = 0;
82f73884
PA
2979
2980 if (*p == 'p')
2981 {
2982 /* Multi-process ptid. */
2983 pp = unpack_varlen_hex (p + 1, &pid);
2984 if (*pp != '.')
b37520b6 2985 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2986
2987 p = pp;
2988 pp = unpack_varlen_hex (p + 1, &tid);
2989 if (obuf)
2990 *obuf = pp;
fd79271b 2991 return ptid_t (pid, tid, 0);
82f73884
PA
2992 }
2993
2994 /* No multi-process. Just a tid. */
2995 pp = unpack_varlen_hex (p, &tid);
2996
c9f35b34
KB
2997 /* Return null_ptid when no thread id is found. */
2998 if (p == pp)
2999 {
3000 if (obuf)
3001 *obuf = pp;
3002 return null_ptid;
3003 }
3004
82f73884 3005 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
3006 what's in inferior_ptid, unless it's null at this point. If so,
3007 then since there's no way to know the pid of the reported
3008 threads, use the magic number. */
d7e15655 3009 if (inferior_ptid == null_ptid)
e99b03dc 3010 pid = magic_null_ptid.pid ();
ca19bf23 3011 else
e99b03dc 3012 pid = inferior_ptid.pid ();
82f73884
PA
3013
3014 if (obuf)
3015 *obuf = pp;
fd79271b 3016 return ptid_t (pid, tid, 0);
82f73884
PA
3017}
3018
c906108c 3019static int
fba45db2 3020stubhex (int ch)
c906108c
SS
3021{
3022 if (ch >= 'a' && ch <= 'f')
3023 return ch - 'a' + 10;
3024 if (ch >= '0' && ch <= '9')
3025 return ch - '0';
3026 if (ch >= 'A' && ch <= 'F')
3027 return ch - 'A' + 10;
3028 return -1;
3029}
3030
3031static int
fba45db2 3032stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
3033{
3034 int nibble;
3035 int retval = 0;
3036
3037 while (fieldlength)
3038 {
3039 nibble = stubhex (*buff++);
3040 retval |= nibble;
3041 fieldlength--;
3042 if (fieldlength)
3043 retval = retval << 4;
3044 }
3045 return retval;
3046}
3047
c906108c 3048static char *
fba45db2 3049unpack_nibble (char *buf, int *val)
c906108c 3050{
b7589f7d 3051 *val = fromhex (*buf++);
c906108c
SS
3052 return buf;
3053}
3054
c906108c 3055static char *
fba45db2 3056unpack_byte (char *buf, int *value)
c906108c
SS
3057{
3058 *value = stub_unpack_int (buf, 2);
3059 return buf + 2;
3060}
3061
3062static char *
fba45db2 3063pack_int (char *buf, int value)
c906108c
SS
3064{
3065 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3066 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3067 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3068 buf = pack_hex_byte (buf, (value & 0xff));
3069 return buf;
3070}
3071
3072static char *
fba45db2 3073unpack_int (char *buf, int *value)
c906108c
SS
3074{
3075 *value = stub_unpack_int (buf, 8);
3076 return buf + 8;
3077}
3078
23860348 3079#if 0 /* Currently unused, uncomment when needed. */
a14ed312 3080static char *pack_string (char *pkt, char *string);
c906108c
SS
3081
3082static char *
fba45db2 3083pack_string (char *pkt, char *string)
c906108c
SS
3084{
3085 char ch;
3086 int len;
3087
3088 len = strlen (string);
3089 if (len > 200)
23860348 3090 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
3091 pkt = pack_hex_byte (pkt, len);
3092 while (len-- > 0)
3093 {
3094 ch = *string++;
3095 if ((ch == '\0') || (ch == '#'))
23860348 3096 ch = '*'; /* Protect encapsulation. */
c906108c
SS
3097 *pkt++ = ch;
3098 }
3099 return pkt;
3100}
3101#endif /* 0 (unused) */
3102
3103static char *
fba45db2 3104unpack_string (char *src, char *dest, int length)
c906108c
SS
3105{
3106 while (length--)
3107 *dest++ = *src++;
3108 *dest = '\0';
3109 return src;
3110}
3111
3112static char *
fba45db2 3113pack_threadid (char *pkt, threadref *id)
c906108c
SS
3114{
3115 char *limit;
3116 unsigned char *altid;
3117
3118 altid = (unsigned char *) id;
3119 limit = pkt + BUF_THREAD_ID_SIZE;
3120 while (pkt < limit)
3121 pkt = pack_hex_byte (pkt, *altid++);
3122 return pkt;
3123}
3124
3125
3126static char *
fba45db2 3127unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
3128{
3129 char *altref;
3130 char *limit = inbuf + BUF_THREAD_ID_SIZE;
3131 int x, y;
3132
3133 altref = (char *) id;
3134
3135 while (inbuf < limit)
3136 {
3137 x = stubhex (*inbuf++);
3138 y = stubhex (*inbuf++);
3139 *altref++ = (x << 4) | y;
3140 }
3141 return inbuf;
3142}
3143
3144/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 3145 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
3146 to use 64bit thread references internally. This is an adapter
3147 function. */
3148
3149void
fba45db2 3150int_to_threadref (threadref *id, int value)
c906108c
SS
3151{
3152 unsigned char *scan;
3153
3154 scan = (unsigned char *) id;
3155 {
3156 int i = 4;
3157 while (i--)
3158 *scan++ = 0;
3159 }
3160 *scan++ = (value >> 24) & 0xff;
3161 *scan++ = (value >> 16) & 0xff;
3162 *scan++ = (value >> 8) & 0xff;
3163 *scan++ = (value & 0xff);
3164}
3165
3166static int
fba45db2 3167threadref_to_int (threadref *ref)
c906108c
SS
3168{
3169 int i, value = 0;
3170 unsigned char *scan;
3171
cfd77fa1 3172 scan = *ref;
c906108c
SS
3173 scan += 4;
3174 i = 4;
3175 while (i-- > 0)
3176 value = (value << 8) | ((*scan++) & 0xff);
3177 return value;
3178}
3179
3180static void
fba45db2 3181copy_threadref (threadref *dest, threadref *src)
c906108c
SS
3182{
3183 int i;
3184 unsigned char *csrc, *cdest;
3185
3186 csrc = (unsigned char *) src;
3187 cdest = (unsigned char *) dest;
3188 i = 8;
3189 while (i--)
3190 *cdest++ = *csrc++;
3191}
3192
3193static int
fba45db2 3194threadmatch (threadref *dest, threadref *src)
c906108c 3195{
23860348 3196 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
3197#if 0
3198 unsigned char *srcp, *destp;
3199 int i, result;
3200 srcp = (char *) src;
3201 destp = (char *) dest;
3202
3203 result = 1;
3204 while (i-- > 0)
3205 result &= (*srcp++ == *destp++) ? 1 : 0;
3206 return result;
3207#endif
3208 return 1;
3209}
3210
3211/*
c5aa993b
JM
3212 threadid:1, # always request threadid
3213 context_exists:2,
3214 display:4,
3215 unique_name:8,
3216 more_display:16
3217 */
c906108c
SS
3218
3219/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3220
3221static char *
fba45db2 3222pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 3223{
23860348
MS
3224 *pkt++ = 'q'; /* Info Query */
3225 *pkt++ = 'P'; /* process or thread info */
3226 pkt = pack_int (pkt, mode); /* mode */
c906108c 3227 pkt = pack_threadid (pkt, id); /* threadid */
23860348 3228 *pkt = '\0'; /* terminate */
c906108c
SS
3229 return pkt;
3230}
3231
23860348 3232/* These values tag the fields in a thread info response packet. */
c906108c 3233/* Tagging the fields allows us to request specific fields and to
23860348 3234 add more fields as time goes by. */
c906108c 3235
23860348 3236#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 3237#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 3238 fetch registers and its stack? */
c5aa993b 3239#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 3240#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 3241#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 3242 the process. */
c906108c 3243
6b8edb51
PA
3244int
3245remote_target::remote_unpack_thread_info_response (char *pkt,
3246 threadref *expectedref,
3247 gdb_ext_thread_info *info)
c906108c 3248{
d01949b6 3249 struct remote_state *rs = get_remote_state ();
c906108c 3250 int mask, length;
cfd77fa1 3251 int tag;
c906108c 3252 threadref ref;
6d820c5c 3253 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
3254 int retval = 1;
3255
23860348 3256 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
3257 info->active = 0;
3258 info->display[0] = '\0';
3259 info->shortname[0] = '\0';
3260 info->more_display[0] = '\0';
3261
23860348
MS
3262 /* Assume the characters indicating the packet type have been
3263 stripped. */
c906108c
SS
3264 pkt = unpack_int (pkt, &mask); /* arg mask */
3265 pkt = unpack_threadid (pkt, &ref);
3266
3267 if (mask == 0)
8a3fe4f8 3268 warning (_("Incomplete response to threadinfo request."));
c906108c 3269 if (!threadmatch (&ref, expectedref))
23860348 3270 { /* This is an answer to a different request. */
8a3fe4f8 3271 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
3272 return 0;
3273 }
3274 copy_threadref (&info->threadid, &ref);
3275
23860348 3276 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 3277
23860348
MS
3278 /* Packets are terminated with nulls. */
3279 while ((pkt < limit) && mask && *pkt)
c906108c
SS
3280 {
3281 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
3282 pkt = unpack_byte (pkt, &length); /* length */
3283 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 3284 {
8a3fe4f8 3285 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
3286 retval = 0;
3287 break;
3288 }
3289 if (tag == TAG_THREADID)
3290 {
3291 if (length != 16)
3292 {
8a3fe4f8 3293 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
3294 retval = 0;
3295 break;
3296 }
3297 pkt = unpack_threadid (pkt, &ref);
3298 mask = mask & ~TAG_THREADID;
3299 continue;
3300 }
3301 if (tag == TAG_EXISTS)
3302 {
3303 info->active = stub_unpack_int (pkt, length);
3304 pkt += length;
3305 mask = mask & ~(TAG_EXISTS);
3306 if (length > 8)
3307 {
8a3fe4f8 3308 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
3309 retval = 0;
3310 break;
3311 }
3312 continue;
3313 }
3314 if (tag == TAG_THREADNAME)
3315 {
3316 pkt = unpack_string (pkt, &info->shortname[0], length);
3317 mask = mask & ~TAG_THREADNAME;
3318 continue;
3319 }
3320 if (tag == TAG_DISPLAY)
3321 {
3322 pkt = unpack_string (pkt, &info->display[0], length);
3323 mask = mask & ~TAG_DISPLAY;
3324 continue;
3325 }
3326 if (tag == TAG_MOREDISPLAY)
3327 {
3328 pkt = unpack_string (pkt, &info->more_display[0], length);
3329 mask = mask & ~TAG_MOREDISPLAY;
3330 continue;
3331 }
8a3fe4f8 3332 warning (_("ERROR RMT: unknown thread info tag."));
23860348 3333 break; /* Not a tag we know about. */
c906108c
SS
3334 }
3335 return retval;
3336}
3337
6b8edb51
PA
3338int
3339remote_target::remote_get_threadinfo (threadref *threadid,
3340 int fieldset,
3341 gdb_ext_thread_info *info)
c906108c 3342{
d01949b6 3343 struct remote_state *rs = get_remote_state ();
c906108c 3344 int result;
c906108c 3345
2e9f7625
DJ
3346 pack_threadinfo_request (rs->buf, fieldset, threadid);
3347 putpkt (rs->buf);
6d820c5c 3348 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
3349
3350 if (rs->buf[0] == '\0')
3351 return 0;
3352
2e9f7625 3353 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 3354 threadid, info);
c906108c
SS
3355 return result;
3356}
3357
c906108c
SS
3358/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3359
3360static char *
fba45db2
KB
3361pack_threadlist_request (char *pkt, int startflag, int threadcount,
3362 threadref *nextthread)
c906108c
SS
3363{
3364 *pkt++ = 'q'; /* info query packet */
3365 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 3366 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
3367 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3368 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3369 *pkt = '\0';
3370 return pkt;
3371}
3372
3373/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3374
6b8edb51
PA
3375int
3376remote_target::parse_threadlist_response (char *pkt, int result_limit,
3377 threadref *original_echo,
3378 threadref *resultlist,
3379 int *doneflag)
c906108c 3380{
d01949b6 3381 struct remote_state *rs = get_remote_state ();
c906108c
SS
3382 char *limit;
3383 int count, resultcount, done;
3384
3385 resultcount = 0;
3386 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 3387 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 3388 /* done parse past here */
c906108c
SS
3389 pkt = unpack_byte (pkt, &count); /* count field */
3390 pkt = unpack_nibble (pkt, &done);
3391 /* The first threadid is the argument threadid. */
3392 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3393 while ((count-- > 0) && (pkt < limit))
3394 {
3395 pkt = unpack_threadid (pkt, resultlist++);
3396 if (resultcount++ >= result_limit)
3397 break;
3398 }
3399 if (doneflag)
3400 *doneflag = done;
3401 return resultcount;
3402}
3403
6dc54d91
PA
3404/* Fetch the next batch of threads from the remote. Returns -1 if the
3405 qL packet is not supported, 0 on error and 1 on success. */
3406
6b8edb51
PA
3407int
3408remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3409 int result_limit, int *done, int *result_count,
3410 threadref *threadlist)
c906108c 3411{
d01949b6 3412 struct remote_state *rs = get_remote_state ();
c906108c
SS
3413 int result = 1;
3414
23860348 3415 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
3416 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3417 >= get_remote_packet_size ())
ea9c271d 3418 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 3419
6d820c5c
DJ
3420 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
3421 putpkt (rs->buf);
3422 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 3423 if (*rs->buf == '\0')
6dc54d91
PA
3424 {
3425 /* Packet not supported. */
3426 return -1;
3427 }
3428
3429 *result_count =
3430 parse_threadlist_response (rs->buf + 2, result_limit,
3431 &rs->echo_nextthread, threadlist, done);
c906108c 3432
0d031856 3433 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 3434 {
23860348
MS
3435 /* FIXME: This is a good reason to drop the packet. */
3436 /* Possably, there is a duplicate response. */
c906108c
SS
3437 /* Possabilities :
3438 retransmit immediatly - race conditions
3439 retransmit after timeout - yes
3440 exit
3441 wait for packet, then exit
3442 */
8a3fe4f8 3443 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 3444 return 0; /* I choose simply exiting. */
c906108c
SS
3445 }
3446 if (*result_count <= 0)
3447 {
3448 if (*done != 1)
3449 {
8a3fe4f8 3450 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
3451 result = 0;
3452 }
3453 return result; /* break; */
3454 }
3455 if (*result_count > result_limit)
3456 {
3457 *result_count = 0;
8a3fe4f8 3458 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
3459 return 0;
3460 }
3461 return result;
3462}
3463
6dc54d91
PA
3464/* Fetch the list of remote threads, with the qL packet, and call
3465 STEPFUNCTION for each thread found. Stops iterating and returns 1
3466 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3467 STEPFUNCTION returns false. If the packet is not supported,
3468 returns -1. */
c906108c 3469
6b8edb51
PA
3470int
3471remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3472 void *context, int looplimit)
c906108c 3473{
0d031856 3474 struct remote_state *rs = get_remote_state ();
c906108c
SS
3475 int done, i, result_count;
3476 int startflag = 1;
3477 int result = 1;
3478 int loopcount = 0;
c906108c
SS
3479
3480 done = 0;
3481 while (!done)
3482 {
3483 if (loopcount++ > looplimit)
3484 {
3485 result = 0;
8a3fe4f8 3486 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
3487 break;
3488 }
6dc54d91
PA
3489 result = remote_get_threadlist (startflag, &rs->nextthread,
3490 MAXTHREADLISTRESULTS,
3491 &done, &result_count,
3492 rs->resultthreadlist);
3493 if (result <= 0)
3494 break;
23860348 3495 /* Clear for later iterations. */
c906108c
SS
3496 startflag = 0;
3497 /* Setup to resume next batch of thread references, set nextthread. */
3498 if (result_count >= 1)
0d031856
TT
3499 copy_threadref (&rs->nextthread,
3500 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
3501 i = 0;
3502 while (result_count--)
6dc54d91
PA
3503 {
3504 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3505 {
3506 result = 0;
3507 break;
3508 }
3509 }
c906108c
SS
3510 }
3511 return result;
3512}
3513
6dc54d91
PA
3514/* A thread found on the remote target. */
3515
21fe1c75 3516struct thread_item
6dc54d91 3517{
21fe1c75
SM
3518 explicit thread_item (ptid_t ptid_)
3519 : ptid (ptid_)
3520 {}
3521
3522 thread_item (thread_item &&other) = default;
3523 thread_item &operator= (thread_item &&other) = default;
3524
3525 DISABLE_COPY_AND_ASSIGN (thread_item);
3526
6dc54d91
PA
3527 /* The thread's PTID. */
3528 ptid_t ptid;
3529
21fe1c75
SM
3530 /* The thread's extra info. */
3531 std::string extra;
6dc54d91 3532
21fe1c75
SM
3533 /* The thread's name. */
3534 std::string name;
79efa585 3535
6dc54d91 3536 /* The core the thread was running on. -1 if not known. */
21fe1c75 3537 int core = -1;
f6327dcb
KB
3538
3539 /* The thread handle associated with the thread. */
21fe1c75 3540 gdb::byte_vector thread_handle;
21fe1c75 3541};
6dc54d91
PA
3542
3543/* Context passed around to the various methods listing remote
3544 threads. As new threads are found, they're added to the ITEMS
3545 vector. */
3546
3547struct threads_listing_context
3548{
21fe1c75
SM
3549 /* Return true if this object contains an entry for a thread with ptid
3550 PTID. */
6dc54d91 3551
21fe1c75
SM
3552 bool contains_thread (ptid_t ptid) const
3553 {
3554 auto match_ptid = [&] (const thread_item &item)
3555 {
3556 return item.ptid == ptid;
3557 };
80134cf5 3558
21fe1c75
SM
3559 auto it = std::find_if (this->items.begin (),
3560 this->items.end (),
3561 match_ptid);
80134cf5 3562
21fe1c75
SM
3563 return it != this->items.end ();
3564 }
80134cf5 3565
21fe1c75 3566 /* Remove the thread with ptid PTID. */
80134cf5 3567
21fe1c75
SM
3568 void remove_thread (ptid_t ptid)
3569 {
3570 auto match_ptid = [&] (const thread_item &item)
3571 {
3572 return item.ptid == ptid;
3573 };
cbb8991c 3574
21fe1c75
SM
3575 auto it = std::remove_if (this->items.begin (),
3576 this->items.end (),
3577 match_ptid);
cbb8991c 3578
21fe1c75
SM
3579 if (it != this->items.end ())
3580 this->items.erase (it);
3581 }
3582
3583 /* The threads found on the remote target. */
3584 std::vector<thread_item> items;
3585};
cbb8991c 3586
c906108c 3587static int
6dc54d91 3588remote_newthread_step (threadref *ref, void *data)
c906108c 3589{
19ba03f4
SM
3590 struct threads_listing_context *context
3591 = (struct threads_listing_context *) data;
21fe1c75
SM
3592 int pid = inferior_ptid.pid ();
3593 int lwp = threadref_to_int (ref);
3594 ptid_t ptid (pid, lwp);
6dc54d91 3595
21fe1c75 3596 context->items.emplace_back (ptid);
6dc54d91 3597
c906108c
SS
3598 return 1; /* continue iterator */
3599}
3600
3601#define CRAZY_MAX_THREADS 1000
3602
6b8edb51
PA
3603ptid_t
3604remote_target::remote_current_thread (ptid_t oldpid)
c906108c 3605{
d01949b6 3606 struct remote_state *rs = get_remote_state ();
c906108c
SS
3607
3608 putpkt ("qC");
6d820c5c 3609 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3610 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34 3611 {
256642e8 3612 const char *obuf;
c9f35b34
KB
3613 ptid_t result;
3614
3615 result = read_ptid (&rs->buf[2], &obuf);
3616 if (*obuf != '\0' && remote_debug)
3617 fprintf_unfiltered (gdb_stdlog,
3618 "warning: garbage in qC reply\n");
3619
3620 return result;
3621 }
c906108c
SS
3622 else
3623 return oldpid;
3624}
3625
6dc54d91 3626/* List remote threads using the deprecated qL packet. */
cce74817 3627
6b8edb51
PA
3628int
3629remote_target::remote_get_threads_with_ql (threads_listing_context *context)
c906108c 3630{
6dc54d91
PA
3631 if (remote_threadlist_iterator (remote_newthread_step, context,
3632 CRAZY_MAX_THREADS) >= 0)
3633 return 1;
3634
3635 return 0;
c906108c
SS
3636}
3637
dc146f7c
VP
3638#if defined(HAVE_LIBEXPAT)
3639
dc146f7c
VP
3640static void
3641start_thread (struct gdb_xml_parser *parser,
3642 const struct gdb_xml_element *element,
4d0fdd9b
SM
3643 void *user_data,
3644 std::vector<gdb_xml_value> &attributes)
dc146f7c 3645{
19ba03f4
SM
3646 struct threads_listing_context *data
3647 = (struct threads_listing_context *) user_data;
3d2c1d41 3648 struct gdb_xml_value *attr;
dc146f7c 3649
4d0fdd9b 3650 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
21fe1c75
SM
3651 ptid_t ptid = read_ptid (id, NULL);
3652
3653 data->items.emplace_back (ptid);
3654 thread_item &item = data->items.back ();
dc146f7c 3655
3d2c1d41
PA
3656 attr = xml_find_attribute (attributes, "core");
3657 if (attr != NULL)
4d0fdd9b 3658 item.core = *(ULONGEST *) attr->value.get ();
dc146f7c 3659
79efa585 3660 attr = xml_find_attribute (attributes, "name");
21fe1c75 3661 if (attr != NULL)
4d0fdd9b 3662 item.name = (const char *) attr->value.get ();
79efa585 3663
f6327dcb
KB
3664 attr = xml_find_attribute (attributes, "handle");
3665 if (attr != NULL)
4d0fdd9b 3666 item.thread_handle = hex2bin ((const char *) attr->value.get ());
dc146f7c
VP
3667}
3668
3669static void
3670end_thread (struct gdb_xml_parser *parser,
3671 const struct gdb_xml_element *element,
3672 void *user_data, const char *body_text)
3673{
19ba03f4
SM
3674 struct threads_listing_context *data
3675 = (struct threads_listing_context *) user_data;
dc146f7c 3676
21fe1c75
SM
3677 if (body_text != NULL && *body_text != '\0')
3678 data->items.back ().extra = body_text;
dc146f7c
VP
3679}
3680
3681const struct gdb_xml_attribute thread_attributes[] = {
3682 { "id", GDB_XML_AF_NONE, NULL, NULL },
3683 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3684 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
f6327dcb 3685 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3686 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3687};
3688
3689const struct gdb_xml_element thread_children[] = {
3690 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3691};
3692
3693const struct gdb_xml_element threads_children[] = {
3694 { "thread", thread_attributes, thread_children,
3695 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3696 start_thread, end_thread },
3697 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3698};
3699
3700const struct gdb_xml_element threads_elements[] = {
3701 { "threads", NULL, threads_children,
3702 GDB_XML_EF_NONE, NULL, NULL },
3703 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3704};
3705
3706#endif
3707
6dc54d91 3708/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3709
6b8edb51
PA
3710int
3711remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
0f71a2f6 3712{
dc146f7c 3713#if defined(HAVE_LIBEXPAT)
4082afcc 3714 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3715 {
9018be22 3716 gdb::optional<gdb::char_vector> xml
6b8edb51 3717 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
efc0eabd 3718
9018be22 3719 if (xml && (*xml)[0] != '\0')
dc146f7c 3720 {
6dc54d91 3721 gdb_xml_parse_quick (_("threads"), "threads.dtd",
9018be22 3722 threads_elements, xml->data (), context);
dc146f7c
VP
3723 }
3724
6dc54d91 3725 return 1;
dc146f7c
VP
3726 }
3727#endif
3728
6dc54d91
PA
3729 return 0;
3730}
3731
3732/* List remote threads using qfThreadInfo/qsThreadInfo. */
3733
6b8edb51
PA
3734int
3735remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
6dc54d91
PA
3736{
3737 struct remote_state *rs = get_remote_state ();
3738
b80fafe3 3739 if (rs->use_threadinfo_query)
9d1f7ab2 3740 {
256642e8 3741 const char *bufp;
6dc54d91 3742
9d1f7ab2 3743 putpkt ("qfThreadInfo");
6d820c5c 3744 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3745 bufp = rs->buf;
9d1f7ab2 3746 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3747 {
9d1f7ab2
MS
3748 while (*bufp++ == 'm') /* reply contains one or more TID */
3749 {
3750 do
3751 {
21fe1c75
SM
3752 ptid_t ptid = read_ptid (bufp, &bufp);
3753 context->items.emplace_back (ptid);
9d1f7ab2
MS
3754 }
3755 while (*bufp++ == ','); /* comma-separated list */
3756 putpkt ("qsThreadInfo");
6d820c5c 3757 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 3758 bufp = rs->buf;
9d1f7ab2 3759 }
6dc54d91
PA
3760 return 1;
3761 }
3762 else
3763 {
3764 /* Packet not recognized. */
3765 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3766 }
3767 }
3768
6dc54d91
PA
3769 return 0;
3770}
3771
e8032dde 3772/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3773 targets. */
3774
f6ac5f3d
PA
3775void
3776remote_target::update_thread_list ()
6dc54d91 3777{
6dc54d91 3778 struct threads_listing_context context;
ab970af1 3779 int got_list = 0;
e8032dde 3780
6dc54d91
PA
3781 /* We have a few different mechanisms to fetch the thread list. Try
3782 them all, starting with the most preferred one first, falling
3783 back to older methods. */
6b8edb51
PA
3784 if (remote_get_threads_with_qxfer (&context)
3785 || remote_get_threads_with_qthreadinfo (&context)
3786 || remote_get_threads_with_ql (&context))
6dc54d91 3787 {
ab970af1
PA
3788 struct thread_info *tp, *tmp;
3789
3790 got_list = 1;
3791
21fe1c75 3792 if (context.items.empty ()
f6ac5f3d 3793 && remote_thread_always_alive (inferior_ptid))
7d1a114c
PA
3794 {
3795 /* Some targets don't really support threads, but still
3796 reply an (empty) thread list in response to the thread
3797 listing packets, instead of replying "packet not
3798 supported". Exit early so we don't delete the main
3799 thread. */
7d1a114c
PA
3800 return;
3801 }
3802
ab970af1
PA
3803 /* CONTEXT now holds the current thread list on the remote
3804 target end. Delete GDB-side threads no longer found on the
3805 target. */
8a06aea7 3806 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3807 {
21fe1c75 3808 if (!context.contains_thread (tp->ptid))
ab970af1
PA
3809 {
3810 /* Not found. */
00431a78 3811 delete_thread (tp);
ab970af1 3812 }
cbb8991c
DB
3813 }
3814
3815 /* Remove any unreported fork child threads from CONTEXT so
3816 that we don't interfere with follow fork, which is where
3817 creation of such threads is handled. */
3818 remove_new_fork_children (&context);
74531fed 3819
ab970af1 3820 /* And now add threads we don't know about yet to our list. */
21fe1c75 3821 for (thread_item &item : context.items)
6dc54d91 3822 {
21fe1c75 3823 if (item.ptid != null_ptid)
6dc54d91 3824 {
6dc54d91 3825 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
3826 executing until proven otherwise with a stop reply.
3827 In all-stop, we can only get here if all threads are
6dc54d91 3828 stopped. */
0d5b594f 3829 int executing = target_is_non_stop_p () ? 1 : 0;
6dc54d91 3830
21fe1c75 3831 remote_notice_new_inferior (item.ptid, executing);
6dc54d91 3832
00431a78
PA
3833 thread_info *tp = find_thread_ptid (item.ptid);
3834 remote_thread_info *info = get_remote_thread_info (tp);
21fe1c75 3835 info->core = item.core;
7aabaf9d
SM
3836 info->extra = std::move (item.extra);
3837 info->name = std::move (item.name);
3838 info->thread_handle = std::move (item.thread_handle);
6dc54d91
PA
3839 }
3840 }
3841 }
3842
ab970af1
PA
3843 if (!got_list)
3844 {
3845 /* If no thread listing method is supported, then query whether
3846 each known thread is alive, one by one, with the T packet.
3847 If the target doesn't support threads at all, then this is a
3848 no-op. See remote_thread_alive. */
3849 prune_threads ();
3850 }
9d1f7ab2
MS
3851}
3852
802188a7 3853/*
9d1f7ab2
MS
3854 * Collect a descriptive string about the given thread.
3855 * The target may say anything it wants to about the thread
3856 * (typically info about its blocked / runnable state, name, etc.).
3857 * This string will appear in the info threads display.
802188a7 3858 *
9d1f7ab2
MS
3859 * Optional: targets are not required to implement this function.
3860 */
3861
f6ac5f3d
PA
3862const char *
3863remote_target::extra_thread_info (thread_info *tp)
9d1f7ab2 3864{
d01949b6 3865 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3866 int set;
3867 threadref id;
3868 struct gdb_ext_thread_info threadinfo;
9d1f7ab2 3869
5d93a237 3870 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3871 internal_error (__FILE__, __LINE__,
e2e0b3e5 3872 _("remote_threads_extra_info"));
9d1f7ab2 3873
d7e15655 3874 if (tp->ptid == magic_null_ptid
e38504b3 3875 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
60e569b9
PA
3876 /* This is the main thread which was added by GDB. The remote
3877 server doesn't know about it. */
3878 return NULL;
3879
c76a8ea3
PA
3880 std::string &extra = get_remote_thread_info (tp)->extra;
3881
3882 /* If already have cached info, use it. */
3883 if (!extra.empty ())
3884 return extra.c_str ();
3885
4082afcc 3886 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3887 {
c76a8ea3
PA
3888 /* If we're using qXfer:threads:read, then the extra info is
3889 included in the XML. So if we didn't have anything cached,
3890 it's because there's really no extra info. */
3891 return NULL;
dc146f7c
VP
3892 }
3893
b80fafe3 3894 if (rs->use_threadextra_query)
9d1f7ab2 3895 {
82f73884
PA
3896 char *b = rs->buf;
3897 char *endb = rs->buf + get_remote_packet_size ();
3898
3899 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3900 b += strlen (b);
3901 write_ptid (b, endb, tp->ptid);
3902
2e9f7625 3903 putpkt (rs->buf);
6d820c5c 3904 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3905 if (rs->buf[0] != 0)
9d1f7ab2 3906 {
c76a8ea3
PA
3907 extra.resize (strlen (rs->buf) / 2);
3908 hex2bin (rs->buf, (gdb_byte *) &extra[0], extra.size ());
3909 return extra.c_str ();
9d1f7ab2 3910 }
0f71a2f6 3911 }
9d1f7ab2
MS
3912
3913 /* If the above query fails, fall back to the old method. */
b80fafe3 3914 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3915 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3916 | TAG_MOREDISPLAY | TAG_DISPLAY;
e38504b3 3917 int_to_threadref (&id, tp->ptid.lwp ());
9d1f7ab2
MS
3918 if (remote_get_threadinfo (&id, set, &threadinfo))
3919 if (threadinfo.active)
0f71a2f6 3920 {
9d1f7ab2 3921 if (*threadinfo.shortname)
c76a8ea3 3922 string_appendf (extra, " Name: %s", threadinfo.shortname);
9d1f7ab2 3923 if (*threadinfo.display)
c76a8ea3
PA
3924 {
3925 if (!extra.empty ())
3926 extra += ',';
3927 string_appendf (extra, " State: %s", threadinfo.display);
3928 }
9d1f7ab2 3929 if (*threadinfo.more_display)
c5aa993b 3930 {
c76a8ea3
PA
3931 if (!extra.empty ())
3932 extra += ',';
3933 string_appendf (extra, " Priority: %s", threadinfo.more_display);
c5aa993b 3934 }
c76a8ea3 3935 return extra.c_str ();
0f71a2f6 3936 }
9d1f7ab2 3937 return NULL;
0f71a2f6 3938}
c906108c 3939\f
c5aa993b 3940
f6ac5f3d
PA
3941bool
3942remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3943 struct static_tracepoint_marker *marker)
0fb4aa4b
PA
3944{
3945 struct remote_state *rs = get_remote_state ();
3946 char *p = rs->buf;
3947
bba74b36 3948 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3949 p += strlen (p);
3950 p += hexnumstr (p, addr);
3951 putpkt (rs->buf);
3952 getpkt (&rs->buf, &rs->buf_size, 0);
3953 p = rs->buf;
3954
3955 if (*p == 'E')
3956 error (_("Remote failure reply: %s"), p);
3957
3958 if (*p++ == 'm')
3959 {
256642e8 3960 parse_static_tracepoint_marker_definition (p, NULL, marker);
5d9310c4 3961 return true;
0fb4aa4b
PA
3962 }
3963
5d9310c4 3964 return false;
0fb4aa4b
PA
3965}
3966
f6ac5f3d
PA
3967std::vector<static_tracepoint_marker>
3968remote_target::static_tracepoint_markers_by_strid (const char *strid)
0fb4aa4b
PA
3969{
3970 struct remote_state *rs = get_remote_state ();
5d9310c4 3971 std::vector<static_tracepoint_marker> markers;
256642e8 3972 const char *p;
5d9310c4 3973 static_tracepoint_marker marker;
0fb4aa4b
PA
3974
3975 /* Ask for a first packet of static tracepoint marker
3976 definition. */
3977 putpkt ("qTfSTM");
3978 getpkt (&rs->buf, &rs->buf_size, 0);
3979 p = rs->buf;
3980 if (*p == 'E')
3981 error (_("Remote failure reply: %s"), p);
3982
0fb4aa4b
PA
3983 while (*p++ == 'm')
3984 {
0fb4aa4b
PA
3985 do
3986 {
5d9310c4 3987 parse_static_tracepoint_marker_definition (p, &p, &marker);
0fb4aa4b 3988
5d9310c4
SM
3989 if (strid == NULL || marker.str_id == strid)
3990 markers.push_back (std::move (marker));
0fb4aa4b
PA
3991 }
3992 while (*p++ == ','); /* comma-separated list */
3993 /* Ask for another packet of static tracepoint definition. */
3994 putpkt ("qTsSTM");
3995 getpkt (&rs->buf, &rs->buf_size, 0);
3996 p = rs->buf;
3997 }
3998
0fb4aa4b
PA
3999 return markers;
4000}
4001
4002\f
10760264
JB
4003/* Implement the to_get_ada_task_ptid function for the remote targets. */
4004
f6ac5f3d
PA
4005ptid_t
4006remote_target::get_ada_task_ptid (long lwp, long thread)
10760264 4007{
e99b03dc 4008 return ptid_t (inferior_ptid.pid (), lwp, 0);
10760264
JB
4009}
4010\f
4011
24b06219 4012/* Restart the remote side; this is an extended protocol operation. */
c906108c 4013
6b8edb51
PA
4014void
4015remote_target::extended_remote_restart ()
c906108c 4016{
d01949b6 4017 struct remote_state *rs = get_remote_state ();
c906108c
SS
4018
4019 /* Send the restart command; for reasons I don't understand the
4020 remote side really expects a number after the "R". */
ea9c271d 4021 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 4022 putpkt (rs->buf);
c906108c 4023
ad9a8f3f 4024 remote_fileio_reset ();
c906108c
SS
4025}
4026\f
4027/* Clean up connection to a remote debugger. */
4028
f6ac5f3d
PA
4029void
4030remote_target::close ()
c906108c 4031{
048094ac 4032 /* Make sure we leave stdin registered in the event loop. */
f6ac5f3d 4033 terminal_ours ();
ce5ce7ed 4034
ce5ce7ed 4035 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
4036 of all the inferiors and their threads we were controlling.
4037 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
4038 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 4039 inferior_ptid = null_ptid;
f67fd822 4040 discard_all_inferiors ();
ce5ce7ed 4041
6b8edb51
PA
4042 trace_reset_local_state ();
4043
4044 delete this;
4045}
4046
4047remote_target::~remote_target ()
4048{
4049 struct remote_state *rs = get_remote_state ();
4050
4051 /* Check for NULL because we may get here with a partially
4052 constructed target/connection. */
4053 if (rs->remote_desc == nullptr)
4054 return;
4055
4056 serial_close (rs->remote_desc);
4057
4058 /* We are destroying the remote target, so we should discard
f48ff2a7 4059 everything of this target. */
6b8edb51 4060 discard_pending_stop_replies_in_queue ();
74531fed 4061
6b8edb51
PA
4062 if (rs->remote_async_inferior_event_token)
4063 delete_async_event_handler (&rs->remote_async_inferior_event_token);
722247f1 4064
5965e028 4065 remote_notif_state_xfree (rs->notif_state);
c906108c
SS
4066}
4067
23860348 4068/* Query the remote side for the text, data and bss offsets. */
c906108c 4069
6b8edb51
PA
4070void
4071remote_target::get_offsets ()
c906108c 4072{
d01949b6 4073 struct remote_state *rs = get_remote_state ();
2e9f7625 4074 char *buf;
085dd6e6 4075 char *ptr;
31d99776
DJ
4076 int lose, num_segments = 0, do_sections, do_segments;
4077 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 4078 struct section_offsets *offs;
31d99776
DJ
4079 struct symfile_segment_data *data;
4080
4081 if (symfile_objfile == NULL)
4082 return;
c906108c
SS
4083
4084 putpkt ("qOffsets");
6d820c5c 4085 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4086 buf = rs->buf;
c906108c
SS
4087
4088 if (buf[0] == '\000')
4089 return; /* Return silently. Stub doesn't support
23860348 4090 this command. */
c906108c
SS
4091 if (buf[0] == 'E')
4092 {
8a3fe4f8 4093 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
4094 return;
4095 }
4096
4097 /* Pick up each field in turn. This used to be done with scanf, but
4098 scanf will make trouble if CORE_ADDR size doesn't match
4099 conversion directives correctly. The following code will work
4100 with any size of CORE_ADDR. */
4101 text_addr = data_addr = bss_addr = 0;
4102 ptr = buf;
4103 lose = 0;
4104
61012eef 4105 if (startswith (ptr, "Text="))
c906108c
SS
4106 {
4107 ptr += 5;
4108 /* Don't use strtol, could lose on big values. */
4109 while (*ptr && *ptr != ';')
4110 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 4111
61012eef 4112 if (startswith (ptr, ";Data="))
31d99776
DJ
4113 {
4114 ptr += 6;
4115 while (*ptr && *ptr != ';')
4116 data_addr = (data_addr << 4) + fromhex (*ptr++);
4117 }
4118 else
4119 lose = 1;
4120
61012eef 4121 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
4122 {
4123 ptr += 5;
4124 while (*ptr && *ptr != ';')
4125 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 4126
31d99776
DJ
4127 if (bss_addr != data_addr)
4128 warning (_("Target reported unsupported offsets: %s"), buf);
4129 }
4130 else
4131 lose = 1;
4132 }
61012eef 4133 else if (startswith (ptr, "TextSeg="))
c906108c 4134 {
31d99776
DJ
4135 ptr += 8;
4136 /* Don't use strtol, could lose on big values. */
c906108c 4137 while (*ptr && *ptr != ';')
31d99776
DJ
4138 text_addr = (text_addr << 4) + fromhex (*ptr++);
4139 num_segments = 1;
4140
61012eef 4141 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
4142 {
4143 ptr += 9;
4144 while (*ptr && *ptr != ';')
4145 data_addr = (data_addr << 4) + fromhex (*ptr++);
4146 num_segments++;
4147 }
c906108c
SS
4148 }
4149 else
4150 lose = 1;
4151
4152 if (lose)
8a3fe4f8 4153 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
4154 else if (*ptr != '\0')
4155 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 4156
802188a7 4157 offs = ((struct section_offsets *)
a39a16c4 4158 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 4159 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 4160 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 4161
31d99776
DJ
4162 data = get_symfile_segment_data (symfile_objfile->obfd);
4163 do_segments = (data != NULL);
4164 do_sections = num_segments == 0;
c906108c 4165
28c32713 4166 if (num_segments > 0)
31d99776 4167 {
31d99776
DJ
4168 segments[0] = text_addr;
4169 segments[1] = data_addr;
4170 }
28c32713
JB
4171 /* If we have two segments, we can still try to relocate everything
4172 by assuming that the .text and .data offsets apply to the whole
4173 text and data segments. Convert the offsets given in the packet
4174 to base addresses for symfile_map_offsets_to_segments. */
4175 else if (data && data->num_segments == 2)
4176 {
4177 segments[0] = data->segment_bases[0] + text_addr;
4178 segments[1] = data->segment_bases[1] + data_addr;
4179 num_segments = 2;
4180 }
8d385431
DJ
4181 /* If the object file has only one segment, assume that it is text
4182 rather than data; main programs with no writable data are rare,
4183 but programs with no code are useless. Of course the code might
4184 have ended up in the data segment... to detect that we would need
4185 the permissions here. */
4186 else if (data && data->num_segments == 1)
4187 {
4188 segments[0] = data->segment_bases[0] + text_addr;
4189 num_segments = 1;
4190 }
28c32713
JB
4191 /* There's no way to relocate by segment. */
4192 else
4193 do_segments = 0;
31d99776
DJ
4194
4195 if (do_segments)
4196 {
4197 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
4198 offs, num_segments, segments);
4199
4200 if (ret == 0 && !do_sections)
3e43a32a
MS
4201 error (_("Can not handle qOffsets TextSeg "
4202 "response with this symbol file"));
31d99776
DJ
4203
4204 if (ret > 0)
4205 do_sections = 0;
4206 }
c906108c 4207
9ef895d6
DJ
4208 if (data)
4209 free_symfile_segment_data (data);
31d99776
DJ
4210
4211 if (do_sections)
4212 {
4213 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
4214
3e43a32a
MS
4215 /* This is a temporary kludge to force data and bss to use the
4216 same offsets because that's what nlmconv does now. The real
4217 solution requires changes to the stub and remote.c that I
4218 don't have time to do right now. */
31d99776
DJ
4219
4220 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
4221 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
4222 }
c906108c
SS
4223
4224 objfile_relocate (symfile_objfile, offs);
4225}
4226
9a7071a8 4227/* Send interrupt_sequence to remote target. */
6b8edb51
PA
4228
4229void
4230remote_target::send_interrupt_sequence ()
9a7071a8 4231{
5d93a237
TT
4232 struct remote_state *rs = get_remote_state ();
4233
9a7071a8 4234 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 4235 remote_serial_write ("\x03", 1);
9a7071a8 4236 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 4237 serial_send_break (rs->remote_desc);
9a7071a8
JB
4238 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4239 {
5d93a237 4240 serial_send_break (rs->remote_desc);
c33e31fd 4241 remote_serial_write ("g", 1);
9a7071a8
JB
4242 }
4243 else
4244 internal_error (__FILE__, __LINE__,
4245 _("Invalid value for interrupt_sequence_mode: %s."),
4246 interrupt_sequence_mode);
4247}
4248
3405876a
PA
4249
4250/* If STOP_REPLY is a T stop reply, look for the "thread" register,
4251 and extract the PTID. Returns NULL_PTID if not found. */
4252
4253static ptid_t
4254stop_reply_extract_thread (char *stop_reply)
4255{
4256 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4257 {
256642e8 4258 const char *p;
3405876a
PA
4259
4260 /* Txx r:val ; r:val (...) */
4261 p = &stop_reply[3];
4262
4263 /* Look for "register" named "thread". */
4264 while (*p != '\0')
4265 {
256642e8 4266 const char *p1;
3405876a
PA
4267
4268 p1 = strchr (p, ':');
4269 if (p1 == NULL)
4270 return null_ptid;
4271
4272 if (strncmp (p, "thread", p1 - p) == 0)
4273 return read_ptid (++p1, &p);
4274
4275 p1 = strchr (p, ';');
4276 if (p1 == NULL)
4277 return null_ptid;
4278 p1++;
4279
4280 p = p1;
4281 }
4282 }
4283
4284 return null_ptid;
4285}
4286
b7ea362b
PA
4287/* Determine the remote side's current thread. If we have a stop
4288 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4289 "thread" register we can extract the current thread from. If not,
4290 ask the remote which is the current thread with qC. The former
4291 method avoids a roundtrip. */
4292
6b8edb51
PA
4293ptid_t
4294remote_target::get_current_thread (char *wait_status)
b7ea362b 4295{
6a49a997 4296 ptid_t ptid = null_ptid;
b7ea362b
PA
4297
4298 /* Note we don't use remote_parse_stop_reply as that makes use of
4299 the target architecture, which we haven't yet fully determined at
4300 this point. */
4301 if (wait_status != NULL)
4302 ptid = stop_reply_extract_thread (wait_status);
d7e15655 4303 if (ptid == null_ptid)
b7ea362b
PA
4304 ptid = remote_current_thread (inferior_ptid);
4305
4306 return ptid;
4307}
4308
49c62f2e
PA
4309/* Query the remote target for which is the current thread/process,
4310 add it to our tables, and update INFERIOR_PTID. The caller is
4311 responsible for setting the state such that the remote end is ready
3405876a
PA
4312 to return the current thread.
4313
4314 This function is called after handling the '?' or 'vRun' packets,
4315 whose response is a stop reply from which we can also try
4316 extracting the thread. If the target doesn't support the explicit
4317 qC query, we infer the current thread from that stop reply, passed
4318 in in WAIT_STATUS, which may be NULL. */
49c62f2e 4319
6b8edb51
PA
4320void
4321remote_target::add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
4322{
4323 struct remote_state *rs = get_remote_state ();
4324 int fake_pid_p = 0;
49c62f2e
PA
4325
4326 inferior_ptid = null_ptid;
4327
b7ea362b 4328 /* Now, if we have thread information, update inferior_ptid. */
87215ad1 4329 ptid_t curr_ptid = get_current_thread (wait_status);
3405876a 4330
87215ad1 4331 if (curr_ptid != null_ptid)
49c62f2e
PA
4332 {
4333 if (!remote_multi_process_p (rs))
4334 fake_pid_p = 1;
49c62f2e
PA
4335 }
4336 else
4337 {
4338 /* Without this, some commands which require an active target
4339 (such as kill) won't work. This variable serves (at least)
4340 double duty as both the pid of the target process (if it has
4341 such), and as a flag indicating that a target is active. */
87215ad1 4342 curr_ptid = magic_null_ptid;
49c62f2e
PA
4343 fake_pid_p = 1;
4344 }
4345
e99b03dc 4346 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
49c62f2e 4347
87215ad1
SDJ
4348 /* Add the main thread and switch to it. Don't try reading
4349 registers yet, since we haven't fetched the target description
4350 yet. */
4351 thread_info *tp = add_thread_silent (curr_ptid);
4352 switch_to_thread_no_regs (tp);
49c62f2e
PA
4353}
4354
6efcd9a8
PA
4355/* Print info about a thread that was found already stopped on
4356 connection. */
4357
4358static void
4359print_one_stopped_thread (struct thread_info *thread)
4360{
4361 struct target_waitstatus *ws = &thread->suspend.waitstatus;
4362
00431a78 4363 switch_to_thread (thread);
f2ffa92b 4364 thread->suspend.stop_pc = get_frame_pc (get_current_frame ());
6efcd9a8
PA
4365 set_current_sal_from_frame (get_current_frame ());
4366
4367 thread->suspend.waitstatus_pending_p = 0;
4368
4369 if (ws->kind == TARGET_WAITKIND_STOPPED)
4370 {
4371 enum gdb_signal sig = ws->value.sig;
4372
4373 if (signal_print_state (sig))
76727919 4374 gdb::observers::signal_received.notify (sig);
6efcd9a8 4375 }
76727919 4376 gdb::observers::normal_stop.notify (NULL, 1);
6efcd9a8
PA
4377}
4378
221e1a37
PA
4379/* Process all initial stop replies the remote side sent in response
4380 to the ? packet. These indicate threads that were already stopped
4381 on initial connection. We mark these threads as stopped and print
4382 their current frame before giving the user the prompt. */
4383
6b8edb51
PA
4384void
4385remote_target::process_initial_stop_replies (int from_tty)
221e1a37
PA
4386{
4387 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
4388 struct inferior *inf;
4389 struct thread_info *thread;
4390 struct thread_info *selected = NULL;
4391 struct thread_info *lowest_stopped = NULL;
4392 struct thread_info *first = NULL;
221e1a37
PA
4393
4394 /* Consume the initial pending events. */
4395 while (pending_stop_replies-- > 0)
4396 {
4397 ptid_t waiton_ptid = minus_one_ptid;
4398 ptid_t event_ptid;
4399 struct target_waitstatus ws;
4400 int ignore_event = 0;
6efcd9a8 4401 struct thread_info *thread;
221e1a37
PA
4402
4403 memset (&ws, 0, sizeof (ws));
4404 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4405 if (remote_debug)
4406 print_target_wait_results (waiton_ptid, event_ptid, &ws);
4407
4408 switch (ws.kind)
4409 {
4410 case TARGET_WAITKIND_IGNORE:
4411 case TARGET_WAITKIND_NO_RESUMED:
4412 case TARGET_WAITKIND_SIGNALLED:
4413 case TARGET_WAITKIND_EXITED:
4414 /* We shouldn't see these, but if we do, just ignore. */
4415 if (remote_debug)
4416 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4417 ignore_event = 1;
4418 break;
4419
4420 case TARGET_WAITKIND_EXECD:
4421 xfree (ws.value.execd_pathname);
4422 break;
4423 default:
4424 break;
4425 }
4426
4427 if (ignore_event)
4428 continue;
4429
6efcd9a8 4430 thread = find_thread_ptid (event_ptid);
221e1a37
PA
4431
4432 if (ws.kind == TARGET_WAITKIND_STOPPED)
4433 {
4434 enum gdb_signal sig = ws.value.sig;
4435
4436 /* Stubs traditionally report SIGTRAP as initial signal,
4437 instead of signal 0. Suppress it. */
4438 if (sig == GDB_SIGNAL_TRAP)
4439 sig = GDB_SIGNAL_0;
6efcd9a8
PA
4440 thread->suspend.stop_signal = sig;
4441 ws.value.sig = sig;
4442 }
221e1a37 4443
6efcd9a8
PA
4444 thread->suspend.waitstatus = ws;
4445
4446 if (ws.kind != TARGET_WAITKIND_STOPPED
4447 || ws.value.sig != GDB_SIGNAL_0)
4448 thread->suspend.waitstatus_pending_p = 1;
4449
4450 set_executing (event_ptid, 0);
4451 set_running (event_ptid, 0);
7aabaf9d 4452 get_remote_thread_info (thread)->vcont_resumed = 0;
6efcd9a8
PA
4453 }
4454
4455 /* "Notice" the new inferiors before anything related to
4456 registers/memory. */
4457 ALL_INFERIORS (inf)
4458 {
4459 if (inf->pid == 0)
4460 continue;
4461
4462 inf->needs_setup = 1;
4463
4464 if (non_stop)
4465 {
00431a78
PA
4466 thread = any_live_thread_of_inferior (inf);
4467 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
6efcd9a8
PA
4468 from_tty);
4469 }
4470 }
4471
4472 /* If all-stop on top of non-stop, pause all threads. Note this
4473 records the threads' stop pc, so must be done after "noticing"
4474 the inferiors. */
4475 if (!non_stop)
4476 {
4477 stop_all_threads ();
4478
4479 /* If all threads of an inferior were already stopped, we
4480 haven't setup the inferior yet. */
4481 ALL_INFERIORS (inf)
4482 {
4483 if (inf->pid == 0)
4484 continue;
221e1a37 4485
6efcd9a8
PA
4486 if (inf->needs_setup)
4487 {
00431a78 4488 thread = any_live_thread_of_inferior (inf);
6efcd9a8
PA
4489 switch_to_thread_no_regs (thread);
4490 setup_inferior (0);
4491 }
4492 }
221e1a37 4493 }
6efcd9a8
PA
4494
4495 /* Now go over all threads that are stopped, and print their current
4496 frame. If all-stop, then if there's a signalled thread, pick
4497 that as current. */
4498 ALL_NON_EXITED_THREADS (thread)
4499 {
6efcd9a8
PA
4500 if (first == NULL)
4501 first = thread;
4502
4503 if (!non_stop)
00431a78 4504 thread->set_running (false);
6efcd9a8
PA
4505 else if (thread->state != THREAD_STOPPED)
4506 continue;
4507
6efcd9a8
PA
4508 if (selected == NULL
4509 && thread->suspend.waitstatus_pending_p)
4510 selected = thread;
4511
5d5658a1
PA
4512 if (lowest_stopped == NULL
4513 || thread->inf->num < lowest_stopped->inf->num
4514 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
4515 lowest_stopped = thread;
4516
4517 if (non_stop)
4518 print_one_stopped_thread (thread);
4519 }
4520
4521 /* In all-stop, we only print the status of one thread, and leave
4522 others with their status pending. */
4523 if (!non_stop)
4524 {
4525 thread = selected;
4526 if (thread == NULL)
4527 thread = lowest_stopped;
4528 if (thread == NULL)
4529 thread = first;
4530
4531 print_one_stopped_thread (thread);
4532 }
4533
4534 /* For "info program". */
4535 thread = inferior_thread ();
4536 if (thread->state == THREAD_STOPPED)
4537 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
4538}
4539
048094ac
PA
4540/* Start the remote connection and sync state. */
4541
f6ac5f3d
PA
4542void
4543remote_target::start_remote (int from_tty, int extended_p)
c906108c 4544{
c8d104ad
PA
4545 struct remote_state *rs = get_remote_state ();
4546 struct packet_config *noack_config;
2d717e4f 4547 char *wait_status = NULL;
8621d6a9 4548
048094ac
PA
4549 /* Signal other parts that we're going through the initial setup,
4550 and so things may not be stable yet. E.g., we don't try to
4551 install tracepoints until we've relocated symbols. Also, a
4552 Ctrl-C before we're connected and synced up can't interrupt the
4553 target. Instead, it offers to drop the (potentially wedged)
4554 connection. */
4555 rs->starting_up = 1;
4556
522002f9 4557 QUIT;
c906108c 4558
9a7071a8
JB
4559 if (interrupt_on_connect)
4560 send_interrupt_sequence ();
4561
57e12211 4562 /* Ack any packet which the remote side has already sent. */
048094ac 4563 remote_serial_write ("+", 1);
1e51243a 4564
c8d104ad
PA
4565 /* The first packet we send to the target is the optional "supported
4566 packets" request. If the target can answer this, it will tell us
4567 which later probes to skip. */
4568 remote_query_supported ();
4569
d914c394 4570 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 4571 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
f6ac5f3d 4572 set_permissions ();
d914c394 4573
57809e5e
JK
4574 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4575 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4576 as a reply to known packet. For packet "vFile:setfs:" it is an
4577 invalid reply and GDB would return error in
4578 remote_hostio_set_filesystem, making remote files access impossible.
4579 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4580 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4581 {
4582 const char v_mustreplyempty[] = "vMustReplyEmpty";
4583
4584 putpkt (v_mustreplyempty);
4585 getpkt (&rs->buf, &rs->buf_size, 0);
4586 if (strcmp (rs->buf, "OK") == 0)
4587 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4588 else if (strcmp (rs->buf, "") != 0)
4589 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4590 rs->buf);
4591 }
4592
c8d104ad
PA
4593 /* Next, we possibly activate noack mode.
4594
4595 If the QStartNoAckMode packet configuration is set to AUTO,
4596 enable noack mode if the stub reported a wish for it with
4597 qSupported.
4598
4599 If set to TRUE, then enable noack mode even if the stub didn't
4600 report it in qSupported. If the stub doesn't reply OK, the
4601 session ends with an error.
4602
4603 If FALSE, then don't activate noack mode, regardless of what the
4604 stub claimed should be the default with qSupported. */
4605
4606 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 4607 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
4608 {
4609 putpkt ("QStartNoAckMode");
4610 getpkt (&rs->buf, &rs->buf_size, 0);
4611 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4612 rs->noack_mode = 1;
4613 }
4614
04bd08de 4615 if (extended_p)
5fe04517
PA
4616 {
4617 /* Tell the remote that we are using the extended protocol. */
4618 putpkt ("!");
4619 getpkt (&rs->buf, &rs->buf_size, 0);
4620 }
4621
9b224c5e
PA
4622 /* Let the target know which signals it is allowed to pass down to
4623 the program. */
4624 update_signals_program_target ();
4625
d962ef82
DJ
4626 /* Next, if the target can specify a description, read it. We do
4627 this before anything involving memory or registers. */
4628 target_find_description ();
4629
6c95b8df
PA
4630 /* Next, now that we know something about the target, update the
4631 address spaces in the program spaces. */
4632 update_address_spaces ();
4633
50c71eaf
PA
4634 /* On OSs where the list of libraries is global to all
4635 processes, we fetch them early. */
f5656ead 4636 if (gdbarch_has_global_solist (target_gdbarch ()))
e696b3ad 4637 solib_add (NULL, from_tty, auto_solib_add);
50c71eaf 4638
6efcd9a8 4639 if (target_is_non_stop_p ())
74531fed 4640 {
4082afcc 4641 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
4642 error (_("Non-stop mode requested, but remote "
4643 "does not support non-stop"));
74531fed
PA
4644
4645 putpkt ("QNonStop:1");
4646 getpkt (&rs->buf, &rs->buf_size, 0);
4647
4648 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4649 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
4650
4651 /* Find about threads and processes the stub is already
4652 controlling. We default to adding them in the running state.
4653 The '?' query below will then tell us about which threads are
4654 stopped. */
f6ac5f3d 4655 this->update_thread_list ();
74531fed 4656 }
4082afcc 4657 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4658 {
4659 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4660 Request it explicitly. */
74531fed
PA
4661 putpkt ("QNonStop:0");
4662 getpkt (&rs->buf, &rs->buf_size, 0);
4663
4664 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4665 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
4666 }
4667
a0743c90
YQ
4668 /* Upload TSVs regardless of whether the target is running or not. The
4669 remote stub, such as GDBserver, may have some predefined or builtin
4670 TSVs, even if the target is not running. */
f6ac5f3d 4671 if (get_trace_status (current_trace_status ()) != -1)
a0743c90
YQ
4672 {
4673 struct uploaded_tsv *uploaded_tsvs = NULL;
4674
f6ac5f3d 4675 upload_trace_state_variables (&uploaded_tsvs);
a0743c90
YQ
4676 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4677 }
4678
2d717e4f
DJ
4679 /* Check whether the target is running now. */
4680 putpkt ("?");
4681 getpkt (&rs->buf, &rs->buf_size, 0);
4682
6efcd9a8 4683 if (!target_is_non_stop_p ())
2d717e4f 4684 {
74531fed 4685 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4686 {
04bd08de 4687 if (!extended_p)
74531fed 4688 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4689
4690 /* We're connected, but not running. Drop out before we
4691 call start_remote. */
e278ad5b 4692 rs->starting_up = 0;
c35b1492 4693 return;
2d717e4f
DJ
4694 }
4695 else
74531fed 4696 {
74531fed 4697 /* Save the reply for later. */
224c3ddb 4698 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
4699 strcpy (wait_status, rs->buf);
4700 }
4701
b7ea362b 4702 /* Fetch thread list. */
e8032dde 4703 target_update_thread_list ();
b7ea362b 4704
74531fed
PA
4705 /* Let the stub know that we want it to return the thread. */
4706 set_continue_thread (minus_one_ptid);
4707
b7ea362b
PA
4708 if (thread_count () == 0)
4709 {
4710 /* Target has no concept of threads at all. GDB treats
4711 non-threaded target as single-threaded; add a main
4712 thread. */
4713 add_current_inferior_and_thread (wait_status);
4714 }
4715 else
4716 {
4717 /* We have thread information; select the thread the target
4718 says should be current. If we're reconnecting to a
4719 multi-threaded program, this will ideally be the thread
4720 that last reported an event before GDB disconnected. */
4721 inferior_ptid = get_current_thread (wait_status);
d7e15655 4722 if (inferior_ptid == null_ptid)
b7ea362b
PA
4723 {
4724 /* Odd... The target was able to list threads, but not
4725 tell us which thread was current (no "thread"
4726 register in T stop reply?). Just pick the first
4727 thread in the thread list then. */
c9f35b34
KB
4728
4729 if (remote_debug)
4730 fprintf_unfiltered (gdb_stdlog,
4731 "warning: couldn't determine remote "
4732 "current thread; picking first in list.\n");
4733
b7ea362b
PA
4734 inferior_ptid = thread_list->ptid;
4735 }
4736 }
74531fed 4737
6e586cc5
YQ
4738 /* init_wait_for_inferior should be called before get_offsets in order
4739 to manage `inserted' flag in bp loc in a correct state.
4740 breakpoint_init_inferior, called from init_wait_for_inferior, set
4741 `inserted' flag to 0, while before breakpoint_re_set, called from
4742 start_remote, set `inserted' flag to 1. In the initialization of
4743 inferior, breakpoint_init_inferior should be called first, and then
4744 breakpoint_re_set can be called. If this order is broken, state of
4745 `inserted' flag is wrong, and cause some problems on breakpoint
4746 manipulation. */
4747 init_wait_for_inferior ();
4748
74531fed
PA
4749 get_offsets (); /* Get text, data & bss offsets. */
4750
d962ef82
DJ
4751 /* If we could not find a description using qXfer, and we know
4752 how to do it some other way, try again. This is not
4753 supported for non-stop; it could be, but it is tricky if
4754 there are no stopped threads when we connect. */
f6ac5f3d 4755 if (remote_read_description_p (this)
f5656ead 4756 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4757 {
4758 target_clear_description ();
4759 target_find_description ();
4760 }
4761
74531fed
PA
4762 /* Use the previously fetched status. */
4763 gdb_assert (wait_status != NULL);
4764 strcpy (rs->buf, wait_status);
4765 rs->cached_wait_status = 1;
4766
f6ac5f3d 4767 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4768 }
4769 else
4770 {
68c97600
PA
4771 /* Clear WFI global state. Do this before finding about new
4772 threads and inferiors, and setting the current inferior.
4773 Otherwise we would clear the proceed status of the current
4774 inferior when we want its stop_soon state to be preserved
4775 (see notice_new_inferior). */
4776 init_wait_for_inferior ();
4777
74531fed
PA
4778 /* In non-stop, we will either get an "OK", meaning that there
4779 are no stopped threads at this time; or, a regular stop
4780 reply. In the latter case, there may be more than one thread
4781 stopped --- we pull them all out using the vStopped
4782 mechanism. */
4783 if (strcmp (rs->buf, "OK") != 0)
4784 {
722247f1 4785 struct notif_client *notif = &notif_client_stop;
2d717e4f 4786
722247f1
YQ
4787 /* remote_notif_get_pending_replies acks this one, and gets
4788 the rest out. */
f48ff2a7 4789 rs->notif_state->pending_event[notif_client_stop.id]
6b8edb51 4790 = remote_notif_parse (this, notif, rs->buf);
722247f1 4791 remote_notif_get_pending_events (notif);
74531fed 4792 }
2d717e4f 4793
74531fed
PA
4794 if (thread_count () == 0)
4795 {
04bd08de 4796 if (!extended_p)
74531fed 4797 error (_("The target is not running (try extended-remote?)"));
82f73884 4798
c35b1492
PA
4799 /* We're connected, but not running. Drop out before we
4800 call start_remote. */
e278ad5b 4801 rs->starting_up = 0;
c35b1492
PA
4802 return;
4803 }
74531fed 4804
74531fed
PA
4805 /* In non-stop mode, any cached wait status will be stored in
4806 the stop reply queue. */
4807 gdb_assert (wait_status == NULL);
f0223081 4808
2455069d 4809 /* Report all signals during attach/startup. */
f6ac5f3d 4810 pass_signals (0, NULL);
221e1a37
PA
4811
4812 /* If there are already stopped threads, mark them stopped and
4813 report their stops before giving the prompt to the user. */
6efcd9a8 4814 process_initial_stop_replies (from_tty);
221e1a37
PA
4815
4816 if (target_can_async_p ())
4817 target_async (1);
74531fed 4818 }
c8d104ad 4819
c8d104ad
PA
4820 /* If we connected to a live target, do some additional setup. */
4821 if (target_has_execution)
4822 {
f4ccffad 4823 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4824 remote_check_symbols ();
c8d104ad 4825 }
50c71eaf 4826
d5551862
SS
4827 /* Possibly the target has been engaged in a trace run started
4828 previously; find out where things are at. */
f6ac5f3d 4829 if (get_trace_status (current_trace_status ()) != -1)
d5551862 4830 {
00bf0b85 4831 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4832
00bf0b85
SS
4833 if (current_trace_status ()->running)
4834 printf_filtered (_("Trace is already running on the target.\n"));
4835
f6ac5f3d 4836 upload_tracepoints (&uploaded_tps);
00bf0b85
SS
4837
4838 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4839 }
4840
c0272db5
TW
4841 /* Possibly the target has been engaged in a btrace record started
4842 previously; find out where things are at. */
4843 remote_btrace_maybe_reopen ();
4844
1e51243a
PA
4845 /* The thread and inferior lists are now synchronized with the
4846 target, our symbols have been relocated, and we're merged the
4847 target's tracepoints with ours. We're done with basic start
4848 up. */
4849 rs->starting_up = 0;
4850
a25a5a45
PA
4851 /* Maybe breakpoints are global and need to be inserted now. */
4852 if (breakpoints_should_be_inserted_now ())
50c71eaf 4853 insert_breakpoints ();
c906108c
SS
4854}
4855
4856/* Open a connection to a remote debugger.
4857 NAME is the filename used for communication. */
4858
f6ac5f3d
PA
4859void
4860remote_target::open (const char *name, int from_tty)
c906108c 4861{
f6ac5f3d 4862 open_1 (name, from_tty, 0);
43ff13b4
JM
4863}
4864
c906108c
SS
4865/* Open a connection to a remote debugger using the extended
4866 remote gdb protocol. NAME is the filename used for communication. */
4867
f6ac5f3d
PA
4868void
4869extended_remote_target::open (const char *name, int from_tty)
c906108c 4870{
f6ac5f3d 4871 open_1 (name, from_tty, 1 /*extended_p */);
43ff13b4
JM
4872}
4873
ca4f7f8b
PA
4874/* Reset all packets back to "unknown support". Called when opening a
4875 new connection to a remote target. */
c906108c 4876
d471ea57 4877static void
ca4f7f8b 4878reset_all_packet_configs_support (void)
d471ea57
AC
4879{
4880 int i;
a744cf53 4881
444abaca 4882 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4883 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4884}
4885
ca4f7f8b
PA
4886/* Initialize all packet configs. */
4887
4888static void
4889init_all_packet_configs (void)
4890{
4891 int i;
4892
4893 for (i = 0; i < PACKET_MAX; i++)
4894 {
4895 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4896 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4897 }
4898}
4899
23860348 4900/* Symbol look-up. */
dc8acb97 4901
6b8edb51
PA
4902void
4903remote_target::remote_check_symbols ()
dc8acb97
MS
4904{
4905 char *msg, *reply, *tmp;
dc8acb97 4906 int end;
28170b88 4907 long reply_size;
a5c0808e 4908 struct cleanup *old_chain;
dc8acb97 4909
63154eca
PA
4910 /* The remote side has no concept of inferiors that aren't running
4911 yet, it only knows about running processes. If we're connected
4912 but our current inferior is not running, we should not invite the
4913 remote target to request symbol lookups related to its
4914 (unrelated) current process. */
4915 if (!target_has_execution)
4916 return;
4917
4082afcc 4918 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4919 return;
4920
63154eca
PA
4921 /* Make sure the remote is pointing at the right process. Note
4922 there's no way to select "no process". */
3c9c4b83
PA
4923 set_general_process ();
4924
6d820c5c
DJ
4925 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4926 because we need both at the same time. */
224c3ddb 4927 msg = (char *) xmalloc (get_remote_packet_size ());
a5c0808e 4928 old_chain = make_cleanup (xfree, msg);
28170b88
MK
4929 reply = (char *) xmalloc (get_remote_packet_size ());
4930 make_cleanup (free_current_contents, &reply);
4931 reply_size = get_remote_packet_size ();
6d820c5c 4932
23860348 4933 /* Invite target to request symbol lookups. */
dc8acb97
MS
4934
4935 putpkt ("qSymbol::");
28170b88
MK
4936 getpkt (&reply, &reply_size, 0);
4937 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
dc8acb97 4938
61012eef 4939 while (startswith (reply, "qSymbol:"))
dc8acb97 4940 {
77e371c0
TT
4941 struct bound_minimal_symbol sym;
4942
dc8acb97 4943 tmp = &reply[8];
cfd77fa1 4944 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4945 msg[end] = '\0';
4946 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4947 if (sym.minsym == NULL)
ea9c271d 4948 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4949 else
2bbe3cc1 4950 {
f5656ead 4951 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4952 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4953
4954 /* If this is a function address, return the start of code
4955 instead of any data function descriptor. */
f5656ead 4956 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1 4957 sym_addr,
8b88a78e 4958 current_top_target ());
2bbe3cc1
DJ
4959
4960 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4961 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4962 }
4963
dc8acb97 4964 putpkt (msg);
28170b88 4965 getpkt (&reply, &reply_size, 0);
dc8acb97 4966 }
a5c0808e
PA
4967
4968 do_cleanups (old_chain);
dc8acb97
MS
4969}
4970
9db8d71f 4971static struct serial *
baa336ce 4972remote_serial_open (const char *name)
9db8d71f
DJ
4973{
4974 static int udp_warning = 0;
4975
4976 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4977 of in ser-tcp.c, because it is the remote protocol assuming that the
4978 serial connection is reliable and not the serial connection promising
4979 to be. */
61012eef 4980 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4981 {
3e43a32a
MS
4982 warning (_("The remote protocol may be unreliable over UDP.\n"
4983 "Some events may be lost, rendering further debugging "
4984 "impossible."));
9db8d71f
DJ
4985 udp_warning = 1;
4986 }
4987
4988 return serial_open (name);
4989}
4990
d914c394
SS
4991/* Inform the target of our permission settings. The permission flags
4992 work without this, but if the target knows the settings, it can do
4993 a couple things. First, it can add its own check, to catch cases
4994 that somehow manage to get by the permissions checks in target
4995 methods. Second, if the target is wired to disallow particular
4996 settings (for instance, a system in the field that is not set up to
4997 be able to stop at a breakpoint), it can object to any unavailable
4998 permissions. */
4999
5000void
f6ac5f3d 5001remote_target::set_permissions ()
d914c394
SS
5002{
5003 struct remote_state *rs = get_remote_state ();
5004
bba74b36
YQ
5005 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
5006 "WriteReg:%x;WriteMem:%x;"
5007 "InsertBreak:%x;InsertTrace:%x;"
5008 "InsertFastTrace:%x;Stop:%x",
5009 may_write_registers, may_write_memory,
5010 may_insert_breakpoints, may_insert_tracepoints,
5011 may_insert_fast_tracepoints, may_stop);
d914c394
SS
5012 putpkt (rs->buf);
5013 getpkt (&rs->buf, &rs->buf_size, 0);
5014
5015 /* If the target didn't like the packet, warn the user. Do not try
5016 to undo the user's settings, that would just be maddening. */
5017 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 5018 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
5019}
5020
be2a5f71
DJ
5021/* This type describes each known response to the qSupported
5022 packet. */
5023struct protocol_feature
5024{
5025 /* The name of this protocol feature. */
5026 const char *name;
5027
5028 /* The default for this protocol feature. */
5029 enum packet_support default_support;
5030
5031 /* The function to call when this feature is reported, or after
5032 qSupported processing if the feature is not supported.
5033 The first argument points to this structure. The second
5034 argument indicates whether the packet requested support be
5035 enabled, disabled, or probed (or the default, if this function
5036 is being called at the end of processing and this feature was
5037 not reported). The third argument may be NULL; if not NULL, it
5038 is a NUL-terminated string taken from the packet following
5039 this feature's name and an equals sign. */
6b8edb51
PA
5040 void (*func) (remote_target *remote, const struct protocol_feature *,
5041 enum packet_support, const char *);
be2a5f71
DJ
5042
5043 /* The corresponding packet for this feature. Only used if
5044 FUNC is remote_supported_packet. */
5045 int packet;
5046};
5047
be2a5f71 5048static void
6b8edb51
PA
5049remote_supported_packet (remote_target *remote,
5050 const struct protocol_feature *feature,
be2a5f71
DJ
5051 enum packet_support support,
5052 const char *argument)
5053{
5054 if (argument)
5055 {
5056 warning (_("Remote qSupported response supplied an unexpected value for"
5057 " \"%s\"."), feature->name);
5058 return;
5059 }
5060
4082afcc 5061 remote_protocol_packets[feature->packet].support = support;
be2a5f71 5062}
be2a5f71 5063
6b8edb51
PA
5064void
5065remote_target::remote_packet_size (const protocol_feature *feature,
5066 enum packet_support support, const char *value)
be2a5f71
DJ
5067{
5068 struct remote_state *rs = get_remote_state ();
5069
5070 int packet_size;
5071 char *value_end;
5072
5073 if (support != PACKET_ENABLE)
5074 return;
5075
5076 if (value == NULL || *value == '\0')
5077 {
5078 warning (_("Remote target reported \"%s\" without a size."),
5079 feature->name);
5080 return;
5081 }
5082
5083 errno = 0;
5084 packet_size = strtol (value, &value_end, 16);
5085 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5086 {
5087 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5088 feature->name, value);
5089 return;
5090 }
5091
be2a5f71
DJ
5092 /* Record the new maximum packet size. */
5093 rs->explicit_packet_size = packet_size;
5094}
5095
6b8edb51
PA
5096void
5097remote_packet_size (remote_target *remote, const protocol_feature *feature,
5098 enum packet_support support, const char *value)
5099{
5100 remote->remote_packet_size (feature, support, value);
5101}
5102
dc473cfb 5103static const struct protocol_feature remote_protocol_features[] = {
0876f84a 5104 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 5105 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 5106 PACKET_qXfer_auxv },
c78fa86a
GB
5107 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5108 PACKET_qXfer_exec_file },
23181151
DJ
5109 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5110 PACKET_qXfer_features },
cfa9d6d9
DJ
5111 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5112 PACKET_qXfer_libraries },
2268b414
JK
5113 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5114 PACKET_qXfer_libraries_svr4 },
ced63ec0 5115 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 5116 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 5117 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 5118 PACKET_qXfer_memory_map },
4de6483e
UW
5119 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
5120 PACKET_qXfer_spu_read },
5121 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
5122 PACKET_qXfer_spu_write },
07e059b5
VP
5123 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5124 PACKET_qXfer_osdata },
dc146f7c
VP
5125 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5126 PACKET_qXfer_threads },
b3b9301e
PA
5127 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5128 PACKET_qXfer_traceframe_info },
89be2091
DJ
5129 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5130 PACKET_QPassSignals },
82075af2
JS
5131 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5132 PACKET_QCatchSyscalls },
9b224c5e
PA
5133 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5134 PACKET_QProgramSignals },
bc3b087d
SDJ
5135 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5136 PACKET_QSetWorkingDir },
aefd8b33
SDJ
5137 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5138 PACKET_QStartupWithShell },
0a2dde4a
SDJ
5139 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5140 PACKET_QEnvironmentHexEncoded },
5141 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5142 PACKET_QEnvironmentReset },
5143 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5144 PACKET_QEnvironmentUnset },
a6f3e723
SL
5145 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5146 PACKET_QStartNoAckMode },
4082afcc
PA
5147 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5148 PACKET_multiprocess_feature },
5149 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
5150 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5151 PACKET_qXfer_siginfo_read },
5152 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5153 PACKET_qXfer_siginfo_write },
4082afcc 5154 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 5155 PACKET_ConditionalTracepoints },
4082afcc 5156 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 5157 PACKET_ConditionalBreakpoints },
4082afcc 5158 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 5159 PACKET_BreakpointCommands },
4082afcc 5160 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 5161 PACKET_FastTracepoints },
4082afcc 5162 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 5163 PACKET_StaticTracepoints },
4082afcc 5164 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 5165 PACKET_InstallInTrace},
4082afcc
PA
5166 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5167 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
5168 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5169 PACKET_bc },
5170 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5171 PACKET_bs },
409873ef
SS
5172 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5173 PACKET_TracepointSource },
d914c394
SS
5174 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5175 PACKET_QAllow },
4082afcc
PA
5176 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5177 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
5178 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5179 PACKET_qXfer_fdpic },
169081d0
TG
5180 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5181 PACKET_qXfer_uib },
03583c20
UW
5182 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5183 PACKET_QDisableRandomization },
d1feda86 5184 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
5185 { "QTBuffer:size", PACKET_DISABLE,
5186 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 5187 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
5188 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5189 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 5190 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 5191 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
5192 PACKET_qXfer_btrace },
5193 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
5194 PACKET_qXfer_btrace_conf },
5195 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
5196 PACKET_Qbtrace_conf_bts_size },
5197 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 5198 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
5199 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5200 PACKET_fork_event_feature },
5201 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5202 PACKET_vfork_event_feature },
94585166
DB
5203 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5204 PACKET_exec_event_feature },
b20a6524 5205 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 5206 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
5207 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5208 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 5209 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
be2a5f71
DJ
5210};
5211
c8d5aac9
L
5212static char *remote_support_xml;
5213
5214/* Register string appended to "xmlRegisters=" in qSupported query. */
5215
5216void
6e39997a 5217register_remote_support_xml (const char *xml)
c8d5aac9
L
5218{
5219#if defined(HAVE_LIBEXPAT)
5220 if (remote_support_xml == NULL)
c4f7c687 5221 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
5222 else
5223 {
5224 char *copy = xstrdup (remote_support_xml + 13);
5225 char *p = strtok (copy, ",");
5226
5227 do
5228 {
5229 if (strcmp (p, xml) == 0)
5230 {
5231 /* already there */
5232 xfree (copy);
5233 return;
5234 }
5235 }
5236 while ((p = strtok (NULL, ",")) != NULL);
5237 xfree (copy);
5238
94b0dee1
PA
5239 remote_support_xml = reconcat (remote_support_xml,
5240 remote_support_xml, ",", xml,
5241 (char *) NULL);
c8d5aac9
L
5242 }
5243#endif
5244}
5245
69b6ecb0
TT
5246static void
5247remote_query_supported_append (std::string *msg, const char *append)
c8d5aac9 5248{
69b6ecb0
TT
5249 if (!msg->empty ())
5250 msg->append (";");
5251 msg->append (append);
c8d5aac9
L
5252}
5253
6b8edb51
PA
5254void
5255remote_target::remote_query_supported ()
be2a5f71
DJ
5256{
5257 struct remote_state *rs = get_remote_state ();
5258 char *next;
5259 int i;
5260 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5261
5262 /* The packet support flags are handled differently for this packet
5263 than for most others. We treat an error, a disabled packet, and
5264 an empty response identically: any features which must be reported
5265 to be used will be automatically disabled. An empty buffer
5266 accomplishes this, since that is also the representation for a list
5267 containing no features. */
5268
5269 rs->buf[0] = 0;
4082afcc 5270 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 5271 {
69b6ecb0 5272 std::string q;
c8d5aac9 5273
73b8c1fd 5274 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5275 remote_query_supported_append (&q, "multiprocess+");
c8d5aac9 5276
f7e6eed5 5277 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5278 remote_query_supported_append (&q, "swbreak+");
f7e6eed5 5279 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5280 remote_query_supported_append (&q, "hwbreak+");
f7e6eed5 5281
69b6ecb0 5282 remote_query_supported_append (&q, "qRelocInsn+");
dde08ee1 5283
8020350c
DB
5284 if (packet_set_cmd_state (PACKET_fork_event_feature)
5285 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5286 remote_query_supported_append (&q, "fork-events+");
8020350c
DB
5287 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5288 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5289 remote_query_supported_append (&q, "vfork-events+");
8020350c
DB
5290 if (packet_set_cmd_state (PACKET_exec_event_feature)
5291 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5292 remote_query_supported_append (&q, "exec-events+");
89245bc0 5293
750ce8d1 5294 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5295 remote_query_supported_append (&q, "vContSupported+");
750ce8d1 5296
65706a29 5297 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5298 remote_query_supported_append (&q, "QThreadEvents+");
65706a29 5299
f2faf941 5300 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5301 remote_query_supported_append (&q, "no-resumed+");
f2faf941 5302
b35d5edb
PA
5303 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5304 the qSupported:xmlRegisters=i386 handling. */
7cc244de
PA
5305 if (remote_support_xml != NULL
5306 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
69b6ecb0 5307 remote_query_supported_append (&q, remote_support_xml);
82f73884 5308
69b6ecb0
TT
5309 q = "qSupported:" + q;
5310 putpkt (q.c_str ());
94b0dee1 5311
be2a5f71
DJ
5312 getpkt (&rs->buf, &rs->buf_size, 0);
5313
5314 /* If an error occured, warn, but do not return - just reset the
5315 buffer to empty and go on to disable features. */
5316 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5317 == PACKET_ERROR)
5318 {
5319 warning (_("Remote failure reply: %s"), rs->buf);
5320 rs->buf[0] = 0;
5321 }
5322 }
5323
5324 memset (seen, 0, sizeof (seen));
5325
5326 next = rs->buf;
5327 while (*next)
5328 {
5329 enum packet_support is_supported;
5330 char *p, *end, *name_end, *value;
5331
5332 /* First separate out this item from the rest of the packet. If
5333 there's another item after this, we overwrite the separator
5334 (terminated strings are much easier to work with). */
5335 p = next;
5336 end = strchr (p, ';');
5337 if (end == NULL)
5338 {
5339 end = p + strlen (p);
5340 next = end;
5341 }
5342 else
5343 {
89be2091
DJ
5344 *end = '\0';
5345 next = end + 1;
5346
be2a5f71
DJ
5347 if (end == p)
5348 {
5349 warning (_("empty item in \"qSupported\" response"));
5350 continue;
5351 }
be2a5f71
DJ
5352 }
5353
5354 name_end = strchr (p, '=');
5355 if (name_end)
5356 {
5357 /* This is a name=value entry. */
5358 is_supported = PACKET_ENABLE;
5359 value = name_end + 1;
5360 *name_end = '\0';
5361 }
5362 else
5363 {
5364 value = NULL;
5365 switch (end[-1])
5366 {
5367 case '+':
5368 is_supported = PACKET_ENABLE;
5369 break;
5370
5371 case '-':
5372 is_supported = PACKET_DISABLE;
5373 break;
5374
5375 case '?':
5376 is_supported = PACKET_SUPPORT_UNKNOWN;
5377 break;
5378
5379 default:
3e43a32a
MS
5380 warning (_("unrecognized item \"%s\" "
5381 "in \"qSupported\" response"), p);
be2a5f71
DJ
5382 continue;
5383 }
5384 end[-1] = '\0';
5385 }
5386
5387 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5388 if (strcmp (remote_protocol_features[i].name, p) == 0)
5389 {
5390 const struct protocol_feature *feature;
5391
5392 seen[i] = 1;
5393 feature = &remote_protocol_features[i];
6b8edb51 5394 feature->func (this, feature, is_supported, value);
be2a5f71
DJ
5395 break;
5396 }
5397 }
5398
5399 /* If we increased the packet size, make sure to increase the global
5400 buffer size also. We delay this until after parsing the entire
5401 qSupported packet, because this is the same buffer we were
5402 parsing. */
5403 if (rs->buf_size < rs->explicit_packet_size)
5404 {
5405 rs->buf_size = rs->explicit_packet_size;
224c3ddb 5406 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
be2a5f71
DJ
5407 }
5408
5409 /* Handle the defaults for unmentioned features. */
5410 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5411 if (!seen[i])
5412 {
5413 const struct protocol_feature *feature;
5414
5415 feature = &remote_protocol_features[i];
6b8edb51 5416 feature->func (this, feature, feature->default_support, NULL);
be2a5f71
DJ
5417 }
5418}
5419
048094ac
PA
5420/* Serial QUIT handler for the remote serial descriptor.
5421
5422 Defers handling a Ctrl-C until we're done with the current
5423 command/response packet sequence, unless:
5424
5425 - We're setting up the connection. Don't send a remote interrupt
5426 request, as we're not fully synced yet. Quit immediately
5427 instead.
5428
5429 - The target has been resumed in the foreground
223ffa71 5430 (target_terminal::is_ours is false) with a synchronous resume
048094ac
PA
5431 packet, and we're blocked waiting for the stop reply, thus a
5432 Ctrl-C should be immediately sent to the target.
5433
5434 - We get a second Ctrl-C while still within the same serial read or
5435 write. In that case the serial is seemingly wedged --- offer to
5436 quit/disconnect.
5437
5438 - We see a second Ctrl-C without target response, after having
5439 previously interrupted the target. In that case the target/stub
5440 is probably wedged --- offer to quit/disconnect.
5441*/
5442
6b8edb51
PA
5443void
5444remote_target::remote_serial_quit_handler ()
048094ac
PA
5445{
5446 struct remote_state *rs = get_remote_state ();
5447
5448 if (check_quit_flag ())
5449 {
5450 /* If we're starting up, we're not fully synced yet. Quit
5451 immediately. */
5452 if (rs->starting_up)
5453 quit ();
5454 else if (rs->got_ctrlc_during_io)
5455 {
5456 if (query (_("The target is not responding to GDB commands.\n"
5457 "Stop debugging it? ")))
5458 remote_unpush_and_throw ();
5459 }
5460 /* If ^C has already been sent once, offer to disconnect. */
223ffa71 5461 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
048094ac
PA
5462 interrupt_query ();
5463 /* All-stop protocol, and blocked waiting for stop reply. Send
5464 an interrupt request. */
223ffa71 5465 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
e671cd59 5466 target_interrupt ();
048094ac
PA
5467 else
5468 rs->got_ctrlc_during_io = 1;
5469 }
5470}
5471
6b8edb51
PA
5472/* The remote_target that is current while the quit handler is
5473 overridden with remote_serial_quit_handler. */
5474static remote_target *curr_quit_handler_target;
5475
5476static void
5477remote_serial_quit_handler ()
5478{
5479 curr_quit_handler_target->remote_serial_quit_handler ();
5480}
5481
78a095c3
JK
5482/* Remove any of the remote.c targets from target stack. Upper targets depend
5483 on it so remove them first. */
5484
5485static void
5486remote_unpush_target (void)
5487{
915ef8b1 5488 pop_all_targets_at_and_above (process_stratum);
78a095c3 5489}
be2a5f71 5490
048094ac
PA
5491static void
5492remote_unpush_and_throw (void)
5493{
5494 remote_unpush_target ();
5495 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5496}
5497
f6ac5f3d
PA
5498void
5499remote_target::open_1 (const char *name, int from_tty, int extended_p)
c906108c 5500{
6b8edb51 5501 remote_target *curr_remote = get_current_remote_target ();
a6f3e723 5502
c906108c 5503 if (name == 0)
8a3fe4f8 5504 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 5505 "serial device is attached to the remote system\n"
8a3fe4f8 5506 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 5507
2d717e4f 5508 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
5509 Ask this question first, before target_preopen has a chance to kill
5510 anything. */
6b8edb51 5511 if (curr_remote != NULL && !have_inferiors ())
2d717e4f 5512 {
78a095c3
JK
5513 if (from_tty
5514 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
5515 error (_("Still connected."));
5516 }
5517
78a095c3 5518 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
5519 target_preopen (from_tty);
5520
ad9a8f3f 5521 remote_fileio_reset ();
1dd41f16
NS
5522 reopen_exec_file ();
5523 reread_symbols ();
5524
6b8edb51
PA
5525 remote_target *remote
5526 = (extended_p ? new extended_remote_target () : new remote_target ());
5527 target_ops_up target_holder (remote);
5528
5529 remote_state *rs = remote->get_remote_state ();
5530
5531 /* See FIXME above. */
5532 if (!target_async_permitted)
5533 rs->wait_forever_enabled_p = 1;
5534
5d93a237
TT
5535 rs->remote_desc = remote_serial_open (name);
5536 if (!rs->remote_desc)
c906108c
SS
5537 perror_with_name (name);
5538
5539 if (baud_rate != -1)
5540 {
5d93a237 5541 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 5542 {
9b74d5d3
KB
5543 /* The requested speed could not be set. Error out to
5544 top level after closing remote_desc. Take care to
5545 set remote_desc to NULL to avoid closing remote_desc
5546 more than once. */
5d93a237
TT
5547 serial_close (rs->remote_desc);
5548 rs->remote_desc = NULL;
c906108c
SS
5549 perror_with_name (name);
5550 }
5551 }
5552
236af5e3 5553 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 5554 serial_raw (rs->remote_desc);
c906108c
SS
5555
5556 /* If there is something sitting in the buffer we might take it as a
5557 response to a command, which would be bad. */
5d93a237 5558 serial_flush_input (rs->remote_desc);
c906108c
SS
5559
5560 if (from_tty)
5561 {
5562 puts_filtered ("Remote debugging using ");
5563 puts_filtered (name);
5564 puts_filtered ("\n");
5565 }
d9f719f1 5566
6b8edb51
PA
5567 /* Switch to using the remote target now. */
5568 push_target (remote);
5569 /* The target stack owns the target now. */
5570 target_holder.release ();
c906108c 5571
74531fed 5572 /* Register extra event sources in the event loop. */
6b8edb51 5573 rs->remote_async_inferior_event_token
74531fed 5574 = create_async_event_handler (remote_async_inferior_event_handler,
6b8edb51
PA
5575 remote);
5576 rs->notif_state = remote_notif_state_allocate (remote);
74531fed 5577
be2a5f71
DJ
5578 /* Reset the target state; these things will be queried either by
5579 remote_query_supported or as they are needed. */
ca4f7f8b 5580 reset_all_packet_configs_support ();
74531fed 5581 rs->cached_wait_status = 0;
be2a5f71 5582 rs->explicit_packet_size = 0;
a6f3e723 5583 rs->noack_mode = 0;
82f73884 5584 rs->extended = extended_p;
e24a49d8 5585 rs->waiting_for_stop_reply = 0;
3a29589a 5586 rs->ctrlc_pending_p = 0;
048094ac 5587 rs->got_ctrlc_during_io = 0;
802188a7 5588
47f8a51d
TT
5589 rs->general_thread = not_sent_ptid;
5590 rs->continue_thread = not_sent_ptid;
262e1174 5591 rs->remote_traceframe_number = -1;
c906108c 5592
3a00c802
PA
5593 rs->last_resume_exec_dir = EXEC_FORWARD;
5594
9d1f7ab2 5595 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
5596 rs->use_threadinfo_query = 1;
5597 rs->use_threadextra_query = 1;
9d1f7ab2 5598
dd194f6b 5599 rs->readahead_cache.invalidate ();
80152258 5600
c6ebd6cf 5601 if (target_async_permitted)
92d1e331 5602 {
92d1e331
DJ
5603 /* FIXME: cagney/1999-09-23: During the initial connection it is
5604 assumed that the target is already ready and able to respond to
0df8b418 5605 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 5606 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 5607 around this. Eventually a mechanism that allows
92d1e331 5608 wait_for_inferior() to expect/get timeouts will be
23860348 5609 implemented. */
6b8edb51 5610 rs->wait_forever_enabled_p = 0;
92d1e331
DJ
5611 }
5612
23860348 5613 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 5614 no_shared_libraries (NULL, 0);
f78f6cf1 5615
74531fed
PA
5616 /* Start afresh. */
5617 init_thread_list ();
5618
36918e70 5619 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
5620 target (we'd otherwise be in an inconsistent state) and then
5621 propogate the error on up the exception chain. This ensures that
5622 the caller doesn't stumble along blindly assuming that the
5623 function succeeded. The CLI doesn't have this problem but other
5624 UI's, such as MI do.
36918e70
AC
5625
5626 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5627 this function should return an error indication letting the
ce2826aa 5628 caller restore the previous state. Unfortunately the command
36918e70
AC
5629 ``target remote'' is directly wired to this function making that
5630 impossible. On a positive note, the CLI side of this problem has
5631 been fixed - the function set_cmd_context() makes it possible for
5632 all the ``target ....'' commands to share a common callback
5633 function. See cli-dump.c. */
109c3e39 5634 {
2d717e4f 5635
492d29ea 5636 TRY
04bd08de 5637 {
6b8edb51 5638 remote->start_remote (from_tty, extended_p);
04bd08de 5639 }
492d29ea 5640 CATCH (ex, RETURN_MASK_ALL)
109c3e39 5641 {
c8d104ad
PA
5642 /* Pop the partially set up target - unless something else did
5643 already before throwing the exception. */
6b8edb51 5644 if (ex.error != TARGET_CLOSE_ERROR)
78a095c3 5645 remote_unpush_target ();
109c3e39
AC
5646 throw_exception (ex);
5647 }
492d29ea 5648 END_CATCH
109c3e39 5649 }
c906108c 5650
6b8edb51 5651 remote_btrace_reset (rs);
f4abbc16 5652
c6ebd6cf 5653 if (target_async_permitted)
6b8edb51 5654 rs->wait_forever_enabled_p = 1;
43ff13b4
JM
5655}
5656
de0d863e
DB
5657/* Detach the specified process. */
5658
6b8edb51
PA
5659void
5660remote_target::remote_detach_pid (int pid)
de0d863e
DB
5661{
5662 struct remote_state *rs = get_remote_state ();
5663
5664 if (remote_multi_process_p (rs))
5665 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5666 else
5667 strcpy (rs->buf, "D");
5668
5669 putpkt (rs->buf);
5670 getpkt (&rs->buf, &rs->buf_size, 0);
5671
5672 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5673 ;
5674 else if (rs->buf[0] == '\0')
5675 error (_("Remote doesn't know how to detach"));
5676 else
5677 error (_("Can't detach process."));
5678}
5679
5680/* This detaches a program to which we previously attached, using
5681 inferior_ptid to identify the process. After this is done, GDB
5682 can be used to debug some other program. We better not have left
5683 any breakpoints in the target program or it'll die when it hits
5684 one. */
c906108c 5685
6b8edb51 5686void
00431a78 5687remote_target::remote_detach_1 (inferior *inf, int from_tty)
c906108c 5688{
e99b03dc 5689 int pid = inferior_ptid.pid ();
d01949b6 5690 struct remote_state *rs = get_remote_state ();
de0d863e 5691 int is_fork_parent;
c906108c 5692
2d717e4f
DJ
5693 if (!target_has_execution)
5694 error (_("No process to detach from."));
5695
0f48b757 5696 target_announce_detach (from_tty);
7cee1e54 5697
c906108c 5698 /* Tell the remote target to detach. */
de0d863e 5699 remote_detach_pid (pid);
82f73884 5700
8020350c
DB
5701 /* Exit only if this is the only active inferior. */
5702 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
7cee1e54 5703 puts_filtered (_("Ending remote debugging.\n"));
82f73884 5704
00431a78
PA
5705 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5706
de0d863e
DB
5707 /* Check to see if we are detaching a fork parent. Note that if we
5708 are detaching a fork child, tp == NULL. */
5709 is_fork_parent = (tp != NULL
5710 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5711
5712 /* If doing detach-on-fork, we don't mourn, because that will delete
5713 breakpoints that should be available for the followed inferior. */
5714 if (!is_fork_parent)
f67c0c91 5715 {
249b5733
PA
5716 /* Save the pid as a string before mourning, since that will
5717 unpush the remote target, and we need the string after. */
f2907e49 5718 std::string infpid = target_pid_to_str (ptid_t (pid));
f67c0c91
SDJ
5719
5720 target_mourn_inferior (inferior_ptid);
5721 if (print_inferior_events)
5722 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5723 inf->num, infpid.c_str ());
5724 }
de0d863e
DB
5725 else
5726 {
5727 inferior_ptid = null_ptid;
00431a78 5728 detach_inferior (current_inferior ());
de0d863e 5729 }
2d717e4f
DJ
5730}
5731
f6ac5f3d
PA
5732void
5733remote_target::detach (inferior *inf, int from_tty)
2d717e4f 5734{
00431a78 5735 remote_detach_1 (inf, from_tty);
2d717e4f
DJ
5736}
5737
f6ac5f3d
PA
5738void
5739extended_remote_target::detach (inferior *inf, int from_tty)
2d717e4f 5740{
00431a78 5741 remote_detach_1 (inf, from_tty);
de0d863e
DB
5742}
5743
5744/* Target follow-fork function for remote targets. On entry, and
5745 at return, the current inferior is the fork parent.
5746
5747 Note that although this is currently only used for extended-remote,
5748 it is named remote_follow_fork in anticipation of using it for the
5749 remote target as well. */
5750
f6ac5f3d
PA
5751int
5752remote_target::follow_fork (int follow_child, int detach_fork)
de0d863e
DB
5753{
5754 struct remote_state *rs = get_remote_state ();
c269dbdb 5755 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5756
c269dbdb
DB
5757 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5758 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5759 {
5760 /* When following the parent and detaching the child, we detach
5761 the child here. For the case of following the child and
5762 detaching the parent, the detach is done in the target-
5763 independent follow fork code in infrun.c. We can't use
5764 target_detach when detaching an unfollowed child because
5765 the client side doesn't know anything about the child. */
5766 if (detach_fork && !follow_child)
5767 {
5768 /* Detach the fork child. */
5769 ptid_t child_ptid;
5770 pid_t child_pid;
5771
5772 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
e99b03dc 5773 child_pid = child_ptid.pid ();
de0d863e
DB
5774
5775 remote_detach_pid (child_pid);
de0d863e
DB
5776 }
5777 }
5778 return 0;
c906108c
SS
5779}
5780
94585166
DB
5781/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5782 in the program space of the new inferior. On entry and at return the
5783 current inferior is the exec'ing inferior. INF is the new exec'd
5784 inferior, which may be the same as the exec'ing inferior unless
5785 follow-exec-mode is "new". */
5786
f6ac5f3d
PA
5787void
5788remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
94585166
DB
5789{
5790 /* We know that this is a target file name, so if it has the "target:"
5791 prefix we strip it off before saving it in the program space. */
5792 if (is_target_filename (execd_pathname))
5793 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5794
5795 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5796}
5797
6ad8ae5c
DJ
5798/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5799
f6ac5f3d
PA
5800void
5801remote_target::disconnect (const char *args, int from_tty)
43ff13b4 5802{
43ff13b4 5803 if (args)
2d717e4f 5804 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5805
8020350c
DB
5806 /* Make sure we unpush even the extended remote targets. Calling
5807 target_mourn_inferior won't unpush, and remote_mourn won't
5808 unpush if there is more than one inferior left. */
f6ac5f3d 5809 unpush_target (this);
8020350c 5810 generic_mourn_inferior ();
2d717e4f 5811
43ff13b4
JM
5812 if (from_tty)
5813 puts_filtered ("Ending remote debugging.\n");
5814}
5815
2d717e4f
DJ
5816/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5817 be chatty about it. */
5818
f6ac5f3d
PA
5819void
5820extended_remote_target::attach (const char *args, int from_tty)
2d717e4f
DJ
5821{
5822 struct remote_state *rs = get_remote_state ();
be86555c 5823 int pid;
96ef3384 5824 char *wait_status = NULL;
2d717e4f 5825
74164c56 5826 pid = parse_pid_to_attach (args);
2d717e4f 5827
74164c56
JK
5828 /* Remote PID can be freely equal to getpid, do not check it here the same
5829 way as in other targets. */
2d717e4f 5830
4082afcc 5831 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5832 error (_("This target does not support attaching to a process"));
5833
7cee1e54
PA
5834 if (from_tty)
5835 {
5836 char *exec_file = get_exec_file (0);
5837
5838 if (exec_file)
5839 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
f2907e49 5840 target_pid_to_str (ptid_t (pid)));
7cee1e54
PA
5841 else
5842 printf_unfiltered (_("Attaching to %s\n"),
f2907e49 5843 target_pid_to_str (ptid_t (pid)));
7cee1e54
PA
5844
5845 gdb_flush (gdb_stdout);
5846 }
5847
bba74b36 5848 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
5849 putpkt (rs->buf);
5850 getpkt (&rs->buf, &rs->buf_size, 0);
5851
4082afcc
PA
5852 switch (packet_ok (rs->buf,
5853 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5854 {
4082afcc 5855 case PACKET_OK:
6efcd9a8 5856 if (!target_is_non_stop_p ())
74531fed
PA
5857 {
5858 /* Save the reply for later. */
224c3ddb 5859 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
5860 strcpy (wait_status, rs->buf);
5861 }
5862 else if (strcmp (rs->buf, "OK") != 0)
5863 error (_("Attaching to %s failed with: %s"),
f2907e49 5864 target_pid_to_str (ptid_t (pid)),
74531fed 5865 rs->buf);
4082afcc
PA
5866 break;
5867 case PACKET_UNKNOWN:
5868 error (_("This target does not support attaching to a process"));
5869 default:
5870 error (_("Attaching to %s failed"),
f2907e49 5871 target_pid_to_str (ptid_t (pid)));
2d717e4f 5872 }
2d717e4f 5873
1b6e6f5c 5874 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 5875
f2907e49 5876 inferior_ptid = ptid_t (pid);
79d7f229 5877
6efcd9a8 5878 if (target_is_non_stop_p ())
bad34192
PA
5879 {
5880 struct thread_info *thread;
79d7f229 5881
bad34192 5882 /* Get list of threads. */
f6ac5f3d 5883 update_thread_list ();
82f73884 5884
00431a78 5885 thread = first_thread_of_inferior (current_inferior ());
bad34192
PA
5886 if (thread)
5887 inferior_ptid = thread->ptid;
5888 else
f2907e49 5889 inferior_ptid = ptid_t (pid);
bad34192
PA
5890
5891 /* Invalidate our notion of the remote current thread. */
47f8a51d 5892 record_currthread (rs, minus_one_ptid);
bad34192 5893 }
74531fed 5894 else
bad34192
PA
5895 {
5896 /* Now, if we have thread information, update inferior_ptid. */
5897 inferior_ptid = remote_current_thread (inferior_ptid);
5898
5899 /* Add the main thread to the thread list. */
00aecdcf
PA
5900 thread_info *thr = add_thread_silent (inferior_ptid);
5901 /* Don't consider the thread stopped until we've processed the
5902 saved stop reply. */
5903 set_executing (thr->ptid, true);
bad34192 5904 }
c0a2216e 5905
96ef3384
UW
5906 /* Next, if the target can specify a description, read it. We do
5907 this before anything involving memory or registers. */
5908 target_find_description ();
5909
6efcd9a8 5910 if (!target_is_non_stop_p ())
74531fed
PA
5911 {
5912 /* Use the previously fetched status. */
5913 gdb_assert (wait_status != NULL);
5914
5915 if (target_can_async_p ())
5916 {
722247f1 5917 struct notif_event *reply
6b8edb51 5918 = remote_notif_parse (this, &notif_client_stop, wait_status);
74531fed 5919
722247f1 5920 push_stop_reply ((struct stop_reply *) reply);
74531fed 5921
6a3753b3 5922 target_async (1);
74531fed
PA
5923 }
5924 else
5925 {
5926 gdb_assert (wait_status != NULL);
5927 strcpy (rs->buf, wait_status);
5928 rs->cached_wait_status = 1;
5929 }
5930 }
5931 else
5932 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5933}
5934
b9c1d481
AS
5935/* Implementation of the to_post_attach method. */
5936
f6ac5f3d
PA
5937void
5938extended_remote_target::post_attach (int pid)
b9c1d481 5939{
6efcd9a8
PA
5940 /* Get text, data & bss offsets. */
5941 get_offsets ();
5942
b9c1d481
AS
5943 /* In certain cases GDB might not have had the chance to start
5944 symbol lookup up until now. This could happen if the debugged
5945 binary is not using shared libraries, the vsyscall page is not
5946 present (on Linux) and the binary itself hadn't changed since the
5947 debugging process was started. */
5948 if (symfile_objfile != NULL)
5949 remote_check_symbols();
5950}
5951
c906108c 5952\f
506fb367
DJ
5953/* Check for the availability of vCont. This function should also check
5954 the response. */
c906108c 5955
6b8edb51
PA
5956void
5957remote_target::remote_vcont_probe ()
c906108c 5958{
6b8edb51 5959 remote_state *rs = get_remote_state ();
2e9f7625 5960 char *buf;
6d820c5c 5961
2e9f7625
DJ
5962 strcpy (rs->buf, "vCont?");
5963 putpkt (rs->buf);
6d820c5c 5964 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 5965 buf = rs->buf;
c906108c 5966
506fb367 5967 /* Make sure that the features we assume are supported. */
61012eef 5968 if (startswith (buf, "vCont"))
506fb367
DJ
5969 {
5970 char *p = &buf[5];
750ce8d1 5971 int support_c, support_C;
506fb367 5972
750ce8d1
YQ
5973 rs->supports_vCont.s = 0;
5974 rs->supports_vCont.S = 0;
506fb367
DJ
5975 support_c = 0;
5976 support_C = 0;
d458bd84 5977 rs->supports_vCont.t = 0;
c1e36e3e 5978 rs->supports_vCont.r = 0;
506fb367
DJ
5979 while (p && *p == ';')
5980 {
5981 p++;
5982 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5983 rs->supports_vCont.s = 1;
506fb367 5984 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5985 rs->supports_vCont.S = 1;
506fb367
DJ
5986 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5987 support_c = 1;
5988 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5989 support_C = 1;
74531fed 5990 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5991 rs->supports_vCont.t = 1;
c1e36e3e
PA
5992 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5993 rs->supports_vCont.r = 1;
506fb367
DJ
5994
5995 p = strchr (p, ';');
5996 }
c906108c 5997
750ce8d1
YQ
5998 /* If c, and C are not all supported, we can't use vCont. Clearing
5999 BUF will make packet_ok disable the packet. */
6000 if (!support_c || !support_C)
506fb367
DJ
6001 buf[0] = 0;
6002 }
c906108c 6003
444abaca 6004 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 6005}
c906108c 6006
0d8f58ca
PA
6007/* Helper function for building "vCont" resumptions. Write a
6008 resumption to P. ENDP points to one-passed-the-end of the buffer
6009 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6010 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6011 resumed thread should be single-stepped and/or signalled. If PTID
6012 equals minus_one_ptid, then all threads are resumed; if PTID
6013 represents a process, then all threads of the process are resumed;
6014 the thread to be stepped and/or signalled is given in the global
6015 INFERIOR_PTID. */
6016
6b8edb51
PA
6017char *
6018remote_target::append_resumption (char *p, char *endp,
6019 ptid_t ptid, int step, gdb_signal siggnal)
0d8f58ca
PA
6020{
6021 struct remote_state *rs = get_remote_state ();
6022
a493e3e2 6023 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 6024 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
6025 else if (step
6026 /* GDB is willing to range step. */
6027 && use_range_stepping
6028 /* Target supports range stepping. */
6029 && rs->supports_vCont.r
6030 /* We don't currently support range stepping multiple
6031 threads with a wildcard (though the protocol allows it,
6032 so stubs shouldn't make an active effort to forbid
6033 it). */
0e998d96 6034 && !(remote_multi_process_p (rs) && ptid.is_pid ()))
c1e36e3e
PA
6035 {
6036 struct thread_info *tp;
6037
d7e15655 6038 if (ptid == minus_one_ptid)
c1e36e3e
PA
6039 {
6040 /* If we don't know about the target thread's tid, then
6041 we're resuming magic_null_ptid (see caller). */
6042 tp = find_thread_ptid (magic_null_ptid);
6043 }
6044 else
6045 tp = find_thread_ptid (ptid);
6046 gdb_assert (tp != NULL);
6047
6048 if (tp->control.may_range_step)
6049 {
6050 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6051
6052 p += xsnprintf (p, endp - p, ";r%s,%s",
6053 phex_nz (tp->control.step_range_start,
6054 addr_size),
6055 phex_nz (tp->control.step_range_end,
6056 addr_size));
6057 }
6058 else
6059 p += xsnprintf (p, endp - p, ";s");
6060 }
0d8f58ca
PA
6061 else if (step)
6062 p += xsnprintf (p, endp - p, ";s");
a493e3e2 6063 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
6064 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6065 else
6066 p += xsnprintf (p, endp - p, ";c");
6067
0e998d96 6068 if (remote_multi_process_p (rs) && ptid.is_pid ())
0d8f58ca
PA
6069 {
6070 ptid_t nptid;
6071
6072 /* All (-1) threads of process. */
e99b03dc 6073 nptid = ptid_t (ptid.pid (), -1, 0);
0d8f58ca
PA
6074
6075 p += xsnprintf (p, endp - p, ":");
6076 p = write_ptid (p, endp, nptid);
6077 }
d7e15655 6078 else if (ptid != minus_one_ptid)
0d8f58ca
PA
6079 {
6080 p += xsnprintf (p, endp - p, ":");
6081 p = write_ptid (p, endp, ptid);
6082 }
6083
6084 return p;
6085}
6086
799a2abe
PA
6087/* Clear the thread's private info on resume. */
6088
6089static void
6090resume_clear_thread_private_info (struct thread_info *thread)
6091{
6092 if (thread->priv != NULL)
6093 {
7aabaf9d
SM
6094 remote_thread_info *priv = get_remote_thread_info (thread);
6095
6096 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6097 priv->watch_data_address = 0;
799a2abe
PA
6098 }
6099}
6100
e5ef252a
PA
6101/* Append a vCont continue-with-signal action for threads that have a
6102 non-zero stop signal. */
6103
6b8edb51
PA
6104char *
6105remote_target::append_pending_thread_resumptions (char *p, char *endp,
6106 ptid_t ptid)
e5ef252a
PA
6107{
6108 struct thread_info *thread;
6109
034f788c 6110 ALL_NON_EXITED_THREADS (thread)
26a57c92 6111 if (thread->ptid.matches (ptid)
d7e15655 6112 && inferior_ptid != thread->ptid
70509625 6113 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
6114 {
6115 p = append_resumption (p, endp, thread->ptid,
6116 0, thread->suspend.stop_signal);
6117 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 6118 resume_clear_thread_private_info (thread);
e5ef252a
PA
6119 }
6120
6121 return p;
6122}
6123
7b68ffbb
PA
6124/* Set the target running, using the packets that use Hc
6125 (c/s/C/S). */
6126
6b8edb51
PA
6127void
6128remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6129 gdb_signal siggnal)
7b68ffbb
PA
6130{
6131 struct remote_state *rs = get_remote_state ();
6132 struct thread_info *thread;
6133 char *buf;
6134
6135 rs->last_sent_signal = siggnal;
6136 rs->last_sent_step = step;
6137
6138 /* The c/s/C/S resume packets use Hc, so set the continue
6139 thread. */
d7e15655 6140 if (ptid == minus_one_ptid)
7b68ffbb
PA
6141 set_continue_thread (any_thread_ptid);
6142 else
6143 set_continue_thread (ptid);
6144
6145 ALL_NON_EXITED_THREADS (thread)
6146 resume_clear_thread_private_info (thread);
6147
6148 buf = rs->buf;
6b8edb51 6149 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6150 {
6151 /* We don't pass signals to the target in reverse exec mode. */
6152 if (info_verbose && siggnal != GDB_SIGNAL_0)
6153 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6154 siggnal);
6155
6156 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6157 error (_("Remote reverse-step not supported."));
6158 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6159 error (_("Remote reverse-continue not supported."));
6160
6161 strcpy (buf, step ? "bs" : "bc");
6162 }
6163 else if (siggnal != GDB_SIGNAL_0)
6164 {
6165 buf[0] = step ? 'S' : 'C';
6166 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6167 buf[2] = tohex (((int) siggnal) & 0xf);
6168 buf[3] = '\0';
6169 }
6170 else
6171 strcpy (buf, step ? "s" : "c");
6172
6173 putpkt (buf);
6174}
6175
506fb367
DJ
6176/* Resume the remote inferior by using a "vCont" packet. The thread
6177 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
6178 resumed thread should be single-stepped and/or signalled. If PTID
6179 equals minus_one_ptid, then all threads are resumed; the thread to
6180 be stepped and/or signalled is given in the global INFERIOR_PTID.
6181 This function returns non-zero iff it resumes the inferior.
44eaed12 6182
7b68ffbb
PA
6183 This function issues a strict subset of all possible vCont commands
6184 at the moment. */
44eaed12 6185
6b8edb51
PA
6186int
6187remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6188 enum gdb_signal siggnal)
506fb367
DJ
6189{
6190 struct remote_state *rs = get_remote_state ();
82f73884
PA
6191 char *p;
6192 char *endp;
44eaed12 6193
7b68ffbb 6194 /* No reverse execution actions defined for vCont. */
6b8edb51 6195 if (::execution_direction == EXEC_REVERSE)
7b68ffbb
PA
6196 return 0;
6197
4082afcc 6198 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 6199 remote_vcont_probe ();
44eaed12 6200
4082afcc 6201 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 6202 return 0;
44eaed12 6203
82f73884
PA
6204 p = rs->buf;
6205 endp = rs->buf + get_remote_packet_size ();
6206
506fb367
DJ
6207 /* If we could generate a wider range of packets, we'd have to worry
6208 about overflowing BUF. Should there be a generic
6209 "multi-part-packet" packet? */
6210
0d8f58ca
PA
6211 p += xsnprintf (p, endp - p, "vCont");
6212
d7e15655 6213 if (ptid == magic_null_ptid)
c906108c 6214 {
79d7f229
PA
6215 /* MAGIC_NULL_PTID means that we don't have any active threads,
6216 so we don't have any TID numbers the inferior will
6217 understand. Make sure to only send forms that do not specify
6218 a TID. */
a9cbf802 6219 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 6220 }
d7e15655 6221 else if (ptid == minus_one_ptid || ptid.is_pid ())
506fb367 6222 {
0d8f58ca
PA
6223 /* Resume all threads (of all processes, or of a single
6224 process), with preference for INFERIOR_PTID. This assumes
6225 inferior_ptid belongs to the set of all threads we are about
6226 to resume. */
a493e3e2 6227 if (step || siggnal != GDB_SIGNAL_0)
82f73884 6228 {
0d8f58ca
PA
6229 /* Step inferior_ptid, with or without signal. */
6230 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 6231 }
0d8f58ca 6232
e5ef252a
PA
6233 /* Also pass down any pending signaled resumption for other
6234 threads not the current. */
6235 p = append_pending_thread_resumptions (p, endp, ptid);
6236
0d8f58ca 6237 /* And continue others without a signal. */
a493e3e2 6238 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
6239 }
6240 else
506fb367
DJ
6241 {
6242 /* Scheduler locking; resume only PTID. */
a9cbf802 6243 append_resumption (p, endp, ptid, step, siggnal);
506fb367 6244 }
c906108c 6245
82f73884
PA
6246 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
6247 putpkt (rs->buf);
506fb367 6248
6efcd9a8 6249 if (target_is_non_stop_p ())
74531fed
PA
6250 {
6251 /* In non-stop, the stub replies to vCont with "OK". The stop
6252 reply will be reported asynchronously by means of a `%Stop'
6253 notification. */
6254 getpkt (&rs->buf, &rs->buf_size, 0);
6255 if (strcmp (rs->buf, "OK") != 0)
6256 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6257 }
6258
506fb367 6259 return 1;
c906108c 6260}
43ff13b4 6261
506fb367
DJ
6262/* Tell the remote machine to resume. */
6263
f6ac5f3d
PA
6264void
6265remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 6266{
d01949b6 6267 struct remote_state *rs = get_remote_state ();
43ff13b4 6268
85ad3aaf
PA
6269 /* When connected in non-stop mode, the core resumes threads
6270 individually. Resuming remote threads directly in target_resume
6271 would thus result in sending one packet per thread. Instead, to
6272 minimize roundtrip latency, here we just store the resume
6273 request; the actual remote resumption will be done in
6274 target_commit_resume / remote_commit_resume, where we'll be able
6275 to do vCont action coalescing. */
f6ac5f3d 6276 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
85ad3aaf 6277 {
7aabaf9d 6278 remote_thread_info *remote_thr;
85ad3aaf 6279
d7e15655 6280 if (minus_one_ptid == ptid || ptid.is_pid ())
7aabaf9d 6281 remote_thr = get_remote_thread_info (inferior_ptid);
85ad3aaf 6282 else
7aabaf9d
SM
6283 remote_thr = get_remote_thread_info (ptid);
6284
85ad3aaf
PA
6285 remote_thr->last_resume_step = step;
6286 remote_thr->last_resume_sig = siggnal;
6287 return;
6288 }
6289
722247f1
YQ
6290 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6291 (explained in remote-notif.c:handle_notification) so
6292 remote_notif_process is not called. We need find a place where
6293 it is safe to start a 'vNotif' sequence. It is good to do it
6294 before resuming inferior, because inferior was stopped and no RSP
6295 traffic at that moment. */
6efcd9a8 6296 if (!target_is_non_stop_p ())
5965e028 6297 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 6298
f6ac5f3d 6299 rs->last_resume_exec_dir = ::execution_direction;
3a00c802 6300
7b68ffbb
PA
6301 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6302 if (!remote_resume_with_vcont (ptid, step, siggnal))
6b8edb51 6303 remote_resume_with_hc (ptid, step, siggnal);
43ff13b4 6304
2acceee2 6305 /* We are about to start executing the inferior, let's register it
0df8b418
MS
6306 with the event loop. NOTE: this is the one place where all the
6307 execution commands end up. We could alternatively do this in each
23860348 6308 of the execution commands in infcmd.c. */
2acceee2
JM
6309 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6310 into infcmd.c in order to allow inferior function calls to work
23860348 6311 NOT asynchronously. */
362646f5 6312 if (target_can_async_p ())
6a3753b3 6313 target_async (1);
e24a49d8
PA
6314
6315 /* We've just told the target to resume. The remote server will
6316 wait for the inferior to stop, and then send a stop reply. In
6317 the mean time, we can't start another command/query ourselves
74531fed
PA
6318 because the stub wouldn't be ready to process it. This applies
6319 only to the base all-stop protocol, however. In non-stop (which
6320 only supports vCont), the stub replies with an "OK", and is
6321 immediate able to process further serial input. */
6efcd9a8 6322 if (!target_is_non_stop_p ())
74531fed 6323 rs->waiting_for_stop_reply = 1;
43ff13b4 6324}
85ad3aaf 6325
85ad3aaf
PA
6326static int is_pending_fork_parent_thread (struct thread_info *thread);
6327
6328/* Private per-inferior info for target remote processes. */
6329
089354bb 6330struct remote_inferior : public private_inferior
85ad3aaf
PA
6331{
6332 /* Whether we can send a wildcard vCont for this process. */
089354bb 6333 bool may_wildcard_vcont = true;
85ad3aaf
PA
6334};
6335
089354bb
SM
6336/* Get the remote private inferior data associated to INF. */
6337
6338static remote_inferior *
6339get_remote_inferior (inferior *inf)
6340{
6341 if (inf->priv == NULL)
6342 inf->priv.reset (new remote_inferior);
6343
6344 return static_cast<remote_inferior *> (inf->priv.get ());
6345}
6346
f5db4863 6347/* Class used to track the construction of a vCont packet in the
85ad3aaf
PA
6348 outgoing packet buffer. This is used to send multiple vCont
6349 packets if we have more actions than would fit a single packet. */
6350
f5db4863 6351class vcont_builder
85ad3aaf 6352{
f5db4863 6353public:
6b8edb51
PA
6354 explicit vcont_builder (remote_target *remote)
6355 : m_remote (remote)
f5db4863
PA
6356 {
6357 restart ();
6358 }
6359
6360 void flush ();
6361 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6362
6363private:
6364 void restart ();
6365
6b8edb51
PA
6366 /* The remote target. */
6367 remote_target *m_remote;
6368
85ad3aaf
PA
6369 /* Pointer to the first action. P points here if no action has been
6370 appended yet. */
f5db4863 6371 char *m_first_action;
85ad3aaf
PA
6372
6373 /* Where the next action will be appended. */
f5db4863 6374 char *m_p;
85ad3aaf
PA
6375
6376 /* The end of the buffer. Must never write past this. */
f5db4863 6377 char *m_endp;
85ad3aaf
PA
6378};
6379
6380/* Prepare the outgoing buffer for a new vCont packet. */
6381
f5db4863
PA
6382void
6383vcont_builder::restart ()
85ad3aaf 6384{
6b8edb51 6385 struct remote_state *rs = m_remote->get_remote_state ();
85ad3aaf 6386
f5db4863 6387 m_p = rs->buf;
6b8edb51 6388 m_endp = rs->buf + m_remote->get_remote_packet_size ();
f5db4863
PA
6389 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6390 m_first_action = m_p;
85ad3aaf
PA
6391}
6392
6393/* If the vCont packet being built has any action, send it to the
6394 remote end. */
6395
f5db4863
PA
6396void
6397vcont_builder::flush ()
85ad3aaf
PA
6398{
6399 struct remote_state *rs;
6400
f5db4863 6401 if (m_p == m_first_action)
85ad3aaf
PA
6402 return;
6403
6b8edb51
PA
6404 rs = m_remote->get_remote_state ();
6405 m_remote->putpkt (rs->buf);
6406 m_remote->getpkt (&rs->buf, &rs->buf_size, 0);
85ad3aaf
PA
6407 if (strcmp (rs->buf, "OK") != 0)
6408 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6409}
6410
6411/* The largest action is range-stepping, with its two addresses. This
6412 is more than sufficient. If a new, bigger action is created, it'll
6413 quickly trigger a failed assertion in append_resumption (and we'll
6414 just bump this). */
6415#define MAX_ACTION_SIZE 200
6416
6417/* Append a new vCont action in the outgoing packet being built. If
6418 the action doesn't fit the packet along with previous actions, push
6419 what we've got so far to the remote end and start over a new vCont
6420 packet (with the new action). */
6421
f5db4863
PA
6422void
6423vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
85ad3aaf
PA
6424{
6425 char buf[MAX_ACTION_SIZE + 1];
85ad3aaf 6426
6b8edb51
PA
6427 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6428 ptid, step, siggnal);
85ad3aaf
PA
6429
6430 /* Check whether this new action would fit in the vCont packet along
6431 with previous actions. If not, send what we've got so far and
6432 start a new vCont packet. */
f5db4863
PA
6433 size_t rsize = endp - buf;
6434 if (rsize > m_endp - m_p)
85ad3aaf 6435 {
f5db4863
PA
6436 flush ();
6437 restart ();
85ad3aaf
PA
6438
6439 /* Should now fit. */
f5db4863 6440 gdb_assert (rsize <= m_endp - m_p);
85ad3aaf
PA
6441 }
6442
f5db4863
PA
6443 memcpy (m_p, buf, rsize);
6444 m_p += rsize;
6445 *m_p = '\0';
85ad3aaf
PA
6446}
6447
6448/* to_commit_resume implementation. */
6449
f6ac5f3d
PA
6450void
6451remote_target::commit_resume ()
85ad3aaf 6452{
85ad3aaf
PA
6453 struct inferior *inf;
6454 struct thread_info *tp;
6455 int any_process_wildcard;
6456 int may_global_wildcard_vcont;
85ad3aaf
PA
6457
6458 /* If connected in all-stop mode, we'd send the remote resume
6459 request directly from remote_resume. Likewise if
6460 reverse-debugging, as there are no defined vCont actions for
6461 reverse execution. */
f6ac5f3d 6462 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
85ad3aaf
PA
6463 return;
6464
6465 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6466 instead of resuming all threads of each process individually.
6467 However, if any thread of a process must remain halted, we can't
6468 send wildcard resumes and must send one action per thread.
6469
6470 Care must be taken to not resume threads/processes the server
6471 side already told us are stopped, but the core doesn't know about
6472 yet, because the events are still in the vStopped notification
6473 queue. For example:
6474
6475 #1 => vCont s:p1.1;c
6476 #2 <= OK
6477 #3 <= %Stopped T05 p1.1
6478 #4 => vStopped
6479 #5 <= T05 p1.2
6480 #6 => vStopped
6481 #7 <= OK
6482 #8 (infrun handles the stop for p1.1 and continues stepping)
6483 #9 => vCont s:p1.1;c
6484
6485 The last vCont above would resume thread p1.2 by mistake, because
6486 the server has no idea that the event for p1.2 had not been
6487 handled yet.
6488
6489 The server side must similarly ignore resume actions for the
6490 thread that has a pending %Stopped notification (and any other
6491 threads with events pending), until GDB acks the notification
6492 with vStopped. Otherwise, e.g., the following case is
6493 mishandled:
6494
6495 #1 => g (or any other packet)
6496 #2 <= [registers]
6497 #3 <= %Stopped T05 p1.2
6498 #4 => vCont s:p1.1;c
6499 #5 <= OK
6500
6501 Above, the server must not resume thread p1.2. GDB can't know
6502 that p1.2 stopped until it acks the %Stopped notification, and
6503 since from GDB's perspective all threads should be running, it
6504 sends a "c" action.
6505
6506 Finally, special care must also be given to handling fork/vfork
6507 events. A (v)fork event actually tells us that two processes
6508 stopped -- the parent and the child. Until we follow the fork,
6509 we must not resume the child. Therefore, if we have a pending
6510 fork follow, we must not send a global wildcard resume action
6511 (vCont;c). We can still send process-wide wildcards though. */
6512
6513 /* Start by assuming a global wildcard (vCont;c) is possible. */
6514 may_global_wildcard_vcont = 1;
6515
6516 /* And assume every process is individually wildcard-able too. */
6517 ALL_NON_EXITED_INFERIORS (inf)
6518 {
089354bb
SM
6519 remote_inferior *priv = get_remote_inferior (inf);
6520
6521 priv->may_wildcard_vcont = true;
85ad3aaf
PA
6522 }
6523
6524 /* Check for any pending events (not reported or processed yet) and
6525 disable process and global wildcard resumes appropriately. */
6526 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6527
6528 ALL_NON_EXITED_THREADS (tp)
6529 {
6530 /* If a thread of a process is not meant to be resumed, then we
6531 can't wildcard that process. */
6532 if (!tp->executing)
6533 {
089354bb 6534 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
85ad3aaf
PA
6535
6536 /* And if we can't wildcard a process, we can't wildcard
6537 everything either. */
6538 may_global_wildcard_vcont = 0;
6539 continue;
6540 }
6541
6542 /* If a thread is the parent of an unfollowed fork, then we
6543 can't do a global wildcard, as that would resume the fork
6544 child. */
6545 if (is_pending_fork_parent_thread (tp))
6546 may_global_wildcard_vcont = 0;
6547 }
6548
6549 /* Now let's build the vCont packet(s). Actions must be appended
6550 from narrower to wider scopes (thread -> process -> global). If
6551 we end up with too many actions for a single packet vcont_builder
6552 flushes the current vCont packet to the remote side and starts a
6553 new one. */
6b8edb51 6554 struct vcont_builder vcont_builder (this);
85ad3aaf
PA
6555
6556 /* Threads first. */
6557 ALL_NON_EXITED_THREADS (tp)
6558 {
7aabaf9d 6559 remote_thread_info *remote_thr = get_remote_thread_info (tp);
85ad3aaf
PA
6560
6561 if (!tp->executing || remote_thr->vcont_resumed)
6562 continue;
6563
6564 gdb_assert (!thread_is_in_step_over_chain (tp));
6565
6566 if (!remote_thr->last_resume_step
6567 && remote_thr->last_resume_sig == GDB_SIGNAL_0
089354bb 6568 && get_remote_inferior (tp->inf)->may_wildcard_vcont)
85ad3aaf
PA
6569 {
6570 /* We'll send a wildcard resume instead. */
6571 remote_thr->vcont_resumed = 1;
6572 continue;
6573 }
6574
f5db4863 6575 vcont_builder.push_action (tp->ptid,
85ad3aaf
PA
6576 remote_thr->last_resume_step,
6577 remote_thr->last_resume_sig);
6578 remote_thr->vcont_resumed = 1;
6579 }
6580
6581 /* Now check whether we can send any process-wide wildcard. This is
6582 to avoid sending a global wildcard in the case nothing is
6583 supposed to be resumed. */
6584 any_process_wildcard = 0;
6585
6586 ALL_NON_EXITED_INFERIORS (inf)
6587 {
089354bb 6588 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf
PA
6589 {
6590 any_process_wildcard = 1;
6591 break;
6592 }
6593 }
6594
6595 if (any_process_wildcard)
6596 {
6597 /* If all processes are wildcard-able, then send a single "c"
6598 action, otherwise, send an "all (-1) threads of process"
6599 continue action for each running process, if any. */
6600 if (may_global_wildcard_vcont)
6601 {
f5db4863
PA
6602 vcont_builder.push_action (minus_one_ptid,
6603 false, GDB_SIGNAL_0);
85ad3aaf
PA
6604 }
6605 else
6606 {
6607 ALL_NON_EXITED_INFERIORS (inf)
6608 {
089354bb 6609 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf 6610 {
f2907e49 6611 vcont_builder.push_action (ptid_t (inf->pid),
f5db4863 6612 false, GDB_SIGNAL_0);
85ad3aaf
PA
6613 }
6614 }
6615 }
6616 }
6617
f5db4863 6618 vcont_builder.flush ();
85ad3aaf
PA
6619}
6620
c906108c 6621\f
43ff13b4 6622
74531fed
PA
6623/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6624 thread, all threads of a remote process, or all threads of all
6625 processes. */
6626
6b8edb51
PA
6627void
6628remote_target::remote_stop_ns (ptid_t ptid)
74531fed
PA
6629{
6630 struct remote_state *rs = get_remote_state ();
6631 char *p = rs->buf;
6632 char *endp = rs->buf + get_remote_packet_size ();
74531fed 6633
4082afcc 6634 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 6635 remote_vcont_probe ();
74531fed 6636
d458bd84 6637 if (!rs->supports_vCont.t)
74531fed
PA
6638 error (_("Remote server does not support stopping threads"));
6639
d7e15655 6640 if (ptid == minus_one_ptid
0e998d96 6641 || (!remote_multi_process_p (rs) && ptid.is_pid ()))
74531fed
PA
6642 p += xsnprintf (p, endp - p, "vCont;t");
6643 else
6644 {
6645 ptid_t nptid;
6646
74531fed
PA
6647 p += xsnprintf (p, endp - p, "vCont;t:");
6648
0e998d96 6649 if (ptid.is_pid ())
74531fed 6650 /* All (-1) threads of process. */
e99b03dc 6651 nptid = ptid_t (ptid.pid (), -1, 0);
74531fed
PA
6652 else
6653 {
6654 /* Small optimization: if we already have a stop reply for
6655 this thread, no use in telling the stub we want this
6656 stopped. */
6657 if (peek_stop_reply (ptid))
6658 return;
6659
6660 nptid = ptid;
6661 }
6662
a9cbf802 6663 write_ptid (p, endp, nptid);
74531fed
PA
6664 }
6665
6666 /* In non-stop, we get an immediate OK reply. The stop reply will
6667 come in asynchronously by notification. */
6668 putpkt (rs->buf);
6669 getpkt (&rs->buf, &rs->buf_size, 0);
6670 if (strcmp (rs->buf, "OK") != 0)
6671 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6672}
6673
bfedc46a
PA
6674/* All-stop version of target_interrupt. Sends a break or a ^C to
6675 interrupt the remote target. It is undefined which thread of which
6676 process reports the interrupt. */
74531fed 6677
6b8edb51
PA
6678void
6679remote_target::remote_interrupt_as ()
74531fed
PA
6680{
6681 struct remote_state *rs = get_remote_state ();
6682
3a29589a
DJ
6683 rs->ctrlc_pending_p = 1;
6684
74531fed
PA
6685 /* If the inferior is stopped already, but the core didn't know
6686 about it yet, just ignore the request. The cached wait status
6687 will be collected in remote_wait. */
6688 if (rs->cached_wait_status)
6689 return;
6690
9a7071a8
JB
6691 /* Send interrupt_sequence to remote target. */
6692 send_interrupt_sequence ();
74531fed
PA
6693}
6694
de979965
PA
6695/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6696 the remote target. It is undefined which thread of which process
e42de8c7
PA
6697 reports the interrupt. Throws an error if the packet is not
6698 supported by the server. */
de979965 6699
6b8edb51
PA
6700void
6701remote_target::remote_interrupt_ns ()
de979965
PA
6702{
6703 struct remote_state *rs = get_remote_state ();
6704 char *p = rs->buf;
6705 char *endp = rs->buf + get_remote_packet_size ();
6706
6707 xsnprintf (p, endp - p, "vCtrlC");
6708
6709 /* In non-stop, we get an immediate OK reply. The stop reply will
6710 come in asynchronously by notification. */
6711 putpkt (rs->buf);
6712 getpkt (&rs->buf, &rs->buf_size, 0);
6713
6714 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6715 {
6716 case PACKET_OK:
6717 break;
6718 case PACKET_UNKNOWN:
e42de8c7 6719 error (_("No support for interrupting the remote target."));
de979965
PA
6720 case PACKET_ERROR:
6721 error (_("Interrupting target failed: %s"), rs->buf);
6722 }
de979965
PA
6723}
6724
bfedc46a 6725/* Implement the to_stop function for the remote targets. */
74531fed 6726
f6ac5f3d
PA
6727void
6728remote_target::stop (ptid_t ptid)
c906108c 6729{
7a292a7a 6730 if (remote_debug)
0f71a2f6 6731 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 6732
6efcd9a8 6733 if (target_is_non_stop_p ())
74531fed 6734 remote_stop_ns (ptid);
c906108c 6735 else
bfedc46a
PA
6736 {
6737 /* We don't currently have a way to transparently pause the
6738 remote target in all-stop mode. Interrupt it instead. */
de979965 6739 remote_interrupt_as ();
bfedc46a
PA
6740 }
6741}
6742
6743/* Implement the to_interrupt function for the remote targets. */
6744
f6ac5f3d
PA
6745void
6746remote_target::interrupt ()
bfedc46a
PA
6747{
6748 if (remote_debug)
6749 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6750
e42de8c7
PA
6751 if (target_is_non_stop_p ())
6752 remote_interrupt_ns ();
bfedc46a 6753 else
e42de8c7 6754 remote_interrupt_as ();
c906108c
SS
6755}
6756
93692b58
PA
6757/* Implement the to_pass_ctrlc function for the remote targets. */
6758
f6ac5f3d
PA
6759void
6760remote_target::pass_ctrlc ()
93692b58
PA
6761{
6762 struct remote_state *rs = get_remote_state ();
6763
6764 if (remote_debug)
6765 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6766
6767 /* If we're starting up, we're not fully synced yet. Quit
6768 immediately. */
6769 if (rs->starting_up)
6770 quit ();
6771 /* If ^C has already been sent once, offer to disconnect. */
6772 else if (rs->ctrlc_pending_p)
6773 interrupt_query ();
6774 else
e671cd59 6775 target_interrupt ();
93692b58
PA
6776}
6777
c906108c
SS
6778/* Ask the user what to do when an interrupt is received. */
6779
6b8edb51
PA
6780void
6781remote_target::interrupt_query ()
c906108c 6782{
abc56d60 6783 struct remote_state *rs = get_remote_state ();
c906108c 6784
abc56d60 6785 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 6786 {
abc56d60
PA
6787 if (query (_("The target is not responding to interrupt requests.\n"
6788 "Stop debugging it? ")))
74531fed 6789 {
78a095c3 6790 remote_unpush_target ();
abc56d60 6791 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
6792 }
6793 }
abc56d60
PA
6794 else
6795 {
6796 if (query (_("Interrupted while waiting for the program.\n"
6797 "Give up waiting? ")))
6798 quit ();
6799 }
c906108c
SS
6800}
6801
6426a772
JM
6802/* Enable/disable target terminal ownership. Most targets can use
6803 terminal groups to control terminal ownership. Remote targets are
6804 different in that explicit transfer of ownership to/from GDB/target
23860348 6805 is required. */
6426a772 6806
f6ac5f3d
PA
6807void
6808remote_target::terminal_inferior ()
6426a772 6809{
6426a772
JM
6810 /* NOTE: At this point we could also register our selves as the
6811 recipient of all input. Any characters typed could then be
23860348 6812 passed on down to the target. */
6426a772
JM
6813}
6814
f6ac5f3d
PA
6815void
6816remote_target::terminal_ours ()
6426a772 6817{
6426a772
JM
6818}
6819
176a6961 6820static void
917317f4 6821remote_console_output (char *msg)
c906108c
SS
6822{
6823 char *p;
6824
c5aa993b 6825 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
6826 {
6827 char tb[2];
6828 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 6829
c906108c
SS
6830 tb[0] = c;
6831 tb[1] = 0;
43ff13b4 6832 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 6833 }
00db5b94
PA
6834 gdb_flush (gdb_stdtarg);
6835}
74531fed 6836
74531fed
PA
6837DEF_VEC_O(cached_reg_t);
6838
722247f1 6839typedef struct stop_reply
74531fed 6840{
722247f1 6841 struct notif_event base;
74531fed 6842
722247f1 6843 /* The identifier of the thread about this event */
74531fed
PA
6844 ptid_t ptid;
6845
340e3c99 6846 /* The remote state this event is associated with. When the remote
bcc75809
YQ
6847 connection, represented by a remote_state object, is closed,
6848 all the associated stop_reply events should be released. */
6849 struct remote_state *rs;
6850
74531fed
PA
6851 struct target_waitstatus ws;
6852
5cd63fda
PA
6853 /* The architecture associated with the expedited registers. */
6854 gdbarch *arch;
6855
15148d6a
PA
6856 /* Expedited registers. This makes remote debugging a bit more
6857 efficient for those targets that provide critical registers as
6858 part of their normal status mechanism (as another roundtrip to
6859 fetch them is avoided). */
74531fed
PA
6860 VEC(cached_reg_t) *regcache;
6861
f7e6eed5
PA
6862 enum target_stop_reason stop_reason;
6863
74531fed
PA
6864 CORE_ADDR watch_data_address;
6865
dc146f7c 6866 int core;
722247f1 6867} *stop_reply_p;
a744cf53 6868
74531fed
PA
6869static void
6870stop_reply_xfree (struct stop_reply *r)
6871{
f48ff2a7 6872 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
6873}
6874
221e1a37
PA
6875/* Return the length of the stop reply queue. */
6876
6b8edb51
PA
6877int
6878remote_target::stop_reply_queue_length ()
221e1a37 6879{
6b8edb51 6880 remote_state *rs = get_remote_state ();
953edf2b 6881 return rs->stop_reply_queue.size ();
221e1a37
PA
6882}
6883
6b8edb51
PA
6884void
6885remote_notif_stop_parse (remote_target *remote,
6886 struct notif_client *self, char *buf,
722247f1
YQ
6887 struct notif_event *event)
6888{
6b8edb51 6889 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
722247f1
YQ
6890}
6891
6892static void
6b8edb51
PA
6893remote_notif_stop_ack (remote_target *remote,
6894 struct notif_client *self, char *buf,
722247f1
YQ
6895 struct notif_event *event)
6896{
6897 struct stop_reply *stop_reply = (struct stop_reply *) event;
6898
6899 /* acknowledge */
6b8edb51 6900 putpkt (remote, self->ack_command);
722247f1
YQ
6901
6902 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6b8edb51 6903 {
722247f1
YQ
6904 /* We got an unknown stop reply. */
6905 error (_("Unknown stop reply"));
6b8edb51 6906 }
722247f1 6907
6b8edb51 6908 remote->push_stop_reply (stop_reply);
722247f1
YQ
6909}
6910
6911static int
6b8edb51
PA
6912remote_notif_stop_can_get_pending_events (remote_target *remote,
6913 struct notif_client *self)
722247f1
YQ
6914{
6915 /* We can't get pending events in remote_notif_process for
6916 notification stop, and we have to do this in remote_wait_ns
6917 instead. If we fetch all queued events from stub, remote stub
6918 may exit and we have no chance to process them back in
6919 remote_wait_ns. */
6b8edb51
PA
6920 remote_state *rs = remote->get_remote_state ();
6921 mark_async_event_handler (rs->remote_async_inferior_event_token);
722247f1
YQ
6922 return 0;
6923}
6924
6925static void
6926stop_reply_dtr (struct notif_event *event)
6927{
6928 struct stop_reply *r = (struct stop_reply *) event;
d1dff226
AH
6929 cached_reg_t *reg;
6930 int ix;
6931
6932 for (ix = 0;
6933 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6934 ix++)
6935 xfree (reg->data);
722247f1
YQ
6936
6937 VEC_free (cached_reg_t, r->regcache);
6938}
6939
6940static struct notif_event *
6941remote_notif_stop_alloc_reply (void)
6942{
8d749320
SM
6943 /* We cast to a pointer to the "base class". */
6944 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
6945
6946 r->dtr = stop_reply_dtr;
6947
6948 return r;
6949}
6950
6951/* A client of notification Stop. */
6952
6953struct notif_client notif_client_stop =
6954{
6955 "Stop",
6956 "vStopped",
6957 remote_notif_stop_parse,
6958 remote_notif_stop_ack,
6959 remote_notif_stop_can_get_pending_events,
6960 remote_notif_stop_alloc_reply,
f48ff2a7 6961 REMOTE_NOTIF_STOP,
722247f1
YQ
6962};
6963
85ad3aaf 6964/* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
cbb8991c
DB
6965 the pid of the process that owns the threads we want to check, or
6966 -1 if we want to check all threads. */
6967
6968static int
6969is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6970 ptid_t thread_ptid)
6971{
6972 if (ws->kind == TARGET_WAITKIND_FORKED
6973 || ws->kind == TARGET_WAITKIND_VFORKED)
6974 {
e99b03dc 6975 if (event_pid == -1 || event_pid == thread_ptid.pid ())
cbb8991c
DB
6976 return 1;
6977 }
6978
6979 return 0;
6980}
6981
85ad3aaf
PA
6982/* Return the thread's pending status used to determine whether the
6983 thread is a fork parent stopped at a fork event. */
6984
6985static struct target_waitstatus *
6986thread_pending_fork_status (struct thread_info *thread)
6987{
6988 if (thread->suspend.waitstatus_pending_p)
6989 return &thread->suspend.waitstatus;
6990 else
6991 return &thread->pending_follow;
6992}
6993
6994/* Determine if THREAD is a pending fork parent thread. */
6995
6996static int
6997is_pending_fork_parent_thread (struct thread_info *thread)
6998{
6999 struct target_waitstatus *ws = thread_pending_fork_status (thread);
7000 int pid = -1;
7001
7002 return is_pending_fork_parent (ws, pid, thread->ptid);
7003}
7004
cbb8991c
DB
7005/* If CONTEXT contains any fork child threads that have not been
7006 reported yet, remove them from the CONTEXT list. If such a
7007 thread exists it is because we are stopped at a fork catchpoint
7008 and have not yet called follow_fork, which will set up the
7009 host-side data structures for the new process. */
7010
6b8edb51
PA
7011void
7012remote_target::remove_new_fork_children (threads_listing_context *context)
cbb8991c
DB
7013{
7014 struct thread_info * thread;
7015 int pid = -1;
7016 struct notif_client *notif = &notif_client_stop;
cbb8991c
DB
7017
7018 /* For any threads stopped at a fork event, remove the corresponding
7019 fork child threads from the CONTEXT list. */
7020 ALL_NON_EXITED_THREADS (thread)
7021 {
85ad3aaf 7022 struct target_waitstatus *ws = thread_pending_fork_status (thread);
cbb8991c
DB
7023
7024 if (is_pending_fork_parent (ws, pid, thread->ptid))
21fe1c75 7025 context->remove_thread (ws->value.related_pid);
cbb8991c
DB
7026 }
7027
7028 /* Check for any pending fork events (not reported or processed yet)
7029 in process PID and remove those fork child threads from the
7030 CONTEXT list as well. */
7031 remote_notif_get_pending_events (notif);
953edf2b
TT
7032 for (auto &event : get_remote_state ()->stop_reply_queue)
7033 if (event->ws.kind == TARGET_WAITKIND_FORKED
7034 || event->ws.kind == TARGET_WAITKIND_VFORKED
7035 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
7036 context->remove_thread (event->ws.value.related_pid);
85ad3aaf
PA
7037}
7038
7039/* Check whether any event pending in the vStopped queue would prevent
7040 a global or process wildcard vCont action. Clear
7041 *may_global_wildcard if we can't do a global wildcard (vCont;c),
7042 and clear the event inferior's may_wildcard_vcont flag if we can't
7043 do a process-wide wildcard resume (vCont;c:pPID.-1). */
7044
6b8edb51
PA
7045void
7046remote_target::check_pending_events_prevent_wildcard_vcont
7047 (int *may_global_wildcard)
85ad3aaf
PA
7048{
7049 struct notif_client *notif = &notif_client_stop;
7050
7051 remote_notif_get_pending_events (notif);
953edf2b
TT
7052 for (auto &event : get_remote_state ()->stop_reply_queue)
7053 {
7054 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
7055 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
7056 continue;
85ad3aaf 7057
953edf2b
TT
7058 if (event->ws.kind == TARGET_WAITKIND_FORKED
7059 || event->ws.kind == TARGET_WAITKIND_VFORKED)
7060 *may_global_wildcard = 0;
722247f1 7061
953edf2b 7062 struct inferior *inf = find_inferior_ptid (event->ptid);
722247f1 7063
953edf2b
TT
7064 /* This may be the first time we heard about this process.
7065 Regardless, we must not do a global wildcard resume, otherwise
7066 we'd resume this process too. */
7067 *may_global_wildcard = 0;
7068 if (inf != NULL)
7069 get_remote_inferior (inf)->may_wildcard_vcont = false;
722247f1 7070 }
722247f1
YQ
7071}
7072
f48ff2a7 7073/* Discard all pending stop replies of inferior INF. */
c906108c 7074
6b8edb51
PA
7075void
7076remote_target::discard_pending_stop_replies (struct inferior *inf)
c906108c 7077{
f48ff2a7
YQ
7078 struct stop_reply *reply;
7079 struct remote_state *rs = get_remote_state ();
7080 struct remote_notif_state *rns = rs->notif_state;
7081
7082 /* This function can be notified when an inferior exists. When the
7083 target is not remote, the notification state is NULL. */
7084 if (rs->remote_desc == NULL)
7085 return;
7086
7087 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 7088
74531fed 7089 /* Discard the in-flight notification. */
e99b03dc 7090 if (reply != NULL && reply->ptid.pid () == inf->pid)
74531fed 7091 {
722247f1 7092 stop_reply_xfree (reply);
f48ff2a7 7093 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 7094 }
c906108c 7095
74531fed
PA
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->ptid.pid () == inf->pid;
7103 });
7104 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
bcc75809
YQ
7105}
7106
7107/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7 7108
6b8edb51
PA
7109void
7110remote_target::discard_pending_stop_replies_in_queue ()
f48ff2a7 7111{
6b8edb51 7112 remote_state *rs = get_remote_state ();
f48ff2a7 7113
f48ff2a7
YQ
7114 /* Discard the stop replies we have already pulled with
7115 vStopped. */
953edf2b
TT
7116 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7117 rs->stop_reply_queue.end (),
7118 [=] (const stop_reply_up &event)
7119 {
7120 return event->rs == rs;
7121 });
7122 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
74531fed 7123}
43ff13b4 7124
722247f1
YQ
7125/* Remove the first reply in 'stop_reply_queue' which matches
7126 PTID. */
2e9f7625 7127
6b8edb51
PA
7128struct stop_reply *
7129remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 7130{
953edf2b 7131 remote_state *rs = get_remote_state ();
722247f1 7132
953edf2b
TT
7133 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7134 rs->stop_reply_queue.end (),
7135 [=] (const stop_reply_up &event)
7136 {
7137 return event->ptid.matches (ptid);
7138 });
7139 struct stop_reply *result;
7140 if (iter == rs->stop_reply_queue.end ())
7141 result = nullptr;
7142 else
7143 {
7144 result = iter->release ();
7145 rs->stop_reply_queue.erase (iter);
7146 }
722247f1 7147
722247f1
YQ
7148 if (notif_debug)
7149 fprintf_unfiltered (gdb_stdlog,
7150 "notif: discard queued event: 'Stop' in %s\n",
7151 target_pid_to_str (ptid));
a744cf53 7152
953edf2b 7153 return result;
74531fed 7154}
75c99385 7155
74531fed
PA
7156/* Look for a queued stop reply belonging to PTID. If one is found,
7157 remove it from the queue, and return it. Returns NULL if none is
7158 found. If there are still queued events left to process, tell the
7159 event loop to get back to target_wait soon. */
e24a49d8 7160
6b8edb51
PA
7161struct stop_reply *
7162remote_target::queued_stop_reply (ptid_t ptid)
74531fed 7163{
953edf2b 7164 remote_state *rs = get_remote_state ();
722247f1 7165 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 7166
953edf2b 7167 if (!rs->stop_reply_queue.empty ())
6b8edb51 7168 {
6b8edb51
PA
7169 /* There's still at least an event left. */
7170 mark_async_event_handler (rs->remote_async_inferior_event_token);
7171 }
74531fed 7172
722247f1 7173 return r;
74531fed
PA
7174}
7175
7176/* Push a fully parsed stop reply in the stop reply queue. Since we
7177 know that we now have at least one queued event left to pass to the
7178 core side, tell the event loop to get back to target_wait soon. */
7179
6b8edb51
PA
7180void
7181remote_target::push_stop_reply (struct stop_reply *new_event)
74531fed 7182{
6b8edb51 7183 remote_state *rs = get_remote_state ();
953edf2b 7184 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
74531fed 7185
722247f1
YQ
7186 if (notif_debug)
7187 fprintf_unfiltered (gdb_stdlog,
7188 "notif: push 'Stop' %s to queue %d\n",
7189 target_pid_to_str (new_event->ptid),
953edf2b 7190 int (rs->stop_reply_queue.size ()));
74531fed 7191
6b8edb51 7192 mark_async_event_handler (rs->remote_async_inferior_event_token);
74531fed
PA
7193}
7194
7195/* Returns true if we have a stop reply for PTID. */
7196
6b8edb51
PA
7197int
7198remote_target::peek_stop_reply (ptid_t ptid)
74531fed 7199{
6b8edb51 7200 remote_state *rs = get_remote_state ();
953edf2b
TT
7201 for (auto &event : rs->stop_reply_queue)
7202 if (ptid == event->ptid
7203 && event->ws.kind == TARGET_WAITKIND_STOPPED)
7204 return 1;
7205 return 0;
74531fed
PA
7206}
7207
26d56a93
SL
7208/* Helper for remote_parse_stop_reply. Return nonzero if the substring
7209 starting with P and ending with PEND matches PREFIX. */
7210
7211static int
7212strprefix (const char *p, const char *pend, const char *prefix)
7213{
7214 for ( ; p < pend; p++, prefix++)
7215 if (*p != *prefix)
7216 return 0;
7217 return *prefix == '\0';
7218}
7219
74531fed
PA
7220/* Parse the stop reply in BUF. Either the function succeeds, and the
7221 result is stored in EVENT, or throws an error. */
7222
6b8edb51
PA
7223void
7224remote_target::remote_parse_stop_reply (char *buf, stop_reply *event)
74531fed 7225{
5cd63fda 7226 remote_arch_state *rsa = NULL;
74531fed 7227 ULONGEST addr;
256642e8 7228 const char *p;
94585166 7229 int skipregs = 0;
74531fed
PA
7230
7231 event->ptid = null_ptid;
bcc75809 7232 event->rs = get_remote_state ();
74531fed
PA
7233 event->ws.kind = TARGET_WAITKIND_IGNORE;
7234 event->ws.value.integer = 0;
f7e6eed5 7235 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 7236 event->regcache = NULL;
dc146f7c 7237 event->core = -1;
74531fed
PA
7238
7239 switch (buf[0])
7240 {
7241 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
7242 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7243 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7244 ss = signal number
7245 n... = register number
7246 r... = register contents
7247 */
7248
7249 p = &buf[3]; /* after Txx */
7250 while (*p)
7251 {
256642e8 7252 const char *p1;
cea39f65 7253 int fieldsize;
43ff13b4 7254
1f10ba14
PA
7255 p1 = strchr (p, ':');
7256 if (p1 == NULL)
7257 error (_("Malformed packet(a) (missing colon): %s\n\
7258Packet: '%s'\n"),
7259 p, buf);
7260 if (p == p1)
7261 error (_("Malformed packet(a) (missing register number): %s\n\
7262Packet: '%s'\n"),
7263 p, buf);
3c3bea1c 7264
1f10ba14
PA
7265 /* Some "registers" are actually extended stop information.
7266 Note if you're adding a new entry here: GDB 7.9 and
7267 earlier assume that all register "numbers" that start
7268 with an hex digit are real register numbers. Make sure
7269 the server only sends such a packet if it knows the
7270 client understands it. */
c8e38a49 7271
26d56a93 7272 if (strprefix (p, p1, "thread"))
1f10ba14 7273 event->ptid = read_ptid (++p1, &p);
82075af2
JS
7274 else if (strprefix (p, p1, "syscall_entry"))
7275 {
7276 ULONGEST sysno;
7277
7278 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7279 p = unpack_varlen_hex (++p1, &sysno);
7280 event->ws.value.syscall_number = (int) sysno;
7281 }
7282 else if (strprefix (p, p1, "syscall_return"))
7283 {
7284 ULONGEST sysno;
7285
7286 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7287 p = unpack_varlen_hex (++p1, &sysno);
7288 event->ws.value.syscall_number = (int) sysno;
7289 }
26d56a93
SL
7290 else if (strprefix (p, p1, "watch")
7291 || strprefix (p, p1, "rwatch")
7292 || strprefix (p, p1, "awatch"))
cea39f65 7293 {
f7e6eed5 7294 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
7295 p = unpack_varlen_hex (++p1, &addr);
7296 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 7297 }
26d56a93 7298 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
7299 {
7300 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7301
7302 /* Make sure the stub doesn't forget to indicate support
7303 with qSupported. */
7304 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7305 error (_("Unexpected swbreak stop reason"));
7306
7307 /* The value part is documented as "must be empty",
7308 though we ignore it, in case we ever decide to make
7309 use of it in a backward compatible way. */
8424cc97 7310 p = strchrnul (p1 + 1, ';');
f7e6eed5 7311 }
26d56a93 7312 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
7313 {
7314 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7315
7316 /* Make sure the stub doesn't forget to indicate support
7317 with qSupported. */
7318 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7319 error (_("Unexpected hwbreak stop reason"));
7320
7321 /* See above. */
8424cc97 7322 p = strchrnul (p1 + 1, ';');
f7e6eed5 7323 }
26d56a93 7324 else if (strprefix (p, p1, "library"))
cea39f65 7325 {
1f10ba14 7326 event->ws.kind = TARGET_WAITKIND_LOADED;
8424cc97 7327 p = strchrnul (p1 + 1, ';');
1f10ba14 7328 }
26d56a93 7329 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
7330 {
7331 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7332 /* p1 will indicate "begin" or "end", but it makes
7333 no difference for now, so ignore it. */
8424cc97 7334 p = strchrnul (p1 + 1, ';');
1f10ba14 7335 }
26d56a93 7336 else if (strprefix (p, p1, "core"))
1f10ba14
PA
7337 {
7338 ULONGEST c;
a744cf53 7339
1f10ba14
PA
7340 p = unpack_varlen_hex (++p1, &c);
7341 event->core = c;
cea39f65 7342 }
26d56a93 7343 else if (strprefix (p, p1, "fork"))
de0d863e
DB
7344 {
7345 event->ws.value.related_pid = read_ptid (++p1, &p);
7346 event->ws.kind = TARGET_WAITKIND_FORKED;
7347 }
26d56a93 7348 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
7349 {
7350 event->ws.value.related_pid = read_ptid (++p1, &p);
7351 event->ws.kind = TARGET_WAITKIND_VFORKED;
7352 }
26d56a93 7353 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
7354 {
7355 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
8424cc97 7356 p = strchrnul (p1 + 1, ';');
c269dbdb 7357 }
6ab24463 7358 else if (strprefix (p, p1, "exec"))
94585166
DB
7359 {
7360 ULONGEST ignored;
7361 char pathname[PATH_MAX];
7362 int pathlen;
7363
7364 /* Determine the length of the execd pathname. */
7365 p = unpack_varlen_hex (++p1, &ignored);
7366 pathlen = (p - p1) / 2;
7367
7368 /* Save the pathname for event reporting and for
7369 the next run command. */
7370 hex2bin (p1, (gdb_byte *) pathname, pathlen);
7371 pathname[pathlen] = '\0';
7372
7373 /* This is freed during event handling. */
7374 event->ws.value.execd_pathname = xstrdup (pathname);
7375 event->ws.kind = TARGET_WAITKIND_EXECD;
7376
7377 /* Skip the registers included in this packet, since
7378 they may be for an architecture different from the
7379 one used by the original program. */
7380 skipregs = 1;
7381 }
65706a29
PA
7382 else if (strprefix (p, p1, "create"))
7383 {
7384 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
8424cc97 7385 p = strchrnul (p1 + 1, ';');
65706a29 7386 }
cea39f65
MS
7387 else
7388 {
1f10ba14 7389 ULONGEST pnum;
256642e8 7390 const char *p_temp;
1f10ba14 7391
94585166
DB
7392 if (skipregs)
7393 {
8424cc97 7394 p = strchrnul (p1 + 1, ';');
94585166
DB
7395 p++;
7396 continue;
7397 }
7398
1f10ba14
PA
7399 /* Maybe a real ``P'' register number. */
7400 p_temp = unpack_varlen_hex (p, &pnum);
7401 /* If the first invalid character is the colon, we got a
7402 register number. Otherwise, it's an unknown stop
7403 reason. */
7404 if (p_temp == p1)
7405 {
5cd63fda
PA
7406 /* If we haven't parsed the event's thread yet, find
7407 it now, in order to find the architecture of the
7408 reported expedited registers. */
7409 if (event->ptid == null_ptid)
7410 {
7411 const char *thr = strstr (p1 + 1, ";thread:");
7412 if (thr != NULL)
7413 event->ptid = read_ptid (thr + strlen (";thread:"),
7414 NULL);
7415 else
3cada740
PA
7416 {
7417 /* Either the current thread hasn't changed,
7418 or the inferior is not multi-threaded.
7419 The event must be for the thread we last
7420 set as (or learned as being) current. */
7421 event->ptid = event->rs->general_thread;
7422 }
5cd63fda
PA
7423 }
7424
7425 if (rsa == NULL)
7426 {
7427 inferior *inf = (event->ptid == null_ptid
7428 ? NULL
7429 : find_inferior_ptid (event->ptid));
7430 /* If this is the first time we learn anything
7431 about this process, skip the registers
7432 included in this packet, since we don't yet
7433 know which architecture to use to parse them.
7434 We'll determine the architecture later when
7435 we process the stop reply and retrieve the
7436 target description, via
7437 remote_notice_new_inferior ->
7438 post_create_inferior. */
7439 if (inf == NULL)
7440 {
7441 p = strchrnul (p1 + 1, ';');
7442 p++;
7443 continue;
7444 }
7445
7446 event->arch = inf->gdbarch;
9d6eea31 7447 rsa = event->rs->get_remote_arch_state (event->arch);
5cd63fda
PA
7448 }
7449
7450 packet_reg *reg
7451 = packet_reg_from_pnum (event->arch, rsa, pnum);
1f10ba14 7452 cached_reg_t cached_reg;
43ff13b4 7453
1f10ba14
PA
7454 if (reg == NULL)
7455 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 7456Packet: '%s'\n"),
1f10ba14 7457 hex_string (pnum), p, buf);
c8e38a49 7458
1f10ba14 7459 cached_reg.num = reg->regnum;
d1dff226 7460 cached_reg.data = (gdb_byte *)
5cd63fda 7461 xmalloc (register_size (event->arch, reg->regnum));
4100683b 7462
1f10ba14
PA
7463 p = p1 + 1;
7464 fieldsize = hex2bin (p, cached_reg.data,
5cd63fda 7465 register_size (event->arch, reg->regnum));
1f10ba14 7466 p += 2 * fieldsize;
5cd63fda 7467 if (fieldsize < register_size (event->arch, reg->regnum))
1f10ba14 7468 warning (_("Remote reply is too short: %s"), buf);
74531fed 7469
1f10ba14
PA
7470 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7471 }
7472 else
7473 {
7474 /* Not a number. Silently skip unknown optional
7475 info. */
8424cc97 7476 p = strchrnul (p1 + 1, ';');
1f10ba14 7477 }
cea39f65 7478 }
c8e38a49 7479
cea39f65
MS
7480 if (*p != ';')
7481 error (_("Remote register badly formatted: %s\nhere: %s"),
7482 buf, p);
7483 ++p;
7484 }
5b5596ff
PA
7485
7486 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7487 break;
7488
c8e38a49
PA
7489 /* fall through */
7490 case 'S': /* Old style status, just signal only. */
3a09da41
PA
7491 {
7492 int sig;
7493
7494 event->ws.kind = TARGET_WAITKIND_STOPPED;
7495 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7496 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7497 event->ws.value.sig = (enum gdb_signal) sig;
7498 else
7499 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7500 }
c8e38a49 7501 break;
65706a29
PA
7502 case 'w': /* Thread exited. */
7503 {
256642e8 7504 const char *p;
65706a29
PA
7505 ULONGEST value;
7506
7507 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7508 p = unpack_varlen_hex (&buf[1], &value);
7509 event->ws.value.integer = value;
7510 if (*p != ';')
7511 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 7512 event->ptid = read_ptid (++p, NULL);
65706a29
PA
7513 break;
7514 }
c8e38a49
PA
7515 case 'W': /* Target exited. */
7516 case 'X':
7517 {
256642e8 7518 const char *p;
c8e38a49
PA
7519 int pid;
7520 ULONGEST value;
82f73884 7521
c8e38a49
PA
7522 /* GDB used to accept only 2 hex chars here. Stubs should
7523 only send more if they detect GDB supports multi-process
7524 support. */
7525 p = unpack_varlen_hex (&buf[1], &value);
82f73884 7526
c8e38a49
PA
7527 if (buf[0] == 'W')
7528 {
7529 /* The remote process exited. */
74531fed
PA
7530 event->ws.kind = TARGET_WAITKIND_EXITED;
7531 event->ws.value.integer = value;
c8e38a49
PA
7532 }
7533 else
7534 {
7535 /* The remote process exited with a signal. */
74531fed 7536 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
7537 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7538 event->ws.value.sig = (enum gdb_signal) value;
7539 else
7540 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 7541 }
82f73884 7542
c8e38a49 7543 /* If no process is specified, assume inferior_ptid. */
e99b03dc 7544 pid = inferior_ptid.pid ();
c8e38a49
PA
7545 if (*p == '\0')
7546 ;
7547 else if (*p == ';')
7548 {
7549 p++;
7550
0b24eb2d 7551 if (*p == '\0')
82f73884 7552 ;
61012eef 7553 else if (startswith (p, "process:"))
82f73884 7554 {
c8e38a49 7555 ULONGEST upid;
a744cf53 7556
c8e38a49
PA
7557 p += sizeof ("process:") - 1;
7558 unpack_varlen_hex (p, &upid);
7559 pid = upid;
82f73884
PA
7560 }
7561 else
7562 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 7563 }
c8e38a49
PA
7564 else
7565 error (_("unknown stop reply packet: %s"), buf);
f2907e49 7566 event->ptid = ptid_t (pid);
74531fed
PA
7567 }
7568 break;
f2faf941
PA
7569 case 'N':
7570 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7571 event->ptid = minus_one_ptid;
7572 break;
74531fed
PA
7573 }
7574
d7e15655 7575 if (target_is_non_stop_p () && event->ptid == null_ptid)
74531fed
PA
7576 error (_("No process or thread specified in stop reply: %s"), buf);
7577}
7578
722247f1
YQ
7579/* When the stub wants to tell GDB about a new notification reply, it
7580 sends a notification (%Stop, for example). Those can come it at
7581 any time, hence, we have to make sure that any pending
7582 putpkt/getpkt sequence we're making is finished, before querying
7583 the stub for more events with the corresponding ack command
7584 (vStopped, for example). E.g., if we started a vStopped sequence
7585 immediately upon receiving the notification, something like this
7586 could happen:
74531fed
PA
7587
7588 1.1) --> Hg 1
7589 1.2) <-- OK
7590 1.3) --> g
7591 1.4) <-- %Stop
7592 1.5) --> vStopped
7593 1.6) <-- (registers reply to step #1.3)
7594
7595 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7596 query.
7597
796cb314 7598 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
7599 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7600 doing whatever we were doing:
7601
7602 2.1) --> Hg 1
7603 2.2) <-- OK
7604 2.3) --> g
7605 2.4) <-- %Stop
7606 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7607 2.5) <-- (registers reply to step #2.3)
7608
7609 Eventualy after step #2.5, we return to the event loop, which
7610 notices there's an event on the
7611 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7612 associated callback --- the function below. At this point, we're
7613 always safe to start a vStopped sequence. :
7614
7615 2.6) --> vStopped
7616 2.7) <-- T05 thread:2
7617 2.8) --> vStopped
7618 2.9) --> OK
7619*/
7620
722247f1 7621void
6b8edb51 7622remote_target::remote_notif_get_pending_events (notif_client *nc)
74531fed
PA
7623{
7624 struct remote_state *rs = get_remote_state ();
74531fed 7625
f48ff2a7 7626 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 7627 {
722247f1
YQ
7628 if (notif_debug)
7629 fprintf_unfiltered (gdb_stdlog,
7630 "notif: process: '%s' ack pending event\n",
7631 nc->name);
74531fed 7632
722247f1 7633 /* acknowledge */
6b8edb51 7634 nc->ack (this, nc, rs->buf, rs->notif_state->pending_event[nc->id]);
f48ff2a7 7635 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
7636
7637 while (1)
7638 {
7639 getpkt (&rs->buf, &rs->buf_size, 0);
7640 if (strcmp (rs->buf, "OK") == 0)
7641 break;
7642 else
6b8edb51 7643 remote_notif_ack (this, nc, rs->buf);
74531fed
PA
7644 }
7645 }
722247f1
YQ
7646 else
7647 {
7648 if (notif_debug)
7649 fprintf_unfiltered (gdb_stdlog,
7650 "notif: process: '%s' no pending reply\n",
7651 nc->name);
7652 }
74531fed
PA
7653}
7654
6b8edb51
PA
7655/* Wrapper around remote_target::remote_notif_get_pending_events to
7656 avoid having to export the whole remote_target class. */
7657
7658void
7659remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7660{
7661 remote->remote_notif_get_pending_events (nc);
7662}
7663
74531fed
PA
7664/* Called when it is decided that STOP_REPLY holds the info of the
7665 event that is to be returned to the core. This function always
7666 destroys STOP_REPLY. */
7667
6b8edb51
PA
7668ptid_t
7669remote_target::process_stop_reply (struct stop_reply *stop_reply,
7670 struct target_waitstatus *status)
74531fed
PA
7671{
7672 ptid_t ptid;
7673
7674 *status = stop_reply->ws;
7675 ptid = stop_reply->ptid;
7676
7677 /* If no thread/process was reported by the stub, assume the current
7678 inferior. */
d7e15655 7679 if (ptid == null_ptid)
74531fed
PA
7680 ptid = inferior_ptid;
7681
5f3563ea 7682 if (status->kind != TARGET_WAITKIND_EXITED
f2faf941
PA
7683 && status->kind != TARGET_WAITKIND_SIGNALLED
7684 && status->kind != TARGET_WAITKIND_NO_RESUMED)
74531fed 7685 {
5f3563ea
PA
7686 /* Expedited registers. */
7687 if (stop_reply->regcache)
7688 {
217f1f79 7689 struct regcache *regcache
5cd63fda 7690 = get_thread_arch_regcache (ptid, stop_reply->arch);
5f3563ea
PA
7691 cached_reg_t *reg;
7692 int ix;
7693
7694 for (ix = 0;
d1dff226 7695 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
5f3563ea 7696 ix++)
d1dff226 7697 {
73e1c03f 7698 regcache->raw_supply (reg->num, reg->data);
d1dff226
AH
7699 xfree (reg->data);
7700 }
7701
5f3563ea
PA
7702 VEC_free (cached_reg_t, stop_reply->regcache);
7703 }
74531fed 7704
1941c569 7705 remote_notice_new_inferior (ptid, 0);
7aabaf9d 7706 remote_thread_info *remote_thr = get_remote_thread_info (ptid);
799a2abe
PA
7707 remote_thr->core = stop_reply->core;
7708 remote_thr->stop_reason = stop_reply->stop_reason;
7709 remote_thr->watch_data_address = stop_reply->watch_data_address;
85ad3aaf 7710 remote_thr->vcont_resumed = 0;
74531fed
PA
7711 }
7712
74531fed
PA
7713 stop_reply_xfree (stop_reply);
7714 return ptid;
7715}
7716
7717/* The non-stop mode version of target_wait. */
7718
6b8edb51
PA
7719ptid_t
7720remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
7721{
7722 struct remote_state *rs = get_remote_state ();
74531fed
PA
7723 struct stop_reply *stop_reply;
7724 int ret;
fee9eda9 7725 int is_notif = 0;
74531fed
PA
7726
7727 /* If in non-stop mode, get out of getpkt even if a
7728 notification is received. */
7729
7730 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 7731 0 /* forever */, &is_notif);
74531fed
PA
7732 while (1)
7733 {
fee9eda9 7734 if (ret != -1 && !is_notif)
74531fed
PA
7735 switch (rs->buf[0])
7736 {
7737 case 'E': /* Error of some sort. */
7738 /* We're out of sync with the target now. Did it continue
7739 or not? We can't tell which thread it was in non-stop,
7740 so just ignore this. */
7741 warning (_("Remote failure reply: %s"), rs->buf);
7742 break;
7743 case 'O': /* Console output. */
7744 remote_console_output (rs->buf + 1);
7745 break;
7746 default:
7747 warning (_("Invalid remote reply: %s"), rs->buf);
7748 break;
7749 }
7750
7751 /* Acknowledge a pending stop reply that may have arrived in the
7752 mean time. */
f48ff2a7 7753 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 7754 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
7755
7756 /* If indeed we noticed a stop reply, we're done. */
7757 stop_reply = queued_stop_reply (ptid);
7758 if (stop_reply != NULL)
7759 return process_stop_reply (stop_reply, status);
7760
47608cb1 7761 /* Still no event. If we're just polling for an event, then
74531fed 7762 return to the event loop. */
47608cb1 7763 if (options & TARGET_WNOHANG)
74531fed
PA
7764 {
7765 status->kind = TARGET_WAITKIND_IGNORE;
7766 return minus_one_ptid;
7767 }
7768
47608cb1 7769 /* Otherwise do a blocking wait. */
74531fed 7770 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 7771 1 /* forever */, &is_notif);
74531fed
PA
7772 }
7773}
7774
7775/* Wait until the remote machine stops, then return, storing status in
7776 STATUS just as `wait' would. */
7777
6b8edb51
PA
7778ptid_t
7779remote_target::wait_as (ptid_t ptid, target_waitstatus *status, int options)
74531fed
PA
7780{
7781 struct remote_state *rs = get_remote_state ();
74531fed 7782 ptid_t event_ptid = null_ptid;
cea39f65 7783 char *buf;
74531fed
PA
7784 struct stop_reply *stop_reply;
7785
47608cb1
PA
7786 again:
7787
74531fed
PA
7788 status->kind = TARGET_WAITKIND_IGNORE;
7789 status->value.integer = 0;
7790
7791 stop_reply = queued_stop_reply (ptid);
7792 if (stop_reply != NULL)
7793 return process_stop_reply (stop_reply, status);
7794
7795 if (rs->cached_wait_status)
7796 /* Use the cached wait status, but only once. */
7797 rs->cached_wait_status = 0;
7798 else
7799 {
7800 int ret;
722247f1 7801 int is_notif;
567420d1 7802 int forever = ((options & TARGET_WNOHANG) == 0
6b8edb51 7803 && rs->wait_forever_enabled_p);
567420d1
PA
7804
7805 if (!rs->waiting_for_stop_reply)
7806 {
7807 status->kind = TARGET_WAITKIND_NO_RESUMED;
7808 return minus_one_ptid;
7809 }
74531fed 7810
74531fed
PA
7811 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7812 _never_ wait for ever -> test on target_is_async_p().
7813 However, before we do that we need to ensure that the caller
7814 knows how to take the target into/out of async mode. */
722247f1 7815 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 7816 forever, &is_notif);
722247f1
YQ
7817
7818 /* GDB gets a notification. Return to core as this event is
7819 not interesting. */
7820 if (ret != -1 && is_notif)
7821 return minus_one_ptid;
567420d1
PA
7822
7823 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7824 return minus_one_ptid;
74531fed
PA
7825 }
7826
7827 buf = rs->buf;
7828
3a29589a
DJ
7829 /* Assume that the target has acknowledged Ctrl-C unless we receive
7830 an 'F' or 'O' packet. */
7831 if (buf[0] != 'F' && buf[0] != 'O')
7832 rs->ctrlc_pending_p = 0;
7833
74531fed
PA
7834 switch (buf[0])
7835 {
7836 case 'E': /* Error of some sort. */
7837 /* We're out of sync with the target now. Did it continue or
7838 not? Not is more likely, so report a stop. */
29090fb6
LM
7839 rs->waiting_for_stop_reply = 0;
7840
74531fed
PA
7841 warning (_("Remote failure reply: %s"), buf);
7842 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 7843 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
7844 break;
7845 case 'F': /* File-I/O request. */
e42e5352
YQ
7846 /* GDB may access the inferior memory while handling the File-I/O
7847 request, but we don't want GDB accessing memory while waiting
7848 for a stop reply. See the comments in putpkt_binary. Set
7849 waiting_for_stop_reply to 0 temporarily. */
7850 rs->waiting_for_stop_reply = 0;
6b8edb51 7851 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
3a29589a 7852 rs->ctrlc_pending_p = 0;
e42e5352
YQ
7853 /* GDB handled the File-I/O request, and the target is running
7854 again. Keep waiting for events. */
7855 rs->waiting_for_stop_reply = 1;
74531fed 7856 break;
f2faf941 7857 case 'N': case 'T': case 'S': case 'X': case 'W':
74531fed 7858 {
29090fb6
LM
7859 struct stop_reply *stop_reply;
7860
7861 /* There is a stop reply to handle. */
7862 rs->waiting_for_stop_reply = 0;
7863
7864 stop_reply
6b8edb51
PA
7865 = (struct stop_reply *) remote_notif_parse (this,
7866 &notif_client_stop,
722247f1 7867 rs->buf);
74531fed 7868
74531fed 7869 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
7870 break;
7871 }
7872 case 'O': /* Console output. */
7873 remote_console_output (buf + 1);
c8e38a49
PA
7874 break;
7875 case '\0':
b73be471 7876 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
7877 {
7878 /* Zero length reply means that we tried 'S' or 'C' and the
7879 remote system doesn't support it. */
223ffa71 7880 target_terminal::ours_for_output ();
c8e38a49
PA
7881 printf_filtered
7882 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
7883 gdb_signal_to_name (rs->last_sent_signal));
7884 rs->last_sent_signal = GDB_SIGNAL_0;
223ffa71 7885 target_terminal::inferior ();
c8e38a49 7886
f5c4fcd9
TT
7887 strcpy (buf, rs->last_sent_step ? "s" : "c");
7888 putpkt (buf);
c8e38a49 7889 break;
43ff13b4 7890 }
86a73007 7891 /* fallthrough */
c8e38a49
PA
7892 default:
7893 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 7894 break;
43ff13b4 7895 }
c8e38a49 7896
f2faf941
PA
7897 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7898 return minus_one_ptid;
7899 else if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
7900 {
7901 /* Nothing interesting happened. If we're doing a non-blocking
7902 poll, we're done. Otherwise, go back to waiting. */
7903 if (options & TARGET_WNOHANG)
7904 return minus_one_ptid;
7905 else
7906 goto again;
7907 }
74531fed
PA
7908 else if (status->kind != TARGET_WAITKIND_EXITED
7909 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884 7910 {
d7e15655 7911 if (event_ptid != null_ptid)
47f8a51d 7912 record_currthread (rs, event_ptid);
82f73884
PA
7913 else
7914 event_ptid = inferior_ptid;
43ff13b4 7915 }
74531fed
PA
7916 else
7917 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 7918 record_currthread (rs, minus_one_ptid);
79d7f229 7919
82f73884 7920 return event_ptid;
43ff13b4
JM
7921}
7922
74531fed
PA
7923/* Wait until the remote machine stops, then return, storing status in
7924 STATUS just as `wait' would. */
7925
f6ac5f3d
PA
7926ptid_t
7927remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
7928{
7929 ptid_t event_ptid;
7930
6efcd9a8 7931 if (target_is_non_stop_p ())
6b8edb51 7932 event_ptid = wait_ns (ptid, status, options);
74531fed 7933 else
6b8edb51 7934 event_ptid = wait_as (ptid, status, options);
c8e38a49 7935
d9d41e78 7936 if (target_is_async_p ())
c8e38a49 7937 {
6b8edb51
PA
7938 remote_state *rs = get_remote_state ();
7939
74531fed
PA
7940 /* If there are are events left in the queue tell the event loop
7941 to return here. */
953edf2b 7942 if (!rs->stop_reply_queue.empty ())
6b8edb51 7943 mark_async_event_handler (rs->remote_async_inferior_event_token);
c8e38a49 7944 }
c8e38a49
PA
7945
7946 return event_ptid;
7947}
7948
74ca34ce 7949/* Fetch a single register using a 'p' packet. */
c906108c 7950
6b8edb51
PA
7951int
7952remote_target::fetch_register_using_p (struct regcache *regcache,
7953 packet_reg *reg)
b96ec7ac 7954{
ac7936df 7955 struct gdbarch *gdbarch = regcache->arch ();
b96ec7ac 7956 struct remote_state *rs = get_remote_state ();
2e9f7625 7957 char *buf, *p;
9890e433 7958 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
b96ec7ac
AC
7959 int i;
7960
4082afcc 7961 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
7962 return 0;
7963
7964 if (reg->pnum == -1)
7965 return 0;
7966
2e9f7625 7967 p = rs->buf;
fcad0fa4 7968 *p++ = 'p';
74ca34ce 7969 p += hexnumstr (p, reg->pnum);
fcad0fa4 7970 *p++ = '\0';
1f4437a4
MS
7971 putpkt (rs->buf);
7972 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 7973
2e9f7625
DJ
7974 buf = rs->buf;
7975
74ca34ce
DJ
7976 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7977 {
7978 case PACKET_OK:
7979 break;
7980 case PACKET_UNKNOWN:
7981 return 0;
7982 case PACKET_ERROR:
27a9c0bf 7983 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
ac7936df 7984 gdbarch_register_name (regcache->arch (),
27a9c0bf
MS
7985 reg->regnum),
7986 buf);
74ca34ce 7987 }
3f9a994c
JB
7988
7989 /* If this register is unfetchable, tell the regcache. */
7990 if (buf[0] == 'x')
8480adf2 7991 {
73e1c03f 7992 regcache->raw_supply (reg->regnum, NULL);
8480adf2 7993 return 1;
b96ec7ac 7994 }
b96ec7ac 7995
3f9a994c
JB
7996 /* Otherwise, parse and supply the value. */
7997 p = buf;
7998 i = 0;
7999 while (p[0] != 0)
8000 {
8001 if (p[1] == 0)
74ca34ce 8002 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
8003
8004 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8005 p += 2;
8006 }
73e1c03f 8007 regcache->raw_supply (reg->regnum, regp);
3f9a994c 8008 return 1;
b96ec7ac
AC
8009}
8010
74ca34ce
DJ
8011/* Fetch the registers included in the target's 'g' packet. */
8012
6b8edb51
PA
8013int
8014remote_target::send_g_packet ()
c906108c 8015{
d01949b6 8016 struct remote_state *rs = get_remote_state ();
cea39f65 8017 int buf_len;
c906108c 8018
bba74b36 8019 xsnprintf (rs->buf, get_remote_packet_size (), "g");
b75abf5b
AK
8020 putpkt (rs->buf);
8021 getpkt (&rs->buf, &rs->buf_size, 0);
8022 if (packet_check_result (rs->buf) == PACKET_ERROR)
8023 error (_("Could not read registers; remote failure reply '%s'"),
8024 rs->buf);
c906108c 8025
29709017
DJ
8026 /* We can get out of synch in various cases. If the first character
8027 in the buffer is not a hex character, assume that has happened
8028 and try to fetch another packet to read. */
8029 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8030 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8031 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8032 && rs->buf[0] != 'x') /* New: unavailable register value. */
8033 {
8034 if (remote_debug)
8035 fprintf_unfiltered (gdb_stdlog,
8036 "Bad register packet; fetching a new packet\n");
8037 getpkt (&rs->buf, &rs->buf_size, 0);
8038 }
8039
74ca34ce
DJ
8040 buf_len = strlen (rs->buf);
8041
8042 /* Sanity check the received packet. */
8043 if (buf_len % 2 != 0)
8044 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
8045
8046 return buf_len / 2;
8047}
8048
6b8edb51
PA
8049void
8050remote_target::process_g_packet (struct regcache *regcache)
29709017 8051{
ac7936df 8052 struct gdbarch *gdbarch = regcache->arch ();
29709017 8053 struct remote_state *rs = get_remote_state ();
9d6eea31 8054 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
29709017
DJ
8055 int i, buf_len;
8056 char *p;
8057 char *regs;
8058
8059 buf_len = strlen (rs->buf);
8060
8061 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce 8062 if (buf_len > 2 * rsa->sizeof_g_packet)
fc809827
SM
8063 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8064 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
74ca34ce
DJ
8065
8066 /* Save the size of the packet sent to us by the target. It is used
8067 as a heuristic when determining the max size of packets that the
8068 target can safely receive. */
8069 if (rsa->actual_register_packet_size == 0)
8070 rsa->actual_register_packet_size = buf_len;
8071
8072 /* If this is smaller than we guessed the 'g' packet would be,
8073 update our records. A 'g' reply that doesn't include a register's
8074 value implies either that the register is not available, or that
8075 the 'p' packet must be used. */
8076 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 8077 {
9dc193c3 8078 long sizeof_g_packet = buf_len / 2;
74ca34ce 8079
4a22f64d 8080 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 8081 {
9dc193c3
LF
8082 long offset = rsa->regs[i].offset;
8083 long reg_size = register_size (gdbarch, i);
8084
74ca34ce
DJ
8085 if (rsa->regs[i].pnum == -1)
8086 continue;
8087
9dc193c3 8088 if (offset >= sizeof_g_packet)
74ca34ce 8089 rsa->regs[i].in_g_packet = 0;
9dc193c3
LF
8090 else if (offset + reg_size > sizeof_g_packet)
8091 error (_("Truncated register %d in remote 'g' packet"), i);
b96ec7ac 8092 else
74ca34ce 8093 rsa->regs[i].in_g_packet = 1;
b96ec7ac 8094 }
9dc193c3
LF
8095
8096 /* Looks valid enough, we can assume this is the correct length
8097 for a 'g' packet. It's important not to adjust
8098 rsa->sizeof_g_packet if we have truncated registers otherwise
8099 this "if" won't be run the next time the method is called
8100 with a packet of the same size and one of the internal errors
8101 below will trigger instead. */
8102 rsa->sizeof_g_packet = sizeof_g_packet;
74ca34ce 8103 }
b323314b 8104
224c3ddb 8105 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
8106
8107 /* Unimplemented registers read as all bits zero. */
ea9c271d 8108 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 8109
c906108c
SS
8110 /* Reply describes registers byte by byte, each byte encoded as two
8111 hex characters. Suck them all up, then supply them to the
8112 register cacheing/storage mechanism. */
8113
74ca34ce 8114 p = rs->buf;
ea9c271d 8115 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 8116 {
74ca34ce
DJ
8117 if (p[0] == 0 || p[1] == 0)
8118 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8119 internal_error (__FILE__, __LINE__,
9b20d036 8120 _("unexpected end of 'g' packet reply"));
74ca34ce 8121
c906108c 8122 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 8123 regs[i] = 0; /* 'x' */
c906108c
SS
8124 else
8125 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8126 p += 2;
8127 }
8128
a744cf53
MS
8129 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8130 {
8131 struct packet_reg *r = &rsa->regs[i];
9dc193c3 8132 long reg_size = register_size (gdbarch, i);
a744cf53
MS
8133
8134 if (r->in_g_packet)
8135 {
9dc193c3 8136 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
a744cf53
MS
8137 /* This shouldn't happen - we adjusted in_g_packet above. */
8138 internal_error (__FILE__, __LINE__,
9b20d036 8139 _("unexpected end of 'g' packet reply"));
a744cf53
MS
8140 else if (rs->buf[r->offset * 2] == 'x')
8141 {
8142 gdb_assert (r->offset * 2 < strlen (rs->buf));
8143 /* The register isn't available, mark it as such (at
8144 the same time setting the value to zero). */
73e1c03f 8145 regcache->raw_supply (r->regnum, NULL);
a744cf53
MS
8146 }
8147 else
73e1c03f 8148 regcache->raw_supply (r->regnum, regs + r->offset);
a744cf53
MS
8149 }
8150 }
c906108c
SS
8151}
8152
6b8edb51
PA
8153void
8154remote_target::fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
8155{
8156 send_g_packet ();
56be3814 8157 process_g_packet (regcache);
29709017
DJ
8158}
8159
e6e4e701
PA
8160/* Make the remote selected traceframe match GDB's selected
8161 traceframe. */
8162
6b8edb51
PA
8163void
8164remote_target::set_remote_traceframe ()
e6e4e701
PA
8165{
8166 int newnum;
262e1174 8167 struct remote_state *rs = get_remote_state ();
e6e4e701 8168
262e1174 8169 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
8170 return;
8171
8172 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 8173 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
8174
8175 newnum = target_trace_find (tfind_number,
8176 get_traceframe_number (), 0, 0, NULL);
8177
8178 /* Should not happen. If it does, all bets are off. */
8179 if (newnum != get_traceframe_number ())
8180 warning (_("could not set remote traceframe"));
8181}
8182
f6ac5f3d
PA
8183void
8184remote_target::fetch_registers (struct regcache *regcache, int regnum)
74ca34ce 8185{
ac7936df 8186 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8187 struct remote_state *rs = get_remote_state ();
8188 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8189 int i;
8190
e6e4e701 8191 set_remote_traceframe ();
222312d3 8192 set_general_thread (regcache->ptid ());
74ca34ce
DJ
8193
8194 if (regnum >= 0)
8195 {
5cd63fda 8196 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8197
74ca34ce
DJ
8198 gdb_assert (reg != NULL);
8199
8200 /* If this register might be in the 'g' packet, try that first -
8201 we are likely to read more than one register. If this is the
8202 first 'g' packet, we might be overly optimistic about its
8203 contents, so fall back to 'p'. */
8204 if (reg->in_g_packet)
8205 {
56be3814 8206 fetch_registers_using_g (regcache);
74ca34ce
DJ
8207 if (reg->in_g_packet)
8208 return;
8209 }
8210
56be3814 8211 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
8212 return;
8213
8214 /* This register is not available. */
73e1c03f 8215 regcache->raw_supply (reg->regnum, NULL);
74ca34ce
DJ
8216
8217 return;
8218 }
8219
56be3814 8220 fetch_registers_using_g (regcache);
74ca34ce 8221
5cd63fda 8222 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8223 if (!rsa->regs[i].in_g_packet)
56be3814 8224 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
8225 {
8226 /* This register is not available. */
73e1c03f 8227 regcache->raw_supply (i, NULL);
74ca34ce
DJ
8228 }
8229}
8230
c906108c
SS
8231/* Prepare to store registers. Since we may send them all (using a
8232 'G' request), we have to read out the ones we don't want to change
8233 first. */
8234
f6ac5f3d
PA
8235void
8236remote_target::prepare_to_store (struct regcache *regcache)
c906108c 8237{
9d6eea31
PA
8238 struct remote_state *rs = get_remote_state ();
8239 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cf0e1e0d 8240 int i;
cf0e1e0d 8241
c906108c 8242 /* Make sure the entire registers array is valid. */
4082afcc 8243 switch (packet_support (PACKET_P))
5a2468f5
JM
8244 {
8245 case PACKET_DISABLE:
8246 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 8247 /* Make sure all the necessary registers are cached. */
ac7936df 8248 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
ea9c271d 8249 if (rsa->regs[i].in_g_packet)
0b47d985 8250 regcache->raw_update (rsa->regs[i].regnum);
5a2468f5
JM
8251 break;
8252 case PACKET_ENABLE:
8253 break;
8254 }
8255}
8256
ad10f812 8257/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 8258 packet was not recognized. */
5a2468f5 8259
6b8edb51
PA
8260int
8261remote_target::store_register_using_P (const struct regcache *regcache,
8262 packet_reg *reg)
5a2468f5 8263{
ac7936df 8264 struct gdbarch *gdbarch = regcache->arch ();
d01949b6 8265 struct remote_state *rs = get_remote_state ();
5a2468f5 8266 /* Try storing a single register. */
6d820c5c 8267 char *buf = rs->buf;
9890e433 8268 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
5a2468f5 8269 char *p;
5a2468f5 8270
4082afcc 8271 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
8272 return 0;
8273
8274 if (reg->pnum == -1)
8275 return 0;
8276
ea9c271d 8277 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 8278 p = buf + strlen (buf);
34a79281 8279 regcache->raw_collect (reg->regnum, regp);
4a22f64d 8280 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
8281 putpkt (rs->buf);
8282 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 8283
74ca34ce
DJ
8284 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8285 {
8286 case PACKET_OK:
8287 return 1;
8288 case PACKET_ERROR:
27a9c0bf
MS
8289 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8290 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
8291 case PACKET_UNKNOWN:
8292 return 0;
8293 default:
8294 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8295 }
c906108c
SS
8296}
8297
23860348
MS
8298/* Store register REGNUM, or all registers if REGNUM == -1, from the
8299 contents of the register cache buffer. FIXME: ignores errors. */
c906108c 8300
6b8edb51
PA
8301void
8302remote_target::store_registers_using_G (const struct regcache *regcache)
c906108c 8303{
d01949b6 8304 struct remote_state *rs = get_remote_state ();
9d6eea31 8305 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
cfd77fa1 8306 gdb_byte *regs;
c906108c
SS
8307 char *p;
8308
193cb69f
AC
8309 /* Extract all the registers in the regcache copying them into a
8310 local buffer. */
8311 {
b323314b 8312 int i;
a744cf53 8313
224c3ddb 8314 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 8315 memset (regs, 0, rsa->sizeof_g_packet);
ac7936df 8316 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
193cb69f 8317 {
ea9c271d 8318 struct packet_reg *r = &rsa->regs[i];
a744cf53 8319
b323314b 8320 if (r->in_g_packet)
34a79281 8321 regcache->raw_collect (r->regnum, regs + r->offset);
193cb69f
AC
8322 }
8323 }
c906108c
SS
8324
8325 /* Command describes registers byte by byte,
8326 each byte encoded as two hex characters. */
6d820c5c 8327 p = rs->buf;
193cb69f 8328 *p++ = 'G';
74ca34ce 8329 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
8330 putpkt (rs->buf);
8331 getpkt (&rs->buf, &rs->buf_size, 0);
8332 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
8333 error (_("Could not write registers; remote failure reply '%s'"),
8334 rs->buf);
c906108c 8335}
74ca34ce
DJ
8336
8337/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8338 of the register cache buffer. FIXME: ignores errors. */
8339
f6ac5f3d
PA
8340void
8341remote_target::store_registers (struct regcache *regcache, int regnum)
74ca34ce 8342{
5cd63fda 8343 struct gdbarch *gdbarch = regcache->arch ();
9d6eea31
PA
8344 struct remote_state *rs = get_remote_state ();
8345 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
74ca34ce
DJ
8346 int i;
8347
e6e4e701 8348 set_remote_traceframe ();
222312d3 8349 set_general_thread (regcache->ptid ());
74ca34ce
DJ
8350
8351 if (regnum >= 0)
8352 {
5cd63fda 8353 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8354
74ca34ce
DJ
8355 gdb_assert (reg != NULL);
8356
8357 /* Always prefer to store registers using the 'P' packet if
8358 possible; we often change only a small number of registers.
8359 Sometimes we change a larger number; we'd need help from a
8360 higher layer to know to use 'G'. */
56be3814 8361 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
8362 return;
8363
8364 /* For now, don't complain if we have no way to write the
8365 register. GDB loses track of unavailable registers too
8366 easily. Some day, this may be an error. We don't have
0df8b418 8367 any way to read the register, either... */
74ca34ce
DJ
8368 if (!reg->in_g_packet)
8369 return;
8370
56be3814 8371 store_registers_using_G (regcache);
74ca34ce
DJ
8372 return;
8373 }
8374
56be3814 8375 store_registers_using_G (regcache);
74ca34ce 8376
5cd63fda 8377 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8378 if (!rsa->regs[i].in_g_packet)
56be3814 8379 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
8380 /* See above for why we do not issue an error here. */
8381 continue;
8382}
c906108c
SS
8383\f
8384
8385/* Return the number of hex digits in num. */
8386
8387static int
fba45db2 8388hexnumlen (ULONGEST num)
c906108c
SS
8389{
8390 int i;
8391
8392 for (i = 0; num != 0; i++)
8393 num >>= 4;
8394
325fac50 8395 return std::max (i, 1);
c906108c
SS
8396}
8397
2df3850c 8398/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
8399
8400static int
fba45db2 8401hexnumstr (char *buf, ULONGEST num)
c906108c 8402{
c906108c 8403 int len = hexnumlen (num);
a744cf53 8404
2df3850c
JM
8405 return hexnumnstr (buf, num, len);
8406}
8407
c906108c 8408
2df3850c 8409/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 8410
2df3850c 8411static int
fba45db2 8412hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
8413{
8414 int i;
8415
8416 buf[width] = '\0';
8417
8418 for (i = width - 1; i >= 0; i--)
c906108c 8419 {
c5aa993b 8420 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
8421 num >>= 4;
8422 }
8423
2df3850c 8424 return width;
c906108c
SS
8425}
8426
23860348 8427/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
8428
8429static CORE_ADDR
fba45db2 8430remote_address_masked (CORE_ADDR addr)
c906108c 8431{
883b9c6c 8432 unsigned int address_size = remote_address_size;
a744cf53 8433
911c95a5
UW
8434 /* If "remoteaddresssize" was not set, default to target address size. */
8435 if (!address_size)
f5656ead 8436 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
8437
8438 if (address_size > 0
8439 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
8440 {
8441 /* Only create a mask when that mask can safely be constructed
23860348 8442 in a ULONGEST variable. */
c906108c 8443 ULONGEST mask = 1;
a744cf53 8444
911c95a5 8445 mask = (mask << address_size) - 1;
c906108c
SS
8446 addr &= mask;
8447 }
8448 return addr;
8449}
8450
8451/* Determine whether the remote target supports binary downloading.
8452 This is accomplished by sending a no-op memory write of zero length
8453 to the target at the specified address. It does not suffice to send
23860348
MS
8454 the whole packet, since many stubs strip the eighth bit and
8455 subsequently compute a wrong checksum, which causes real havoc with
8456 remote_write_bytes.
7a292a7a 8457
96baa820 8458 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 8459 clean. In cases like this, the user should clear "remote
23860348 8460 X-packet". */
96baa820 8461
6b8edb51
PA
8462void
8463remote_target::check_binary_download (CORE_ADDR addr)
c906108c 8464{
d01949b6 8465 struct remote_state *rs = get_remote_state ();
24b06219 8466
4082afcc 8467 switch (packet_support (PACKET_X))
c906108c 8468 {
96baa820
JM
8469 case PACKET_DISABLE:
8470 break;
8471 case PACKET_ENABLE:
8472 break;
8473 case PACKET_SUPPORT_UNKNOWN:
8474 {
96baa820 8475 char *p;
802188a7 8476
2e9f7625 8477 p = rs->buf;
96baa820
JM
8478 *p++ = 'X';
8479 p += hexnumstr (p, (ULONGEST) addr);
8480 *p++ = ',';
8481 p += hexnumstr (p, (ULONGEST) 0);
8482 *p++ = ':';
8483 *p = '\0';
802188a7 8484
2e9f7625 8485 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 8486 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 8487
2e9f7625 8488 if (rs->buf[0] == '\0')
96baa820
JM
8489 {
8490 if (remote_debug)
8491 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8492 "binary downloading NOT "
8493 "supported by target\n");
444abaca 8494 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
8495 }
8496 else
8497 {
8498 if (remote_debug)
8499 fprintf_unfiltered (gdb_stdlog,
64b9b334 8500 "binary downloading supported by target\n");
444abaca 8501 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
8502 }
8503 break;
8504 }
c906108c
SS
8505 }
8506}
8507
124e13d9
SM
8508/* Helper function to resize the payload in order to try to get a good
8509 alignment. We try to write an amount of data such that the next write will
8510 start on an address aligned on REMOTE_ALIGN_WRITES. */
8511
8512static int
8513align_for_efficient_write (int todo, CORE_ADDR memaddr)
8514{
8515 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8516}
8517
c906108c
SS
8518/* Write memory data directly to the remote machine.
8519 This does not inform the data cache; the data cache uses this.
a76d924d 8520 HEADER is the starting part of the packet.
c906108c
SS
8521 MEMADDR is the address in the remote memory space.
8522 MYADDR is the address of the buffer in our space.
124e13d9
SM
8523 LEN_UNITS is the number of addressable units to write.
8524 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
8525 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8526 should send data as binary ('X'), or hex-encoded ('M').
8527
8528 The function creates packet of the form
8529 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8530
124e13d9 8531 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
8532
8533 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8534 are omitted.
8535
9b409511 8536 Return the transferred status, error or OK (an
124e13d9
SM
8537 'enum target_xfer_status' value). Save the number of addressable units
8538 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8539
8540 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8541 exchange between gdb and the stub could look like (?? in place of the
8542 checksum):
8543
8544 -> $m1000,4#??
8545 <- aaaabbbbccccdddd
8546
8547 -> $M1000,3:eeeeffffeeee#??
8548 <- OK
8549
8550 -> $m1000,4#??
8551 <- eeeeffffeeeedddd */
c906108c 8552
6b8edb51
PA
8553target_xfer_status
8554remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8555 const gdb_byte *myaddr,
8556 ULONGEST len_units,
8557 int unit_size,
8558 ULONGEST *xfered_len_units,
8559 char packet_format, int use_length)
c906108c 8560{
6d820c5c 8561 struct remote_state *rs = get_remote_state ();
cfd77fa1 8562 char *p;
a76d924d
DJ
8563 char *plen = NULL;
8564 int plenlen = 0;
124e13d9
SM
8565 int todo_units;
8566 int units_written;
8567 int payload_capacity_bytes;
8568 int payload_length_bytes;
a76d924d
DJ
8569
8570 if (packet_format != 'X' && packet_format != 'M')
8571 internal_error (__FILE__, __LINE__,
9b20d036 8572 _("remote_write_bytes_aux: bad packet format"));
c906108c 8573
124e13d9 8574 if (len_units == 0)
9b409511 8575 return TARGET_XFER_EOF;
b2182ed2 8576
124e13d9 8577 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 8578
6d820c5c
DJ
8579 /* The packet buffer will be large enough for the payload;
8580 get_memory_packet_size ensures this. */
a76d924d 8581 rs->buf[0] = '\0';
c906108c 8582
a257b5bb 8583 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
8584 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8585
124e13d9 8586 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 8587 if (!use_length)
0df8b418 8588 /* The comma won't be used. */
124e13d9
SM
8589 payload_capacity_bytes += 1;
8590 payload_capacity_bytes -= strlen (header);
8591 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 8592
a76d924d 8593 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 8594
a76d924d
DJ
8595 strcat (rs->buf, header);
8596 p = rs->buf + strlen (header);
8597
8598 /* Compute a best guess of the number of bytes actually transfered. */
8599 if (packet_format == 'X')
c906108c 8600 {
23860348 8601 /* Best guess at number of bytes that will fit. */
325fac50
PA
8602 todo_units = std::min (len_units,
8603 (ULONGEST) payload_capacity_bytes / unit_size);
a76d924d 8604 if (use_length)
124e13d9 8605 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50 8606 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
8607 }
8608 else
8609 {
124e13d9 8610 /* Number of bytes that will fit. */
325fac50
PA
8611 todo_units
8612 = std::min (len_units,
8613 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
a76d924d 8614 if (use_length)
124e13d9 8615 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50
PA
8616 todo_units = std::min (todo_units,
8617 (payload_capacity_bytes / unit_size) / 2);
917317f4 8618 }
a76d924d 8619
124e13d9 8620 if (todo_units <= 0)
3de11b2e 8621 internal_error (__FILE__, __LINE__,
405f8e94 8622 _("minimum packet size too small to write data"));
802188a7 8623
6765f3e5
DJ
8624 /* If we already need another packet, then try to align the end
8625 of this packet to a useful boundary. */
124e13d9
SM
8626 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8627 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 8628
a257b5bb 8629 /* Append "<memaddr>". */
917317f4
JM
8630 memaddr = remote_address_masked (memaddr);
8631 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 8632
a76d924d
DJ
8633 if (use_length)
8634 {
8635 /* Append ",". */
8636 *p++ = ',';
802188a7 8637
124e13d9
SM
8638 /* Append the length and retain its location and size. It may need to be
8639 adjusted once the packet body has been created. */
a76d924d 8640 plen = p;
124e13d9 8641 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
8642 p += plenlen;
8643 }
a257b5bb
AC
8644
8645 /* Append ":". */
917317f4
JM
8646 *p++ = ':';
8647 *p = '\0';
802188a7 8648
a257b5bb 8649 /* Append the packet body. */
a76d924d 8650 if (packet_format == 'X')
917317f4 8651 {
917317f4
JM
8652 /* Binary mode. Send target system values byte by byte, in
8653 increasing byte addresses. Only escape certain critical
8654 characters. */
124e13d9
SM
8655 payload_length_bytes =
8656 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8657 &units_written, payload_capacity_bytes);
6765f3e5 8658
124e13d9 8659 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
8660 a second try to keep the end of the packet aligned. Don't do
8661 this if the packet is tiny. */
124e13d9 8662 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 8663 {
124e13d9
SM
8664 int new_todo_units;
8665
8666 new_todo_units = align_for_efficient_write (units_written, memaddr);
8667
8668 if (new_todo_units != units_written)
8669 payload_length_bytes =
8670 remote_escape_output (myaddr, new_todo_units, unit_size,
8671 (gdb_byte *) p, &units_written,
8672 payload_capacity_bytes);
6765f3e5
DJ
8673 }
8674
124e13d9
SM
8675 p += payload_length_bytes;
8676 if (use_length && units_written < todo_units)
c906108c 8677 {
802188a7 8678 /* Escape chars have filled up the buffer prematurely,
124e13d9 8679 and we have actually sent fewer units than planned.
917317f4
JM
8680 Fix-up the length field of the packet. Use the same
8681 number of characters as before. */
124e13d9
SM
8682 plen += hexnumnstr (plen, (ULONGEST) units_written,
8683 plenlen);
917317f4 8684 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 8685 }
a76d924d
DJ
8686 }
8687 else
8688 {
917317f4
JM
8689 /* Normal mode: Send target system values byte by byte, in
8690 increasing byte addresses. Each byte is encoded as a two hex
8691 value. */
124e13d9
SM
8692 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8693 units_written = todo_units;
c906108c 8694 }
802188a7 8695
2e9f7625 8696 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 8697 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 8698
2e9f7625 8699 if (rs->buf[0] == 'E')
00d84524 8700 return TARGET_XFER_E_IO;
802188a7 8701
124e13d9
SM
8702 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8703 send fewer units than we'd planned. */
8704 *xfered_len_units = (ULONGEST) units_written;
92ffd475 8705 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
8706}
8707
a76d924d
DJ
8708/* Write memory data directly to the remote machine.
8709 This does not inform the data cache; the data cache uses this.
8710 MEMADDR is the address in the remote memory space.
8711 MYADDR is the address of the buffer in our space.
8712 LEN is the number of bytes.
8713
9b409511
YQ
8714 Return the transferred status, error or OK (an
8715 'enum target_xfer_status' value). Save the number of bytes
8716 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 8717
6b8edb51
PA
8718target_xfer_status
8719remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
8720 ULONGEST len, int unit_size,
8721 ULONGEST *xfered_len)
a76d924d 8722{
a121b7c1 8723 const char *packet_format = NULL;
a76d924d
DJ
8724
8725 /* Check whether the target supports binary download. */
8726 check_binary_download (memaddr);
8727
4082afcc 8728 switch (packet_support (PACKET_X))
a76d924d
DJ
8729 {
8730 case PACKET_ENABLE:
8731 packet_format = "X";
8732 break;
8733 case PACKET_DISABLE:
8734 packet_format = "M";
8735 break;
8736 case PACKET_SUPPORT_UNKNOWN:
8737 internal_error (__FILE__, __LINE__,
8738 _("remote_write_bytes: bad internal state"));
8739 default:
8740 internal_error (__FILE__, __LINE__, _("bad switch"));
8741 }
8742
8743 return remote_write_bytes_aux (packet_format,
124e13d9 8744 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 8745 packet_format[0], 1);
a76d924d
DJ
8746}
8747
9217e74e
YQ
8748/* Read memory data directly from the remote machine.
8749 This does not use the data cache; the data cache uses this.
8750 MEMADDR is the address in the remote memory space.
8751 MYADDR is the address of the buffer in our space.
124e13d9
SM
8752 LEN_UNITS is the number of addressable memory units to read..
8753 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
8754
8755 Return the transferred status, error or OK (an
8756 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
8757 transferred in *XFERED_LEN_UNITS.
8758
8759 See the comment of remote_write_bytes_aux for an example of
8760 memory read/write exchange between gdb and the stub. */
9217e74e 8761
6b8edb51
PA
8762target_xfer_status
8763remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
8764 ULONGEST len_units,
8765 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
8766{
8767 struct remote_state *rs = get_remote_state ();
124e13d9 8768 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 8769 char *p;
124e13d9
SM
8770 int todo_units;
8771 int decoded_bytes;
9217e74e 8772
124e13d9 8773 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
8774 /* The packet buffer will be large enough for the payload;
8775 get_memory_packet_size ensures this. */
8776
124e13d9 8777 /* Number of units that will fit. */
325fac50
PA
8778 todo_units = std::min (len_units,
8779 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
8780
8781 /* Construct "m"<memaddr>","<len>". */
8782 memaddr = remote_address_masked (memaddr);
8783 p = rs->buf;
8784 *p++ = 'm';
8785 p += hexnumstr (p, (ULONGEST) memaddr);
8786 *p++ = ',';
124e13d9 8787 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
8788 *p = '\0';
8789 putpkt (rs->buf);
8790 getpkt (&rs->buf, &rs->buf_size, 0);
8791 if (rs->buf[0] == 'E'
8792 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8793 && rs->buf[3] == '\0')
8794 return TARGET_XFER_E_IO;
8795 /* Reply describes memory byte by byte, each byte encoded as two hex
8796 characters. */
8797 p = rs->buf;
124e13d9 8798 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 8799 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 8800 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
92ffd475 8801 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9217e74e
YQ
8802}
8803
b55fbac4
YQ
8804/* Using the set of read-only target sections of remote, read live
8805 read-only memory.
8acf9577
YQ
8806
8807 For interface/parameters/return description see target.h,
8808 to_xfer_partial. */
8809
6b8edb51
PA
8810target_xfer_status
8811remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
8812 ULONGEST memaddr,
8813 ULONGEST len,
8814 int unit_size,
8815 ULONGEST *xfered_len)
8acf9577
YQ
8816{
8817 struct target_section *secp;
8818 struct target_section_table *table;
8819
6b8edb51 8820 secp = target_section_by_addr (this, memaddr);
8acf9577
YQ
8821 if (secp != NULL
8822 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8823 secp->the_bfd_section)
8824 & SEC_READONLY))
8825 {
8826 struct target_section *p;
8827 ULONGEST memend = memaddr + len;
8828
6b8edb51 8829 table = target_get_section_table (this);
8acf9577
YQ
8830
8831 for (p = table->sections; p < table->sections_end; p++)
8832 {
8833 if (memaddr >= p->addr)
8834 {
8835 if (memend <= p->endaddr)
8836 {
8837 /* Entire transfer is within this section. */
124e13d9 8838 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8839 xfered_len);
8acf9577
YQ
8840 }
8841 else if (memaddr >= p->endaddr)
8842 {
8843 /* This section ends before the transfer starts. */
8844 continue;
8845 }
8846 else
8847 {
8848 /* This section overlaps the transfer. Just do half. */
8849 len = p->endaddr - memaddr;
124e13d9 8850 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8851 xfered_len);
8acf9577
YQ
8852 }
8853 }
8854 }
8855 }
8856
8857 return TARGET_XFER_EOF;
8858}
8859
9217e74e
YQ
8860/* Similar to remote_read_bytes_1, but it reads from the remote stub
8861 first if the requested memory is unavailable in traceframe.
8862 Otherwise, fall back to remote_read_bytes_1. */
c906108c 8863
6b8edb51
PA
8864target_xfer_status
8865remote_target::remote_read_bytes (CORE_ADDR memaddr,
8866 gdb_byte *myaddr, ULONGEST len, int unit_size,
8867 ULONGEST *xfered_len)
c906108c 8868{
6b6aa828 8869 if (len == 0)
96c4f946 8870 return TARGET_XFER_EOF;
b2182ed2 8871
8acf9577
YQ
8872 if (get_traceframe_number () != -1)
8873 {
a79b1bc6 8874 std::vector<mem_range> available;
8acf9577
YQ
8875
8876 /* If we fail to get the set of available memory, then the
8877 target does not support querying traceframe info, and so we
8878 attempt reading from the traceframe anyway (assuming the
8879 target implements the old QTro packet then). */
8880 if (traceframe_available_memory (&available, memaddr, len))
8881 {
a79b1bc6 8882 if (available.empty () || available[0].start != memaddr)
8acf9577
YQ
8883 {
8884 enum target_xfer_status res;
8885
8886 /* Don't read into the traceframe's available
8887 memory. */
a79b1bc6 8888 if (!available.empty ())
8acf9577
YQ
8889 {
8890 LONGEST oldlen = len;
8891
a79b1bc6 8892 len = available[0].start - memaddr;
8acf9577
YQ
8893 gdb_assert (len <= oldlen);
8894 }
8895
8acf9577 8896 /* This goes through the topmost target again. */
6b8edb51 8897 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
124e13d9 8898 len, unit_size, xfered_len);
8acf9577
YQ
8899 if (res == TARGET_XFER_OK)
8900 return TARGET_XFER_OK;
8901 else
8902 {
8903 /* No use trying further, we know some memory starting
8904 at MEMADDR isn't available. */
8905 *xfered_len = len;
92ffd475
PC
8906 return (*xfered_len != 0) ?
8907 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8acf9577
YQ
8908 }
8909 }
8910
8911 /* Don't try to read more than how much is available, in
8912 case the target implements the deprecated QTro packet to
8913 cater for older GDBs (the target's knowledge of read-only
8914 sections may be outdated by now). */
a79b1bc6 8915 len = available[0].length;
8acf9577
YQ
8916 }
8917 }
8918
124e13d9 8919 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 8920}
74531fed 8921
c906108c 8922\f
c906108c 8923
a76d924d
DJ
8924/* Sends a packet with content determined by the printf format string
8925 FORMAT and the remaining arguments, then gets the reply. Returns
8926 whether the packet was a success, a failure, or unknown. */
8927
6b8edb51
PA
8928packet_result
8929remote_target::remote_send_printf (const char *format, ...)
a76d924d
DJ
8930{
8931 struct remote_state *rs = get_remote_state ();
8932 int max_size = get_remote_packet_size ();
a76d924d 8933 va_list ap;
a744cf53 8934
a76d924d
DJ
8935 va_start (ap, format);
8936
8937 rs->buf[0] = '\0';
8938 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 8939 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
8940
8941 if (putpkt (rs->buf) < 0)
8942 error (_("Communication problem with target."));
8943
8944 rs->buf[0] = '\0';
8945 getpkt (&rs->buf, &rs->buf_size, 0);
8946
8947 return packet_check_result (rs->buf);
8948}
8949
a76d924d
DJ
8950/* Flash writing can take quite some time. We'll set
8951 effectively infinite timeout for flash operations.
8952 In future, we'll need to decide on a better approach. */
8953static const int remote_flash_timeout = 1000;
8954
f6ac5f3d
PA
8955void
8956remote_target::flash_erase (ULONGEST address, LONGEST length)
a76d924d 8957{
f5656ead 8958 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d 8959 enum packet_result ret;
2ec845e7
TT
8960 scoped_restore restore_timeout
8961 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
a76d924d
DJ
8962
8963 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 8964 phex (address, addr_size),
a76d924d
DJ
8965 phex (length, 4));
8966 switch (ret)
8967 {
8968 case PACKET_UNKNOWN:
8969 error (_("Remote target does not support flash erase"));
8970 case PACKET_ERROR:
8971 error (_("Error erasing flash with vFlashErase packet"));
8972 default:
8973 break;
8974 }
a76d924d
DJ
8975}
8976
6b8edb51
PA
8977target_xfer_status
8978remote_target::remote_flash_write (ULONGEST address,
8979 ULONGEST length, ULONGEST *xfered_len,
8980 const gdb_byte *data)
a76d924d 8981{
2ec845e7
TT
8982 scoped_restore restore_timeout
8983 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8984 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8985 xfered_len,'X', 0);
a76d924d
DJ
8986}
8987
f6ac5f3d
PA
8988void
8989remote_target::flash_done ()
a76d924d 8990{
a76d924d 8991 int ret;
a76d924d 8992
2ec845e7
TT
8993 scoped_restore restore_timeout
8994 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8995
a76d924d 8996 ret = remote_send_printf ("vFlashDone");
a76d924d
DJ
8997
8998 switch (ret)
8999 {
9000 case PACKET_UNKNOWN:
9001 error (_("Remote target does not support vFlashDone"));
9002 case PACKET_ERROR:
9003 error (_("Error finishing flash operation"));
9004 default:
9005 break;
9006 }
9007}
9008
f6ac5f3d
PA
9009void
9010remote_target::files_info ()
c906108c
SS
9011{
9012 puts_filtered ("Debugging a target over a serial line.\n");
9013}
9014\f
9015/* Stuff for dealing with the packets which are part of this protocol.
9016 See comment at top of file for details. */
9017
1927e618
PA
9018/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9019 error to higher layers. Called when a serial error is detected.
9020 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
9021 the system error message for errno at function entry and final dot
9022 for output compatibility with throw_perror_with_name. */
1927e618
PA
9023
9024static void
9025unpush_and_perror (const char *string)
9026{
d6cb50a2 9027 int saved_errno = errno;
1927e618
PA
9028
9029 remote_unpush_target ();
d6cb50a2
JK
9030 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9031 safe_strerror (saved_errno));
1927e618
PA
9032}
9033
048094ac
PA
9034/* Read a single character from the remote end. The current quit
9035 handler is overridden to avoid quitting in the middle of packet
9036 sequence, as that would break communication with the remote server.
9037 See remote_serial_quit_handler for more detail. */
c906108c 9038
6b8edb51
PA
9039int
9040remote_target::readchar (int timeout)
c906108c
SS
9041{
9042 int ch;
5d93a237 9043 struct remote_state *rs = get_remote_state ();
048094ac 9044
2ec845e7 9045 {
6b8edb51
PA
9046 scoped_restore restore_quit_target
9047 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9048 scoped_restore restore_quit
6b8edb51 9049 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
c906108c 9050
2ec845e7 9051 rs->got_ctrlc_during_io = 0;
c906108c 9052
2ec845e7 9053 ch = serial_readchar (rs->remote_desc, timeout);
048094ac 9054
2ec845e7
TT
9055 if (rs->got_ctrlc_during_io)
9056 set_quit_flag ();
9057 }
048094ac 9058
2acceee2 9059 if (ch >= 0)
0876f84a 9060 return ch;
2acceee2
JM
9061
9062 switch ((enum serial_rc) ch)
c906108c
SS
9063 {
9064 case SERIAL_EOF:
78a095c3 9065 remote_unpush_target ();
598d3636 9066 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 9067 /* no return */
c906108c 9068 case SERIAL_ERROR:
1927e618
PA
9069 unpush_and_perror (_("Remote communication error. "
9070 "Target disconnected."));
2acceee2 9071 /* no return */
c906108c 9072 case SERIAL_TIMEOUT:
2acceee2 9073 break;
c906108c 9074 }
2acceee2 9075 return ch;
c906108c
SS
9076}
9077
c33e31fd 9078/* Wrapper for serial_write that closes the target and throws if
048094ac
PA
9079 writing fails. The current quit handler is overridden to avoid
9080 quitting in the middle of packet sequence, as that would break
9081 communication with the remote server. See
9082 remote_serial_quit_handler for more detail. */
c33e31fd 9083
6b8edb51
PA
9084void
9085remote_target::remote_serial_write (const char *str, int len)
c33e31fd 9086{
5d93a237 9087 struct remote_state *rs = get_remote_state ();
048094ac 9088
6b8edb51
PA
9089 scoped_restore restore_quit_target
9090 = make_scoped_restore (&curr_quit_handler_target, this);
2ec845e7 9091 scoped_restore restore_quit
6b8edb51 9092 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
048094ac
PA
9093
9094 rs->got_ctrlc_during_io = 0;
5d93a237
TT
9095
9096 if (serial_write (rs->remote_desc, str, len))
c33e31fd 9097 {
1927e618
PA
9098 unpush_and_perror (_("Remote communication error. "
9099 "Target disconnected."));
c33e31fd 9100 }
048094ac
PA
9101
9102 if (rs->got_ctrlc_during_io)
9103 set_quit_flag ();
c33e31fd
PA
9104}
9105
b3ced9ba
PA
9106/* Return a string representing an escaped version of BUF, of len N.
9107 E.g. \n is converted to \\n, \t to \\t, etc. */
6e5abd65 9108
b3ced9ba 9109static std::string
6e5abd65
PA
9110escape_buffer (const char *buf, int n)
9111{
d7e74731 9112 string_file stb;
6e5abd65 9113
d7e74731
PA
9114 stb.putstrn (buf, n, '\\');
9115 return std::move (stb.string ());
6e5abd65
PA
9116}
9117
c906108c
SS
9118/* Display a null-terminated packet on stdout, for debugging, using C
9119 string notation. */
9120
9121static void
baa336ce 9122print_packet (const char *buf)
c906108c
SS
9123{
9124 puts_filtered ("\"");
43e526b9 9125 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
9126 puts_filtered ("\"");
9127}
9128
9129int
6b8edb51 9130remote_target::putpkt (const char *buf)
c906108c
SS
9131{
9132 return putpkt_binary (buf, strlen (buf));
9133}
9134
6b8edb51
PA
9135/* Wrapper around remote_target::putpkt to avoid exporting
9136 remote_target. */
9137
9138int
9139putpkt (remote_target *remote, const char *buf)
9140{
9141 return remote->putpkt (buf);
9142}
9143
c906108c 9144/* Send a packet to the remote machine, with error checking. The data
23860348 9145 of the packet is in BUF. The string in BUF can be at most
ea9c271d 9146 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
9147 and for a possible /0 if we are debugging (remote_debug) and want
9148 to print the sent packet as a string. */
c906108c 9149
6b8edb51
PA
9150int
9151remote_target::putpkt_binary (const char *buf, int cnt)
c906108c 9152{
2d717e4f 9153 struct remote_state *rs = get_remote_state ();
c906108c
SS
9154 int i;
9155 unsigned char csum = 0;
b80406ac
TT
9156 gdb::def_vector<char> data (cnt + 6);
9157 char *buf2 = data.data ();
085dd6e6 9158
c906108c
SS
9159 int ch;
9160 int tcount = 0;
9161 char *p;
9162
e24a49d8
PA
9163 /* Catch cases like trying to read memory or listing threads while
9164 we're waiting for a stop reply. The remote server wouldn't be
9165 ready to handle this request, so we'd hang and timeout. We don't
9166 have to worry about this in synchronous mode, because in that
9167 case it's not possible to issue a command while the target is
74531fed
PA
9168 running. This is not a problem in non-stop mode, because in that
9169 case, the stub is always ready to process serial input. */
6efcd9a8
PA
9170 if (!target_is_non_stop_p ()
9171 && target_is_async_p ()
9172 && rs->waiting_for_stop_reply)
9597b22a
DE
9173 {
9174 error (_("Cannot execute this command while the target is running.\n"
9175 "Use the \"interrupt\" command to stop the target\n"
9176 "and then try again."));
9177 }
e24a49d8 9178
2d717e4f
DJ
9179 /* We're sending out a new packet. Make sure we don't look at a
9180 stale cached response. */
9181 rs->cached_wait_status = 0;
9182
c906108c
SS
9183 /* Copy the packet into buffer BUF2, encapsulating it
9184 and giving it a checksum. */
9185
c906108c
SS
9186 p = buf2;
9187 *p++ = '$';
9188
9189 for (i = 0; i < cnt; i++)
9190 {
9191 csum += buf[i];
9192 *p++ = buf[i];
9193 }
9194 *p++ = '#';
9195 *p++ = tohex ((csum >> 4) & 0xf);
9196 *p++ = tohex (csum & 0xf);
9197
9198 /* Send it over and over until we get a positive ack. */
9199
9200 while (1)
9201 {
9202 int started_error_output = 0;
9203
9204 if (remote_debug)
9205 {
9206 *p = '\0';
b3ced9ba 9207
6f8976bf
YQ
9208 int len = (int) (p - buf2);
9209
9210 std::string str
9211 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
9212
9213 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
9214
567a3e54
SM
9215 if (len > REMOTE_DEBUG_MAX_CHAR)
9216 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9217 len - REMOTE_DEBUG_MAX_CHAR);
6f8976bf
YQ
9218
9219 fprintf_unfiltered (gdb_stdlog, "...");
b3ced9ba 9220
0f71a2f6 9221 gdb_flush (gdb_stdlog);
c906108c 9222 }
c33e31fd 9223 remote_serial_write (buf2, p - buf2);
c906108c 9224
a6f3e723
SL
9225 /* If this is a no acks version of the remote protocol, send the
9226 packet and move on. */
9227 if (rs->noack_mode)
9228 break;
9229
74531fed
PA
9230 /* Read until either a timeout occurs (-2) or '+' is read.
9231 Handle any notification that arrives in the mean time. */
c906108c
SS
9232 while (1)
9233 {
9234 ch = readchar (remote_timeout);
9235
c5aa993b 9236 if (remote_debug)
c906108c
SS
9237 {
9238 switch (ch)
9239 {
9240 case '+':
1216fa2c 9241 case '-':
c906108c
SS
9242 case SERIAL_TIMEOUT:
9243 case '$':
74531fed 9244 case '%':
c906108c
SS
9245 if (started_error_output)
9246 {
9247 putchar_unfiltered ('\n');
9248 started_error_output = 0;
9249 }
9250 }
9251 }
9252
9253 switch (ch)
9254 {
9255 case '+':
9256 if (remote_debug)
0f71a2f6 9257 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 9258 return 1;
1216fa2c
AC
9259 case '-':
9260 if (remote_debug)
9261 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 9262 /* FALLTHROUGH */
c906108c 9263 case SERIAL_TIMEOUT:
c5aa993b 9264 tcount++;
c906108c 9265 if (tcount > 3)
b80406ac 9266 return 0;
23860348 9267 break; /* Retransmit buffer. */
c906108c
SS
9268 case '$':
9269 {
40e3f985 9270 if (remote_debug)
2bc416ba 9271 fprintf_unfiltered (gdb_stdlog,
23860348 9272 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
9273 /* It's probably an old response sent because an ACK
9274 was lost. Gobble up the packet and ack it so it
9275 doesn't get retransmitted when we resend this
9276 packet. */
6d820c5c 9277 skip_frame ();
c33e31fd 9278 remote_serial_write ("+", 1);
23860348 9279 continue; /* Now, go look for +. */
c906108c 9280 }
74531fed
PA
9281
9282 case '%':
9283 {
9284 int val;
9285
9286 /* If we got a notification, handle it, and go back to looking
9287 for an ack. */
9288 /* We've found the start of a notification. Now
9289 collect the data. */
9290 val = read_frame (&rs->buf, &rs->buf_size);
9291 if (val >= 0)
9292 {
9293 if (remote_debug)
9294 {
b3ced9ba 9295 std::string str = escape_buffer (rs->buf, val);
6e5abd65 9296
6e5abd65
PA
9297 fprintf_unfiltered (gdb_stdlog,
9298 " Notification received: %s\n",
b3ced9ba 9299 str.c_str ());
74531fed 9300 }
5965e028 9301 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
9302 /* We're in sync now, rewait for the ack. */
9303 tcount = 0;
9304 }
9305 else
9306 {
9307 if (remote_debug)
9308 {
9309 if (!started_error_output)
9310 {
9311 started_error_output = 1;
9312 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9313 }
9314 fputc_unfiltered (ch & 0177, gdb_stdlog);
9315 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9316 }
9317 }
9318 continue;
9319 }
9320 /* fall-through */
c906108c
SS
9321 default:
9322 if (remote_debug)
9323 {
9324 if (!started_error_output)
9325 {
9326 started_error_output = 1;
0f71a2f6 9327 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 9328 }
0f71a2f6 9329 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
9330 }
9331 continue;
9332 }
23860348 9333 break; /* Here to retransmit. */
c906108c
SS
9334 }
9335
9336#if 0
9337 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
9338 able to get out next time we call QUIT, without anything as
9339 violent as interrupt_query. If we want to provide a way out of
9340 here without getting to the next QUIT, it should be based on
9341 hitting ^C twice as in remote_wait. */
c906108c
SS
9342 if (quit_flag)
9343 {
9344 quit_flag = 0;
9345 interrupt_query ();
9346 }
9347#endif
9348 }
a5c0808e 9349
a6f3e723 9350 return 0;
c906108c
SS
9351}
9352
6d820c5c
DJ
9353/* Come here after finding the start of a frame when we expected an
9354 ack. Do our best to discard the rest of this packet. */
9355
6b8edb51
PA
9356void
9357remote_target::skip_frame ()
6d820c5c
DJ
9358{
9359 int c;
9360
9361 while (1)
9362 {
9363 c = readchar (remote_timeout);
9364 switch (c)
9365 {
9366 case SERIAL_TIMEOUT:
9367 /* Nothing we can do. */
9368 return;
9369 case '#':
9370 /* Discard the two bytes of checksum and stop. */
9371 c = readchar (remote_timeout);
9372 if (c >= 0)
9373 c = readchar (remote_timeout);
9374
9375 return;
9376 case '*': /* Run length encoding. */
9377 /* Discard the repeat count. */
9378 c = readchar (remote_timeout);
9379 if (c < 0)
9380 return;
9381 break;
9382 default:
9383 /* A regular character. */
9384 break;
9385 }
9386 }
9387}
9388
c906108c 9389/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
9390 into *BUF, verifying the checksum, length, and handling run-length
9391 compression. NUL terminate the buffer. If there is not enough room,
9392 expand *BUF using xrealloc.
c906108c 9393
c2d11a7d
JM
9394 Returns -1 on error, number of characters in buffer (ignoring the
9395 trailing NULL) on success. (could be extended to return one of the
23860348 9396 SERIAL status indications). */
c2d11a7d 9397
6b8edb51
PA
9398long
9399remote_target::read_frame (char **buf_p, long *sizeof_buf)
c906108c
SS
9400{
9401 unsigned char csum;
c2d11a7d 9402 long bc;
c906108c 9403 int c;
6d820c5c 9404 char *buf = *buf_p;
a6f3e723 9405 struct remote_state *rs = get_remote_state ();
c906108c
SS
9406
9407 csum = 0;
c2d11a7d 9408 bc = 0;
c906108c
SS
9409
9410 while (1)
9411 {
9412 c = readchar (remote_timeout);
c906108c
SS
9413 switch (c)
9414 {
9415 case SERIAL_TIMEOUT:
9416 if (remote_debug)
0f71a2f6 9417 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 9418 return -1;
c906108c
SS
9419 case '$':
9420 if (remote_debug)
0f71a2f6
JM
9421 fputs_filtered ("Saw new packet start in middle of old one\n",
9422 gdb_stdlog);
23860348 9423 return -1; /* Start a new packet, count retries. */
c906108c
SS
9424 case '#':
9425 {
9426 unsigned char pktcsum;
e1b09194
AC
9427 int check_0 = 0;
9428 int check_1 = 0;
c906108c 9429
c2d11a7d 9430 buf[bc] = '\0';
c906108c 9431
e1b09194
AC
9432 check_0 = readchar (remote_timeout);
9433 if (check_0 >= 0)
9434 check_1 = readchar (remote_timeout);
802188a7 9435
e1b09194
AC
9436 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9437 {
9438 if (remote_debug)
2bc416ba 9439 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 9440 gdb_stdlog);
e1b09194
AC
9441 return -1;
9442 }
9443 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
9444 {
9445 if (remote_debug)
2bc416ba 9446 fputs_filtered ("Communication error in checksum\n",
23860348 9447 gdb_stdlog);
40e3f985
FN
9448 return -1;
9449 }
c906108c 9450
a6f3e723
SL
9451 /* Don't recompute the checksum; with no ack packets we
9452 don't have any way to indicate a packet retransmission
9453 is necessary. */
9454 if (rs->noack_mode)
9455 return bc;
9456
e1b09194 9457 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 9458 if (csum == pktcsum)
c2d11a7d 9459 return bc;
c906108c 9460
c5aa993b 9461 if (remote_debug)
c906108c 9462 {
b3ced9ba 9463 std::string str = escape_buffer (buf, bc);
6e5abd65 9464
6e5abd65 9465 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
9466 "Bad checksum, sentsum=0x%x, "
9467 "csum=0x%x, buf=%s\n",
b3ced9ba 9468 pktcsum, csum, str.c_str ());
c906108c 9469 }
c2d11a7d 9470 /* Number of characters in buffer ignoring trailing
23860348 9471 NULL. */
c2d11a7d 9472 return -1;
c906108c 9473 }
23860348 9474 case '*': /* Run length encoding. */
c2c6d25f
JM
9475 {
9476 int repeat;
c906108c 9477
a744cf53 9478 csum += c;
b4501125
AC
9479 c = readchar (remote_timeout);
9480 csum += c;
23860348 9481 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 9482
23860348 9483 /* The character before ``*'' is repeated. */
c2d11a7d 9484
6d820c5c 9485 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 9486 {
6d820c5c
DJ
9487 if (bc + repeat - 1 >= *sizeof_buf - 1)
9488 {
9489 /* Make some more room in the buffer. */
9490 *sizeof_buf += repeat;
224c3ddb 9491 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c
DJ
9492 buf = *buf_p;
9493 }
9494
c2d11a7d
JM
9495 memset (&buf[bc], buf[bc - 1], repeat);
9496 bc += repeat;
c2c6d25f
JM
9497 continue;
9498 }
9499
c2d11a7d 9500 buf[bc] = '\0';
6d820c5c 9501 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 9502 return -1;
c2c6d25f 9503 }
c906108c 9504 default:
6d820c5c 9505 if (bc >= *sizeof_buf - 1)
c906108c 9506 {
6d820c5c
DJ
9507 /* Make some more room in the buffer. */
9508 *sizeof_buf *= 2;
224c3ddb 9509 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c 9510 buf = *buf_p;
c906108c
SS
9511 }
9512
6d820c5c
DJ
9513 buf[bc++] = c;
9514 csum += c;
9515 continue;
c906108c
SS
9516 }
9517 }
9518}
9519
9520/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
9521 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9522 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9523 rather than timing out; this is used (in synchronous mode) to wait
9524 for a target that is is executing user code to stop. */
d9fcf2fb
JM
9525/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9526 don't have to change all the calls to getpkt to deal with the
9527 return value, because at the moment I don't know what the right
23860348 9528 thing to do it for those. */
6b8edb51 9529
c906108c 9530void
6b8edb51 9531remote_target::getpkt (char **buf, long *sizeof_buf, int forever)
d9fcf2fb 9532{
54887903 9533 getpkt_sane (buf, sizeof_buf, forever);
d9fcf2fb
JM
9534}
9535
9536
9537/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
9538 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9539 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9540 rather than timing out; this is used (in synchronous mode) to wait
9541 for a target that is is executing user code to stop. If FOREVER ==
9542 0, this function is allowed to time out gracefully and return an
74531fed
PA
9543 indication of this to the caller. Otherwise return the number of
9544 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
9545 enough reason to return to the caller. *IS_NOTIF is an output
9546 boolean that indicates whether *BUF holds a notification or not
9547 (a regular packet). */
74531fed 9548
6b8edb51
PA
9549int
9550remote_target::getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf,
9551 int forever, int expecting_notif,
9552 int *is_notif)
c906108c 9553{
2d717e4f 9554 struct remote_state *rs = get_remote_state ();
c906108c
SS
9555 int c;
9556 int tries;
9557 int timeout;
df4b58fe 9558 int val = -1;
c906108c 9559
2d717e4f
DJ
9560 /* We're reading a new response. Make sure we don't look at a
9561 previously cached response. */
9562 rs->cached_wait_status = 0;
9563
6d820c5c 9564 strcpy (*buf, "timeout");
c906108c
SS
9565
9566 if (forever)
74531fed
PA
9567 timeout = watchdog > 0 ? watchdog : -1;
9568 else if (expecting_notif)
9569 timeout = 0; /* There should already be a char in the buffer. If
9570 not, bail out. */
c906108c
SS
9571 else
9572 timeout = remote_timeout;
9573
9574#define MAX_TRIES 3
9575
74531fed
PA
9576 /* Process any number of notifications, and then return when
9577 we get a packet. */
9578 for (;;)
c906108c 9579 {
d9c43928 9580 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
9581 times. */
9582 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 9583 {
74531fed
PA
9584 /* This can loop forever if the remote side sends us
9585 characters continuously, but if it pauses, we'll get
9586 SERIAL_TIMEOUT from readchar because of timeout. Then
9587 we'll count that as a retry.
9588
9589 Note that even when forever is set, we will only wait
9590 forever prior to the start of a packet. After that, we
9591 expect characters to arrive at a brisk pace. They should
9592 show up within remote_timeout intervals. */
9593 do
9594 c = readchar (timeout);
9595 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
9596
9597 if (c == SERIAL_TIMEOUT)
9598 {
74531fed
PA
9599 if (expecting_notif)
9600 return -1; /* Don't complain, it's normal to not get
9601 anything in this case. */
9602
23860348 9603 if (forever) /* Watchdog went off? Kill the target. */
c906108c 9604 {
78a095c3 9605 remote_unpush_target ();
598d3636
JK
9606 throw_error (TARGET_CLOSE_ERROR,
9607 _("Watchdog timeout has expired. "
9608 "Target detached."));
c906108c 9609 }
c906108c 9610 if (remote_debug)
0f71a2f6 9611 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 9612 }
74531fed
PA
9613 else
9614 {
9615 /* We've found the start of a packet or notification.
9616 Now collect the data. */
9617 val = read_frame (buf, sizeof_buf);
9618 if (val >= 0)
9619 break;
9620 }
9621
c33e31fd 9622 remote_serial_write ("-", 1);
c906108c 9623 }
c906108c 9624
74531fed
PA
9625 if (tries > MAX_TRIES)
9626 {
9627 /* We have tried hard enough, and just can't receive the
9628 packet/notification. Give up. */
9629 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 9630
74531fed
PA
9631 /* Skip the ack char if we're in no-ack mode. */
9632 if (!rs->noack_mode)
c33e31fd 9633 remote_serial_write ("+", 1);
74531fed
PA
9634 return -1;
9635 }
c906108c 9636
74531fed
PA
9637 /* If we got an ordinary packet, return that to our caller. */
9638 if (c == '$')
c906108c
SS
9639 {
9640 if (remote_debug)
43e526b9 9641 {
6f8976bf
YQ
9642 std::string str
9643 = escape_buffer (*buf,
9644 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9645
9646 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9647 str.c_str ());
9648
567a3e54
SM
9649 if (val > REMOTE_DEBUG_MAX_CHAR)
9650 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9651 val - REMOTE_DEBUG_MAX_CHAR);
6e5abd65 9652
6f8976bf 9653 fprintf_unfiltered (gdb_stdlog, "\n");
43e526b9 9654 }
a6f3e723
SL
9655
9656 /* Skip the ack char if we're in no-ack mode. */
9657 if (!rs->noack_mode)
c33e31fd 9658 remote_serial_write ("+", 1);
fee9eda9
YQ
9659 if (is_notif != NULL)
9660 *is_notif = 0;
0876f84a 9661 return val;
c906108c
SS
9662 }
9663
74531fed
PA
9664 /* If we got a notification, handle it, and go back to looking
9665 for a packet. */
9666 else
9667 {
9668 gdb_assert (c == '%');
9669
9670 if (remote_debug)
9671 {
b3ced9ba 9672 std::string str = escape_buffer (*buf, val);
6e5abd65 9673
6e5abd65
PA
9674 fprintf_unfiltered (gdb_stdlog,
9675 " Notification received: %s\n",
b3ced9ba 9676 str.c_str ());
74531fed 9677 }
fee9eda9
YQ
9678 if (is_notif != NULL)
9679 *is_notif = 1;
c906108c 9680
5965e028 9681 handle_notification (rs->notif_state, *buf);
c906108c 9682
74531fed 9683 /* Notifications require no acknowledgement. */
a6f3e723 9684
74531fed 9685 if (expecting_notif)
fee9eda9 9686 return val;
74531fed
PA
9687 }
9688 }
9689}
9690
6b8edb51
PA
9691int
9692remote_target::getpkt_sane (char **buf, long *sizeof_buf, int forever)
74531fed 9693{
fee9eda9 9694 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
9695}
9696
6b8edb51
PA
9697int
9698remote_target::getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9699 int *is_notif)
74531fed 9700{
fee9eda9
YQ
9701 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9702 is_notif);
c906108c 9703}
74531fed 9704
cbb8991c
DB
9705/* Kill any new fork children of process PID that haven't been
9706 processed by follow_fork. */
9707
6b8edb51
PA
9708void
9709remote_target::kill_new_fork_children (int pid)
cbb8991c 9710{
6b8edb51 9711 remote_state *rs = get_remote_state ();
cbb8991c
DB
9712 struct thread_info *thread;
9713 struct notif_client *notif = &notif_client_stop;
cbb8991c
DB
9714
9715 /* Kill the fork child threads of any threads in process PID
9716 that are stopped at a fork event. */
9717 ALL_NON_EXITED_THREADS (thread)
9718 {
9719 struct target_waitstatus *ws = &thread->pending_follow;
9720
9721 if (is_pending_fork_parent (ws, pid, thread->ptid))
9722 {
953edf2b 9723 int child_pid = ws->value.related_pid.pid ();
cbb8991c
DB
9724 int res;
9725
6b8edb51 9726 res = remote_vkill (child_pid);
cbb8991c
DB
9727 if (res != 0)
9728 error (_("Can't kill fork child process %d"), child_pid);
9729 }
9730 }
9731
9732 /* Check for any pending fork events (not reported or processed yet)
9733 in process PID and kill those fork child threads as well. */
9734 remote_notif_get_pending_events (notif);
953edf2b
TT
9735 for (auto &event : rs->stop_reply_queue)
9736 if (is_pending_fork_parent (&event->ws, pid, event->ptid))
9737 {
9738 int child_pid = event->ws.value.related_pid.pid ();
9739 int res;
9740
9741 res = remote_vkill (child_pid);
9742 if (res != 0)
9743 error (_("Can't kill fork child process %d"), child_pid);
9744 }
cbb8991c
DB
9745}
9746
c906108c 9747\f
8020350c
DB
9748/* Target hook to kill the current inferior. */
9749
f6ac5f3d
PA
9750void
9751remote_target::kill ()
43ff13b4 9752{
8020350c 9753 int res = -1;
e99b03dc 9754 int pid = inferior_ptid.pid ();
8020350c 9755 struct remote_state *rs = get_remote_state ();
0fdf84ca 9756
8020350c 9757 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 9758 {
8020350c
DB
9759 /* If we're stopped while forking and we haven't followed yet,
9760 kill the child task. We need to do this before killing the
9761 parent task because if this is a vfork then the parent will
9762 be sleeping. */
6b8edb51 9763 kill_new_fork_children (pid);
8020350c 9764
6b8edb51 9765 res = remote_vkill (pid);
8020350c 9766 if (res == 0)
0fdf84ca 9767 {
bc1e6c81 9768 target_mourn_inferior (inferior_ptid);
0fdf84ca
PA
9769 return;
9770 }
8020350c 9771 }
0fdf84ca 9772
8020350c
DB
9773 /* If we are in 'target remote' mode and we are killing the only
9774 inferior, then we will tell gdbserver to exit and unpush the
9775 target. */
9776 if (res == -1 && !remote_multi_process_p (rs)
9777 && number_of_live_inferiors () == 1)
9778 {
9779 remote_kill_k ();
9780
9781 /* We've killed the remote end, we get to mourn it. If we are
9782 not in extended mode, mourning the inferior also unpushes
9783 remote_ops from the target stack, which closes the remote
9784 connection. */
bc1e6c81 9785 target_mourn_inferior (inferior_ptid);
8020350c
DB
9786
9787 return;
0fdf84ca 9788 }
43ff13b4 9789
8020350c 9790 error (_("Can't kill process"));
43ff13b4
JM
9791}
9792
8020350c
DB
9793/* Send a kill request to the target using the 'vKill' packet. */
9794
6b8edb51
PA
9795int
9796remote_target::remote_vkill (int pid)
82f73884 9797{
4082afcc 9798 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
9799 return -1;
9800
6b8edb51
PA
9801 remote_state *rs = get_remote_state ();
9802
82f73884 9803 /* Tell the remote target to detach. */
bba74b36 9804 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
9805 putpkt (rs->buf);
9806 getpkt (&rs->buf, &rs->buf_size, 0);
9807
4082afcc
PA
9808 switch (packet_ok (rs->buf,
9809 &remote_protocol_packets[PACKET_vKill]))
9810 {
9811 case PACKET_OK:
9812 return 0;
9813 case PACKET_ERROR:
9814 return 1;
9815 case PACKET_UNKNOWN:
9816 return -1;
9817 default:
9818 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9819 }
82f73884
PA
9820}
9821
8020350c
DB
9822/* Send a kill request to the target using the 'k' packet. */
9823
6b8edb51
PA
9824void
9825remote_target::remote_kill_k ()
82f73884 9826{
8020350c
DB
9827 /* Catch errors so the user can quit from gdb even when we
9828 aren't on speaking terms with the remote system. */
9829 TRY
82f73884 9830 {
82f73884 9831 putpkt ("k");
82f73884 9832 }
8020350c
DB
9833 CATCH (ex, RETURN_MASK_ERROR)
9834 {
9835 if (ex.error == TARGET_CLOSE_ERROR)
9836 {
9837 /* If we got an (EOF) error that caused the target
9838 to go away, then we're done, that's what we wanted.
9839 "k" is susceptible to cause a premature EOF, given
9840 that the remote server isn't actually required to
9841 reply to "k", and it can happen that it doesn't
9842 even get to reply ACK to the "k". */
9843 return;
9844 }
82f73884 9845
8020350c
DB
9846 /* Otherwise, something went wrong. We didn't actually kill
9847 the target. Just propagate the exception, and let the
9848 user or higher layers decide what to do. */
9849 throw_exception (ex);
9850 }
9851 END_CATCH
82f73884
PA
9852}
9853
f6ac5f3d
PA
9854void
9855remote_target::mourn_inferior ()
c906108c 9856{
8020350c 9857 struct remote_state *rs = get_remote_state ();
ce5ce7ed 9858
9607784a
PA
9859 /* We're no longer interested in notification events of an inferior
9860 that exited or was killed/detached. */
9861 discard_pending_stop_replies (current_inferior ());
9862
8020350c
DB
9863 /* In 'target remote' mode with one inferior, we close the connection. */
9864 if (!rs->extended && number_of_live_inferiors () <= 1)
9865 {
f6ac5f3d 9866 unpush_target (this);
c906108c 9867
8020350c
DB
9868 /* remote_close takes care of doing most of the clean up. */
9869 generic_mourn_inferior ();
9870 return;
9871 }
c906108c 9872
e24a49d8
PA
9873 /* In case we got here due to an error, but we're going to stay
9874 connected. */
9875 rs->waiting_for_stop_reply = 0;
9876
dc1981d7
PA
9877 /* If the current general thread belonged to the process we just
9878 detached from or has exited, the remote side current general
9879 thread becomes undefined. Considering a case like this:
9880
9881 - We just got here due to a detach.
9882 - The process that we're detaching from happens to immediately
9883 report a global breakpoint being hit in non-stop mode, in the
9884 same thread we had selected before.
9885 - GDB attaches to this process again.
9886 - This event happens to be the next event we handle.
9887
9888 GDB would consider that the current general thread didn't need to
9889 be set on the stub side (with Hg), since for all it knew,
9890 GENERAL_THREAD hadn't changed.
9891
9892 Notice that although in all-stop mode, the remote server always
9893 sets the current thread to the thread reporting the stop event,
9894 that doesn't happen in non-stop mode; in non-stop, the stub *must
9895 not* change the current thread when reporting a breakpoint hit,
9896 due to the decoupling of event reporting and event handling.
9897
9898 To keep things simple, we always invalidate our notion of the
9899 current thread. */
47f8a51d 9900 record_currthread (rs, minus_one_ptid);
dc1981d7 9901
8020350c 9902 /* Call common code to mark the inferior as not running. */
48aa3c27
PA
9903 generic_mourn_inferior ();
9904
d729566a 9905 if (!have_inferiors ())
2d717e4f 9906 {
82f73884
PA
9907 if (!remote_multi_process_p (rs))
9908 {
9909 /* Check whether the target is running now - some remote stubs
9910 automatically restart after kill. */
9911 putpkt ("?");
9912 getpkt (&rs->buf, &rs->buf_size, 0);
9913
9914 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9915 {
3e43a32a
MS
9916 /* Assume that the target has been restarted. Set
9917 inferior_ptid so that bits of core GDB realizes
9918 there's something here, e.g., so that the user can
9919 say "kill" again. */
82f73884
PA
9920 inferior_ptid = magic_null_ptid;
9921 }
82f73884 9922 }
2d717e4f
DJ
9923 }
9924}
c906108c 9925
57810aa7 9926bool
f6ac5f3d 9927extended_remote_target::supports_disable_randomization ()
03583c20 9928{
4082afcc 9929 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
9930}
9931
6b8edb51
PA
9932void
9933remote_target::extended_remote_disable_randomization (int val)
03583c20
UW
9934{
9935 struct remote_state *rs = get_remote_state ();
9936 char *reply;
9937
bba74b36
YQ
9938 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9939 val);
03583c20 9940 putpkt (rs->buf);
b6bb3468 9941 reply = remote_get_noisy_reply ();
03583c20
UW
9942 if (*reply == '\0')
9943 error (_("Target does not support QDisableRandomization."));
9944 if (strcmp (reply, "OK") != 0)
9945 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9946}
9947
6b8edb51
PA
9948int
9949remote_target::extended_remote_run (const std::string &args)
2d717e4f
DJ
9950{
9951 struct remote_state *rs = get_remote_state ();
2d717e4f 9952 int len;
94585166 9953 const char *remote_exec_file = get_remote_exec_file ();
c906108c 9954
2d717e4f
DJ
9955 /* If the user has disabled vRun support, or we have detected that
9956 support is not available, do not try it. */
4082afcc 9957 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 9958 return -1;
424163ea 9959
2d717e4f
DJ
9960 strcpy (rs->buf, "vRun;");
9961 len = strlen (rs->buf);
c906108c 9962
2d717e4f
DJ
9963 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9964 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
9965 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9966 strlen (remote_exec_file));
2d717e4f 9967
7c5ded6a 9968 if (!args.empty ())
2d717e4f 9969 {
2d717e4f 9970 int i;
2d717e4f 9971
773a1edc 9972 gdb_argv argv (args.c_str ());
2d717e4f
DJ
9973 for (i = 0; argv[i] != NULL; i++)
9974 {
9975 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9976 error (_("Argument list too long for run packet"));
9977 rs->buf[len++] = ';';
9f1b45b0
TT
9978 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9979 strlen (argv[i]));
2d717e4f 9980 }
2d717e4f
DJ
9981 }
9982
9983 rs->buf[len++] = '\0';
9984
9985 putpkt (rs->buf);
9986 getpkt (&rs->buf, &rs->buf_size, 0);
9987
4082afcc 9988 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 9989 {
4082afcc 9990 case PACKET_OK:
3405876a 9991 /* We have a wait response. All is well. */
2d717e4f 9992 return 0;
4082afcc
PA
9993 case PACKET_UNKNOWN:
9994 return -1;
9995 case PACKET_ERROR:
2d717e4f
DJ
9996 if (remote_exec_file[0] == '\0')
9997 error (_("Running the default executable on the remote target failed; "
9998 "try \"set remote exec-file\"?"));
9999 else
10000 error (_("Running \"%s\" on the remote target failed"),
10001 remote_exec_file);
4082afcc
PA
10002 default:
10003 gdb_assert_not_reached (_("bad switch"));
2d717e4f 10004 }
c906108c
SS
10005}
10006
0a2dde4a
SDJ
10007/* Helper function to send set/unset environment packets. ACTION is
10008 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10009 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10010 sent. */
10011
6b8edb51
PA
10012void
10013remote_target::send_environment_packet (const char *action,
10014 const char *packet,
10015 const char *value)
0a2dde4a 10016{
6b8edb51
PA
10017 remote_state *rs = get_remote_state ();
10018
0a2dde4a
SDJ
10019 /* Convert the environment variable to an hex string, which
10020 is the best format to be transmitted over the wire. */
10021 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10022 strlen (value));
10023
10024 xsnprintf (rs->buf, get_remote_packet_size (),
10025 "%s:%s", packet, encoded_value.c_str ());
10026
10027 putpkt (rs->buf);
10028 getpkt (&rs->buf, &rs->buf_size, 0);
10029 if (strcmp (rs->buf, "OK") != 0)
10030 warning (_("Unable to %s environment variable '%s' on remote."),
10031 action, value);
10032}
10033
10034/* Helper function to handle the QEnvironment* packets. */
10035
6b8edb51
PA
10036void
10037remote_target::extended_remote_environment_support ()
0a2dde4a 10038{
6b8edb51
PA
10039 remote_state *rs = get_remote_state ();
10040
0a2dde4a
SDJ
10041 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10042 {
10043 putpkt ("QEnvironmentReset");
10044 getpkt (&rs->buf, &rs->buf_size, 0);
10045 if (strcmp (rs->buf, "OK") != 0)
10046 warning (_("Unable to reset environment on remote."));
10047 }
10048
10049 gdb_environ *e = &current_inferior ()->environment;
10050
10051 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10052 for (const std::string &el : e->user_set_env ())
6b8edb51 10053 send_environment_packet ("set", "QEnvironmentHexEncoded",
0a2dde4a
SDJ
10054 el.c_str ());
10055
10056 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10057 for (const std::string &el : e->user_unset_env ())
6b8edb51 10058 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
0a2dde4a
SDJ
10059}
10060
bc3b087d
SDJ
10061/* Helper function to set the current working directory for the
10062 inferior in the remote target. */
10063
6b8edb51
PA
10064void
10065remote_target::extended_remote_set_inferior_cwd ()
bc3b087d
SDJ
10066{
10067 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10068 {
10069 const char *inferior_cwd = get_inferior_cwd ();
6b8edb51 10070 remote_state *rs = get_remote_state ();
bc3b087d
SDJ
10071
10072 if (inferior_cwd != NULL)
10073 {
10074 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
10075 strlen (inferior_cwd));
10076
10077 xsnprintf (rs->buf, get_remote_packet_size (),
10078 "QSetWorkingDir:%s", hexpath.c_str ());
10079 }
10080 else
10081 {
10082 /* An empty inferior_cwd means that the user wants us to
10083 reset the remote server's inferior's cwd. */
10084 xsnprintf (rs->buf, get_remote_packet_size (),
10085 "QSetWorkingDir:");
10086 }
10087
10088 putpkt (rs->buf);
10089 getpkt (&rs->buf, &rs->buf_size, 0);
10090 if (packet_ok (rs->buf,
10091 &remote_protocol_packets[PACKET_QSetWorkingDir])
10092 != PACKET_OK)
10093 error (_("\
10094Remote replied unexpectedly while setting the inferior's working\n\
10095directory: %s"),
10096 rs->buf);
10097
10098 }
10099}
10100
2d717e4f
DJ
10101/* In the extended protocol we want to be able to do things like
10102 "run" and have them basically work as expected. So we need
10103 a special create_inferior function. We support changing the
10104 executable file and the command line arguments, but not the
10105 environment. */
10106
f6ac5f3d
PA
10107void
10108extended_remote_target::create_inferior (const char *exec_file,
10109 const std::string &args,
10110 char **env, int from_tty)
43ff13b4 10111{
3405876a
PA
10112 int run_worked;
10113 char *stop_reply;
10114 struct remote_state *rs = get_remote_state ();
94585166 10115 const char *remote_exec_file = get_remote_exec_file ();
3405876a 10116
43ff13b4 10117 /* If running asynchronously, register the target file descriptor
23860348 10118 with the event loop. */
75c99385 10119 if (target_can_async_p ())
6a3753b3 10120 target_async (1);
43ff13b4 10121
03583c20 10122 /* Disable address space randomization if requested (and supported). */
f6ac5f3d 10123 if (supports_disable_randomization ())
03583c20
UW
10124 extended_remote_disable_randomization (disable_randomization);
10125
aefd8b33
SDJ
10126 /* If startup-with-shell is on, we inform gdbserver to start the
10127 remote inferior using a shell. */
10128 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10129 {
10130 xsnprintf (rs->buf, get_remote_packet_size (),
10131 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10132 putpkt (rs->buf);
10133 getpkt (&rs->buf, &rs->buf_size, 0);
10134 if (strcmp (rs->buf, "OK") != 0)
10135 error (_("\
10136Remote replied unexpectedly while setting startup-with-shell: %s"),
10137 rs->buf);
10138 }
10139
6b8edb51 10140 extended_remote_environment_support ();
0a2dde4a 10141
6b8edb51 10142 extended_remote_set_inferior_cwd ();
bc3b087d 10143
43ff13b4 10144 /* Now restart the remote server. */
3405876a
PA
10145 run_worked = extended_remote_run (args) != -1;
10146 if (!run_worked)
2d717e4f
DJ
10147 {
10148 /* vRun was not supported. Fail if we need it to do what the
10149 user requested. */
10150 if (remote_exec_file[0])
10151 error (_("Remote target does not support \"set remote exec-file\""));
7c5ded6a 10152 if (!args.empty ())
2d717e4f 10153 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 10154
2d717e4f
DJ
10155 /* Fall back to "R". */
10156 extended_remote_restart ();
10157 }
424163ea 10158
6c95b8df
PA
10159 if (!have_inferiors ())
10160 {
10161 /* Clean up from the last time we ran, before we mark the target
10162 running again. This will mark breakpoints uninserted, and
10163 get_offsets may insert breakpoints. */
10164 init_thread_list ();
10165 init_wait_for_inferior ();
10166 }
45280a52 10167
3405876a
PA
10168 /* vRun's success return is a stop reply. */
10169 stop_reply = run_worked ? rs->buf : NULL;
10170 add_current_inferior_and_thread (stop_reply);
c0a2216e 10171
2d717e4f
DJ
10172 /* Get updated offsets, if the stub uses qOffsets. */
10173 get_offsets ();
2d717e4f 10174}
c906108c 10175\f
c5aa993b 10176
b775012e
LM
10177/* Given a location's target info BP_TGT and the packet buffer BUF, output
10178 the list of conditions (in agent expression bytecode format), if any, the
10179 target needs to evaluate. The output is placed into the packet buffer
bba74b36 10180 started from BUF and ended at BUF_END. */
b775012e
LM
10181
10182static int
10183remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
10184 struct bp_target_info *bp_tgt, char *buf,
10185 char *buf_end)
b775012e 10186{
3cde5c42 10187 if (bp_tgt->conditions.empty ())
b775012e
LM
10188 return 0;
10189
10190 buf += strlen (buf);
bba74b36 10191 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
10192 buf++;
10193
83621223 10194 /* Send conditions to the target. */
d538e36d 10195 for (agent_expr *aexpr : bp_tgt->conditions)
b775012e 10196 {
bba74b36 10197 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e 10198 buf += strlen (buf);
3cde5c42 10199 for (int i = 0; i < aexpr->len; ++i)
b775012e
LM
10200 buf = pack_hex_byte (buf, aexpr->buf[i]);
10201 *buf = '\0';
10202 }
b775012e
LM
10203 return 0;
10204}
10205
d3ce09f5
SS
10206static void
10207remote_add_target_side_commands (struct gdbarch *gdbarch,
10208 struct bp_target_info *bp_tgt, char *buf)
10209{
3cde5c42 10210 if (bp_tgt->tcommands.empty ())
d3ce09f5
SS
10211 return;
10212
10213 buf += strlen (buf);
10214
10215 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10216 buf += strlen (buf);
10217
10218 /* Concatenate all the agent expressions that are commands into the
10219 cmds parameter. */
df97be55 10220 for (agent_expr *aexpr : bp_tgt->tcommands)
d3ce09f5
SS
10221 {
10222 sprintf (buf, "X%x,", aexpr->len);
10223 buf += strlen (buf);
3cde5c42 10224 for (int i = 0; i < aexpr->len; ++i)
d3ce09f5
SS
10225 buf = pack_hex_byte (buf, aexpr->buf[i]);
10226 *buf = '\0';
10227 }
d3ce09f5
SS
10228}
10229
8181d85f
DJ
10230/* Insert a breakpoint. On targets that have software breakpoint
10231 support, we ask the remote target to do the work; on targets
10232 which don't, we insert a traditional memory breakpoint. */
c906108c 10233
f6ac5f3d
PA
10234int
10235remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10236 struct bp_target_info *bp_tgt)
c906108c 10237{
d471ea57
AC
10238 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10239 If it succeeds, then set the support to PACKET_ENABLE. If it
10240 fails, and the user has explicitly requested the Z support then
23860348 10241 report an error, otherwise, mark it disabled and go on. */
802188a7 10242
4082afcc 10243 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10244 {
0d5ed153 10245 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10246 struct remote_state *rs;
bba74b36 10247 char *p, *endbuf;
4fff2411 10248
28439a30
PA
10249 /* Make sure the remote is pointing at the right process, if
10250 necessary. */
10251 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10252 set_general_process ();
10253
4fff2411
JZ
10254 rs = get_remote_state ();
10255 p = rs->buf;
bba74b36 10256 endbuf = rs->buf + get_remote_packet_size ();
802188a7 10257
96baa820
JM
10258 *(p++) = 'Z';
10259 *(p++) = '0';
10260 *(p++) = ',';
7c0f6dcc 10261 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 10262 p += hexnumstr (p, addr);
579c6ad9 10263 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10264
f6ac5f3d 10265 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10266 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10267
f6ac5f3d 10268 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10269 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10270
6d820c5c
DJ
10271 putpkt (rs->buf);
10272 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10273
6d820c5c 10274 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 10275 {
d471ea57
AC
10276 case PACKET_ERROR:
10277 return -1;
10278 case PACKET_OK:
10279 return 0;
10280 case PACKET_UNKNOWN:
10281 break;
96baa820
JM
10282 }
10283 }
c906108c 10284
0000e5cc
PA
10285 /* If this breakpoint has target-side commands but this stub doesn't
10286 support Z0 packets, throw error. */
3cde5c42 10287 if (!bp_tgt->tcommands.empty ())
0000e5cc
PA
10288 throw_error (NOT_SUPPORTED_ERROR, _("\
10289Target doesn't support breakpoints that have target side commands."));
10290
f6ac5f3d 10291 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
c906108c
SS
10292}
10293
f6ac5f3d
PA
10294int
10295remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10296 struct bp_target_info *bp_tgt,
10297 enum remove_bp_reason reason)
c906108c 10298{
8181d85f 10299 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 10300 struct remote_state *rs = get_remote_state ();
96baa820 10301
4082afcc 10302 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10303 {
6d820c5c 10304 char *p = rs->buf;
bba74b36 10305 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 10306
28439a30
PA
10307 /* Make sure the remote is pointing at the right process, if
10308 necessary. */
10309 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10310 set_general_process ();
10311
96baa820
JM
10312 *(p++) = 'z';
10313 *(p++) = '0';
10314 *(p++) = ',';
10315
8181d85f
DJ
10316 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10317 p += hexnumstr (p, addr);
579c6ad9 10318 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10319
6d820c5c
DJ
10320 putpkt (rs->buf);
10321 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10322
6d820c5c 10323 return (rs->buf[0] == 'E');
96baa820
JM
10324 }
10325
f6ac5f3d 10326 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
c906108c
SS
10327}
10328
f486487f 10329static enum Z_packet_type
d471ea57
AC
10330watchpoint_to_Z_packet (int type)
10331{
10332 switch (type)
10333 {
10334 case hw_write:
bb858e6a 10335 return Z_PACKET_WRITE_WP;
d471ea57
AC
10336 break;
10337 case hw_read:
bb858e6a 10338 return Z_PACKET_READ_WP;
d471ea57
AC
10339 break;
10340 case hw_access:
bb858e6a 10341 return Z_PACKET_ACCESS_WP;
d471ea57
AC
10342 break;
10343 default:
8e65ff28 10344 internal_error (__FILE__, __LINE__,
e2e0b3e5 10345 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
10346 }
10347}
10348
f6ac5f3d
PA
10349int
10350remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10351 enum target_hw_bp_type type, struct expression *cond)
96baa820 10352{
d01949b6 10353 struct remote_state *rs = get_remote_state ();
bba74b36 10354 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 10355 char *p;
d471ea57 10356 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 10357
4082afcc 10358 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 10359 return 1;
802188a7 10360
28439a30
PA
10361 /* Make sure the remote is pointing at the right process, if
10362 necessary. */
10363 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10364 set_general_process ();
10365
bba74b36 10366 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 10367 p = strchr (rs->buf, '\0');
96baa820
JM
10368 addr = remote_address_masked (addr);
10369 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10370 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 10371
6d820c5c
DJ
10372 putpkt (rs->buf);
10373 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10374
6d820c5c 10375 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10376 {
10377 case PACKET_ERROR:
d471ea57 10378 return -1;
85d721b8
PA
10379 case PACKET_UNKNOWN:
10380 return 1;
d471ea57
AC
10381 case PACKET_OK:
10382 return 0;
10383 }
8e65ff28 10384 internal_error (__FILE__, __LINE__,
e2e0b3e5 10385 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
10386}
10387
57810aa7 10388bool
f6ac5f3d
PA
10389remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10390 CORE_ADDR start, int length)
283002cf
MR
10391{
10392 CORE_ADDR diff = remote_address_masked (addr - start);
10393
10394 return diff < length;
10395}
10396
d471ea57 10397
f6ac5f3d
PA
10398int
10399remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10400 enum target_hw_bp_type type, struct expression *cond)
96baa820 10401{
d01949b6 10402 struct remote_state *rs = get_remote_state ();
bba74b36 10403 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 10404 char *p;
d471ea57
AC
10405 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10406
4082afcc 10407 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 10408 return -1;
802188a7 10409
28439a30
PA
10410 /* Make sure the remote is pointing at the right process, if
10411 necessary. */
10412 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10413 set_general_process ();
10414
bba74b36 10415 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 10416 p = strchr (rs->buf, '\0');
96baa820
JM
10417 addr = remote_address_masked (addr);
10418 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10419 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
10420 putpkt (rs->buf);
10421 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10422
6d820c5c 10423 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10424 {
10425 case PACKET_ERROR:
10426 case PACKET_UNKNOWN:
10427 return -1;
10428 case PACKET_OK:
10429 return 0;
10430 }
8e65ff28 10431 internal_error (__FILE__, __LINE__,
e2e0b3e5 10432 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
10433}
10434
3c3bea1c 10435
501eef12 10436int remote_hw_watchpoint_limit = -1;
480a3f21 10437int remote_hw_watchpoint_length_limit = -1;
501eef12 10438int remote_hw_breakpoint_limit = -1;
d471ea57 10439
f6ac5f3d
PA
10440int
10441remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
480a3f21
PW
10442{
10443 if (remote_hw_watchpoint_length_limit == 0)
10444 return 0;
10445 else if (remote_hw_watchpoint_length_limit < 0)
10446 return 1;
10447 else if (len <= remote_hw_watchpoint_length_limit)
10448 return 1;
10449 else
10450 return 0;
10451}
10452
f6ac5f3d
PA
10453int
10454remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
96baa820 10455{
3c3bea1c
GS
10456 if (type == bp_hardware_breakpoint)
10457 {
10458 if (remote_hw_breakpoint_limit == 0)
10459 return 0;
501eef12
AC
10460 else if (remote_hw_breakpoint_limit < 0)
10461 return 1;
3c3bea1c
GS
10462 else if (cnt <= remote_hw_breakpoint_limit)
10463 return 1;
10464 }
10465 else
10466 {
10467 if (remote_hw_watchpoint_limit == 0)
10468 return 0;
501eef12
AC
10469 else if (remote_hw_watchpoint_limit < 0)
10470 return 1;
3c3bea1c
GS
10471 else if (ot)
10472 return -1;
10473 else if (cnt <= remote_hw_watchpoint_limit)
10474 return 1;
10475 }
10476 return -1;
10477}
10478
f7e6eed5
PA
10479/* The to_stopped_by_sw_breakpoint method of target remote. */
10480
57810aa7 10481bool
f6ac5f3d 10482remote_target::stopped_by_sw_breakpoint ()
f7e6eed5 10483{
799a2abe 10484 struct thread_info *thread = inferior_thread ();
f7e6eed5 10485
799a2abe 10486 return (thread->priv != NULL
7aabaf9d
SM
10487 && (get_remote_thread_info (thread)->stop_reason
10488 == TARGET_STOPPED_BY_SW_BREAKPOINT));
f7e6eed5
PA
10489}
10490
10491/* The to_supports_stopped_by_sw_breakpoint method of target
10492 remote. */
10493
57810aa7 10494bool
f6ac5f3d 10495remote_target::supports_stopped_by_sw_breakpoint ()
f7e6eed5 10496{
f7e6eed5
PA
10497 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10498}
10499
10500/* The to_stopped_by_hw_breakpoint method of target remote. */
10501
57810aa7 10502bool
f6ac5f3d 10503remote_target::stopped_by_hw_breakpoint ()
f7e6eed5 10504{
799a2abe 10505 struct thread_info *thread = inferior_thread ();
f7e6eed5 10506
799a2abe 10507 return (thread->priv != NULL
7aabaf9d
SM
10508 && (get_remote_thread_info (thread)->stop_reason
10509 == TARGET_STOPPED_BY_HW_BREAKPOINT));
f7e6eed5
PA
10510}
10511
10512/* The to_supports_stopped_by_hw_breakpoint method of target
10513 remote. */
10514
57810aa7 10515bool
f6ac5f3d 10516remote_target::supports_stopped_by_hw_breakpoint ()
f7e6eed5 10517{
f7e6eed5
PA
10518 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10519}
10520
57810aa7 10521bool
f6ac5f3d 10522remote_target::stopped_by_watchpoint ()
3c3bea1c 10523{
799a2abe 10524 struct thread_info *thread = inferior_thread ();
ee154bee 10525
799a2abe 10526 return (thread->priv != NULL
7aabaf9d
SM
10527 && (get_remote_thread_info (thread)->stop_reason
10528 == TARGET_STOPPED_BY_WATCHPOINT));
3c3bea1c
GS
10529}
10530
57810aa7 10531bool
f6ac5f3d 10532remote_target::stopped_data_address (CORE_ADDR *addr_p)
3c3bea1c 10533{
799a2abe 10534 struct thread_info *thread = inferior_thread ();
a744cf53 10535
799a2abe 10536 if (thread->priv != NULL
7aabaf9d
SM
10537 && (get_remote_thread_info (thread)->stop_reason
10538 == TARGET_STOPPED_BY_WATCHPOINT))
4aa7a7f5 10539 {
7aabaf9d 10540 *addr_p = get_remote_thread_info (thread)->watch_data_address;
57810aa7 10541 return true;
4aa7a7f5
JJ
10542 }
10543
57810aa7 10544 return false;
3c3bea1c
GS
10545}
10546
10547
f6ac5f3d
PA
10548int
10549remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10550 struct bp_target_info *bp_tgt)
3c3bea1c 10551{
0d5ed153 10552 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10553 struct remote_state *rs;
bba74b36 10554 char *p, *endbuf;
dd61ec5c 10555 char *message;
3c3bea1c 10556
4082afcc 10557 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10558 return -1;
2bc416ba 10559
28439a30
PA
10560 /* Make sure the remote is pointing at the right process, if
10561 necessary. */
10562 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10563 set_general_process ();
10564
4fff2411
JZ
10565 rs = get_remote_state ();
10566 p = rs->buf;
bba74b36 10567 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 10568
96baa820
JM
10569 *(p++) = 'Z';
10570 *(p++) = '1';
10571 *(p++) = ',';
802188a7 10572
0d5ed153 10573 addr = remote_address_masked (addr);
96baa820 10574 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10575 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10576
f6ac5f3d 10577 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10578 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10579
f6ac5f3d 10580 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10581 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10582
6d820c5c
DJ
10583 putpkt (rs->buf);
10584 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10585
6d820c5c 10586 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10587 {
10588 case PACKET_ERROR:
dd61ec5c
MW
10589 if (rs->buf[1] == '.')
10590 {
10591 message = strchr (rs->buf + 2, '.');
10592 if (message)
0316657e 10593 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
10594 }
10595 return -1;
d471ea57
AC
10596 case PACKET_UNKNOWN:
10597 return -1;
10598 case PACKET_OK:
10599 return 0;
10600 }
8e65ff28 10601 internal_error (__FILE__, __LINE__,
e2e0b3e5 10602 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
10603}
10604
d471ea57 10605
f6ac5f3d
PA
10606int
10607remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10608 struct bp_target_info *bp_tgt)
96baa820 10609{
8181d85f 10610 CORE_ADDR addr;
d01949b6 10611 struct remote_state *rs = get_remote_state ();
6d820c5c 10612 char *p = rs->buf;
bba74b36 10613 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 10614
4082afcc 10615 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10616 return -1;
802188a7 10617
28439a30
PA
10618 /* Make sure the remote is pointing at the right process, if
10619 necessary. */
10620 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10621 set_general_process ();
10622
96baa820
JM
10623 *(p++) = 'z';
10624 *(p++) = '1';
10625 *(p++) = ',';
802188a7 10626
8181d85f 10627 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 10628 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10629 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10630
6d820c5c
DJ
10631 putpkt (rs->buf);
10632 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 10633
6d820c5c 10634 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10635 {
10636 case PACKET_ERROR:
10637 case PACKET_UNKNOWN:
10638 return -1;
10639 case PACKET_OK:
10640 return 0;
10641 }
8e65ff28 10642 internal_error (__FILE__, __LINE__,
e2e0b3e5 10643 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 10644}
96baa820 10645
4a5e7a5b
PA
10646/* Verify memory using the "qCRC:" request. */
10647
f6ac5f3d
PA
10648int
10649remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
4a5e7a5b
PA
10650{
10651 struct remote_state *rs = get_remote_state ();
10652 unsigned long host_crc, target_crc;
10653 char *tmp;
10654
936d2992
PA
10655 /* It doesn't make sense to use qCRC if the remote target is
10656 connected but not running. */
10657 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10658 {
10659 enum packet_result result;
28439a30 10660
936d2992
PA
10661 /* Make sure the remote is pointing at the right process. */
10662 set_general_process ();
4a5e7a5b 10663
936d2992
PA
10664 /* FIXME: assumes lma can fit into long. */
10665 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10666 (long) lma, (long) size);
10667 putpkt (rs->buf);
4a5e7a5b 10668
936d2992
PA
10669 /* Be clever; compute the host_crc before waiting for target
10670 reply. */
10671 host_crc = xcrc32 (data, size, 0xffffffff);
10672
10673 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 10674
936d2992
PA
10675 result = packet_ok (rs->buf,
10676 &remote_protocol_packets[PACKET_qCRC]);
10677 if (result == PACKET_ERROR)
10678 return -1;
10679 else if (result == PACKET_OK)
10680 {
10681 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10682 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 10683
936d2992
PA
10684 return (host_crc == target_crc);
10685 }
10686 }
4a5e7a5b 10687
f6ac5f3d 10688 return simple_verify_memory (this, data, lma, size);
4a5e7a5b
PA
10689}
10690
c906108c
SS
10691/* compare-sections command
10692
10693 With no arguments, compares each loadable section in the exec bfd
10694 with the same memory range on the target, and reports mismatches.
4a5e7a5b 10695 Useful for verifying the image on the target against the exec file. */
e514a9d6 10696
c906108c 10697static void
ac88e2de 10698compare_sections_command (const char *args, int from_tty)
c906108c
SS
10699{
10700 asection *s;
ce359b09 10701 const char *sectname;
c906108c
SS
10702 bfd_size_type size;
10703 bfd_vma lma;
10704 int matched = 0;
10705 int mismatched = 0;
4a5e7a5b 10706 int res;
95cf3b38 10707 int read_only = 0;
c906108c
SS
10708
10709 if (!exec_bfd)
8a3fe4f8 10710 error (_("command cannot be used without an exec file"));
c906108c 10711
95cf3b38
DT
10712 if (args != NULL && strcmp (args, "-r") == 0)
10713 {
10714 read_only = 1;
10715 args = NULL;
10716 }
10717
c5aa993b 10718 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
10719 {
10720 if (!(s->flags & SEC_LOAD))
0df8b418 10721 continue; /* Skip non-loadable section. */
c906108c 10722
95cf3b38
DT
10723 if (read_only && (s->flags & SEC_READONLY) == 0)
10724 continue; /* Skip writeable sections */
10725
2c500098 10726 size = bfd_get_section_size (s);
c906108c 10727 if (size == 0)
0df8b418 10728 continue; /* Skip zero-length section. */
c906108c 10729
ce359b09 10730 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 10731 if (args && strcmp (args, sectname) != 0)
0df8b418 10732 continue; /* Not the section selected by user. */
c906108c 10733
0df8b418 10734 matched = 1; /* Do this section. */
c906108c 10735 lma = s->lma;
c906108c 10736
b80406ac
TT
10737 gdb::byte_vector sectdata (size);
10738 bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
c906108c 10739
b80406ac 10740 res = target_verify_memory (sectdata.data (), lma, size);
4a5e7a5b
PA
10741
10742 if (res == -1)
5af949e3 10743 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
10744 paddress (target_gdbarch (), lma),
10745 paddress (target_gdbarch (), lma + size));
c906108c 10746
5af949e3 10747 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
10748 paddress (target_gdbarch (), lma),
10749 paddress (target_gdbarch (), lma + size));
4a5e7a5b 10750 if (res)
c906108c
SS
10751 printf_filtered ("matched.\n");
10752 else
c5aa993b
JM
10753 {
10754 printf_filtered ("MIS-MATCHED!\n");
10755 mismatched++;
10756 }
c906108c
SS
10757 }
10758 if (mismatched > 0)
936d2992 10759 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 10760the loaded file\n"));
c906108c 10761 if (args && !matched)
a3f17187 10762 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
10763}
10764
0e7f50da
UW
10765/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10766 into remote target. The number of bytes written to the remote
10767 target is returned, or -1 for error. */
10768
6b8edb51
PA
10769target_xfer_status
10770remote_target::remote_write_qxfer (const char *object_name,
10771 const char *annex, const gdb_byte *writebuf,
10772 ULONGEST offset, LONGEST len,
10773 ULONGEST *xfered_len,
10774 struct packet_config *packet)
0e7f50da
UW
10775{
10776 int i, buf_len;
10777 ULONGEST n;
0e7f50da
UW
10778 struct remote_state *rs = get_remote_state ();
10779 int max_size = get_memory_write_packet_size ();
10780
7cc244de 10781 if (packet_config_support (packet) == PACKET_DISABLE)
2ed4b548 10782 return TARGET_XFER_E_IO;
0e7f50da
UW
10783
10784 /* Insert header. */
10785 i = snprintf (rs->buf, max_size,
10786 "qXfer:%s:write:%s:%s:",
10787 object_name, annex ? annex : "",
10788 phex_nz (offset, sizeof offset));
10789 max_size -= (i + 1);
10790
10791 /* Escape as much data as fits into rs->buf. */
10792 buf_len = remote_escape_output
124e13d9 10793 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
10794
10795 if (putpkt_binary (rs->buf, i + buf_len) < 0
10796 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10797 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10798 return TARGET_XFER_E_IO;
0e7f50da
UW
10799
10800 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
10801
10802 *xfered_len = n;
92ffd475 10803 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
0e7f50da
UW
10804}
10805
0876f84a
DJ
10806/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10807 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10808 number of bytes read is returned, or 0 for EOF, or -1 for error.
10809 The number of bytes read may be less than LEN without indicating an
10810 EOF. PACKET is checked and updated to indicate whether the remote
10811 target supports this object. */
10812
6b8edb51
PA
10813target_xfer_status
10814remote_target::remote_read_qxfer (const char *object_name,
10815 const char *annex,
10816 gdb_byte *readbuf, ULONGEST offset,
10817 LONGEST len,
10818 ULONGEST *xfered_len,
10819 struct packet_config *packet)
0876f84a 10820{
0876f84a 10821 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
10822 LONGEST i, n, packet_len;
10823
7cc244de 10824 if (packet_config_support (packet) == PACKET_DISABLE)
2ed4b548 10825 return TARGET_XFER_E_IO;
0876f84a
DJ
10826
10827 /* Check whether we've cached an end-of-object packet that matches
10828 this request. */
8e88304f 10829 if (rs->finished_object)
0876f84a 10830 {
8e88304f
TT
10831 if (strcmp (object_name, rs->finished_object) == 0
10832 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10833 && offset == rs->finished_offset)
9b409511
YQ
10834 return TARGET_XFER_EOF;
10835
0876f84a
DJ
10836
10837 /* Otherwise, we're now reading something different. Discard
10838 the cache. */
8e88304f
TT
10839 xfree (rs->finished_object);
10840 xfree (rs->finished_annex);
10841 rs->finished_object = NULL;
10842 rs->finished_annex = NULL;
0876f84a
DJ
10843 }
10844
10845 /* Request only enough to fit in a single packet. The actual data
10846 may not, since we don't know how much of it will need to be escaped;
10847 the target is free to respond with slightly less data. We subtract
10848 five to account for the response type and the protocol frame. */
768adc05 10849 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
0876f84a
DJ
10850 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10851 object_name, annex ? annex : "",
10852 phex_nz (offset, sizeof offset),
10853 phex_nz (n, sizeof n));
10854 i = putpkt (rs->buf);
10855 if (i < 0)
2ed4b548 10856 return TARGET_XFER_E_IO;
0876f84a
DJ
10857
10858 rs->buf[0] = '\0';
10859 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10860 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10861 return TARGET_XFER_E_IO;
0876f84a
DJ
10862
10863 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10864 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10865
10866 /* 'm' means there is (or at least might be) more data after this
10867 batch. That does not make sense unless there's at least one byte
10868 of data in this reply. */
10869 if (rs->buf[0] == 'm' && packet_len == 1)
10870 error (_("Remote qXfer reply contained no data."));
10871
10872 /* Got some data. */
bc20a4af
PA
10873 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10874 packet_len - 1, readbuf, n);
0876f84a
DJ
10875
10876 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
10877 or possibly empty. If we have the final block of a non-empty
10878 object, record this fact to bypass a subsequent partial read. */
10879 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 10880 {
8e88304f
TT
10881 rs->finished_object = xstrdup (object_name);
10882 rs->finished_annex = xstrdup (annex ? annex : "");
10883 rs->finished_offset = offset + i;
0876f84a
DJ
10884 }
10885
9b409511
YQ
10886 if (i == 0)
10887 return TARGET_XFER_EOF;
10888 else
10889 {
10890 *xfered_len = i;
10891 return TARGET_XFER_OK;
10892 }
0876f84a
DJ
10893}
10894
f6ac5f3d
PA
10895enum target_xfer_status
10896remote_target::xfer_partial (enum target_object object,
10897 const char *annex, gdb_byte *readbuf,
10898 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10899 ULONGEST *xfered_len)
c906108c 10900{
82f73884 10901 struct remote_state *rs;
c906108c 10902 int i;
6d820c5c 10903 char *p2;
1e3ff5ad 10904 char query_type;
124e13d9 10905 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 10906
e6e4e701 10907 set_remote_traceframe ();
82f73884
PA
10908 set_general_thread (inferior_ptid);
10909
10910 rs = get_remote_state ();
10911
b2182ed2 10912 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
10913 if (object == TARGET_OBJECT_MEMORY)
10914 {
2d717e4f
DJ
10915 /* If the remote target is connected but not running, we should
10916 pass this request down to a lower stratum (e.g. the executable
10917 file). */
10918 if (!target_has_execution)
9b409511 10919 return TARGET_XFER_EOF;
2d717e4f 10920
21e3b9b9 10921 if (writebuf != NULL)
124e13d9
SM
10922 return remote_write_bytes (offset, writebuf, len, unit_size,
10923 xfered_len);
21e3b9b9 10924 else
6b8edb51 10925 return remote_read_bytes (offset, readbuf, len, unit_size,
124e13d9 10926 xfered_len);
21e3b9b9
DJ
10927 }
10928
0df8b418 10929 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
10930 if (object == TARGET_OBJECT_SPU)
10931 {
10932 if (readbuf)
f6ac5f3d 10933 return remote_read_qxfer ("spu", annex, readbuf, offset, len,
9b409511
YQ
10934 xfered_len, &remote_protocol_packets
10935 [PACKET_qXfer_spu_read]);
0e7f50da 10936 else
f6ac5f3d 10937 return remote_write_qxfer ("spu", annex, writebuf, offset, len,
9b409511
YQ
10938 xfered_len, &remote_protocol_packets
10939 [PACKET_qXfer_spu_write]);
0e7f50da
UW
10940 }
10941
4aa995e1
PA
10942 /* Handle extra signal info using qxfer packets. */
10943 if (object == TARGET_OBJECT_SIGNAL_INFO)
10944 {
10945 if (readbuf)
f6ac5f3d 10946 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
9b409511 10947 xfered_len, &remote_protocol_packets
4aa995e1
PA
10948 [PACKET_qXfer_siginfo_read]);
10949 else
f6ac5f3d 10950 return remote_write_qxfer ("siginfo", annex,
9b409511 10951 writebuf, offset, len, xfered_len,
4aa995e1
PA
10952 &remote_protocol_packets
10953 [PACKET_qXfer_siginfo_write]);
10954 }
10955
0fb4aa4b
PA
10956 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10957 {
10958 if (readbuf)
f6ac5f3d 10959 return remote_read_qxfer ("statictrace", annex,
9b409511 10960 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
10961 &remote_protocol_packets
10962 [PACKET_qXfer_statictrace_read]);
10963 else
2ed4b548 10964 return TARGET_XFER_E_IO;
0fb4aa4b
PA
10965 }
10966
a76d924d
DJ
10967 /* Only handle flash writes. */
10968 if (writebuf != NULL)
10969 {
a76d924d
DJ
10970 switch (object)
10971 {
10972 case TARGET_OBJECT_FLASH:
6b8edb51 10973 return remote_flash_write (offset, len, xfered_len,
9b409511 10974 writebuf);
a76d924d
DJ
10975
10976 default:
2ed4b548 10977 return TARGET_XFER_E_IO;
a76d924d
DJ
10978 }
10979 }
4b8a223f 10980
1e3ff5ad
AC
10981 /* Map pre-existing objects onto letters. DO NOT do this for new
10982 objects!!! Instead specify new query packets. */
10983 switch (object)
c906108c 10984 {
1e3ff5ad
AC
10985 case TARGET_OBJECT_AVR:
10986 query_type = 'R';
10987 break;
802188a7
RM
10988
10989 case TARGET_OBJECT_AUXV:
0876f84a 10990 gdb_assert (annex == NULL);
f6ac5f3d 10991 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
9b409511 10992 xfered_len,
0876f84a 10993 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 10994
23181151
DJ
10995 case TARGET_OBJECT_AVAILABLE_FEATURES:
10996 return remote_read_qxfer
f6ac5f3d 10997 ("features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
10998 &remote_protocol_packets[PACKET_qXfer_features]);
10999
cfa9d6d9
DJ
11000 case TARGET_OBJECT_LIBRARIES:
11001 return remote_read_qxfer
f6ac5f3d 11002 ("libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
11003 &remote_protocol_packets[PACKET_qXfer_libraries]);
11004
2268b414
JK
11005 case TARGET_OBJECT_LIBRARIES_SVR4:
11006 return remote_read_qxfer
f6ac5f3d 11007 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
11008 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
11009
fd79ecee
DJ
11010 case TARGET_OBJECT_MEMORY_MAP:
11011 gdb_assert (annex == NULL);
f6ac5f3d 11012 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
9b409511 11013 xfered_len,
fd79ecee
DJ
11014 &remote_protocol_packets[PACKET_qXfer_memory_map]);
11015
07e059b5
VP
11016 case TARGET_OBJECT_OSDATA:
11017 /* Should only get here if we're connected. */
5d93a237 11018 gdb_assert (rs->remote_desc);
07e059b5 11019 return remote_read_qxfer
f6ac5f3d 11020 ("osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
11021 &remote_protocol_packets[PACKET_qXfer_osdata]);
11022
dc146f7c
VP
11023 case TARGET_OBJECT_THREADS:
11024 gdb_assert (annex == NULL);
f6ac5f3d 11025 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
9b409511 11026 xfered_len,
dc146f7c
VP
11027 &remote_protocol_packets[PACKET_qXfer_threads]);
11028
b3b9301e
PA
11029 case TARGET_OBJECT_TRACEFRAME_INFO:
11030 gdb_assert (annex == NULL);
11031 return remote_read_qxfer
f6ac5f3d 11032 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 11033 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
11034
11035 case TARGET_OBJECT_FDPIC:
f6ac5f3d 11036 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
9b409511 11037 xfered_len,
78d85199 11038 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
11039
11040 case TARGET_OBJECT_OPENVMS_UIB:
f6ac5f3d 11041 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
9b409511 11042 xfered_len,
169081d0
TG
11043 &remote_protocol_packets[PACKET_qXfer_uib]);
11044
9accd112 11045 case TARGET_OBJECT_BTRACE:
f6ac5f3d 11046 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
9b409511 11047 xfered_len,
9accd112
MM
11048 &remote_protocol_packets[PACKET_qXfer_btrace]);
11049
f4abbc16 11050 case TARGET_OBJECT_BTRACE_CONF:
f6ac5f3d 11051 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
f4abbc16
MM
11052 len, xfered_len,
11053 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11054
c78fa86a 11055 case TARGET_OBJECT_EXEC_FILE:
f6ac5f3d 11056 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
c78fa86a
GB
11057 len, xfered_len,
11058 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11059
1e3ff5ad 11060 default:
2ed4b548 11061 return TARGET_XFER_E_IO;
c906108c
SS
11062 }
11063
0df8b418 11064 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 11065 large enough let the caller deal with it. */
ea9c271d 11066 if (len < get_remote_packet_size ())
2ed4b548 11067 return TARGET_XFER_E_IO;
ea9c271d 11068 len = get_remote_packet_size ();
1e3ff5ad 11069
23860348 11070 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 11071 if (!rs->remote_desc)
8a3fe4f8 11072 error (_("remote query is only available after target open"));
c906108c 11073
1e3ff5ad 11074 gdb_assert (annex != NULL);
4b8a223f 11075 gdb_assert (readbuf != NULL);
c906108c 11076
6d820c5c 11077 p2 = rs->buf;
c906108c
SS
11078 *p2++ = 'q';
11079 *p2++ = query_type;
11080
23860348
MS
11081 /* We used one buffer char for the remote protocol q command and
11082 another for the query type. As the remote protocol encapsulation
11083 uses 4 chars plus one extra in case we are debugging
11084 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11085 string. */
c906108c 11086 i = 0;
ea9c271d 11087 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 11088 {
1e3ff5ad
AC
11089 /* Bad caller may have sent forbidden characters. */
11090 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11091 *p2++ = annex[i];
c906108c
SS
11092 i++;
11093 }
1e3ff5ad
AC
11094 *p2 = '\0';
11095 gdb_assert (annex[i] == '\0');
c906108c 11096
6d820c5c 11097 i = putpkt (rs->buf);
c5aa993b 11098 if (i < 0)
2ed4b548 11099 return TARGET_XFER_E_IO;
c906108c 11100
6d820c5c
DJ
11101 getpkt (&rs->buf, &rs->buf_size, 0);
11102 strcpy ((char *) readbuf, rs->buf);
c906108c 11103
9b409511 11104 *xfered_len = strlen ((char *) readbuf);
92ffd475 11105 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
11106}
11107
09c98b44
DB
11108/* Implementation of to_get_memory_xfer_limit. */
11109
f6ac5f3d
PA
11110ULONGEST
11111remote_target::get_memory_xfer_limit ()
09c98b44
DB
11112{
11113 return get_memory_write_packet_size ();
11114}
11115
f6ac5f3d
PA
11116int
11117remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11118 const gdb_byte *pattern, ULONGEST pattern_len,
11119 CORE_ADDR *found_addrp)
08388c79 11120{
f5656ead 11121 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
11122 struct remote_state *rs = get_remote_state ();
11123 int max_size = get_memory_write_packet_size ();
11124 struct packet_config *packet =
11125 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
11126 /* Number of packet bytes used to encode the pattern;
11127 this could be more than PATTERN_LEN due to escape characters. */
08388c79 11128 int escaped_pattern_len;
0df8b418 11129 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
11130 int used_pattern_len;
11131 int i;
11132 int found;
11133 ULONGEST found_addr;
11134
7cc244de
PA
11135 /* Don't go to the target if we don't have to. This is done before
11136 checking packet_config_support to avoid the possibility that a
11137 success for this edge case means the facility works in
11138 general. */
08388c79
DE
11139 if (pattern_len > search_space_len)
11140 return 0;
11141 if (pattern_len == 0)
11142 {
11143 *found_addrp = start_addr;
11144 return 1;
11145 }
11146
11147 /* If we already know the packet isn't supported, fall back to the simple
11148 way of searching memory. */
11149
4082afcc 11150 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
11151 {
11152 /* Target doesn't provided special support, fall back and use the
11153 standard support (copy memory and do the search here). */
f6ac5f3d 11154 return simple_search_memory (this, start_addr, search_space_len,
08388c79
DE
11155 pattern, pattern_len, found_addrp);
11156 }
11157
28439a30
PA
11158 /* Make sure the remote is pointing at the right process. */
11159 set_general_process ();
11160
08388c79
DE
11161 /* Insert header. */
11162 i = snprintf (rs->buf, max_size,
11163 "qSearch:memory:%s;%s;",
5af949e3 11164 phex_nz (start_addr, addr_size),
08388c79
DE
11165 phex_nz (search_space_len, sizeof (search_space_len)));
11166 max_size -= (i + 1);
11167
11168 /* Escape as much data as fits into rs->buf. */
11169 escaped_pattern_len =
124e13d9 11170 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
11171 &used_pattern_len, max_size);
11172
11173 /* Bail if the pattern is too large. */
11174 if (used_pattern_len != pattern_len)
9b20d036 11175 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
11176
11177 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
11178 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
11179 || packet_ok (rs->buf, packet) != PACKET_OK)
11180 {
11181 /* The request may not have worked because the command is not
11182 supported. If so, fall back to the simple way. */
7cc244de 11183 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79 11184 {
f6ac5f3d 11185 return simple_search_memory (this, start_addr, search_space_len,
08388c79
DE
11186 pattern, pattern_len, found_addrp);
11187 }
11188 return -1;
11189 }
11190
11191 if (rs->buf[0] == '0')
11192 found = 0;
11193 else if (rs->buf[0] == '1')
11194 {
11195 found = 1;
11196 if (rs->buf[1] != ',')
10e0fa18 11197 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
11198 unpack_varlen_hex (rs->buf + 2, &found_addr);
11199 *found_addrp = found_addr;
11200 }
11201 else
10e0fa18 11202 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
11203
11204 return found;
11205}
11206
f6ac5f3d
PA
11207void
11208remote_target::rcmd (const char *command, struct ui_file *outbuf)
96baa820 11209{
d01949b6 11210 struct remote_state *rs = get_remote_state ();
2e9f7625 11211 char *p = rs->buf;
96baa820 11212
5d93a237 11213 if (!rs->remote_desc)
8a3fe4f8 11214 error (_("remote rcmd is only available after target open"));
96baa820 11215
23860348 11216 /* Send a NULL command across as an empty command. */
7be570e7
JM
11217 if (command == NULL)
11218 command = "";
11219
23860348 11220 /* The query prefix. */
2e9f7625
DJ
11221 strcpy (rs->buf, "qRcmd,");
11222 p = strchr (rs->buf, '\0');
96baa820 11223
3e43a32a
MS
11224 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
11225 > get_remote_packet_size ())
8a3fe4f8 11226 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 11227
23860348 11228 /* Encode the actual command. */
a30bf1f1 11229 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 11230
6d820c5c 11231 if (putpkt (rs->buf) < 0)
8a3fe4f8 11232 error (_("Communication problem with target."));
96baa820
JM
11233
11234 /* get/display the response */
11235 while (1)
11236 {
2e9f7625
DJ
11237 char *buf;
11238
00bf0b85 11239 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 11240 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 11241 rs->buf[0] = '\0';
5b37825d
PW
11242 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11243 {
11244 /* Timeout. Continue to (try to) read responses.
11245 This is better than stopping with an error, assuming the stub
11246 is still executing the (long) monitor command.
11247 If needed, the user can interrupt gdb using C-c, obtaining
11248 an effect similar to stop on timeout. */
11249 continue;
11250 }
2e9f7625 11251 buf = rs->buf;
96baa820 11252 if (buf[0] == '\0')
8a3fe4f8 11253 error (_("Target does not support this command."));
96baa820
JM
11254 if (buf[0] == 'O' && buf[1] != 'K')
11255 {
23860348 11256 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
11257 continue;
11258 }
11259 if (strcmp (buf, "OK") == 0)
11260 break;
7be570e7
JM
11261 if (strlen (buf) == 3 && buf[0] == 'E'
11262 && isdigit (buf[1]) && isdigit (buf[2]))
11263 {
8a3fe4f8 11264 error (_("Protocol error with Rcmd"));
7be570e7 11265 }
96baa820
JM
11266 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11267 {
11268 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 11269
96baa820
JM
11270 fputc_unfiltered (c, outbuf);
11271 }
11272 break;
11273 }
11274}
11275
f6ac5f3d
PA
11276std::vector<mem_region>
11277remote_target::memory_map ()
fd79ecee 11278{
a664f67e 11279 std::vector<mem_region> result;
9018be22 11280 gdb::optional<gdb::char_vector> text
8b88a78e 11281 = target_read_stralloc (current_top_target (), TARGET_OBJECT_MEMORY_MAP, NULL);
fd79ecee
DJ
11282
11283 if (text)
9018be22 11284 result = parse_memory_map (text->data ());
fd79ecee
DJ
11285
11286 return result;
11287}
11288
c906108c 11289static void
ac88e2de 11290packet_command (const char *args, int from_tty)
c906108c 11291{
6b8edb51 11292 remote_target *remote = get_current_remote_target ();
c906108c 11293
6b8edb51 11294 if (remote == nullptr)
8a3fe4f8 11295 error (_("command can only be used with remote target"));
c906108c 11296
6b8edb51
PA
11297 remote->packet_command (args, from_tty);
11298}
11299
11300void
11301remote_target::packet_command (const char *args, int from_tty)
11302{
c5aa993b 11303 if (!args)
8a3fe4f8 11304 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
11305
11306 puts_filtered ("sending: ");
11307 print_packet (args);
11308 puts_filtered ("\n");
11309 putpkt (args);
11310
6b8edb51
PA
11311 remote_state *rs = get_remote_state ();
11312
6d820c5c 11313 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 11314 puts_filtered ("received: ");
6d820c5c 11315 print_packet (rs->buf);
c906108c
SS
11316 puts_filtered ("\n");
11317}
11318
11319#if 0
23860348 11320/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 11321
a14ed312 11322static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 11323
a14ed312 11324static void threadset_test_cmd (char *cmd, int tty);
c906108c 11325
a14ed312 11326static void threadalive_test (char *cmd, int tty);
c906108c 11327
a14ed312 11328static void threadlist_test_cmd (char *cmd, int tty);
c906108c 11329
23860348 11330int get_and_display_threadinfo (threadref *ref);
c906108c 11331
a14ed312 11332static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 11333
23860348 11334static int thread_display_step (threadref *ref, void *context);
c906108c 11335
a14ed312 11336static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 11337
a14ed312 11338static void init_remote_threadtests (void);
c906108c 11339
23860348 11340#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
11341
11342static void
0b39b52e 11343threadset_test_cmd (const char *cmd, int tty)
c906108c
SS
11344{
11345 int sample_thread = SAMPLE_THREAD;
11346
a3f17187 11347 printf_filtered (_("Remote threadset test\n"));
79d7f229 11348 set_general_thread (sample_thread);
c906108c
SS
11349}
11350
11351
11352static void
0b39b52e 11353threadalive_test (const char *cmd, int tty)
c906108c
SS
11354{
11355 int sample_thread = SAMPLE_THREAD;
e99b03dc 11356 int pid = inferior_ptid.pid ();
fd79271b 11357 ptid_t ptid = ptid_t (pid, sample_thread, 0);
c906108c 11358
79d7f229 11359 if (remote_thread_alive (ptid))
c906108c
SS
11360 printf_filtered ("PASS: Thread alive test\n");
11361 else
11362 printf_filtered ("FAIL: Thread alive test\n");
11363}
11364
23860348 11365void output_threadid (char *title, threadref *ref);
c906108c
SS
11366
11367void
fba45db2 11368output_threadid (char *title, threadref *ref)
c906108c
SS
11369{
11370 char hexid[20];
11371
23860348 11372 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
11373 hexid[16] = 0;
11374 printf_filtered ("%s %s\n", title, (&hexid[0]));
11375}
11376
11377static void
0b39b52e 11378threadlist_test_cmd (const char *cmd, int tty)
c906108c
SS
11379{
11380 int startflag = 1;
11381 threadref nextthread;
11382 int done, result_count;
11383 threadref threadlist[3];
11384
11385 printf_filtered ("Remote Threadlist test\n");
11386 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11387 &result_count, &threadlist[0]))
11388 printf_filtered ("FAIL: threadlist test\n");
11389 else
11390 {
11391 threadref *scan = threadlist;
11392 threadref *limit = scan + result_count;
11393
11394 while (scan < limit)
11395 output_threadid (" thread ", scan++);
11396 }
11397}
11398
11399void
fba45db2 11400display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
11401{
11402 output_threadid ("Threadid: ", &info->threadid);
11403 printf_filtered ("Name: %s\n ", info->shortname);
11404 printf_filtered ("State: %s\n", info->display);
11405 printf_filtered ("other: %s\n\n", info->more_display);
11406}
11407
11408int
fba45db2 11409get_and_display_threadinfo (threadref *ref)
c906108c
SS
11410{
11411 int result;
11412 int set;
11413 struct gdb_ext_thread_info threadinfo;
11414
11415 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11416 | TAG_MOREDISPLAY | TAG_DISPLAY;
11417 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11418 display_thread_info (&threadinfo);
11419 return result;
11420}
11421
11422static void
0b39b52e 11423threadinfo_test_cmd (const char *cmd, int tty)
c906108c
SS
11424{
11425 int athread = SAMPLE_THREAD;
11426 threadref thread;
11427 int set;
11428
11429 int_to_threadref (&thread, athread);
11430 printf_filtered ("Remote Threadinfo test\n");
11431 if (!get_and_display_threadinfo (&thread))
11432 printf_filtered ("FAIL cannot get thread info\n");
11433}
11434
11435static int
fba45db2 11436thread_display_step (threadref *ref, void *context)
c906108c
SS
11437{
11438 /* output_threadid(" threadstep ",ref); *//* simple test */
11439 return get_and_display_threadinfo (ref);
11440}
11441
11442static void
0b39b52e 11443threadlist_update_test_cmd (const char *cmd, int tty)
c906108c
SS
11444{
11445 printf_filtered ("Remote Threadlist update test\n");
11446 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11447}
11448
11449static void
11450init_remote_threadtests (void)
11451{
3e43a32a
MS
11452 add_com ("tlist", class_obscure, threadlist_test_cmd,
11453 _("Fetch and print the remote list of "
11454 "thread identifiers, one pkt only"));
c906108c 11455 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 11456 _("Fetch and display info about one thread"));
c906108c 11457 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 11458 _("Test setting to a different thread"));
c906108c 11459 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 11460 _("Iterate through updating all remote thread info"));
c906108c 11461 add_com ("talive", class_obscure, threadalive_test,
1bedd215 11462 _(" Remote thread alive test "));
c906108c
SS
11463}
11464
11465#endif /* 0 */
11466
f3fb8c85
MS
11467/* Convert a thread ID to a string. Returns the string in a static
11468 buffer. */
11469
f6ac5f3d
PA
11470const char *
11471remote_target::pid_to_str (ptid_t ptid)
f3fb8c85 11472{
79d7f229 11473 static char buf[64];
82f73884 11474 struct remote_state *rs = get_remote_state ();
f3fb8c85 11475
d7e15655 11476 if (ptid == null_ptid)
7cee1e54 11477 return normal_pid_to_str (ptid);
0e998d96 11478 else if (ptid.is_pid ())
ecd0ada5
PA
11479 {
11480 /* Printing an inferior target id. */
11481
11482 /* When multi-process extensions are off, there's no way in the
11483 remote protocol to know the remote process id, if there's any
11484 at all. There's one exception --- when we're connected with
11485 target extended-remote, and we manually attached to a process
11486 with "attach PID". We don't record anywhere a flag that
11487 allows us to distinguish that case from the case of
11488 connecting with extended-remote and the stub already being
11489 attached to a process, and reporting yes to qAttached, hence
11490 no smart special casing here. */
11491 if (!remote_multi_process_p (rs))
11492 {
11493 xsnprintf (buf, sizeof buf, "Remote target");
11494 return buf;
11495 }
11496
11497 return normal_pid_to_str (ptid);
82f73884 11498 }
ecd0ada5 11499 else
79d7f229 11500 {
d7e15655 11501 if (magic_null_ptid == ptid)
ecd0ada5 11502 xsnprintf (buf, sizeof buf, "Thread <main>");
8020350c 11503 else if (remote_multi_process_p (rs))
e38504b3 11504 if (ptid.lwp () == 0)
de0d863e
DB
11505 return normal_pid_to_str (ptid);
11506 else
11507 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
e38504b3 11508 ptid.pid (), ptid.lwp ());
ecd0ada5
PA
11509 else
11510 xsnprintf (buf, sizeof buf, "Thread %ld",
e38504b3 11511 ptid.lwp ());
79d7f229
PA
11512 return buf;
11513 }
f3fb8c85
MS
11514}
11515
38691318
KB
11516/* Get the address of the thread local variable in OBJFILE which is
11517 stored at OFFSET within the thread local storage for thread PTID. */
11518
f6ac5f3d
PA
11519CORE_ADDR
11520remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11521 CORE_ADDR offset)
38691318 11522{
4082afcc 11523 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
11524 {
11525 struct remote_state *rs = get_remote_state ();
6d820c5c 11526 char *p = rs->buf;
82f73884 11527 char *endp = rs->buf + get_remote_packet_size ();
571dd617 11528 enum packet_result result;
38691318
KB
11529
11530 strcpy (p, "qGetTLSAddr:");
11531 p += strlen (p);
82f73884 11532 p = write_ptid (p, endp, ptid);
38691318
KB
11533 *p++ = ',';
11534 p += hexnumstr (p, offset);
11535 *p++ = ',';
11536 p += hexnumstr (p, lm);
11537 *p++ = '\0';
11538
6d820c5c
DJ
11539 putpkt (rs->buf);
11540 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
11541 result = packet_ok (rs->buf,
11542 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 11543 if (result == PACKET_OK)
38691318
KB
11544 {
11545 ULONGEST result;
11546
6d820c5c 11547 unpack_varlen_hex (rs->buf, &result);
38691318
KB
11548 return result;
11549 }
571dd617 11550 else if (result == PACKET_UNKNOWN)
109c3e39
AC
11551 throw_error (TLS_GENERIC_ERROR,
11552 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 11553 else
109c3e39
AC
11554 throw_error (TLS_GENERIC_ERROR,
11555 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
11556 }
11557 else
109c3e39
AC
11558 throw_error (TLS_GENERIC_ERROR,
11559 _("TLS not supported or disabled on this target"));
38691318
KB
11560 /* Not reached. */
11561 return 0;
11562}
11563
711e434b
PM
11564/* Provide thread local base, i.e. Thread Information Block address.
11565 Returns 1 if ptid is found and thread_local_base is non zero. */
11566
57810aa7 11567bool
f6ac5f3d 11568remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
711e434b 11569{
4082afcc 11570 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
11571 {
11572 struct remote_state *rs = get_remote_state ();
11573 char *p = rs->buf;
11574 char *endp = rs->buf + get_remote_packet_size ();
11575 enum packet_result result;
11576
11577 strcpy (p, "qGetTIBAddr:");
11578 p += strlen (p);
11579 p = write_ptid (p, endp, ptid);
11580 *p++ = '\0';
11581
11582 putpkt (rs->buf);
11583 getpkt (&rs->buf, &rs->buf_size, 0);
11584 result = packet_ok (rs->buf,
11585 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11586 if (result == PACKET_OK)
11587 {
11588 ULONGEST result;
11589
11590 unpack_varlen_hex (rs->buf, &result);
11591 if (addr)
11592 *addr = (CORE_ADDR) result;
57810aa7 11593 return true;
711e434b
PM
11594 }
11595 else if (result == PACKET_UNKNOWN)
11596 error (_("Remote target doesn't support qGetTIBAddr packet"));
11597 else
11598 error (_("Remote target failed to process qGetTIBAddr request"));
11599 }
11600 else
11601 error (_("qGetTIBAddr not supported or disabled on this target"));
11602 /* Not reached. */
57810aa7 11603 return false;
711e434b
PM
11604}
11605
29709017
DJ
11606/* Support for inferring a target description based on the current
11607 architecture and the size of a 'g' packet. While the 'g' packet
11608 can have any size (since optional registers can be left off the
11609 end), some sizes are easily recognizable given knowledge of the
11610 approximate architecture. */
11611
11612struct remote_g_packet_guess
11613{
11614 int bytes;
11615 const struct target_desc *tdesc;
11616};
11617typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11618DEF_VEC_O(remote_g_packet_guess_s);
11619
11620struct remote_g_packet_data
11621{
11622 VEC(remote_g_packet_guess_s) *guesses;
11623};
11624
11625static struct gdbarch_data *remote_g_packet_data_handle;
11626
11627static void *
11628remote_g_packet_data_init (struct obstack *obstack)
11629{
11630 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11631}
11632
11633void
11634register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11635 const struct target_desc *tdesc)
11636{
11637 struct remote_g_packet_data *data
19ba03f4
SM
11638 = ((struct remote_g_packet_data *)
11639 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
11640 struct remote_g_packet_guess new_guess, *guess;
11641 int ix;
11642
11643 gdb_assert (tdesc != NULL);
11644
11645 for (ix = 0;
11646 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11647 ix++)
11648 if (guess->bytes == bytes)
11649 internal_error (__FILE__, __LINE__,
9b20d036 11650 _("Duplicate g packet description added for size %d"),
29709017
DJ
11651 bytes);
11652
11653 new_guess.bytes = bytes;
11654 new_guess.tdesc = tdesc;
11655 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11656}
11657
d962ef82
DJ
11658/* Return 1 if remote_read_description would do anything on this target
11659 and architecture, 0 otherwise. */
11660
11661static int
11662remote_read_description_p (struct target_ops *target)
11663{
11664 struct remote_g_packet_data *data
19ba03f4
SM
11665 = ((struct remote_g_packet_data *)
11666 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
11667
11668 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11669 return 1;
11670
11671 return 0;
11672}
11673
f6ac5f3d
PA
11674const struct target_desc *
11675remote_target::read_description ()
29709017
DJ
11676{
11677 struct remote_g_packet_data *data
19ba03f4
SM
11678 = ((struct remote_g_packet_data *)
11679 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 11680
d962ef82
DJ
11681 /* Do not try this during initial connection, when we do not know
11682 whether there is a running but stopped thread. */
d7e15655 11683 if (!target_has_execution || inferior_ptid == null_ptid)
b6a8c27b 11684 return beneath ()->read_description ();
d962ef82 11685
29709017
DJ
11686 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11687 {
11688 struct remote_g_packet_guess *guess;
11689 int ix;
11690 int bytes = send_g_packet ();
11691
11692 for (ix = 0;
11693 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11694 ix++)
11695 if (guess->bytes == bytes)
11696 return guess->tdesc;
11697
11698 /* We discard the g packet. A minor optimization would be to
11699 hold on to it, and fill the register cache once we have selected
11700 an architecture, but it's too tricky to do safely. */
11701 }
11702
b6a8c27b 11703 return beneath ()->read_description ();
29709017
DJ
11704}
11705
a6b151f1
DJ
11706/* Remote file transfer support. This is host-initiated I/O, not
11707 target-initiated; for target-initiated, see remote-fileio.c. */
11708
11709/* If *LEFT is at least the length of STRING, copy STRING to
11710 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11711 decrease *LEFT. Otherwise raise an error. */
11712
11713static void
a121b7c1 11714remote_buffer_add_string (char **buffer, int *left, const char *string)
a6b151f1
DJ
11715{
11716 int len = strlen (string);
11717
11718 if (len > *left)
11719 error (_("Packet too long for target."));
11720
11721 memcpy (*buffer, string, len);
11722 *buffer += len;
11723 *left -= len;
11724
11725 /* NUL-terminate the buffer as a convenience, if there is
11726 room. */
11727 if (*left)
11728 **buffer = '\0';
11729}
11730
11731/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11732 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11733 decrease *LEFT. Otherwise raise an error. */
11734
11735static void
11736remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11737 int len)
11738{
11739 if (2 * len > *left)
11740 error (_("Packet too long for target."));
11741
11742 bin2hex (bytes, *buffer, len);
11743 *buffer += 2 * len;
11744 *left -= 2 * len;
11745
11746 /* NUL-terminate the buffer as a convenience, if there is
11747 room. */
11748 if (*left)
11749 **buffer = '\0';
11750}
11751
11752/* If *LEFT is large enough, convert VALUE to hex and add it to
11753 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11754 decrease *LEFT. Otherwise raise an error. */
11755
11756static void
11757remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11758{
11759 int len = hexnumlen (value);
11760
11761 if (len > *left)
11762 error (_("Packet too long for target."));
11763
11764 hexnumstr (*buffer, value);
11765 *buffer += len;
11766 *left -= len;
11767
11768 /* NUL-terminate the buffer as a convenience, if there is
11769 room. */
11770 if (*left)
11771 **buffer = '\0';
11772}
11773
11774/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11775 value, *REMOTE_ERRNO to the remote error number or zero if none
11776 was included, and *ATTACHMENT to point to the start of the annex
11777 if any. The length of the packet isn't needed here; there may
11778 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11779
11780 Return 0 if the packet could be parsed, -1 if it could not. If
11781 -1 is returned, the other variables may not be initialized. */
11782
11783static int
11784remote_hostio_parse_result (char *buffer, int *retcode,
11785 int *remote_errno, char **attachment)
11786{
11787 char *p, *p2;
11788
11789 *remote_errno = 0;
11790 *attachment = NULL;
11791
11792 if (buffer[0] != 'F')
11793 return -1;
11794
11795 errno = 0;
11796 *retcode = strtol (&buffer[1], &p, 16);
11797 if (errno != 0 || p == &buffer[1])
11798 return -1;
11799
11800 /* Check for ",errno". */
11801 if (*p == ',')
11802 {
11803 errno = 0;
11804 *remote_errno = strtol (p + 1, &p2, 16);
11805 if (errno != 0 || p + 1 == p2)
11806 return -1;
11807 p = p2;
11808 }
11809
11810 /* Check for ";attachment". If there is no attachment, the
11811 packet should end here. */
11812 if (*p == ';')
11813 {
11814 *attachment = p + 1;
11815 return 0;
11816 }
11817 else if (*p == '\0')
11818 return 0;
11819 else
11820 return -1;
11821}
11822
11823/* Send a prepared I/O packet to the target and read its response.
11824 The prepared packet is in the global RS->BUF before this function
11825 is called, and the answer is there when we return.
11826
11827 COMMAND_BYTES is the length of the request to send, which may include
11828 binary data. WHICH_PACKET is the packet configuration to check
11829 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11830 is set to the error number and -1 is returned. Otherwise the value
11831 returned by the function is returned.
11832
11833 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11834 attachment is expected; an error will be reported if there's a
11835 mismatch. If one is found, *ATTACHMENT will be set to point into
11836 the packet buffer and *ATTACHMENT_LEN will be set to the
11837 attachment's length. */
11838
6b8edb51
PA
11839int
11840remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
11841 int *remote_errno, char **attachment,
11842 int *attachment_len)
a6b151f1
DJ
11843{
11844 struct remote_state *rs = get_remote_state ();
11845 int ret, bytes_read;
11846 char *attachment_tmp;
11847
20db9c52 11848 if (packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
11849 {
11850 *remote_errno = FILEIO_ENOSYS;
11851 return -1;
11852 }
11853
11854 putpkt_binary (rs->buf, command_bytes);
11855 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11856
11857 /* If it timed out, something is wrong. Don't try to parse the
11858 buffer. */
11859 if (bytes_read < 0)
11860 {
11861 *remote_errno = FILEIO_EINVAL;
11862 return -1;
11863 }
11864
11865 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11866 {
11867 case PACKET_ERROR:
11868 *remote_errno = FILEIO_EINVAL;
11869 return -1;
11870 case PACKET_UNKNOWN:
11871 *remote_errno = FILEIO_ENOSYS;
11872 return -1;
11873 case PACKET_OK:
11874 break;
11875 }
11876
11877 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11878 &attachment_tmp))
11879 {
11880 *remote_errno = FILEIO_EINVAL;
11881 return -1;
11882 }
11883
11884 /* Make sure we saw an attachment if and only if we expected one. */
11885 if ((attachment_tmp == NULL && attachment != NULL)
11886 || (attachment_tmp != NULL && attachment == NULL))
11887 {
11888 *remote_errno = FILEIO_EINVAL;
11889 return -1;
11890 }
11891
11892 /* If an attachment was found, it must point into the packet buffer;
11893 work out how many bytes there were. */
11894 if (attachment_tmp != NULL)
11895 {
11896 *attachment = attachment_tmp;
11897 *attachment_len = bytes_read - (*attachment - rs->buf);
11898 }
11899
11900 return ret;
11901}
11902
dd194f6b 11903/* See declaration.h. */
80152258 11904
dd194f6b
PA
11905void
11906readahead_cache::invalidate ()
80152258 11907{
dd194f6b 11908 this->fd = -1;
80152258
PA
11909}
11910
dd194f6b 11911/* See declaration.h. */
80152258 11912
dd194f6b
PA
11913void
11914readahead_cache::invalidate_fd (int fd)
80152258 11915{
dd194f6b
PA
11916 if (this->fd == fd)
11917 this->fd = -1;
80152258
PA
11918}
11919
15a201c8
GB
11920/* Set the filesystem remote_hostio functions that take FILENAME
11921 arguments will use. Return 0 on success, or -1 if an error
11922 occurs (and set *REMOTE_ERRNO). */
11923
6b8edb51
PA
11924int
11925remote_target::remote_hostio_set_filesystem (struct inferior *inf,
11926 int *remote_errno)
15a201c8
GB
11927{
11928 struct remote_state *rs = get_remote_state ();
11929 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11930 char *p = rs->buf;
11931 int left = get_remote_packet_size () - 1;
11932 char arg[9];
11933 int ret;
11934
11935 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11936 return 0;
11937
11938 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11939 return 0;
11940
11941 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11942
11943 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11944 remote_buffer_add_string (&p, &left, arg);
11945
11946 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11947 remote_errno, NULL, NULL);
11948
11949 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11950 return 0;
11951
11952 if (ret == 0)
11953 rs->fs_pid = required_pid;
11954
11955 return ret;
11956}
11957
12e2a5fd 11958/* Implementation of to_fileio_open. */
a6b151f1 11959
6b8edb51
PA
11960int
11961remote_target::remote_hostio_open (inferior *inf, const char *filename,
11962 int flags, int mode, int warn_if_slow,
11963 int *remote_errno)
a6b151f1
DJ
11964{
11965 struct remote_state *rs = get_remote_state ();
11966 char *p = rs->buf;
11967 int left = get_remote_packet_size () - 1;
11968
4313b8c0
GB
11969 if (warn_if_slow)
11970 {
11971 static int warning_issued = 0;
11972
11973 printf_unfiltered (_("Reading %s from remote target...\n"),
11974 filename);
11975
11976 if (!warning_issued)
11977 {
11978 warning (_("File transfers from remote targets can be slow."
11979 " Use \"set sysroot\" to access files locally"
11980 " instead."));
11981 warning_issued = 1;
11982 }
11983 }
11984
15a201c8
GB
11985 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11986 return -1;
11987
a6b151f1
DJ
11988 remote_buffer_add_string (&p, &left, "vFile:open:");
11989
11990 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11991 strlen (filename));
11992 remote_buffer_add_string (&p, &left, ",");
11993
11994 remote_buffer_add_int (&p, &left, flags);
11995 remote_buffer_add_string (&p, &left, ",");
11996
11997 remote_buffer_add_int (&p, &left, mode);
11998
11999 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
12000 remote_errno, NULL, NULL);
12001}
12002
f6ac5f3d
PA
12003int
12004remote_target::fileio_open (struct inferior *inf, const char *filename,
12005 int flags, int mode, int warn_if_slow,
12006 int *remote_errno)
12007{
6b8edb51 12008 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
f6ac5f3d
PA
12009 remote_errno);
12010}
12011
12e2a5fd 12012/* Implementation of to_fileio_pwrite. */
a6b151f1 12013
6b8edb51
PA
12014int
12015remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12016 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
12017{
12018 struct remote_state *rs = get_remote_state ();
12019 char *p = rs->buf;
12020 int left = get_remote_packet_size ();
12021 int out_len;
12022
dd194f6b 12023 rs->readahead_cache.invalidate_fd (fd);
80152258 12024
a6b151f1
DJ
12025 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12026
12027 remote_buffer_add_int (&p, &left, fd);
12028 remote_buffer_add_string (&p, &left, ",");
12029
12030 remote_buffer_add_int (&p, &left, offset);
12031 remote_buffer_add_string (&p, &left, ",");
12032
124e13d9 12033 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
12034 get_remote_packet_size () - (p - rs->buf));
12035
12036 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
12037 remote_errno, NULL, NULL);
12038}
12039
f6ac5f3d
PA
12040int
12041remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12042 ULONGEST offset, int *remote_errno)
12043{
6b8edb51 12044 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
f6ac5f3d
PA
12045}
12046
80152258
PA
12047/* Helper for the implementation of to_fileio_pread. Read the file
12048 from the remote side with vFile:pread. */
a6b151f1 12049
6b8edb51
PA
12050int
12051remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12052 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
12053{
12054 struct remote_state *rs = get_remote_state ();
12055 char *p = rs->buf;
12056 char *attachment;
12057 int left = get_remote_packet_size ();
12058 int ret, attachment_len;
12059 int read_len;
12060
12061 remote_buffer_add_string (&p, &left, "vFile:pread:");
12062
12063 remote_buffer_add_int (&p, &left, fd);
12064 remote_buffer_add_string (&p, &left, ",");
12065
12066 remote_buffer_add_int (&p, &left, len);
12067 remote_buffer_add_string (&p, &left, ",");
12068
12069 remote_buffer_add_int (&p, &left, offset);
12070
12071 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
12072 remote_errno, &attachment,
12073 &attachment_len);
12074
12075 if (ret < 0)
12076 return ret;
12077
bc20a4af 12078 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
12079 read_buf, len);
12080 if (read_len != ret)
12081 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12082
12083 return ret;
12084}
12085
dd194f6b 12086/* See declaration.h. */
80152258 12087
dd194f6b
PA
12088int
12089readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12090 ULONGEST offset)
80152258 12091{
dd194f6b
PA
12092 if (this->fd == fd
12093 && this->offset <= offset
12094 && offset < this->offset + this->bufsize)
80152258 12095 {
dd194f6b 12096 ULONGEST max = this->offset + this->bufsize;
80152258
PA
12097
12098 if (offset + len > max)
12099 len = max - offset;
12100
dd194f6b 12101 memcpy (read_buf, this->buf + offset - this->offset, len);
80152258
PA
12102 return len;
12103 }
12104
12105 return 0;
12106}
12107
12108/* Implementation of to_fileio_pread. */
12109
6b8edb51
PA
12110int
12111remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12112 ULONGEST offset, int *remote_errno)
80152258
PA
12113{
12114 int ret;
12115 struct remote_state *rs = get_remote_state ();
dd194f6b 12116 readahead_cache *cache = &rs->readahead_cache;
80152258 12117
dd194f6b 12118 ret = cache->pread (fd, read_buf, len, offset);
80152258
PA
12119 if (ret > 0)
12120 {
12121 cache->hit_count++;
12122
12123 if (remote_debug)
12124 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
12125 pulongest (cache->hit_count));
12126 return ret;
12127 }
12128
12129 cache->miss_count++;
12130 if (remote_debug)
12131 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
12132 pulongest (cache->miss_count));
12133
12134 cache->fd = fd;
12135 cache->offset = offset;
12136 cache->bufsize = get_remote_packet_size ();
224c3ddb 12137 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258 12138
6b8edb51 12139 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
80152258
PA
12140 cache->offset, remote_errno);
12141 if (ret <= 0)
12142 {
dd194f6b 12143 cache->invalidate_fd (fd);
80152258
PA
12144 return ret;
12145 }
12146
12147 cache->bufsize = ret;
dd194f6b 12148 return cache->pread (fd, read_buf, len, offset);
80152258
PA
12149}
12150
f6ac5f3d
PA
12151int
12152remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12153 ULONGEST offset, int *remote_errno)
12154{
6b8edb51 12155 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
f6ac5f3d
PA
12156}
12157
12e2a5fd 12158/* Implementation of to_fileio_close. */
a6b151f1 12159
6b8edb51
PA
12160int
12161remote_target::remote_hostio_close (int fd, int *remote_errno)
a6b151f1
DJ
12162{
12163 struct remote_state *rs = get_remote_state ();
12164 char *p = rs->buf;
12165 int left = get_remote_packet_size () - 1;
12166
dd194f6b 12167 rs->readahead_cache.invalidate_fd (fd);
80152258 12168
a6b151f1
DJ
12169 remote_buffer_add_string (&p, &left, "vFile:close:");
12170
12171 remote_buffer_add_int (&p, &left, fd);
12172
12173 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
12174 remote_errno, NULL, NULL);
12175}
12176
f6ac5f3d
PA
12177int
12178remote_target::fileio_close (int fd, int *remote_errno)
12179{
6b8edb51 12180 return remote_hostio_close (fd, remote_errno);
f6ac5f3d
PA
12181}
12182
12e2a5fd 12183/* Implementation of to_fileio_unlink. */
a6b151f1 12184
6b8edb51
PA
12185int
12186remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12187 int *remote_errno)
a6b151f1
DJ
12188{
12189 struct remote_state *rs = get_remote_state ();
12190 char *p = rs->buf;
12191 int left = get_remote_packet_size () - 1;
12192
15a201c8
GB
12193 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12194 return -1;
12195
a6b151f1
DJ
12196 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12197
12198 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12199 strlen (filename));
12200
12201 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
12202 remote_errno, NULL, NULL);
12203}
12204
f6ac5f3d
PA
12205int
12206remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12207 int *remote_errno)
12208{
6b8edb51 12209 return remote_hostio_unlink (inf, filename, remote_errno);
f6ac5f3d
PA
12210}
12211
12e2a5fd 12212/* Implementation of to_fileio_readlink. */
b9e7b9c3 12213
f6ac5f3d
PA
12214gdb::optional<std::string>
12215remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12216 int *remote_errno)
b9e7b9c3
UW
12217{
12218 struct remote_state *rs = get_remote_state ();
12219 char *p = rs->buf;
12220 char *attachment;
12221 int left = get_remote_packet_size ();
12222 int len, attachment_len;
12223 int read_len;
b9e7b9c3 12224
15a201c8 12225 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
e0d3522b 12226 return {};
15a201c8 12227
b9e7b9c3
UW
12228 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12229
12230 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12231 strlen (filename));
12232
12233 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12234 remote_errno, &attachment,
12235 &attachment_len);
12236
12237 if (len < 0)
e0d3522b 12238 return {};
b9e7b9c3 12239
e0d3522b 12240 std::string ret (len, '\0');
b9e7b9c3 12241
bc20a4af 12242 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
e0d3522b 12243 (gdb_byte *) &ret[0], len);
b9e7b9c3
UW
12244 if (read_len != len)
12245 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12246
b9e7b9c3
UW
12247 return ret;
12248}
12249
12e2a5fd 12250/* Implementation of to_fileio_fstat. */
0a93529c 12251
f6ac5f3d
PA
12252int
12253remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
0a93529c
GB
12254{
12255 struct remote_state *rs = get_remote_state ();
12256 char *p = rs->buf;
12257 int left = get_remote_packet_size ();
12258 int attachment_len, ret;
12259 char *attachment;
12260 struct fio_stat fst;
12261 int read_len;
12262
464b0089
GB
12263 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12264
12265 remote_buffer_add_int (&p, &left, fd);
12266
12267 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12268 remote_errno, &attachment,
12269 &attachment_len);
12270 if (ret < 0)
0a93529c 12271 {
464b0089
GB
12272 if (*remote_errno != FILEIO_ENOSYS)
12273 return ret;
12274
0a93529c
GB
12275 /* Strictly we should return -1, ENOSYS here, but when
12276 "set sysroot remote:" was implemented in August 2008
12277 BFD's need for a stat function was sidestepped with
12278 this hack. This was not remedied until March 2015
12279 so we retain the previous behavior to avoid breaking
12280 compatibility.
12281
12282 Note that the memset is a March 2015 addition; older
12283 GDBs set st_size *and nothing else* so the structure
12284 would have garbage in all other fields. This might
12285 break something but retaining the previous behavior
12286 here would be just too wrong. */
12287
12288 memset (st, 0, sizeof (struct stat));
12289 st->st_size = INT_MAX;
12290 return 0;
12291 }
12292
0a93529c
GB
12293 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12294 (gdb_byte *) &fst, sizeof (fst));
12295
12296 if (read_len != ret)
12297 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12298
12299 if (read_len != sizeof (fst))
12300 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12301 read_len, (int) sizeof (fst));
12302
12303 remote_fileio_to_host_stat (&fst, st);
12304
12305 return 0;
12306}
12307
12e2a5fd 12308/* Implementation of to_filesystem_is_local. */
e3dd7556 12309
57810aa7 12310bool
f6ac5f3d 12311remote_target::filesystem_is_local ()
e3dd7556
GB
12312{
12313 /* Valgrind GDB presents itself as a remote target but works
12314 on the local filesystem: it does not implement remote get
12315 and users are not expected to set a sysroot. To handle
12316 this case we treat the remote filesystem as local if the
12317 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12318 does not support vFile:open. */
a3be80c3 12319 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
12320 {
12321 enum packet_support ps = packet_support (PACKET_vFile_open);
12322
12323 if (ps == PACKET_SUPPORT_UNKNOWN)
12324 {
12325 int fd, remote_errno;
12326
12327 /* Try opening a file to probe support. The supplied
12328 filename is irrelevant, we only care about whether
12329 the stub recognizes the packet or not. */
6b8edb51 12330 fd = remote_hostio_open (NULL, "just probing",
4313b8c0 12331 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
12332 &remote_errno);
12333
12334 if (fd >= 0)
6b8edb51 12335 remote_hostio_close (fd, &remote_errno);
e3dd7556
GB
12336
12337 ps = packet_support (PACKET_vFile_open);
12338 }
12339
12340 if (ps == PACKET_DISABLE)
12341 {
12342 static int warning_issued = 0;
12343
12344 if (!warning_issued)
12345 {
12346 warning (_("remote target does not support file"
12347 " transfer, attempting to access files"
12348 " from local filesystem."));
12349 warning_issued = 1;
12350 }
12351
57810aa7 12352 return true;
e3dd7556
GB
12353 }
12354 }
12355
57810aa7 12356 return false;
e3dd7556
GB
12357}
12358
a6b151f1
DJ
12359static int
12360remote_fileio_errno_to_host (int errnum)
12361{
12362 switch (errnum)
12363 {
12364 case FILEIO_EPERM:
12365 return EPERM;
12366 case FILEIO_ENOENT:
12367 return ENOENT;
12368 case FILEIO_EINTR:
12369 return EINTR;
12370 case FILEIO_EIO:
12371 return EIO;
12372 case FILEIO_EBADF:
12373 return EBADF;
12374 case FILEIO_EACCES:
12375 return EACCES;
12376 case FILEIO_EFAULT:
12377 return EFAULT;
12378 case FILEIO_EBUSY:
12379 return EBUSY;
12380 case FILEIO_EEXIST:
12381 return EEXIST;
12382 case FILEIO_ENODEV:
12383 return ENODEV;
12384 case FILEIO_ENOTDIR:
12385 return ENOTDIR;
12386 case FILEIO_EISDIR:
12387 return EISDIR;
12388 case FILEIO_EINVAL:
12389 return EINVAL;
12390 case FILEIO_ENFILE:
12391 return ENFILE;
12392 case FILEIO_EMFILE:
12393 return EMFILE;
12394 case FILEIO_EFBIG:
12395 return EFBIG;
12396 case FILEIO_ENOSPC:
12397 return ENOSPC;
12398 case FILEIO_ESPIPE:
12399 return ESPIPE;
12400 case FILEIO_EROFS:
12401 return EROFS;
12402 case FILEIO_ENOSYS:
12403 return ENOSYS;
12404 case FILEIO_ENAMETOOLONG:
12405 return ENAMETOOLONG;
12406 }
12407 return -1;
12408}
12409
12410static char *
12411remote_hostio_error (int errnum)
12412{
12413 int host_error = remote_fileio_errno_to_host (errnum);
12414
12415 if (host_error == -1)
12416 error (_("Unknown remote I/O error %d"), errnum);
12417 else
12418 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12419}
12420
440b7aec
PA
12421/* A RAII wrapper around a remote file descriptor. */
12422
12423class scoped_remote_fd
a6b151f1 12424{
440b7aec 12425public:
6b8edb51
PA
12426 scoped_remote_fd (remote_target *remote, int fd)
12427 : m_remote (remote), m_fd (fd)
440b7aec
PA
12428 {
12429 }
a6b151f1 12430
440b7aec
PA
12431 ~scoped_remote_fd ()
12432 {
12433 if (m_fd != -1)
12434 {
12435 try
12436 {
12437 int remote_errno;
6b8edb51 12438 m_remote->remote_hostio_close (m_fd, &remote_errno);
440b7aec
PA
12439 }
12440 catch (...)
12441 {
12442 /* Swallow exception before it escapes the dtor. If
12443 something goes wrong, likely the connection is gone,
12444 and there's nothing else that can be done. */
12445 }
12446 }
12447 }
12448
12449 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12450
12451 /* Release ownership of the file descriptor, and return it. */
12452 int release () noexcept
12453 {
12454 int fd = m_fd;
12455 m_fd = -1;
12456 return fd;
12457 }
12458
12459 /* Return the owned file descriptor. */
12460 int get () const noexcept
12461 {
12462 return m_fd;
12463 }
12464
12465private:
6b8edb51
PA
12466 /* The remote target. */
12467 remote_target *m_remote;
12468
440b7aec
PA
12469 /* The owned remote I/O file descriptor. */
12470 int m_fd;
12471};
a6b151f1
DJ
12472
12473void
12474remote_file_put (const char *local_file, const char *remote_file, int from_tty)
6b8edb51
PA
12475{
12476 remote_target *remote = get_current_remote_target ();
12477
12478 if (remote == nullptr)
12479 error (_("command can only be used with remote target"));
12480
12481 remote->remote_file_put (local_file, remote_file, from_tty);
12482}
12483
12484void
12485remote_target::remote_file_put (const char *local_file, const char *remote_file,
12486 int from_tty)
a6b151f1 12487{
440b7aec 12488 int retcode, remote_errno, bytes, io_size;
a6b151f1
DJ
12489 int bytes_in_buffer;
12490 int saw_eof;
12491 ULONGEST offset;
a6b151f1 12492
d419f42d 12493 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
12494 if (file == NULL)
12495 perror_with_name (local_file);
a6b151f1 12496
440b7aec 12497 scoped_remote_fd fd
6b8edb51
PA
12498 (this, remote_hostio_open (NULL,
12499 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12500 | FILEIO_O_TRUNC),
12501 0700, 0, &remote_errno));
440b7aec 12502 if (fd.get () == -1)
a6b151f1
DJ
12503 remote_hostio_error (remote_errno);
12504
12505 /* Send up to this many bytes at once. They won't all fit in the
12506 remote packet limit, so we'll transfer slightly fewer. */
12507 io_size = get_remote_packet_size ();
5ca3b260 12508 gdb::byte_vector buffer (io_size);
a6b151f1 12509
a6b151f1
DJ
12510 bytes_in_buffer = 0;
12511 saw_eof = 0;
12512 offset = 0;
12513 while (bytes_in_buffer || !saw_eof)
12514 {
12515 if (!saw_eof)
12516 {
5ca3b260 12517 bytes = fread (buffer.data () + bytes_in_buffer, 1,
3e43a32a 12518 io_size - bytes_in_buffer,
d419f42d 12519 file.get ());
a6b151f1
DJ
12520 if (bytes == 0)
12521 {
d419f42d 12522 if (ferror (file.get ()))
a6b151f1
DJ
12523 error (_("Error reading %s."), local_file);
12524 else
12525 {
12526 /* EOF. Unless there is something still in the
12527 buffer from the last iteration, we are done. */
12528 saw_eof = 1;
12529 if (bytes_in_buffer == 0)
12530 break;
12531 }
12532 }
12533 }
12534 else
12535 bytes = 0;
12536
12537 bytes += bytes_in_buffer;
12538 bytes_in_buffer = 0;
12539
5ca3b260 12540 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
3e43a32a 12541 offset, &remote_errno);
a6b151f1
DJ
12542
12543 if (retcode < 0)
12544 remote_hostio_error (remote_errno);
12545 else if (retcode == 0)
12546 error (_("Remote write of %d bytes returned 0!"), bytes);
12547 else if (retcode < bytes)
12548 {
12549 /* Short write. Save the rest of the read data for the next
12550 write. */
12551 bytes_in_buffer = bytes - retcode;
5ca3b260 12552 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
a6b151f1
DJ
12553 }
12554
12555 offset += retcode;
12556 }
12557
6b8edb51 12558 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
12559 remote_hostio_error (remote_errno);
12560
12561 if (from_tty)
12562 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
a6b151f1
DJ
12563}
12564
12565void
12566remote_file_get (const char *remote_file, const char *local_file, int from_tty)
6b8edb51
PA
12567{
12568 remote_target *remote = get_current_remote_target ();
12569
12570 if (remote == nullptr)
12571 error (_("command can only be used with remote target"));
12572
12573 remote->remote_file_get (remote_file, local_file, from_tty);
12574}
12575
12576void
12577remote_target::remote_file_get (const char *remote_file, const char *local_file,
12578 int from_tty)
a6b151f1 12579{
440b7aec 12580 int remote_errno, bytes, io_size;
a6b151f1 12581 ULONGEST offset;
a6b151f1 12582
440b7aec 12583 scoped_remote_fd fd
6b8edb51
PA
12584 (this, remote_hostio_open (NULL,
12585 remote_file, FILEIO_O_RDONLY, 0, 0,
12586 &remote_errno));
440b7aec 12587 if (fd.get () == -1)
a6b151f1
DJ
12588 remote_hostio_error (remote_errno);
12589
d419f42d 12590 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
12591 if (file == NULL)
12592 perror_with_name (local_file);
a6b151f1
DJ
12593
12594 /* Send up to this many bytes at once. They won't all fit in the
12595 remote packet limit, so we'll transfer slightly fewer. */
12596 io_size = get_remote_packet_size ();
5ca3b260 12597 gdb::byte_vector buffer (io_size);
a6b151f1 12598
a6b151f1
DJ
12599 offset = 0;
12600 while (1)
12601 {
5ca3b260 12602 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
440b7aec 12603 &remote_errno);
a6b151f1
DJ
12604 if (bytes == 0)
12605 /* Success, but no bytes, means end-of-file. */
12606 break;
12607 if (bytes == -1)
12608 remote_hostio_error (remote_errno);
12609
12610 offset += bytes;
12611
5ca3b260 12612 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
a6b151f1
DJ
12613 if (bytes == 0)
12614 perror_with_name (local_file);
12615 }
12616
6b8edb51 12617 if (remote_hostio_close (fd.release (), &remote_errno))
a6b151f1
DJ
12618 remote_hostio_error (remote_errno);
12619
12620 if (from_tty)
12621 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
a6b151f1
DJ
12622}
12623
12624void
12625remote_file_delete (const char *remote_file, int from_tty)
12626{
6b8edb51 12627 remote_target *remote = get_current_remote_target ();
a6b151f1 12628
6b8edb51 12629 if (remote == nullptr)
a6b151f1
DJ
12630 error (_("command can only be used with remote target"));
12631
6b8edb51
PA
12632 remote->remote_file_delete (remote_file, from_tty);
12633}
12634
12635void
12636remote_target::remote_file_delete (const char *remote_file, int from_tty)
12637{
12638 int retcode, remote_errno;
12639
12640 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
a6b151f1
DJ
12641 if (retcode == -1)
12642 remote_hostio_error (remote_errno);
12643
12644 if (from_tty)
12645 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12646}
12647
12648static void
ac88e2de 12649remote_put_command (const char *args, int from_tty)
a6b151f1 12650{
d1a41061
PP
12651 if (args == NULL)
12652 error_no_arg (_("file to put"));
12653
773a1edc 12654 gdb_argv argv (args);
a6b151f1
DJ
12655 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12656 error (_("Invalid parameters to remote put"));
12657
12658 remote_file_put (argv[0], argv[1], from_tty);
a6b151f1
DJ
12659}
12660
12661static void
ac88e2de 12662remote_get_command (const char *args, int from_tty)
a6b151f1 12663{
d1a41061
PP
12664 if (args == NULL)
12665 error_no_arg (_("file to get"));
12666
773a1edc 12667 gdb_argv argv (args);
a6b151f1
DJ
12668 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12669 error (_("Invalid parameters to remote get"));
12670
12671 remote_file_get (argv[0], argv[1], from_tty);
a6b151f1
DJ
12672}
12673
12674static void
ac88e2de 12675remote_delete_command (const char *args, int from_tty)
a6b151f1 12676{
d1a41061
PP
12677 if (args == NULL)
12678 error_no_arg (_("file to delete"));
12679
773a1edc 12680 gdb_argv argv (args);
a6b151f1
DJ
12681 if (argv[0] == NULL || argv[1] != NULL)
12682 error (_("Invalid parameters to remote delete"));
12683
12684 remote_file_delete (argv[0], from_tty);
a6b151f1
DJ
12685}
12686
12687static void
981a3fb3 12688remote_command (const char *args, int from_tty)
a6b151f1 12689{
635c7e8a 12690 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
12691}
12692
57810aa7 12693bool
f6ac5f3d 12694remote_target::can_execute_reverse ()
b2175913 12695{
4082afcc
PA
12696 if (packet_support (PACKET_bs) == PACKET_ENABLE
12697 || packet_support (PACKET_bc) == PACKET_ENABLE)
57810aa7 12698 return true;
40ab02ce 12699 else
57810aa7 12700 return false;
b2175913
MS
12701}
12702
57810aa7 12703bool
f6ac5f3d 12704remote_target::supports_non_stop ()
74531fed 12705{
57810aa7 12706 return true;
74531fed
PA
12707}
12708
57810aa7 12709bool
f6ac5f3d 12710remote_target::supports_disable_randomization ()
03583c20
UW
12711{
12712 /* Only supported in extended mode. */
57810aa7 12713 return false;
03583c20
UW
12714}
12715
57810aa7 12716bool
f6ac5f3d 12717remote_target::supports_multi_process ()
8a305172
PA
12718{
12719 struct remote_state *rs = get_remote_state ();
a744cf53 12720
8020350c 12721 return remote_multi_process_p (rs);
8a305172
PA
12722}
12723
70221824 12724static int
f6ac5f3d 12725remote_supports_cond_tracepoints ()
782b2b07 12726{
4082afcc 12727 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
12728}
12729
57810aa7 12730bool
f6ac5f3d 12731remote_target::supports_evaluation_of_breakpoint_conditions ()
3788aec7 12732{
4082afcc 12733 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
12734}
12735
70221824 12736static int
f6ac5f3d 12737remote_supports_fast_tracepoints ()
7a697b8d 12738{
4082afcc 12739 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
12740}
12741
0fb4aa4b 12742static int
f6ac5f3d 12743remote_supports_static_tracepoints ()
0fb4aa4b 12744{
4082afcc 12745 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
12746}
12747
1e4d1764 12748static int
f6ac5f3d 12749remote_supports_install_in_trace ()
1e4d1764 12750{
4082afcc 12751 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
12752}
12753
57810aa7 12754bool
f6ac5f3d 12755remote_target::supports_enable_disable_tracepoint ()
d248b706 12756{
4082afcc
PA
12757 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12758 == PACKET_ENABLE);
d248b706
KY
12759}
12760
57810aa7 12761bool
f6ac5f3d 12762remote_target::supports_string_tracing ()
3065dfb6 12763{
4082afcc 12764 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
12765}
12766
57810aa7 12767bool
f6ac5f3d 12768remote_target::can_run_breakpoint_commands ()
d3ce09f5 12769{
4082afcc 12770 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
12771}
12772
f6ac5f3d
PA
12773void
12774remote_target::trace_init ()
35b1e5cc 12775{
b6bb3468
PA
12776 struct remote_state *rs = get_remote_state ();
12777
35b1e5cc 12778 putpkt ("QTinit");
b6bb3468
PA
12779 remote_get_noisy_reply ();
12780 if (strcmp (rs->buf, "OK") != 0)
35b1e5cc
SS
12781 error (_("Target does not support this command."));
12782}
12783
409873ef
SS
12784/* Recursive routine to walk through command list including loops, and
12785 download packets for each command. */
12786
6b8edb51
PA
12787void
12788remote_target::remote_download_command_source (int num, ULONGEST addr,
12789 struct command_line *cmds)
409873ef
SS
12790{
12791 struct remote_state *rs = get_remote_state ();
12792 struct command_line *cmd;
12793
12794 for (cmd = cmds; cmd; cmd = cmd->next)
12795 {
0df8b418 12796 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
12797 strcpy (rs->buf, "QTDPsrc:");
12798 encode_source_string (num, addr, "cmd", cmd->line,
12799 rs->buf + strlen (rs->buf),
12800 rs->buf_size - strlen (rs->buf));
12801 putpkt (rs->buf);
b6bb3468
PA
12802 remote_get_noisy_reply ();
12803 if (strcmp (rs->buf, "OK"))
409873ef
SS
12804 warning (_("Target does not support source download."));
12805
12806 if (cmd->control_type == while_control
12807 || cmd->control_type == while_stepping_control)
12808 {
12973681 12809 remote_download_command_source (num, addr, cmd->body_list_0.get ());
409873ef 12810
0df8b418 12811 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
12812 strcpy (rs->buf, "QTDPsrc:");
12813 encode_source_string (num, addr, "cmd", "end",
12814 rs->buf + strlen (rs->buf),
12815 rs->buf_size - strlen (rs->buf));
12816 putpkt (rs->buf);
b6bb3468
PA
12817 remote_get_noisy_reply ();
12818 if (strcmp (rs->buf, "OK"))
409873ef
SS
12819 warning (_("Target does not support source download."));
12820 }
12821 }
12822}
12823
f6ac5f3d
PA
12824void
12825remote_target::download_tracepoint (struct bp_location *loc)
35b1e5cc 12826{
bba74b36 12827#define BUF_SIZE 2048
e8ba3115 12828
35b1e5cc 12829 CORE_ADDR tpaddr;
409873ef 12830 char addrbuf[40];
bba74b36 12831 char buf[BUF_SIZE];
b44ec619
SM
12832 std::vector<std::string> tdp_actions;
12833 std::vector<std::string> stepping_actions;
35b1e5cc 12834 char *pkt;
e8ba3115 12835 struct breakpoint *b = loc->owner;
d9b3f62e 12836 struct tracepoint *t = (struct tracepoint *) b;
b6bb3468 12837 struct remote_state *rs = get_remote_state ();
35b1e5cc 12838
dc673c81 12839 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
12840
12841 tpaddr = loc->address;
12842 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
12843 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12844 addrbuf, /* address */
12845 (b->enable_state == bp_enabled ? 'E' : 'D'),
12846 t->step_count, t->pass_count);
e8ba3115
YQ
12847 /* Fast tracepoints are mostly handled by the target, but we can
12848 tell the target how big of an instruction block should be moved
12849 around. */
12850 if (b->type == bp_fast_tracepoint)
12851 {
12852 /* Only test for support at download time; we may not know
12853 target capabilities at definition time. */
12854 if (remote_supports_fast_tracepoints ())
35b1e5cc 12855 {
6b940e6a
PL
12856 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12857 NULL))
bba74b36 12858 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 12859 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 12860 else
e8ba3115
YQ
12861 /* If it passed validation at definition but fails now,
12862 something is very wrong. */
12863 internal_error (__FILE__, __LINE__,
12864 _("Fast tracepoint not "
12865 "valid during download"));
35b1e5cc 12866 }
e8ba3115
YQ
12867 else
12868 /* Fast tracepoints are functionally identical to regular
12869 tracepoints, so don't take lack of support as a reason to
12870 give up on the trace run. */
12871 warning (_("Target does not support fast tracepoints, "
12872 "downloading %d as regular tracepoint"), b->number);
12873 }
12874 else if (b->type == bp_static_tracepoint)
12875 {
12876 /* Only test for support at download time; we may not know
12877 target capabilities at definition time. */
12878 if (remote_supports_static_tracepoints ())
0fb4aa4b 12879 {
e8ba3115 12880 struct static_tracepoint_marker marker;
0fb4aa4b 12881
e8ba3115
YQ
12882 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12883 strcat (buf, ":S");
0fb4aa4b 12884 else
e8ba3115 12885 error (_("Static tracepoint not valid during download"));
0fb4aa4b 12886 }
e8ba3115
YQ
12887 else
12888 /* Fast tracepoints are functionally identical to regular
12889 tracepoints, so don't take lack of support as a reason
12890 to give up on the trace run. */
12891 error (_("Target does not support static tracepoints"));
12892 }
12893 /* If the tracepoint has a conditional, make it into an agent
12894 expression and append to the definition. */
12895 if (loc->cond)
12896 {
12897 /* Only test support at download time, we may not know target
12898 capabilities at definition time. */
12899 if (remote_supports_cond_tracepoints ())
35b1e5cc 12900 {
833177a4 12901 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
bba74b36
YQ
12902 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12903 aexpr->len);
e8ba3115 12904 pkt = buf + strlen (buf);
b44ec619 12905 for (int ndx = 0; ndx < aexpr->len; ++ndx)
e8ba3115
YQ
12906 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12907 *pkt = '\0';
35b1e5cc 12908 }
e8ba3115
YQ
12909 else
12910 warning (_("Target does not support conditional tracepoints, "
12911 "ignoring tp %d cond"), b->number);
12912 }
35b1e5cc 12913
d9b3f62e 12914 if (b->commands || *default_collect)
e8ba3115
YQ
12915 strcat (buf, "-");
12916 putpkt (buf);
b6bb3468
PA
12917 remote_get_noisy_reply ();
12918 if (strcmp (rs->buf, "OK"))
e8ba3115 12919 error (_("Target does not support tracepoints."));
35b1e5cc 12920
e8ba3115 12921 /* do_single_steps (t); */
b44ec619
SM
12922 for (auto action_it = tdp_actions.begin ();
12923 action_it != tdp_actions.end (); action_it++)
e8ba3115 12924 {
b44ec619
SM
12925 QUIT; /* Allow user to bail out with ^C. */
12926
12927 bool has_more = (action_it != tdp_actions.end ()
12928 || !stepping_actions.empty ());
12929
12930 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12931 b->number, addrbuf, /* address */
12932 action_it->c_str (),
12933 has_more ? '-' : 0);
12934 putpkt (buf);
12935 remote_get_noisy_reply ();
12936 if (strcmp (rs->buf, "OK"))
12937 error (_("Error on target while setting tracepoints."));
e8ba3115 12938 }
409873ef 12939
b44ec619
SM
12940 for (auto action_it = stepping_actions.begin ();
12941 action_it != stepping_actions.end (); action_it++)
12942 {
12943 QUIT; /* Allow user to bail out with ^C. */
12944
12945 bool is_first = action_it == stepping_actions.begin ();
12946 bool has_more = action_it != stepping_actions.end ();
12947
12948 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12949 b->number, addrbuf, /* address */
12950 is_first ? "S" : "",
12951 action_it->c_str (),
12952 has_more ? "-" : "");
12953 putpkt (buf);
12954 remote_get_noisy_reply ();
12955 if (strcmp (rs->buf, "OK"))
12956 error (_("Error on target while setting tracepoints."));
12957 }
12958
4082afcc 12959 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 12960 {
f00aae0f 12961 if (b->location != NULL)
409873ef 12962 {
e8ba3115 12963 strcpy (buf, "QTDPsrc:");
f00aae0f 12964 encode_source_string (b->number, loc->address, "at",
d28cd78a 12965 event_location_to_string (b->location.get ()),
f00aae0f 12966 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115 12967 putpkt (buf);
b6bb3468
PA
12968 remote_get_noisy_reply ();
12969 if (strcmp (rs->buf, "OK"))
e8ba3115 12970 warning (_("Target does not support source download."));
409873ef 12971 }
e8ba3115
YQ
12972 if (b->cond_string)
12973 {
12974 strcpy (buf, "QTDPsrc:");
12975 encode_source_string (b->number, loc->address,
12976 "cond", b->cond_string, buf + strlen (buf),
12977 2048 - strlen (buf));
12978 putpkt (buf);
b6bb3468
PA
12979 remote_get_noisy_reply ();
12980 if (strcmp (rs->buf, "OK"))
e8ba3115
YQ
12981 warning (_("Target does not support source download."));
12982 }
12983 remote_download_command_source (b->number, loc->address,
12984 breakpoint_commands (b));
35b1e5cc 12985 }
35b1e5cc
SS
12986}
12987
57810aa7 12988bool
f6ac5f3d 12989remote_target::can_download_tracepoint ()
1e4d1764 12990{
1e51243a
PA
12991 struct remote_state *rs = get_remote_state ();
12992 struct trace_status *ts;
12993 int status;
12994
12995 /* Don't try to install tracepoints until we've relocated our
12996 symbols, and fetched and merged the target's tracepoint list with
12997 ours. */
12998 if (rs->starting_up)
57810aa7 12999 return false;
1e51243a
PA
13000
13001 ts = current_trace_status ();
f6ac5f3d 13002 status = get_trace_status (ts);
1e4d1764
YQ
13003
13004 if (status == -1 || !ts->running_known || !ts->running)
57810aa7 13005 return false;
1e4d1764
YQ
13006
13007 /* If we are in a tracing experiment, but remote stub doesn't support
13008 installing tracepoint in trace, we have to return. */
13009 if (!remote_supports_install_in_trace ())
57810aa7 13010 return false;
1e4d1764 13011
57810aa7 13012 return true;
1e4d1764
YQ
13013}
13014
13015
f6ac5f3d
PA
13016void
13017remote_target::download_trace_state_variable (const trace_state_variable &tsv)
35b1e5cc
SS
13018{
13019 struct remote_state *rs = get_remote_state ();
00bf0b85 13020 char *p;
35b1e5cc 13021
bba74b36 13022 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
c252925c
SM
13023 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13024 tsv.builtin);
00bf0b85 13025 p = rs->buf + strlen (rs->buf);
c252925c 13026 if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
00bf0b85 13027 error (_("Trace state variable name too long for tsv definition packet"));
c252925c 13028 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
00bf0b85 13029 *p++ = '\0';
35b1e5cc 13030 putpkt (rs->buf);
b6bb3468
PA
13031 remote_get_noisy_reply ();
13032 if (*rs->buf == '\0')
ad91cd99 13033 error (_("Target does not support this command."));
b6bb3468 13034 if (strcmp (rs->buf, "OK") != 0)
ad91cd99 13035 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
13036}
13037
f6ac5f3d
PA
13038void
13039remote_target::enable_tracepoint (struct bp_location *location)
d248b706
KY
13040{
13041 struct remote_state *rs = get_remote_state ();
13042 char addr_buf[40];
13043
13044 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
13045 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
13046 location->owner->number, addr_buf);
d248b706 13047 putpkt (rs->buf);
b6bb3468 13048 remote_get_noisy_reply ();
d248b706
KY
13049 if (*rs->buf == '\0')
13050 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13051 if (strcmp (rs->buf, "OK") != 0)
13052 error (_("Error on target while enabling tracepoint."));
13053}
13054
f6ac5f3d
PA
13055void
13056remote_target::disable_tracepoint (struct bp_location *location)
d248b706
KY
13057{
13058 struct remote_state *rs = get_remote_state ();
13059 char addr_buf[40];
13060
13061 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
13062 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
13063 location->owner->number, addr_buf);
d248b706 13064 putpkt (rs->buf);
b6bb3468 13065 remote_get_noisy_reply ();
d248b706
KY
13066 if (*rs->buf == '\0')
13067 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13068 if (strcmp (rs->buf, "OK") != 0)
13069 error (_("Error on target while disabling tracepoint."));
13070}
13071
f6ac5f3d
PA
13072void
13073remote_target::trace_set_readonly_regions ()
35b1e5cc
SS
13074{
13075 asection *s;
81b9b86e 13076 bfd *abfd = NULL;
35b1e5cc 13077 bfd_size_type size;
608bcef2 13078 bfd_vma vma;
35b1e5cc 13079 int anysecs = 0;
c2fa21f1 13080 int offset = 0;
35b1e5cc
SS
13081
13082 if (!exec_bfd)
13083 return; /* No information to give. */
13084
b6bb3468
PA
13085 struct remote_state *rs = get_remote_state ();
13086
13087 strcpy (rs->buf, "QTro");
13088 offset = strlen (rs->buf);
35b1e5cc
SS
13089 for (s = exec_bfd->sections; s; s = s->next)
13090 {
13091 char tmp1[40], tmp2[40];
c2fa21f1 13092 int sec_length;
35b1e5cc
SS
13093
13094 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 13095 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
13096 (s->flags & SEC_READONLY) == 0)
13097 continue;
13098
13099 anysecs = 1;
81b9b86e 13100 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 13101 size = bfd_get_section_size (s);
608bcef2
HZ
13102 sprintf_vma (tmp1, vma);
13103 sprintf_vma (tmp2, vma + size);
c2fa21f1 13104 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
b6bb3468 13105 if (offset + sec_length + 1 > rs->buf_size)
c2fa21f1 13106 {
4082afcc 13107 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 13108 warning (_("\
c2fa21f1
HZ
13109Too many sections for read-only sections definition packet."));
13110 break;
13111 }
b6bb3468 13112 xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
bba74b36 13113 tmp1, tmp2);
c2fa21f1 13114 offset += sec_length;
35b1e5cc
SS
13115 }
13116 if (anysecs)
13117 {
b6bb3468
PA
13118 putpkt (rs->buf);
13119 getpkt (&rs->buf, &rs->buf_size, 0);
35b1e5cc
SS
13120 }
13121}
13122
f6ac5f3d
PA
13123void
13124remote_target::trace_start ()
35b1e5cc 13125{
b6bb3468
PA
13126 struct remote_state *rs = get_remote_state ();
13127
35b1e5cc 13128 putpkt ("QTStart");
b6bb3468
PA
13129 remote_get_noisy_reply ();
13130 if (*rs->buf == '\0')
ad91cd99 13131 error (_("Target does not support this command."));
b6bb3468
PA
13132 if (strcmp (rs->buf, "OK") != 0)
13133 error (_("Bogus reply from target: %s"), rs->buf);
35b1e5cc
SS
13134}
13135
f6ac5f3d
PA
13136int
13137remote_target::get_trace_status (struct trace_status *ts)
35b1e5cc 13138{
953b98d1 13139 /* Initialize it just to avoid a GCC false warning. */
f652de6f 13140 char *p = NULL;
0df8b418 13141 /* FIXME we need to get register block size some other way. */
00bf0b85 13142 extern int trace_regblock_size;
bd3eecc3 13143 enum packet_result result;
b6bb3468 13144 struct remote_state *rs = get_remote_state ();
bd3eecc3 13145
4082afcc 13146 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 13147 return -1;
a744cf53 13148
5cd63fda 13149 trace_regblock_size
9d6eea31 13150 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
00bf0b85 13151
049dc89b
JK
13152 putpkt ("qTStatus");
13153
492d29ea 13154 TRY
67f41397 13155 {
b6bb3468 13156 p = remote_get_noisy_reply ();
67f41397 13157 }
492d29ea 13158 CATCH (ex, RETURN_MASK_ERROR)
67f41397 13159 {
598d3636
JK
13160 if (ex.error != TARGET_CLOSE_ERROR)
13161 {
13162 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13163 return -1;
13164 }
13165 throw_exception (ex);
67f41397 13166 }
492d29ea 13167 END_CATCH
00bf0b85 13168
bd3eecc3
PA
13169 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13170
00bf0b85 13171 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 13172 if (result == PACKET_UNKNOWN)
00bf0b85 13173 return -1;
35b1e5cc 13174
00bf0b85 13175 /* We're working with a live target. */
f5911ea1 13176 ts->filename = NULL;
00bf0b85 13177
00bf0b85 13178 if (*p++ != 'T')
b6bb3468 13179 error (_("Bogus trace status reply from target: %s"), rs->buf);
35b1e5cc 13180
84cebc4a
YQ
13181 /* Function 'parse_trace_status' sets default value of each field of
13182 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
13183 parse_trace_status (p, ts);
13184
13185 return ts->running;
35b1e5cc
SS
13186}
13187
f6ac5f3d
PA
13188void
13189remote_target::get_tracepoint_status (struct breakpoint *bp,
13190 struct uploaded_tp *utp)
f196051f
SS
13191{
13192 struct remote_state *rs = get_remote_state ();
f196051f
SS
13193 char *reply;
13194 struct bp_location *loc;
13195 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 13196 size_t size = get_remote_packet_size ();
f196051f
SS
13197
13198 if (tp)
13199 {
c1fc2657 13200 tp->hit_count = 0;
f196051f 13201 tp->traceframe_usage = 0;
c1fc2657 13202 for (loc = tp->loc; loc; loc = loc->next)
f196051f
SS
13203 {
13204 /* If the tracepoint was never downloaded, don't go asking for
13205 any status. */
13206 if (tp->number_on_target == 0)
13207 continue;
bba74b36
YQ
13208 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
13209 phex_nz (loc->address, 0));
f196051f 13210 putpkt (rs->buf);
b6bb3468 13211 reply = remote_get_noisy_reply ();
f196051f
SS
13212 if (reply && *reply)
13213 {
13214 if (*reply == 'V')
13215 parse_tracepoint_status (reply + 1, bp, utp);
13216 }
13217 }
13218 }
13219 else if (utp)
13220 {
13221 utp->hit_count = 0;
13222 utp->traceframe_usage = 0;
bba74b36
YQ
13223 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
13224 phex_nz (utp->addr, 0));
f196051f 13225 putpkt (rs->buf);
b6bb3468 13226 reply = remote_get_noisy_reply ();
f196051f
SS
13227 if (reply && *reply)
13228 {
13229 if (*reply == 'V')
13230 parse_tracepoint_status (reply + 1, bp, utp);
13231 }
13232 }
13233}
13234
f6ac5f3d
PA
13235void
13236remote_target::trace_stop ()
35b1e5cc 13237{
b6bb3468
PA
13238 struct remote_state *rs = get_remote_state ();
13239
35b1e5cc 13240 putpkt ("QTStop");
b6bb3468
PA
13241 remote_get_noisy_reply ();
13242 if (*rs->buf == '\0')
ad91cd99 13243 error (_("Target does not support this command."));
b6bb3468
PA
13244 if (strcmp (rs->buf, "OK") != 0)
13245 error (_("Bogus reply from target: %s"), rs->buf);
35b1e5cc
SS
13246}
13247
f6ac5f3d
PA
13248int
13249remote_target::trace_find (enum trace_find_type type, int num,
13250 CORE_ADDR addr1, CORE_ADDR addr2,
13251 int *tpp)
35b1e5cc
SS
13252{
13253 struct remote_state *rs = get_remote_state ();
bba74b36 13254 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
13255 char *p, *reply;
13256 int target_frameno = -1, target_tracept = -1;
13257
e6e4e701
PA
13258 /* Lookups other than by absolute frame number depend on the current
13259 trace selected, so make sure it is correct on the remote end
13260 first. */
13261 if (type != tfind_number)
13262 set_remote_traceframe ();
13263
35b1e5cc
SS
13264 p = rs->buf;
13265 strcpy (p, "QTFrame:");
13266 p = strchr (p, '\0');
13267 switch (type)
13268 {
13269 case tfind_number:
bba74b36 13270 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
13271 break;
13272 case tfind_pc:
bba74b36 13273 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
13274 break;
13275 case tfind_tp:
bba74b36 13276 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
13277 break;
13278 case tfind_range:
bba74b36
YQ
13279 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13280 phex_nz (addr2, 0));
35b1e5cc
SS
13281 break;
13282 case tfind_outside:
bba74b36
YQ
13283 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13284 phex_nz (addr2, 0));
35b1e5cc
SS
13285 break;
13286 default:
9b20d036 13287 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
13288 }
13289
13290 putpkt (rs->buf);
b6bb3468 13291 reply = remote_get_noisy_reply ();
ad91cd99
PA
13292 if (*reply == '\0')
13293 error (_("Target does not support this command."));
35b1e5cc
SS
13294
13295 while (reply && *reply)
13296 switch (*reply)
13297 {
13298 case 'F':
f197e0f1
VP
13299 p = ++reply;
13300 target_frameno = (int) strtol (p, &reply, 16);
13301 if (reply == p)
13302 error (_("Unable to parse trace frame number"));
e6e4e701
PA
13303 /* Don't update our remote traceframe number cache on failure
13304 to select a remote traceframe. */
f197e0f1
VP
13305 if (target_frameno == -1)
13306 return -1;
35b1e5cc
SS
13307 break;
13308 case 'T':
f197e0f1
VP
13309 p = ++reply;
13310 target_tracept = (int) strtol (p, &reply, 16);
13311 if (reply == p)
13312 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
13313 break;
13314 case 'O': /* "OK"? */
13315 if (reply[1] == 'K' && reply[2] == '\0')
13316 reply += 2;
13317 else
13318 error (_("Bogus reply from target: %s"), reply);
13319 break;
13320 default:
13321 error (_("Bogus reply from target: %s"), reply);
13322 }
13323 if (tpp)
13324 *tpp = target_tracept;
e6e4e701 13325
262e1174 13326 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
13327 return target_frameno;
13328}
13329
57810aa7 13330bool
f6ac5f3d 13331remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
35b1e5cc
SS
13332{
13333 struct remote_state *rs = get_remote_state ();
13334 char *reply;
13335 ULONGEST uval;
13336
e6e4e701
PA
13337 set_remote_traceframe ();
13338
bba74b36 13339 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc 13340 putpkt (rs->buf);
b6bb3468 13341 reply = remote_get_noisy_reply ();
35b1e5cc
SS
13342 if (reply && *reply)
13343 {
13344 if (*reply == 'V')
13345 {
13346 unpack_varlen_hex (reply + 1, &uval);
13347 *val = (LONGEST) uval;
57810aa7 13348 return true;
35b1e5cc
SS
13349 }
13350 }
57810aa7 13351 return false;
35b1e5cc
SS
13352}
13353
f6ac5f3d
PA
13354int
13355remote_target::save_trace_data (const char *filename)
00bf0b85
SS
13356{
13357 struct remote_state *rs = get_remote_state ();
13358 char *p, *reply;
13359
13360 p = rs->buf;
13361 strcpy (p, "QTSave:");
13362 p += strlen (p);
13363 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13364 error (_("Remote file name too long for trace save packet"));
9f1b45b0 13365 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
13366 *p++ = '\0';
13367 putpkt (rs->buf);
b6bb3468 13368 reply = remote_get_noisy_reply ();
d6c5869f 13369 if (*reply == '\0')
ad91cd99
PA
13370 error (_("Target does not support this command."));
13371 if (strcmp (reply, "OK") != 0)
13372 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
13373 return 0;
13374}
13375
13376/* This is basically a memory transfer, but needs to be its own packet
13377 because we don't know how the target actually organizes its trace
13378 memory, plus we want to be able to ask for as much as possible, but
13379 not be unhappy if we don't get as much as we ask for. */
13380
f6ac5f3d
PA
13381LONGEST
13382remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
13383{
13384 struct remote_state *rs = get_remote_state ();
13385 char *reply;
13386 char *p;
13387 int rslt;
13388
13389 p = rs->buf;
13390 strcpy (p, "qTBuffer:");
13391 p += strlen (p);
13392 p += hexnumstr (p, offset);
13393 *p++ = ',';
13394 p += hexnumstr (p, len);
13395 *p++ = '\0';
13396
13397 putpkt (rs->buf);
b6bb3468 13398 reply = remote_get_noisy_reply ();
00bf0b85
SS
13399 if (reply && *reply)
13400 {
13401 /* 'l' by itself means we're at the end of the buffer and
13402 there is nothing more to get. */
13403 if (*reply == 'l')
13404 return 0;
13405
13406 /* Convert the reply into binary. Limit the number of bytes to
13407 convert according to our passed-in buffer size, rather than
13408 what was returned in the packet; if the target is
13409 unexpectedly generous and gives us a bigger reply than we
13410 asked for, we don't want to crash. */
b6bb3468 13411 rslt = hex2bin (reply, buf, len);
00bf0b85
SS
13412 return rslt;
13413 }
13414
13415 /* Something went wrong, flag as an error. */
13416 return -1;
13417}
13418
f6ac5f3d
PA
13419void
13420remote_target::set_disconnected_tracing (int val)
35b1e5cc
SS
13421{
13422 struct remote_state *rs = get_remote_state ();
13423
4082afcc 13424 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 13425 {
ad91cd99
PA
13426 char *reply;
13427
bba74b36 13428 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 13429 putpkt (rs->buf);
b6bb3468 13430 reply = remote_get_noisy_reply ();
ad91cd99 13431 if (*reply == '\0')
33da3f1c 13432 error (_("Target does not support this command."));
ad91cd99
PA
13433 if (strcmp (reply, "OK") != 0)
13434 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
13435 }
13436 else if (val)
13437 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
13438}
13439
f6ac5f3d
PA
13440int
13441remote_target::core_of_thread (ptid_t ptid)
dc146f7c
VP
13442{
13443 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 13444
7aabaf9d
SM
13445 if (info != NULL && info->priv != NULL)
13446 return get_remote_thread_info (info)->core;
13447
dc146f7c
VP
13448 return -1;
13449}
13450
f6ac5f3d
PA
13451void
13452remote_target::set_circular_trace_buffer (int val)
4daf5ac0
SS
13453{
13454 struct remote_state *rs = get_remote_state ();
ad91cd99 13455 char *reply;
4daf5ac0 13456
bba74b36 13457 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 13458 putpkt (rs->buf);
b6bb3468 13459 reply = remote_get_noisy_reply ();
ad91cd99 13460 if (*reply == '\0')
4daf5ac0 13461 error (_("Target does not support this command."));
ad91cd99
PA
13462 if (strcmp (reply, "OK") != 0)
13463 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
13464}
13465
f6ac5f3d
PA
13466traceframe_info_up
13467remote_target::traceframe_info ()
b3b9301e 13468{
9018be22 13469 gdb::optional<gdb::char_vector> text
8b88a78e 13470 = target_read_stralloc (current_top_target (), TARGET_OBJECT_TRACEFRAME_INFO,
b7b030ad 13471 NULL);
9018be22
SM
13472 if (text)
13473 return parse_traceframe_info (text->data ());
b3b9301e
PA
13474
13475 return NULL;
13476}
13477
405f8e94
SS
13478/* Handle the qTMinFTPILen packet. Returns the minimum length of
13479 instruction on which a fast tracepoint may be placed. Returns -1
13480 if the packet is not supported, and 0 if the minimum instruction
13481 length is unknown. */
13482
f6ac5f3d
PA
13483int
13484remote_target::get_min_fast_tracepoint_insn_len ()
405f8e94
SS
13485{
13486 struct remote_state *rs = get_remote_state ();
13487 char *reply;
13488
e886a173
PA
13489 /* If we're not debugging a process yet, the IPA can't be
13490 loaded. */
13491 if (!target_has_execution)
13492 return 0;
13493
13494 /* Make sure the remote is pointing at the right process. */
13495 set_general_process ();
13496
bba74b36 13497 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94 13498 putpkt (rs->buf);
b6bb3468 13499 reply = remote_get_noisy_reply ();
405f8e94
SS
13500 if (*reply == '\0')
13501 return -1;
13502 else
13503 {
13504 ULONGEST min_insn_len;
13505
13506 unpack_varlen_hex (reply, &min_insn_len);
13507
13508 return (int) min_insn_len;
13509 }
13510}
13511
f6ac5f3d
PA
13512void
13513remote_target::set_trace_buffer_size (LONGEST val)
f6f899bf 13514{
4082afcc 13515 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
13516 {
13517 struct remote_state *rs = get_remote_state ();
13518 char *buf = rs->buf;
13519 char *endbuf = rs->buf + get_remote_packet_size ();
13520 enum packet_result result;
13521
13522 gdb_assert (val >= 0 || val == -1);
13523 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13524 /* Send -1 as literal "-1" to avoid host size dependency. */
13525 if (val < 0)
13526 {
13527 *buf++ = '-';
13528 buf += hexnumstr (buf, (ULONGEST) -val);
13529 }
13530 else
13531 buf += hexnumstr (buf, (ULONGEST) val);
13532
13533 putpkt (rs->buf);
b6bb3468 13534 remote_get_noisy_reply ();
f6f899bf
HAQ
13535 result = packet_ok (rs->buf,
13536 &remote_protocol_packets[PACKET_QTBuffer_size]);
13537
13538 if (result != PACKET_OK)
13539 warning (_("Bogus reply from target: %s"), rs->buf);
13540 }
13541}
13542
57810aa7 13543bool
f6ac5f3d
PA
13544remote_target::set_trace_notes (const char *user, const char *notes,
13545 const char *stop_notes)
f196051f
SS
13546{
13547 struct remote_state *rs = get_remote_state ();
13548 char *reply;
13549 char *buf = rs->buf;
13550 char *endbuf = rs->buf + get_remote_packet_size ();
13551 int nbytes;
13552
13553 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13554 if (user)
13555 {
13556 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 13557 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
13558 buf += 2 * nbytes;
13559 *buf++ = ';';
13560 }
13561 if (notes)
13562 {
13563 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 13564 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
13565 buf += 2 * nbytes;
13566 *buf++ = ';';
13567 }
13568 if (stop_notes)
13569 {
13570 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 13571 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
13572 buf += 2 * nbytes;
13573 *buf++ = ';';
13574 }
13575 /* Ensure the buffer is terminated. */
13576 *buf = '\0';
13577
13578 putpkt (rs->buf);
b6bb3468 13579 reply = remote_get_noisy_reply ();
f196051f 13580 if (*reply == '\0')
57810aa7 13581 return false;
f196051f
SS
13582
13583 if (strcmp (reply, "OK") != 0)
13584 error (_("Bogus reply from target: %s"), reply);
13585
57810aa7 13586 return true;
f196051f
SS
13587}
13588
57810aa7
PA
13589bool
13590remote_target::use_agent (bool use)
d1feda86 13591{
4082afcc 13592 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
13593 {
13594 struct remote_state *rs = get_remote_state ();
13595
13596 /* If the stub supports QAgent. */
bba74b36 13597 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
13598 putpkt (rs->buf);
13599 getpkt (&rs->buf, &rs->buf_size, 0);
13600
13601 if (strcmp (rs->buf, "OK") == 0)
13602 {
f6ac5f3d 13603 ::use_agent = use;
57810aa7 13604 return true;
d1feda86
YQ
13605 }
13606 }
13607
57810aa7 13608 return false;
d1feda86
YQ
13609}
13610
57810aa7 13611bool
f6ac5f3d 13612remote_target::can_use_agent ()
d1feda86 13613{
4082afcc 13614 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
13615}
13616
9accd112
MM
13617struct btrace_target_info
13618{
13619 /* The ptid of the traced thread. */
13620 ptid_t ptid;
f4abbc16
MM
13621
13622 /* The obtained branch trace configuration. */
13623 struct btrace_config conf;
9accd112
MM
13624};
13625
f4abbc16
MM
13626/* Reset our idea of our target's btrace configuration. */
13627
13628static void
6b8edb51 13629remote_btrace_reset (remote_state *rs)
f4abbc16 13630{
f4abbc16
MM
13631 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13632}
13633
f4abbc16
MM
13634/* Synchronize the configuration with the target. */
13635
6b8edb51
PA
13636void
13637remote_target::btrace_sync_conf (const btrace_config *conf)
f4abbc16 13638{
d33501a5
MM
13639 struct packet_config *packet;
13640 struct remote_state *rs;
13641 char *buf, *pos, *endbuf;
13642
13643 rs = get_remote_state ();
13644 buf = rs->buf;
13645 endbuf = buf + get_remote_packet_size ();
13646
13647 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13648 if (packet_config_support (packet) == PACKET_ENABLE
13649 && conf->bts.size != rs->btrace_config.bts.size)
13650 {
13651 pos = buf;
13652 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13653 conf->bts.size);
13654
13655 putpkt (buf);
13656 getpkt (&buf, &rs->buf_size, 0);
13657
13658 if (packet_ok (buf, packet) == PACKET_ERROR)
13659 {
13660 if (buf[0] == 'E' && buf[1] == '.')
13661 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13662 else
13663 error (_("Failed to configure the BTS buffer size."));
13664 }
13665
13666 rs->btrace_config.bts.size = conf->bts.size;
13667 }
b20a6524
MM
13668
13669 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13670 if (packet_config_support (packet) == PACKET_ENABLE
13671 && conf->pt.size != rs->btrace_config.pt.size)
13672 {
13673 pos = buf;
13674 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13675 conf->pt.size);
13676
13677 putpkt (buf);
13678 getpkt (&buf, &rs->buf_size, 0);
13679
13680 if (packet_ok (buf, packet) == PACKET_ERROR)
13681 {
13682 if (buf[0] == 'E' && buf[1] == '.')
13683 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13684 else
13685 error (_("Failed to configure the trace buffer size."));
13686 }
13687
13688 rs->btrace_config.pt.size = conf->pt.size;
13689 }
f4abbc16
MM
13690}
13691
13692/* Read the current thread's btrace configuration from the target and
13693 store it into CONF. */
13694
13695static void
13696btrace_read_config (struct btrace_config *conf)
13697{
9018be22 13698 gdb::optional<gdb::char_vector> xml
8b88a78e 13699 = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE_CONF, "");
9018be22
SM
13700 if (xml)
13701 parse_xml_btrace_conf (conf, xml->data ());
f4abbc16
MM
13702}
13703
c0272db5
TW
13704/* Maybe reopen target btrace. */
13705
6b8edb51
PA
13706void
13707remote_target::remote_btrace_maybe_reopen ()
c0272db5
TW
13708{
13709 struct remote_state *rs = get_remote_state ();
c0272db5
TW
13710 struct thread_info *tp;
13711 int btrace_target_pushed = 0;
13712 int warned = 0;
13713
5ed8105e
PA
13714 scoped_restore_current_thread restore_thread;
13715
c0272db5
TW
13716 ALL_NON_EXITED_THREADS (tp)
13717 {
13718 set_general_thread (tp->ptid);
13719
13720 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13721 btrace_read_config (&rs->btrace_config);
13722
13723 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13724 continue;
13725
13726#if !defined (HAVE_LIBIPT)
13727 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13728 {
13729 if (!warned)
13730 {
13731 warned = 1;
c4e12631
MM
13732 warning (_("Target is recording using Intel Processor Trace "
13733 "but support was disabled at compile time."));
c0272db5
TW
13734 }
13735
13736 continue;
13737 }
13738#endif /* !defined (HAVE_LIBIPT) */
13739
13740 /* Push target, once, but before anything else happens. This way our
13741 changes to the threads will be cleaned up by unpushing the target
13742 in case btrace_read_config () throws. */
13743 if (!btrace_target_pushed)
13744 {
13745 btrace_target_pushed = 1;
13746 record_btrace_push_target ();
13747 printf_filtered (_("Target is recording using %s.\n"),
13748 btrace_format_string (rs->btrace_config.format));
13749 }
13750
13751 tp->btrace.target = XCNEW (struct btrace_target_info);
13752 tp->btrace.target->ptid = tp->ptid;
13753 tp->btrace.target->conf = rs->btrace_config;
13754 }
c0272db5
TW
13755}
13756
9accd112
MM
13757/* Enable branch tracing. */
13758
f6ac5f3d
PA
13759struct btrace_target_info *
13760remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
9accd112
MM
13761{
13762 struct btrace_target_info *tinfo = NULL;
b20a6524 13763 struct packet_config *packet = NULL;
9accd112
MM
13764 struct remote_state *rs = get_remote_state ();
13765 char *buf = rs->buf;
13766 char *endbuf = rs->buf + get_remote_packet_size ();
13767
b20a6524
MM
13768 switch (conf->format)
13769 {
13770 case BTRACE_FORMAT_BTS:
13771 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13772 break;
13773
13774 case BTRACE_FORMAT_PT:
13775 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13776 break;
13777 }
13778
13779 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13780 error (_("Target does not support branch tracing."));
13781
f4abbc16
MM
13782 btrace_sync_conf (conf);
13783
9accd112
MM
13784 set_general_thread (ptid);
13785
13786 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13787 putpkt (rs->buf);
13788 getpkt (&rs->buf, &rs->buf_size, 0);
13789
13790 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13791 {
13792 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13793 error (_("Could not enable branch tracing for %s: %s"),
13794 target_pid_to_str (ptid), rs->buf + 2);
13795 else
13796 error (_("Could not enable branch tracing for %s."),
13797 target_pid_to_str (ptid));
13798 }
13799
8d749320 13800 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
13801 tinfo->ptid = ptid;
13802
f4abbc16
MM
13803 /* If we fail to read the configuration, we lose some information, but the
13804 tracing itself is not impacted. */
492d29ea
PA
13805 TRY
13806 {
13807 btrace_read_config (&tinfo->conf);
13808 }
13809 CATCH (err, RETURN_MASK_ERROR)
13810 {
13811 if (err.message != NULL)
13812 warning ("%s", err.message);
13813 }
13814 END_CATCH
f4abbc16 13815
9accd112
MM
13816 return tinfo;
13817}
13818
13819/* Disable branch tracing. */
13820
f6ac5f3d
PA
13821void
13822remote_target::disable_btrace (struct btrace_target_info *tinfo)
9accd112
MM
13823{
13824 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13825 struct remote_state *rs = get_remote_state ();
13826 char *buf = rs->buf;
13827 char *endbuf = rs->buf + get_remote_packet_size ();
13828
4082afcc 13829 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13830 error (_("Target does not support branch tracing."));
13831
13832 set_general_thread (tinfo->ptid);
13833
13834 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13835 putpkt (rs->buf);
13836 getpkt (&rs->buf, &rs->buf_size, 0);
13837
13838 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13839 {
13840 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13841 error (_("Could not disable branch tracing for %s: %s"),
13842 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13843 else
13844 error (_("Could not disable branch tracing for %s."),
13845 target_pid_to_str (tinfo->ptid));
13846 }
13847
13848 xfree (tinfo);
13849}
13850
13851/* Teardown branch tracing. */
13852
f6ac5f3d
PA
13853void
13854remote_target::teardown_btrace (struct btrace_target_info *tinfo)
9accd112
MM
13855{
13856 /* We must not talk to the target during teardown. */
13857 xfree (tinfo);
13858}
13859
13860/* Read the branch trace. */
13861
f6ac5f3d
PA
13862enum btrace_error
13863remote_target::read_btrace (struct btrace_data *btrace,
13864 struct btrace_target_info *tinfo,
13865 enum btrace_read_type type)
9accd112
MM
13866{
13867 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
9accd112 13868 const char *annex;
9accd112 13869
4082afcc 13870 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13871 error (_("Target does not support branch tracing."));
13872
13873#if !defined(HAVE_LIBEXPAT)
13874 error (_("Cannot process branch tracing result. XML parsing not supported."));
13875#endif
13876
13877 switch (type)
13878 {
864089d2 13879 case BTRACE_READ_ALL:
9accd112
MM
13880 annex = "all";
13881 break;
864089d2 13882 case BTRACE_READ_NEW:
9accd112
MM
13883 annex = "new";
13884 break;
969c39fb
MM
13885 case BTRACE_READ_DELTA:
13886 annex = "delta";
13887 break;
9accd112
MM
13888 default:
13889 internal_error (__FILE__, __LINE__,
13890 _("Bad branch tracing read type: %u."),
13891 (unsigned int) type);
13892 }
13893
9018be22 13894 gdb::optional<gdb::char_vector> xml
8b88a78e 13895 = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE, annex);
9018be22 13896 if (!xml)
969c39fb 13897 return BTRACE_ERR_UNKNOWN;
9accd112 13898
9018be22 13899 parse_xml_btrace (btrace, xml->data ());
9accd112 13900
969c39fb 13901 return BTRACE_ERR_NONE;
9accd112
MM
13902}
13903
f6ac5f3d
PA
13904const struct btrace_config *
13905remote_target::btrace_conf (const struct btrace_target_info *tinfo)
f4abbc16
MM
13906{
13907 return &tinfo->conf;
13908}
13909
57810aa7 13910bool
f6ac5f3d 13911remote_target::augmented_libraries_svr4_read ()
ced63ec0 13912{
4082afcc
PA
13913 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13914 == PACKET_ENABLE);
ced63ec0
GB
13915}
13916
9dd130a0
TT
13917/* Implementation of to_load. */
13918
f6ac5f3d
PA
13919void
13920remote_target::load (const char *name, int from_tty)
9dd130a0
TT
13921{
13922 generic_load (name, from_tty);
13923}
13924
c78fa86a
GB
13925/* Accepts an integer PID; returns a string representing a file that
13926 can be opened on the remote side to get the symbols for the child
13927 process. Returns NULL if the operation is not supported. */
13928
f6ac5f3d
PA
13929char *
13930remote_target::pid_to_exec_file (int pid)
c78fa86a 13931{
9018be22 13932 static gdb::optional<gdb::char_vector> filename;
835205d0
GB
13933 struct inferior *inf;
13934 char *annex = NULL;
c78fa86a
GB
13935
13936 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13937 return NULL;
13938
835205d0
GB
13939 inf = find_inferior_pid (pid);
13940 if (inf == NULL)
13941 internal_error (__FILE__, __LINE__,
13942 _("not currently attached to process %d"), pid);
13943
13944 if (!inf->fake_pid_p)
13945 {
13946 const int annex_size = 9;
13947
224c3ddb 13948 annex = (char *) alloca (annex_size);
835205d0
GB
13949 xsnprintf (annex, annex_size, "%x", pid);
13950 }
13951
8b88a78e 13952 filename = target_read_stralloc (current_top_target (),
c78fa86a
GB
13953 TARGET_OBJECT_EXEC_FILE, annex);
13954
9018be22 13955 return filename ? filename->data () : nullptr;
c78fa86a
GB
13956}
13957
750ce8d1
YQ
13958/* Implement the to_can_do_single_step target_ops method. */
13959
f6ac5f3d
PA
13960int
13961remote_target::can_do_single_step ()
750ce8d1
YQ
13962{
13963 /* We can only tell whether target supports single step or not by
13964 supported s and S vCont actions if the stub supports vContSupported
13965 feature. If the stub doesn't support vContSupported feature,
13966 we have conservatively to think target doesn't supports single
13967 step. */
13968 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13969 {
13970 struct remote_state *rs = get_remote_state ();
13971
13972 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6b8edb51 13973 remote_vcont_probe ();
750ce8d1
YQ
13974
13975 return rs->supports_vCont.s && rs->supports_vCont.S;
13976 }
13977 else
13978 return 0;
13979}
13980
3a00c802
PA
13981/* Implementation of the to_execution_direction method for the remote
13982 target. */
13983
f6ac5f3d
PA
13984enum exec_direction_kind
13985remote_target::execution_direction ()
3a00c802
PA
13986{
13987 struct remote_state *rs = get_remote_state ();
13988
13989 return rs->last_resume_exec_dir;
13990}
13991
f6327dcb
KB
13992/* Return pointer to the thread_info struct which corresponds to
13993 THREAD_HANDLE (having length HANDLE_LEN). */
13994
f6ac5f3d
PA
13995thread_info *
13996remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
13997 int handle_len,
13998 inferior *inf)
f6327dcb
KB
13999{
14000 struct thread_info *tp;
14001
14002 ALL_NON_EXITED_THREADS (tp)
14003 {
7aabaf9d 14004 remote_thread_info *priv = get_remote_thread_info (tp);
f6327dcb
KB
14005
14006 if (tp->inf == inf && priv != NULL)
14007 {
7aabaf9d 14008 if (handle_len != priv->thread_handle.size ())
f6327dcb 14009 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
7aabaf9d
SM
14010 handle_len, priv->thread_handle.size ());
14011 if (memcmp (thread_handle, priv->thread_handle.data (),
f6327dcb
KB
14012 handle_len) == 0)
14013 return tp;
14014 }
14015 }
14016
14017 return NULL;
14018}
14019
57810aa7 14020bool
f6ac5f3d 14021remote_target::can_async_p ()
6426a772 14022{
5d93a237
TT
14023 struct remote_state *rs = get_remote_state ();
14024
3015c064
SM
14025 /* We don't go async if the user has explicitly prevented it with the
14026 "maint set target-async" command. */
c6ebd6cf 14027 if (!target_async_permitted)
57810aa7 14028 return false;
75c99385 14029
23860348 14030 /* We're async whenever the serial device is. */
5d93a237 14031 return serial_can_async_p (rs->remote_desc);
6426a772
JM
14032}
14033
57810aa7 14034bool
f6ac5f3d 14035remote_target::is_async_p ()
6426a772 14036{
5d93a237
TT
14037 struct remote_state *rs = get_remote_state ();
14038
c6ebd6cf 14039 if (!target_async_permitted)
75c99385 14040 /* We only enable async when the user specifically asks for it. */
57810aa7 14041 return false;
75c99385 14042
23860348 14043 /* We're async whenever the serial device is. */
5d93a237 14044 return serial_is_async_p (rs->remote_desc);
6426a772
JM
14045}
14046
2acceee2
JM
14047/* Pass the SERIAL event on and up to the client. One day this code
14048 will be able to delay notifying the client of an event until the
23860348 14049 point where an entire packet has been received. */
2acceee2 14050
2acceee2
JM
14051static serial_event_ftype remote_async_serial_handler;
14052
6426a772 14053static void
819cc324 14054remote_async_serial_handler (struct serial *scb, void *context)
6426a772 14055{
2acceee2
JM
14056 /* Don't propogate error information up to the client. Instead let
14057 the client find out about the error by querying the target. */
6a3753b3 14058 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
14059}
14060
74531fed
PA
14061static void
14062remote_async_inferior_event_handler (gdb_client_data data)
14063{
6b8edb51 14064 inferior_event_handler (INF_REG_EVENT, data);
74531fed
PA
14065}
14066
f6ac5f3d
PA
14067void
14068remote_target::async (int enable)
2acceee2 14069{
5d93a237
TT
14070 struct remote_state *rs = get_remote_state ();
14071
6a3753b3 14072 if (enable)
2acceee2 14073 {
88b496c3 14074 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
14075
14076 /* If there are pending events in the stop reply queue tell the
14077 event loop to process them. */
953edf2b 14078 if (!rs->stop_reply_queue.empty ())
6b8edb51 14079 mark_async_event_handler (rs->remote_async_inferior_event_token);
6efcd9a8
PA
14080 /* For simplicity, below we clear the pending events token
14081 without remembering whether it is marked, so here we always
14082 mark it. If there's actually no pending notification to
14083 process, this ends up being a no-op (other than a spurious
14084 event-loop wakeup). */
14085 if (target_is_non_stop_p ())
14086 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
14087 }
14088 else
b7d2e916
PA
14089 {
14090 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
14091 /* If the core is disabling async, it doesn't want to be
14092 disturbed with target events. Clear all async event sources
14093 too. */
6b8edb51 14094 clear_async_event_handler (rs->remote_async_inferior_event_token);
6efcd9a8
PA
14095 if (target_is_non_stop_p ())
14096 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 14097 }
6426a772
JM
14098}
14099
65706a29
PA
14100/* Implementation of the to_thread_events method. */
14101
f6ac5f3d
PA
14102void
14103remote_target::thread_events (int enable)
65706a29
PA
14104{
14105 struct remote_state *rs = get_remote_state ();
14106 size_t size = get_remote_packet_size ();
65706a29
PA
14107
14108 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14109 return;
14110
14111 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
14112 putpkt (rs->buf);
14113 getpkt (&rs->buf, &rs->buf_size, 0);
14114
14115 switch (packet_ok (rs->buf,
14116 &remote_protocol_packets[PACKET_QThreadEvents]))
14117 {
14118 case PACKET_OK:
14119 if (strcmp (rs->buf, "OK") != 0)
14120 error (_("Remote refused setting thread events: %s"), rs->buf);
14121 break;
14122 case PACKET_ERROR:
14123 warning (_("Remote failure reply: %s"), rs->buf);
14124 break;
14125 case PACKET_UNKNOWN:
14126 break;
14127 }
14128}
14129
5a2468f5 14130static void
981a3fb3 14131set_remote_cmd (const char *args, int from_tty)
5a2468f5 14132{
635c7e8a 14133 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
14134}
14135
d471ea57 14136static void
981a3fb3 14137show_remote_cmd (const char *args, int from_tty)
d471ea57 14138{
37a105a1 14139 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 14140 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1 14141 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 14142 struct ui_out *uiout = current_uiout;
37a105a1 14143
2e783024 14144 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
37a105a1
DJ
14145 for (; list != NULL; list = list->next)
14146 if (strcmp (list->name, "Z-packet") == 0)
14147 continue;
427c3a89
DJ
14148 else if (list->type == not_set_cmd)
14149 /* Alias commands are exactly like the original, except they
14150 don't have the normal type. */
14151 continue;
14152 else
37a105a1 14153 {
2e783024 14154 ui_out_emit_tuple option_emitter (uiout, "option");
a744cf53 14155
112e8700
SM
14156 uiout->field_string ("name", list->name);
14157 uiout->text (": ");
427c3a89 14158 if (list->type == show_cmd)
f5c4fcd9 14159 do_show_command (NULL, from_tty, list);
427c3a89
DJ
14160 else
14161 cmd_func (list, NULL, from_tty);
37a105a1 14162 }
d471ea57 14163}
5a2468f5 14164
0f71a2f6 14165
23860348 14166/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
14167static void
14168remote_new_objfile (struct objfile *objfile)
14169{
6b8edb51 14170 remote_target *remote = get_current_remote_target ();
5d93a237 14171
6b8edb51
PA
14172 if (remote != NULL) /* Have a remote connection. */
14173 remote->remote_check_symbols ();
dc8acb97
MS
14174}
14175
00bf0b85
SS
14176/* Pull all the tracepoints defined on the target and create local
14177 data structures representing them. We don't want to create real
14178 tracepoints yet, we don't want to mess up the user's existing
14179 collection. */
14180
f6ac5f3d
PA
14181int
14182remote_target::upload_tracepoints (struct uploaded_tp **utpp)
d5551862 14183{
00bf0b85
SS
14184 struct remote_state *rs = get_remote_state ();
14185 char *p;
d5551862 14186
00bf0b85
SS
14187 /* Ask for a first packet of tracepoint definition. */
14188 putpkt ("qTfP");
14189 getpkt (&rs->buf, &rs->buf_size, 0);
14190 p = rs->buf;
14191 while (*p && *p != 'l')
d5551862 14192 {
00bf0b85
SS
14193 parse_tracepoint_definition (p, utpp);
14194 /* Ask for another packet of tracepoint definition. */
14195 putpkt ("qTsP");
14196 getpkt (&rs->buf, &rs->buf_size, 0);
14197 p = rs->buf;
d5551862 14198 }
00bf0b85 14199 return 0;
d5551862
SS
14200}
14201
f6ac5f3d
PA
14202int
14203remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
d5551862 14204{
00bf0b85 14205 struct remote_state *rs = get_remote_state ();
d5551862 14206 char *p;
d5551862 14207
00bf0b85
SS
14208 /* Ask for a first packet of variable definition. */
14209 putpkt ("qTfV");
d5551862
SS
14210 getpkt (&rs->buf, &rs->buf_size, 0);
14211 p = rs->buf;
00bf0b85 14212 while (*p && *p != 'l')
d5551862 14213 {
00bf0b85
SS
14214 parse_tsv_definition (p, utsvp);
14215 /* Ask for another packet of variable definition. */
14216 putpkt ("qTsV");
d5551862
SS
14217 getpkt (&rs->buf, &rs->buf_size, 0);
14218 p = rs->buf;
14219 }
00bf0b85 14220 return 0;
d5551862
SS
14221}
14222
c1e36e3e
PA
14223/* The "set/show range-stepping" show hook. */
14224
14225static void
14226show_range_stepping (struct ui_file *file, int from_tty,
14227 struct cmd_list_element *c,
14228 const char *value)
14229{
14230 fprintf_filtered (file,
14231 _("Debugger's willingness to use range stepping "
14232 "is %s.\n"), value);
14233}
14234
6b8edb51
PA
14235/* Return true if the vCont;r action is supported by the remote
14236 stub. */
14237
14238bool
14239remote_target::vcont_r_supported ()
14240{
14241 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14242 remote_vcont_probe ();
14243
14244 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14245 && get_remote_state ()->supports_vCont.r);
14246}
14247
c1e36e3e
PA
14248/* The "set/show range-stepping" set hook. */
14249
14250static void
eb4c3f4a 14251set_range_stepping (const char *ignore_args, int from_tty,
c1e36e3e
PA
14252 struct cmd_list_element *c)
14253{
6b8edb51
PA
14254 /* When enabling, check whether range stepping is actually supported
14255 by the target, and warn if not. */
c1e36e3e
PA
14256 if (use_range_stepping)
14257 {
6b8edb51
PA
14258 remote_target *remote = get_current_remote_target ();
14259 if (remote == NULL
14260 || !remote->vcont_r_supported ())
14261 warning (_("Range stepping is not supported by the current target"));
c1e36e3e
PA
14262 }
14263}
14264
c906108c 14265void
fba45db2 14266_initialize_remote (void)
c906108c 14267{
9a7071a8 14268 struct cmd_list_element *cmd;
6f937416 14269 const char *cmd_name;
ea9c271d 14270
0f71a2f6 14271 /* architecture specific data */
29709017
DJ
14272 remote_g_packet_data_handle =
14273 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 14274
94585166
DB
14275 remote_pspace_data
14276 = register_program_space_data_with_cleanup (NULL,
14277 remote_pspace_data_cleanup);
14278
d9f719f1
PA
14279 add_target (remote_target_info, remote_target::open);
14280 add_target (extended_remote_target_info, extended_remote_target::open);
cce74817 14281
dc8acb97 14282 /* Hook into new objfile notification. */
76727919 14283 gdb::observers::new_objfile.attach (remote_new_objfile);
dc8acb97 14284
c906108c
SS
14285#if 0
14286 init_remote_threadtests ();
14287#endif
14288
23860348 14289 /* set/show remote ... */
d471ea57 14290
1bedd215 14291 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
14292Remote protocol specific variables\n\
14293Configure various remote-protocol specific variables such as\n\
1bedd215 14294the packets being used"),
cff3e48b 14295 &remote_set_cmdlist, "set remote ",
23860348 14296 0 /* allow-unknown */, &setlist);
1bedd215 14297 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
14298Remote protocol specific variables\n\
14299Configure various remote-protocol specific variables such as\n\
1bedd215 14300the packets being used"),
cff3e48b 14301 &remote_show_cmdlist, "show remote ",
23860348 14302 0 /* allow-unknown */, &showlist);
5a2468f5 14303
1a966eab
AC
14304 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14305Compare section data on target to the exec file.\n\
95cf3b38
DT
14306Argument is a single section name (default: all loaded sections).\n\
14307To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
14308 &cmdlist);
14309
1a966eab
AC
14310 add_cmd ("packet", class_maintenance, packet_command, _("\
14311Send an arbitrary packet to a remote target.\n\
c906108c
SS
14312 maintenance packet TEXT\n\
14313If GDB is talking to an inferior via the GDB serial protocol, then\n\
14314this command sends the string TEXT to the inferior, and displays the\n\
14315response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 14316terminating `#' character and checksum."),
c906108c
SS
14317 &maintenancelist);
14318
7915a72c
AC
14319 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14320Set whether to send break if interrupted."), _("\
14321Show whether to send break if interrupted."), _("\
14322If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 14323 set_remotebreak, show_remotebreak,
e707bbc2 14324 &setlist, &showlist);
9a7071a8
JB
14325 cmd_name = "remotebreak";
14326 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14327 deprecate_cmd (cmd, "set remote interrupt-sequence");
14328 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14329 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14330 deprecate_cmd (cmd, "show remote interrupt-sequence");
14331
14332 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
14333 interrupt_sequence_modes, &interrupt_sequence_mode,
14334 _("\
9a7071a8
JB
14335Set interrupt sequence to remote target."), _("\
14336Show interrupt sequence to remote target."), _("\
14337Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14338 NULL, show_interrupt_sequence,
14339 &remote_set_cmdlist,
14340 &remote_show_cmdlist);
14341
14342 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14343 &interrupt_on_connect, _("\
14344Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14345Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14346If set, interrupt sequence is sent to remote target."),
14347 NULL, NULL,
14348 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 14349
23860348 14350 /* Install commands for configuring memory read/write packets. */
11cf8741 14351
1a966eab
AC
14352 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14353Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 14354 &setlist);
1a966eab
AC
14355 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14356Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
14357 &showlist);
14358 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
14359 set_memory_write_packet_size, _("\
14360Set the maximum number of bytes per memory-write packet.\n\
14361Specify the number of bytes in a packet or 0 (zero) for the\n\
14362default packet size. The actual limit is further reduced\n\
14363dependent on the target. Specify ``fixed'' to disable the\n\
14364further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14365 &remote_set_cmdlist);
14366 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
14367 set_memory_read_packet_size, _("\
14368Set the maximum number of bytes per memory-read packet.\n\
14369Specify the number of bytes in a packet or 0 (zero) for the\n\
14370default packet size. The actual limit is further reduced\n\
14371dependent on the target. Specify ``fixed'' to disable the\n\
14372further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14373 &remote_set_cmdlist);
14374 add_cmd ("memory-write-packet-size", no_class,
14375 show_memory_write_packet_size,
1a966eab 14376 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
14377 &remote_show_cmdlist);
14378 add_cmd ("memory-read-packet-size", no_class,
14379 show_memory_read_packet_size,
1a966eab 14380 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 14381 &remote_show_cmdlist);
c906108c 14382
055303e2 14383 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
14384 &remote_hw_watchpoint_limit, _("\
14385Set the maximum number of target hardware watchpoints."), _("\
14386Show the maximum number of target hardware watchpoints."), _("\
055303e2
AB
14387Specify \"unlimited\" for unlimited hardware watchpoints."),
14388 NULL, show_hardware_watchpoint_limit,
14389 &remote_set_cmdlist,
14390 &remote_show_cmdlist);
14391 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
14392 no_class,
480a3f21
PW
14393 &remote_hw_watchpoint_length_limit, _("\
14394Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14395Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
055303e2
AB
14396Specify \"unlimited\" to allow watchpoints of unlimited size."),
14397 NULL, show_hardware_watchpoint_length_limit,
480a3f21 14398 &remote_set_cmdlist, &remote_show_cmdlist);
055303e2 14399 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
14400 &remote_hw_breakpoint_limit, _("\
14401Set the maximum number of target hardware breakpoints."), _("\
14402Show the maximum number of target hardware breakpoints."), _("\
055303e2
AB
14403Specify \"unlimited\" for unlimited hardware breakpoints."),
14404 NULL, show_hardware_breakpoint_limit,
b3f42336 14405 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 14406
1b493192
PA
14407 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14408 &remote_address_size, _("\
4d28ad1e
AC
14409Set the maximum size of the address (in bits) in a memory packet."), _("\
14410Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
14411 NULL,
14412 NULL, /* FIXME: i18n: */
14413 &setlist, &showlist);
c906108c 14414
ca4f7f8b
PA
14415 init_all_packet_configs ();
14416
444abaca 14417 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 14418 "X", "binary-download", 1);
0f71a2f6 14419
444abaca 14420 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 14421 "vCont", "verbose-resume", 0);
506fb367 14422
89be2091
DJ
14423 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14424 "QPassSignals", "pass-signals", 0);
14425
82075af2
JS
14426 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14427 "QCatchSyscalls", "catch-syscalls", 0);
14428
9b224c5e
PA
14429 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14430 "QProgramSignals", "program-signals", 0);
14431
bc3b087d
SDJ
14432 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14433 "QSetWorkingDir", "set-working-dir", 0);
14434
aefd8b33
SDJ
14435 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14436 "QStartupWithShell", "startup-with-shell", 0);
14437
0a2dde4a
SDJ
14438 add_packet_config_cmd (&remote_protocol_packets
14439 [PACKET_QEnvironmentHexEncoded],
14440 "QEnvironmentHexEncoded", "environment-hex-encoded",
14441 0);
14442
14443 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14444 "QEnvironmentReset", "environment-reset",
14445 0);
14446
14447 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14448 "QEnvironmentUnset", "environment-unset",
14449 0);
14450
444abaca 14451 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 14452 "qSymbol", "symbol-lookup", 0);
dc8acb97 14453
444abaca 14454 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 14455 "P", "set-register", 1);
d471ea57 14456
444abaca 14457 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 14458 "p", "fetch-register", 1);
b96ec7ac 14459
444abaca 14460 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 14461 "Z0", "software-breakpoint", 0);
d471ea57 14462
444abaca 14463 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 14464 "Z1", "hardware-breakpoint", 0);
d471ea57 14465
444abaca 14466 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 14467 "Z2", "write-watchpoint", 0);
d471ea57 14468
444abaca 14469 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 14470 "Z3", "read-watchpoint", 0);
d471ea57 14471
444abaca 14472 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 14473 "Z4", "access-watchpoint", 0);
d471ea57 14474
0876f84a
DJ
14475 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14476 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 14477
c78fa86a
GB
14478 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14479 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14480
23181151
DJ
14481 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14482 "qXfer:features:read", "target-features", 0);
14483
cfa9d6d9
DJ
14484 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14485 "qXfer:libraries:read", "library-info", 0);
14486
2268b414
JK
14487 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14488 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14489
fd79ecee
DJ
14490 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14491 "qXfer:memory-map:read", "memory-map", 0);
14492
0e7f50da
UW
14493 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14494 "qXfer:spu:read", "read-spu-object", 0);
14495
14496 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14497 "qXfer:spu:write", "write-spu-object", 0);
14498
07e059b5
VP
14499 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14500 "qXfer:osdata:read", "osdata", 0);
14501
dc146f7c
VP
14502 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14503 "qXfer:threads:read", "threads", 0);
14504
4aa995e1
PA
14505 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14506 "qXfer:siginfo:read", "read-siginfo-object", 0);
14507
14508 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14509 "qXfer:siginfo:write", "write-siginfo-object", 0);
14510
b3b9301e
PA
14511 add_packet_config_cmd
14512 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 14513 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 14514
169081d0
TG
14515 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14516 "qXfer:uib:read", "unwind-info-block", 0);
14517
444abaca 14518 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 14519 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
14520 0);
14521
711e434b
PM
14522 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14523 "qGetTIBAddr", "get-thread-information-block-address",
14524 0);
14525
40ab02ce
MS
14526 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14527 "bc", "reverse-continue", 0);
14528
14529 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14530 "bs", "reverse-step", 0);
14531
be2a5f71
DJ
14532 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14533 "qSupported", "supported-packets", 0);
14534
08388c79
DE
14535 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14536 "qSearch:memory", "search-memory", 0);
14537
bd3eecc3
PA
14538 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14539 "qTStatus", "trace-status", 0);
14540
15a201c8
GB
14541 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14542 "vFile:setfs", "hostio-setfs", 0);
14543
a6b151f1
DJ
14544 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14545 "vFile:open", "hostio-open", 0);
14546
14547 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14548 "vFile:pread", "hostio-pread", 0);
14549
14550 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14551 "vFile:pwrite", "hostio-pwrite", 0);
14552
14553 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14554 "vFile:close", "hostio-close", 0);
14555
14556 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14557 "vFile:unlink", "hostio-unlink", 0);
14558
b9e7b9c3
UW
14559 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14560 "vFile:readlink", "hostio-readlink", 0);
14561
0a93529c
GB
14562 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14563 "vFile:fstat", "hostio-fstat", 0);
14564
2d717e4f
DJ
14565 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14566 "vAttach", "attach", 0);
14567
14568 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14569 "vRun", "run", 0);
14570
a6f3e723
SL
14571 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14572 "QStartNoAckMode", "noack", 0);
14573
82f73884
PA
14574 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14575 "vKill", "kill", 0);
14576
0b16c5cf
PA
14577 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14578 "qAttached", "query-attached", 0);
14579
782b2b07 14580 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
14581 "ConditionalTracepoints",
14582 "conditional-tracepoints", 0);
3788aec7
LM
14583
14584 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14585 "ConditionalBreakpoints",
14586 "conditional-breakpoints", 0);
14587
d3ce09f5
SS
14588 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14589 "BreakpointCommands",
14590 "breakpoint-commands", 0);
14591
7a697b8d
SS
14592 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14593 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 14594
409873ef
SS
14595 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14596 "TracepointSource", "TracepointSource", 0);
14597
d914c394
SS
14598 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14599 "QAllow", "allow", 0);
14600
0fb4aa4b
PA
14601 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14602 "StaticTracepoints", "static-tracepoints", 0);
14603
1e4d1764
YQ
14604 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14605 "InstallInTrace", "install-in-trace", 0);
14606
0fb4aa4b
PA
14607 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14608 "qXfer:statictrace:read", "read-sdata-object", 0);
14609
78d85199
YQ
14610 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14611 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14612
03583c20
UW
14613 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14614 "QDisableRandomization", "disable-randomization", 0);
14615
d1feda86
YQ
14616 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14617 "QAgent", "agent", 0);
14618
f6f899bf
HAQ
14619 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14620 "QTBuffer:size", "trace-buffer-size", 0);
14621
9accd112
MM
14622 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14623 "Qbtrace:off", "disable-btrace", 0);
14624
14625 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
14626 "Qbtrace:bts", "enable-btrace-bts", 0);
14627
14628 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14629 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
14630
14631 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14632 "qXfer:btrace", "read-btrace", 0);
14633
f4abbc16
MM
14634 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14635 "qXfer:btrace-conf", "read-btrace-conf", 0);
14636
d33501a5
MM
14637 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14638 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14639
73b8c1fd
PA
14640 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14641 "multiprocess-feature", "multiprocess-feature", 0);
14642
f7e6eed5
PA
14643 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14644 "swbreak-feature", "swbreak-feature", 0);
14645
14646 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14647 "hwbreak-feature", "hwbreak-feature", 0);
14648
89245bc0
DB
14649 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14650 "fork-event-feature", "fork-event-feature", 0);
14651
14652 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14653 "vfork-event-feature", "vfork-event-feature", 0);
14654
b20a6524
MM
14655 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14656 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14657
750ce8d1
YQ
14658 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14659 "vContSupported", "verbose-resume-supported", 0);
14660
94585166
DB
14661 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14662 "exec-event-feature", "exec-event-feature", 0);
14663
de979965
PA
14664 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14665 "vCtrlC", "ctrl-c", 0);
14666
65706a29
PA
14667 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14668 "QThreadEvents", "thread-events", 0);
14669
f2faf941
PA
14670 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14671 "N stop reply", "no-resumed-stop-reply", 0);
14672
0b736949
DB
14673 /* Assert that we've registered "set remote foo-packet" commands
14674 for all packet configs. */
ca4f7f8b
PA
14675 {
14676 int i;
14677
14678 for (i = 0; i < PACKET_MAX; i++)
14679 {
14680 /* Ideally all configs would have a command associated. Some
14681 still don't though. */
14682 int excepted;
14683
14684 switch (i)
14685 {
14686 case PACKET_QNonStop:
ca4f7f8b
PA
14687 case PACKET_EnableDisableTracepoints_feature:
14688 case PACKET_tracenz_feature:
14689 case PACKET_DisconnectedTracing_feature:
14690 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
14691 case PACKET_qCRC:
14692 /* Additions to this list need to be well justified:
14693 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
14694 excepted = 1;
14695 break;
14696 default:
14697 excepted = 0;
14698 break;
14699 }
14700
14701 /* This catches both forgetting to add a config command, and
14702 forgetting to remove a packet from the exception list. */
14703 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14704 }
14705 }
14706
37a105a1
DJ
14707 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14708 Z sub-packet has its own set and show commands, but users may
14709 have sets to this variable in their .gdbinit files (or in their
14710 documentation). */
e9e68a56 14711 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
14712 &remote_Z_packet_detect, _("\
14713Set use of remote protocol `Z' packets"), _("\
14714Show use of remote protocol `Z' packets "), _("\
3b64bf98 14715When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 14716packets."),
e9e68a56 14717 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
14718 show_remote_protocol_Z_packet_cmd,
14719 /* FIXME: i18n: Use of remote protocol
14720 `Z' packets is %s. */
e9e68a56 14721 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 14722
a6b151f1
DJ
14723 add_prefix_cmd ("remote", class_files, remote_command, _("\
14724Manipulate files on the remote system\n\
14725Transfer files to and from the remote target system."),
14726 &remote_cmdlist, "remote ",
14727 0 /* allow-unknown */, &cmdlist);
14728
14729 add_cmd ("put", class_files, remote_put_command,
14730 _("Copy a local file to the remote system."),
14731 &remote_cmdlist);
14732
14733 add_cmd ("get", class_files, remote_get_command,
14734 _("Copy a remote file to the local system."),
14735 &remote_cmdlist);
14736
14737 add_cmd ("delete", class_files, remote_delete_command,
14738 _("Delete a remote file."),
14739 &remote_cmdlist);
14740
2d717e4f 14741 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 14742 &remote_exec_file_var, _("\
2d717e4f 14743Set the remote pathname for \"run\""), _("\
94585166
DB
14744Show the remote pathname for \"run\""), NULL,
14745 set_remote_exec_file,
14746 show_remote_exec_file,
14747 &remote_set_cmdlist,
14748 &remote_show_cmdlist);
2d717e4f 14749
c1e36e3e
PA
14750 add_setshow_boolean_cmd ("range-stepping", class_run,
14751 &use_range_stepping, _("\
14752Enable or disable range stepping."), _("\
14753Show whether target-assisted range stepping is enabled."), _("\
14754If on, and the target supports it, when stepping a source line, GDB\n\
14755tells the target to step the corresponding range of addresses itself instead\n\
14756of issuing multiple single-steps. This speeds up source level\n\
14757stepping. If off, GDB always issues single-steps, even if range\n\
14758stepping is supported by the target. The default is on."),
14759 set_range_stepping,
14760 show_range_stepping,
14761 &setlist,
14762 &showlist);
14763
449092f6
CV
14764 /* Eventually initialize fileio. See fileio.c */
14765 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 14766
ba348170 14767 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 14768 special ptids with it set to != 0. */
fd79271b
TT
14769 magic_null_ptid = ptid_t (42000, -1, 1);
14770 not_sent_ptid = ptid_t (42000, -2, 1);
14771 any_thread_ptid = ptid_t (42000, 0, 1);
c906108c 14772}
This page took 4.868759 seconds and 4 git commands to generate.