]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/remote.c
make-target-delegates: line break between return type and function name
[thirdparty/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"
35b1e5cc 78
f6ac5f3d
PA
79/* The remote target. */
80
81class remote_target : public target_ops
82{
83public:
84 remote_target ()
85 {
86 to_stratum = process_stratum;
87 }
88
89 const char *shortname () override
90 { return "remote"; }
91
92 const char *longname () override
93 { return _("Remote serial target in gdb-specific protocol"); }
94
95 const char *doc () override
96 {
97 return _("\
98Use a remote computer via a serial line, using a gdb-specific protocol.\n\
99Specify the serial device it is connected to\n\
100(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
101 }
102
103 thread_control_capabilities get_thread_control_capabilities () override
104 { return tc_schedlock; }
105
106 void open (const char *, int) override;
107 void close () override;
108
109 void detach (inferior *, int) override;
110 void disconnect (const char *, int) override;
111
112 void commit_resume () override;
113 void resume (ptid_t, int, enum gdb_signal) override;
114 ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
115
116 void fetch_registers (struct regcache *, int) override;
117 void store_registers (struct regcache *, int) override;
118 void prepare_to_store (struct regcache *) override;
119
120 void files_info () override;
121
122 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
123
124 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
125 enum remove_bp_reason) override;
126
127
128 int stopped_by_sw_breakpoint () override;
129 int supports_stopped_by_sw_breakpoint () override;
130
131 int stopped_by_hw_breakpoint () override;
132
133 int supports_stopped_by_hw_breakpoint () override;
134
135 int stopped_by_watchpoint () override;
136
137 int stopped_data_address (CORE_ADDR *) override;
138
139 int watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
140
141 int can_use_hw_breakpoint (enum bptype, int, int) override;
142
143 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
144
145 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
146
147 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
148
149 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
150 struct expression *) override;
151
152 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
153 struct expression *) override;
154
155 void kill () override;
156
157 void load (const char *, int) override;
158
159 void mourn_inferior () override;
160
161 void pass_signals (int, unsigned char *) override;
162
163 int set_syscall_catchpoint (int, bool, int,
164 gdb::array_view<const int>) override;
165
166 void program_signals (int, unsigned char *) override;
167
168 int thread_alive (ptid_t ptid) override;
169
170 const char *thread_name (struct thread_info *) override;
171
172 void update_thread_list () override;
173
174 const char *pid_to_str (ptid_t) override;
175
176 const char *extra_thread_info (struct thread_info *) override;
177
178 ptid_t get_ada_task_ptid (long lwp, long thread) override;
179
180 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
181 int handle_len,
182 inferior *inf) override;
183
184 void stop (ptid_t) override;
185
186 void interrupt () override;
187
188 void pass_ctrlc () override;
189
190 enum target_xfer_status xfer_partial (enum target_object object,
191 const char *annex,
192 gdb_byte *readbuf,
193 const gdb_byte *writebuf,
194 ULONGEST offset, ULONGEST len,
195 ULONGEST *xfered_len) override;
196
197 ULONGEST get_memory_xfer_limit () override;
198
199 void rcmd (const char *command, struct ui_file *output) override;
200
201 char *pid_to_exec_file (int pid) override;
202
203 void log_command (const char *cmd) override
204 {
205 serial_log_command (this, cmd);
206 }
207
208 CORE_ADDR get_thread_local_address (ptid_t ptid,
209 CORE_ADDR load_module_addr,
210 CORE_ADDR offset) override;
211
212 int has_all_memory () override { return default_child_has_all_memory (); }
213 int has_memory () override { return default_child_has_memory (); }
214 int has_stack () override { return default_child_has_stack (); }
215 int has_registers () override { return default_child_has_registers (); }
216 int has_execution (ptid_t ptid) override { return default_child_has_execution (ptid); }
217
218 int can_execute_reverse () override;
219
220 std::vector<mem_region> memory_map () override;
221
222 void flash_erase (ULONGEST address, LONGEST length) override;
223
224 void flash_done () override;
225
226 const struct target_desc *read_description () override;
227
228 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
229 const gdb_byte *pattern, ULONGEST pattern_len,
230 CORE_ADDR *found_addrp) override;
231
232 int can_async_p () override;
233
234 int is_async_p () override;
235
236 void async (int) override;
237
238 void thread_events (int) override;
239
240 int can_do_single_step () override;
241
242 void terminal_inferior () override;
243
244 void terminal_ours () override;
245
246 int supports_non_stop () override;
247
248 int supports_multi_process () override;
249
250 int supports_disable_randomization () override;
251
252 int filesystem_is_local () override;
253
254
255 int fileio_open (struct inferior *inf, const char *filename,
256 int flags, int mode, int warn_if_slow,
257 int *target_errno) override;
258
259 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
260 ULONGEST offset, int *target_errno) override;
261
262 int fileio_pread (int fd, gdb_byte *read_buf, int len,
263 ULONGEST offset, int *target_errno) override;
264
265 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
266
267 int fileio_close (int fd, int *target_errno) override;
268
269 int fileio_unlink (struct inferior *inf,
270 const char *filename,
271 int *target_errno) override;
272
273 gdb::optional<std::string>
274 fileio_readlink (struct inferior *inf,
275 const char *filename,
276 int *target_errno) override;
277
278 int supports_enable_disable_tracepoint () override;
279
280 int supports_string_tracing () override;
281
282 int supports_evaluation_of_breakpoint_conditions () override;
283
284 int can_run_breakpoint_commands () override;
285
286 void trace_init () override;
287
288 void download_tracepoint (struct bp_location *location) override;
289
290 int can_download_tracepoint () override;
291
292 void download_trace_state_variable (const trace_state_variable &tsv) override;
293
294 void enable_tracepoint (struct bp_location *location) override;
295
296 void disable_tracepoint (struct bp_location *location) override;
297
298 void trace_set_readonly_regions () override;
299
300 void trace_start () override;
301
302 int get_trace_status (struct trace_status *ts) override;
303
304 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
305 override;
306
307 void trace_stop () override;
308
309 int trace_find (enum trace_find_type type, int num,
310 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
311
312 int get_trace_state_variable_value (int tsv, LONGEST *val) override;
313
314 int save_trace_data (const char *filename) override;
315
316 int upload_tracepoints (struct uploaded_tp **utpp) override;
317
318 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
319
320 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
321
322 int get_min_fast_tracepoint_insn_len () override;
323
324 void set_disconnected_tracing (int val) override;
325
326 void set_circular_trace_buffer (int val) override;
327
328 void set_trace_buffer_size (LONGEST val) override;
329
330 int set_trace_notes (const char *user, const char *notes,
331 const char *stopnotes) override;
332
333 int core_of_thread (ptid_t ptid) override;
334
335 int verify_memory (const gdb_byte *data,
336 CORE_ADDR memaddr, ULONGEST size) override;
337
338
339 int get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
340
341 void set_permissions () override;
342
343 bool static_tracepoint_marker_at (CORE_ADDR,
344 struct static_tracepoint_marker *marker)
345 override;
346
347 std::vector<static_tracepoint_marker>
348 static_tracepoint_markers_by_strid (const char *id) override;
349
350 traceframe_info_up traceframe_info () override;
351
352 int use_agent (int use) override;
353 int can_use_agent () override;
354
355 struct btrace_target_info *enable_btrace (ptid_t ptid,
356 const struct btrace_config *conf) override;
357
358 void disable_btrace (struct btrace_target_info *tinfo) override;
359
360 void teardown_btrace (struct btrace_target_info *tinfo) override;
361
362 enum btrace_error read_btrace (struct btrace_data *data,
363 struct btrace_target_info *btinfo,
364 enum btrace_read_type type) override;
365
366 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
367 int augmented_libraries_svr4_read () override;
368 int follow_fork (int, int) override;
369 void follow_exec (struct inferior *, char *) override;
370 int insert_fork_catchpoint (int) override;
371 int remove_fork_catchpoint (int) override;
372 int insert_vfork_catchpoint (int) override;
373 int remove_vfork_catchpoint (int) override;
374 int insert_exec_catchpoint (int) override;
375 int remove_exec_catchpoint (int) override;
376 enum exec_direction_kind execution_direction () override;
377
378protected:
379 void open_1 (const char *name, int from_tty, int extended_p);
380 void start_remote (int from_tty, int extended_p);
381};
382
383/* Set up the extended remote target by extending the standard remote
384 target and adding to it. */
385
386class extended_remote_target final : public remote_target
387{
388public:
389 const char *shortname () override
390 { return "extended-remote"; }
391
392 const char *longname () override
393 { return _("Extended remote serial target in gdb-specific protocol"); }
394
395 void open (const char *, int) override;
396
397 bool can_create_inferior () override { return true; }
398 void create_inferior (const char *, const std::string &,
399 char **, int) override;
400
401 void detach (inferior *, int) override;
402
403 bool can_attach () override { return true; }
404 void attach (const char *, int) override;
405
406 void post_attach (int) override;
407 int supports_disable_randomization () override;
408};
409
94585166
DB
410/* Per-program-space data key. */
411static const struct program_space_data *remote_pspace_data;
412
413/* The variable registered as the control variable used by the
414 remote exec-file commands. While the remote exec-file setting is
415 per-program-space, the set/show machinery uses this as the
416 location of the remote exec-file value. */
417static char *remote_exec_file_var;
418
6765f3e5
DJ
419/* The size to align memory write packets, when practical. The protocol
420 does not guarantee any alignment, and gdb will generate short
421 writes and unaligned writes, but even as a best-effort attempt this
422 can improve bulk transfers. For instance, if a write is misaligned
423 relative to the target's data bus, the stub may need to make an extra
424 round trip fetching data from the target. This doesn't make a
425 huge difference, but it's easy to do, so we try to be helpful.
426
427 The alignment chosen is arbitrary; usually data bus width is
428 important here, not the possibly larger cache line size. */
429enum { REMOTE_ALIGN_WRITES = 16 };
430
23860348 431/* Prototypes for local functions. */
6d820c5c 432static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
74531fed 433static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
fee9eda9 434 int forever, int *is_notif);
6426a772 435
cbb8991c
DB
436struct remote_state;
437
438static int remote_vkill (int pid, struct remote_state *rs);
439
8020350c
DB
440static void remote_kill_k (void);
441
a14ed312 442static int readchar (int timeout);
c906108c 443
c33e31fd
PA
444static void remote_serial_write (const char *str, int len);
445
a14ed312 446static void interrupt_query (void);
c906108c 447
d62a8ae2
SM
448static void set_general_thread (ptid_t ptid);
449static void set_continue_thread (ptid_t ptid);
c906108c 450
a14ed312 451static void get_offsets (void);
c906108c 452
6d820c5c
DJ
453static void skip_frame (void);
454
455static long read_frame (char **buf_p, long *sizeof_buf);
c906108c 456
a14ed312 457static int hexnumlen (ULONGEST num);
c906108c 458
a14ed312 459static int stubhex (int ch);
c906108c 460
a14ed312 461static int hexnumstr (char *, ULONGEST);
c906108c 462
a14ed312 463static int hexnumnstr (char *, ULONGEST, int);
2df3850c 464
a14ed312 465static CORE_ADDR remote_address_masked (CORE_ADDR);
c906108c 466
baa336ce 467static void print_packet (const char *);
c906108c 468
a14ed312 469static int stub_unpack_int (char *buff, int fieldlength);
c906108c 470
39f77062 471static ptid_t remote_current_thread (ptid_t oldptid);
c906108c 472
baa336ce 473static int putpkt_binary (const char *buf, int cnt);
c906108c 474
a14ed312 475static void check_binary_download (CORE_ADDR addr);
c906108c 476
5a2468f5 477struct packet_config;
5a2468f5 478
a14ed312 479static void show_packet_config_cmd (struct packet_config *config);
5a2468f5 480
bb572ddd
DJ
481static void show_remote_protocol_packet_cmd (struct ui_file *file,
482 int from_tty,
483 struct cmd_list_element *c,
484 const char *value);
485
82f73884 486static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
256642e8 487static ptid_t read_ptid (const char *buf, const char **obuf);
82f73884 488
c8d104ad
PA
489static void remote_query_supported (void);
490
36d25514 491static void remote_check_symbols (void);
c8d104ad 492
74531fed 493struct stop_reply;
74531fed 494static void stop_reply_xfree (struct stop_reply *);
722247f1 495static void remote_parse_stop_reply (char *, struct stop_reply *);
74531fed 496static void push_stop_reply (struct stop_reply *);
bcc75809 497static void discard_pending_stop_replies_in_queue (struct remote_state *);
74531fed
PA
498static int peek_stop_reply (ptid_t ptid);
499
cbb8991c
DB
500struct threads_listing_context;
501static void remove_new_fork_children (struct threads_listing_context *);
502
74531fed 503static void remote_async_inferior_event_handler (gdb_client_data);
74531fed 504
d962ef82
DJ
505static int remote_read_description_p (struct target_ops *target);
506
176a6961 507static void remote_console_output (char *msg);
dde08ee1 508
f4abbc16
MM
509static void remote_btrace_reset (void);
510
c0272db5
TW
511static void remote_btrace_maybe_reopen (void);
512
221e1a37
PA
513static int stop_reply_queue_length (void);
514
80152258
PA
515static void readahead_cache_invalidate (void);
516
048094ac
PA
517static void remote_unpush_and_throw (void);
518
b6bb3468
PA
519static struct remote_state *get_remote_state (void);
520
a6b151f1
DJ
521/* For "remote". */
522
523static struct cmd_list_element *remote_cmdlist;
524
bb572ddd
DJ
525/* For "set remote" and "show remote". */
526
527static struct cmd_list_element *remote_set_cmdlist;
528static struct cmd_list_element *remote_show_cmdlist;
529
d458bd84
PA
530/* Stub vCont actions support.
531
532 Each field is a boolean flag indicating whether the stub reports
533 support for the corresponding action. */
534
535struct vCont_action_support
536{
537 /* vCont;t */
538 int t;
c1e36e3e
PA
539
540 /* vCont;r */
541 int r;
750ce8d1
YQ
542
543 /* vCont;s */
544 int s;
545
546 /* vCont;S */
547 int S;
d458bd84
PA
548};
549
c1e36e3e
PA
550/* Controls whether GDB is willing to use range stepping. */
551
552static int use_range_stepping = 1;
553
0d031856
TT
554#define OPAQUETHREADBYTES 8
555
556/* a 64 bit opaque identifier */
557typedef unsigned char threadref[OPAQUETHREADBYTES];
558
559/* About this many threadisds fit in a packet. */
560
561#define MAXTHREADLISTRESULTS 32
562
6f8976bf
YQ
563/* The max number of chars in debug output. The rest of chars are
564 omitted. */
565
566#define REMOTE_DEBUG_MAX_CHAR 512
567
80152258
PA
568/* Data for the vFile:pread readahead cache. */
569
570struct readahead_cache
571{
572 /* The file descriptor for the file that is being cached. -1 if the
573 cache is invalid. */
574 int fd;
575
576 /* The offset into the file that the cache buffer corresponds
577 to. */
578 ULONGEST offset;
579
580 /* The buffer holding the cache contents. */
581 gdb_byte *buf;
582 /* The buffer's size. We try to read as much as fits into a packet
583 at a time. */
584 size_t bufsize;
585
586 /* Cache hit and miss counters. */
587 ULONGEST hit_count;
588 ULONGEST miss_count;
589};
590
ea9c271d
DJ
591/* Description of the remote protocol state for the currently
592 connected target. This is per-target state, and independent of the
593 selected architecture. */
594
595struct remote_state
596{
597 /* A buffer to use for incoming packets, and its current size. The
598 buffer is grown dynamically for larger incoming packets.
599 Outgoing packets may also be constructed in this buffer.
600 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
601 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
602 packets. */
603 char *buf;
604 long buf_size;
be2a5f71 605
1e51243a
PA
606 /* True if we're going through initial connection setup (finding out
607 about the remote side's threads, relocating symbols, etc.). */
608 int starting_up;
609
be2a5f71
DJ
610 /* If we negotiated packet size explicitly (and thus can bypass
611 heuristics for the largest packet size that will not overflow
612 a buffer in the stub), this will be set to that packet size.
613 Otherwise zero, meaning to use the guessed size. */
614 long explicit_packet_size;
2d717e4f
DJ
615
616 /* remote_wait is normally called when the target is running and
617 waits for a stop reply packet. But sometimes we need to call it
618 when the target is already stopped. We can send a "?" packet
619 and have remote_wait read the response. Or, if we already have
620 the response, we can stash it in BUF and tell remote_wait to
621 skip calling getpkt. This flag is set when BUF contains a
622 stop reply packet and the target is not waiting. */
623 int cached_wait_status;
a6f3e723
SL
624
625 /* True, if in no ack mode. That is, neither GDB nor the stub will
626 expect acks from each other. The connection is assumed to be
627 reliable. */
628 int noack_mode;
82f73884
PA
629
630 /* True if we're connected in extended remote mode. */
631 int extended;
632
e24a49d8
PA
633 /* True if we resumed the target and we're waiting for the target to
634 stop. In the mean time, we can't start another command/query.
635 The remote server wouldn't be ready to process it, so we'd
636 timeout waiting for a reply that would never come and eventually
637 we'd close the connection. This can happen in asynchronous mode
638 because we allow GDB commands while the target is running. */
639 int waiting_for_stop_reply;
74531fed 640
d458bd84
PA
641 /* The status of the stub support for the various vCont actions. */
642 struct vCont_action_support supports_vCont;
782b2b07 643
3a29589a
DJ
644 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
645 responded to that. */
646 int ctrlc_pending_p;
5d93a237 647
048094ac
PA
648 /* True if we saw a Ctrl-C while reading or writing from/to the
649 remote descriptor. At that point it is not safe to send a remote
650 interrupt packet, so we instead remember we saw the Ctrl-C and
651 process it once we're done with sending/receiving the current
652 packet, which should be shortly. If however that takes too long,
653 and the user presses Ctrl-C again, we offer to disconnect. */
654 int got_ctrlc_during_io;
655
5d93a237
TT
656 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
657 remote_open knows that we don't have a file open when the program
658 starts. */
659 struct serial *remote_desc;
47f8a51d
TT
660
661 /* These are the threads which we last sent to the remote system. The
662 TID member will be -1 for all or -2 for not sent yet. */
663 ptid_t general_thread;
664 ptid_t continue_thread;
262e1174
TT
665
666 /* This is the traceframe which we last selected on the remote system.
667 It will be -1 if no traceframe is selected. */
668 int remote_traceframe_number;
747dc59d
TT
669
670 char *last_pass_packet;
5e4a05c4
TT
671
672 /* The last QProgramSignals packet sent to the target. We bypass
673 sending a new program signals list down to the target if the new
674 packet is exactly the same as the last we sent. IOW, we only let
675 the target know about program signals list changes. */
676 char *last_program_signals_packet;
b73be471
TT
677
678 enum gdb_signal last_sent_signal;
280ceea3
TT
679
680 int last_sent_step;
8e88304f 681
3a00c802
PA
682 /* The execution direction of the last resume we got. */
683 enum exec_direction_kind last_resume_exec_dir;
684
8e88304f
TT
685 char *finished_object;
686 char *finished_annex;
687 ULONGEST finished_offset;
b80fafe3
TT
688
689 /* Should we try the 'ThreadInfo' query packet?
690
691 This variable (NOT available to the user: auto-detect only!)
692 determines whether GDB will use the new, simpler "ThreadInfo"
693 query or the older, more complex syntax for thread queries.
694 This is an auto-detect variable (set to true at each connect,
695 and set to false when the target fails to recognize it). */
696 int use_threadinfo_query;
697 int use_threadextra_query;
88b496c3 698
0d031856
TT
699 threadref echo_nextthread;
700 threadref nextthread;
701 threadref resultthreadlist[MAXTHREADLISTRESULTS];
5965e028
YQ
702
703 /* The state of remote notification. */
704 struct remote_notif_state *notif_state;
f4abbc16
MM
705
706 /* The branch trace configuration. */
707 struct btrace_config btrace_config;
15a201c8
GB
708
709 /* The argument to the last "vFile:setfs:" packet we sent, used
710 to avoid sending repeated unnecessary "vFile:setfs:" packets.
711 Initialized to -1 to indicate that no "vFile:setfs:" packet
712 has yet been sent. */
713 int fs_pid;
80152258
PA
714
715 /* A readahead cache for vFile:pread. Often, reading a binary
716 involves a sequence of small reads. E.g., when parsing an ELF
717 file. A readahead cache helps mostly the case of remote
718 debugging on a connection with higher latency, due to the
719 request/reply nature of the RSP. We only cache data for a single
720 file descriptor at a time. */
721 struct readahead_cache readahead_cache;
ea9c271d
DJ
722};
723
7aabaf9d
SM
724/* Private data that we'll store in (struct thread_info)->priv. */
725struct remote_thread_info : public private_thread_info
dc146f7c 726{
7aabaf9d
SM
727 std::string extra;
728 std::string name;
729 int core = -1;
799a2abe 730
f6327dcb
KB
731 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
732 sequence of bytes. */
7aabaf9d 733 gdb::byte_vector thread_handle;
f6327dcb 734
799a2abe 735 /* Whether the target stopped for a breakpoint/watchpoint. */
7aabaf9d 736 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
799a2abe
PA
737
738 /* This is set to the data address of the access causing the target
739 to stop for a watchpoint. */
7aabaf9d 740 CORE_ADDR watch_data_address = 0;
85ad3aaf
PA
741
742 /* Fields used by the vCont action coalescing implemented in
743 remote_resume / remote_commit_resume. remote_resume stores each
744 thread's last resume request in these fields, so that a later
745 remote_commit_resume knows which is the proper action for this
746 thread to include in the vCont packet. */
747
748 /* True if the last target_resume call for this thread was a step
749 request, false if a continue request. */
7aabaf9d 750 int last_resume_step = 0;
85ad3aaf
PA
751
752 /* The signal specified in the last target_resume call for this
753 thread. */
7aabaf9d 754 gdb_signal last_resume_sig = GDB_SIGNAL_0;
85ad3aaf
PA
755
756 /* Whether this thread was already vCont-resumed on the remote
757 side. */
7aabaf9d 758 int vcont_resumed = 0;
dc146f7c
VP
759};
760
ea9c271d
DJ
761/* This data could be associated with a target, but we do not always
762 have access to the current target when we need it, so for now it is
763 static. This will be fine for as long as only one target is in use
764 at a time. */
cf792862 765static struct remote_state *remote_state;
ea9c271d
DJ
766
767static struct remote_state *
0b83947e 768get_remote_state_raw (void)
ea9c271d 769{
cf792862
TT
770 return remote_state;
771}
772
773/* Allocate a new struct remote_state with xmalloc, initialize it, and
774 return it. */
775
776static struct remote_state *
777new_remote_state (void)
778{
779 struct remote_state *result = XCNEW (struct remote_state);
780
781 /* The default buffer size is unimportant; it will be expanded
782 whenever a larger buffer is needed. */
783 result->buf_size = 400;
224c3ddb 784 result->buf = (char *) xmalloc (result->buf_size);
262e1174 785 result->remote_traceframe_number = -1;
b73be471 786 result->last_sent_signal = GDB_SIGNAL_0;
3a00c802 787 result->last_resume_exec_dir = EXEC_FORWARD;
15a201c8 788 result->fs_pid = -1;
cf792862
TT
789
790 return result;
ea9c271d
DJ
791}
792
793/* Description of the remote protocol for a given architecture. */
d01949b6 794
ad10f812
AC
795struct packet_reg
796{
797 long offset; /* Offset into G packet. */
798 long regnum; /* GDB's internal register number. */
799 LONGEST pnum; /* Remote protocol register number. */
b323314b 800 int in_g_packet; /* Always part of G packet. */
f5656ead 801 /* long size in bytes; == register_size (target_gdbarch (), regnum);
23860348 802 at present. */
f5656ead 803 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
c9f4d572 804 at present. */
ad10f812
AC
805};
806
ea9c271d 807struct remote_arch_state
d01949b6 808{
ad10f812
AC
809 /* Description of the remote protocol registers. */
810 long sizeof_g_packet;
b323314b
AC
811
812 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 813 (making an array gdbarch_num_regs in size). */
b323314b 814 struct packet_reg *regs;
ad10f812 815
d01949b6
AC
816 /* This is the size (in chars) of the first response to the ``g''
817 packet. It is used as a heuristic when determining the maximum
818 size of memory-read and memory-write packets. A target will
819 typically only reserve a buffer large enough to hold the ``g''
820 packet. The size does not include packet overhead (headers and
23860348 821 trailers). */
d01949b6
AC
822 long actual_register_packet_size;
823
824 /* This is the maximum size (in chars) of a non read/write packet.
23860348 825 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
826 long remote_packet_size;
827};
828
35b1e5cc
SS
829/* Utility: generate error from an incoming stub packet. */
830static void
831trace_error (char *buf)
832{
833 if (*buf++ != 'E')
834 return; /* not an error msg */
835 switch (*buf)
836 {
837 case '1': /* malformed packet error */
838 if (*++buf == '0') /* general case: */
839 error (_("remote.c: error in outgoing packet."));
840 else
841 error (_("remote.c: error in outgoing packet at field #%ld."),
842 strtol (buf, NULL, 16));
35b1e5cc
SS
843 default:
844 error (_("Target returns error code '%s'."), buf);
845 }
846}
847
848/* Utility: wait for reply from stub, while accepting "O" packets. */
b6bb3468 849
35b1e5cc 850static char *
b6bb3468 851remote_get_noisy_reply ()
35b1e5cc 852{
b6bb3468
PA
853 struct remote_state *rs = get_remote_state ();
854
35b1e5cc
SS
855 do /* Loop on reply from remote stub. */
856 {
857 char *buf;
a744cf53 858
0df8b418 859 QUIT; /* Allow user to bail out with ^C. */
b6bb3468
PA
860 getpkt (&rs->buf, &rs->buf_size, 0);
861 buf = rs->buf;
ad91cd99 862 if (buf[0] == 'E')
35b1e5cc 863 trace_error (buf);
61012eef 864 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
865 {
866 ULONGEST ul;
867 CORE_ADDR from, to, org_to;
256642e8 868 const char *p, *pp;
dde08ee1 869 int adjusted_size = 0;
7556d4a4 870 int relocated = 0;
dde08ee1
PA
871
872 p = buf + strlen ("qRelocInsn:");
873 pp = unpack_varlen_hex (p, &ul);
874 if (*pp != ';')
cb91c06a 875 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
876 from = ul;
877
878 p = pp + 1;
a9cbf802 879 unpack_varlen_hex (p, &ul);
dde08ee1
PA
880 to = ul;
881
882 org_to = to;
883
492d29ea 884 TRY
dde08ee1 885 {
f5656ead 886 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 887 relocated = 1;
dde08ee1 888 }
492d29ea 889 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
890 {
891 if (ex.error == MEMORY_ERROR)
892 {
893 /* Propagate memory errors silently back to the
894 target. The stub may have limited the range of
895 addresses we can write to, for example. */
896 }
897 else
898 {
899 /* Something unexpectedly bad happened. Be verbose
900 so we can tell what, and propagate the error back
901 to the stub, so it doesn't get stuck waiting for
902 a response. */
903 exception_fprintf (gdb_stderr, ex,
904 _("warning: relocating instruction: "));
905 }
906 putpkt ("E01");
907 }
492d29ea 908 END_CATCH
7556d4a4
PA
909
910 if (relocated)
dde08ee1
PA
911 {
912 adjusted_size = to - org_to;
913
b6bb3468 914 xsnprintf (buf, rs->buf_size, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
915 putpkt (buf);
916 }
dde08ee1 917 }
ad91cd99 918 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
919 remote_console_output (buf + 1); /* 'O' message from stub */
920 else
0df8b418 921 return buf; /* Here's the actual reply. */
35b1e5cc
SS
922 }
923 while (1);
924}
3c3bea1c 925
d01949b6
AC
926/* Handle for retreving the remote protocol data from gdbarch. */
927static struct gdbarch_data *remote_gdbarch_data_handle;
928
ea9c271d 929static struct remote_arch_state *
5cd63fda 930get_remote_arch_state (struct gdbarch *gdbarch)
d01949b6 931{
5cd63fda 932 gdb_assert (gdbarch != NULL);
19ba03f4 933 return ((struct remote_arch_state *)
5cd63fda 934 gdbarch_data (gdbarch, remote_gdbarch_data_handle));
d01949b6
AC
935}
936
0b83947e
DJ
937/* Fetch the global remote target state. */
938
939static struct remote_state *
940get_remote_state (void)
941{
942 /* Make sure that the remote architecture state has been
943 initialized, because doing so might reallocate rs->buf. Any
944 function which calls getpkt also needs to be mindful of changes
945 to rs->buf, but this call limits the number of places which run
946 into trouble. */
5cd63fda 947 get_remote_arch_state (target_gdbarch ());
0b83947e
DJ
948
949 return get_remote_state_raw ();
950}
951
94585166
DB
952/* Cleanup routine for the remote module's pspace data. */
953
954static void
955remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
956{
19ba03f4 957 char *remote_exec_file = (char *) arg;
94585166
DB
958
959 xfree (remote_exec_file);
960}
961
962/* Fetch the remote exec-file from the current program space. */
963
964static const char *
965get_remote_exec_file (void)
966{
967 char *remote_exec_file;
968
19ba03f4
SM
969 remote_exec_file
970 = (char *) program_space_data (current_program_space,
971 remote_pspace_data);
94585166
DB
972 if (remote_exec_file == NULL)
973 return "";
974
975 return remote_exec_file;
976}
977
978/* Set the remote exec file for PSPACE. */
979
980static void
981set_pspace_remote_exec_file (struct program_space *pspace,
982 char *remote_exec_file)
983{
19ba03f4 984 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
94585166
DB
985
986 xfree (old_file);
987 set_program_space_data (pspace, remote_pspace_data,
988 xstrdup (remote_exec_file));
989}
990
991/* The "set/show remote exec-file" set command hook. */
992
993static void
eb4c3f4a 994set_remote_exec_file (const char *ignored, int from_tty,
94585166
DB
995 struct cmd_list_element *c)
996{
997 gdb_assert (remote_exec_file_var != NULL);
998 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
999}
1000
1001/* The "set/show remote exec-file" show command hook. */
1002
1003static void
1004show_remote_exec_file (struct ui_file *file, int from_tty,
1005 struct cmd_list_element *cmd, const char *value)
1006{
1007 fprintf_filtered (file, "%s\n", remote_exec_file_var);
1008}
1009
74ca34ce
DJ
1010static int
1011compare_pnums (const void *lhs_, const void *rhs_)
1012{
19ba03f4
SM
1013 const struct packet_reg * const *lhs
1014 = (const struct packet_reg * const *) lhs_;
1015 const struct packet_reg * const *rhs
1016 = (const struct packet_reg * const *) rhs_;
74ca34ce
DJ
1017
1018 if ((*lhs)->pnum < (*rhs)->pnum)
1019 return -1;
1020 else if ((*lhs)->pnum == (*rhs)->pnum)
1021 return 0;
1022 else
1023 return 1;
1024}
1025
c21236dc
PA
1026static int
1027map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 1028{
74ca34ce 1029 int regnum, num_remote_regs, offset;
74ca34ce 1030 struct packet_reg **remote_regs;
ea9c271d 1031
4a22f64d 1032 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 1033 {
c21236dc 1034 struct packet_reg *r = &regs[regnum];
baef701f 1035
4a22f64d 1036 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
1037 /* Do not try to fetch zero-sized (placeholder) registers. */
1038 r->pnum = -1;
1039 else
1040 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1041
b323314b 1042 r->regnum = regnum;
74ca34ce
DJ
1043 }
1044
1045 /* Define the g/G packet format as the contents of each register
1046 with a remote protocol number, in order of ascending protocol
1047 number. */
1048
224c3ddb 1049 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 1050 for (num_remote_regs = 0, regnum = 0;
4a22f64d 1051 regnum < gdbarch_num_regs (gdbarch);
f57d151a 1052 regnum++)
c21236dc
PA
1053 if (regs[regnum].pnum != -1)
1054 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 1055
74ca34ce
DJ
1056 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
1057 compare_pnums);
1058
1059 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1060 {
1061 remote_regs[regnum]->in_g_packet = 1;
1062 remote_regs[regnum]->offset = offset;
4a22f64d 1063 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
1064 }
1065
c21236dc
PA
1066 return offset;
1067}
1068
1069/* Given the architecture described by GDBARCH, return the remote
1070 protocol register's number and the register's offset in the g/G
1071 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1072 If the target does not have a mapping for REGNUM, return false,
1073 otherwise, return true. */
1074
1075int
1076remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1077 int *pnum, int *poffset)
1078{
c21236dc
PA
1079 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1080
b80406ac 1081 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
c21236dc 1082
b80406ac 1083 map_regcache_remote_table (gdbarch, regs.data ());
c21236dc
PA
1084
1085 *pnum = regs[regnum].pnum;
1086 *poffset = regs[regnum].offset;
1087
c21236dc
PA
1088 return *pnum != -1;
1089}
1090
1091static void *
1092init_remote_state (struct gdbarch *gdbarch)
1093{
1094 struct remote_state *rs = get_remote_state_raw ();
1095 struct remote_arch_state *rsa;
1096
1097 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
1098
1099 /* Use the architecture to build a regnum<->pnum table, which will be
1100 1:1 unless a feature set specifies otherwise. */
1101 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
1102 gdbarch_num_regs (gdbarch),
1103 struct packet_reg);
1104
74ca34ce
DJ
1105 /* Record the maximum possible size of the g packet - it may turn out
1106 to be smaller. */
c21236dc 1107 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 1108
0df8b418 1109 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
1110 remote stubs have a hardwired buffer size of 400 bytes
1111 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1112 as the maximum packet-size to ensure that the packet and an extra
1113 NUL character can always fit in the buffer. This stops GDB
1114 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
1115 already a full buffer (As of 1999-12-04 that was most stubs). */
1116 rsa->remote_packet_size = 400 - 1;
d01949b6 1117
ea9c271d
DJ
1118 /* This one is filled in when a ``g'' packet is received. */
1119 rsa->actual_register_packet_size = 0;
1120
1121 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
1122 default, adjust the size accordingly. Remember that each byte is
1123 encoded as two characters. 32 is the overhead for the packet
1124 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 1125 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 1126 little. */
ea9c271d
DJ
1127 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
1128 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 1129
ea9c271d
DJ
1130 /* Make sure that the packet buffer is plenty big enough for
1131 this architecture. */
1132 if (rs->buf_size < rsa->remote_packet_size)
1133 {
1134 rs->buf_size = 2 * rsa->remote_packet_size;
224c3ddb 1135 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
ea9c271d 1136 }
6d820c5c 1137
ea9c271d
DJ
1138 return rsa;
1139}
1140
1141/* Return the current allowed size of a remote packet. This is
1142 inferred from the current architecture, and should be used to
1143 limit the length of outgoing packets. */
1144static long
1145get_remote_packet_size (void)
1146{
be2a5f71 1147 struct remote_state *rs = get_remote_state ();
5cd63fda 1148 remote_arch_state *rsa = get_remote_arch_state (target_gdbarch ());
ea9c271d 1149
be2a5f71
DJ
1150 if (rs->explicit_packet_size)
1151 return rs->explicit_packet_size;
1152
ea9c271d 1153 return rsa->remote_packet_size;
d01949b6
AC
1154}
1155
ad10f812 1156static struct packet_reg *
5cd63fda
PA
1157packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1158 long regnum)
ad10f812 1159{
5cd63fda 1160 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
b323314b
AC
1161 return NULL;
1162 else
ad10f812 1163 {
ea9c271d 1164 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 1165
b323314b
AC
1166 gdb_assert (r->regnum == regnum);
1167 return r;
ad10f812 1168 }
ad10f812
AC
1169}
1170
1171static struct packet_reg *
5cd63fda
PA
1172packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1173 LONGEST pnum)
ad10f812 1174{
b323314b 1175 int i;
a744cf53 1176
5cd63fda 1177 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
ad10f812 1178 {
ea9c271d 1179 struct packet_reg *r = &rsa->regs[i];
a744cf53 1180
b323314b
AC
1181 if (r->pnum == pnum)
1182 return r;
ad10f812
AC
1183 }
1184 return NULL;
d01949b6
AC
1185}
1186
f6ac5f3d 1187static remote_target remote_ops;
c906108c 1188
f6ac5f3d 1189static extended_remote_target extended_remote_ops;
c906108c 1190
6426a772
JM
1191/* FIXME: cagney/1999-09-23: Even though getpkt was called with
1192 ``forever'' still use the normal timeout mechanism. This is
1193 currently used by the ASYNC code to guarentee that target reads
1194 during the initial connect always time-out. Once getpkt has been
1195 modified to return a timeout indication and, in turn
1196 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 1197 this can go away. */
6426a772
JM
1198static int wait_forever_enabled_p = 1;
1199
9a7071a8
JB
1200/* Allow the user to specify what sequence to send to the remote
1201 when he requests a program interruption: Although ^C is usually
1202 what remote systems expect (this is the default, here), it is
1203 sometimes preferable to send a break. On other systems such
1204 as the Linux kernel, a break followed by g, which is Magic SysRq g
1205 is required in order to interrupt the execution. */
1206const char interrupt_sequence_control_c[] = "Ctrl-C";
1207const char interrupt_sequence_break[] = "BREAK";
1208const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 1209static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
1210 {
1211 interrupt_sequence_control_c,
1212 interrupt_sequence_break,
1213 interrupt_sequence_break_g,
1214 NULL
1215 };
1216static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1217
1218static void
1219show_interrupt_sequence (struct ui_file *file, int from_tty,
1220 struct cmd_list_element *c,
1221 const char *value)
1222{
1223 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1224 fprintf_filtered (file,
1225 _("Send the ASCII ETX character (Ctrl-c) "
1226 "to the remote target to interrupt the "
1227 "execution of the program.\n"));
1228 else if (interrupt_sequence_mode == interrupt_sequence_break)
1229 fprintf_filtered (file,
1230 _("send a break signal to the remote target "
1231 "to interrupt the execution of the program.\n"));
1232 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1233 fprintf_filtered (file,
1234 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1235 "the remote target to interrupt the execution "
1236 "of Linux kernel.\n"));
1237 else
1238 internal_error (__FILE__, __LINE__,
1239 _("Invalid value for interrupt_sequence_mode: %s."),
1240 interrupt_sequence_mode);
1241}
6426a772 1242
9a7071a8
JB
1243/* This boolean variable specifies whether interrupt_sequence is sent
1244 to the remote target when gdb connects to it.
1245 This is mostly needed when you debug the Linux kernel: The Linux kernel
1246 expects BREAK g which is Magic SysRq g for connecting gdb. */
1247static int interrupt_on_connect = 0;
c906108c 1248
9a7071a8
JB
1249/* This variable is used to implement the "set/show remotebreak" commands.
1250 Since these commands are now deprecated in favor of "set/show remote
1251 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
1252static int remote_break;
1253
9a7071a8 1254static void
eb4c3f4a 1255set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
9a7071a8
JB
1256{
1257 if (remote_break)
1258 interrupt_sequence_mode = interrupt_sequence_break;
1259 else
1260 interrupt_sequence_mode = interrupt_sequence_control_c;
1261}
1262
1263static void
1264show_remotebreak (struct ui_file *file, int from_tty,
1265 struct cmd_list_element *c,
1266 const char *value)
1267{
1268}
1269
c906108c
SS
1270/* This variable sets the number of bits in an address that are to be
1271 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 1272 leading zeros, the entire address would be sent. This variable
c906108c
SS
1273 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1274 initial implementation of remote.c restricted the address sent in
1275 memory packets to ``host::sizeof long'' bytes - (typically 32
1276 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1277 address was never sent. Since fixing this bug may cause a break in
1278 some remote targets this variable is principly provided to
23860348 1279 facilitate backward compatibility. */
c906108c 1280
883b9c6c 1281static unsigned int remote_address_size;
c906108c 1282
11cf8741 1283\f
11cf8741 1284/* User configurable variables for the number of characters in a
ea9c271d
DJ
1285 memory read/write packet. MIN (rsa->remote_packet_size,
1286 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 1287 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
1288 (speed up transfers). The variables ``preferred_*'' (the user
1289 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 1290 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
1291
1292struct memory_packet_config
1293{
a121b7c1 1294 const char *name;
11cf8741
JM
1295 long size;
1296 int fixed_p;
1297};
1298
a5c0808e
PA
1299/* The default max memory-write-packet-size. The 16k is historical.
1300 (It came from older GDB's using alloca for buffers and the
1301 knowledge (folklore?) that some hosts don't cope very well with
1302 large alloca calls.) */
1303#define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1304
1305/* The minimum remote packet size for memory transfers. Ensures we
1306 can write at least one byte. */
1307#define MIN_MEMORY_PACKET_SIZE 20
1308
11cf8741
JM
1309/* Compute the current size of a read/write packet. Since this makes
1310 use of ``actual_register_packet_size'' the computation is dynamic. */
1311
1312static long
1313get_memory_packet_size (struct memory_packet_config *config)
1314{
d01949b6 1315 struct remote_state *rs = get_remote_state ();
5cd63fda 1316 remote_arch_state *rsa = get_remote_arch_state (target_gdbarch ());
ea9c271d 1317
11cf8741
JM
1318 long what_they_get;
1319 if (config->fixed_p)
1320 {
1321 if (config->size <= 0)
a5c0808e 1322 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
11cf8741
JM
1323 else
1324 what_they_get = config->size;
1325 }
1326 else
1327 {
ea9c271d 1328 what_they_get = get_remote_packet_size ();
23860348 1329 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1330 if (config->size > 0
1331 && what_they_get > config->size)
1332 what_they_get = config->size;
be2a5f71
DJ
1333
1334 /* Limit it to the size of the targets ``g'' response unless we have
1335 permission from the stub to use a larger packet size. */
1336 if (rs->explicit_packet_size == 0
1337 && rsa->actual_register_packet_size > 0
1338 && what_they_get > rsa->actual_register_packet_size)
1339 what_they_get = rsa->actual_register_packet_size;
11cf8741 1340 }
a5c0808e
PA
1341 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1342 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1343
1344 /* Make sure there is room in the global buffer for this packet
1345 (including its trailing NUL byte). */
1346 if (rs->buf_size < what_they_get + 1)
1347 {
1348 rs->buf_size = 2 * what_they_get;
224c3ddb 1349 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
6d820c5c
DJ
1350 }
1351
11cf8741
JM
1352 return what_they_get;
1353}
1354
0df8b418 1355/* Update the size of a read/write packet. If they user wants
23860348 1356 something really big then do a sanity check. */
11cf8741
JM
1357
1358static void
ac88e2de 1359set_memory_packet_size (const char *args, struct memory_packet_config *config)
11cf8741
JM
1360{
1361 int fixed_p = config->fixed_p;
1362 long size = config->size;
a744cf53 1363
11cf8741 1364 if (args == NULL)
8a3fe4f8 1365 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1366 else if (strcmp (args, "hard") == 0
1367 || strcmp (args, "fixed") == 0)
1368 fixed_p = 1;
1369 else if (strcmp (args, "soft") == 0
1370 || strcmp (args, "limit") == 0)
1371 fixed_p = 0;
1372 else
1373 {
1374 char *end;
a744cf53 1375
11cf8741
JM
1376 size = strtoul (args, &end, 0);
1377 if (args == end)
8a3fe4f8 1378 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1379
1380 /* Instead of explicitly capping the size of a packet to or
1381 disallowing it, the user is allowed to set the size to
1382 something arbitrarily large. */
11cf8741 1383 }
a5c0808e
PA
1384
1385 /* So that the query shows the correct value. */
1386 if (size <= 0)
1387 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1388
23860348 1389 /* Extra checks? */
11cf8741
JM
1390 if (fixed_p && !config->fixed_p)
1391 {
e2e0b3e5
AC
1392 if (! query (_("The target may not be able to correctly handle a %s\n"
1393 "of %ld bytes. Change the packet size? "),
11cf8741 1394 config->name, size))
8a3fe4f8 1395 error (_("Packet size not changed."));
11cf8741 1396 }
23860348 1397 /* Update the config. */
11cf8741
JM
1398 config->fixed_p = fixed_p;
1399 config->size = size;
1400}
1401
1402static void
1403show_memory_packet_size (struct memory_packet_config *config)
1404{
a3f17187 1405 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1406 if (config->fixed_p)
a3f17187 1407 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
1408 get_memory_packet_size (config));
1409 else
a3f17187 1410 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
1411 get_memory_packet_size (config));
1412}
1413
1414static struct memory_packet_config memory_write_packet_config =
1415{
1416 "memory-write-packet-size",
1417};
1418
1419static void
ac88e2de 1420set_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1421{
1422 set_memory_packet_size (args, &memory_write_packet_config);
1423}
1424
1425static void
ac88e2de 1426show_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1427{
1428 show_memory_packet_size (&memory_write_packet_config);
1429}
1430
1431static long
1432get_memory_write_packet_size (void)
1433{
1434 return get_memory_packet_size (&memory_write_packet_config);
1435}
1436
1437static struct memory_packet_config memory_read_packet_config =
1438{
1439 "memory-read-packet-size",
1440};
1441
1442static void
ac88e2de 1443set_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1444{
1445 set_memory_packet_size (args, &memory_read_packet_config);
1446}
1447
1448static void
ac88e2de 1449show_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1450{
1451 show_memory_packet_size (&memory_read_packet_config);
1452}
1453
1454static long
1455get_memory_read_packet_size (void)
1456{
1457 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1458
11cf8741
JM
1459 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1460 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1461 increased beyond this. */
1462 if (size > get_remote_packet_size ())
1463 size = get_remote_packet_size ();
11cf8741
JM
1464 return size;
1465}
1466
11cf8741 1467\f
5a2468f5 1468/* Generic configuration support for packets the stub optionally
0df8b418 1469 supports. Allows the user to specify the use of the packet as well
23860348 1470 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1471
1472enum packet_support
1473 {
1474 PACKET_SUPPORT_UNKNOWN = 0,
1475 PACKET_ENABLE,
1476 PACKET_DISABLE
1477 };
1478
5a2468f5
JM
1479struct packet_config
1480 {
bb572ddd
DJ
1481 const char *name;
1482 const char *title;
4082afcc
PA
1483
1484 /* If auto, GDB auto-detects support for this packet or feature,
1485 either through qSupported, or by trying the packet and looking
1486 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1487 packet. If false, the packet is disabled. Configs that don't
1488 have an associated command always have this set to auto. */
7f19b9a2 1489 enum auto_boolean detect;
4082afcc
PA
1490
1491 /* Does the target support this packet? */
5a2468f5
JM
1492 enum packet_support support;
1493 };
1494
d471ea57 1495/* Analyze a packet's return value and update the packet config
23860348 1496 accordingly. */
d471ea57
AC
1497
1498enum packet_result
1499{
1500 PACKET_ERROR,
1501 PACKET_OK,
1502 PACKET_UNKNOWN
1503};
1504
4082afcc
PA
1505static enum packet_support packet_config_support (struct packet_config *config);
1506static enum packet_support packet_support (int packet);
5a2468f5
JM
1507
1508static void
fba45db2 1509show_packet_config_cmd (struct packet_config *config)
5a2468f5 1510{
a121b7c1 1511 const char *support = "internal-error";
a744cf53 1512
4082afcc 1513 switch (packet_config_support (config))
5a2468f5
JM
1514 {
1515 case PACKET_ENABLE:
1516 support = "enabled";
1517 break;
1518 case PACKET_DISABLE:
1519 support = "disabled";
1520 break;
1521 case PACKET_SUPPORT_UNKNOWN:
1522 support = "unknown";
1523 break;
1524 }
1525 switch (config->detect)
1526 {
7f19b9a2 1527 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1528 printf_filtered (_("Support for the `%s' packet "
1529 "is auto-detected, currently %s.\n"),
37a105a1 1530 config->name, support);
5a2468f5 1531 break;
7f19b9a2
AC
1532 case AUTO_BOOLEAN_TRUE:
1533 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1534 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1535 config->name, support);
8e248173 1536 break;
5a2468f5
JM
1537 }
1538}
1539
1540static void
bb572ddd
DJ
1541add_packet_config_cmd (struct packet_config *config, const char *name,
1542 const char *title, int legacy)
d471ea57 1543{
5a2468f5
JM
1544 char *set_doc;
1545 char *show_doc;
d471ea57 1546 char *cmd_name;
3ed07be4 1547
5a2468f5
JM
1548 config->name = name;
1549 config->title = title;
b435e160
AC
1550 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1551 name, title);
3e43a32a
MS
1552 show_doc = xstrprintf ("Show current use of remote "
1553 "protocol `%s' (%s) packet",
b435e160 1554 name, title);
d471ea57 1555 /* set/show TITLE-packet {auto,on,off} */
b435e160 1556 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1557 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1558 &config->detect, set_doc,
1559 show_doc, NULL, /* help_doc */
4082afcc 1560 NULL,
bb572ddd
DJ
1561 show_remote_protocol_packet_cmd,
1562 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1563 /* The command code copies the documentation strings. */
1564 xfree (set_doc);
1565 xfree (show_doc);
23860348 1566 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1567 if (legacy)
1568 {
1569 char *legacy_name;
a744cf53 1570
b435e160 1571 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1572 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1573 &remote_set_cmdlist);
d471ea57 1574 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1575 &remote_show_cmdlist);
d471ea57 1576 }
5a2468f5
JM
1577}
1578
d471ea57 1579static enum packet_result
a76d924d 1580packet_check_result (const char *buf)
5a2468f5 1581{
d471ea57 1582 if (buf[0] != '\0')
5a2468f5 1583 {
d471ea57 1584 /* The stub recognized the packet request. Check that the
23860348 1585 operation succeeded. */
a76d924d
DJ
1586 if (buf[0] == 'E'
1587 && isxdigit (buf[1]) && isxdigit (buf[2])
1588 && buf[3] == '\0')
1589 /* "Enn" - definitly an error. */
1590 return PACKET_ERROR;
1591
1592 /* Always treat "E." as an error. This will be used for
1593 more verbose error messages, such as E.memtypes. */
1594 if (buf[0] == 'E' && buf[1] == '.')
1595 return PACKET_ERROR;
1596
1597 /* The packet may or may not be OK. Just assume it is. */
1598 return PACKET_OK;
1599 }
1600 else
1601 /* The stub does not support the packet. */
1602 return PACKET_UNKNOWN;
1603}
1604
1605static enum packet_result
1606packet_ok (const char *buf, struct packet_config *config)
1607{
1608 enum packet_result result;
1609
4082afcc
PA
1610 if (config->detect != AUTO_BOOLEAN_TRUE
1611 && config->support == PACKET_DISABLE)
1612 internal_error (__FILE__, __LINE__,
1613 _("packet_ok: attempt to use a disabled packet"));
1614
a76d924d
DJ
1615 result = packet_check_result (buf);
1616 switch (result)
1617 {
1618 case PACKET_OK:
1619 case PACKET_ERROR:
1620 /* The stub recognized the packet request. */
4082afcc 1621 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1622 {
d471ea57
AC
1623 if (remote_debug)
1624 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1625 "Packet %s (%s) is supported\n",
1626 config->name, config->title);
d471ea57 1627 config->support = PACKET_ENABLE;
d471ea57 1628 }
a76d924d
DJ
1629 break;
1630 case PACKET_UNKNOWN:
23860348 1631 /* The stub does not support the packet. */
4082afcc
PA
1632 if (config->detect == AUTO_BOOLEAN_AUTO
1633 && config->support == PACKET_ENABLE)
d471ea57 1634 {
4082afcc
PA
1635 /* If the stub previously indicated that the packet was
1636 supported then there is a protocol error. */
1637 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1638 config->name, config->title);
1639 }
1640 else if (config->detect == AUTO_BOOLEAN_TRUE)
1641 {
1642 /* The user set it wrong. */
1643 error (_("Enabled packet %s (%s) not recognized by stub"),
1644 config->name, config->title);
d471ea57 1645 }
4082afcc
PA
1646
1647 if (remote_debug)
1648 fprintf_unfiltered (gdb_stdlog,
1649 "Packet %s (%s) is NOT supported\n",
1650 config->name, config->title);
1651 config->support = PACKET_DISABLE;
a76d924d 1652 break;
5a2468f5 1653 }
a76d924d
DJ
1654
1655 return result;
5a2468f5
JM
1656}
1657
444abaca
DJ
1658enum {
1659 PACKET_vCont = 0,
1660 PACKET_X,
1661 PACKET_qSymbol,
1662 PACKET_P,
1663 PACKET_p,
1664 PACKET_Z0,
1665 PACKET_Z1,
1666 PACKET_Z2,
1667 PACKET_Z3,
1668 PACKET_Z4,
15a201c8 1669 PACKET_vFile_setfs,
a6b151f1
DJ
1670 PACKET_vFile_open,
1671 PACKET_vFile_pread,
1672 PACKET_vFile_pwrite,
1673 PACKET_vFile_close,
1674 PACKET_vFile_unlink,
b9e7b9c3 1675 PACKET_vFile_readlink,
0a93529c 1676 PACKET_vFile_fstat,
0876f84a 1677 PACKET_qXfer_auxv,
23181151 1678 PACKET_qXfer_features,
c78fa86a 1679 PACKET_qXfer_exec_file,
cfa9d6d9 1680 PACKET_qXfer_libraries,
2268b414 1681 PACKET_qXfer_libraries_svr4,
fd79ecee 1682 PACKET_qXfer_memory_map,
0e7f50da
UW
1683 PACKET_qXfer_spu_read,
1684 PACKET_qXfer_spu_write,
07e059b5 1685 PACKET_qXfer_osdata,
dc146f7c 1686 PACKET_qXfer_threads,
0fb4aa4b 1687 PACKET_qXfer_statictrace_read,
b3b9301e 1688 PACKET_qXfer_traceframe_info,
169081d0 1689 PACKET_qXfer_uib,
711e434b 1690 PACKET_qGetTIBAddr,
444abaca 1691 PACKET_qGetTLSAddr,
be2a5f71 1692 PACKET_qSupported,
bd3eecc3 1693 PACKET_qTStatus,
89be2091 1694 PACKET_QPassSignals,
82075af2 1695 PACKET_QCatchSyscalls,
9b224c5e 1696 PACKET_QProgramSignals,
bc3b087d 1697 PACKET_QSetWorkingDir,
aefd8b33 1698 PACKET_QStartupWithShell,
0a2dde4a
SDJ
1699 PACKET_QEnvironmentHexEncoded,
1700 PACKET_QEnvironmentReset,
1701 PACKET_QEnvironmentUnset,
936d2992 1702 PACKET_qCRC,
08388c79 1703 PACKET_qSearch_memory,
2d717e4f
DJ
1704 PACKET_vAttach,
1705 PACKET_vRun,
a6f3e723 1706 PACKET_QStartNoAckMode,
82f73884 1707 PACKET_vKill,
4aa995e1
PA
1708 PACKET_qXfer_siginfo_read,
1709 PACKET_qXfer_siginfo_write,
0b16c5cf 1710 PACKET_qAttached,
4082afcc
PA
1711
1712 /* Support for conditional tracepoints. */
782b2b07 1713 PACKET_ConditionalTracepoints,
4082afcc
PA
1714
1715 /* Support for target-side breakpoint conditions. */
3788aec7 1716 PACKET_ConditionalBreakpoints,
4082afcc
PA
1717
1718 /* Support for target-side breakpoint commands. */
d3ce09f5 1719 PACKET_BreakpointCommands,
4082afcc
PA
1720
1721 /* Support for fast tracepoints. */
7a697b8d 1722 PACKET_FastTracepoints,
4082afcc
PA
1723
1724 /* Support for static tracepoints. */
0fb4aa4b 1725 PACKET_StaticTracepoints,
4082afcc
PA
1726
1727 /* Support for installing tracepoints while a trace experiment is
1728 running. */
1e4d1764 1729 PACKET_InstallInTrace,
4082afcc 1730
40ab02ce
MS
1731 PACKET_bc,
1732 PACKET_bs,
409873ef 1733 PACKET_TracepointSource,
d914c394 1734 PACKET_QAllow,
78d85199 1735 PACKET_qXfer_fdpic,
03583c20 1736 PACKET_QDisableRandomization,
d1feda86 1737 PACKET_QAgent,
f6f899bf 1738 PACKET_QTBuffer_size,
9accd112
MM
1739 PACKET_Qbtrace_off,
1740 PACKET_Qbtrace_bts,
b20a6524 1741 PACKET_Qbtrace_pt,
9accd112 1742 PACKET_qXfer_btrace,
4082afcc
PA
1743
1744 /* Support for the QNonStop packet. */
1745 PACKET_QNonStop,
1746
65706a29
PA
1747 /* Support for the QThreadEvents packet. */
1748 PACKET_QThreadEvents,
1749
4082afcc
PA
1750 /* Support for multi-process extensions. */
1751 PACKET_multiprocess_feature,
1752
1753 /* Support for enabling and disabling tracepoints while a trace
1754 experiment is running. */
1755 PACKET_EnableDisableTracepoints_feature,
1756
1757 /* Support for collecting strings using the tracenz bytecode. */
1758 PACKET_tracenz_feature,
1759
1760 /* Support for continuing to run a trace experiment while GDB is
1761 disconnected. */
1762 PACKET_DisconnectedTracing_feature,
1763
1764 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1765 PACKET_augmented_libraries_svr4_read_feature,
1766
f4abbc16
MM
1767 /* Support for the qXfer:btrace-conf:read packet. */
1768 PACKET_qXfer_btrace_conf,
1769
d33501a5
MM
1770 /* Support for the Qbtrace-conf:bts:size packet. */
1771 PACKET_Qbtrace_conf_bts_size,
1772
f7e6eed5
PA
1773 /* Support for swbreak+ feature. */
1774 PACKET_swbreak_feature,
1775
1776 /* Support for hwbreak+ feature. */
1777 PACKET_hwbreak_feature,
1778
89245bc0
DB
1779 /* Support for fork events. */
1780 PACKET_fork_event_feature,
1781
1782 /* Support for vfork events. */
1783 PACKET_vfork_event_feature,
1784
b20a6524
MM
1785 /* Support for the Qbtrace-conf:pt:size packet. */
1786 PACKET_Qbtrace_conf_pt_size,
1787
94585166
DB
1788 /* Support for exec events. */
1789 PACKET_exec_event_feature,
1790
750ce8d1
YQ
1791 /* Support for query supported vCont actions. */
1792 PACKET_vContSupported,
1793
de979965
PA
1794 /* Support remote CTRL-C. */
1795 PACKET_vCtrlC,
1796
f2faf941
PA
1797 /* Support TARGET_WAITKIND_NO_RESUMED. */
1798 PACKET_no_resumed,
1799
444abaca
DJ
1800 PACKET_MAX
1801};
506fb367 1802
444abaca 1803static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1804
f7e6eed5
PA
1805/* Returns the packet's corresponding "set remote foo-packet" command
1806 state. See struct packet_config for more details. */
1807
1808static enum auto_boolean
1809packet_set_cmd_state (int packet)
1810{
1811 return remote_protocol_packets[packet].detect;
1812}
1813
4082afcc
PA
1814/* Returns whether a given packet or feature is supported. This takes
1815 into account the state of the corresponding "set remote foo-packet"
1816 command, which may be used to bypass auto-detection. */
dc8acb97 1817
4082afcc
PA
1818static enum packet_support
1819packet_config_support (struct packet_config *config)
1820{
1821 switch (config->detect)
444abaca 1822 {
4082afcc
PA
1823 case AUTO_BOOLEAN_TRUE:
1824 return PACKET_ENABLE;
1825 case AUTO_BOOLEAN_FALSE:
1826 return PACKET_DISABLE;
1827 case AUTO_BOOLEAN_AUTO:
1828 return config->support;
1829 default:
1830 gdb_assert_not_reached (_("bad switch"));
444abaca 1831 }
4082afcc
PA
1832}
1833
1834/* Same as packet_config_support, but takes the packet's enum value as
1835 argument. */
1836
1837static enum packet_support
1838packet_support (int packet)
1839{
1840 struct packet_config *config = &remote_protocol_packets[packet];
1841
1842 return packet_config_support (config);
dc8acb97
MS
1843}
1844
5a2468f5 1845static void
444abaca
DJ
1846show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1847 struct cmd_list_element *c,
1848 const char *value)
5a2468f5 1849{
444abaca 1850 struct packet_config *packet;
5a2468f5 1851
444abaca
DJ
1852 for (packet = remote_protocol_packets;
1853 packet < &remote_protocol_packets[PACKET_MAX];
1854 packet++)
1855 {
1856 if (&packet->detect == c->var)
1857 {
1858 show_packet_config_cmd (packet);
1859 return;
1860 }
1861 }
9b20d036 1862 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1863 c->name);
5a2468f5
JM
1864}
1865
d471ea57
AC
1866/* Should we try one of the 'Z' requests? */
1867
1868enum Z_packet_type
1869{
1870 Z_PACKET_SOFTWARE_BP,
1871 Z_PACKET_HARDWARE_BP,
1872 Z_PACKET_WRITE_WP,
1873 Z_PACKET_READ_WP,
1874 Z_PACKET_ACCESS_WP,
1875 NR_Z_PACKET_TYPES
1876};
96baa820 1877
d471ea57 1878/* For compatibility with older distributions. Provide a ``set remote
23860348 1879 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1880
7f19b9a2 1881static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1882
1883static void
eb4c3f4a 1884set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
fba45db2 1885 struct cmd_list_element *c)
96baa820 1886{
d471ea57 1887 int i;
a744cf53 1888
d471ea57 1889 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1890 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1891}
1892
1893static void
08546159
AC
1894show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1895 struct cmd_list_element *c,
1896 const char *value)
96baa820 1897{
d471ea57 1898 int i;
a744cf53 1899
d471ea57
AC
1900 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1901 {
444abaca 1902 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1903 }
96baa820
JM
1904}
1905
4082afcc
PA
1906/* Returns true if the multi-process extensions are in effect. */
1907
1908static int
1909remote_multi_process_p (struct remote_state *rs)
1910{
1911 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1912}
1913
de0d863e
DB
1914/* Returns true if fork events are supported. */
1915
1916static int
1917remote_fork_event_p (struct remote_state *rs)
1918{
1919 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1920}
1921
c269dbdb
DB
1922/* Returns true if vfork events are supported. */
1923
1924static int
1925remote_vfork_event_p (struct remote_state *rs)
1926{
1927 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1928}
1929
d46addbb
DB
1930/* Returns true if exec events are supported. */
1931
1932static int
1933remote_exec_event_p (struct remote_state *rs)
1934{
1935 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1936}
1937
cbb8991c
DB
1938/* Insert fork catchpoint target routine. If fork events are enabled
1939 then return success, nothing more to do. */
1940
f6ac5f3d
PA
1941int
1942remote_target::insert_fork_catchpoint (int pid)
cbb8991c
DB
1943{
1944 struct remote_state *rs = get_remote_state ();
1945
1946 return !remote_fork_event_p (rs);
1947}
1948
1949/* Remove fork catchpoint target routine. Nothing to do, just
1950 return success. */
1951
f6ac5f3d
PA
1952int
1953remote_target::remove_fork_catchpoint (int pid)
cbb8991c
DB
1954{
1955 return 0;
1956}
1957
1958/* Insert vfork catchpoint target routine. If vfork events are enabled
1959 then return success, nothing more to do. */
1960
f6ac5f3d
PA
1961int
1962remote_target::insert_vfork_catchpoint (int pid)
cbb8991c
DB
1963{
1964 struct remote_state *rs = get_remote_state ();
1965
1966 return !remote_vfork_event_p (rs);
1967}
1968
1969/* Remove vfork catchpoint target routine. Nothing to do, just
1970 return success. */
1971
f6ac5f3d
PA
1972int
1973remote_target::remove_vfork_catchpoint (int pid)
cbb8991c
DB
1974{
1975 return 0;
1976}
1977
d46addbb
DB
1978/* Insert exec catchpoint target routine. If exec events are
1979 enabled, just return success. */
1980
f6ac5f3d
PA
1981int
1982remote_target::insert_exec_catchpoint (int pid)
d46addbb
DB
1983{
1984 struct remote_state *rs = get_remote_state ();
1985
1986 return !remote_exec_event_p (rs);
1987}
1988
1989/* Remove exec catchpoint target routine. Nothing to do, just
1990 return success. */
1991
f6ac5f3d
PA
1992int
1993remote_target::remove_exec_catchpoint (int pid)
d46addbb
DB
1994{
1995 return 0;
1996}
1997
74531fed
PA
1998\f
1999/* Asynchronous signal handle registered as event loop source for
2000 when we have pending events ready to be passed to the core. */
2001
2002static struct async_event_handler *remote_async_inferior_event_token;
2003
c906108c
SS
2004\f
2005
79d7f229
PA
2006static ptid_t magic_null_ptid;
2007static ptid_t not_sent_ptid;
2008static ptid_t any_thread_ptid;
2009
0b16c5cf
PA
2010/* Find out if the stub attached to PID (and hence GDB should offer to
2011 detach instead of killing it when bailing out). */
2012
2013static int
2014remote_query_attached (int pid)
2015{
2016 struct remote_state *rs = get_remote_state ();
bba74b36 2017 size_t size = get_remote_packet_size ();
0b16c5cf 2018
4082afcc 2019 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
2020 return 0;
2021
2022 if (remote_multi_process_p (rs))
bba74b36 2023 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 2024 else
bba74b36 2025 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
2026
2027 putpkt (rs->buf);
2028 getpkt (&rs->buf, &rs->buf_size, 0);
2029
2030 switch (packet_ok (rs->buf,
1554e9be 2031 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
2032 {
2033 case PACKET_OK:
2034 if (strcmp (rs->buf, "1") == 0)
2035 return 1;
2036 break;
2037 case PACKET_ERROR:
2038 warning (_("Remote failure reply: %s"), rs->buf);
2039 break;
2040 case PACKET_UNKNOWN:
2041 break;
2042 }
2043
2044 return 0;
2045}
2046
49c62f2e
PA
2047/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2048 has been invented by GDB, instead of reported by the target. Since
2049 we can be connected to a remote system before before knowing about
2050 any inferior, mark the target with execution when we find the first
2051 inferior. If ATTACHED is 1, then we had just attached to this
2052 inferior. If it is 0, then we just created this inferior. If it
2053 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
2054 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2055 attempt to open this inferior's executable as the main executable
2056 if no main executable is open already. */
1941c569
PA
2057
2058static struct inferior *
1b6e6f5c
GB
2059remote_add_inferior (int fake_pid_p, int pid, int attached,
2060 int try_open_exec)
1941c569 2061{
1941c569
PA
2062 struct inferior *inf;
2063
0b16c5cf
PA
2064 /* Check whether this process we're learning about is to be
2065 considered attached, or if is to be considered to have been
2066 spawned by the stub. */
2067 if (attached == -1)
2068 attached = remote_query_attached (pid);
2069
f5656ead 2070 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
2071 {
2072 /* If the target shares code across all inferiors, then every
2073 attach adds a new inferior. */
2074 inf = add_inferior (pid);
2075
2076 /* ... and every inferior is bound to the same program space.
2077 However, each inferior may still have its own address
2078 space. */
2079 inf->aspace = maybe_new_address_space ();
2080 inf->pspace = current_program_space;
2081 }
2082 else
2083 {
2084 /* In the traditional debugging scenario, there's a 1-1 match
2085 between program/address spaces. We simply bind the inferior
2086 to the program space's address space. */
2087 inf = current_inferior ();
2088 inferior_appeared (inf, pid);
2089 }
1941c569 2090
0b16c5cf 2091 inf->attach_flag = attached;
49c62f2e 2092 inf->fake_pid_p = fake_pid_p;
0b16c5cf 2093
1b6e6f5c
GB
2094 /* If no main executable is currently open then attempt to
2095 open the file that was executed to create this inferior. */
835205d0 2096 if (try_open_exec && get_exec_file (0) == NULL)
bb805577 2097 exec_file_locate_attach (pid, 0, 1);
1b6e6f5c 2098
1941c569
PA
2099 return inf;
2100}
2101
7aabaf9d 2102static remote_thread_info *get_remote_thread_info (thread_info *thread);
85ad3aaf 2103
1941c569
PA
2104/* Add thread PTID to GDB's thread list. Tag it as executing/running
2105 according to RUNNING. */
2106
c906108c 2107static void
0d5b594f 2108remote_add_thread (ptid_t ptid, int running, int executing)
c906108c 2109{
b7ea362b 2110 struct remote_state *rs = get_remote_state ();
85ad3aaf 2111 struct thread_info *thread;
b7ea362b
PA
2112
2113 /* GDB historically didn't pull threads in the initial connection
2114 setup. If the remote target doesn't even have a concept of
2115 threads (e.g., a bare-metal target), even if internally we
2116 consider that a single-threaded target, mentioning a new thread
2117 might be confusing to the user. Be silent then, preserving the
2118 age old behavior. */
2119 if (rs->starting_up)
85ad3aaf 2120 thread = add_thread_silent (ptid);
b7ea362b 2121 else
85ad3aaf 2122 thread = add_thread (ptid);
1941c569 2123
7aabaf9d 2124 get_remote_thread_info (thread)->vcont_resumed = executing;
0d5b594f 2125 set_executing (ptid, executing);
1941c569
PA
2126 set_running (ptid, running);
2127}
2128
2129/* Come here when we learn about a thread id from the remote target.
2130 It may be the first time we hear about such thread, so take the
2131 opportunity to add it to GDB's thread list. In case this is the
2132 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
2133 GDB's inferior list as well. EXECUTING indicates whether the
2134 thread is (internally) executing or stopped. */
1941c569
PA
2135
2136static void
0d5b594f 2137remote_notice_new_inferior (ptid_t currthread, int executing)
1941c569 2138{
0d5b594f
PA
2139 /* In non-stop mode, we assume new found threads are (externally)
2140 running until proven otherwise with a stop reply. In all-stop,
2141 we can only get here if all threads are stopped. */
2142 int running = target_is_non_stop_p () ? 1 : 0;
2143
c906108c
SS
2144 /* If this is a new thread, add it to GDB's thread list.
2145 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
2146
2147 if (in_thread_list (currthread) && is_exited (currthread))
2148 {
2149 /* We're seeing an event on a thread id we knew had exited.
2150 This has to be a new thread reusing the old id. Add it. */
0d5b594f 2151 remote_add_thread (currthread, running, executing);
82f73884
PA
2152 return;
2153 }
2154
79d7f229 2155 if (!in_thread_list (currthread))
c0a2216e 2156 {
1941c569 2157 struct inferior *inf = NULL;
bad34192 2158 int pid = ptid_get_pid (currthread);
1941c569 2159
bad34192
PA
2160 if (ptid_is_pid (inferior_ptid)
2161 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
2162 {
2163 /* inferior_ptid has no thread member yet. This can happen
2164 with the vAttach -> remote_wait,"TAAthread:" path if the
2165 stub doesn't support qC. This is the first stop reported
2166 after an attach, so this is the main thread. Update the
2167 ptid in the thread list. */
bad34192
PA
2168 if (in_thread_list (pid_to_ptid (pid)))
2169 thread_change_ptid (inferior_ptid, currthread);
2170 else
2171 {
0d5b594f 2172 remote_add_thread (currthread, running, executing);
bad34192
PA
2173 inferior_ptid = currthread;
2174 }
dc146f7c 2175 return;
c0a2216e 2176 }
82f73884
PA
2177
2178 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
2179 {
2180 /* inferior_ptid is not set yet. This can happen with the
2181 vRun -> remote_wait,"TAAthread:" path if the stub
2182 doesn't support qC. This is the first stop reported
2183 after an attach, so this is the main thread. Update the
2184 ptid in the thread list. */
dc146f7c 2185 thread_change_ptid (inferior_ptid, currthread);
82f73884 2186 return;
c0a2216e 2187 }
82f73884 2188
29c87f7f
PA
2189 /* When connecting to a target remote, or to a target
2190 extended-remote which already was debugging an inferior, we
2191 may not know about it yet. Add it before adding its child
2192 thread, so notifications are emitted in a sensible order. */
2193 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
2194 {
2195 struct remote_state *rs = get_remote_state ();
2196 int fake_pid_p = !remote_multi_process_p (rs);
2197
2198 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 2199 ptid_get_pid (currthread), -1, 1);
49c62f2e 2200 }
29c87f7f 2201
82f73884 2202 /* This is really a new thread. Add it. */
0d5b594f 2203 remote_add_thread (currthread, running, executing);
1941c569
PA
2204
2205 /* If we found a new inferior, let the common code do whatever
2206 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
2207 breakpoints), unless we're just setting up an all-stop
2208 connection. */
1941c569 2209 if (inf != NULL)
b7ea362b
PA
2210 {
2211 struct remote_state *rs = get_remote_state ();
2212
6efcd9a8 2213 if (!rs->starting_up)
0d5b594f 2214 notice_new_inferior (currthread, executing, 0);
b7ea362b 2215 }
c0a2216e 2216 }
c906108c
SS
2217}
2218
85ad3aaf 2219/* Return THREAD's private thread data, creating it if necessary. */
dc146f7c 2220
7aabaf9d
SM
2221static remote_thread_info *
2222get_remote_thread_info (thread_info *thread)
dc146f7c 2223{
85ad3aaf 2224 gdb_assert (thread != NULL);
dc146f7c 2225
85ad3aaf 2226 if (thread->priv == NULL)
7aabaf9d 2227 thread->priv.reset (new remote_thread_info);
dc146f7c 2228
7aabaf9d 2229 return static_cast<remote_thread_info *> (thread->priv.get ());
85ad3aaf
PA
2230}
2231
2232/* Return PTID's private thread data, creating it if necessary. */
2233
7aabaf9d
SM
2234static remote_thread_info *
2235get_remote_thread_info (ptid_t ptid)
85ad3aaf
PA
2236{
2237 struct thread_info *info = find_thread_ptid (ptid);
2238
7aabaf9d 2239 return get_remote_thread_info (info);
dc146f7c
VP
2240}
2241
74531fed
PA
2242/* Call this function as a result of
2243 1) A halt indication (T packet) containing a thread id
2244 2) A direct query of currthread
0df8b418 2245 3) Successful execution of set thread */
74531fed
PA
2246
2247static void
47f8a51d 2248record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 2249{
47f8a51d 2250 rs->general_thread = currthread;
74531fed
PA
2251}
2252
89be2091
DJ
2253/* If 'QPassSignals' is supported, tell the remote stub what signals
2254 it can simply pass through to the inferior without reporting. */
2255
f6ac5f3d
PA
2256void
2257remote_target::pass_signals (int numsigs, unsigned char *pass_signals)
89be2091 2258{
4082afcc 2259 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
2260 {
2261 char *pass_packet, *p;
89be2091 2262 int count = 0, i;
747dc59d 2263 struct remote_state *rs = get_remote_state ();
89be2091
DJ
2264
2265 gdb_assert (numsigs < 256);
2266 for (i = 0; i < numsigs; i++)
2267 {
2455069d 2268 if (pass_signals[i])
89be2091
DJ
2269 count++;
2270 }
224c3ddb 2271 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
2272 strcpy (pass_packet, "QPassSignals:");
2273 p = pass_packet + strlen (pass_packet);
2274 for (i = 0; i < numsigs; i++)
2275 {
2455069d 2276 if (pass_signals[i])
89be2091
DJ
2277 {
2278 if (i >= 16)
2279 *p++ = tohex (i >> 4);
2280 *p++ = tohex (i & 15);
2281 if (count)
2282 *p++ = ';';
2283 else
2284 break;
2285 count--;
2286 }
2287 }
2288 *p = 0;
747dc59d 2289 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 2290 {
89be2091
DJ
2291 putpkt (pass_packet);
2292 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2293 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
2294 if (rs->last_pass_packet)
2295 xfree (rs->last_pass_packet);
2296 rs->last_pass_packet = pass_packet;
89be2091
DJ
2297 }
2298 else
2299 xfree (pass_packet);
2300 }
2301}
2302
82075af2
JS
2303/* If 'QCatchSyscalls' is supported, tell the remote stub
2304 to report syscalls to GDB. */
2305
f6ac5f3d
PA
2306int
2307remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2308 gdb::array_view<const int> syscall_counts)
82075af2 2309{
b80406ac 2310 const char *catch_packet;
82075af2
JS
2311 enum packet_result result;
2312 int n_sysno = 0;
2313
2314 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2315 {
2316 /* Not supported. */
2317 return 1;
2318 }
2319
649a140c 2320 if (needed && any_count == 0)
82075af2 2321 {
649a140c
PA
2322 /* Count how many syscalls are to be caught. */
2323 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2324 {
649a140c 2325 if (syscall_counts[i] != 0)
82075af2
JS
2326 n_sysno++;
2327 }
2328 }
2329
2330 if (remote_debug)
2331 {
2332 fprintf_unfiltered (gdb_stdlog,
2333 "remote_set_syscall_catchpoint "
2334 "pid %d needed %d any_count %d n_sysno %d\n",
2335 pid, needed, any_count, n_sysno);
2336 }
2337
1b81856f 2338 std::string built_packet;
82075af2
JS
2339 if (needed)
2340 {
2341 /* Prepare a packet with the sysno list, assuming max 8+1
2342 characters for a sysno. If the resulting packet size is too
2343 big, fallback on the non-selective packet. */
2344 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
1b81856f
PA
2345 built_packet.reserve (maxpktsz);
2346 built_packet = "QCatchSyscalls:1";
649a140c 2347 if (any_count == 0)
82075af2 2348 {
649a140c
PA
2349 /* Add in each syscall to be caught. */
2350 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2351 {
649a140c
PA
2352 if (syscall_counts[i] != 0)
2353 string_appendf (built_packet, ";%zx", i);
82075af2
JS
2354 }
2355 }
1b81856f 2356 if (built_packet.size () > get_remote_packet_size ())
82075af2
JS
2357 {
2358 /* catch_packet too big. Fallback to less efficient
2359 non selective mode, with GDB doing the filtering. */
b80406ac 2360 catch_packet = "QCatchSyscalls:1";
82075af2 2361 }
b80406ac 2362 else
1b81856f 2363 catch_packet = built_packet.c_str ();
82075af2
JS
2364 }
2365 else
b80406ac 2366 catch_packet = "QCatchSyscalls:0";
82075af2 2367
b80406ac 2368 struct remote_state *rs = get_remote_state ();
82075af2 2369
b80406ac
TT
2370 putpkt (catch_packet);
2371 getpkt (&rs->buf, &rs->buf_size, 0);
2372 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2373 if (result == PACKET_OK)
2374 return 0;
2375 else
2376 return -1;
82075af2
JS
2377}
2378
9b224c5e
PA
2379/* If 'QProgramSignals' is supported, tell the remote stub what
2380 signals it should pass through to the inferior when detaching. */
2381
f6ac5f3d
PA
2382void
2383remote_target::program_signals (int numsigs, unsigned char *signals)
9b224c5e 2384{
4082afcc 2385 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
2386 {
2387 char *packet, *p;
2388 int count = 0, i;
5e4a05c4 2389 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
2390
2391 gdb_assert (numsigs < 256);
2392 for (i = 0; i < numsigs; i++)
2393 {
2394 if (signals[i])
2395 count++;
2396 }
224c3ddb 2397 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2398 strcpy (packet, "QProgramSignals:");
2399 p = packet + strlen (packet);
2400 for (i = 0; i < numsigs; i++)
2401 {
2402 if (signal_pass_state (i))
2403 {
2404 if (i >= 16)
2405 *p++ = tohex (i >> 4);
2406 *p++ = tohex (i & 15);
2407 if (count)
2408 *p++ = ';';
2409 else
2410 break;
2411 count--;
2412 }
2413 }
2414 *p = 0;
5e4a05c4
TT
2415 if (!rs->last_program_signals_packet
2416 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2417 {
9b224c5e
PA
2418 putpkt (packet);
2419 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2420 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2421 xfree (rs->last_program_signals_packet);
2422 rs->last_program_signals_packet = packet;
9b224c5e
PA
2423 }
2424 else
2425 xfree (packet);
2426 }
2427}
2428
79d7f229
PA
2429/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2430 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2431 thread. If GEN is set, set the general thread, if not, then set
2432 the step/continue thread. */
c906108c 2433static void
d62a8ae2 2434set_thread (ptid_t ptid, int gen)
c906108c 2435{
d01949b6 2436 struct remote_state *rs = get_remote_state ();
47f8a51d 2437 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 2438 char *buf = rs->buf;
79d7f229 2439 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 2440
79d7f229 2441 if (ptid_equal (state, ptid))
c906108c
SS
2442 return;
2443
79d7f229
PA
2444 *buf++ = 'H';
2445 *buf++ = gen ? 'g' : 'c';
2446 if (ptid_equal (ptid, magic_null_ptid))
2447 xsnprintf (buf, endbuf - buf, "0");
2448 else if (ptid_equal (ptid, any_thread_ptid))
2449 xsnprintf (buf, endbuf - buf, "0");
2450 else if (ptid_equal (ptid, minus_one_ptid))
2451 xsnprintf (buf, endbuf - buf, "-1");
2452 else
82f73884 2453 write_ptid (buf, endbuf, ptid);
79d7f229 2454 putpkt (rs->buf);
6d820c5c 2455 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2456 if (gen)
47f8a51d 2457 rs->general_thread = ptid;
c906108c 2458 else
47f8a51d 2459 rs->continue_thread = ptid;
c906108c 2460}
79d7f229
PA
2461
2462static void
d62a8ae2 2463set_general_thread (ptid_t ptid)
79d7f229
PA
2464{
2465 set_thread (ptid, 1);
2466}
2467
2468static void
d62a8ae2 2469set_continue_thread (ptid_t ptid)
79d7f229
PA
2470{
2471 set_thread (ptid, 0);
2472}
2473
3c9c4b83
PA
2474/* Change the remote current process. Which thread within the process
2475 ends up selected isn't important, as long as it is the same process
2476 as what INFERIOR_PTID points to.
2477
2478 This comes from that fact that there is no explicit notion of
2479 "selected process" in the protocol. The selected process for
2480 general operations is the process the selected general thread
2481 belongs to. */
2482
2483static void
2484set_general_process (void)
2485{
2486 struct remote_state *rs = get_remote_state ();
2487
2488 /* If the remote can't handle multiple processes, don't bother. */
8020350c 2489 if (!remote_multi_process_p (rs))
3c9c4b83
PA
2490 return;
2491
2492 /* We only need to change the remote current thread if it's pointing
2493 at some other process. */
47f8a51d 2494 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
2495 set_general_thread (inferior_ptid);
2496}
2497
c906108c 2498\f
7d1a114c
PA
2499/* Return nonzero if this is the main thread that we made up ourselves
2500 to model non-threaded targets as single-threaded. */
c906108c
SS
2501
2502static int
f6ac5f3d 2503remote_thread_always_alive (ptid_t ptid)
c906108c 2504{
c0a2216e
PA
2505 if (ptid_equal (ptid, magic_null_ptid))
2506 /* The main thread is always alive. */
2507 return 1;
2508
ba348170 2509 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
2510 /* The main thread is always alive. This can happen after a
2511 vAttach, if the remote side doesn't support
2512 multi-threading. */
2513 return 1;
2514
7d1a114c
PA
2515 return 0;
2516}
2517
2518/* Return nonzero if the thread PTID is still alive on the remote
2519 system. */
2520
f6ac5f3d
PA
2521int
2522remote_target::thread_alive (ptid_t ptid)
7d1a114c
PA
2523{
2524 struct remote_state *rs = get_remote_state ();
2525 char *p, *endp;
2526
2527 /* Check if this is a thread that we made up ourselves to model
2528 non-threaded targets as single-threaded. */
f6ac5f3d 2529 if (remote_thread_always_alive (ptid))
7d1a114c
PA
2530 return 1;
2531
82f73884
PA
2532 p = rs->buf;
2533 endp = rs->buf + get_remote_packet_size ();
2534
2535 *p++ = 'T';
2536 write_ptid (p, endp, ptid);
2537
2e9f7625 2538 putpkt (rs->buf);
6d820c5c 2539 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2540 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2541}
2542
79efa585
SM
2543/* Return a pointer to a thread name if we know it and NULL otherwise.
2544 The thread_info object owns the memory for the name. */
2545
f6ac5f3d
PA
2546const char *
2547remote_target::thread_name (struct thread_info *info)
79efa585
SM
2548{
2549 if (info->priv != NULL)
a9334058
SM
2550 {
2551 const std::string &name = get_remote_thread_info (info)->name;
2552 return !name.empty () ? name.c_str () : NULL;
2553 }
79efa585
SM
2554
2555 return NULL;
2556}
2557
c906108c
SS
2558/* About these extended threadlist and threadinfo packets. They are
2559 variable length packets but, the fields within them are often fixed
2560 length. They are redundent enough to send over UDP as is the
2561 remote protocol in general. There is a matching unit test module
2562 in libstub. */
2563
23860348 2564/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2565 libstub protocol encoding, and remote.c. It is not particularly
23860348 2566 changable. */
cce74817
JM
2567
2568/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2569 Plan to fix this. */
cce74817 2570
23860348 2571typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2572
9d1f7ab2 2573/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2574 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2575
2576struct gdb_ext_thread_info
c5aa993b 2577 {
23860348 2578 threadref threadid; /* External form of thread reference. */
2bc416ba 2579 int active; /* Has state interesting to GDB?
23860348 2580 regs, stack. */
2bc416ba 2581 char display[256]; /* Brief state display, name,
cedea757 2582 blocked/suspended. */
23860348 2583 char shortname[32]; /* To be used to name threads. */
2bc416ba 2584 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2585 whatever. */
c5aa993b 2586 };
cce74817
JM
2587
2588/* The volume of remote transfers can be limited by submitting
2589 a mask containing bits specifying the desired information.
2590 Use a union of these values as the 'selection' parameter to
0df8b418 2591 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2592
2593#define TAG_THREADID 1
2594#define TAG_EXISTS 2
2595#define TAG_DISPLAY 4
2596#define TAG_THREADNAME 8
c5aa993b 2597#define TAG_MOREDISPLAY 16
cce74817 2598
23860348 2599#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2600
a14ed312 2601static char *unpack_nibble (char *buf, int *val);
cce74817 2602
a14ed312 2603static char *unpack_byte (char *buf, int *value);
cce74817 2604
a14ed312 2605static char *pack_int (char *buf, int value);
cce74817 2606
a14ed312 2607static char *unpack_int (char *buf, int *value);
cce74817 2608
a14ed312 2609static char *unpack_string (char *src, char *dest, int length);
cce74817 2610
23860348 2611static char *pack_threadid (char *pkt, threadref *id);
cce74817 2612
23860348 2613static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2614
23860348 2615void int_to_threadref (threadref *id, int value);
cce74817 2616
23860348 2617static int threadref_to_int (threadref *ref);
cce74817 2618
23860348 2619static void copy_threadref (threadref *dest, threadref *src);
cce74817 2620
23860348 2621static int threadmatch (threadref *dest, threadref *src);
cce74817 2622
2bc416ba 2623static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2624 threadref *id);
cce74817 2625
a14ed312 2626static int remote_unpack_thread_info_response (char *pkt,
23860348 2627 threadref *expectedref,
a14ed312
KB
2628 struct gdb_ext_thread_info
2629 *info);
cce74817
JM
2630
2631
2bc416ba 2632static int remote_get_threadinfo (threadref *threadid,
23860348 2633 int fieldset, /*TAG mask */
a14ed312 2634 struct gdb_ext_thread_info *info);
cce74817 2635
a14ed312
KB
2636static char *pack_threadlist_request (char *pkt, int startflag,
2637 int threadcount,
23860348 2638 threadref *nextthread);
cce74817 2639
a14ed312
KB
2640static int parse_threadlist_response (char *pkt,
2641 int result_limit,
23860348 2642 threadref *original_echo,
2bc416ba 2643 threadref *resultlist,
23860348 2644 int *doneflag);
cce74817 2645
a14ed312 2646static int remote_get_threadlist (int startflag,
23860348 2647 threadref *nextthread,
a14ed312
KB
2648 int result_limit,
2649 int *done,
2bc416ba 2650 int *result_count,
23860348 2651 threadref *threadlist);
cce74817 2652
23860348 2653typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2654
a14ed312
KB
2655static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2656 void *context, int looplimit);
cce74817 2657
23860348 2658static int remote_newthread_step (threadref *ref, void *context);
cce74817 2659
82f73884
PA
2660
2661/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2662 buffer we're allowed to write to. Returns
2663 BUF+CHARACTERS_WRITTEN. */
2664
2665static char *
2666write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2667{
2668 int pid, tid;
2669 struct remote_state *rs = get_remote_state ();
2670
2671 if (remote_multi_process_p (rs))
2672 {
2673 pid = ptid_get_pid (ptid);
2674 if (pid < 0)
2675 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2676 else
2677 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2678 }
ba348170 2679 tid = ptid_get_lwp (ptid);
82f73884
PA
2680 if (tid < 0)
2681 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2682 else
2683 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2684
2685 return buf;
2686}
2687
256642e8
PA
2688/* Extract a PTID from BUF. If non-null, OBUF is set to one past the
2689 last parsed char. Returns null_ptid if no thread id is found, and
2690 throws an error if the thread id has an invalid format. */
82f73884
PA
2691
2692static ptid_t
256642e8 2693read_ptid (const char *buf, const char **obuf)
82f73884 2694{
256642e8
PA
2695 const char *p = buf;
2696 const char *pp;
82f73884 2697 ULONGEST pid = 0, tid = 0;
82f73884
PA
2698
2699 if (*p == 'p')
2700 {
2701 /* Multi-process ptid. */
2702 pp = unpack_varlen_hex (p + 1, &pid);
2703 if (*pp != '.')
b37520b6 2704 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2705
2706 p = pp;
2707 pp = unpack_varlen_hex (p + 1, &tid);
2708 if (obuf)
2709 *obuf = pp;
ba348170 2710 return ptid_build (pid, tid, 0);
82f73884
PA
2711 }
2712
2713 /* No multi-process. Just a tid. */
2714 pp = unpack_varlen_hex (p, &tid);
2715
c9f35b34
KB
2716 /* Return null_ptid when no thread id is found. */
2717 if (p == pp)
2718 {
2719 if (obuf)
2720 *obuf = pp;
2721 return null_ptid;
2722 }
2723
82f73884 2724 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2725 what's in inferior_ptid, unless it's null at this point. If so,
2726 then since there's no way to know the pid of the reported
2727 threads, use the magic number. */
2728 if (ptid_equal (inferior_ptid, null_ptid))
2729 pid = ptid_get_pid (magic_null_ptid);
2730 else
2731 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2732
2733 if (obuf)
2734 *obuf = pp;
ba348170 2735 return ptid_build (pid, tid, 0);
82f73884
PA
2736}
2737
c906108c 2738static int
fba45db2 2739stubhex (int ch)
c906108c
SS
2740{
2741 if (ch >= 'a' && ch <= 'f')
2742 return ch - 'a' + 10;
2743 if (ch >= '0' && ch <= '9')
2744 return ch - '0';
2745 if (ch >= 'A' && ch <= 'F')
2746 return ch - 'A' + 10;
2747 return -1;
2748}
2749
2750static int
fba45db2 2751stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2752{
2753 int nibble;
2754 int retval = 0;
2755
2756 while (fieldlength)
2757 {
2758 nibble = stubhex (*buff++);
2759 retval |= nibble;
2760 fieldlength--;
2761 if (fieldlength)
2762 retval = retval << 4;
2763 }
2764 return retval;
2765}
2766
c906108c 2767static char *
fba45db2 2768unpack_nibble (char *buf, int *val)
c906108c 2769{
b7589f7d 2770 *val = fromhex (*buf++);
c906108c
SS
2771 return buf;
2772}
2773
c906108c 2774static char *
fba45db2 2775unpack_byte (char *buf, int *value)
c906108c
SS
2776{
2777 *value = stub_unpack_int (buf, 2);
2778 return buf + 2;
2779}
2780
2781static char *
fba45db2 2782pack_int (char *buf, int value)
c906108c
SS
2783{
2784 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2785 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2786 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2787 buf = pack_hex_byte (buf, (value & 0xff));
2788 return buf;
2789}
2790
2791static char *
fba45db2 2792unpack_int (char *buf, int *value)
c906108c
SS
2793{
2794 *value = stub_unpack_int (buf, 8);
2795 return buf + 8;
2796}
2797
23860348 2798#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2799static char *pack_string (char *pkt, char *string);
c906108c
SS
2800
2801static char *
fba45db2 2802pack_string (char *pkt, char *string)
c906108c
SS
2803{
2804 char ch;
2805 int len;
2806
2807 len = strlen (string);
2808 if (len > 200)
23860348 2809 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2810 pkt = pack_hex_byte (pkt, len);
2811 while (len-- > 0)
2812 {
2813 ch = *string++;
2814 if ((ch == '\0') || (ch == '#'))
23860348 2815 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2816 *pkt++ = ch;
2817 }
2818 return pkt;
2819}
2820#endif /* 0 (unused) */
2821
2822static char *
fba45db2 2823unpack_string (char *src, char *dest, int length)
c906108c
SS
2824{
2825 while (length--)
2826 *dest++ = *src++;
2827 *dest = '\0';
2828 return src;
2829}
2830
2831static char *
fba45db2 2832pack_threadid (char *pkt, threadref *id)
c906108c
SS
2833{
2834 char *limit;
2835 unsigned char *altid;
2836
2837 altid = (unsigned char *) id;
2838 limit = pkt + BUF_THREAD_ID_SIZE;
2839 while (pkt < limit)
2840 pkt = pack_hex_byte (pkt, *altid++);
2841 return pkt;
2842}
2843
2844
2845static char *
fba45db2 2846unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2847{
2848 char *altref;
2849 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2850 int x, y;
2851
2852 altref = (char *) id;
2853
2854 while (inbuf < limit)
2855 {
2856 x = stubhex (*inbuf++);
2857 y = stubhex (*inbuf++);
2858 *altref++ = (x << 4) | y;
2859 }
2860 return inbuf;
2861}
2862
2863/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2864 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2865 to use 64bit thread references internally. This is an adapter
2866 function. */
2867
2868void
fba45db2 2869int_to_threadref (threadref *id, int value)
c906108c
SS
2870{
2871 unsigned char *scan;
2872
2873 scan = (unsigned char *) id;
2874 {
2875 int i = 4;
2876 while (i--)
2877 *scan++ = 0;
2878 }
2879 *scan++ = (value >> 24) & 0xff;
2880 *scan++ = (value >> 16) & 0xff;
2881 *scan++ = (value >> 8) & 0xff;
2882 *scan++ = (value & 0xff);
2883}
2884
2885static int
fba45db2 2886threadref_to_int (threadref *ref)
c906108c
SS
2887{
2888 int i, value = 0;
2889 unsigned char *scan;
2890
cfd77fa1 2891 scan = *ref;
c906108c
SS
2892 scan += 4;
2893 i = 4;
2894 while (i-- > 0)
2895 value = (value << 8) | ((*scan++) & 0xff);
2896 return value;
2897}
2898
2899static void
fba45db2 2900copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2901{
2902 int i;
2903 unsigned char *csrc, *cdest;
2904
2905 csrc = (unsigned char *) src;
2906 cdest = (unsigned char *) dest;
2907 i = 8;
2908 while (i--)
2909 *cdest++ = *csrc++;
2910}
2911
2912static int
fba45db2 2913threadmatch (threadref *dest, threadref *src)
c906108c 2914{
23860348 2915 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2916#if 0
2917 unsigned char *srcp, *destp;
2918 int i, result;
2919 srcp = (char *) src;
2920 destp = (char *) dest;
2921
2922 result = 1;
2923 while (i-- > 0)
2924 result &= (*srcp++ == *destp++) ? 1 : 0;
2925 return result;
2926#endif
2927 return 1;
2928}
2929
2930/*
c5aa993b
JM
2931 threadid:1, # always request threadid
2932 context_exists:2,
2933 display:4,
2934 unique_name:8,
2935 more_display:16
2936 */
c906108c
SS
2937
2938/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2939
2940static char *
fba45db2 2941pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2942{
23860348
MS
2943 *pkt++ = 'q'; /* Info Query */
2944 *pkt++ = 'P'; /* process or thread info */
2945 pkt = pack_int (pkt, mode); /* mode */
c906108c 2946 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2947 *pkt = '\0'; /* terminate */
c906108c
SS
2948 return pkt;
2949}
2950
23860348 2951/* These values tag the fields in a thread info response packet. */
c906108c 2952/* Tagging the fields allows us to request specific fields and to
23860348 2953 add more fields as time goes by. */
c906108c 2954
23860348 2955#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2956#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2957 fetch registers and its stack? */
c5aa993b 2958#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2959#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2960#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2961 the process. */
c906108c
SS
2962
2963static int
fba45db2
KB
2964remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2965 struct gdb_ext_thread_info *info)
c906108c 2966{
d01949b6 2967 struct remote_state *rs = get_remote_state ();
c906108c 2968 int mask, length;
cfd77fa1 2969 int tag;
c906108c 2970 threadref ref;
6d820c5c 2971 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2972 int retval = 1;
2973
23860348 2974 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2975 info->active = 0;
2976 info->display[0] = '\0';
2977 info->shortname[0] = '\0';
2978 info->more_display[0] = '\0';
2979
23860348
MS
2980 /* Assume the characters indicating the packet type have been
2981 stripped. */
c906108c
SS
2982 pkt = unpack_int (pkt, &mask); /* arg mask */
2983 pkt = unpack_threadid (pkt, &ref);
2984
2985 if (mask == 0)
8a3fe4f8 2986 warning (_("Incomplete response to threadinfo request."));
c906108c 2987 if (!threadmatch (&ref, expectedref))
23860348 2988 { /* This is an answer to a different request. */
8a3fe4f8 2989 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2990 return 0;
2991 }
2992 copy_threadref (&info->threadid, &ref);
2993
23860348 2994 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2995
23860348
MS
2996 /* Packets are terminated with nulls. */
2997 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2998 {
2999 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
3000 pkt = unpack_byte (pkt, &length); /* length */
3001 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 3002 {
8a3fe4f8 3003 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
3004 retval = 0;
3005 break;
3006 }
3007 if (tag == TAG_THREADID)
3008 {
3009 if (length != 16)
3010 {
8a3fe4f8 3011 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
3012 retval = 0;
3013 break;
3014 }
3015 pkt = unpack_threadid (pkt, &ref);
3016 mask = mask & ~TAG_THREADID;
3017 continue;
3018 }
3019 if (tag == TAG_EXISTS)
3020 {
3021 info->active = stub_unpack_int (pkt, length);
3022 pkt += length;
3023 mask = mask & ~(TAG_EXISTS);
3024 if (length > 8)
3025 {
8a3fe4f8 3026 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
3027 retval = 0;
3028 break;
3029 }
3030 continue;
3031 }
3032 if (tag == TAG_THREADNAME)
3033 {
3034 pkt = unpack_string (pkt, &info->shortname[0], length);
3035 mask = mask & ~TAG_THREADNAME;
3036 continue;
3037 }
3038 if (tag == TAG_DISPLAY)
3039 {
3040 pkt = unpack_string (pkt, &info->display[0], length);
3041 mask = mask & ~TAG_DISPLAY;
3042 continue;
3043 }
3044 if (tag == TAG_MOREDISPLAY)
3045 {
3046 pkt = unpack_string (pkt, &info->more_display[0], length);
3047 mask = mask & ~TAG_MOREDISPLAY;
3048 continue;
3049 }
8a3fe4f8 3050 warning (_("ERROR RMT: unknown thread info tag."));
23860348 3051 break; /* Not a tag we know about. */
c906108c
SS
3052 }
3053 return retval;
3054}
3055
3056static int
fba45db2
KB
3057remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
3058 struct gdb_ext_thread_info *info)
c906108c 3059{
d01949b6 3060 struct remote_state *rs = get_remote_state ();
c906108c 3061 int result;
c906108c 3062
2e9f7625
DJ
3063 pack_threadinfo_request (rs->buf, fieldset, threadid);
3064 putpkt (rs->buf);
6d820c5c 3065 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
3066
3067 if (rs->buf[0] == '\0')
3068 return 0;
3069
2e9f7625 3070 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 3071 threadid, info);
c906108c
SS
3072 return result;
3073}
3074
c906108c
SS
3075/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3076
3077static char *
fba45db2
KB
3078pack_threadlist_request (char *pkt, int startflag, int threadcount,
3079 threadref *nextthread)
c906108c
SS
3080{
3081 *pkt++ = 'q'; /* info query packet */
3082 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 3083 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
3084 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3085 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3086 *pkt = '\0';
3087 return pkt;
3088}
3089
3090/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3091
3092static int
fba45db2
KB
3093parse_threadlist_response (char *pkt, int result_limit,
3094 threadref *original_echo, threadref *resultlist,
3095 int *doneflag)
c906108c 3096{
d01949b6 3097 struct remote_state *rs = get_remote_state ();
c906108c
SS
3098 char *limit;
3099 int count, resultcount, done;
3100
3101 resultcount = 0;
3102 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 3103 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 3104 /* done parse past here */
c906108c
SS
3105 pkt = unpack_byte (pkt, &count); /* count field */
3106 pkt = unpack_nibble (pkt, &done);
3107 /* The first threadid is the argument threadid. */
3108 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3109 while ((count-- > 0) && (pkt < limit))
3110 {
3111 pkt = unpack_threadid (pkt, resultlist++);
3112 if (resultcount++ >= result_limit)
3113 break;
3114 }
3115 if (doneflag)
3116 *doneflag = done;
3117 return resultcount;
3118}
3119
6dc54d91
PA
3120/* Fetch the next batch of threads from the remote. Returns -1 if the
3121 qL packet is not supported, 0 on error and 1 on success. */
3122
c906108c 3123static int
fba45db2
KB
3124remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
3125 int *done, int *result_count, threadref *threadlist)
c906108c 3126{
d01949b6 3127 struct remote_state *rs = get_remote_state ();
c906108c
SS
3128 int result = 1;
3129
23860348 3130 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
3131 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3132 >= get_remote_packet_size ())
ea9c271d 3133 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 3134
6d820c5c
DJ
3135 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
3136 putpkt (rs->buf);
3137 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 3138 if (*rs->buf == '\0')
6dc54d91
PA
3139 {
3140 /* Packet not supported. */
3141 return -1;
3142 }
3143
3144 *result_count =
3145 parse_threadlist_response (rs->buf + 2, result_limit,
3146 &rs->echo_nextthread, threadlist, done);
c906108c 3147
0d031856 3148 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 3149 {
23860348
MS
3150 /* FIXME: This is a good reason to drop the packet. */
3151 /* Possably, there is a duplicate response. */
c906108c
SS
3152 /* Possabilities :
3153 retransmit immediatly - race conditions
3154 retransmit after timeout - yes
3155 exit
3156 wait for packet, then exit
3157 */
8a3fe4f8 3158 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 3159 return 0; /* I choose simply exiting. */
c906108c
SS
3160 }
3161 if (*result_count <= 0)
3162 {
3163 if (*done != 1)
3164 {
8a3fe4f8 3165 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
3166 result = 0;
3167 }
3168 return result; /* break; */
3169 }
3170 if (*result_count > result_limit)
3171 {
3172 *result_count = 0;
8a3fe4f8 3173 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
3174 return 0;
3175 }
3176 return result;
3177}
3178
6dc54d91
PA
3179/* Fetch the list of remote threads, with the qL packet, and call
3180 STEPFUNCTION for each thread found. Stops iterating and returns 1
3181 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3182 STEPFUNCTION returns false. If the packet is not supported,
3183 returns -1. */
c906108c 3184
c906108c 3185static int
fba45db2
KB
3186remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
3187 int looplimit)
c906108c 3188{
0d031856 3189 struct remote_state *rs = get_remote_state ();
c906108c
SS
3190 int done, i, result_count;
3191 int startflag = 1;
3192 int result = 1;
3193 int loopcount = 0;
c906108c
SS
3194
3195 done = 0;
3196 while (!done)
3197 {
3198 if (loopcount++ > looplimit)
3199 {
3200 result = 0;
8a3fe4f8 3201 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
3202 break;
3203 }
6dc54d91
PA
3204 result = remote_get_threadlist (startflag, &rs->nextthread,
3205 MAXTHREADLISTRESULTS,
3206 &done, &result_count,
3207 rs->resultthreadlist);
3208 if (result <= 0)
3209 break;
23860348 3210 /* Clear for later iterations. */
c906108c
SS
3211 startflag = 0;
3212 /* Setup to resume next batch of thread references, set nextthread. */
3213 if (result_count >= 1)
0d031856
TT
3214 copy_threadref (&rs->nextthread,
3215 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
3216 i = 0;
3217 while (result_count--)
6dc54d91
PA
3218 {
3219 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3220 {
3221 result = 0;
3222 break;
3223 }
3224 }
c906108c
SS
3225 }
3226 return result;
3227}
3228
6dc54d91
PA
3229/* A thread found on the remote target. */
3230
21fe1c75 3231struct thread_item
6dc54d91 3232{
21fe1c75
SM
3233 explicit thread_item (ptid_t ptid_)
3234 : ptid (ptid_)
3235 {}
3236
3237 thread_item (thread_item &&other) = default;
3238 thread_item &operator= (thread_item &&other) = default;
3239
3240 DISABLE_COPY_AND_ASSIGN (thread_item);
3241
6dc54d91
PA
3242 /* The thread's PTID. */
3243 ptid_t ptid;
3244
21fe1c75
SM
3245 /* The thread's extra info. */
3246 std::string extra;
6dc54d91 3247
21fe1c75
SM
3248 /* The thread's name. */
3249 std::string name;
79efa585 3250
6dc54d91 3251 /* The core the thread was running on. -1 if not known. */
21fe1c75 3252 int core = -1;
f6327dcb
KB
3253
3254 /* The thread handle associated with the thread. */
21fe1c75 3255 gdb::byte_vector thread_handle;
21fe1c75 3256};
6dc54d91
PA
3257
3258/* Context passed around to the various methods listing remote
3259 threads. As new threads are found, they're added to the ITEMS
3260 vector. */
3261
3262struct threads_listing_context
3263{
21fe1c75
SM
3264 /* Return true if this object contains an entry for a thread with ptid
3265 PTID. */
6dc54d91 3266
21fe1c75
SM
3267 bool contains_thread (ptid_t ptid) const
3268 {
3269 auto match_ptid = [&] (const thread_item &item)
3270 {
3271 return item.ptid == ptid;
3272 };
80134cf5 3273
21fe1c75
SM
3274 auto it = std::find_if (this->items.begin (),
3275 this->items.end (),
3276 match_ptid);
80134cf5 3277
21fe1c75
SM
3278 return it != this->items.end ();
3279 }
80134cf5 3280
21fe1c75 3281 /* Remove the thread with ptid PTID. */
80134cf5 3282
21fe1c75
SM
3283 void remove_thread (ptid_t ptid)
3284 {
3285 auto match_ptid = [&] (const thread_item &item)
3286 {
3287 return item.ptid == ptid;
3288 };
cbb8991c 3289
21fe1c75
SM
3290 auto it = std::remove_if (this->items.begin (),
3291 this->items.end (),
3292 match_ptid);
cbb8991c 3293
21fe1c75
SM
3294 if (it != this->items.end ())
3295 this->items.erase (it);
3296 }
3297
3298 /* The threads found on the remote target. */
3299 std::vector<thread_item> items;
3300};
cbb8991c 3301
c906108c 3302static int
6dc54d91 3303remote_newthread_step (threadref *ref, void *data)
c906108c 3304{
19ba03f4
SM
3305 struct threads_listing_context *context
3306 = (struct threads_listing_context *) data;
21fe1c75
SM
3307 int pid = inferior_ptid.pid ();
3308 int lwp = threadref_to_int (ref);
3309 ptid_t ptid (pid, lwp);
6dc54d91 3310
21fe1c75 3311 context->items.emplace_back (ptid);
6dc54d91 3312
c906108c
SS
3313 return 1; /* continue iterator */
3314}
3315
3316#define CRAZY_MAX_THREADS 1000
3317
39f77062
KB
3318static ptid_t
3319remote_current_thread (ptid_t oldpid)
c906108c 3320{
d01949b6 3321 struct remote_state *rs = get_remote_state ();
c906108c
SS
3322
3323 putpkt ("qC");
6d820c5c 3324 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3325 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34 3326 {
256642e8 3327 const char *obuf;
c9f35b34
KB
3328 ptid_t result;
3329
3330 result = read_ptid (&rs->buf[2], &obuf);
3331 if (*obuf != '\0' && remote_debug)
3332 fprintf_unfiltered (gdb_stdlog,
3333 "warning: garbage in qC reply\n");
3334
3335 return result;
3336 }
c906108c
SS
3337 else
3338 return oldpid;
3339}
3340
6dc54d91 3341/* List remote threads using the deprecated qL packet. */
cce74817 3342
6dc54d91
PA
3343static int
3344remote_get_threads_with_ql (struct target_ops *ops,
3345 struct threads_listing_context *context)
c906108c 3346{
6dc54d91
PA
3347 if (remote_threadlist_iterator (remote_newthread_step, context,
3348 CRAZY_MAX_THREADS) >= 0)
3349 return 1;
3350
3351 return 0;
c906108c
SS
3352}
3353
dc146f7c
VP
3354#if defined(HAVE_LIBEXPAT)
3355
dc146f7c
VP
3356static void
3357start_thread (struct gdb_xml_parser *parser,
3358 const struct gdb_xml_element *element,
4d0fdd9b
SM
3359 void *user_data,
3360 std::vector<gdb_xml_value> &attributes)
dc146f7c 3361{
19ba03f4
SM
3362 struct threads_listing_context *data
3363 = (struct threads_listing_context *) user_data;
3d2c1d41 3364 struct gdb_xml_value *attr;
dc146f7c 3365
4d0fdd9b 3366 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
21fe1c75
SM
3367 ptid_t ptid = read_ptid (id, NULL);
3368
3369 data->items.emplace_back (ptid);
3370 thread_item &item = data->items.back ();
dc146f7c 3371
3d2c1d41
PA
3372 attr = xml_find_attribute (attributes, "core");
3373 if (attr != NULL)
4d0fdd9b 3374 item.core = *(ULONGEST *) attr->value.get ();
dc146f7c 3375
79efa585 3376 attr = xml_find_attribute (attributes, "name");
21fe1c75 3377 if (attr != NULL)
4d0fdd9b 3378 item.name = (const char *) attr->value.get ();
79efa585 3379
f6327dcb
KB
3380 attr = xml_find_attribute (attributes, "handle");
3381 if (attr != NULL)
4d0fdd9b 3382 item.thread_handle = hex2bin ((const char *) attr->value.get ());
dc146f7c
VP
3383}
3384
3385static void
3386end_thread (struct gdb_xml_parser *parser,
3387 const struct gdb_xml_element *element,
3388 void *user_data, const char *body_text)
3389{
19ba03f4
SM
3390 struct threads_listing_context *data
3391 = (struct threads_listing_context *) user_data;
dc146f7c 3392
21fe1c75
SM
3393 if (body_text != NULL && *body_text != '\0')
3394 data->items.back ().extra = body_text;
dc146f7c
VP
3395}
3396
3397const struct gdb_xml_attribute thread_attributes[] = {
3398 { "id", GDB_XML_AF_NONE, NULL, NULL },
3399 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3400 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
f6327dcb 3401 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3402 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3403};
3404
3405const struct gdb_xml_element thread_children[] = {
3406 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3407};
3408
3409const struct gdb_xml_element threads_children[] = {
3410 { "thread", thread_attributes, thread_children,
3411 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3412 start_thread, end_thread },
3413 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3414};
3415
3416const struct gdb_xml_element threads_elements[] = {
3417 { "threads", NULL, threads_children,
3418 GDB_XML_EF_NONE, NULL, NULL },
3419 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3420};
3421
3422#endif
3423
6dc54d91 3424/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3425
6dc54d91
PA
3426static int
3427remote_get_threads_with_qxfer (struct target_ops *ops,
3428 struct threads_listing_context *context)
0f71a2f6 3429{
dc146f7c 3430#if defined(HAVE_LIBEXPAT)
4082afcc 3431 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3432 {
9018be22 3433 gdb::optional<gdb::char_vector> xml
b7b030ad 3434 = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
efc0eabd 3435
9018be22 3436 if (xml && (*xml)[0] != '\0')
dc146f7c 3437 {
6dc54d91 3438 gdb_xml_parse_quick (_("threads"), "threads.dtd",
9018be22 3439 threads_elements, xml->data (), context);
dc146f7c
VP
3440 }
3441
6dc54d91 3442 return 1;
dc146f7c
VP
3443 }
3444#endif
3445
6dc54d91
PA
3446 return 0;
3447}
3448
3449/* List remote threads using qfThreadInfo/qsThreadInfo. */
3450
3451static int
3452remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3453 struct threads_listing_context *context)
3454{
3455 struct remote_state *rs = get_remote_state ();
3456
b80fafe3 3457 if (rs->use_threadinfo_query)
9d1f7ab2 3458 {
256642e8 3459 const char *bufp;
6dc54d91 3460
9d1f7ab2 3461 putpkt ("qfThreadInfo");
6d820c5c 3462 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3463 bufp = rs->buf;
9d1f7ab2 3464 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3465 {
9d1f7ab2
MS
3466 while (*bufp++ == 'm') /* reply contains one or more TID */
3467 {
3468 do
3469 {
21fe1c75
SM
3470 ptid_t ptid = read_ptid (bufp, &bufp);
3471 context->items.emplace_back (ptid);
9d1f7ab2
MS
3472 }
3473 while (*bufp++ == ','); /* comma-separated list */
3474 putpkt ("qsThreadInfo");
6d820c5c 3475 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 3476 bufp = rs->buf;
9d1f7ab2 3477 }
6dc54d91
PA
3478 return 1;
3479 }
3480 else
3481 {
3482 /* Packet not recognized. */
3483 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3484 }
3485 }
3486
6dc54d91
PA
3487 return 0;
3488}
3489
e8032dde 3490/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3491 targets. */
3492
f6ac5f3d
PA
3493void
3494remote_target::update_thread_list ()
6dc54d91 3495{
6dc54d91 3496 struct threads_listing_context context;
ab970af1 3497 int got_list = 0;
e8032dde 3498
6dc54d91
PA
3499 /* We have a few different mechanisms to fetch the thread list. Try
3500 them all, starting with the most preferred one first, falling
3501 back to older methods. */
f6ac5f3d
PA
3502 if (remote_get_threads_with_qxfer (this, &context)
3503 || remote_get_threads_with_qthreadinfo (this, &context)
3504 || remote_get_threads_with_ql (this, &context))
6dc54d91 3505 {
ab970af1
PA
3506 struct thread_info *tp, *tmp;
3507
3508 got_list = 1;
3509
21fe1c75 3510 if (context.items.empty ()
f6ac5f3d 3511 && remote_thread_always_alive (inferior_ptid))
7d1a114c
PA
3512 {
3513 /* Some targets don't really support threads, but still
3514 reply an (empty) thread list in response to the thread
3515 listing packets, instead of replying "packet not
3516 supported". Exit early so we don't delete the main
3517 thread. */
7d1a114c
PA
3518 return;
3519 }
3520
ab970af1
PA
3521 /* CONTEXT now holds the current thread list on the remote
3522 target end. Delete GDB-side threads no longer found on the
3523 target. */
8a06aea7 3524 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3525 {
21fe1c75 3526 if (!context.contains_thread (tp->ptid))
ab970af1
PA
3527 {
3528 /* Not found. */
3529 delete_thread (tp->ptid);
3530 }
cbb8991c
DB
3531 }
3532
3533 /* Remove any unreported fork child threads from CONTEXT so
3534 that we don't interfere with follow fork, which is where
3535 creation of such threads is handled. */
3536 remove_new_fork_children (&context);
74531fed 3537
ab970af1 3538 /* And now add threads we don't know about yet to our list. */
21fe1c75 3539 for (thread_item &item : context.items)
6dc54d91 3540 {
21fe1c75 3541 if (item.ptid != null_ptid)
6dc54d91 3542 {
6dc54d91 3543 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
3544 executing until proven otherwise with a stop reply.
3545 In all-stop, we can only get here if all threads are
6dc54d91 3546 stopped. */
0d5b594f 3547 int executing = target_is_non_stop_p () ? 1 : 0;
6dc54d91 3548
21fe1c75 3549 remote_notice_new_inferior (item.ptid, executing);
6dc54d91 3550
7aabaf9d 3551 remote_thread_info *info = get_remote_thread_info (item.ptid);
21fe1c75 3552 info->core = item.core;
7aabaf9d
SM
3553 info->extra = std::move (item.extra);
3554 info->name = std::move (item.name);
3555 info->thread_handle = std::move (item.thread_handle);
6dc54d91
PA
3556 }
3557 }
3558 }
3559
ab970af1
PA
3560 if (!got_list)
3561 {
3562 /* If no thread listing method is supported, then query whether
3563 each known thread is alive, one by one, with the T packet.
3564 If the target doesn't support threads at all, then this is a
3565 no-op. See remote_thread_alive. */
3566 prune_threads ();
3567 }
9d1f7ab2
MS
3568}
3569
802188a7 3570/*
9d1f7ab2
MS
3571 * Collect a descriptive string about the given thread.
3572 * The target may say anything it wants to about the thread
3573 * (typically info about its blocked / runnable state, name, etc.).
3574 * This string will appear in the info threads display.
802188a7 3575 *
9d1f7ab2
MS
3576 * Optional: targets are not required to implement this function.
3577 */
3578
f6ac5f3d
PA
3579const char *
3580remote_target::extra_thread_info (thread_info *tp)
9d1f7ab2 3581{
d01949b6 3582 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3583 int result;
3584 int set;
3585 threadref id;
3586 struct gdb_ext_thread_info threadinfo;
23860348 3587 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3588 int n = 0; /* position in display_buf */
3589
5d93a237 3590 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3591 internal_error (__FILE__, __LINE__,
e2e0b3e5 3592 _("remote_threads_extra_info"));
9d1f7ab2 3593
60e569b9 3594 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3595 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3596 /* This is the main thread which was added by GDB. The remote
3597 server doesn't know about it. */
3598 return NULL;
3599
4082afcc 3600 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3601 {
3602 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3603
7aabaf9d 3604 if (info != NULL && info->priv != NULL)
a9334058
SM
3605 {
3606 const std::string &extra = get_remote_thread_info (info)->extra;
3607 return !extra.empty () ? extra.c_str () : NULL;
3608 }
dc146f7c
VP
3609 else
3610 return NULL;
3611 }
3612
b80fafe3 3613 if (rs->use_threadextra_query)
9d1f7ab2 3614 {
82f73884
PA
3615 char *b = rs->buf;
3616 char *endb = rs->buf + get_remote_packet_size ();
3617
3618 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3619 b += strlen (b);
3620 write_ptid (b, endb, tp->ptid);
3621
2e9f7625 3622 putpkt (rs->buf);
6d820c5c 3623 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3624 if (rs->buf[0] != 0)
9d1f7ab2 3625 {
325fac50 3626 n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
2e9f7625 3627 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3628 display_buf [result] = '\0';
9d1f7ab2
MS
3629 return display_buf;
3630 }
0f71a2f6 3631 }
9d1f7ab2
MS
3632
3633 /* If the above query fails, fall back to the old method. */
b80fafe3 3634 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3635 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3636 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3637 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3638 if (remote_get_threadinfo (&id, set, &threadinfo))
3639 if (threadinfo.active)
0f71a2f6 3640 {
9d1f7ab2 3641 if (*threadinfo.shortname)
2bc416ba 3642 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3643 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3644 if (*threadinfo.display)
2bc416ba 3645 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3646 " State: %s,", threadinfo.display);
9d1f7ab2 3647 if (*threadinfo.more_display)
2bc416ba 3648 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3649 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3650
3651 if (n > 0)
c5aa993b 3652 {
23860348 3653 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3654 if (',' == display_buf[n-1])
3655 display_buf[n-1] = ' ';
3656 return display_buf;
c5aa993b 3657 }
0f71a2f6 3658 }
9d1f7ab2 3659 return NULL;
0f71a2f6 3660}
c906108c 3661\f
c5aa993b 3662
f6ac5f3d
PA
3663bool
3664remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3665 struct static_tracepoint_marker *marker)
0fb4aa4b
PA
3666{
3667 struct remote_state *rs = get_remote_state ();
3668 char *p = rs->buf;
3669
bba74b36 3670 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3671 p += strlen (p);
3672 p += hexnumstr (p, addr);
3673 putpkt (rs->buf);
3674 getpkt (&rs->buf, &rs->buf_size, 0);
3675 p = rs->buf;
3676
3677 if (*p == 'E')
3678 error (_("Remote failure reply: %s"), p);
3679
3680 if (*p++ == 'm')
3681 {
256642e8 3682 parse_static_tracepoint_marker_definition (p, NULL, marker);
5d9310c4 3683 return true;
0fb4aa4b
PA
3684 }
3685
5d9310c4 3686 return false;
0fb4aa4b
PA
3687}
3688
f6ac5f3d
PA
3689std::vector<static_tracepoint_marker>
3690remote_target::static_tracepoint_markers_by_strid (const char *strid)
0fb4aa4b
PA
3691{
3692 struct remote_state *rs = get_remote_state ();
5d9310c4 3693 std::vector<static_tracepoint_marker> markers;
256642e8 3694 const char *p;
5d9310c4 3695 static_tracepoint_marker marker;
0fb4aa4b
PA
3696
3697 /* Ask for a first packet of static tracepoint marker
3698 definition. */
3699 putpkt ("qTfSTM");
3700 getpkt (&rs->buf, &rs->buf_size, 0);
3701 p = rs->buf;
3702 if (*p == 'E')
3703 error (_("Remote failure reply: %s"), p);
3704
0fb4aa4b
PA
3705 while (*p++ == 'm')
3706 {
0fb4aa4b
PA
3707 do
3708 {
5d9310c4 3709 parse_static_tracepoint_marker_definition (p, &p, &marker);
0fb4aa4b 3710
5d9310c4
SM
3711 if (strid == NULL || marker.str_id == strid)
3712 markers.push_back (std::move (marker));
0fb4aa4b
PA
3713 }
3714 while (*p++ == ','); /* comma-separated list */
3715 /* Ask for another packet of static tracepoint definition. */
3716 putpkt ("qTsSTM");
3717 getpkt (&rs->buf, &rs->buf_size, 0);
3718 p = rs->buf;
3719 }
3720
0fb4aa4b
PA
3721 return markers;
3722}
3723
3724\f
10760264
JB
3725/* Implement the to_get_ada_task_ptid function for the remote targets. */
3726
f6ac5f3d
PA
3727ptid_t
3728remote_target::get_ada_task_ptid (long lwp, long thread)
10760264 3729{
ba348170 3730 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3731}
3732\f
3733
24b06219 3734/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3735
3736static void
fba45db2 3737extended_remote_restart (void)
c906108c 3738{
d01949b6 3739 struct remote_state *rs = get_remote_state ();
c906108c
SS
3740
3741 /* Send the restart command; for reasons I don't understand the
3742 remote side really expects a number after the "R". */
ea9c271d 3743 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3744 putpkt (rs->buf);
c906108c 3745
ad9a8f3f 3746 remote_fileio_reset ();
c906108c
SS
3747}
3748\f
3749/* Clean up connection to a remote debugger. */
3750
f6ac5f3d
PA
3751void
3752remote_target::close ()
c906108c 3753{
5d93a237
TT
3754 struct remote_state *rs = get_remote_state ();
3755
3756 if (rs->remote_desc == NULL)
d3fd5342
PA
3757 return; /* already closed */
3758
048094ac 3759 /* Make sure we leave stdin registered in the event loop. */
f6ac5f3d 3760 terminal_ours ();
ce5ce7ed 3761
5d93a237
TT
3762 serial_close (rs->remote_desc);
3763 rs->remote_desc = NULL;
ce5ce7ed
PA
3764
3765 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3766 of all the inferiors and their threads we were controlling.
3767 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3768 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3769 inferior_ptid = null_ptid;
f67fd822 3770 discard_all_inferiors ();
ce5ce7ed 3771
f48ff2a7
YQ
3772 /* We are closing the remote target, so we should discard
3773 everything of this target. */
bcc75809 3774 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3775
3776 if (remote_async_inferior_event_token)
3777 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3778
5965e028 3779 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3780
3781 trace_reset_local_state ();
c906108c
SS
3782}
3783
23860348 3784/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3785
3786static void
fba45db2 3787get_offsets (void)
c906108c 3788{
d01949b6 3789 struct remote_state *rs = get_remote_state ();
2e9f7625 3790 char *buf;
085dd6e6 3791 char *ptr;
31d99776
DJ
3792 int lose, num_segments = 0, do_sections, do_segments;
3793 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3794 struct section_offsets *offs;
31d99776
DJ
3795 struct symfile_segment_data *data;
3796
3797 if (symfile_objfile == NULL)
3798 return;
c906108c
SS
3799
3800 putpkt ("qOffsets");
6d820c5c 3801 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3802 buf = rs->buf;
c906108c
SS
3803
3804 if (buf[0] == '\000')
3805 return; /* Return silently. Stub doesn't support
23860348 3806 this command. */
c906108c
SS
3807 if (buf[0] == 'E')
3808 {
8a3fe4f8 3809 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3810 return;
3811 }
3812
3813 /* Pick up each field in turn. This used to be done with scanf, but
3814 scanf will make trouble if CORE_ADDR size doesn't match
3815 conversion directives correctly. The following code will work
3816 with any size of CORE_ADDR. */
3817 text_addr = data_addr = bss_addr = 0;
3818 ptr = buf;
3819 lose = 0;
3820
61012eef 3821 if (startswith (ptr, "Text="))
c906108c
SS
3822 {
3823 ptr += 5;
3824 /* Don't use strtol, could lose on big values. */
3825 while (*ptr && *ptr != ';')
3826 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3827
61012eef 3828 if (startswith (ptr, ";Data="))
31d99776
DJ
3829 {
3830 ptr += 6;
3831 while (*ptr && *ptr != ';')
3832 data_addr = (data_addr << 4) + fromhex (*ptr++);
3833 }
3834 else
3835 lose = 1;
3836
61012eef 3837 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3838 {
3839 ptr += 5;
3840 while (*ptr && *ptr != ';')
3841 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3842
31d99776
DJ
3843 if (bss_addr != data_addr)
3844 warning (_("Target reported unsupported offsets: %s"), buf);
3845 }
3846 else
3847 lose = 1;
3848 }
61012eef 3849 else if (startswith (ptr, "TextSeg="))
c906108c 3850 {
31d99776
DJ
3851 ptr += 8;
3852 /* Don't use strtol, could lose on big values. */
c906108c 3853 while (*ptr && *ptr != ';')
31d99776
DJ
3854 text_addr = (text_addr << 4) + fromhex (*ptr++);
3855 num_segments = 1;
3856
61012eef 3857 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3858 {
3859 ptr += 9;
3860 while (*ptr && *ptr != ';')
3861 data_addr = (data_addr << 4) + fromhex (*ptr++);
3862 num_segments++;
3863 }
c906108c
SS
3864 }
3865 else
3866 lose = 1;
3867
3868 if (lose)
8a3fe4f8 3869 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3870 else if (*ptr != '\0')
3871 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3872
802188a7 3873 offs = ((struct section_offsets *)
a39a16c4 3874 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3875 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3876 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3877
31d99776
DJ
3878 data = get_symfile_segment_data (symfile_objfile->obfd);
3879 do_segments = (data != NULL);
3880 do_sections = num_segments == 0;
c906108c 3881
28c32713 3882 if (num_segments > 0)
31d99776 3883 {
31d99776
DJ
3884 segments[0] = text_addr;
3885 segments[1] = data_addr;
3886 }
28c32713
JB
3887 /* If we have two segments, we can still try to relocate everything
3888 by assuming that the .text and .data offsets apply to the whole
3889 text and data segments. Convert the offsets given in the packet
3890 to base addresses for symfile_map_offsets_to_segments. */
3891 else if (data && data->num_segments == 2)
3892 {
3893 segments[0] = data->segment_bases[0] + text_addr;
3894 segments[1] = data->segment_bases[1] + data_addr;
3895 num_segments = 2;
3896 }
8d385431
DJ
3897 /* If the object file has only one segment, assume that it is text
3898 rather than data; main programs with no writable data are rare,
3899 but programs with no code are useless. Of course the code might
3900 have ended up in the data segment... to detect that we would need
3901 the permissions here. */
3902 else if (data && data->num_segments == 1)
3903 {
3904 segments[0] = data->segment_bases[0] + text_addr;
3905 num_segments = 1;
3906 }
28c32713
JB
3907 /* There's no way to relocate by segment. */
3908 else
3909 do_segments = 0;
31d99776
DJ
3910
3911 if (do_segments)
3912 {
3913 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3914 offs, num_segments, segments);
3915
3916 if (ret == 0 && !do_sections)
3e43a32a
MS
3917 error (_("Can not handle qOffsets TextSeg "
3918 "response with this symbol file"));
31d99776
DJ
3919
3920 if (ret > 0)
3921 do_sections = 0;
3922 }
c906108c 3923
9ef895d6
DJ
3924 if (data)
3925 free_symfile_segment_data (data);
31d99776
DJ
3926
3927 if (do_sections)
3928 {
3929 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3930
3e43a32a
MS
3931 /* This is a temporary kludge to force data and bss to use the
3932 same offsets because that's what nlmconv does now. The real
3933 solution requires changes to the stub and remote.c that I
3934 don't have time to do right now. */
31d99776
DJ
3935
3936 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3937 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3938 }
c906108c
SS
3939
3940 objfile_relocate (symfile_objfile, offs);
3941}
3942
9a7071a8
JB
3943/* Send interrupt_sequence to remote target. */
3944static void
eeae04df 3945send_interrupt_sequence (void)
9a7071a8 3946{
5d93a237
TT
3947 struct remote_state *rs = get_remote_state ();
3948
9a7071a8 3949 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3950 remote_serial_write ("\x03", 1);
9a7071a8 3951 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3952 serial_send_break (rs->remote_desc);
9a7071a8
JB
3953 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3954 {
5d93a237 3955 serial_send_break (rs->remote_desc);
c33e31fd 3956 remote_serial_write ("g", 1);
9a7071a8
JB
3957 }
3958 else
3959 internal_error (__FILE__, __LINE__,
3960 _("Invalid value for interrupt_sequence_mode: %s."),
3961 interrupt_sequence_mode);
3962}
3963
3405876a
PA
3964
3965/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3966 and extract the PTID. Returns NULL_PTID if not found. */
3967
3968static ptid_t
3969stop_reply_extract_thread (char *stop_reply)
3970{
3971 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3972 {
256642e8 3973 const char *p;
3405876a
PA
3974
3975 /* Txx r:val ; r:val (...) */
3976 p = &stop_reply[3];
3977
3978 /* Look for "register" named "thread". */
3979 while (*p != '\0')
3980 {
256642e8 3981 const char *p1;
3405876a
PA
3982
3983 p1 = strchr (p, ':');
3984 if (p1 == NULL)
3985 return null_ptid;
3986
3987 if (strncmp (p, "thread", p1 - p) == 0)
3988 return read_ptid (++p1, &p);
3989
3990 p1 = strchr (p, ';');
3991 if (p1 == NULL)
3992 return null_ptid;
3993 p1++;
3994
3995 p = p1;
3996 }
3997 }
3998
3999 return null_ptid;
4000}
4001
b7ea362b
PA
4002/* Determine the remote side's current thread. If we have a stop
4003 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4004 "thread" register we can extract the current thread from. If not,
4005 ask the remote which is the current thread with qC. The former
4006 method avoids a roundtrip. */
4007
4008static ptid_t
4009get_current_thread (char *wait_status)
4010{
6a49a997 4011 ptid_t ptid = null_ptid;
b7ea362b
PA
4012
4013 /* Note we don't use remote_parse_stop_reply as that makes use of
4014 the target architecture, which we haven't yet fully determined at
4015 this point. */
4016 if (wait_status != NULL)
4017 ptid = stop_reply_extract_thread (wait_status);
4018 if (ptid_equal (ptid, null_ptid))
4019 ptid = remote_current_thread (inferior_ptid);
4020
4021 return ptid;
4022}
4023
49c62f2e
PA
4024/* Query the remote target for which is the current thread/process,
4025 add it to our tables, and update INFERIOR_PTID. The caller is
4026 responsible for setting the state such that the remote end is ready
3405876a
PA
4027 to return the current thread.
4028
4029 This function is called after handling the '?' or 'vRun' packets,
4030 whose response is a stop reply from which we can also try
4031 extracting the thread. If the target doesn't support the explicit
4032 qC query, we infer the current thread from that stop reply, passed
4033 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
4034
4035static void
3405876a 4036add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
4037{
4038 struct remote_state *rs = get_remote_state ();
4039 int fake_pid_p = 0;
49c62f2e
PA
4040
4041 inferior_ptid = null_ptid;
4042
b7ea362b 4043 /* Now, if we have thread information, update inferior_ptid. */
87215ad1 4044 ptid_t curr_ptid = get_current_thread (wait_status);
3405876a 4045
87215ad1 4046 if (curr_ptid != null_ptid)
49c62f2e
PA
4047 {
4048 if (!remote_multi_process_p (rs))
4049 fake_pid_p = 1;
49c62f2e
PA
4050 }
4051 else
4052 {
4053 /* Without this, some commands which require an active target
4054 (such as kill) won't work. This variable serves (at least)
4055 double duty as both the pid of the target process (if it has
4056 such), and as a flag indicating that a target is active. */
87215ad1 4057 curr_ptid = magic_null_ptid;
49c62f2e
PA
4058 fake_pid_p = 1;
4059 }
4060
87215ad1 4061 remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
49c62f2e 4062
87215ad1
SDJ
4063 /* Add the main thread and switch to it. Don't try reading
4064 registers yet, since we haven't fetched the target description
4065 yet. */
4066 thread_info *tp = add_thread_silent (curr_ptid);
4067 switch_to_thread_no_regs (tp);
49c62f2e
PA
4068}
4069
6efcd9a8
PA
4070/* Print info about a thread that was found already stopped on
4071 connection. */
4072
4073static void
4074print_one_stopped_thread (struct thread_info *thread)
4075{
4076 struct target_waitstatus *ws = &thread->suspend.waitstatus;
4077
4078 switch_to_thread (thread->ptid);
4079 stop_pc = get_frame_pc (get_current_frame ());
4080 set_current_sal_from_frame (get_current_frame ());
4081
4082 thread->suspend.waitstatus_pending_p = 0;
4083
4084 if (ws->kind == TARGET_WAITKIND_STOPPED)
4085 {
4086 enum gdb_signal sig = ws->value.sig;
4087
4088 if (signal_print_state (sig))
76727919 4089 gdb::observers::signal_received.notify (sig);
6efcd9a8 4090 }
76727919 4091 gdb::observers::normal_stop.notify (NULL, 1);
6efcd9a8
PA
4092}
4093
221e1a37
PA
4094/* Process all initial stop replies the remote side sent in response
4095 to the ? packet. These indicate threads that were already stopped
4096 on initial connection. We mark these threads as stopped and print
4097 their current frame before giving the user the prompt. */
4098
4099static void
6efcd9a8 4100process_initial_stop_replies (int from_tty)
221e1a37
PA
4101{
4102 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
4103 struct inferior *inf;
4104 struct thread_info *thread;
4105 struct thread_info *selected = NULL;
4106 struct thread_info *lowest_stopped = NULL;
4107 struct thread_info *first = NULL;
221e1a37
PA
4108
4109 /* Consume the initial pending events. */
4110 while (pending_stop_replies-- > 0)
4111 {
4112 ptid_t waiton_ptid = minus_one_ptid;
4113 ptid_t event_ptid;
4114 struct target_waitstatus ws;
4115 int ignore_event = 0;
6efcd9a8 4116 struct thread_info *thread;
221e1a37
PA
4117
4118 memset (&ws, 0, sizeof (ws));
4119 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4120 if (remote_debug)
4121 print_target_wait_results (waiton_ptid, event_ptid, &ws);
4122
4123 switch (ws.kind)
4124 {
4125 case TARGET_WAITKIND_IGNORE:
4126 case TARGET_WAITKIND_NO_RESUMED:
4127 case TARGET_WAITKIND_SIGNALLED:
4128 case TARGET_WAITKIND_EXITED:
4129 /* We shouldn't see these, but if we do, just ignore. */
4130 if (remote_debug)
4131 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4132 ignore_event = 1;
4133 break;
4134
4135 case TARGET_WAITKIND_EXECD:
4136 xfree (ws.value.execd_pathname);
4137 break;
4138 default:
4139 break;
4140 }
4141
4142 if (ignore_event)
4143 continue;
4144
6efcd9a8 4145 thread = find_thread_ptid (event_ptid);
221e1a37
PA
4146
4147 if (ws.kind == TARGET_WAITKIND_STOPPED)
4148 {
4149 enum gdb_signal sig = ws.value.sig;
4150
4151 /* Stubs traditionally report SIGTRAP as initial signal,
4152 instead of signal 0. Suppress it. */
4153 if (sig == GDB_SIGNAL_TRAP)
4154 sig = GDB_SIGNAL_0;
6efcd9a8
PA
4155 thread->suspend.stop_signal = sig;
4156 ws.value.sig = sig;
4157 }
221e1a37 4158
6efcd9a8
PA
4159 thread->suspend.waitstatus = ws;
4160
4161 if (ws.kind != TARGET_WAITKIND_STOPPED
4162 || ws.value.sig != GDB_SIGNAL_0)
4163 thread->suspend.waitstatus_pending_p = 1;
4164
4165 set_executing (event_ptid, 0);
4166 set_running (event_ptid, 0);
7aabaf9d 4167 get_remote_thread_info (thread)->vcont_resumed = 0;
6efcd9a8
PA
4168 }
4169
4170 /* "Notice" the new inferiors before anything related to
4171 registers/memory. */
4172 ALL_INFERIORS (inf)
4173 {
4174 if (inf->pid == 0)
4175 continue;
4176
4177 inf->needs_setup = 1;
4178
4179 if (non_stop)
4180 {
4181 thread = any_live_thread_of_process (inf->pid);
4182 notice_new_inferior (thread->ptid,
4183 thread->state == THREAD_RUNNING,
4184 from_tty);
4185 }
4186 }
4187
4188 /* If all-stop on top of non-stop, pause all threads. Note this
4189 records the threads' stop pc, so must be done after "noticing"
4190 the inferiors. */
4191 if (!non_stop)
4192 {
4193 stop_all_threads ();
4194
4195 /* If all threads of an inferior were already stopped, we
4196 haven't setup the inferior yet. */
4197 ALL_INFERIORS (inf)
4198 {
4199 if (inf->pid == 0)
4200 continue;
221e1a37 4201
6efcd9a8
PA
4202 if (inf->needs_setup)
4203 {
4204 thread = any_live_thread_of_process (inf->pid);
4205 switch_to_thread_no_regs (thread);
4206 setup_inferior (0);
4207 }
4208 }
221e1a37 4209 }
6efcd9a8
PA
4210
4211 /* Now go over all threads that are stopped, and print their current
4212 frame. If all-stop, then if there's a signalled thread, pick
4213 that as current. */
4214 ALL_NON_EXITED_THREADS (thread)
4215 {
6efcd9a8
PA
4216 if (first == NULL)
4217 first = thread;
4218
4219 if (!non_stop)
4220 set_running (thread->ptid, 0);
4221 else if (thread->state != THREAD_STOPPED)
4222 continue;
4223
6efcd9a8
PA
4224 if (selected == NULL
4225 && thread->suspend.waitstatus_pending_p)
4226 selected = thread;
4227
5d5658a1
PA
4228 if (lowest_stopped == NULL
4229 || thread->inf->num < lowest_stopped->inf->num
4230 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
4231 lowest_stopped = thread;
4232
4233 if (non_stop)
4234 print_one_stopped_thread (thread);
4235 }
4236
4237 /* In all-stop, we only print the status of one thread, and leave
4238 others with their status pending. */
4239 if (!non_stop)
4240 {
4241 thread = selected;
4242 if (thread == NULL)
4243 thread = lowest_stopped;
4244 if (thread == NULL)
4245 thread = first;
4246
4247 print_one_stopped_thread (thread);
4248 }
4249
4250 /* For "info program". */
4251 thread = inferior_thread ();
4252 if (thread->state == THREAD_STOPPED)
4253 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
4254}
4255
048094ac
PA
4256/* Start the remote connection and sync state. */
4257
f6ac5f3d
PA
4258void
4259remote_target::start_remote (int from_tty, int extended_p)
c906108c 4260{
c8d104ad
PA
4261 struct remote_state *rs = get_remote_state ();
4262 struct packet_config *noack_config;
2d717e4f 4263 char *wait_status = NULL;
8621d6a9 4264
048094ac
PA
4265 /* Signal other parts that we're going through the initial setup,
4266 and so things may not be stable yet. E.g., we don't try to
4267 install tracepoints until we've relocated symbols. Also, a
4268 Ctrl-C before we're connected and synced up can't interrupt the
4269 target. Instead, it offers to drop the (potentially wedged)
4270 connection. */
4271 rs->starting_up = 1;
4272
522002f9 4273 QUIT;
c906108c 4274
9a7071a8
JB
4275 if (interrupt_on_connect)
4276 send_interrupt_sequence ();
4277
57e12211 4278 /* Ack any packet which the remote side has already sent. */
048094ac 4279 remote_serial_write ("+", 1);
1e51243a 4280
c8d104ad
PA
4281 /* The first packet we send to the target is the optional "supported
4282 packets" request. If the target can answer this, it will tell us
4283 which later probes to skip. */
4284 remote_query_supported ();
4285
d914c394 4286 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 4287 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
f6ac5f3d 4288 set_permissions ();
d914c394 4289
57809e5e
JK
4290 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4291 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4292 as a reply to known packet. For packet "vFile:setfs:" it is an
4293 invalid reply and GDB would return error in
4294 remote_hostio_set_filesystem, making remote files access impossible.
4295 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4296 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4297 {
4298 const char v_mustreplyempty[] = "vMustReplyEmpty";
4299
4300 putpkt (v_mustreplyempty);
4301 getpkt (&rs->buf, &rs->buf_size, 0);
4302 if (strcmp (rs->buf, "OK") == 0)
4303 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4304 else if (strcmp (rs->buf, "") != 0)
4305 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4306 rs->buf);
4307 }
4308
c8d104ad
PA
4309 /* Next, we possibly activate noack mode.
4310
4311 If the QStartNoAckMode packet configuration is set to AUTO,
4312 enable noack mode if the stub reported a wish for it with
4313 qSupported.
4314
4315 If set to TRUE, then enable noack mode even if the stub didn't
4316 report it in qSupported. If the stub doesn't reply OK, the
4317 session ends with an error.
4318
4319 If FALSE, then don't activate noack mode, regardless of what the
4320 stub claimed should be the default with qSupported. */
4321
4322 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 4323 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
4324 {
4325 putpkt ("QStartNoAckMode");
4326 getpkt (&rs->buf, &rs->buf_size, 0);
4327 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4328 rs->noack_mode = 1;
4329 }
4330
04bd08de 4331 if (extended_p)
5fe04517
PA
4332 {
4333 /* Tell the remote that we are using the extended protocol. */
4334 putpkt ("!");
4335 getpkt (&rs->buf, &rs->buf_size, 0);
4336 }
4337
9b224c5e
PA
4338 /* Let the target know which signals it is allowed to pass down to
4339 the program. */
4340 update_signals_program_target ();
4341
d962ef82
DJ
4342 /* Next, if the target can specify a description, read it. We do
4343 this before anything involving memory or registers. */
4344 target_find_description ();
4345
6c95b8df
PA
4346 /* Next, now that we know something about the target, update the
4347 address spaces in the program spaces. */
4348 update_address_spaces ();
4349
50c71eaf
PA
4350 /* On OSs where the list of libraries is global to all
4351 processes, we fetch them early. */
f5656ead 4352 if (gdbarch_has_global_solist (target_gdbarch ()))
e696b3ad 4353 solib_add (NULL, from_tty, auto_solib_add);
50c71eaf 4354
6efcd9a8 4355 if (target_is_non_stop_p ())
74531fed 4356 {
4082afcc 4357 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
4358 error (_("Non-stop mode requested, but remote "
4359 "does not support non-stop"));
74531fed
PA
4360
4361 putpkt ("QNonStop:1");
4362 getpkt (&rs->buf, &rs->buf_size, 0);
4363
4364 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4365 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
4366
4367 /* Find about threads and processes the stub is already
4368 controlling. We default to adding them in the running state.
4369 The '?' query below will then tell us about which threads are
4370 stopped. */
f6ac5f3d 4371 this->update_thread_list ();
74531fed 4372 }
4082afcc 4373 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4374 {
4375 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4376 Request it explicitly. */
74531fed
PA
4377 putpkt ("QNonStop:0");
4378 getpkt (&rs->buf, &rs->buf_size, 0);
4379
4380 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4381 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
4382 }
4383
a0743c90
YQ
4384 /* Upload TSVs regardless of whether the target is running or not. The
4385 remote stub, such as GDBserver, may have some predefined or builtin
4386 TSVs, even if the target is not running. */
f6ac5f3d 4387 if (get_trace_status (current_trace_status ()) != -1)
a0743c90
YQ
4388 {
4389 struct uploaded_tsv *uploaded_tsvs = NULL;
4390
f6ac5f3d 4391 upload_trace_state_variables (&uploaded_tsvs);
a0743c90
YQ
4392 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4393 }
4394
2d717e4f
DJ
4395 /* Check whether the target is running now. */
4396 putpkt ("?");
4397 getpkt (&rs->buf, &rs->buf_size, 0);
4398
6efcd9a8 4399 if (!target_is_non_stop_p ())
2d717e4f 4400 {
74531fed 4401 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4402 {
04bd08de 4403 if (!extended_p)
74531fed 4404 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4405
4406 /* We're connected, but not running. Drop out before we
4407 call start_remote. */
e278ad5b 4408 rs->starting_up = 0;
c35b1492 4409 return;
2d717e4f
DJ
4410 }
4411 else
74531fed 4412 {
74531fed 4413 /* Save the reply for later. */
224c3ddb 4414 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
4415 strcpy (wait_status, rs->buf);
4416 }
4417
b7ea362b 4418 /* Fetch thread list. */
e8032dde 4419 target_update_thread_list ();
b7ea362b 4420
74531fed
PA
4421 /* Let the stub know that we want it to return the thread. */
4422 set_continue_thread (minus_one_ptid);
4423
b7ea362b
PA
4424 if (thread_count () == 0)
4425 {
4426 /* Target has no concept of threads at all. GDB treats
4427 non-threaded target as single-threaded; add a main
4428 thread. */
4429 add_current_inferior_and_thread (wait_status);
4430 }
4431 else
4432 {
4433 /* We have thread information; select the thread the target
4434 says should be current. If we're reconnecting to a
4435 multi-threaded program, this will ideally be the thread
4436 that last reported an event before GDB disconnected. */
4437 inferior_ptid = get_current_thread (wait_status);
4438 if (ptid_equal (inferior_ptid, null_ptid))
4439 {
4440 /* Odd... The target was able to list threads, but not
4441 tell us which thread was current (no "thread"
4442 register in T stop reply?). Just pick the first
4443 thread in the thread list then. */
c9f35b34
KB
4444
4445 if (remote_debug)
4446 fprintf_unfiltered (gdb_stdlog,
4447 "warning: couldn't determine remote "
4448 "current thread; picking first in list.\n");
4449
b7ea362b
PA
4450 inferior_ptid = thread_list->ptid;
4451 }
4452 }
74531fed 4453
6e586cc5
YQ
4454 /* init_wait_for_inferior should be called before get_offsets in order
4455 to manage `inserted' flag in bp loc in a correct state.
4456 breakpoint_init_inferior, called from init_wait_for_inferior, set
4457 `inserted' flag to 0, while before breakpoint_re_set, called from
4458 start_remote, set `inserted' flag to 1. In the initialization of
4459 inferior, breakpoint_init_inferior should be called first, and then
4460 breakpoint_re_set can be called. If this order is broken, state of
4461 `inserted' flag is wrong, and cause some problems on breakpoint
4462 manipulation. */
4463 init_wait_for_inferior ();
4464
74531fed
PA
4465 get_offsets (); /* Get text, data & bss offsets. */
4466
d962ef82
DJ
4467 /* If we could not find a description using qXfer, and we know
4468 how to do it some other way, try again. This is not
4469 supported for non-stop; it could be, but it is tricky if
4470 there are no stopped threads when we connect. */
f6ac5f3d 4471 if (remote_read_description_p (this)
f5656ead 4472 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4473 {
4474 target_clear_description ();
4475 target_find_description ();
4476 }
4477
74531fed
PA
4478 /* Use the previously fetched status. */
4479 gdb_assert (wait_status != NULL);
4480 strcpy (rs->buf, wait_status);
4481 rs->cached_wait_status = 1;
4482
f6ac5f3d 4483 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4484 }
4485 else
4486 {
68c97600
PA
4487 /* Clear WFI global state. Do this before finding about new
4488 threads and inferiors, and setting the current inferior.
4489 Otherwise we would clear the proceed status of the current
4490 inferior when we want its stop_soon state to be preserved
4491 (see notice_new_inferior). */
4492 init_wait_for_inferior ();
4493
74531fed
PA
4494 /* In non-stop, we will either get an "OK", meaning that there
4495 are no stopped threads at this time; or, a regular stop
4496 reply. In the latter case, there may be more than one thread
4497 stopped --- we pull them all out using the vStopped
4498 mechanism. */
4499 if (strcmp (rs->buf, "OK") != 0)
4500 {
722247f1 4501 struct notif_client *notif = &notif_client_stop;
2d717e4f 4502
722247f1
YQ
4503 /* remote_notif_get_pending_replies acks this one, and gets
4504 the rest out. */
f48ff2a7 4505 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
4506 = remote_notif_parse (notif, rs->buf);
4507 remote_notif_get_pending_events (notif);
74531fed 4508 }
2d717e4f 4509
74531fed
PA
4510 if (thread_count () == 0)
4511 {
04bd08de 4512 if (!extended_p)
74531fed 4513 error (_("The target is not running (try extended-remote?)"));
82f73884 4514
c35b1492
PA
4515 /* We're connected, but not running. Drop out before we
4516 call start_remote. */
e278ad5b 4517 rs->starting_up = 0;
c35b1492
PA
4518 return;
4519 }
74531fed 4520
74531fed
PA
4521 /* In non-stop mode, any cached wait status will be stored in
4522 the stop reply queue. */
4523 gdb_assert (wait_status == NULL);
f0223081 4524
2455069d 4525 /* Report all signals during attach/startup. */
f6ac5f3d 4526 pass_signals (0, NULL);
221e1a37
PA
4527
4528 /* If there are already stopped threads, mark them stopped and
4529 report their stops before giving the prompt to the user. */
6efcd9a8 4530 process_initial_stop_replies (from_tty);
221e1a37
PA
4531
4532 if (target_can_async_p ())
4533 target_async (1);
74531fed 4534 }
c8d104ad 4535
c8d104ad
PA
4536 /* If we connected to a live target, do some additional setup. */
4537 if (target_has_execution)
4538 {
f4ccffad 4539 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4540 remote_check_symbols ();
c8d104ad 4541 }
50c71eaf 4542
d5551862
SS
4543 /* Possibly the target has been engaged in a trace run started
4544 previously; find out where things are at. */
f6ac5f3d 4545 if (get_trace_status (current_trace_status ()) != -1)
d5551862 4546 {
00bf0b85 4547 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4548
00bf0b85
SS
4549 if (current_trace_status ()->running)
4550 printf_filtered (_("Trace is already running on the target.\n"));
4551
f6ac5f3d 4552 upload_tracepoints (&uploaded_tps);
00bf0b85
SS
4553
4554 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4555 }
4556
c0272db5
TW
4557 /* Possibly the target has been engaged in a btrace record started
4558 previously; find out where things are at. */
4559 remote_btrace_maybe_reopen ();
4560
1e51243a
PA
4561 /* The thread and inferior lists are now synchronized with the
4562 target, our symbols have been relocated, and we're merged the
4563 target's tracepoints with ours. We're done with basic start
4564 up. */
4565 rs->starting_up = 0;
4566
a25a5a45
PA
4567 /* Maybe breakpoints are global and need to be inserted now. */
4568 if (breakpoints_should_be_inserted_now ())
50c71eaf 4569 insert_breakpoints ();
c906108c
SS
4570}
4571
4572/* Open a connection to a remote debugger.
4573 NAME is the filename used for communication. */
4574
f6ac5f3d
PA
4575void
4576remote_target::open (const char *name, int from_tty)
c906108c 4577{
f6ac5f3d 4578 open_1 (name, from_tty, 0);
43ff13b4
JM
4579}
4580
c906108c
SS
4581/* Open a connection to a remote debugger using the extended
4582 remote gdb protocol. NAME is the filename used for communication. */
4583
f6ac5f3d
PA
4584void
4585extended_remote_target::open (const char *name, int from_tty)
c906108c 4586{
f6ac5f3d 4587 open_1 (name, from_tty, 1 /*extended_p */);
43ff13b4
JM
4588}
4589
ca4f7f8b
PA
4590/* Reset all packets back to "unknown support". Called when opening a
4591 new connection to a remote target. */
c906108c 4592
d471ea57 4593static void
ca4f7f8b 4594reset_all_packet_configs_support (void)
d471ea57
AC
4595{
4596 int i;
a744cf53 4597
444abaca 4598 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4599 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4600}
4601
ca4f7f8b
PA
4602/* Initialize all packet configs. */
4603
4604static void
4605init_all_packet_configs (void)
4606{
4607 int i;
4608
4609 for (i = 0; i < PACKET_MAX; i++)
4610 {
4611 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4612 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4613 }
4614}
4615
23860348 4616/* Symbol look-up. */
dc8acb97
MS
4617
4618static void
36d25514 4619remote_check_symbols (void)
dc8acb97
MS
4620{
4621 char *msg, *reply, *tmp;
dc8acb97 4622 int end;
28170b88 4623 long reply_size;
a5c0808e 4624 struct cleanup *old_chain;
dc8acb97 4625
63154eca
PA
4626 /* The remote side has no concept of inferiors that aren't running
4627 yet, it only knows about running processes. If we're connected
4628 but our current inferior is not running, we should not invite the
4629 remote target to request symbol lookups related to its
4630 (unrelated) current process. */
4631 if (!target_has_execution)
4632 return;
4633
4082afcc 4634 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4635 return;
4636
63154eca
PA
4637 /* Make sure the remote is pointing at the right process. Note
4638 there's no way to select "no process". */
3c9c4b83
PA
4639 set_general_process ();
4640
6d820c5c
DJ
4641 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4642 because we need both at the same time. */
224c3ddb 4643 msg = (char *) xmalloc (get_remote_packet_size ());
a5c0808e 4644 old_chain = make_cleanup (xfree, msg);
28170b88
MK
4645 reply = (char *) xmalloc (get_remote_packet_size ());
4646 make_cleanup (free_current_contents, &reply);
4647 reply_size = get_remote_packet_size ();
6d820c5c 4648
23860348 4649 /* Invite target to request symbol lookups. */
dc8acb97
MS
4650
4651 putpkt ("qSymbol::");
28170b88
MK
4652 getpkt (&reply, &reply_size, 0);
4653 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
dc8acb97 4654
61012eef 4655 while (startswith (reply, "qSymbol:"))
dc8acb97 4656 {
77e371c0
TT
4657 struct bound_minimal_symbol sym;
4658
dc8acb97 4659 tmp = &reply[8];
cfd77fa1 4660 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4661 msg[end] = '\0';
4662 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4663 if (sym.minsym == NULL)
ea9c271d 4664 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4665 else
2bbe3cc1 4666 {
f5656ead 4667 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4668 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4669
4670 /* If this is a function address, return the start of code
4671 instead of any data function descriptor. */
f5656ead 4672 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1 4673 sym_addr,
f6ac5f3d 4674 target_stack);
2bbe3cc1
DJ
4675
4676 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4677 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4678 }
4679
dc8acb97 4680 putpkt (msg);
28170b88 4681 getpkt (&reply, &reply_size, 0);
dc8acb97 4682 }
a5c0808e
PA
4683
4684 do_cleanups (old_chain);
dc8acb97
MS
4685}
4686
9db8d71f 4687static struct serial *
baa336ce 4688remote_serial_open (const char *name)
9db8d71f
DJ
4689{
4690 static int udp_warning = 0;
4691
4692 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4693 of in ser-tcp.c, because it is the remote protocol assuming that the
4694 serial connection is reliable and not the serial connection promising
4695 to be. */
61012eef 4696 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4697 {
3e43a32a
MS
4698 warning (_("The remote protocol may be unreliable over UDP.\n"
4699 "Some events may be lost, rendering further debugging "
4700 "impossible."));
9db8d71f
DJ
4701 udp_warning = 1;
4702 }
4703
4704 return serial_open (name);
4705}
4706
d914c394
SS
4707/* Inform the target of our permission settings. The permission flags
4708 work without this, but if the target knows the settings, it can do
4709 a couple things. First, it can add its own check, to catch cases
4710 that somehow manage to get by the permissions checks in target
4711 methods. Second, if the target is wired to disallow particular
4712 settings (for instance, a system in the field that is not set up to
4713 be able to stop at a breakpoint), it can object to any unavailable
4714 permissions. */
4715
4716void
f6ac5f3d 4717remote_target::set_permissions ()
d914c394
SS
4718{
4719 struct remote_state *rs = get_remote_state ();
4720
bba74b36
YQ
4721 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4722 "WriteReg:%x;WriteMem:%x;"
4723 "InsertBreak:%x;InsertTrace:%x;"
4724 "InsertFastTrace:%x;Stop:%x",
4725 may_write_registers, may_write_memory,
4726 may_insert_breakpoints, may_insert_tracepoints,
4727 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4728 putpkt (rs->buf);
4729 getpkt (&rs->buf, &rs->buf_size, 0);
4730
4731 /* If the target didn't like the packet, warn the user. Do not try
4732 to undo the user's settings, that would just be maddening. */
4733 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4734 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4735}
4736
be2a5f71
DJ
4737/* This type describes each known response to the qSupported
4738 packet. */
4739struct protocol_feature
4740{
4741 /* The name of this protocol feature. */
4742 const char *name;
4743
4744 /* The default for this protocol feature. */
4745 enum packet_support default_support;
4746
4747 /* The function to call when this feature is reported, or after
4748 qSupported processing if the feature is not supported.
4749 The first argument points to this structure. The second
4750 argument indicates whether the packet requested support be
4751 enabled, disabled, or probed (or the default, if this function
4752 is being called at the end of processing and this feature was
4753 not reported). The third argument may be NULL; if not NULL, it
4754 is a NUL-terminated string taken from the packet following
4755 this feature's name and an equals sign. */
4756 void (*func) (const struct protocol_feature *, enum packet_support,
4757 const char *);
4758
4759 /* The corresponding packet for this feature. Only used if
4760 FUNC is remote_supported_packet. */
4761 int packet;
4762};
4763
be2a5f71
DJ
4764static void
4765remote_supported_packet (const struct protocol_feature *feature,
4766 enum packet_support support,
4767 const char *argument)
4768{
4769 if (argument)
4770 {
4771 warning (_("Remote qSupported response supplied an unexpected value for"
4772 " \"%s\"."), feature->name);
4773 return;
4774 }
4775
4082afcc 4776 remote_protocol_packets[feature->packet].support = support;
be2a5f71 4777}
be2a5f71
DJ
4778
4779static void
4780remote_packet_size (const struct protocol_feature *feature,
4781 enum packet_support support, const char *value)
4782{
4783 struct remote_state *rs = get_remote_state ();
4784
4785 int packet_size;
4786 char *value_end;
4787
4788 if (support != PACKET_ENABLE)
4789 return;
4790
4791 if (value == NULL || *value == '\0')
4792 {
4793 warning (_("Remote target reported \"%s\" without a size."),
4794 feature->name);
4795 return;
4796 }
4797
4798 errno = 0;
4799 packet_size = strtol (value, &value_end, 16);
4800 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4801 {
4802 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4803 feature->name, value);
4804 return;
4805 }
4806
be2a5f71
DJ
4807 /* Record the new maximum packet size. */
4808 rs->explicit_packet_size = packet_size;
4809}
4810
dc473cfb 4811static const struct protocol_feature remote_protocol_features[] = {
0876f84a 4812 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 4813 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 4814 PACKET_qXfer_auxv },
c78fa86a
GB
4815 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4816 PACKET_qXfer_exec_file },
23181151
DJ
4817 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4818 PACKET_qXfer_features },
cfa9d6d9
DJ
4819 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4820 PACKET_qXfer_libraries },
2268b414
JK
4821 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4822 PACKET_qXfer_libraries_svr4 },
ced63ec0 4823 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 4824 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 4825 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 4826 PACKET_qXfer_memory_map },
4de6483e
UW
4827 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4828 PACKET_qXfer_spu_read },
4829 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4830 PACKET_qXfer_spu_write },
07e059b5
VP
4831 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4832 PACKET_qXfer_osdata },
dc146f7c
VP
4833 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4834 PACKET_qXfer_threads },
b3b9301e
PA
4835 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4836 PACKET_qXfer_traceframe_info },
89be2091
DJ
4837 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4838 PACKET_QPassSignals },
82075af2
JS
4839 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4840 PACKET_QCatchSyscalls },
9b224c5e
PA
4841 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4842 PACKET_QProgramSignals },
bc3b087d
SDJ
4843 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
4844 PACKET_QSetWorkingDir },
aefd8b33
SDJ
4845 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
4846 PACKET_QStartupWithShell },
0a2dde4a
SDJ
4847 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
4848 PACKET_QEnvironmentHexEncoded },
4849 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
4850 PACKET_QEnvironmentReset },
4851 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
4852 PACKET_QEnvironmentUnset },
a6f3e723
SL
4853 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4854 PACKET_QStartNoAckMode },
4082afcc
PA
4855 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4856 PACKET_multiprocess_feature },
4857 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4858 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4859 PACKET_qXfer_siginfo_read },
4860 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4861 PACKET_qXfer_siginfo_write },
4082afcc 4862 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4863 PACKET_ConditionalTracepoints },
4082afcc 4864 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4865 PACKET_ConditionalBreakpoints },
4082afcc 4866 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4867 PACKET_BreakpointCommands },
4082afcc 4868 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4869 PACKET_FastTracepoints },
4082afcc 4870 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4871 PACKET_StaticTracepoints },
4082afcc 4872 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4873 PACKET_InstallInTrace},
4082afcc
PA
4874 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4875 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4876 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4877 PACKET_bc },
4878 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4879 PACKET_bs },
409873ef
SS
4880 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4881 PACKET_TracepointSource },
d914c394
SS
4882 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4883 PACKET_QAllow },
4082afcc
PA
4884 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4885 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4886 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4887 PACKET_qXfer_fdpic },
169081d0
TG
4888 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4889 PACKET_qXfer_uib },
03583c20
UW
4890 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4891 PACKET_QDisableRandomization },
d1feda86 4892 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4893 { "QTBuffer:size", PACKET_DISABLE,
4894 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4895 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4896 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4897 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 4898 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 4899 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4900 PACKET_qXfer_btrace },
4901 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4902 PACKET_qXfer_btrace_conf },
4903 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4904 PACKET_Qbtrace_conf_bts_size },
4905 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4906 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
4907 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4908 PACKET_fork_event_feature },
4909 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4910 PACKET_vfork_event_feature },
94585166
DB
4911 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4912 PACKET_exec_event_feature },
b20a6524 4913 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 4914 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
4915 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4916 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 4917 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
be2a5f71
DJ
4918};
4919
c8d5aac9
L
4920static char *remote_support_xml;
4921
4922/* Register string appended to "xmlRegisters=" in qSupported query. */
4923
4924void
6e39997a 4925register_remote_support_xml (const char *xml)
c8d5aac9
L
4926{
4927#if defined(HAVE_LIBEXPAT)
4928 if (remote_support_xml == NULL)
c4f7c687 4929 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4930 else
4931 {
4932 char *copy = xstrdup (remote_support_xml + 13);
4933 char *p = strtok (copy, ",");
4934
4935 do
4936 {
4937 if (strcmp (p, xml) == 0)
4938 {
4939 /* already there */
4940 xfree (copy);
4941 return;
4942 }
4943 }
4944 while ((p = strtok (NULL, ",")) != NULL);
4945 xfree (copy);
4946
94b0dee1
PA
4947 remote_support_xml = reconcat (remote_support_xml,
4948 remote_support_xml, ",", xml,
4949 (char *) NULL);
c8d5aac9
L
4950 }
4951#endif
4952}
4953
4954static char *
4955remote_query_supported_append (char *msg, const char *append)
4956{
4957 if (msg)
94b0dee1 4958 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4959 else
4960 return xstrdup (append);
4961}
4962
be2a5f71
DJ
4963static void
4964remote_query_supported (void)
4965{
4966 struct remote_state *rs = get_remote_state ();
4967 char *next;
4968 int i;
4969 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4970
4971 /* The packet support flags are handled differently for this packet
4972 than for most others. We treat an error, a disabled packet, and
4973 an empty response identically: any features which must be reported
4974 to be used will be automatically disabled. An empty buffer
4975 accomplishes this, since that is also the representation for a list
4976 containing no features. */
4977
4978 rs->buf[0] = 0;
4082afcc 4979 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4980 {
c8d5aac9 4981 char *q = NULL;
94b0dee1 4982 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4983
73b8c1fd
PA
4984 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4985 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4986
f7e6eed5
PA
4987 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4988 q = remote_query_supported_append (q, "swbreak+");
4989 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4990 q = remote_query_supported_append (q, "hwbreak+");
4991
dde08ee1
PA
4992 q = remote_query_supported_append (q, "qRelocInsn+");
4993
8020350c
DB
4994 if (packet_set_cmd_state (PACKET_fork_event_feature)
4995 != AUTO_BOOLEAN_FALSE)
4996 q = remote_query_supported_append (q, "fork-events+");
4997 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4998 != AUTO_BOOLEAN_FALSE)
4999 q = remote_query_supported_append (q, "vfork-events+");
5000 if (packet_set_cmd_state (PACKET_exec_event_feature)
5001 != AUTO_BOOLEAN_FALSE)
5002 q = remote_query_supported_append (q, "exec-events+");
89245bc0 5003
750ce8d1
YQ
5004 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5005 q = remote_query_supported_append (q, "vContSupported+");
5006
65706a29
PA
5007 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5008 q = remote_query_supported_append (q, "QThreadEvents+");
5009
f2faf941
PA
5010 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5011 q = remote_query_supported_append (q, "no-resumed+");
5012
b35d5edb
PA
5013 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5014 the qSupported:xmlRegisters=i386 handling. */
7cc244de
PA
5015 if (remote_support_xml != NULL
5016 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
b35d5edb
PA
5017 q = remote_query_supported_append (q, remote_support_xml);
5018
dde08ee1
PA
5019 q = reconcat (q, "qSupported:", q, (char *) NULL);
5020 putpkt (q);
82f73884 5021
94b0dee1
PA
5022 do_cleanups (old_chain);
5023
be2a5f71
DJ
5024 getpkt (&rs->buf, &rs->buf_size, 0);
5025
5026 /* If an error occured, warn, but do not return - just reset the
5027 buffer to empty and go on to disable features. */
5028 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5029 == PACKET_ERROR)
5030 {
5031 warning (_("Remote failure reply: %s"), rs->buf);
5032 rs->buf[0] = 0;
5033 }
5034 }
5035
5036 memset (seen, 0, sizeof (seen));
5037
5038 next = rs->buf;
5039 while (*next)
5040 {
5041 enum packet_support is_supported;
5042 char *p, *end, *name_end, *value;
5043
5044 /* First separate out this item from the rest of the packet. If
5045 there's another item after this, we overwrite the separator
5046 (terminated strings are much easier to work with). */
5047 p = next;
5048 end = strchr (p, ';');
5049 if (end == NULL)
5050 {
5051 end = p + strlen (p);
5052 next = end;
5053 }
5054 else
5055 {
89be2091
DJ
5056 *end = '\0';
5057 next = end + 1;
5058
be2a5f71
DJ
5059 if (end == p)
5060 {
5061 warning (_("empty item in \"qSupported\" response"));
5062 continue;
5063 }
be2a5f71
DJ
5064 }
5065
5066 name_end = strchr (p, '=');
5067 if (name_end)
5068 {
5069 /* This is a name=value entry. */
5070 is_supported = PACKET_ENABLE;
5071 value = name_end + 1;
5072 *name_end = '\0';
5073 }
5074 else
5075 {
5076 value = NULL;
5077 switch (end[-1])
5078 {
5079 case '+':
5080 is_supported = PACKET_ENABLE;
5081 break;
5082
5083 case '-':
5084 is_supported = PACKET_DISABLE;
5085 break;
5086
5087 case '?':
5088 is_supported = PACKET_SUPPORT_UNKNOWN;
5089 break;
5090
5091 default:
3e43a32a
MS
5092 warning (_("unrecognized item \"%s\" "
5093 "in \"qSupported\" response"), p);
be2a5f71
DJ
5094 continue;
5095 }
5096 end[-1] = '\0';
5097 }
5098
5099 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5100 if (strcmp (remote_protocol_features[i].name, p) == 0)
5101 {
5102 const struct protocol_feature *feature;
5103
5104 seen[i] = 1;
5105 feature = &remote_protocol_features[i];
5106 feature->func (feature, is_supported, value);
5107 break;
5108 }
5109 }
5110
5111 /* If we increased the packet size, make sure to increase the global
5112 buffer size also. We delay this until after parsing the entire
5113 qSupported packet, because this is the same buffer we were
5114 parsing. */
5115 if (rs->buf_size < rs->explicit_packet_size)
5116 {
5117 rs->buf_size = rs->explicit_packet_size;
224c3ddb 5118 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
be2a5f71
DJ
5119 }
5120
5121 /* Handle the defaults for unmentioned features. */
5122 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5123 if (!seen[i])
5124 {
5125 const struct protocol_feature *feature;
5126
5127 feature = &remote_protocol_features[i];
5128 feature->func (feature, feature->default_support, NULL);
5129 }
5130}
5131
048094ac
PA
5132/* Serial QUIT handler for the remote serial descriptor.
5133
5134 Defers handling a Ctrl-C until we're done with the current
5135 command/response packet sequence, unless:
5136
5137 - We're setting up the connection. Don't send a remote interrupt
5138 request, as we're not fully synced yet. Quit immediately
5139 instead.
5140
5141 - The target has been resumed in the foreground
223ffa71 5142 (target_terminal::is_ours is false) with a synchronous resume
048094ac
PA
5143 packet, and we're blocked waiting for the stop reply, thus a
5144 Ctrl-C should be immediately sent to the target.
5145
5146 - We get a second Ctrl-C while still within the same serial read or
5147 write. In that case the serial is seemingly wedged --- offer to
5148 quit/disconnect.
5149
5150 - We see a second Ctrl-C without target response, after having
5151 previously interrupted the target. In that case the target/stub
5152 is probably wedged --- offer to quit/disconnect.
5153*/
5154
5155static void
5156remote_serial_quit_handler (void)
5157{
5158 struct remote_state *rs = get_remote_state ();
5159
5160 if (check_quit_flag ())
5161 {
5162 /* If we're starting up, we're not fully synced yet. Quit
5163 immediately. */
5164 if (rs->starting_up)
5165 quit ();
5166 else if (rs->got_ctrlc_during_io)
5167 {
5168 if (query (_("The target is not responding to GDB commands.\n"
5169 "Stop debugging it? ")))
5170 remote_unpush_and_throw ();
5171 }
5172 /* If ^C has already been sent once, offer to disconnect. */
223ffa71 5173 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
048094ac
PA
5174 interrupt_query ();
5175 /* All-stop protocol, and blocked waiting for stop reply. Send
5176 an interrupt request. */
223ffa71 5177 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
e671cd59 5178 target_interrupt ();
048094ac
PA
5179 else
5180 rs->got_ctrlc_during_io = 1;
5181 }
5182}
5183
78a095c3
JK
5184/* Remove any of the remote.c targets from target stack. Upper targets depend
5185 on it so remove them first. */
5186
5187static void
5188remote_unpush_target (void)
5189{
915ef8b1 5190 pop_all_targets_at_and_above (process_stratum);
78a095c3 5191}
be2a5f71 5192
048094ac
PA
5193static void
5194remote_unpush_and_throw (void)
5195{
5196 remote_unpush_target ();
5197 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5198}
5199
f6ac5f3d
PA
5200void
5201remote_target::open_1 (const char *name, int from_tty, int extended_p)
c906108c 5202{
d01949b6 5203 struct remote_state *rs = get_remote_state ();
a6f3e723 5204
c906108c 5205 if (name == 0)
8a3fe4f8 5206 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 5207 "serial device is attached to the remote system\n"
8a3fe4f8 5208 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 5209
23860348 5210 /* See FIXME above. */
c6ebd6cf 5211 if (!target_async_permitted)
92d1e331 5212 wait_forever_enabled_p = 1;
6426a772 5213
2d717e4f 5214 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
5215 Ask this question first, before target_preopen has a chance to kill
5216 anything. */
5d93a237 5217 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 5218 {
78a095c3
JK
5219 if (from_tty
5220 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
5221 error (_("Still connected."));
5222 }
5223
78a095c3 5224 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
5225 target_preopen (from_tty);
5226
89be2091 5227 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
5228 xfree (rs->last_pass_packet);
5229 rs->last_pass_packet = NULL;
89be2091 5230
9b224c5e
PA
5231 /* Make sure we send the program signals list the next time we
5232 resume. */
5e4a05c4
TT
5233 xfree (rs->last_program_signals_packet);
5234 rs->last_program_signals_packet = NULL;
9b224c5e 5235
ad9a8f3f 5236 remote_fileio_reset ();
1dd41f16
NS
5237 reopen_exec_file ();
5238 reread_symbols ();
5239
5d93a237
TT
5240 rs->remote_desc = remote_serial_open (name);
5241 if (!rs->remote_desc)
c906108c
SS
5242 perror_with_name (name);
5243
5244 if (baud_rate != -1)
5245 {
5d93a237 5246 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 5247 {
9b74d5d3
KB
5248 /* The requested speed could not be set. Error out to
5249 top level after closing remote_desc. Take care to
5250 set remote_desc to NULL to avoid closing remote_desc
5251 more than once. */
5d93a237
TT
5252 serial_close (rs->remote_desc);
5253 rs->remote_desc = NULL;
c906108c
SS
5254 perror_with_name (name);
5255 }
5256 }
5257
236af5e3 5258 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 5259 serial_raw (rs->remote_desc);
c906108c
SS
5260
5261 /* If there is something sitting in the buffer we might take it as a
5262 response to a command, which would be bad. */
5d93a237 5263 serial_flush_input (rs->remote_desc);
c906108c
SS
5264
5265 if (from_tty)
5266 {
5267 puts_filtered ("Remote debugging using ");
5268 puts_filtered (name);
5269 puts_filtered ("\n");
5270 }
f6ac5f3d 5271 push_target (this); /* Switch to using remote target now. */
c906108c 5272
74531fed
PA
5273 /* Register extra event sources in the event loop. */
5274 remote_async_inferior_event_token
5275 = create_async_event_handler (remote_async_inferior_event_handler,
5276 NULL);
5965e028 5277 rs->notif_state = remote_notif_state_allocate ();
74531fed 5278
be2a5f71
DJ
5279 /* Reset the target state; these things will be queried either by
5280 remote_query_supported or as they are needed. */
ca4f7f8b 5281 reset_all_packet_configs_support ();
74531fed 5282 rs->cached_wait_status = 0;
be2a5f71 5283 rs->explicit_packet_size = 0;
a6f3e723 5284 rs->noack_mode = 0;
82f73884 5285 rs->extended = extended_p;
e24a49d8 5286 rs->waiting_for_stop_reply = 0;
3a29589a 5287 rs->ctrlc_pending_p = 0;
048094ac 5288 rs->got_ctrlc_during_io = 0;
802188a7 5289
47f8a51d
TT
5290 rs->general_thread = not_sent_ptid;
5291 rs->continue_thread = not_sent_ptid;
262e1174 5292 rs->remote_traceframe_number = -1;
c906108c 5293
3a00c802
PA
5294 rs->last_resume_exec_dir = EXEC_FORWARD;
5295
9d1f7ab2 5296 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
5297 rs->use_threadinfo_query = 1;
5298 rs->use_threadextra_query = 1;
9d1f7ab2 5299
80152258
PA
5300 readahead_cache_invalidate ();
5301
c6ebd6cf 5302 if (target_async_permitted)
92d1e331 5303 {
92d1e331
DJ
5304 /* FIXME: cagney/1999-09-23: During the initial connection it is
5305 assumed that the target is already ready and able to respond to
0df8b418 5306 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 5307 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 5308 around this. Eventually a mechanism that allows
92d1e331 5309 wait_for_inferior() to expect/get timeouts will be
23860348 5310 implemented. */
92d1e331
DJ
5311 wait_forever_enabled_p = 0;
5312 }
5313
23860348 5314 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 5315 no_shared_libraries (NULL, 0);
f78f6cf1 5316
74531fed
PA
5317 /* Start afresh. */
5318 init_thread_list ();
5319
36918e70 5320 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
5321 target (we'd otherwise be in an inconsistent state) and then
5322 propogate the error on up the exception chain. This ensures that
5323 the caller doesn't stumble along blindly assuming that the
5324 function succeeded. The CLI doesn't have this problem but other
5325 UI's, such as MI do.
36918e70
AC
5326
5327 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5328 this function should return an error indication letting the
ce2826aa 5329 caller restore the previous state. Unfortunately the command
36918e70
AC
5330 ``target remote'' is directly wired to this function making that
5331 impossible. On a positive note, the CLI side of this problem has
5332 been fixed - the function set_cmd_context() makes it possible for
5333 all the ``target ....'' commands to share a common callback
5334 function. See cli-dump.c. */
109c3e39 5335 {
2d717e4f 5336
492d29ea 5337 TRY
04bd08de 5338 {
f6ac5f3d 5339 start_remote (from_tty, extended_p);
04bd08de 5340 }
492d29ea 5341 CATCH (ex, RETURN_MASK_ALL)
109c3e39 5342 {
c8d104ad
PA
5343 /* Pop the partially set up target - unless something else did
5344 already before throwing the exception. */
5d93a237 5345 if (rs->remote_desc != NULL)
78a095c3 5346 remote_unpush_target ();
c6ebd6cf 5347 if (target_async_permitted)
109c3e39
AC
5348 wait_forever_enabled_p = 1;
5349 throw_exception (ex);
5350 }
492d29ea 5351 END_CATCH
109c3e39 5352 }
c906108c 5353
f4abbc16
MM
5354 remote_btrace_reset ();
5355
c6ebd6cf 5356 if (target_async_permitted)
92d1e331 5357 wait_forever_enabled_p = 1;
43ff13b4
JM
5358}
5359
de0d863e
DB
5360/* Detach the specified process. */
5361
5362static void
5363remote_detach_pid (int pid)
5364{
5365 struct remote_state *rs = get_remote_state ();
5366
5367 if (remote_multi_process_p (rs))
5368 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5369 else
5370 strcpy (rs->buf, "D");
5371
5372 putpkt (rs->buf);
5373 getpkt (&rs->buf, &rs->buf_size, 0);
5374
5375 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5376 ;
5377 else if (rs->buf[0] == '\0')
5378 error (_("Remote doesn't know how to detach"));
5379 else
5380 error (_("Can't detach process."));
5381}
5382
5383/* This detaches a program to which we previously attached, using
5384 inferior_ptid to identify the process. After this is done, GDB
5385 can be used to debug some other program. We better not have left
5386 any breakpoints in the target program or it'll die when it hits
5387 one. */
c906108c
SS
5388
5389static void
6e1e1966 5390remote_detach_1 (int from_tty, inferior *inf)
c906108c 5391{
82f73884 5392 int pid = ptid_get_pid (inferior_ptid);
d01949b6 5393 struct remote_state *rs = get_remote_state ();
de0d863e
DB
5394 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5395 int is_fork_parent;
c906108c 5396
2d717e4f
DJ
5397 if (!target_has_execution)
5398 error (_("No process to detach from."));
5399
0f48b757 5400 target_announce_detach (from_tty);
7cee1e54 5401
c906108c 5402 /* Tell the remote target to detach. */
de0d863e 5403 remote_detach_pid (pid);
82f73884 5404
8020350c
DB
5405 /* Exit only if this is the only active inferior. */
5406 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
7cee1e54 5407 puts_filtered (_("Ending remote debugging.\n"));
82f73884 5408
de0d863e
DB
5409 /* Check to see if we are detaching a fork parent. Note that if we
5410 are detaching a fork child, tp == NULL. */
5411 is_fork_parent = (tp != NULL
5412 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5413
5414 /* If doing detach-on-fork, we don't mourn, because that will delete
5415 breakpoints that should be available for the followed inferior. */
5416 if (!is_fork_parent)
f67c0c91 5417 {
249b5733
PA
5418 /* Save the pid as a string before mourning, since that will
5419 unpush the remote target, and we need the string after. */
5420 std::string infpid = target_pid_to_str (pid_to_ptid (pid));
f67c0c91
SDJ
5421
5422 target_mourn_inferior (inferior_ptid);
5423 if (print_inferior_events)
5424 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5425 inf->num, infpid.c_str ());
5426 }
de0d863e
DB
5427 else
5428 {
5429 inferior_ptid = null_ptid;
5430 detach_inferior (pid);
5431 }
2d717e4f
DJ
5432}
5433
f6ac5f3d
PA
5434void
5435remote_target::detach (inferior *inf, int from_tty)
2d717e4f 5436{
6e1e1966 5437 remote_detach_1 (from_tty, inf);
2d717e4f
DJ
5438}
5439
f6ac5f3d
PA
5440void
5441extended_remote_target::detach (inferior *inf, int from_tty)
2d717e4f 5442{
6e1e1966 5443 remote_detach_1 (from_tty, inf);
de0d863e
DB
5444}
5445
5446/* Target follow-fork function for remote targets. On entry, and
5447 at return, the current inferior is the fork parent.
5448
5449 Note that although this is currently only used for extended-remote,
5450 it is named remote_follow_fork in anticipation of using it for the
5451 remote target as well. */
5452
f6ac5f3d
PA
5453int
5454remote_target::follow_fork (int follow_child, int detach_fork)
de0d863e
DB
5455{
5456 struct remote_state *rs = get_remote_state ();
c269dbdb 5457 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5458
c269dbdb
DB
5459 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5460 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5461 {
5462 /* When following the parent and detaching the child, we detach
5463 the child here. For the case of following the child and
5464 detaching the parent, the detach is done in the target-
5465 independent follow fork code in infrun.c. We can't use
5466 target_detach when detaching an unfollowed child because
5467 the client side doesn't know anything about the child. */
5468 if (detach_fork && !follow_child)
5469 {
5470 /* Detach the fork child. */
5471 ptid_t child_ptid;
5472 pid_t child_pid;
5473
5474 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5475 child_pid = ptid_get_pid (child_ptid);
5476
5477 remote_detach_pid (child_pid);
de0d863e
DB
5478 }
5479 }
5480 return 0;
c906108c
SS
5481}
5482
94585166
DB
5483/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5484 in the program space of the new inferior. On entry and at return the
5485 current inferior is the exec'ing inferior. INF is the new exec'd
5486 inferior, which may be the same as the exec'ing inferior unless
5487 follow-exec-mode is "new". */
5488
f6ac5f3d
PA
5489void
5490remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
94585166
DB
5491{
5492 /* We know that this is a target file name, so if it has the "target:"
5493 prefix we strip it off before saving it in the program space. */
5494 if (is_target_filename (execd_pathname))
5495 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5496
5497 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5498}
5499
6ad8ae5c
DJ
5500/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5501
f6ac5f3d
PA
5502void
5503remote_target::disconnect (const char *args, int from_tty)
43ff13b4 5504{
43ff13b4 5505 if (args)
2d717e4f 5506 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5507
8020350c
DB
5508 /* Make sure we unpush even the extended remote targets. Calling
5509 target_mourn_inferior won't unpush, and remote_mourn won't
5510 unpush if there is more than one inferior left. */
f6ac5f3d 5511 unpush_target (this);
8020350c 5512 generic_mourn_inferior ();
2d717e4f 5513
43ff13b4
JM
5514 if (from_tty)
5515 puts_filtered ("Ending remote debugging.\n");
5516}
5517
2d717e4f
DJ
5518/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5519 be chatty about it. */
5520
f6ac5f3d
PA
5521void
5522extended_remote_target::attach (const char *args, int from_tty)
2d717e4f
DJ
5523{
5524 struct remote_state *rs = get_remote_state ();
be86555c 5525 int pid;
96ef3384 5526 char *wait_status = NULL;
2d717e4f 5527
74164c56 5528 pid = parse_pid_to_attach (args);
2d717e4f 5529
74164c56
JK
5530 /* Remote PID can be freely equal to getpid, do not check it here the same
5531 way as in other targets. */
2d717e4f 5532
4082afcc 5533 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5534 error (_("This target does not support attaching to a process"));
5535
7cee1e54
PA
5536 if (from_tty)
5537 {
5538 char *exec_file = get_exec_file (0);
5539
5540 if (exec_file)
5541 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5542 target_pid_to_str (pid_to_ptid (pid)));
5543 else
5544 printf_unfiltered (_("Attaching to %s\n"),
5545 target_pid_to_str (pid_to_ptid (pid)));
5546
5547 gdb_flush (gdb_stdout);
5548 }
5549
bba74b36 5550 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
5551 putpkt (rs->buf);
5552 getpkt (&rs->buf, &rs->buf_size, 0);
5553
4082afcc
PA
5554 switch (packet_ok (rs->buf,
5555 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5556 {
4082afcc 5557 case PACKET_OK:
6efcd9a8 5558 if (!target_is_non_stop_p ())
74531fed
PA
5559 {
5560 /* Save the reply for later. */
224c3ddb 5561 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
5562 strcpy (wait_status, rs->buf);
5563 }
5564 else if (strcmp (rs->buf, "OK") != 0)
5565 error (_("Attaching to %s failed with: %s"),
5566 target_pid_to_str (pid_to_ptid (pid)),
5567 rs->buf);
4082afcc
PA
5568 break;
5569 case PACKET_UNKNOWN:
5570 error (_("This target does not support attaching to a process"));
5571 default:
5572 error (_("Attaching to %s failed"),
5573 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 5574 }
2d717e4f 5575
1b6e6f5c 5576 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 5577
2d717e4f 5578 inferior_ptid = pid_to_ptid (pid);
79d7f229 5579
6efcd9a8 5580 if (target_is_non_stop_p ())
bad34192
PA
5581 {
5582 struct thread_info *thread;
79d7f229 5583
bad34192 5584 /* Get list of threads. */
f6ac5f3d 5585 update_thread_list ();
82f73884 5586
bad34192
PA
5587 thread = first_thread_of_process (pid);
5588 if (thread)
5589 inferior_ptid = thread->ptid;
5590 else
5591 inferior_ptid = pid_to_ptid (pid);
5592
5593 /* Invalidate our notion of the remote current thread. */
47f8a51d 5594 record_currthread (rs, minus_one_ptid);
bad34192 5595 }
74531fed 5596 else
bad34192
PA
5597 {
5598 /* Now, if we have thread information, update inferior_ptid. */
5599 inferior_ptid = remote_current_thread (inferior_ptid);
5600
5601 /* Add the main thread to the thread list. */
00aecdcf
PA
5602 thread_info *thr = add_thread_silent (inferior_ptid);
5603 /* Don't consider the thread stopped until we've processed the
5604 saved stop reply. */
5605 set_executing (thr->ptid, true);
bad34192 5606 }
c0a2216e 5607
96ef3384
UW
5608 /* Next, if the target can specify a description, read it. We do
5609 this before anything involving memory or registers. */
5610 target_find_description ();
5611
6efcd9a8 5612 if (!target_is_non_stop_p ())
74531fed
PA
5613 {
5614 /* Use the previously fetched status. */
5615 gdb_assert (wait_status != NULL);
5616
5617 if (target_can_async_p ())
5618 {
722247f1
YQ
5619 struct notif_event *reply
5620 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 5621
722247f1 5622 push_stop_reply ((struct stop_reply *) reply);
74531fed 5623
6a3753b3 5624 target_async (1);
74531fed
PA
5625 }
5626 else
5627 {
5628 gdb_assert (wait_status != NULL);
5629 strcpy (rs->buf, wait_status);
5630 rs->cached_wait_status = 1;
5631 }
5632 }
5633 else
5634 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5635}
5636
b9c1d481
AS
5637/* Implementation of the to_post_attach method. */
5638
f6ac5f3d
PA
5639void
5640extended_remote_target::post_attach (int pid)
b9c1d481 5641{
6efcd9a8
PA
5642 /* Get text, data & bss offsets. */
5643 get_offsets ();
5644
b9c1d481
AS
5645 /* In certain cases GDB might not have had the chance to start
5646 symbol lookup up until now. This could happen if the debugged
5647 binary is not using shared libraries, the vsyscall page is not
5648 present (on Linux) and the binary itself hadn't changed since the
5649 debugging process was started. */
5650 if (symfile_objfile != NULL)
5651 remote_check_symbols();
5652}
5653
c906108c 5654\f
506fb367
DJ
5655/* Check for the availability of vCont. This function should also check
5656 the response. */
c906108c
SS
5657
5658static void
6d820c5c 5659remote_vcont_probe (struct remote_state *rs)
c906108c 5660{
2e9f7625 5661 char *buf;
6d820c5c 5662
2e9f7625
DJ
5663 strcpy (rs->buf, "vCont?");
5664 putpkt (rs->buf);
6d820c5c 5665 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 5666 buf = rs->buf;
c906108c 5667
506fb367 5668 /* Make sure that the features we assume are supported. */
61012eef 5669 if (startswith (buf, "vCont"))
506fb367
DJ
5670 {
5671 char *p = &buf[5];
750ce8d1 5672 int support_c, support_C;
506fb367 5673
750ce8d1
YQ
5674 rs->supports_vCont.s = 0;
5675 rs->supports_vCont.S = 0;
506fb367
DJ
5676 support_c = 0;
5677 support_C = 0;
d458bd84 5678 rs->supports_vCont.t = 0;
c1e36e3e 5679 rs->supports_vCont.r = 0;
506fb367
DJ
5680 while (p && *p == ';')
5681 {
5682 p++;
5683 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5684 rs->supports_vCont.s = 1;
506fb367 5685 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5686 rs->supports_vCont.S = 1;
506fb367
DJ
5687 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5688 support_c = 1;
5689 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5690 support_C = 1;
74531fed 5691 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5692 rs->supports_vCont.t = 1;
c1e36e3e
PA
5693 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5694 rs->supports_vCont.r = 1;
506fb367
DJ
5695
5696 p = strchr (p, ';');
5697 }
c906108c 5698
750ce8d1
YQ
5699 /* If c, and C are not all supported, we can't use vCont. Clearing
5700 BUF will make packet_ok disable the packet. */
5701 if (!support_c || !support_C)
506fb367
DJ
5702 buf[0] = 0;
5703 }
c906108c 5704
444abaca 5705 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 5706}
c906108c 5707
0d8f58ca
PA
5708/* Helper function for building "vCont" resumptions. Write a
5709 resumption to P. ENDP points to one-passed-the-end of the buffer
5710 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5711 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5712 resumed thread should be single-stepped and/or signalled. If PTID
5713 equals minus_one_ptid, then all threads are resumed; if PTID
5714 represents a process, then all threads of the process are resumed;
5715 the thread to be stepped and/or signalled is given in the global
5716 INFERIOR_PTID. */
5717
5718static char *
5719append_resumption (char *p, char *endp,
2ea28649 5720 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
5721{
5722 struct remote_state *rs = get_remote_state ();
5723
a493e3e2 5724 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5725 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5726 else if (step
5727 /* GDB is willing to range step. */
5728 && use_range_stepping
5729 /* Target supports range stepping. */
5730 && rs->supports_vCont.r
5731 /* We don't currently support range stepping multiple
5732 threads with a wildcard (though the protocol allows it,
5733 so stubs shouldn't make an active effort to forbid
5734 it). */
5735 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5736 {
5737 struct thread_info *tp;
5738
5739 if (ptid_equal (ptid, minus_one_ptid))
5740 {
5741 /* If we don't know about the target thread's tid, then
5742 we're resuming magic_null_ptid (see caller). */
5743 tp = find_thread_ptid (magic_null_ptid);
5744 }
5745 else
5746 tp = find_thread_ptid (ptid);
5747 gdb_assert (tp != NULL);
5748
5749 if (tp->control.may_range_step)
5750 {
5751 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5752
5753 p += xsnprintf (p, endp - p, ";r%s,%s",
5754 phex_nz (tp->control.step_range_start,
5755 addr_size),
5756 phex_nz (tp->control.step_range_end,
5757 addr_size));
5758 }
5759 else
5760 p += xsnprintf (p, endp - p, ";s");
5761 }
0d8f58ca
PA
5762 else if (step)
5763 p += xsnprintf (p, endp - p, ";s");
a493e3e2 5764 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
5765 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5766 else
5767 p += xsnprintf (p, endp - p, ";c");
5768
5769 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5770 {
5771 ptid_t nptid;
5772
5773 /* All (-1) threads of process. */
ba348170 5774 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
5775
5776 p += xsnprintf (p, endp - p, ":");
5777 p = write_ptid (p, endp, nptid);
5778 }
5779 else if (!ptid_equal (ptid, minus_one_ptid))
5780 {
5781 p += xsnprintf (p, endp - p, ":");
5782 p = write_ptid (p, endp, ptid);
5783 }
5784
5785 return p;
5786}
5787
799a2abe
PA
5788/* Clear the thread's private info on resume. */
5789
5790static void
5791resume_clear_thread_private_info (struct thread_info *thread)
5792{
5793 if (thread->priv != NULL)
5794 {
7aabaf9d
SM
5795 remote_thread_info *priv = get_remote_thread_info (thread);
5796
5797 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5798 priv->watch_data_address = 0;
799a2abe
PA
5799 }
5800}
5801
e5ef252a
PA
5802/* Append a vCont continue-with-signal action for threads that have a
5803 non-zero stop signal. */
5804
5805static char *
5806append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5807{
5808 struct thread_info *thread;
5809
034f788c 5810 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
5811 if (ptid_match (thread->ptid, ptid)
5812 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 5813 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
5814 {
5815 p = append_resumption (p, endp, thread->ptid,
5816 0, thread->suspend.stop_signal);
5817 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 5818 resume_clear_thread_private_info (thread);
e5ef252a
PA
5819 }
5820
5821 return p;
5822}
5823
7b68ffbb
PA
5824/* Set the target running, using the packets that use Hc
5825 (c/s/C/S). */
5826
5827static void
5828remote_resume_with_hc (struct target_ops *ops,
5829 ptid_t ptid, int step, enum gdb_signal siggnal)
5830{
5831 struct remote_state *rs = get_remote_state ();
5832 struct thread_info *thread;
5833 char *buf;
5834
5835 rs->last_sent_signal = siggnal;
5836 rs->last_sent_step = step;
5837
5838 /* The c/s/C/S resume packets use Hc, so set the continue
5839 thread. */
5840 if (ptid_equal (ptid, minus_one_ptid))
5841 set_continue_thread (any_thread_ptid);
5842 else
5843 set_continue_thread (ptid);
5844
5845 ALL_NON_EXITED_THREADS (thread)
5846 resume_clear_thread_private_info (thread);
5847
5848 buf = rs->buf;
5849 if (execution_direction == EXEC_REVERSE)
5850 {
5851 /* We don't pass signals to the target in reverse exec mode. */
5852 if (info_verbose && siggnal != GDB_SIGNAL_0)
5853 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5854 siggnal);
5855
5856 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5857 error (_("Remote reverse-step not supported."));
5858 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5859 error (_("Remote reverse-continue not supported."));
5860
5861 strcpy (buf, step ? "bs" : "bc");
5862 }
5863 else if (siggnal != GDB_SIGNAL_0)
5864 {
5865 buf[0] = step ? 'S' : 'C';
5866 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5867 buf[2] = tohex (((int) siggnal) & 0xf);
5868 buf[3] = '\0';
5869 }
5870 else
5871 strcpy (buf, step ? "s" : "c");
5872
5873 putpkt (buf);
5874}
5875
506fb367
DJ
5876/* Resume the remote inferior by using a "vCont" packet. The thread
5877 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
5878 resumed thread should be single-stepped and/or signalled. If PTID
5879 equals minus_one_ptid, then all threads are resumed; the thread to
5880 be stepped and/or signalled is given in the global INFERIOR_PTID.
5881 This function returns non-zero iff it resumes the inferior.
44eaed12 5882
7b68ffbb
PA
5883 This function issues a strict subset of all possible vCont commands
5884 at the moment. */
44eaed12 5885
506fb367 5886static int
7b68ffbb 5887remote_resume_with_vcont (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
5888{
5889 struct remote_state *rs = get_remote_state ();
82f73884
PA
5890 char *p;
5891 char *endp;
44eaed12 5892
7b68ffbb
PA
5893 /* No reverse execution actions defined for vCont. */
5894 if (execution_direction == EXEC_REVERSE)
5895 return 0;
5896
4082afcc 5897 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 5898 remote_vcont_probe (rs);
44eaed12 5899
4082afcc 5900 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 5901 return 0;
44eaed12 5902
82f73884
PA
5903 p = rs->buf;
5904 endp = rs->buf + get_remote_packet_size ();
5905
506fb367
DJ
5906 /* If we could generate a wider range of packets, we'd have to worry
5907 about overflowing BUF. Should there be a generic
5908 "multi-part-packet" packet? */
5909
0d8f58ca
PA
5910 p += xsnprintf (p, endp - p, "vCont");
5911
79d7f229 5912 if (ptid_equal (ptid, magic_null_ptid))
c906108c 5913 {
79d7f229
PA
5914 /* MAGIC_NULL_PTID means that we don't have any active threads,
5915 so we don't have any TID numbers the inferior will
5916 understand. Make sure to only send forms that do not specify
5917 a TID. */
a9cbf802 5918 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 5919 }
0d8f58ca 5920 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 5921 {
0d8f58ca
PA
5922 /* Resume all threads (of all processes, or of a single
5923 process), with preference for INFERIOR_PTID. This assumes
5924 inferior_ptid belongs to the set of all threads we are about
5925 to resume. */
a493e3e2 5926 if (step || siggnal != GDB_SIGNAL_0)
82f73884 5927 {
0d8f58ca
PA
5928 /* Step inferior_ptid, with or without signal. */
5929 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 5930 }
0d8f58ca 5931
e5ef252a
PA
5932 /* Also pass down any pending signaled resumption for other
5933 threads not the current. */
5934 p = append_pending_thread_resumptions (p, endp, ptid);
5935
0d8f58ca 5936 /* And continue others without a signal. */
a493e3e2 5937 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
5938 }
5939 else
506fb367
DJ
5940 {
5941 /* Scheduler locking; resume only PTID. */
a9cbf802 5942 append_resumption (p, endp, ptid, step, siggnal);
506fb367 5943 }
c906108c 5944
82f73884
PA
5945 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5946 putpkt (rs->buf);
506fb367 5947
6efcd9a8 5948 if (target_is_non_stop_p ())
74531fed
PA
5949 {
5950 /* In non-stop, the stub replies to vCont with "OK". The stop
5951 reply will be reported asynchronously by means of a `%Stop'
5952 notification. */
5953 getpkt (&rs->buf, &rs->buf_size, 0);
5954 if (strcmp (rs->buf, "OK") != 0)
5955 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5956 }
5957
506fb367 5958 return 1;
c906108c 5959}
43ff13b4 5960
506fb367
DJ
5961/* Tell the remote machine to resume. */
5962
f6ac5f3d
PA
5963void
5964remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 5965{
d01949b6 5966 struct remote_state *rs = get_remote_state ();
43ff13b4 5967
85ad3aaf
PA
5968 /* When connected in non-stop mode, the core resumes threads
5969 individually. Resuming remote threads directly in target_resume
5970 would thus result in sending one packet per thread. Instead, to
5971 minimize roundtrip latency, here we just store the resume
5972 request; the actual remote resumption will be done in
5973 target_commit_resume / remote_commit_resume, where we'll be able
5974 to do vCont action coalescing. */
f6ac5f3d 5975 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
85ad3aaf 5976 {
7aabaf9d 5977 remote_thread_info *remote_thr;
85ad3aaf
PA
5978
5979 if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
7aabaf9d 5980 remote_thr = get_remote_thread_info (inferior_ptid);
85ad3aaf 5981 else
7aabaf9d
SM
5982 remote_thr = get_remote_thread_info (ptid);
5983
85ad3aaf
PA
5984 remote_thr->last_resume_step = step;
5985 remote_thr->last_resume_sig = siggnal;
5986 return;
5987 }
5988
722247f1
YQ
5989 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5990 (explained in remote-notif.c:handle_notification) so
5991 remote_notif_process is not called. We need find a place where
5992 it is safe to start a 'vNotif' sequence. It is good to do it
5993 before resuming inferior, because inferior was stopped and no RSP
5994 traffic at that moment. */
6efcd9a8 5995 if (!target_is_non_stop_p ())
5965e028 5996 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 5997
f6ac5f3d 5998 rs->last_resume_exec_dir = ::execution_direction;
3a00c802 5999
7b68ffbb
PA
6000 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6001 if (!remote_resume_with_vcont (ptid, step, siggnal))
f6ac5f3d 6002 remote_resume_with_hc (this, ptid, step, siggnal);
43ff13b4 6003
2acceee2 6004 /* We are about to start executing the inferior, let's register it
0df8b418
MS
6005 with the event loop. NOTE: this is the one place where all the
6006 execution commands end up. We could alternatively do this in each
23860348 6007 of the execution commands in infcmd.c. */
2acceee2
JM
6008 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6009 into infcmd.c in order to allow inferior function calls to work
23860348 6010 NOT asynchronously. */
362646f5 6011 if (target_can_async_p ())
6a3753b3 6012 target_async (1);
e24a49d8
PA
6013
6014 /* We've just told the target to resume. The remote server will
6015 wait for the inferior to stop, and then send a stop reply. In
6016 the mean time, we can't start another command/query ourselves
74531fed
PA
6017 because the stub wouldn't be ready to process it. This applies
6018 only to the base all-stop protocol, however. In non-stop (which
6019 only supports vCont), the stub replies with an "OK", and is
6020 immediate able to process further serial input. */
6efcd9a8 6021 if (!target_is_non_stop_p ())
74531fed 6022 rs->waiting_for_stop_reply = 1;
43ff13b4 6023}
85ad3aaf
PA
6024
6025static void check_pending_events_prevent_wildcard_vcont
6026 (int *may_global_wildcard_vcont);
6027static int is_pending_fork_parent_thread (struct thread_info *thread);
6028
6029/* Private per-inferior info for target remote processes. */
6030
089354bb 6031struct remote_inferior : public private_inferior
85ad3aaf
PA
6032{
6033 /* Whether we can send a wildcard vCont for this process. */
089354bb 6034 bool may_wildcard_vcont = true;
85ad3aaf
PA
6035};
6036
089354bb
SM
6037/* Get the remote private inferior data associated to INF. */
6038
6039static remote_inferior *
6040get_remote_inferior (inferior *inf)
6041{
6042 if (inf->priv == NULL)
6043 inf->priv.reset (new remote_inferior);
6044
6045 return static_cast<remote_inferior *> (inf->priv.get ());
6046}
6047
85ad3aaf
PA
6048/* Structure used to track the construction of a vCont packet in the
6049 outgoing packet buffer. This is used to send multiple vCont
6050 packets if we have more actions than would fit a single packet. */
6051
6052struct vcont_builder
6053{
6054 /* Pointer to the first action. P points here if no action has been
6055 appended yet. */
6056 char *first_action;
6057
6058 /* Where the next action will be appended. */
6059 char *p;
6060
6061 /* The end of the buffer. Must never write past this. */
6062 char *endp;
6063};
6064
6065/* Prepare the outgoing buffer for a new vCont packet. */
6066
6067static void
6068vcont_builder_restart (struct vcont_builder *builder)
6069{
6070 struct remote_state *rs = get_remote_state ();
6071
6072 builder->p = rs->buf;
6073 builder->endp = rs->buf + get_remote_packet_size ();
6074 builder->p += xsnprintf (builder->p, builder->endp - builder->p, "vCont");
6075 builder->first_action = builder->p;
6076}
6077
6078/* If the vCont packet being built has any action, send it to the
6079 remote end. */
6080
6081static void
6082vcont_builder_flush (struct vcont_builder *builder)
6083{
6084 struct remote_state *rs;
6085
6086 if (builder->p == builder->first_action)
6087 return;
6088
6089 rs = get_remote_state ();
6090 putpkt (rs->buf);
6091 getpkt (&rs->buf, &rs->buf_size, 0);
6092 if (strcmp (rs->buf, "OK") != 0)
6093 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6094}
6095
6096/* The largest action is range-stepping, with its two addresses. This
6097 is more than sufficient. If a new, bigger action is created, it'll
6098 quickly trigger a failed assertion in append_resumption (and we'll
6099 just bump this). */
6100#define MAX_ACTION_SIZE 200
6101
6102/* Append a new vCont action in the outgoing packet being built. If
6103 the action doesn't fit the packet along with previous actions, push
6104 what we've got so far to the remote end and start over a new vCont
6105 packet (with the new action). */
6106
6107static void
6108vcont_builder_push_action (struct vcont_builder *builder,
6109 ptid_t ptid, int step, enum gdb_signal siggnal)
6110{
6111 char buf[MAX_ACTION_SIZE + 1];
6112 char *endp;
6113 size_t rsize;
6114
6115 endp = append_resumption (buf, buf + sizeof (buf),
6116 ptid, step, siggnal);
6117
6118 /* Check whether this new action would fit in the vCont packet along
6119 with previous actions. If not, send what we've got so far and
6120 start a new vCont packet. */
6121 rsize = endp - buf;
6122 if (rsize > builder->endp - builder->p)
6123 {
6124 vcont_builder_flush (builder);
6125 vcont_builder_restart (builder);
6126
6127 /* Should now fit. */
6128 gdb_assert (rsize <= builder->endp - builder->p);
6129 }
6130
6131 memcpy (builder->p, buf, rsize);
6132 builder->p += rsize;
6133 *builder->p = '\0';
6134}
6135
6136/* to_commit_resume implementation. */
6137
f6ac5f3d
PA
6138void
6139remote_target::commit_resume ()
85ad3aaf 6140{
85ad3aaf
PA
6141 struct inferior *inf;
6142 struct thread_info *tp;
6143 int any_process_wildcard;
6144 int may_global_wildcard_vcont;
6145 struct vcont_builder vcont_builder;
6146
6147 /* If connected in all-stop mode, we'd send the remote resume
6148 request directly from remote_resume. Likewise if
6149 reverse-debugging, as there are no defined vCont actions for
6150 reverse execution. */
f6ac5f3d 6151 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
85ad3aaf
PA
6152 return;
6153
6154 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6155 instead of resuming all threads of each process individually.
6156 However, if any thread of a process must remain halted, we can't
6157 send wildcard resumes and must send one action per thread.
6158
6159 Care must be taken to not resume threads/processes the server
6160 side already told us are stopped, but the core doesn't know about
6161 yet, because the events are still in the vStopped notification
6162 queue. For example:
6163
6164 #1 => vCont s:p1.1;c
6165 #2 <= OK
6166 #3 <= %Stopped T05 p1.1
6167 #4 => vStopped
6168 #5 <= T05 p1.2
6169 #6 => vStopped
6170 #7 <= OK
6171 #8 (infrun handles the stop for p1.1 and continues stepping)
6172 #9 => vCont s:p1.1;c
6173
6174 The last vCont above would resume thread p1.2 by mistake, because
6175 the server has no idea that the event for p1.2 had not been
6176 handled yet.
6177
6178 The server side must similarly ignore resume actions for the
6179 thread that has a pending %Stopped notification (and any other
6180 threads with events pending), until GDB acks the notification
6181 with vStopped. Otherwise, e.g., the following case is
6182 mishandled:
6183
6184 #1 => g (or any other packet)
6185 #2 <= [registers]
6186 #3 <= %Stopped T05 p1.2
6187 #4 => vCont s:p1.1;c
6188 #5 <= OK
6189
6190 Above, the server must not resume thread p1.2. GDB can't know
6191 that p1.2 stopped until it acks the %Stopped notification, and
6192 since from GDB's perspective all threads should be running, it
6193 sends a "c" action.
6194
6195 Finally, special care must also be given to handling fork/vfork
6196 events. A (v)fork event actually tells us that two processes
6197 stopped -- the parent and the child. Until we follow the fork,
6198 we must not resume the child. Therefore, if we have a pending
6199 fork follow, we must not send a global wildcard resume action
6200 (vCont;c). We can still send process-wide wildcards though. */
6201
6202 /* Start by assuming a global wildcard (vCont;c) is possible. */
6203 may_global_wildcard_vcont = 1;
6204
6205 /* And assume every process is individually wildcard-able too. */
6206 ALL_NON_EXITED_INFERIORS (inf)
6207 {
089354bb
SM
6208 remote_inferior *priv = get_remote_inferior (inf);
6209
6210 priv->may_wildcard_vcont = true;
85ad3aaf
PA
6211 }
6212
6213 /* Check for any pending events (not reported or processed yet) and
6214 disable process and global wildcard resumes appropriately. */
6215 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6216
6217 ALL_NON_EXITED_THREADS (tp)
6218 {
6219 /* If a thread of a process is not meant to be resumed, then we
6220 can't wildcard that process. */
6221 if (!tp->executing)
6222 {
089354bb 6223 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
85ad3aaf
PA
6224
6225 /* And if we can't wildcard a process, we can't wildcard
6226 everything either. */
6227 may_global_wildcard_vcont = 0;
6228 continue;
6229 }
6230
6231 /* If a thread is the parent of an unfollowed fork, then we
6232 can't do a global wildcard, as that would resume the fork
6233 child. */
6234 if (is_pending_fork_parent_thread (tp))
6235 may_global_wildcard_vcont = 0;
6236 }
6237
6238 /* Now let's build the vCont packet(s). Actions must be appended
6239 from narrower to wider scopes (thread -> process -> global). If
6240 we end up with too many actions for a single packet vcont_builder
6241 flushes the current vCont packet to the remote side and starts a
6242 new one. */
6243 vcont_builder_restart (&vcont_builder);
6244
6245 /* Threads first. */
6246 ALL_NON_EXITED_THREADS (tp)
6247 {
7aabaf9d 6248 remote_thread_info *remote_thr = get_remote_thread_info (tp);
85ad3aaf
PA
6249
6250 if (!tp->executing || remote_thr->vcont_resumed)
6251 continue;
6252
6253 gdb_assert (!thread_is_in_step_over_chain (tp));
6254
6255 if (!remote_thr->last_resume_step
6256 && remote_thr->last_resume_sig == GDB_SIGNAL_0
089354bb 6257 && get_remote_inferior (tp->inf)->may_wildcard_vcont)
85ad3aaf
PA
6258 {
6259 /* We'll send a wildcard resume instead. */
6260 remote_thr->vcont_resumed = 1;
6261 continue;
6262 }
6263
6264 vcont_builder_push_action (&vcont_builder, tp->ptid,
6265 remote_thr->last_resume_step,
6266 remote_thr->last_resume_sig);
6267 remote_thr->vcont_resumed = 1;
6268 }
6269
6270 /* Now check whether we can send any process-wide wildcard. This is
6271 to avoid sending a global wildcard in the case nothing is
6272 supposed to be resumed. */
6273 any_process_wildcard = 0;
6274
6275 ALL_NON_EXITED_INFERIORS (inf)
6276 {
089354bb 6277 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf
PA
6278 {
6279 any_process_wildcard = 1;
6280 break;
6281 }
6282 }
6283
6284 if (any_process_wildcard)
6285 {
6286 /* If all processes are wildcard-able, then send a single "c"
6287 action, otherwise, send an "all (-1) threads of process"
6288 continue action for each running process, if any. */
6289 if (may_global_wildcard_vcont)
6290 {
6291 vcont_builder_push_action (&vcont_builder, minus_one_ptid,
6292 0, GDB_SIGNAL_0);
6293 }
6294 else
6295 {
6296 ALL_NON_EXITED_INFERIORS (inf)
6297 {
089354bb 6298 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf
PA
6299 {
6300 vcont_builder_push_action (&vcont_builder,
6301 pid_to_ptid (inf->pid),
6302 0, GDB_SIGNAL_0);
6303 }
6304 }
6305 }
6306 }
6307
6308 vcont_builder_flush (&vcont_builder);
6309}
6310
c906108c 6311\f
43ff13b4 6312
74531fed
PA
6313/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6314 thread, all threads of a remote process, or all threads of all
6315 processes. */
6316
6317static void
6318remote_stop_ns (ptid_t ptid)
6319{
6320 struct remote_state *rs = get_remote_state ();
6321 char *p = rs->buf;
6322 char *endp = rs->buf + get_remote_packet_size ();
74531fed 6323
4082afcc 6324 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
6325 remote_vcont_probe (rs);
6326
d458bd84 6327 if (!rs->supports_vCont.t)
74531fed
PA
6328 error (_("Remote server does not support stopping threads"));
6329
f91d3df5
PA
6330 if (ptid_equal (ptid, minus_one_ptid)
6331 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
6332 p += xsnprintf (p, endp - p, "vCont;t");
6333 else
6334 {
6335 ptid_t nptid;
6336
74531fed
PA
6337 p += xsnprintf (p, endp - p, "vCont;t:");
6338
6339 if (ptid_is_pid (ptid))
6340 /* All (-1) threads of process. */
ba348170 6341 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
6342 else
6343 {
6344 /* Small optimization: if we already have a stop reply for
6345 this thread, no use in telling the stub we want this
6346 stopped. */
6347 if (peek_stop_reply (ptid))
6348 return;
6349
6350 nptid = ptid;
6351 }
6352
a9cbf802 6353 write_ptid (p, endp, nptid);
74531fed
PA
6354 }
6355
6356 /* In non-stop, we get an immediate OK reply. The stop reply will
6357 come in asynchronously by notification. */
6358 putpkt (rs->buf);
6359 getpkt (&rs->buf, &rs->buf_size, 0);
6360 if (strcmp (rs->buf, "OK") != 0)
6361 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6362}
6363
bfedc46a
PA
6364/* All-stop version of target_interrupt. Sends a break or a ^C to
6365 interrupt the remote target. It is undefined which thread of which
6366 process reports the interrupt. */
74531fed
PA
6367
6368static void
de979965 6369remote_interrupt_as (void)
74531fed
PA
6370{
6371 struct remote_state *rs = get_remote_state ();
6372
3a29589a
DJ
6373 rs->ctrlc_pending_p = 1;
6374
74531fed
PA
6375 /* If the inferior is stopped already, but the core didn't know
6376 about it yet, just ignore the request. The cached wait status
6377 will be collected in remote_wait. */
6378 if (rs->cached_wait_status)
6379 return;
6380
9a7071a8
JB
6381 /* Send interrupt_sequence to remote target. */
6382 send_interrupt_sequence ();
74531fed
PA
6383}
6384
de979965
PA
6385/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6386 the remote target. It is undefined which thread of which process
e42de8c7
PA
6387 reports the interrupt. Throws an error if the packet is not
6388 supported by the server. */
de979965 6389
e42de8c7 6390static void
de979965
PA
6391remote_interrupt_ns (void)
6392{
6393 struct remote_state *rs = get_remote_state ();
6394 char *p = rs->buf;
6395 char *endp = rs->buf + get_remote_packet_size ();
6396
6397 xsnprintf (p, endp - p, "vCtrlC");
6398
6399 /* In non-stop, we get an immediate OK reply. The stop reply will
6400 come in asynchronously by notification. */
6401 putpkt (rs->buf);
6402 getpkt (&rs->buf, &rs->buf_size, 0);
6403
6404 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6405 {
6406 case PACKET_OK:
6407 break;
6408 case PACKET_UNKNOWN:
e42de8c7 6409 error (_("No support for interrupting the remote target."));
de979965
PA
6410 case PACKET_ERROR:
6411 error (_("Interrupting target failed: %s"), rs->buf);
6412 }
de979965
PA
6413}
6414
bfedc46a 6415/* Implement the to_stop function for the remote targets. */
74531fed 6416
f6ac5f3d
PA
6417void
6418remote_target::stop (ptid_t ptid)
c906108c 6419{
7a292a7a 6420 if (remote_debug)
0f71a2f6 6421 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 6422
6efcd9a8 6423 if (target_is_non_stop_p ())
74531fed 6424 remote_stop_ns (ptid);
c906108c 6425 else
bfedc46a
PA
6426 {
6427 /* We don't currently have a way to transparently pause the
6428 remote target in all-stop mode. Interrupt it instead. */
de979965 6429 remote_interrupt_as ();
bfedc46a
PA
6430 }
6431}
6432
6433/* Implement the to_interrupt function for the remote targets. */
6434
f6ac5f3d
PA
6435void
6436remote_target::interrupt ()
bfedc46a
PA
6437{
6438 if (remote_debug)
6439 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6440
e42de8c7
PA
6441 if (target_is_non_stop_p ())
6442 remote_interrupt_ns ();
bfedc46a 6443 else
e42de8c7 6444 remote_interrupt_as ();
c906108c
SS
6445}
6446
93692b58
PA
6447/* Implement the to_pass_ctrlc function for the remote targets. */
6448
f6ac5f3d
PA
6449void
6450remote_target::pass_ctrlc ()
93692b58
PA
6451{
6452 struct remote_state *rs = get_remote_state ();
6453
6454 if (remote_debug)
6455 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6456
6457 /* If we're starting up, we're not fully synced yet. Quit
6458 immediately. */
6459 if (rs->starting_up)
6460 quit ();
6461 /* If ^C has already been sent once, offer to disconnect. */
6462 else if (rs->ctrlc_pending_p)
6463 interrupt_query ();
6464 else
e671cd59 6465 target_interrupt ();
93692b58
PA
6466}
6467
c906108c
SS
6468/* Ask the user what to do when an interrupt is received. */
6469
6470static void
fba45db2 6471interrupt_query (void)
c906108c 6472{
abc56d60 6473 struct remote_state *rs = get_remote_state ();
c906108c 6474
abc56d60 6475 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 6476 {
abc56d60
PA
6477 if (query (_("The target is not responding to interrupt requests.\n"
6478 "Stop debugging it? ")))
74531fed 6479 {
78a095c3 6480 remote_unpush_target ();
abc56d60 6481 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
6482 }
6483 }
abc56d60
PA
6484 else
6485 {
6486 if (query (_("Interrupted while waiting for the program.\n"
6487 "Give up waiting? ")))
6488 quit ();
6489 }
c906108c
SS
6490}
6491
6426a772
JM
6492/* Enable/disable target terminal ownership. Most targets can use
6493 terminal groups to control terminal ownership. Remote targets are
6494 different in that explicit transfer of ownership to/from GDB/target
23860348 6495 is required. */
6426a772 6496
f6ac5f3d
PA
6497void
6498remote_target::terminal_inferior ()
6426a772 6499{
6426a772
JM
6500 /* NOTE: At this point we could also register our selves as the
6501 recipient of all input. Any characters typed could then be
23860348 6502 passed on down to the target. */
6426a772
JM
6503}
6504
f6ac5f3d
PA
6505void
6506remote_target::terminal_ours ()
6426a772 6507{
6426a772
JM
6508}
6509
176a6961 6510static void
917317f4 6511remote_console_output (char *msg)
c906108c
SS
6512{
6513 char *p;
6514
c5aa993b 6515 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
6516 {
6517 char tb[2];
6518 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 6519
c906108c
SS
6520 tb[0] = c;
6521 tb[1] = 0;
43ff13b4 6522 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 6523 }
00db5b94
PA
6524 gdb_flush (gdb_stdtarg);
6525}
74531fed 6526
74531fed
PA
6527DEF_VEC_O(cached_reg_t);
6528
722247f1 6529typedef struct stop_reply
74531fed 6530{
722247f1 6531 struct notif_event base;
74531fed 6532
722247f1 6533 /* The identifier of the thread about this event */
74531fed
PA
6534 ptid_t ptid;
6535
340e3c99 6536 /* The remote state this event is associated with. When the remote
bcc75809
YQ
6537 connection, represented by a remote_state object, is closed,
6538 all the associated stop_reply events should be released. */
6539 struct remote_state *rs;
6540
74531fed
PA
6541 struct target_waitstatus ws;
6542
5cd63fda
PA
6543 /* The architecture associated with the expedited registers. */
6544 gdbarch *arch;
6545
15148d6a
PA
6546 /* Expedited registers. This makes remote debugging a bit more
6547 efficient for those targets that provide critical registers as
6548 part of their normal status mechanism (as another roundtrip to
6549 fetch them is avoided). */
74531fed
PA
6550 VEC(cached_reg_t) *regcache;
6551
f7e6eed5
PA
6552 enum target_stop_reason stop_reason;
6553
74531fed
PA
6554 CORE_ADDR watch_data_address;
6555
dc146f7c 6556 int core;
722247f1 6557} *stop_reply_p;
a744cf53 6558
722247f1
YQ
6559DECLARE_QUEUE_P (stop_reply_p);
6560DEFINE_QUEUE_P (stop_reply_p);
6561/* The list of already fetched and acknowledged stop events. This
6562 queue is used for notification Stop, and other notifications
6563 don't need queue for their events, because the notification events
6564 of Stop can't be consumed immediately, so that events should be
6565 queued first, and be consumed by remote_wait_{ns,as} one per
6566 time. Other notifications can consume their events immediately,
6567 so queue is not needed for them. */
6568static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
6569
6570static void
6571stop_reply_xfree (struct stop_reply *r)
6572{
f48ff2a7 6573 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
6574}
6575
221e1a37
PA
6576/* Return the length of the stop reply queue. */
6577
6578static int
6579stop_reply_queue_length (void)
6580{
6581 return QUEUE_length (stop_reply_p, stop_reply_queue);
6582}
6583
722247f1
YQ
6584static void
6585remote_notif_stop_parse (struct notif_client *self, char *buf,
6586 struct notif_event *event)
6587{
6588 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6589}
6590
6591static void
6592remote_notif_stop_ack (struct notif_client *self, char *buf,
6593 struct notif_event *event)
6594{
6595 struct stop_reply *stop_reply = (struct stop_reply *) event;
6596
6597 /* acknowledge */
f5c4fcd9 6598 putpkt (self->ack_command);
722247f1
YQ
6599
6600 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6601 /* We got an unknown stop reply. */
6602 error (_("Unknown stop reply"));
6603
6604 push_stop_reply (stop_reply);
6605}
6606
6607static int
6608remote_notif_stop_can_get_pending_events (struct notif_client *self)
6609{
6610 /* We can't get pending events in remote_notif_process for
6611 notification stop, and we have to do this in remote_wait_ns
6612 instead. If we fetch all queued events from stub, remote stub
6613 may exit and we have no chance to process them back in
6614 remote_wait_ns. */
6615 mark_async_event_handler (remote_async_inferior_event_token);
6616 return 0;
6617}
6618
6619static void
6620stop_reply_dtr (struct notif_event *event)
6621{
6622 struct stop_reply *r = (struct stop_reply *) event;
d1dff226
AH
6623 cached_reg_t *reg;
6624 int ix;
6625
6626 for (ix = 0;
6627 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6628 ix++)
6629 xfree (reg->data);
722247f1
YQ
6630
6631 VEC_free (cached_reg_t, r->regcache);
6632}
6633
6634static struct notif_event *
6635remote_notif_stop_alloc_reply (void)
6636{
8d749320
SM
6637 /* We cast to a pointer to the "base class". */
6638 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
6639
6640 r->dtr = stop_reply_dtr;
6641
6642 return r;
6643}
6644
6645/* A client of notification Stop. */
6646
6647struct notif_client notif_client_stop =
6648{
6649 "Stop",
6650 "vStopped",
6651 remote_notif_stop_parse,
6652 remote_notif_stop_ack,
6653 remote_notif_stop_can_get_pending_events,
6654 remote_notif_stop_alloc_reply,
f48ff2a7 6655 REMOTE_NOTIF_STOP,
722247f1
YQ
6656};
6657
6658/* A parameter to pass data in and out. */
6659
6660struct queue_iter_param
6661{
6662 void *input;
6663 struct stop_reply *output;
6664};
6665
85ad3aaf 6666/* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
cbb8991c
DB
6667 the pid of the process that owns the threads we want to check, or
6668 -1 if we want to check all threads. */
6669
6670static int
6671is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6672 ptid_t thread_ptid)
6673{
6674 if (ws->kind == TARGET_WAITKIND_FORKED
6675 || ws->kind == TARGET_WAITKIND_VFORKED)
6676 {
6677 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6678 return 1;
6679 }
6680
6681 return 0;
6682}
6683
85ad3aaf
PA
6684/* Return the thread's pending status used to determine whether the
6685 thread is a fork parent stopped at a fork event. */
6686
6687static struct target_waitstatus *
6688thread_pending_fork_status (struct thread_info *thread)
6689{
6690 if (thread->suspend.waitstatus_pending_p)
6691 return &thread->suspend.waitstatus;
6692 else
6693 return &thread->pending_follow;
6694}
6695
6696/* Determine if THREAD is a pending fork parent thread. */
6697
6698static int
6699is_pending_fork_parent_thread (struct thread_info *thread)
6700{
6701 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6702 int pid = -1;
6703
6704 return is_pending_fork_parent (ws, pid, thread->ptid);
6705}
6706
cbb8991c
DB
6707/* Check whether EVENT is a fork event, and if it is, remove the
6708 fork child from the context list passed in DATA. */
6709
6710static int
6711remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6712 QUEUE_ITER (stop_reply_p) *iter,
6713 stop_reply_p event,
6714 void *data)
6715{
19ba03f4
SM
6716 struct queue_iter_param *param = (struct queue_iter_param *) data;
6717 struct threads_listing_context *context
6718 = (struct threads_listing_context *) param->input;
cbb8991c
DB
6719
6720 if (event->ws.kind == TARGET_WAITKIND_FORKED
65706a29
PA
6721 || event->ws.kind == TARGET_WAITKIND_VFORKED
6722 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
21fe1c75 6723 context->remove_thread (event->ws.value.related_pid);
cbb8991c
DB
6724
6725 return 1;
6726}
6727
6728/* If CONTEXT contains any fork child threads that have not been
6729 reported yet, remove them from the CONTEXT list. If such a
6730 thread exists it is because we are stopped at a fork catchpoint
6731 and have not yet called follow_fork, which will set up the
6732 host-side data structures for the new process. */
6733
6734static void
6735remove_new_fork_children (struct threads_listing_context *context)
6736{
6737 struct thread_info * thread;
6738 int pid = -1;
6739 struct notif_client *notif = &notif_client_stop;
6740 struct queue_iter_param param;
6741
6742 /* For any threads stopped at a fork event, remove the corresponding
6743 fork child threads from the CONTEXT list. */
6744 ALL_NON_EXITED_THREADS (thread)
6745 {
85ad3aaf 6746 struct target_waitstatus *ws = thread_pending_fork_status (thread);
cbb8991c
DB
6747
6748 if (is_pending_fork_parent (ws, pid, thread->ptid))
21fe1c75 6749 context->remove_thread (ws->value.related_pid);
cbb8991c
DB
6750 }
6751
6752 /* Check for any pending fork events (not reported or processed yet)
6753 in process PID and remove those fork child threads from the
6754 CONTEXT list as well. */
6755 remote_notif_get_pending_events (notif);
6756 param.input = context;
6757 param.output = NULL;
6758 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6759 remove_child_of_pending_fork, &param);
6760}
6761
85ad3aaf
PA
6762/* Check whether EVENT would prevent a global or process wildcard
6763 vCont action. */
6764
6765static int
6766check_pending_event_prevents_wildcard_vcont_callback
6767 (QUEUE (stop_reply_p) *q,
6768 QUEUE_ITER (stop_reply_p) *iter,
6769 stop_reply_p event,
6770 void *data)
6771{
6772 struct inferior *inf;
6773 int *may_global_wildcard_vcont = (int *) data;
6774
6775 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
6776 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
6777 return 1;
6778
6779 if (event->ws.kind == TARGET_WAITKIND_FORKED
6780 || event->ws.kind == TARGET_WAITKIND_VFORKED)
6781 *may_global_wildcard_vcont = 0;
6782
6783 inf = find_inferior_ptid (event->ptid);
6784
6785 /* This may be the first time we heard about this process.
6786 Regardless, we must not do a global wildcard resume, otherwise
6787 we'd resume this process too. */
6788 *may_global_wildcard_vcont = 0;
6789 if (inf != NULL)
089354bb 6790 get_remote_inferior (inf)->may_wildcard_vcont = false;
85ad3aaf
PA
6791
6792 return 1;
6793}
6794
6795/* Check whether any event pending in the vStopped queue would prevent
6796 a global or process wildcard vCont action. Clear
6797 *may_global_wildcard if we can't do a global wildcard (vCont;c),
6798 and clear the event inferior's may_wildcard_vcont flag if we can't
6799 do a process-wide wildcard resume (vCont;c:pPID.-1). */
6800
6801static void
6802check_pending_events_prevent_wildcard_vcont (int *may_global_wildcard)
6803{
6804 struct notif_client *notif = &notif_client_stop;
6805
6806 remote_notif_get_pending_events (notif);
6807 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6808 check_pending_event_prevents_wildcard_vcont_callback,
6809 may_global_wildcard);
6810}
6811
f48ff2a7
YQ
6812/* Remove stop replies in the queue if its pid is equal to the given
6813 inferior's pid. */
722247f1
YQ
6814
6815static int
f48ff2a7
YQ
6816remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6817 QUEUE_ITER (stop_reply_p) *iter,
6818 stop_reply_p event,
6819 void *data)
722247f1 6820{
19ba03f4
SM
6821 struct queue_iter_param *param = (struct queue_iter_param *) data;
6822 struct inferior *inf = (struct inferior *) param->input;
722247f1 6823
f48ff2a7 6824 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
6825 {
6826 stop_reply_xfree (event);
6827 QUEUE_remove_elem (stop_reply_p, q, iter);
6828 }
6829
6830 return 1;
6831}
6832
f48ff2a7 6833/* Discard all pending stop replies of inferior INF. */
c906108c 6834
74531fed 6835static void
5f4cf0bb 6836discard_pending_stop_replies (struct inferior *inf)
c906108c 6837{
722247f1 6838 struct queue_iter_param param;
f48ff2a7
YQ
6839 struct stop_reply *reply;
6840 struct remote_state *rs = get_remote_state ();
6841 struct remote_notif_state *rns = rs->notif_state;
6842
6843 /* This function can be notified when an inferior exists. When the
6844 target is not remote, the notification state is NULL. */
6845 if (rs->remote_desc == NULL)
6846 return;
6847
6848 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 6849
74531fed 6850 /* Discard the in-flight notification. */
f48ff2a7 6851 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 6852 {
722247f1 6853 stop_reply_xfree (reply);
f48ff2a7 6854 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 6855 }
c906108c 6856
722247f1
YQ
6857 param.input = inf;
6858 param.output = NULL;
74531fed
PA
6859 /* Discard the stop replies we have already pulled with
6860 vStopped. */
722247f1 6861 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
6862 remove_stop_reply_for_inferior, &param);
6863}
6864
bcc75809
YQ
6865/* If its remote state is equal to the given remote state,
6866 remove EVENT from the stop reply queue. */
6867
6868static int
6869remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6870 QUEUE_ITER (stop_reply_p) *iter,
6871 stop_reply_p event,
6872 void *data)
6873{
19ba03f4
SM
6874 struct queue_iter_param *param = (struct queue_iter_param *) data;
6875 struct remote_state *rs = (struct remote_state *) param->input;
bcc75809
YQ
6876
6877 if (event->rs == rs)
6878 {
6879 stop_reply_xfree (event);
6880 QUEUE_remove_elem (stop_reply_p, q, iter);
6881 }
6882
6883 return 1;
6884}
6885
6886/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
6887
6888static void
bcc75809 6889discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
6890{
6891 struct queue_iter_param param;
6892
bcc75809 6893 param.input = rs;
f48ff2a7
YQ
6894 param.output = NULL;
6895 /* Discard the stop replies we have already pulled with
6896 vStopped. */
6897 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 6898 remove_stop_reply_of_remote_state, &param);
722247f1 6899}
74531fed 6900
722247f1
YQ
6901/* A parameter to pass data in and out. */
6902
6903static int
6904remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6905 QUEUE_ITER (stop_reply_p) *iter,
6906 stop_reply_p event,
6907 void *data)
6908{
19ba03f4
SM
6909 struct queue_iter_param *param = (struct queue_iter_param *) data;
6910 ptid_t *ptid = (ptid_t *) param->input;
722247f1
YQ
6911
6912 if (ptid_match (event->ptid, *ptid))
6913 {
6914 param->output = event;
6915 QUEUE_remove_elem (stop_reply_p, q, iter);
6916 return 0;
c8e38a49 6917 }
722247f1
YQ
6918
6919 return 1;
74531fed 6920}
43ff13b4 6921
722247f1
YQ
6922/* Remove the first reply in 'stop_reply_queue' which matches
6923 PTID. */
2e9f7625 6924
722247f1
YQ
6925static struct stop_reply *
6926remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 6927{
722247f1
YQ
6928 struct queue_iter_param param;
6929
6930 param.input = &ptid;
6931 param.output = NULL;
6932
6933 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6934 remote_notif_remove_once_on_match, &param);
6935 if (notif_debug)
6936 fprintf_unfiltered (gdb_stdlog,
6937 "notif: discard queued event: 'Stop' in %s\n",
6938 target_pid_to_str (ptid));
a744cf53 6939
722247f1 6940 return param.output;
74531fed 6941}
75c99385 6942
74531fed
PA
6943/* Look for a queued stop reply belonging to PTID. If one is found,
6944 remove it from the queue, and return it. Returns NULL if none is
6945 found. If there are still queued events left to process, tell the
6946 event loop to get back to target_wait soon. */
e24a49d8 6947
74531fed
PA
6948static struct stop_reply *
6949queued_stop_reply (ptid_t ptid)
6950{
722247f1 6951 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 6952
722247f1 6953 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
6954 /* There's still at least an event left. */
6955 mark_async_event_handler (remote_async_inferior_event_token);
6956
722247f1 6957 return r;
74531fed
PA
6958}
6959
6960/* Push a fully parsed stop reply in the stop reply queue. Since we
6961 know that we now have at least one queued event left to pass to the
6962 core side, tell the event loop to get back to target_wait soon. */
6963
6964static void
6965push_stop_reply (struct stop_reply *new_event)
6966{
722247f1 6967 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 6968
722247f1
YQ
6969 if (notif_debug)
6970 fprintf_unfiltered (gdb_stdlog,
6971 "notif: push 'Stop' %s to queue %d\n",
6972 target_pid_to_str (new_event->ptid),
6973 QUEUE_length (stop_reply_p,
6974 stop_reply_queue));
74531fed
PA
6975
6976 mark_async_event_handler (remote_async_inferior_event_token);
6977}
6978
722247f1
YQ
6979static int
6980stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6981 QUEUE_ITER (stop_reply_p) *iter,
6982 struct stop_reply *event,
6983 void *data)
6984{
19ba03f4 6985 ptid_t *ptid = (ptid_t *) data;
722247f1
YQ
6986
6987 return !(ptid_equal (*ptid, event->ptid)
6988 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6989}
6990
74531fed
PA
6991/* Returns true if we have a stop reply for PTID. */
6992
6993static int
6994peek_stop_reply (ptid_t ptid)
6995{
722247f1
YQ
6996 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6997 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
6998}
6999
26d56a93
SL
7000/* Helper for remote_parse_stop_reply. Return nonzero if the substring
7001 starting with P and ending with PEND matches PREFIX. */
7002
7003static int
7004strprefix (const char *p, const char *pend, const char *prefix)
7005{
7006 for ( ; p < pend; p++, prefix++)
7007 if (*p != *prefix)
7008 return 0;
7009 return *prefix == '\0';
7010}
7011
74531fed
PA
7012/* Parse the stop reply in BUF. Either the function succeeds, and the
7013 result is stored in EVENT, or throws an error. */
7014
7015static void
7016remote_parse_stop_reply (char *buf, struct stop_reply *event)
7017{
5cd63fda 7018 remote_arch_state *rsa = NULL;
74531fed 7019 ULONGEST addr;
256642e8 7020 const char *p;
94585166 7021 int skipregs = 0;
74531fed
PA
7022
7023 event->ptid = null_ptid;
bcc75809 7024 event->rs = get_remote_state ();
74531fed
PA
7025 event->ws.kind = TARGET_WAITKIND_IGNORE;
7026 event->ws.value.integer = 0;
f7e6eed5 7027 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 7028 event->regcache = NULL;
dc146f7c 7029 event->core = -1;
74531fed
PA
7030
7031 switch (buf[0])
7032 {
7033 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
7034 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7035 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7036 ss = signal number
7037 n... = register number
7038 r... = register contents
7039 */
7040
7041 p = &buf[3]; /* after Txx */
7042 while (*p)
7043 {
256642e8 7044 const char *p1;
cea39f65 7045 int fieldsize;
43ff13b4 7046
1f10ba14
PA
7047 p1 = strchr (p, ':');
7048 if (p1 == NULL)
7049 error (_("Malformed packet(a) (missing colon): %s\n\
7050Packet: '%s'\n"),
7051 p, buf);
7052 if (p == p1)
7053 error (_("Malformed packet(a) (missing register number): %s\n\
7054Packet: '%s'\n"),
7055 p, buf);
3c3bea1c 7056
1f10ba14
PA
7057 /* Some "registers" are actually extended stop information.
7058 Note if you're adding a new entry here: GDB 7.9 and
7059 earlier assume that all register "numbers" that start
7060 with an hex digit are real register numbers. Make sure
7061 the server only sends such a packet if it knows the
7062 client understands it. */
c8e38a49 7063
26d56a93 7064 if (strprefix (p, p1, "thread"))
1f10ba14 7065 event->ptid = read_ptid (++p1, &p);
82075af2
JS
7066 else if (strprefix (p, p1, "syscall_entry"))
7067 {
7068 ULONGEST sysno;
7069
7070 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7071 p = unpack_varlen_hex (++p1, &sysno);
7072 event->ws.value.syscall_number = (int) sysno;
7073 }
7074 else if (strprefix (p, p1, "syscall_return"))
7075 {
7076 ULONGEST sysno;
7077
7078 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7079 p = unpack_varlen_hex (++p1, &sysno);
7080 event->ws.value.syscall_number = (int) sysno;
7081 }
26d56a93
SL
7082 else if (strprefix (p, p1, "watch")
7083 || strprefix (p, p1, "rwatch")
7084 || strprefix (p, p1, "awatch"))
cea39f65 7085 {
f7e6eed5 7086 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
7087 p = unpack_varlen_hex (++p1, &addr);
7088 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 7089 }
26d56a93 7090 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
7091 {
7092 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7093
7094 /* Make sure the stub doesn't forget to indicate support
7095 with qSupported. */
7096 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7097 error (_("Unexpected swbreak stop reason"));
7098
7099 /* The value part is documented as "must be empty",
7100 though we ignore it, in case we ever decide to make
7101 use of it in a backward compatible way. */
8424cc97 7102 p = strchrnul (p1 + 1, ';');
f7e6eed5 7103 }
26d56a93 7104 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
7105 {
7106 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7107
7108 /* Make sure the stub doesn't forget to indicate support
7109 with qSupported. */
7110 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7111 error (_("Unexpected hwbreak stop reason"));
7112
7113 /* See above. */
8424cc97 7114 p = strchrnul (p1 + 1, ';');
f7e6eed5 7115 }
26d56a93 7116 else if (strprefix (p, p1, "library"))
cea39f65 7117 {
1f10ba14 7118 event->ws.kind = TARGET_WAITKIND_LOADED;
8424cc97 7119 p = strchrnul (p1 + 1, ';');
1f10ba14 7120 }
26d56a93 7121 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
7122 {
7123 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7124 /* p1 will indicate "begin" or "end", but it makes
7125 no difference for now, so ignore it. */
8424cc97 7126 p = strchrnul (p1 + 1, ';');
1f10ba14 7127 }
26d56a93 7128 else if (strprefix (p, p1, "core"))
1f10ba14
PA
7129 {
7130 ULONGEST c;
a744cf53 7131
1f10ba14
PA
7132 p = unpack_varlen_hex (++p1, &c);
7133 event->core = c;
cea39f65 7134 }
26d56a93 7135 else if (strprefix (p, p1, "fork"))
de0d863e
DB
7136 {
7137 event->ws.value.related_pid = read_ptid (++p1, &p);
7138 event->ws.kind = TARGET_WAITKIND_FORKED;
7139 }
26d56a93 7140 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
7141 {
7142 event->ws.value.related_pid = read_ptid (++p1, &p);
7143 event->ws.kind = TARGET_WAITKIND_VFORKED;
7144 }
26d56a93 7145 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
7146 {
7147 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
8424cc97 7148 p = strchrnul (p1 + 1, ';');
c269dbdb 7149 }
6ab24463 7150 else if (strprefix (p, p1, "exec"))
94585166
DB
7151 {
7152 ULONGEST ignored;
7153 char pathname[PATH_MAX];
7154 int pathlen;
7155
7156 /* Determine the length of the execd pathname. */
7157 p = unpack_varlen_hex (++p1, &ignored);
7158 pathlen = (p - p1) / 2;
7159
7160 /* Save the pathname for event reporting and for
7161 the next run command. */
7162 hex2bin (p1, (gdb_byte *) pathname, pathlen);
7163 pathname[pathlen] = '\0';
7164
7165 /* This is freed during event handling. */
7166 event->ws.value.execd_pathname = xstrdup (pathname);
7167 event->ws.kind = TARGET_WAITKIND_EXECD;
7168
7169 /* Skip the registers included in this packet, since
7170 they may be for an architecture different from the
7171 one used by the original program. */
7172 skipregs = 1;
7173 }
65706a29
PA
7174 else if (strprefix (p, p1, "create"))
7175 {
7176 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
8424cc97 7177 p = strchrnul (p1 + 1, ';');
65706a29 7178 }
cea39f65
MS
7179 else
7180 {
1f10ba14 7181 ULONGEST pnum;
256642e8 7182 const char *p_temp;
1f10ba14 7183
94585166
DB
7184 if (skipregs)
7185 {
8424cc97 7186 p = strchrnul (p1 + 1, ';');
94585166
DB
7187 p++;
7188 continue;
7189 }
7190
1f10ba14
PA
7191 /* Maybe a real ``P'' register number. */
7192 p_temp = unpack_varlen_hex (p, &pnum);
7193 /* If the first invalid character is the colon, we got a
7194 register number. Otherwise, it's an unknown stop
7195 reason. */
7196 if (p_temp == p1)
7197 {
5cd63fda
PA
7198 /* If we haven't parsed the event's thread yet, find
7199 it now, in order to find the architecture of the
7200 reported expedited registers. */
7201 if (event->ptid == null_ptid)
7202 {
7203 const char *thr = strstr (p1 + 1, ";thread:");
7204 if (thr != NULL)
7205 event->ptid = read_ptid (thr + strlen (";thread:"),
7206 NULL);
7207 else
3cada740
PA
7208 {
7209 /* Either the current thread hasn't changed,
7210 or the inferior is not multi-threaded.
7211 The event must be for the thread we last
7212 set as (or learned as being) current. */
7213 event->ptid = event->rs->general_thread;
7214 }
5cd63fda
PA
7215 }
7216
7217 if (rsa == NULL)
7218 {
7219 inferior *inf = (event->ptid == null_ptid
7220 ? NULL
7221 : find_inferior_ptid (event->ptid));
7222 /* If this is the first time we learn anything
7223 about this process, skip the registers
7224 included in this packet, since we don't yet
7225 know which architecture to use to parse them.
7226 We'll determine the architecture later when
7227 we process the stop reply and retrieve the
7228 target description, via
7229 remote_notice_new_inferior ->
7230 post_create_inferior. */
7231 if (inf == NULL)
7232 {
7233 p = strchrnul (p1 + 1, ';');
7234 p++;
7235 continue;
7236 }
7237
7238 event->arch = inf->gdbarch;
7239 rsa = get_remote_arch_state (event->arch);
7240 }
7241
7242 packet_reg *reg
7243 = packet_reg_from_pnum (event->arch, rsa, pnum);
1f10ba14 7244 cached_reg_t cached_reg;
43ff13b4 7245
1f10ba14
PA
7246 if (reg == NULL)
7247 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 7248Packet: '%s'\n"),
1f10ba14 7249 hex_string (pnum), p, buf);
c8e38a49 7250
1f10ba14 7251 cached_reg.num = reg->regnum;
d1dff226 7252 cached_reg.data = (gdb_byte *)
5cd63fda 7253 xmalloc (register_size (event->arch, reg->regnum));
4100683b 7254
1f10ba14
PA
7255 p = p1 + 1;
7256 fieldsize = hex2bin (p, cached_reg.data,
5cd63fda 7257 register_size (event->arch, reg->regnum));
1f10ba14 7258 p += 2 * fieldsize;
5cd63fda 7259 if (fieldsize < register_size (event->arch, reg->regnum))
1f10ba14 7260 warning (_("Remote reply is too short: %s"), buf);
74531fed 7261
1f10ba14
PA
7262 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7263 }
7264 else
7265 {
7266 /* Not a number. Silently skip unknown optional
7267 info. */
8424cc97 7268 p = strchrnul (p1 + 1, ';');
1f10ba14 7269 }
cea39f65 7270 }
c8e38a49 7271
cea39f65
MS
7272 if (*p != ';')
7273 error (_("Remote register badly formatted: %s\nhere: %s"),
7274 buf, p);
7275 ++p;
7276 }
5b5596ff
PA
7277
7278 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7279 break;
7280
c8e38a49
PA
7281 /* fall through */
7282 case 'S': /* Old style status, just signal only. */
3a09da41
PA
7283 {
7284 int sig;
7285
7286 event->ws.kind = TARGET_WAITKIND_STOPPED;
7287 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7288 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7289 event->ws.value.sig = (enum gdb_signal) sig;
7290 else
7291 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7292 }
c8e38a49 7293 break;
65706a29
PA
7294 case 'w': /* Thread exited. */
7295 {
256642e8 7296 const char *p;
65706a29
PA
7297 ULONGEST value;
7298
7299 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7300 p = unpack_varlen_hex (&buf[1], &value);
7301 event->ws.value.integer = value;
7302 if (*p != ';')
7303 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 7304 event->ptid = read_ptid (++p, NULL);
65706a29
PA
7305 break;
7306 }
c8e38a49
PA
7307 case 'W': /* Target exited. */
7308 case 'X':
7309 {
256642e8 7310 const char *p;
c8e38a49
PA
7311 int pid;
7312 ULONGEST value;
82f73884 7313
c8e38a49
PA
7314 /* GDB used to accept only 2 hex chars here. Stubs should
7315 only send more if they detect GDB supports multi-process
7316 support. */
7317 p = unpack_varlen_hex (&buf[1], &value);
82f73884 7318
c8e38a49
PA
7319 if (buf[0] == 'W')
7320 {
7321 /* The remote process exited. */
74531fed
PA
7322 event->ws.kind = TARGET_WAITKIND_EXITED;
7323 event->ws.value.integer = value;
c8e38a49
PA
7324 }
7325 else
7326 {
7327 /* The remote process exited with a signal. */
74531fed 7328 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
7329 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7330 event->ws.value.sig = (enum gdb_signal) value;
7331 else
7332 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 7333 }
82f73884 7334
c8e38a49
PA
7335 /* If no process is specified, assume inferior_ptid. */
7336 pid = ptid_get_pid (inferior_ptid);
7337 if (*p == '\0')
7338 ;
7339 else if (*p == ';')
7340 {
7341 p++;
7342
0b24eb2d 7343 if (*p == '\0')
82f73884 7344 ;
61012eef 7345 else if (startswith (p, "process:"))
82f73884 7346 {
c8e38a49 7347 ULONGEST upid;
a744cf53 7348
c8e38a49
PA
7349 p += sizeof ("process:") - 1;
7350 unpack_varlen_hex (p, &upid);
7351 pid = upid;
82f73884
PA
7352 }
7353 else
7354 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 7355 }
c8e38a49
PA
7356 else
7357 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
7358 event->ptid = pid_to_ptid (pid);
7359 }
7360 break;
f2faf941
PA
7361 case 'N':
7362 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7363 event->ptid = minus_one_ptid;
7364 break;
74531fed
PA
7365 }
7366
6efcd9a8 7367 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
74531fed
PA
7368 error (_("No process or thread specified in stop reply: %s"), buf);
7369}
7370
722247f1
YQ
7371/* When the stub wants to tell GDB about a new notification reply, it
7372 sends a notification (%Stop, for example). Those can come it at
7373 any time, hence, we have to make sure that any pending
7374 putpkt/getpkt sequence we're making is finished, before querying
7375 the stub for more events with the corresponding ack command
7376 (vStopped, for example). E.g., if we started a vStopped sequence
7377 immediately upon receiving the notification, something like this
7378 could happen:
74531fed
PA
7379
7380 1.1) --> Hg 1
7381 1.2) <-- OK
7382 1.3) --> g
7383 1.4) <-- %Stop
7384 1.5) --> vStopped
7385 1.6) <-- (registers reply to step #1.3)
7386
7387 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7388 query.
7389
796cb314 7390 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
7391 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7392 doing whatever we were doing:
7393
7394 2.1) --> Hg 1
7395 2.2) <-- OK
7396 2.3) --> g
7397 2.4) <-- %Stop
7398 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7399 2.5) <-- (registers reply to step #2.3)
7400
7401 Eventualy after step #2.5, we return to the event loop, which
7402 notices there's an event on the
7403 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7404 associated callback --- the function below. At this point, we're
7405 always safe to start a vStopped sequence. :
7406
7407 2.6) --> vStopped
7408 2.7) <-- T05 thread:2
7409 2.8) --> vStopped
7410 2.9) --> OK
7411*/
7412
722247f1
YQ
7413void
7414remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
7415{
7416 struct remote_state *rs = get_remote_state ();
74531fed 7417
f48ff2a7 7418 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 7419 {
722247f1
YQ
7420 if (notif_debug)
7421 fprintf_unfiltered (gdb_stdlog,
7422 "notif: process: '%s' ack pending event\n",
7423 nc->name);
74531fed 7424
722247f1 7425 /* acknowledge */
f48ff2a7
YQ
7426 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7427 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
7428
7429 while (1)
7430 {
7431 getpkt (&rs->buf, &rs->buf_size, 0);
7432 if (strcmp (rs->buf, "OK") == 0)
7433 break;
7434 else
722247f1 7435 remote_notif_ack (nc, rs->buf);
74531fed
PA
7436 }
7437 }
722247f1
YQ
7438 else
7439 {
7440 if (notif_debug)
7441 fprintf_unfiltered (gdb_stdlog,
7442 "notif: process: '%s' no pending reply\n",
7443 nc->name);
7444 }
74531fed
PA
7445}
7446
74531fed
PA
7447/* Called when it is decided that STOP_REPLY holds the info of the
7448 event that is to be returned to the core. This function always
7449 destroys STOP_REPLY. */
7450
7451static ptid_t
7452process_stop_reply (struct stop_reply *stop_reply,
7453 struct target_waitstatus *status)
7454{
7455 ptid_t ptid;
7456
7457 *status = stop_reply->ws;
7458 ptid = stop_reply->ptid;
7459
7460 /* If no thread/process was reported by the stub, assume the current
7461 inferior. */
7462 if (ptid_equal (ptid, null_ptid))
7463 ptid = inferior_ptid;
7464
5f3563ea 7465 if (status->kind != TARGET_WAITKIND_EXITED
f2faf941
PA
7466 && status->kind != TARGET_WAITKIND_SIGNALLED
7467 && status->kind != TARGET_WAITKIND_NO_RESUMED)
74531fed 7468 {
5f3563ea
PA
7469 /* Expedited registers. */
7470 if (stop_reply->regcache)
7471 {
217f1f79 7472 struct regcache *regcache
5cd63fda 7473 = get_thread_arch_regcache (ptid, stop_reply->arch);
5f3563ea
PA
7474 cached_reg_t *reg;
7475 int ix;
7476
7477 for (ix = 0;
d1dff226 7478 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
5f3563ea 7479 ix++)
d1dff226 7480 {
217f1f79 7481 regcache_raw_supply (regcache, reg->num, reg->data);
d1dff226
AH
7482 xfree (reg->data);
7483 }
7484
5f3563ea
PA
7485 VEC_free (cached_reg_t, stop_reply->regcache);
7486 }
74531fed 7487
1941c569 7488 remote_notice_new_inferior (ptid, 0);
7aabaf9d 7489 remote_thread_info *remote_thr = get_remote_thread_info (ptid);
799a2abe
PA
7490 remote_thr->core = stop_reply->core;
7491 remote_thr->stop_reason = stop_reply->stop_reason;
7492 remote_thr->watch_data_address = stop_reply->watch_data_address;
85ad3aaf 7493 remote_thr->vcont_resumed = 0;
74531fed
PA
7494 }
7495
74531fed
PA
7496 stop_reply_xfree (stop_reply);
7497 return ptid;
7498}
7499
7500/* The non-stop mode version of target_wait. */
7501
7502static ptid_t
47608cb1 7503remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
7504{
7505 struct remote_state *rs = get_remote_state ();
74531fed
PA
7506 struct stop_reply *stop_reply;
7507 int ret;
fee9eda9 7508 int is_notif = 0;
74531fed
PA
7509
7510 /* If in non-stop mode, get out of getpkt even if a
7511 notification is received. */
7512
7513 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 7514 0 /* forever */, &is_notif);
74531fed
PA
7515 while (1)
7516 {
fee9eda9 7517 if (ret != -1 && !is_notif)
74531fed
PA
7518 switch (rs->buf[0])
7519 {
7520 case 'E': /* Error of some sort. */
7521 /* We're out of sync with the target now. Did it continue
7522 or not? We can't tell which thread it was in non-stop,
7523 so just ignore this. */
7524 warning (_("Remote failure reply: %s"), rs->buf);
7525 break;
7526 case 'O': /* Console output. */
7527 remote_console_output (rs->buf + 1);
7528 break;
7529 default:
7530 warning (_("Invalid remote reply: %s"), rs->buf);
7531 break;
7532 }
7533
7534 /* Acknowledge a pending stop reply that may have arrived in the
7535 mean time. */
f48ff2a7 7536 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 7537 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
7538
7539 /* If indeed we noticed a stop reply, we're done. */
7540 stop_reply = queued_stop_reply (ptid);
7541 if (stop_reply != NULL)
7542 return process_stop_reply (stop_reply, status);
7543
47608cb1 7544 /* Still no event. If we're just polling for an event, then
74531fed 7545 return to the event loop. */
47608cb1 7546 if (options & TARGET_WNOHANG)
74531fed
PA
7547 {
7548 status->kind = TARGET_WAITKIND_IGNORE;
7549 return minus_one_ptid;
7550 }
7551
47608cb1 7552 /* Otherwise do a blocking wait. */
74531fed 7553 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 7554 1 /* forever */, &is_notif);
74531fed
PA
7555 }
7556}
7557
7558/* Wait until the remote machine stops, then return, storing status in
7559 STATUS just as `wait' would. */
7560
7561static ptid_t
47608cb1 7562remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
7563{
7564 struct remote_state *rs = get_remote_state ();
74531fed 7565 ptid_t event_ptid = null_ptid;
cea39f65 7566 char *buf;
74531fed
PA
7567 struct stop_reply *stop_reply;
7568
47608cb1
PA
7569 again:
7570
74531fed
PA
7571 status->kind = TARGET_WAITKIND_IGNORE;
7572 status->value.integer = 0;
7573
7574 stop_reply = queued_stop_reply (ptid);
7575 if (stop_reply != NULL)
7576 return process_stop_reply (stop_reply, status);
7577
7578 if (rs->cached_wait_status)
7579 /* Use the cached wait status, but only once. */
7580 rs->cached_wait_status = 0;
7581 else
7582 {
7583 int ret;
722247f1 7584 int is_notif;
567420d1
PA
7585 int forever = ((options & TARGET_WNOHANG) == 0
7586 && wait_forever_enabled_p);
7587
7588 if (!rs->waiting_for_stop_reply)
7589 {
7590 status->kind = TARGET_WAITKIND_NO_RESUMED;
7591 return minus_one_ptid;
7592 }
74531fed 7593
74531fed
PA
7594 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7595 _never_ wait for ever -> test on target_is_async_p().
7596 However, before we do that we need to ensure that the caller
7597 knows how to take the target into/out of async mode. */
722247f1 7598 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 7599 forever, &is_notif);
722247f1
YQ
7600
7601 /* GDB gets a notification. Return to core as this event is
7602 not interesting. */
7603 if (ret != -1 && is_notif)
7604 return minus_one_ptid;
567420d1
PA
7605
7606 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7607 return minus_one_ptid;
74531fed
PA
7608 }
7609
7610 buf = rs->buf;
7611
3a29589a
DJ
7612 /* Assume that the target has acknowledged Ctrl-C unless we receive
7613 an 'F' or 'O' packet. */
7614 if (buf[0] != 'F' && buf[0] != 'O')
7615 rs->ctrlc_pending_p = 0;
7616
74531fed
PA
7617 switch (buf[0])
7618 {
7619 case 'E': /* Error of some sort. */
7620 /* We're out of sync with the target now. Did it continue or
7621 not? Not is more likely, so report a stop. */
29090fb6
LM
7622 rs->waiting_for_stop_reply = 0;
7623
74531fed
PA
7624 warning (_("Remote failure reply: %s"), buf);
7625 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 7626 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
7627 break;
7628 case 'F': /* File-I/O request. */
e42e5352
YQ
7629 /* GDB may access the inferior memory while handling the File-I/O
7630 request, but we don't want GDB accessing memory while waiting
7631 for a stop reply. See the comments in putpkt_binary. Set
7632 waiting_for_stop_reply to 0 temporarily. */
7633 rs->waiting_for_stop_reply = 0;
3a29589a
DJ
7634 remote_fileio_request (buf, rs->ctrlc_pending_p);
7635 rs->ctrlc_pending_p = 0;
e42e5352
YQ
7636 /* GDB handled the File-I/O request, and the target is running
7637 again. Keep waiting for events. */
7638 rs->waiting_for_stop_reply = 1;
74531fed 7639 break;
f2faf941 7640 case 'N': case 'T': case 'S': case 'X': case 'W':
74531fed 7641 {
29090fb6
LM
7642 struct stop_reply *stop_reply;
7643
7644 /* There is a stop reply to handle. */
7645 rs->waiting_for_stop_reply = 0;
7646
7647 stop_reply
722247f1
YQ
7648 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
7649 rs->buf);
74531fed 7650
74531fed 7651 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
7652 break;
7653 }
7654 case 'O': /* Console output. */
7655 remote_console_output (buf + 1);
c8e38a49
PA
7656 break;
7657 case '\0':
b73be471 7658 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
7659 {
7660 /* Zero length reply means that we tried 'S' or 'C' and the
7661 remote system doesn't support it. */
223ffa71 7662 target_terminal::ours_for_output ();
c8e38a49
PA
7663 printf_filtered
7664 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
7665 gdb_signal_to_name (rs->last_sent_signal));
7666 rs->last_sent_signal = GDB_SIGNAL_0;
223ffa71 7667 target_terminal::inferior ();
c8e38a49 7668
f5c4fcd9
TT
7669 strcpy (buf, rs->last_sent_step ? "s" : "c");
7670 putpkt (buf);
c8e38a49 7671 break;
43ff13b4 7672 }
c8e38a49
PA
7673 /* else fallthrough */
7674 default:
7675 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 7676 break;
43ff13b4 7677 }
c8e38a49 7678
f2faf941
PA
7679 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7680 return minus_one_ptid;
7681 else if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
7682 {
7683 /* Nothing interesting happened. If we're doing a non-blocking
7684 poll, we're done. Otherwise, go back to waiting. */
7685 if (options & TARGET_WNOHANG)
7686 return minus_one_ptid;
7687 else
7688 goto again;
7689 }
74531fed
PA
7690 else if (status->kind != TARGET_WAITKIND_EXITED
7691 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
7692 {
7693 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 7694 record_currthread (rs, event_ptid);
82f73884
PA
7695 else
7696 event_ptid = inferior_ptid;
43ff13b4 7697 }
74531fed
PA
7698 else
7699 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 7700 record_currthread (rs, minus_one_ptid);
79d7f229 7701
82f73884 7702 return event_ptid;
43ff13b4
JM
7703}
7704
74531fed
PA
7705/* Wait until the remote machine stops, then return, storing status in
7706 STATUS just as `wait' would. */
7707
f6ac5f3d
PA
7708ptid_t
7709remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
7710{
7711 ptid_t event_ptid;
7712
6efcd9a8 7713 if (target_is_non_stop_p ())
47608cb1 7714 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 7715 else
47608cb1 7716 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 7717
d9d41e78 7718 if (target_is_async_p ())
c8e38a49 7719 {
74531fed
PA
7720 /* If there are are events left in the queue tell the event loop
7721 to return here. */
722247f1 7722 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 7723 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 7724 }
c8e38a49
PA
7725
7726 return event_ptid;
7727}
7728
74ca34ce 7729/* Fetch a single register using a 'p' packet. */
c906108c 7730
b96ec7ac 7731static int
56be3814 7732fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac 7733{
ac7936df 7734 struct gdbarch *gdbarch = regcache->arch ();
b96ec7ac 7735 struct remote_state *rs = get_remote_state ();
2e9f7625 7736 char *buf, *p;
9890e433 7737 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
b96ec7ac
AC
7738 int i;
7739
4082afcc 7740 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
7741 return 0;
7742
7743 if (reg->pnum == -1)
7744 return 0;
7745
2e9f7625 7746 p = rs->buf;
fcad0fa4 7747 *p++ = 'p';
74ca34ce 7748 p += hexnumstr (p, reg->pnum);
fcad0fa4 7749 *p++ = '\0';
1f4437a4
MS
7750 putpkt (rs->buf);
7751 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 7752
2e9f7625
DJ
7753 buf = rs->buf;
7754
74ca34ce
DJ
7755 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7756 {
7757 case PACKET_OK:
7758 break;
7759 case PACKET_UNKNOWN:
7760 return 0;
7761 case PACKET_ERROR:
27a9c0bf 7762 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
ac7936df 7763 gdbarch_register_name (regcache->arch (),
27a9c0bf
MS
7764 reg->regnum),
7765 buf);
74ca34ce 7766 }
3f9a994c
JB
7767
7768 /* If this register is unfetchable, tell the regcache. */
7769 if (buf[0] == 'x')
8480adf2 7770 {
56be3814 7771 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 7772 return 1;
b96ec7ac 7773 }
b96ec7ac 7774
3f9a994c
JB
7775 /* Otherwise, parse and supply the value. */
7776 p = buf;
7777 i = 0;
7778 while (p[0] != 0)
7779 {
7780 if (p[1] == 0)
74ca34ce 7781 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
7782
7783 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7784 p += 2;
7785 }
56be3814 7786 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 7787 return 1;
b96ec7ac
AC
7788}
7789
74ca34ce
DJ
7790/* Fetch the registers included in the target's 'g' packet. */
7791
29709017
DJ
7792static int
7793send_g_packet (void)
c906108c 7794{
d01949b6 7795 struct remote_state *rs = get_remote_state ();
cea39f65 7796 int buf_len;
c906108c 7797
bba74b36 7798 xsnprintf (rs->buf, get_remote_packet_size (), "g");
b75abf5b
AK
7799 putpkt (rs->buf);
7800 getpkt (&rs->buf, &rs->buf_size, 0);
7801 if (packet_check_result (rs->buf) == PACKET_ERROR)
7802 error (_("Could not read registers; remote failure reply '%s'"),
7803 rs->buf);
c906108c 7804
29709017
DJ
7805 /* We can get out of synch in various cases. If the first character
7806 in the buffer is not a hex character, assume that has happened
7807 and try to fetch another packet to read. */
7808 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7809 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7810 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7811 && rs->buf[0] != 'x') /* New: unavailable register value. */
7812 {
7813 if (remote_debug)
7814 fprintf_unfiltered (gdb_stdlog,
7815 "Bad register packet; fetching a new packet\n");
7816 getpkt (&rs->buf, &rs->buf_size, 0);
7817 }
7818
74ca34ce
DJ
7819 buf_len = strlen (rs->buf);
7820
7821 /* Sanity check the received packet. */
7822 if (buf_len % 2 != 0)
7823 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
7824
7825 return buf_len / 2;
7826}
7827
7828static void
56be3814 7829process_g_packet (struct regcache *regcache)
29709017 7830{
ac7936df 7831 struct gdbarch *gdbarch = regcache->arch ();
29709017 7832 struct remote_state *rs = get_remote_state ();
5cd63fda 7833 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
29709017
DJ
7834 int i, buf_len;
7835 char *p;
7836 char *regs;
7837
7838 buf_len = strlen (rs->buf);
7839
7840 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce 7841 if (buf_len > 2 * rsa->sizeof_g_packet)
fc809827
SM
7842 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
7843 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
74ca34ce
DJ
7844
7845 /* Save the size of the packet sent to us by the target. It is used
7846 as a heuristic when determining the max size of packets that the
7847 target can safely receive. */
7848 if (rsa->actual_register_packet_size == 0)
7849 rsa->actual_register_packet_size = buf_len;
7850
7851 /* If this is smaller than we guessed the 'g' packet would be,
7852 update our records. A 'g' reply that doesn't include a register's
7853 value implies either that the register is not available, or that
7854 the 'p' packet must be used. */
7855 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 7856 {
9dc193c3 7857 long sizeof_g_packet = buf_len / 2;
74ca34ce 7858
4a22f64d 7859 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 7860 {
9dc193c3
LF
7861 long offset = rsa->regs[i].offset;
7862 long reg_size = register_size (gdbarch, i);
7863
74ca34ce
DJ
7864 if (rsa->regs[i].pnum == -1)
7865 continue;
7866
9dc193c3 7867 if (offset >= sizeof_g_packet)
74ca34ce 7868 rsa->regs[i].in_g_packet = 0;
9dc193c3
LF
7869 else if (offset + reg_size > sizeof_g_packet)
7870 error (_("Truncated register %d in remote 'g' packet"), i);
b96ec7ac 7871 else
74ca34ce 7872 rsa->regs[i].in_g_packet = 1;
b96ec7ac 7873 }
9dc193c3
LF
7874
7875 /* Looks valid enough, we can assume this is the correct length
7876 for a 'g' packet. It's important not to adjust
7877 rsa->sizeof_g_packet if we have truncated registers otherwise
7878 this "if" won't be run the next time the method is called
7879 with a packet of the same size and one of the internal errors
7880 below will trigger instead. */
7881 rsa->sizeof_g_packet = sizeof_g_packet;
74ca34ce 7882 }
b323314b 7883
224c3ddb 7884 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
7885
7886 /* Unimplemented registers read as all bits zero. */
ea9c271d 7887 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 7888
c906108c
SS
7889 /* Reply describes registers byte by byte, each byte encoded as two
7890 hex characters. Suck them all up, then supply them to the
7891 register cacheing/storage mechanism. */
7892
74ca34ce 7893 p = rs->buf;
ea9c271d 7894 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 7895 {
74ca34ce
DJ
7896 if (p[0] == 0 || p[1] == 0)
7897 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7898 internal_error (__FILE__, __LINE__,
9b20d036 7899 _("unexpected end of 'g' packet reply"));
74ca34ce 7900
c906108c 7901 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 7902 regs[i] = 0; /* 'x' */
c906108c
SS
7903 else
7904 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7905 p += 2;
7906 }
7907
a744cf53
MS
7908 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7909 {
7910 struct packet_reg *r = &rsa->regs[i];
9dc193c3 7911 long reg_size = register_size (gdbarch, i);
a744cf53
MS
7912
7913 if (r->in_g_packet)
7914 {
9dc193c3 7915 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
a744cf53
MS
7916 /* This shouldn't happen - we adjusted in_g_packet above. */
7917 internal_error (__FILE__, __LINE__,
9b20d036 7918 _("unexpected end of 'g' packet reply"));
a744cf53
MS
7919 else if (rs->buf[r->offset * 2] == 'x')
7920 {
7921 gdb_assert (r->offset * 2 < strlen (rs->buf));
7922 /* The register isn't available, mark it as such (at
7923 the same time setting the value to zero). */
7924 regcache_raw_supply (regcache, r->regnum, NULL);
7925 }
7926 else
7927 regcache_raw_supply (regcache, r->regnum,
7928 regs + r->offset);
7929 }
7930 }
c906108c
SS
7931}
7932
29709017 7933static void
56be3814 7934fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
7935{
7936 send_g_packet ();
56be3814 7937 process_g_packet (regcache);
29709017
DJ
7938}
7939
e6e4e701
PA
7940/* Make the remote selected traceframe match GDB's selected
7941 traceframe. */
7942
7943static void
7944set_remote_traceframe (void)
7945{
7946 int newnum;
262e1174 7947 struct remote_state *rs = get_remote_state ();
e6e4e701 7948
262e1174 7949 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
7950 return;
7951
7952 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 7953 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
7954
7955 newnum = target_trace_find (tfind_number,
7956 get_traceframe_number (), 0, 0, NULL);
7957
7958 /* Should not happen. If it does, all bets are off. */
7959 if (newnum != get_traceframe_number ())
7960 warning (_("could not set remote traceframe"));
7961}
7962
f6ac5f3d
PA
7963void
7964remote_target::fetch_registers (struct regcache *regcache, int regnum)
74ca34ce 7965{
ac7936df 7966 struct gdbarch *gdbarch = regcache->arch ();
5cd63fda 7967 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
74ca34ce
DJ
7968 int i;
7969
e6e4e701 7970 set_remote_traceframe ();
bcc0c096 7971 set_general_thread (regcache_get_ptid (regcache));
74ca34ce
DJ
7972
7973 if (regnum >= 0)
7974 {
5cd63fda 7975 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 7976
74ca34ce
DJ
7977 gdb_assert (reg != NULL);
7978
7979 /* If this register might be in the 'g' packet, try that first -
7980 we are likely to read more than one register. If this is the
7981 first 'g' packet, we might be overly optimistic about its
7982 contents, so fall back to 'p'. */
7983 if (reg->in_g_packet)
7984 {
56be3814 7985 fetch_registers_using_g (regcache);
74ca34ce
DJ
7986 if (reg->in_g_packet)
7987 return;
7988 }
7989
56be3814 7990 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
7991 return;
7992
7993 /* This register is not available. */
56be3814 7994 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
7995
7996 return;
7997 }
7998
56be3814 7999 fetch_registers_using_g (regcache);
74ca34ce 8000
5cd63fda 8001 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8002 if (!rsa->regs[i].in_g_packet)
56be3814 8003 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
8004 {
8005 /* This register is not available. */
56be3814 8006 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
8007 }
8008}
8009
c906108c
SS
8010/* Prepare to store registers. Since we may send them all (using a
8011 'G' request), we have to read out the ones we don't want to change
8012 first. */
8013
f6ac5f3d
PA
8014void
8015remote_target::prepare_to_store (struct regcache *regcache)
c906108c 8016{
5cd63fda 8017 remote_arch_state *rsa = get_remote_arch_state (regcache->arch ());
cf0e1e0d 8018 int i;
cf0e1e0d 8019
c906108c 8020 /* Make sure the entire registers array is valid. */
4082afcc 8021 switch (packet_support (PACKET_P))
5a2468f5
JM
8022 {
8023 case PACKET_DISABLE:
8024 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 8025 /* Make sure all the necessary registers are cached. */
ac7936df 8026 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
ea9c271d 8027 if (rsa->regs[i].in_g_packet)
8e368124 8028 regcache_raw_update (regcache, rsa->regs[i].regnum);
5a2468f5
JM
8029 break;
8030 case PACKET_ENABLE:
8031 break;
8032 }
8033}
8034
ad10f812 8035/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 8036 packet was not recognized. */
5a2468f5
JM
8037
8038static int
1f4437a4
MS
8039store_register_using_P (const struct regcache *regcache,
8040 struct packet_reg *reg)
5a2468f5 8041{
ac7936df 8042 struct gdbarch *gdbarch = regcache->arch ();
d01949b6 8043 struct remote_state *rs = get_remote_state ();
5a2468f5 8044 /* Try storing a single register. */
6d820c5c 8045 char *buf = rs->buf;
9890e433 8046 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
5a2468f5 8047 char *p;
5a2468f5 8048
4082afcc 8049 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
8050 return 0;
8051
8052 if (reg->pnum == -1)
8053 return 0;
8054
ea9c271d 8055 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 8056 p = buf + strlen (buf);
56be3814 8057 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 8058 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
8059 putpkt (rs->buf);
8060 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 8061
74ca34ce
DJ
8062 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8063 {
8064 case PACKET_OK:
8065 return 1;
8066 case PACKET_ERROR:
27a9c0bf
MS
8067 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8068 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
8069 case PACKET_UNKNOWN:
8070 return 0;
8071 default:
8072 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8073 }
c906108c
SS
8074}
8075
23860348
MS
8076/* Store register REGNUM, or all registers if REGNUM == -1, from the
8077 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
8078
8079static void
56be3814 8080store_registers_using_G (const struct regcache *regcache)
c906108c 8081{
d01949b6 8082 struct remote_state *rs = get_remote_state ();
5cd63fda 8083 remote_arch_state *rsa = get_remote_arch_state (regcache->arch ());
cfd77fa1 8084 gdb_byte *regs;
c906108c
SS
8085 char *p;
8086
193cb69f
AC
8087 /* Extract all the registers in the regcache copying them into a
8088 local buffer. */
8089 {
b323314b 8090 int i;
a744cf53 8091
224c3ddb 8092 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 8093 memset (regs, 0, rsa->sizeof_g_packet);
ac7936df 8094 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
193cb69f 8095 {
ea9c271d 8096 struct packet_reg *r = &rsa->regs[i];
a744cf53 8097
b323314b 8098 if (r->in_g_packet)
56be3814 8099 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
8100 }
8101 }
c906108c
SS
8102
8103 /* Command describes registers byte by byte,
8104 each byte encoded as two hex characters. */
6d820c5c 8105 p = rs->buf;
193cb69f 8106 *p++ = 'G';
74ca34ce 8107 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
8108 putpkt (rs->buf);
8109 getpkt (&rs->buf, &rs->buf_size, 0);
8110 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
8111 error (_("Could not write registers; remote failure reply '%s'"),
8112 rs->buf);
c906108c 8113}
74ca34ce
DJ
8114
8115/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8116 of the register cache buffer. FIXME: ignores errors. */
8117
f6ac5f3d
PA
8118void
8119remote_target::store_registers (struct regcache *regcache, int regnum)
74ca34ce 8120{
5cd63fda
PA
8121 struct gdbarch *gdbarch = regcache->arch ();
8122 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
74ca34ce
DJ
8123 int i;
8124
e6e4e701 8125 set_remote_traceframe ();
bcc0c096 8126 set_general_thread (regcache_get_ptid (regcache));
74ca34ce
DJ
8127
8128 if (regnum >= 0)
8129 {
5cd63fda 8130 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8131
74ca34ce
DJ
8132 gdb_assert (reg != NULL);
8133
8134 /* Always prefer to store registers using the 'P' packet if
8135 possible; we often change only a small number of registers.
8136 Sometimes we change a larger number; we'd need help from a
8137 higher layer to know to use 'G'. */
56be3814 8138 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
8139 return;
8140
8141 /* For now, don't complain if we have no way to write the
8142 register. GDB loses track of unavailable registers too
8143 easily. Some day, this may be an error. We don't have
0df8b418 8144 any way to read the register, either... */
74ca34ce
DJ
8145 if (!reg->in_g_packet)
8146 return;
8147
56be3814 8148 store_registers_using_G (regcache);
74ca34ce
DJ
8149 return;
8150 }
8151
56be3814 8152 store_registers_using_G (regcache);
74ca34ce 8153
5cd63fda 8154 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8155 if (!rsa->regs[i].in_g_packet)
56be3814 8156 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
8157 /* See above for why we do not issue an error here. */
8158 continue;
8159}
c906108c
SS
8160\f
8161
8162/* Return the number of hex digits in num. */
8163
8164static int
fba45db2 8165hexnumlen (ULONGEST num)
c906108c
SS
8166{
8167 int i;
8168
8169 for (i = 0; num != 0; i++)
8170 num >>= 4;
8171
325fac50 8172 return std::max (i, 1);
c906108c
SS
8173}
8174
2df3850c 8175/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
8176
8177static int
fba45db2 8178hexnumstr (char *buf, ULONGEST num)
c906108c 8179{
c906108c 8180 int len = hexnumlen (num);
a744cf53 8181
2df3850c
JM
8182 return hexnumnstr (buf, num, len);
8183}
8184
c906108c 8185
2df3850c 8186/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 8187
2df3850c 8188static int
fba45db2 8189hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
8190{
8191 int i;
8192
8193 buf[width] = '\0';
8194
8195 for (i = width - 1; i >= 0; i--)
c906108c 8196 {
c5aa993b 8197 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
8198 num >>= 4;
8199 }
8200
2df3850c 8201 return width;
c906108c
SS
8202}
8203
23860348 8204/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
8205
8206static CORE_ADDR
fba45db2 8207remote_address_masked (CORE_ADDR addr)
c906108c 8208{
883b9c6c 8209 unsigned int address_size = remote_address_size;
a744cf53 8210
911c95a5
UW
8211 /* If "remoteaddresssize" was not set, default to target address size. */
8212 if (!address_size)
f5656ead 8213 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
8214
8215 if (address_size > 0
8216 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
8217 {
8218 /* Only create a mask when that mask can safely be constructed
23860348 8219 in a ULONGEST variable. */
c906108c 8220 ULONGEST mask = 1;
a744cf53 8221
911c95a5 8222 mask = (mask << address_size) - 1;
c906108c
SS
8223 addr &= mask;
8224 }
8225 return addr;
8226}
8227
8228/* Determine whether the remote target supports binary downloading.
8229 This is accomplished by sending a no-op memory write of zero length
8230 to the target at the specified address. It does not suffice to send
23860348
MS
8231 the whole packet, since many stubs strip the eighth bit and
8232 subsequently compute a wrong checksum, which causes real havoc with
8233 remote_write_bytes.
7a292a7a 8234
96baa820 8235 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 8236 clean. In cases like this, the user should clear "remote
23860348 8237 X-packet". */
96baa820 8238
c906108c 8239static void
fba45db2 8240check_binary_download (CORE_ADDR addr)
c906108c 8241{
d01949b6 8242 struct remote_state *rs = get_remote_state ();
24b06219 8243
4082afcc 8244 switch (packet_support (PACKET_X))
c906108c 8245 {
96baa820
JM
8246 case PACKET_DISABLE:
8247 break;
8248 case PACKET_ENABLE:
8249 break;
8250 case PACKET_SUPPORT_UNKNOWN:
8251 {
96baa820 8252 char *p;
802188a7 8253
2e9f7625 8254 p = rs->buf;
96baa820
JM
8255 *p++ = 'X';
8256 p += hexnumstr (p, (ULONGEST) addr);
8257 *p++ = ',';
8258 p += hexnumstr (p, (ULONGEST) 0);
8259 *p++ = ':';
8260 *p = '\0';
802188a7 8261
2e9f7625 8262 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 8263 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 8264
2e9f7625 8265 if (rs->buf[0] == '\0')
96baa820
JM
8266 {
8267 if (remote_debug)
8268 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8269 "binary downloading NOT "
8270 "supported by target\n");
444abaca 8271 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
8272 }
8273 else
8274 {
8275 if (remote_debug)
8276 fprintf_unfiltered (gdb_stdlog,
64b9b334 8277 "binary downloading supported by target\n");
444abaca 8278 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
8279 }
8280 break;
8281 }
c906108c
SS
8282 }
8283}
8284
124e13d9
SM
8285/* Helper function to resize the payload in order to try to get a good
8286 alignment. We try to write an amount of data such that the next write will
8287 start on an address aligned on REMOTE_ALIGN_WRITES. */
8288
8289static int
8290align_for_efficient_write (int todo, CORE_ADDR memaddr)
8291{
8292 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8293}
8294
c906108c
SS
8295/* Write memory data directly to the remote machine.
8296 This does not inform the data cache; the data cache uses this.
a76d924d 8297 HEADER is the starting part of the packet.
c906108c
SS
8298 MEMADDR is the address in the remote memory space.
8299 MYADDR is the address of the buffer in our space.
124e13d9
SM
8300 LEN_UNITS is the number of addressable units to write.
8301 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
8302 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8303 should send data as binary ('X'), or hex-encoded ('M').
8304
8305 The function creates packet of the form
8306 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8307
124e13d9 8308 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
8309
8310 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8311 are omitted.
8312
9b409511 8313 Return the transferred status, error or OK (an
124e13d9
SM
8314 'enum target_xfer_status' value). Save the number of addressable units
8315 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8316
8317 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8318 exchange between gdb and the stub could look like (?? in place of the
8319 checksum):
8320
8321 -> $m1000,4#??
8322 <- aaaabbbbccccdddd
8323
8324 -> $M1000,3:eeeeffffeeee#??
8325 <- OK
8326
8327 -> $m1000,4#??
8328 <- eeeeffffeeeedddd */
c906108c 8329
9b409511 8330static enum target_xfer_status
a76d924d 8331remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
124e13d9
SM
8332 const gdb_byte *myaddr, ULONGEST len_units,
8333 int unit_size, ULONGEST *xfered_len_units,
8334 char packet_format, int use_length)
c906108c 8335{
6d820c5c 8336 struct remote_state *rs = get_remote_state ();
cfd77fa1 8337 char *p;
a76d924d
DJ
8338 char *plen = NULL;
8339 int plenlen = 0;
124e13d9
SM
8340 int todo_units;
8341 int units_written;
8342 int payload_capacity_bytes;
8343 int payload_length_bytes;
a76d924d
DJ
8344
8345 if (packet_format != 'X' && packet_format != 'M')
8346 internal_error (__FILE__, __LINE__,
9b20d036 8347 _("remote_write_bytes_aux: bad packet format"));
c906108c 8348
124e13d9 8349 if (len_units == 0)
9b409511 8350 return TARGET_XFER_EOF;
b2182ed2 8351
124e13d9 8352 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 8353
6d820c5c
DJ
8354 /* The packet buffer will be large enough for the payload;
8355 get_memory_packet_size ensures this. */
a76d924d 8356 rs->buf[0] = '\0';
c906108c 8357
a257b5bb 8358 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
8359 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8360
124e13d9 8361 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 8362 if (!use_length)
0df8b418 8363 /* The comma won't be used. */
124e13d9
SM
8364 payload_capacity_bytes += 1;
8365 payload_capacity_bytes -= strlen (header);
8366 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 8367
a76d924d 8368 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 8369
a76d924d
DJ
8370 strcat (rs->buf, header);
8371 p = rs->buf + strlen (header);
8372
8373 /* Compute a best guess of the number of bytes actually transfered. */
8374 if (packet_format == 'X')
c906108c 8375 {
23860348 8376 /* Best guess at number of bytes that will fit. */
325fac50
PA
8377 todo_units = std::min (len_units,
8378 (ULONGEST) payload_capacity_bytes / unit_size);
a76d924d 8379 if (use_length)
124e13d9 8380 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50 8381 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
8382 }
8383 else
8384 {
124e13d9 8385 /* Number of bytes that will fit. */
325fac50
PA
8386 todo_units
8387 = std::min (len_units,
8388 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
a76d924d 8389 if (use_length)
124e13d9 8390 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50
PA
8391 todo_units = std::min (todo_units,
8392 (payload_capacity_bytes / unit_size) / 2);
917317f4 8393 }
a76d924d 8394
124e13d9 8395 if (todo_units <= 0)
3de11b2e 8396 internal_error (__FILE__, __LINE__,
405f8e94 8397 _("minimum packet size too small to write data"));
802188a7 8398
6765f3e5
DJ
8399 /* If we already need another packet, then try to align the end
8400 of this packet to a useful boundary. */
124e13d9
SM
8401 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8402 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 8403
a257b5bb 8404 /* Append "<memaddr>". */
917317f4
JM
8405 memaddr = remote_address_masked (memaddr);
8406 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 8407
a76d924d
DJ
8408 if (use_length)
8409 {
8410 /* Append ",". */
8411 *p++ = ',';
802188a7 8412
124e13d9
SM
8413 /* Append the length and retain its location and size. It may need to be
8414 adjusted once the packet body has been created. */
a76d924d 8415 plen = p;
124e13d9 8416 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
8417 p += plenlen;
8418 }
a257b5bb
AC
8419
8420 /* Append ":". */
917317f4
JM
8421 *p++ = ':';
8422 *p = '\0';
802188a7 8423
a257b5bb 8424 /* Append the packet body. */
a76d924d 8425 if (packet_format == 'X')
917317f4 8426 {
917317f4
JM
8427 /* Binary mode. Send target system values byte by byte, in
8428 increasing byte addresses. Only escape certain critical
8429 characters. */
124e13d9
SM
8430 payload_length_bytes =
8431 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8432 &units_written, payload_capacity_bytes);
6765f3e5 8433
124e13d9 8434 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
8435 a second try to keep the end of the packet aligned. Don't do
8436 this if the packet is tiny. */
124e13d9 8437 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 8438 {
124e13d9
SM
8439 int new_todo_units;
8440
8441 new_todo_units = align_for_efficient_write (units_written, memaddr);
8442
8443 if (new_todo_units != units_written)
8444 payload_length_bytes =
8445 remote_escape_output (myaddr, new_todo_units, unit_size,
8446 (gdb_byte *) p, &units_written,
8447 payload_capacity_bytes);
6765f3e5
DJ
8448 }
8449
124e13d9
SM
8450 p += payload_length_bytes;
8451 if (use_length && units_written < todo_units)
c906108c 8452 {
802188a7 8453 /* Escape chars have filled up the buffer prematurely,
124e13d9 8454 and we have actually sent fewer units than planned.
917317f4
JM
8455 Fix-up the length field of the packet. Use the same
8456 number of characters as before. */
124e13d9
SM
8457 plen += hexnumnstr (plen, (ULONGEST) units_written,
8458 plenlen);
917317f4 8459 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 8460 }
a76d924d
DJ
8461 }
8462 else
8463 {
917317f4
JM
8464 /* Normal mode: Send target system values byte by byte, in
8465 increasing byte addresses. Each byte is encoded as a two hex
8466 value. */
124e13d9
SM
8467 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8468 units_written = todo_units;
c906108c 8469 }
802188a7 8470
2e9f7625 8471 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 8472 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 8473
2e9f7625 8474 if (rs->buf[0] == 'E')
00d84524 8475 return TARGET_XFER_E_IO;
802188a7 8476
124e13d9
SM
8477 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8478 send fewer units than we'd planned. */
8479 *xfered_len_units = (ULONGEST) units_written;
92ffd475 8480 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
8481}
8482
a76d924d
DJ
8483/* Write memory data directly to the remote machine.
8484 This does not inform the data cache; the data cache uses this.
8485 MEMADDR is the address in the remote memory space.
8486 MYADDR is the address of the buffer in our space.
8487 LEN is the number of bytes.
8488
9b409511
YQ
8489 Return the transferred status, error or OK (an
8490 'enum target_xfer_status' value). Save the number of bytes
8491 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 8492
9b409511
YQ
8493static enum target_xfer_status
8494remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
124e13d9 8495 int unit_size, ULONGEST *xfered_len)
a76d924d 8496{
a121b7c1 8497 const char *packet_format = NULL;
a76d924d
DJ
8498
8499 /* Check whether the target supports binary download. */
8500 check_binary_download (memaddr);
8501
4082afcc 8502 switch (packet_support (PACKET_X))
a76d924d
DJ
8503 {
8504 case PACKET_ENABLE:
8505 packet_format = "X";
8506 break;
8507 case PACKET_DISABLE:
8508 packet_format = "M";
8509 break;
8510 case PACKET_SUPPORT_UNKNOWN:
8511 internal_error (__FILE__, __LINE__,
8512 _("remote_write_bytes: bad internal state"));
8513 default:
8514 internal_error (__FILE__, __LINE__, _("bad switch"));
8515 }
8516
8517 return remote_write_bytes_aux (packet_format,
124e13d9 8518 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 8519 packet_format[0], 1);
a76d924d
DJ
8520}
8521
9217e74e
YQ
8522/* Read memory data directly from the remote machine.
8523 This does not use the data cache; the data cache uses this.
8524 MEMADDR is the address in the remote memory space.
8525 MYADDR is the address of the buffer in our space.
124e13d9
SM
8526 LEN_UNITS is the number of addressable memory units to read..
8527 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
8528
8529 Return the transferred status, error or OK (an
8530 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
8531 transferred in *XFERED_LEN_UNITS.
8532
8533 See the comment of remote_write_bytes_aux for an example of
8534 memory read/write exchange between gdb and the stub. */
9217e74e
YQ
8535
8536static enum target_xfer_status
124e13d9
SM
8537remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
8538 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
8539{
8540 struct remote_state *rs = get_remote_state ();
124e13d9 8541 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 8542 char *p;
124e13d9
SM
8543 int todo_units;
8544 int decoded_bytes;
9217e74e 8545
124e13d9 8546 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
8547 /* The packet buffer will be large enough for the payload;
8548 get_memory_packet_size ensures this. */
8549
124e13d9 8550 /* Number of units that will fit. */
325fac50
PA
8551 todo_units = std::min (len_units,
8552 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
8553
8554 /* Construct "m"<memaddr>","<len>". */
8555 memaddr = remote_address_masked (memaddr);
8556 p = rs->buf;
8557 *p++ = 'm';
8558 p += hexnumstr (p, (ULONGEST) memaddr);
8559 *p++ = ',';
124e13d9 8560 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
8561 *p = '\0';
8562 putpkt (rs->buf);
8563 getpkt (&rs->buf, &rs->buf_size, 0);
8564 if (rs->buf[0] == 'E'
8565 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8566 && rs->buf[3] == '\0')
8567 return TARGET_XFER_E_IO;
8568 /* Reply describes memory byte by byte, each byte encoded as two hex
8569 characters. */
8570 p = rs->buf;
124e13d9 8571 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 8572 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 8573 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
92ffd475 8574 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9217e74e
YQ
8575}
8576
b55fbac4
YQ
8577/* Using the set of read-only target sections of remote, read live
8578 read-only memory.
8acf9577
YQ
8579
8580 For interface/parameters/return description see target.h,
8581 to_xfer_partial. */
8582
8583static enum target_xfer_status
b55fbac4
YQ
8584remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
8585 ULONGEST memaddr, ULONGEST len,
124e13d9 8586 int unit_size, ULONGEST *xfered_len)
8acf9577
YQ
8587{
8588 struct target_section *secp;
8589 struct target_section_table *table;
8590
8591 secp = target_section_by_addr (ops, memaddr);
8592 if (secp != NULL
8593 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8594 secp->the_bfd_section)
8595 & SEC_READONLY))
8596 {
8597 struct target_section *p;
8598 ULONGEST memend = memaddr + len;
8599
8600 table = target_get_section_table (ops);
8601
8602 for (p = table->sections; p < table->sections_end; p++)
8603 {
8604 if (memaddr >= p->addr)
8605 {
8606 if (memend <= p->endaddr)
8607 {
8608 /* Entire transfer is within this section. */
124e13d9 8609 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8610 xfered_len);
8acf9577
YQ
8611 }
8612 else if (memaddr >= p->endaddr)
8613 {
8614 /* This section ends before the transfer starts. */
8615 continue;
8616 }
8617 else
8618 {
8619 /* This section overlaps the transfer. Just do half. */
8620 len = p->endaddr - memaddr;
124e13d9 8621 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8622 xfered_len);
8acf9577
YQ
8623 }
8624 }
8625 }
8626 }
8627
8628 return TARGET_XFER_EOF;
8629}
8630
9217e74e
YQ
8631/* Similar to remote_read_bytes_1, but it reads from the remote stub
8632 first if the requested memory is unavailable in traceframe.
8633 Otherwise, fall back to remote_read_bytes_1. */
c906108c 8634
9b409511 8635static enum target_xfer_status
8acf9577 8636remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
124e13d9
SM
8637 gdb_byte *myaddr, ULONGEST len, int unit_size,
8638 ULONGEST *xfered_len)
c906108c 8639{
6b6aa828 8640 if (len == 0)
96c4f946 8641 return TARGET_XFER_EOF;
b2182ed2 8642
8acf9577
YQ
8643 if (get_traceframe_number () != -1)
8644 {
a79b1bc6 8645 std::vector<mem_range> available;
8acf9577
YQ
8646
8647 /* If we fail to get the set of available memory, then the
8648 target does not support querying traceframe info, and so we
8649 attempt reading from the traceframe anyway (assuming the
8650 target implements the old QTro packet then). */
8651 if (traceframe_available_memory (&available, memaddr, len))
8652 {
a79b1bc6 8653 if (available.empty () || available[0].start != memaddr)
8acf9577
YQ
8654 {
8655 enum target_xfer_status res;
8656
8657 /* Don't read into the traceframe's available
8658 memory. */
a79b1bc6 8659 if (!available.empty ())
8acf9577
YQ
8660 {
8661 LONGEST oldlen = len;
8662
a79b1bc6 8663 len = available[0].start - memaddr;
8acf9577
YQ
8664 gdb_assert (len <= oldlen);
8665 }
8666
8acf9577 8667 /* This goes through the topmost target again. */
b55fbac4 8668 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
124e13d9 8669 len, unit_size, xfered_len);
8acf9577
YQ
8670 if (res == TARGET_XFER_OK)
8671 return TARGET_XFER_OK;
8672 else
8673 {
8674 /* No use trying further, we know some memory starting
8675 at MEMADDR isn't available. */
8676 *xfered_len = len;
92ffd475
PC
8677 return (*xfered_len != 0) ?
8678 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8acf9577
YQ
8679 }
8680 }
8681
8682 /* Don't try to read more than how much is available, in
8683 case the target implements the deprecated QTro packet to
8684 cater for older GDBs (the target's knowledge of read-only
8685 sections may be outdated by now). */
a79b1bc6 8686 len = available[0].length;
8acf9577
YQ
8687 }
8688 }
8689
124e13d9 8690 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 8691}
74531fed 8692
c906108c 8693\f
c906108c 8694
a76d924d
DJ
8695/* Sends a packet with content determined by the printf format string
8696 FORMAT and the remaining arguments, then gets the reply. Returns
8697 whether the packet was a success, a failure, or unknown. */
8698
77b64a49
PA
8699static enum packet_result remote_send_printf (const char *format, ...)
8700 ATTRIBUTE_PRINTF (1, 2);
8701
2c0b251b 8702static enum packet_result
a76d924d
DJ
8703remote_send_printf (const char *format, ...)
8704{
8705 struct remote_state *rs = get_remote_state ();
8706 int max_size = get_remote_packet_size ();
a76d924d 8707 va_list ap;
a744cf53 8708
a76d924d
DJ
8709 va_start (ap, format);
8710
8711 rs->buf[0] = '\0';
8712 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 8713 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
8714
8715 if (putpkt (rs->buf) < 0)
8716 error (_("Communication problem with target."));
8717
8718 rs->buf[0] = '\0';
8719 getpkt (&rs->buf, &rs->buf_size, 0);
8720
8721 return packet_check_result (rs->buf);
8722}
8723
a76d924d
DJ
8724/* Flash writing can take quite some time. We'll set
8725 effectively infinite timeout for flash operations.
8726 In future, we'll need to decide on a better approach. */
8727static const int remote_flash_timeout = 1000;
8728
f6ac5f3d
PA
8729void
8730remote_target::flash_erase (ULONGEST address, LONGEST length)
a76d924d 8731{
f5656ead 8732 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d 8733 enum packet_result ret;
2ec845e7
TT
8734 scoped_restore restore_timeout
8735 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
a76d924d
DJ
8736
8737 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 8738 phex (address, addr_size),
a76d924d
DJ
8739 phex (length, 4));
8740 switch (ret)
8741 {
8742 case PACKET_UNKNOWN:
8743 error (_("Remote target does not support flash erase"));
8744 case PACKET_ERROR:
8745 error (_("Error erasing flash with vFlashErase packet"));
8746 default:
8747 break;
8748 }
a76d924d
DJ
8749}
8750
9b409511
YQ
8751static enum target_xfer_status
8752remote_flash_write (struct target_ops *ops, ULONGEST address,
8753 ULONGEST length, ULONGEST *xfered_len,
8754 const gdb_byte *data)
a76d924d 8755{
2ec845e7
TT
8756 scoped_restore restore_timeout
8757 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8758 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8759 xfered_len,'X', 0);
a76d924d
DJ
8760}
8761
f6ac5f3d
PA
8762void
8763remote_target::flash_done ()
a76d924d 8764{
a76d924d 8765 int ret;
a76d924d 8766
2ec845e7
TT
8767 scoped_restore restore_timeout
8768 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8769
a76d924d 8770 ret = remote_send_printf ("vFlashDone");
a76d924d
DJ
8771
8772 switch (ret)
8773 {
8774 case PACKET_UNKNOWN:
8775 error (_("Remote target does not support vFlashDone"));
8776 case PACKET_ERROR:
8777 error (_("Error finishing flash operation"));
8778 default:
8779 break;
8780 }
8781}
8782
f6ac5f3d
PA
8783void
8784remote_target::files_info ()
c906108c
SS
8785{
8786 puts_filtered ("Debugging a target over a serial line.\n");
8787}
8788\f
8789/* Stuff for dealing with the packets which are part of this protocol.
8790 See comment at top of file for details. */
8791
1927e618
PA
8792/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8793 error to higher layers. Called when a serial error is detected.
8794 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
8795 the system error message for errno at function entry and final dot
8796 for output compatibility with throw_perror_with_name. */
1927e618
PA
8797
8798static void
8799unpush_and_perror (const char *string)
8800{
d6cb50a2 8801 int saved_errno = errno;
1927e618
PA
8802
8803 remote_unpush_target ();
d6cb50a2
JK
8804 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8805 safe_strerror (saved_errno));
1927e618
PA
8806}
8807
048094ac
PA
8808/* Read a single character from the remote end. The current quit
8809 handler is overridden to avoid quitting in the middle of packet
8810 sequence, as that would break communication with the remote server.
8811 See remote_serial_quit_handler for more detail. */
c906108c
SS
8812
8813static int
fba45db2 8814readchar (int timeout)
c906108c
SS
8815{
8816 int ch;
5d93a237 8817 struct remote_state *rs = get_remote_state ();
048094ac 8818
2ec845e7
TT
8819 {
8820 scoped_restore restore_quit
8821 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
c906108c 8822
2ec845e7 8823 rs->got_ctrlc_during_io = 0;
c906108c 8824
2ec845e7 8825 ch = serial_readchar (rs->remote_desc, timeout);
048094ac 8826
2ec845e7
TT
8827 if (rs->got_ctrlc_during_io)
8828 set_quit_flag ();
8829 }
048094ac 8830
2acceee2 8831 if (ch >= 0)
0876f84a 8832 return ch;
2acceee2
JM
8833
8834 switch ((enum serial_rc) ch)
c906108c
SS
8835 {
8836 case SERIAL_EOF:
78a095c3 8837 remote_unpush_target ();
598d3636 8838 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 8839 /* no return */
c906108c 8840 case SERIAL_ERROR:
1927e618
PA
8841 unpush_and_perror (_("Remote communication error. "
8842 "Target disconnected."));
2acceee2 8843 /* no return */
c906108c 8844 case SERIAL_TIMEOUT:
2acceee2 8845 break;
c906108c 8846 }
2acceee2 8847 return ch;
c906108c
SS
8848}
8849
c33e31fd 8850/* Wrapper for serial_write that closes the target and throws if
048094ac
PA
8851 writing fails. The current quit handler is overridden to avoid
8852 quitting in the middle of packet sequence, as that would break
8853 communication with the remote server. See
8854 remote_serial_quit_handler for more detail. */
c33e31fd
PA
8855
8856static void
8857remote_serial_write (const char *str, int len)
8858{
5d93a237 8859 struct remote_state *rs = get_remote_state ();
048094ac 8860
2ec845e7
TT
8861 scoped_restore restore_quit
8862 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
048094ac
PA
8863
8864 rs->got_ctrlc_during_io = 0;
5d93a237
TT
8865
8866 if (serial_write (rs->remote_desc, str, len))
c33e31fd 8867 {
1927e618
PA
8868 unpush_and_perror (_("Remote communication error. "
8869 "Target disconnected."));
c33e31fd 8870 }
048094ac
PA
8871
8872 if (rs->got_ctrlc_during_io)
8873 set_quit_flag ();
c33e31fd
PA
8874}
8875
b3ced9ba
PA
8876/* Return a string representing an escaped version of BUF, of len N.
8877 E.g. \n is converted to \\n, \t to \\t, etc. */
6e5abd65 8878
b3ced9ba 8879static std::string
6e5abd65
PA
8880escape_buffer (const char *buf, int n)
8881{
d7e74731 8882 string_file stb;
6e5abd65 8883
d7e74731
PA
8884 stb.putstrn (buf, n, '\\');
8885 return std::move (stb.string ());
6e5abd65
PA
8886}
8887
c906108c
SS
8888/* Display a null-terminated packet on stdout, for debugging, using C
8889 string notation. */
8890
8891static void
baa336ce 8892print_packet (const char *buf)
c906108c
SS
8893{
8894 puts_filtered ("\"");
43e526b9 8895 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
8896 puts_filtered ("\"");
8897}
8898
8899int
baa336ce 8900putpkt (const char *buf)
c906108c
SS
8901{
8902 return putpkt_binary (buf, strlen (buf));
8903}
8904
8905/* Send a packet to the remote machine, with error checking. The data
23860348 8906 of the packet is in BUF. The string in BUF can be at most
ea9c271d 8907 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
8908 and for a possible /0 if we are debugging (remote_debug) and want
8909 to print the sent packet as a string. */
c906108c
SS
8910
8911static int
baa336ce 8912putpkt_binary (const char *buf, int cnt)
c906108c 8913{
2d717e4f 8914 struct remote_state *rs = get_remote_state ();
c906108c
SS
8915 int i;
8916 unsigned char csum = 0;
b80406ac
TT
8917 gdb::def_vector<char> data (cnt + 6);
8918 char *buf2 = data.data ();
085dd6e6 8919
c906108c
SS
8920 int ch;
8921 int tcount = 0;
8922 char *p;
8923
e24a49d8
PA
8924 /* Catch cases like trying to read memory or listing threads while
8925 we're waiting for a stop reply. The remote server wouldn't be
8926 ready to handle this request, so we'd hang and timeout. We don't
8927 have to worry about this in synchronous mode, because in that
8928 case it's not possible to issue a command while the target is
74531fed
PA
8929 running. This is not a problem in non-stop mode, because in that
8930 case, the stub is always ready to process serial input. */
6efcd9a8
PA
8931 if (!target_is_non_stop_p ()
8932 && target_is_async_p ()
8933 && rs->waiting_for_stop_reply)
9597b22a
DE
8934 {
8935 error (_("Cannot execute this command while the target is running.\n"
8936 "Use the \"interrupt\" command to stop the target\n"
8937 "and then try again."));
8938 }
e24a49d8 8939
2d717e4f
DJ
8940 /* We're sending out a new packet. Make sure we don't look at a
8941 stale cached response. */
8942 rs->cached_wait_status = 0;
8943
c906108c
SS
8944 /* Copy the packet into buffer BUF2, encapsulating it
8945 and giving it a checksum. */
8946
c906108c
SS
8947 p = buf2;
8948 *p++ = '$';
8949
8950 for (i = 0; i < cnt; i++)
8951 {
8952 csum += buf[i];
8953 *p++ = buf[i];
8954 }
8955 *p++ = '#';
8956 *p++ = tohex ((csum >> 4) & 0xf);
8957 *p++ = tohex (csum & 0xf);
8958
8959 /* Send it over and over until we get a positive ack. */
8960
8961 while (1)
8962 {
8963 int started_error_output = 0;
8964
8965 if (remote_debug)
8966 {
8967 *p = '\0';
b3ced9ba 8968
6f8976bf
YQ
8969 int len = (int) (p - buf2);
8970
8971 std::string str
8972 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
8973
8974 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
8975
567a3e54
SM
8976 if (len > REMOTE_DEBUG_MAX_CHAR)
8977 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
8978 len - REMOTE_DEBUG_MAX_CHAR);
6f8976bf
YQ
8979
8980 fprintf_unfiltered (gdb_stdlog, "...");
b3ced9ba 8981
0f71a2f6 8982 gdb_flush (gdb_stdlog);
c906108c 8983 }
c33e31fd 8984 remote_serial_write (buf2, p - buf2);
c906108c 8985
a6f3e723
SL
8986 /* If this is a no acks version of the remote protocol, send the
8987 packet and move on. */
8988 if (rs->noack_mode)
8989 break;
8990
74531fed
PA
8991 /* Read until either a timeout occurs (-2) or '+' is read.
8992 Handle any notification that arrives in the mean time. */
c906108c
SS
8993 while (1)
8994 {
8995 ch = readchar (remote_timeout);
8996
c5aa993b 8997 if (remote_debug)
c906108c
SS
8998 {
8999 switch (ch)
9000 {
9001 case '+':
1216fa2c 9002 case '-':
c906108c
SS
9003 case SERIAL_TIMEOUT:
9004 case '$':
74531fed 9005 case '%':
c906108c
SS
9006 if (started_error_output)
9007 {
9008 putchar_unfiltered ('\n');
9009 started_error_output = 0;
9010 }
9011 }
9012 }
9013
9014 switch (ch)
9015 {
9016 case '+':
9017 if (remote_debug)
0f71a2f6 9018 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 9019 return 1;
1216fa2c
AC
9020 case '-':
9021 if (remote_debug)
9022 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 9023 /* FALLTHROUGH */
c906108c 9024 case SERIAL_TIMEOUT:
c5aa993b 9025 tcount++;
c906108c 9026 if (tcount > 3)
b80406ac 9027 return 0;
23860348 9028 break; /* Retransmit buffer. */
c906108c
SS
9029 case '$':
9030 {
40e3f985 9031 if (remote_debug)
2bc416ba 9032 fprintf_unfiltered (gdb_stdlog,
23860348 9033 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
9034 /* It's probably an old response sent because an ACK
9035 was lost. Gobble up the packet and ack it so it
9036 doesn't get retransmitted when we resend this
9037 packet. */
6d820c5c 9038 skip_frame ();
c33e31fd 9039 remote_serial_write ("+", 1);
23860348 9040 continue; /* Now, go look for +. */
c906108c 9041 }
74531fed
PA
9042
9043 case '%':
9044 {
9045 int val;
9046
9047 /* If we got a notification, handle it, and go back to looking
9048 for an ack. */
9049 /* We've found the start of a notification. Now
9050 collect the data. */
9051 val = read_frame (&rs->buf, &rs->buf_size);
9052 if (val >= 0)
9053 {
9054 if (remote_debug)
9055 {
b3ced9ba 9056 std::string str = escape_buffer (rs->buf, val);
6e5abd65 9057
6e5abd65
PA
9058 fprintf_unfiltered (gdb_stdlog,
9059 " Notification received: %s\n",
b3ced9ba 9060 str.c_str ());
74531fed 9061 }
5965e028 9062 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
9063 /* We're in sync now, rewait for the ack. */
9064 tcount = 0;
9065 }
9066 else
9067 {
9068 if (remote_debug)
9069 {
9070 if (!started_error_output)
9071 {
9072 started_error_output = 1;
9073 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9074 }
9075 fputc_unfiltered (ch & 0177, gdb_stdlog);
9076 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9077 }
9078 }
9079 continue;
9080 }
9081 /* fall-through */
c906108c
SS
9082 default:
9083 if (remote_debug)
9084 {
9085 if (!started_error_output)
9086 {
9087 started_error_output = 1;
0f71a2f6 9088 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 9089 }
0f71a2f6 9090 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
9091 }
9092 continue;
9093 }
23860348 9094 break; /* Here to retransmit. */
c906108c
SS
9095 }
9096
9097#if 0
9098 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
9099 able to get out next time we call QUIT, without anything as
9100 violent as interrupt_query. If we want to provide a way out of
9101 here without getting to the next QUIT, it should be based on
9102 hitting ^C twice as in remote_wait. */
c906108c
SS
9103 if (quit_flag)
9104 {
9105 quit_flag = 0;
9106 interrupt_query ();
9107 }
9108#endif
9109 }
a5c0808e 9110
a6f3e723 9111 return 0;
c906108c
SS
9112}
9113
6d820c5c
DJ
9114/* Come here after finding the start of a frame when we expected an
9115 ack. Do our best to discard the rest of this packet. */
9116
9117static void
9118skip_frame (void)
9119{
9120 int c;
9121
9122 while (1)
9123 {
9124 c = readchar (remote_timeout);
9125 switch (c)
9126 {
9127 case SERIAL_TIMEOUT:
9128 /* Nothing we can do. */
9129 return;
9130 case '#':
9131 /* Discard the two bytes of checksum and stop. */
9132 c = readchar (remote_timeout);
9133 if (c >= 0)
9134 c = readchar (remote_timeout);
9135
9136 return;
9137 case '*': /* Run length encoding. */
9138 /* Discard the repeat count. */
9139 c = readchar (remote_timeout);
9140 if (c < 0)
9141 return;
9142 break;
9143 default:
9144 /* A regular character. */
9145 break;
9146 }
9147 }
9148}
9149
c906108c 9150/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
9151 into *BUF, verifying the checksum, length, and handling run-length
9152 compression. NUL terminate the buffer. If there is not enough room,
9153 expand *BUF using xrealloc.
c906108c 9154
c2d11a7d
JM
9155 Returns -1 on error, number of characters in buffer (ignoring the
9156 trailing NULL) on success. (could be extended to return one of the
23860348 9157 SERIAL status indications). */
c2d11a7d
JM
9158
9159static long
6d820c5c
DJ
9160read_frame (char **buf_p,
9161 long *sizeof_buf)
c906108c
SS
9162{
9163 unsigned char csum;
c2d11a7d 9164 long bc;
c906108c 9165 int c;
6d820c5c 9166 char *buf = *buf_p;
a6f3e723 9167 struct remote_state *rs = get_remote_state ();
c906108c
SS
9168
9169 csum = 0;
c2d11a7d 9170 bc = 0;
c906108c
SS
9171
9172 while (1)
9173 {
9174 c = readchar (remote_timeout);
c906108c
SS
9175 switch (c)
9176 {
9177 case SERIAL_TIMEOUT:
9178 if (remote_debug)
0f71a2f6 9179 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 9180 return -1;
c906108c
SS
9181 case '$':
9182 if (remote_debug)
0f71a2f6
JM
9183 fputs_filtered ("Saw new packet start in middle of old one\n",
9184 gdb_stdlog);
23860348 9185 return -1; /* Start a new packet, count retries. */
c906108c
SS
9186 case '#':
9187 {
9188 unsigned char pktcsum;
e1b09194
AC
9189 int check_0 = 0;
9190 int check_1 = 0;
c906108c 9191
c2d11a7d 9192 buf[bc] = '\0';
c906108c 9193
e1b09194
AC
9194 check_0 = readchar (remote_timeout);
9195 if (check_0 >= 0)
9196 check_1 = readchar (remote_timeout);
802188a7 9197
e1b09194
AC
9198 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9199 {
9200 if (remote_debug)
2bc416ba 9201 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 9202 gdb_stdlog);
e1b09194
AC
9203 return -1;
9204 }
9205 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
9206 {
9207 if (remote_debug)
2bc416ba 9208 fputs_filtered ("Communication error in checksum\n",
23860348 9209 gdb_stdlog);
40e3f985
FN
9210 return -1;
9211 }
c906108c 9212
a6f3e723
SL
9213 /* Don't recompute the checksum; with no ack packets we
9214 don't have any way to indicate a packet retransmission
9215 is necessary. */
9216 if (rs->noack_mode)
9217 return bc;
9218
e1b09194 9219 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 9220 if (csum == pktcsum)
c2d11a7d 9221 return bc;
c906108c 9222
c5aa993b 9223 if (remote_debug)
c906108c 9224 {
b3ced9ba 9225 std::string str = escape_buffer (buf, bc);
6e5abd65 9226
6e5abd65 9227 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
9228 "Bad checksum, sentsum=0x%x, "
9229 "csum=0x%x, buf=%s\n",
b3ced9ba 9230 pktcsum, csum, str.c_str ());
c906108c 9231 }
c2d11a7d 9232 /* Number of characters in buffer ignoring trailing
23860348 9233 NULL. */
c2d11a7d 9234 return -1;
c906108c 9235 }
23860348 9236 case '*': /* Run length encoding. */
c2c6d25f
JM
9237 {
9238 int repeat;
c906108c 9239
a744cf53 9240 csum += c;
b4501125
AC
9241 c = readchar (remote_timeout);
9242 csum += c;
23860348 9243 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 9244
23860348 9245 /* The character before ``*'' is repeated. */
c2d11a7d 9246
6d820c5c 9247 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 9248 {
6d820c5c
DJ
9249 if (bc + repeat - 1 >= *sizeof_buf - 1)
9250 {
9251 /* Make some more room in the buffer. */
9252 *sizeof_buf += repeat;
224c3ddb 9253 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c
DJ
9254 buf = *buf_p;
9255 }
9256
c2d11a7d
JM
9257 memset (&buf[bc], buf[bc - 1], repeat);
9258 bc += repeat;
c2c6d25f
JM
9259 continue;
9260 }
9261
c2d11a7d 9262 buf[bc] = '\0';
6d820c5c 9263 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 9264 return -1;
c2c6d25f 9265 }
c906108c 9266 default:
6d820c5c 9267 if (bc >= *sizeof_buf - 1)
c906108c 9268 {
6d820c5c
DJ
9269 /* Make some more room in the buffer. */
9270 *sizeof_buf *= 2;
224c3ddb 9271 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c 9272 buf = *buf_p;
c906108c
SS
9273 }
9274
6d820c5c
DJ
9275 buf[bc++] = c;
9276 csum += c;
9277 continue;
c906108c
SS
9278 }
9279 }
9280}
9281
9282/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
9283 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9284 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9285 rather than timing out; this is used (in synchronous mode) to wait
9286 for a target that is is executing user code to stop. */
d9fcf2fb
JM
9287/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9288 don't have to change all the calls to getpkt to deal with the
9289 return value, because at the moment I don't know what the right
23860348 9290 thing to do it for those. */
c906108c 9291void
6d820c5c
DJ
9292getpkt (char **buf,
9293 long *sizeof_buf,
c2d11a7d 9294 int forever)
d9fcf2fb 9295{
54887903 9296 getpkt_sane (buf, sizeof_buf, forever);
d9fcf2fb
JM
9297}
9298
9299
9300/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
9301 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9302 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9303 rather than timing out; this is used (in synchronous mode) to wait
9304 for a target that is is executing user code to stop. If FOREVER ==
9305 0, this function is allowed to time out gracefully and return an
74531fed
PA
9306 indication of this to the caller. Otherwise return the number of
9307 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
9308 enough reason to return to the caller. *IS_NOTIF is an output
9309 boolean that indicates whether *BUF holds a notification or not
9310 (a regular packet). */
74531fed 9311
3172dc30 9312static int
74531fed 9313getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 9314 int expecting_notif, int *is_notif)
c906108c 9315{
2d717e4f 9316 struct remote_state *rs = get_remote_state ();
c906108c
SS
9317 int c;
9318 int tries;
9319 int timeout;
df4b58fe 9320 int val = -1;
c906108c 9321
2d717e4f
DJ
9322 /* We're reading a new response. Make sure we don't look at a
9323 previously cached response. */
9324 rs->cached_wait_status = 0;
9325
6d820c5c 9326 strcpy (*buf, "timeout");
c906108c
SS
9327
9328 if (forever)
74531fed
PA
9329 timeout = watchdog > 0 ? watchdog : -1;
9330 else if (expecting_notif)
9331 timeout = 0; /* There should already be a char in the buffer. If
9332 not, bail out. */
c906108c
SS
9333 else
9334 timeout = remote_timeout;
9335
9336#define MAX_TRIES 3
9337
74531fed
PA
9338 /* Process any number of notifications, and then return when
9339 we get a packet. */
9340 for (;;)
c906108c 9341 {
d9c43928 9342 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
9343 times. */
9344 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 9345 {
74531fed
PA
9346 /* This can loop forever if the remote side sends us
9347 characters continuously, but if it pauses, we'll get
9348 SERIAL_TIMEOUT from readchar because of timeout. Then
9349 we'll count that as a retry.
9350
9351 Note that even when forever is set, we will only wait
9352 forever prior to the start of a packet. After that, we
9353 expect characters to arrive at a brisk pace. They should
9354 show up within remote_timeout intervals. */
9355 do
9356 c = readchar (timeout);
9357 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
9358
9359 if (c == SERIAL_TIMEOUT)
9360 {
74531fed
PA
9361 if (expecting_notif)
9362 return -1; /* Don't complain, it's normal to not get
9363 anything in this case. */
9364
23860348 9365 if (forever) /* Watchdog went off? Kill the target. */
c906108c 9366 {
78a095c3 9367 remote_unpush_target ();
598d3636
JK
9368 throw_error (TARGET_CLOSE_ERROR,
9369 _("Watchdog timeout has expired. "
9370 "Target detached."));
c906108c 9371 }
c906108c 9372 if (remote_debug)
0f71a2f6 9373 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 9374 }
74531fed
PA
9375 else
9376 {
9377 /* We've found the start of a packet or notification.
9378 Now collect the data. */
9379 val = read_frame (buf, sizeof_buf);
9380 if (val >= 0)
9381 break;
9382 }
9383
c33e31fd 9384 remote_serial_write ("-", 1);
c906108c 9385 }
c906108c 9386
74531fed
PA
9387 if (tries > MAX_TRIES)
9388 {
9389 /* We have tried hard enough, and just can't receive the
9390 packet/notification. Give up. */
9391 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 9392
74531fed
PA
9393 /* Skip the ack char if we're in no-ack mode. */
9394 if (!rs->noack_mode)
c33e31fd 9395 remote_serial_write ("+", 1);
74531fed
PA
9396 return -1;
9397 }
c906108c 9398
74531fed
PA
9399 /* If we got an ordinary packet, return that to our caller. */
9400 if (c == '$')
c906108c
SS
9401 {
9402 if (remote_debug)
43e526b9 9403 {
6f8976bf
YQ
9404 std::string str
9405 = escape_buffer (*buf,
9406 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9407
9408 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9409 str.c_str ());
9410
567a3e54
SM
9411 if (val > REMOTE_DEBUG_MAX_CHAR)
9412 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9413 val - REMOTE_DEBUG_MAX_CHAR);
6e5abd65 9414
6f8976bf 9415 fprintf_unfiltered (gdb_stdlog, "\n");
43e526b9 9416 }
a6f3e723
SL
9417
9418 /* Skip the ack char if we're in no-ack mode. */
9419 if (!rs->noack_mode)
c33e31fd 9420 remote_serial_write ("+", 1);
fee9eda9
YQ
9421 if (is_notif != NULL)
9422 *is_notif = 0;
0876f84a 9423 return val;
c906108c
SS
9424 }
9425
74531fed
PA
9426 /* If we got a notification, handle it, and go back to looking
9427 for a packet. */
9428 else
9429 {
9430 gdb_assert (c == '%');
9431
9432 if (remote_debug)
9433 {
b3ced9ba 9434 std::string str = escape_buffer (*buf, val);
6e5abd65 9435
6e5abd65
PA
9436 fprintf_unfiltered (gdb_stdlog,
9437 " Notification received: %s\n",
b3ced9ba 9438 str.c_str ());
74531fed 9439 }
fee9eda9
YQ
9440 if (is_notif != NULL)
9441 *is_notif = 1;
c906108c 9442
5965e028 9443 handle_notification (rs->notif_state, *buf);
c906108c 9444
74531fed 9445 /* Notifications require no acknowledgement. */
a6f3e723 9446
74531fed 9447 if (expecting_notif)
fee9eda9 9448 return val;
74531fed
PA
9449 }
9450 }
9451}
9452
9453static int
9454getpkt_sane (char **buf, long *sizeof_buf, int forever)
9455{
fee9eda9 9456 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
9457}
9458
9459static int
fee9eda9
YQ
9460getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9461 int *is_notif)
74531fed 9462{
fee9eda9
YQ
9463 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9464 is_notif);
c906108c 9465}
74531fed 9466
cbb8991c
DB
9467/* Check whether EVENT is a fork event for the process specified
9468 by the pid passed in DATA, and if it is, kill the fork child. */
9469
9470static int
9471kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9472 QUEUE_ITER (stop_reply_p) *iter,
9473 stop_reply_p event,
9474 void *data)
9475{
19ba03f4 9476 struct queue_iter_param *param = (struct queue_iter_param *) data;
cbb8991c
DB
9477 int parent_pid = *(int *) param->input;
9478
9479 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9480 {
9481 struct remote_state *rs = get_remote_state ();
9482 int child_pid = ptid_get_pid (event->ws.value.related_pid);
9483 int res;
9484
9485 res = remote_vkill (child_pid, rs);
9486 if (res != 0)
9487 error (_("Can't kill fork child process %d"), child_pid);
9488 }
9489
9490 return 1;
9491}
9492
9493/* Kill any new fork children of process PID that haven't been
9494 processed by follow_fork. */
9495
9496static void
9497kill_new_fork_children (int pid, struct remote_state *rs)
9498{
9499 struct thread_info *thread;
9500 struct notif_client *notif = &notif_client_stop;
9501 struct queue_iter_param param;
9502
9503 /* Kill the fork child threads of any threads in process PID
9504 that are stopped at a fork event. */
9505 ALL_NON_EXITED_THREADS (thread)
9506 {
9507 struct target_waitstatus *ws = &thread->pending_follow;
9508
9509 if (is_pending_fork_parent (ws, pid, thread->ptid))
9510 {
9511 struct remote_state *rs = get_remote_state ();
9512 int child_pid = ptid_get_pid (ws->value.related_pid);
9513 int res;
9514
9515 res = remote_vkill (child_pid, rs);
9516 if (res != 0)
9517 error (_("Can't kill fork child process %d"), child_pid);
9518 }
9519 }
9520
9521 /* Check for any pending fork events (not reported or processed yet)
9522 in process PID and kill those fork child threads as well. */
9523 remote_notif_get_pending_events (notif);
9524 param.input = &pid;
9525 param.output = NULL;
9526 QUEUE_iterate (stop_reply_p, stop_reply_queue,
9527 kill_child_of_pending_fork, &param);
9528}
9529
c906108c 9530\f
8020350c
DB
9531/* Target hook to kill the current inferior. */
9532
f6ac5f3d
PA
9533void
9534remote_target::kill ()
43ff13b4 9535{
8020350c
DB
9536 int res = -1;
9537 int pid = ptid_get_pid (inferior_ptid);
9538 struct remote_state *rs = get_remote_state ();
0fdf84ca 9539
8020350c 9540 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 9541 {
8020350c
DB
9542 /* If we're stopped while forking and we haven't followed yet,
9543 kill the child task. We need to do this before killing the
9544 parent task because if this is a vfork then the parent will
9545 be sleeping. */
9546 kill_new_fork_children (pid, rs);
9547
9548 res = remote_vkill (pid, rs);
9549 if (res == 0)
0fdf84ca 9550 {
bc1e6c81 9551 target_mourn_inferior (inferior_ptid);
0fdf84ca
PA
9552 return;
9553 }
8020350c 9554 }
0fdf84ca 9555
8020350c
DB
9556 /* If we are in 'target remote' mode and we are killing the only
9557 inferior, then we will tell gdbserver to exit and unpush the
9558 target. */
9559 if (res == -1 && !remote_multi_process_p (rs)
9560 && number_of_live_inferiors () == 1)
9561 {
9562 remote_kill_k ();
9563
9564 /* We've killed the remote end, we get to mourn it. If we are
9565 not in extended mode, mourning the inferior also unpushes
9566 remote_ops from the target stack, which closes the remote
9567 connection. */
bc1e6c81 9568 target_mourn_inferior (inferior_ptid);
8020350c
DB
9569
9570 return;
0fdf84ca 9571 }
43ff13b4 9572
8020350c 9573 error (_("Can't kill process"));
43ff13b4
JM
9574}
9575
8020350c
DB
9576/* Send a kill request to the target using the 'vKill' packet. */
9577
82f73884
PA
9578static int
9579remote_vkill (int pid, struct remote_state *rs)
9580{
4082afcc 9581 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
9582 return -1;
9583
9584 /* Tell the remote target to detach. */
bba74b36 9585 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
9586 putpkt (rs->buf);
9587 getpkt (&rs->buf, &rs->buf_size, 0);
9588
4082afcc
PA
9589 switch (packet_ok (rs->buf,
9590 &remote_protocol_packets[PACKET_vKill]))
9591 {
9592 case PACKET_OK:
9593 return 0;
9594 case PACKET_ERROR:
9595 return 1;
9596 case PACKET_UNKNOWN:
9597 return -1;
9598 default:
9599 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9600 }
82f73884
PA
9601}
9602
8020350c
DB
9603/* Send a kill request to the target using the 'k' packet. */
9604
82f73884 9605static void
8020350c 9606remote_kill_k (void)
82f73884 9607{
8020350c
DB
9608 /* Catch errors so the user can quit from gdb even when we
9609 aren't on speaking terms with the remote system. */
9610 TRY
82f73884 9611 {
82f73884 9612 putpkt ("k");
82f73884 9613 }
8020350c
DB
9614 CATCH (ex, RETURN_MASK_ERROR)
9615 {
9616 if (ex.error == TARGET_CLOSE_ERROR)
9617 {
9618 /* If we got an (EOF) error that caused the target
9619 to go away, then we're done, that's what we wanted.
9620 "k" is susceptible to cause a premature EOF, given
9621 that the remote server isn't actually required to
9622 reply to "k", and it can happen that it doesn't
9623 even get to reply ACK to the "k". */
9624 return;
9625 }
82f73884 9626
8020350c
DB
9627 /* Otherwise, something went wrong. We didn't actually kill
9628 the target. Just propagate the exception, and let the
9629 user or higher layers decide what to do. */
9630 throw_exception (ex);
9631 }
9632 END_CATCH
82f73884
PA
9633}
9634
f6ac5f3d
PA
9635void
9636remote_target::mourn_inferior ()
c906108c 9637{
8020350c 9638 struct remote_state *rs = get_remote_state ();
ce5ce7ed 9639
8020350c
DB
9640 /* In 'target remote' mode with one inferior, we close the connection. */
9641 if (!rs->extended && number_of_live_inferiors () <= 1)
9642 {
f6ac5f3d 9643 unpush_target (this);
c906108c 9644
8020350c
DB
9645 /* remote_close takes care of doing most of the clean up. */
9646 generic_mourn_inferior ();
9647 return;
9648 }
c906108c 9649
e24a49d8
PA
9650 /* In case we got here due to an error, but we're going to stay
9651 connected. */
9652 rs->waiting_for_stop_reply = 0;
9653
dc1981d7
PA
9654 /* If the current general thread belonged to the process we just
9655 detached from or has exited, the remote side current general
9656 thread becomes undefined. Considering a case like this:
9657
9658 - We just got here due to a detach.
9659 - The process that we're detaching from happens to immediately
9660 report a global breakpoint being hit in non-stop mode, in the
9661 same thread we had selected before.
9662 - GDB attaches to this process again.
9663 - This event happens to be the next event we handle.
9664
9665 GDB would consider that the current general thread didn't need to
9666 be set on the stub side (with Hg), since for all it knew,
9667 GENERAL_THREAD hadn't changed.
9668
9669 Notice that although in all-stop mode, the remote server always
9670 sets the current thread to the thread reporting the stop event,
9671 that doesn't happen in non-stop mode; in non-stop, the stub *must
9672 not* change the current thread when reporting a breakpoint hit,
9673 due to the decoupling of event reporting and event handling.
9674
9675 To keep things simple, we always invalidate our notion of the
9676 current thread. */
47f8a51d 9677 record_currthread (rs, minus_one_ptid);
dc1981d7 9678
8020350c 9679 /* Call common code to mark the inferior as not running. */
48aa3c27
PA
9680 generic_mourn_inferior ();
9681
d729566a 9682 if (!have_inferiors ())
2d717e4f 9683 {
82f73884
PA
9684 if (!remote_multi_process_p (rs))
9685 {
9686 /* Check whether the target is running now - some remote stubs
9687 automatically restart after kill. */
9688 putpkt ("?");
9689 getpkt (&rs->buf, &rs->buf_size, 0);
9690
9691 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9692 {
3e43a32a
MS
9693 /* Assume that the target has been restarted. Set
9694 inferior_ptid so that bits of core GDB realizes
9695 there's something here, e.g., so that the user can
9696 say "kill" again. */
82f73884
PA
9697 inferior_ptid = magic_null_ptid;
9698 }
82f73884 9699 }
2d717e4f
DJ
9700 }
9701}
c906108c 9702
f6ac5f3d
PA
9703int
9704extended_remote_target::supports_disable_randomization ()
03583c20 9705{
4082afcc 9706 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
9707}
9708
9709static void
9710extended_remote_disable_randomization (int val)
9711{
9712 struct remote_state *rs = get_remote_state ();
9713 char *reply;
9714
bba74b36
YQ
9715 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9716 val);
03583c20 9717 putpkt (rs->buf);
b6bb3468 9718 reply = remote_get_noisy_reply ();
03583c20
UW
9719 if (*reply == '\0')
9720 error (_("Target does not support QDisableRandomization."));
9721 if (strcmp (reply, "OK") != 0)
9722 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9723}
9724
2d717e4f 9725static int
7c5ded6a 9726extended_remote_run (const std::string &args)
2d717e4f
DJ
9727{
9728 struct remote_state *rs = get_remote_state ();
2d717e4f 9729 int len;
94585166 9730 const char *remote_exec_file = get_remote_exec_file ();
c906108c 9731
2d717e4f
DJ
9732 /* If the user has disabled vRun support, or we have detected that
9733 support is not available, do not try it. */
4082afcc 9734 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 9735 return -1;
424163ea 9736
2d717e4f
DJ
9737 strcpy (rs->buf, "vRun;");
9738 len = strlen (rs->buf);
c906108c 9739
2d717e4f
DJ
9740 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9741 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
9742 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9743 strlen (remote_exec_file));
2d717e4f 9744
7c5ded6a 9745 if (!args.empty ())
2d717e4f 9746 {
2d717e4f 9747 int i;
2d717e4f 9748
773a1edc 9749 gdb_argv argv (args.c_str ());
2d717e4f
DJ
9750 for (i = 0; argv[i] != NULL; i++)
9751 {
9752 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9753 error (_("Argument list too long for run packet"));
9754 rs->buf[len++] = ';';
9f1b45b0
TT
9755 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9756 strlen (argv[i]));
2d717e4f 9757 }
2d717e4f
DJ
9758 }
9759
9760 rs->buf[len++] = '\0';
9761
9762 putpkt (rs->buf);
9763 getpkt (&rs->buf, &rs->buf_size, 0);
9764
4082afcc 9765 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 9766 {
4082afcc 9767 case PACKET_OK:
3405876a 9768 /* We have a wait response. All is well. */
2d717e4f 9769 return 0;
4082afcc
PA
9770 case PACKET_UNKNOWN:
9771 return -1;
9772 case PACKET_ERROR:
2d717e4f
DJ
9773 if (remote_exec_file[0] == '\0')
9774 error (_("Running the default executable on the remote target failed; "
9775 "try \"set remote exec-file\"?"));
9776 else
9777 error (_("Running \"%s\" on the remote target failed"),
9778 remote_exec_file);
4082afcc
PA
9779 default:
9780 gdb_assert_not_reached (_("bad switch"));
2d717e4f 9781 }
c906108c
SS
9782}
9783
0a2dde4a
SDJ
9784/* Helper function to send set/unset environment packets. ACTION is
9785 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
9786 or "QEnvironmentUnsetVariable". VALUE is the variable to be
9787 sent. */
9788
9789static void
9790send_environment_packet (struct remote_state *rs,
9791 const char *action,
9792 const char *packet,
9793 const char *value)
9794{
9795 /* Convert the environment variable to an hex string, which
9796 is the best format to be transmitted over the wire. */
9797 std::string encoded_value = bin2hex ((const gdb_byte *) value,
9798 strlen (value));
9799
9800 xsnprintf (rs->buf, get_remote_packet_size (),
9801 "%s:%s", packet, encoded_value.c_str ());
9802
9803 putpkt (rs->buf);
9804 getpkt (&rs->buf, &rs->buf_size, 0);
9805 if (strcmp (rs->buf, "OK") != 0)
9806 warning (_("Unable to %s environment variable '%s' on remote."),
9807 action, value);
9808}
9809
9810/* Helper function to handle the QEnvironment* packets. */
9811
9812static void
9813extended_remote_environment_support (struct remote_state *rs)
9814{
9815 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
9816 {
9817 putpkt ("QEnvironmentReset");
9818 getpkt (&rs->buf, &rs->buf_size, 0);
9819 if (strcmp (rs->buf, "OK") != 0)
9820 warning (_("Unable to reset environment on remote."));
9821 }
9822
9823 gdb_environ *e = &current_inferior ()->environment;
9824
9825 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
9826 for (const std::string &el : e->user_set_env ())
9827 send_environment_packet (rs, "set", "QEnvironmentHexEncoded",
9828 el.c_str ());
9829
9830 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
9831 for (const std::string &el : e->user_unset_env ())
9832 send_environment_packet (rs, "unset", "QEnvironmentUnset", el.c_str ());
9833}
9834
bc3b087d
SDJ
9835/* Helper function to set the current working directory for the
9836 inferior in the remote target. */
9837
9838static void
9839extended_remote_set_inferior_cwd (struct remote_state *rs)
9840{
9841 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
9842 {
9843 const char *inferior_cwd = get_inferior_cwd ();
9844
9845 if (inferior_cwd != NULL)
9846 {
9847 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
9848 strlen (inferior_cwd));
9849
9850 xsnprintf (rs->buf, get_remote_packet_size (),
9851 "QSetWorkingDir:%s", hexpath.c_str ());
9852 }
9853 else
9854 {
9855 /* An empty inferior_cwd means that the user wants us to
9856 reset the remote server's inferior's cwd. */
9857 xsnprintf (rs->buf, get_remote_packet_size (),
9858 "QSetWorkingDir:");
9859 }
9860
9861 putpkt (rs->buf);
9862 getpkt (&rs->buf, &rs->buf_size, 0);
9863 if (packet_ok (rs->buf,
9864 &remote_protocol_packets[PACKET_QSetWorkingDir])
9865 != PACKET_OK)
9866 error (_("\
9867Remote replied unexpectedly while setting the inferior's working\n\
9868directory: %s"),
9869 rs->buf);
9870
9871 }
9872}
9873
2d717e4f
DJ
9874/* In the extended protocol we want to be able to do things like
9875 "run" and have them basically work as expected. So we need
9876 a special create_inferior function. We support changing the
9877 executable file and the command line arguments, but not the
9878 environment. */
9879
f6ac5f3d
PA
9880void
9881extended_remote_target::create_inferior (const char *exec_file,
9882 const std::string &args,
9883 char **env, int from_tty)
43ff13b4 9884{
3405876a
PA
9885 int run_worked;
9886 char *stop_reply;
9887 struct remote_state *rs = get_remote_state ();
94585166 9888 const char *remote_exec_file = get_remote_exec_file ();
3405876a 9889
43ff13b4 9890 /* If running asynchronously, register the target file descriptor
23860348 9891 with the event loop. */
75c99385 9892 if (target_can_async_p ())
6a3753b3 9893 target_async (1);
43ff13b4 9894
03583c20 9895 /* Disable address space randomization if requested (and supported). */
f6ac5f3d 9896 if (supports_disable_randomization ())
03583c20
UW
9897 extended_remote_disable_randomization (disable_randomization);
9898
aefd8b33
SDJ
9899 /* If startup-with-shell is on, we inform gdbserver to start the
9900 remote inferior using a shell. */
9901 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
9902 {
9903 xsnprintf (rs->buf, get_remote_packet_size (),
9904 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
9905 putpkt (rs->buf);
9906 getpkt (&rs->buf, &rs->buf_size, 0);
9907 if (strcmp (rs->buf, "OK") != 0)
9908 error (_("\
9909Remote replied unexpectedly while setting startup-with-shell: %s"),
9910 rs->buf);
9911 }
9912
0a2dde4a
SDJ
9913 extended_remote_environment_support (rs);
9914
bc3b087d
SDJ
9915 extended_remote_set_inferior_cwd (rs);
9916
43ff13b4 9917 /* Now restart the remote server. */
3405876a
PA
9918 run_worked = extended_remote_run (args) != -1;
9919 if (!run_worked)
2d717e4f
DJ
9920 {
9921 /* vRun was not supported. Fail if we need it to do what the
9922 user requested. */
9923 if (remote_exec_file[0])
9924 error (_("Remote target does not support \"set remote exec-file\""));
7c5ded6a 9925 if (!args.empty ())
2d717e4f 9926 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 9927
2d717e4f
DJ
9928 /* Fall back to "R". */
9929 extended_remote_restart ();
9930 }
424163ea 9931
6c95b8df
PA
9932 if (!have_inferiors ())
9933 {
9934 /* Clean up from the last time we ran, before we mark the target
9935 running again. This will mark breakpoints uninserted, and
9936 get_offsets may insert breakpoints. */
9937 init_thread_list ();
9938 init_wait_for_inferior ();
9939 }
45280a52 9940
3405876a
PA
9941 /* vRun's success return is a stop reply. */
9942 stop_reply = run_worked ? rs->buf : NULL;
9943 add_current_inferior_and_thread (stop_reply);
c0a2216e 9944
2d717e4f
DJ
9945 /* Get updated offsets, if the stub uses qOffsets. */
9946 get_offsets ();
2d717e4f 9947}
c906108c 9948\f
c5aa993b 9949
b775012e
LM
9950/* Given a location's target info BP_TGT and the packet buffer BUF, output
9951 the list of conditions (in agent expression bytecode format), if any, the
9952 target needs to evaluate. The output is placed into the packet buffer
bba74b36 9953 started from BUF and ended at BUF_END. */
b775012e
LM
9954
9955static int
9956remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
9957 struct bp_target_info *bp_tgt, char *buf,
9958 char *buf_end)
b775012e 9959{
3cde5c42 9960 if (bp_tgt->conditions.empty ())
b775012e
LM
9961 return 0;
9962
9963 buf += strlen (buf);
bba74b36 9964 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
9965 buf++;
9966
83621223 9967 /* Send conditions to the target. */
d538e36d 9968 for (agent_expr *aexpr : bp_tgt->conditions)
b775012e 9969 {
bba74b36 9970 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e 9971 buf += strlen (buf);
3cde5c42 9972 for (int i = 0; i < aexpr->len; ++i)
b775012e
LM
9973 buf = pack_hex_byte (buf, aexpr->buf[i]);
9974 *buf = '\0';
9975 }
b775012e
LM
9976 return 0;
9977}
9978
d3ce09f5
SS
9979static void
9980remote_add_target_side_commands (struct gdbarch *gdbarch,
9981 struct bp_target_info *bp_tgt, char *buf)
9982{
3cde5c42 9983 if (bp_tgt->tcommands.empty ())
d3ce09f5
SS
9984 return;
9985
9986 buf += strlen (buf);
9987
9988 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9989 buf += strlen (buf);
9990
9991 /* Concatenate all the agent expressions that are commands into the
9992 cmds parameter. */
df97be55 9993 for (agent_expr *aexpr : bp_tgt->tcommands)
d3ce09f5
SS
9994 {
9995 sprintf (buf, "X%x,", aexpr->len);
9996 buf += strlen (buf);
3cde5c42 9997 for (int i = 0; i < aexpr->len; ++i)
d3ce09f5
SS
9998 buf = pack_hex_byte (buf, aexpr->buf[i]);
9999 *buf = '\0';
10000 }
d3ce09f5
SS
10001}
10002
8181d85f
DJ
10003/* Insert a breakpoint. On targets that have software breakpoint
10004 support, we ask the remote target to do the work; on targets
10005 which don't, we insert a traditional memory breakpoint. */
c906108c 10006
f6ac5f3d
PA
10007int
10008remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10009 struct bp_target_info *bp_tgt)
c906108c 10010{
d471ea57
AC
10011 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10012 If it succeeds, then set the support to PACKET_ENABLE. If it
10013 fails, and the user has explicitly requested the Z support then
23860348 10014 report an error, otherwise, mark it disabled and go on. */
802188a7 10015
4082afcc 10016 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10017 {
0d5ed153 10018 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10019 struct remote_state *rs;
bba74b36 10020 char *p, *endbuf;
4fff2411 10021
28439a30
PA
10022 /* Make sure the remote is pointing at the right process, if
10023 necessary. */
10024 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10025 set_general_process ();
10026
4fff2411
JZ
10027 rs = get_remote_state ();
10028 p = rs->buf;
bba74b36 10029 endbuf = rs->buf + get_remote_packet_size ();
802188a7 10030
96baa820
JM
10031 *(p++) = 'Z';
10032 *(p++) = '0';
10033 *(p++) = ',';
7c0f6dcc 10034 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 10035 p += hexnumstr (p, addr);
579c6ad9 10036 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10037
f6ac5f3d 10038 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10039 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10040
f6ac5f3d 10041 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10042 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10043
6d820c5c
DJ
10044 putpkt (rs->buf);
10045 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10046
6d820c5c 10047 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 10048 {
d471ea57
AC
10049 case PACKET_ERROR:
10050 return -1;
10051 case PACKET_OK:
10052 return 0;
10053 case PACKET_UNKNOWN:
10054 break;
96baa820
JM
10055 }
10056 }
c906108c 10057
0000e5cc
PA
10058 /* If this breakpoint has target-side commands but this stub doesn't
10059 support Z0 packets, throw error. */
3cde5c42 10060 if (!bp_tgt->tcommands.empty ())
0000e5cc
PA
10061 throw_error (NOT_SUPPORTED_ERROR, _("\
10062Target doesn't support breakpoints that have target side commands."));
10063
f6ac5f3d 10064 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
c906108c
SS
10065}
10066
f6ac5f3d
PA
10067int
10068remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10069 struct bp_target_info *bp_tgt,
10070 enum remove_bp_reason reason)
c906108c 10071{
8181d85f 10072 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 10073 struct remote_state *rs = get_remote_state ();
96baa820 10074
4082afcc 10075 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10076 {
6d820c5c 10077 char *p = rs->buf;
bba74b36 10078 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 10079
28439a30
PA
10080 /* Make sure the remote is pointing at the right process, if
10081 necessary. */
10082 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10083 set_general_process ();
10084
96baa820
JM
10085 *(p++) = 'z';
10086 *(p++) = '0';
10087 *(p++) = ',';
10088
8181d85f
DJ
10089 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10090 p += hexnumstr (p, addr);
579c6ad9 10091 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10092
6d820c5c
DJ
10093 putpkt (rs->buf);
10094 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10095
6d820c5c 10096 return (rs->buf[0] == 'E');
96baa820
JM
10097 }
10098
f6ac5f3d 10099 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
c906108c
SS
10100}
10101
f486487f 10102static enum Z_packet_type
d471ea57
AC
10103watchpoint_to_Z_packet (int type)
10104{
10105 switch (type)
10106 {
10107 case hw_write:
bb858e6a 10108 return Z_PACKET_WRITE_WP;
d471ea57
AC
10109 break;
10110 case hw_read:
bb858e6a 10111 return Z_PACKET_READ_WP;
d471ea57
AC
10112 break;
10113 case hw_access:
bb858e6a 10114 return Z_PACKET_ACCESS_WP;
d471ea57
AC
10115 break;
10116 default:
8e65ff28 10117 internal_error (__FILE__, __LINE__,
e2e0b3e5 10118 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
10119 }
10120}
10121
f6ac5f3d
PA
10122int
10123remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10124 enum target_hw_bp_type type, struct expression *cond)
96baa820 10125{
d01949b6 10126 struct remote_state *rs = get_remote_state ();
bba74b36 10127 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 10128 char *p;
d471ea57 10129 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 10130
4082afcc 10131 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 10132 return 1;
802188a7 10133
28439a30
PA
10134 /* Make sure the remote is pointing at the right process, if
10135 necessary. */
10136 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10137 set_general_process ();
10138
bba74b36 10139 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 10140 p = strchr (rs->buf, '\0');
96baa820
JM
10141 addr = remote_address_masked (addr);
10142 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10143 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 10144
6d820c5c
DJ
10145 putpkt (rs->buf);
10146 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10147
6d820c5c 10148 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10149 {
10150 case PACKET_ERROR:
d471ea57 10151 return -1;
85d721b8
PA
10152 case PACKET_UNKNOWN:
10153 return 1;
d471ea57
AC
10154 case PACKET_OK:
10155 return 0;
10156 }
8e65ff28 10157 internal_error (__FILE__, __LINE__,
e2e0b3e5 10158 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
10159}
10160
f6ac5f3d
PA
10161int
10162remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10163 CORE_ADDR start, int length)
283002cf
MR
10164{
10165 CORE_ADDR diff = remote_address_masked (addr - start);
10166
10167 return diff < length;
10168}
10169
d471ea57 10170
f6ac5f3d
PA
10171int
10172remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10173 enum target_hw_bp_type type, struct expression *cond)
96baa820 10174{
d01949b6 10175 struct remote_state *rs = get_remote_state ();
bba74b36 10176 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 10177 char *p;
d471ea57
AC
10178 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10179
4082afcc 10180 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 10181 return -1;
802188a7 10182
28439a30
PA
10183 /* Make sure the remote is pointing at the right process, if
10184 necessary. */
10185 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10186 set_general_process ();
10187
bba74b36 10188 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 10189 p = strchr (rs->buf, '\0');
96baa820
JM
10190 addr = remote_address_masked (addr);
10191 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10192 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
10193 putpkt (rs->buf);
10194 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10195
6d820c5c 10196 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10197 {
10198 case PACKET_ERROR:
10199 case PACKET_UNKNOWN:
10200 return -1;
10201 case PACKET_OK:
10202 return 0;
10203 }
8e65ff28 10204 internal_error (__FILE__, __LINE__,
e2e0b3e5 10205 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
10206}
10207
3c3bea1c 10208
501eef12 10209int remote_hw_watchpoint_limit = -1;
480a3f21 10210int remote_hw_watchpoint_length_limit = -1;
501eef12 10211int remote_hw_breakpoint_limit = -1;
d471ea57 10212
f6ac5f3d
PA
10213int
10214remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
480a3f21
PW
10215{
10216 if (remote_hw_watchpoint_length_limit == 0)
10217 return 0;
10218 else if (remote_hw_watchpoint_length_limit < 0)
10219 return 1;
10220 else if (len <= remote_hw_watchpoint_length_limit)
10221 return 1;
10222 else
10223 return 0;
10224}
10225
f6ac5f3d
PA
10226int
10227remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
96baa820 10228{
3c3bea1c
GS
10229 if (type == bp_hardware_breakpoint)
10230 {
10231 if (remote_hw_breakpoint_limit == 0)
10232 return 0;
501eef12
AC
10233 else if (remote_hw_breakpoint_limit < 0)
10234 return 1;
3c3bea1c
GS
10235 else if (cnt <= remote_hw_breakpoint_limit)
10236 return 1;
10237 }
10238 else
10239 {
10240 if (remote_hw_watchpoint_limit == 0)
10241 return 0;
501eef12
AC
10242 else if (remote_hw_watchpoint_limit < 0)
10243 return 1;
3c3bea1c
GS
10244 else if (ot)
10245 return -1;
10246 else if (cnt <= remote_hw_watchpoint_limit)
10247 return 1;
10248 }
10249 return -1;
10250}
10251
f7e6eed5
PA
10252/* The to_stopped_by_sw_breakpoint method of target remote. */
10253
f6ac5f3d
PA
10254int
10255remote_target::stopped_by_sw_breakpoint ()
f7e6eed5 10256{
799a2abe 10257 struct thread_info *thread = inferior_thread ();
f7e6eed5 10258
799a2abe 10259 return (thread->priv != NULL
7aabaf9d
SM
10260 && (get_remote_thread_info (thread)->stop_reason
10261 == TARGET_STOPPED_BY_SW_BREAKPOINT));
f7e6eed5
PA
10262}
10263
10264/* The to_supports_stopped_by_sw_breakpoint method of target
10265 remote. */
10266
f6ac5f3d
PA
10267int
10268remote_target::supports_stopped_by_sw_breakpoint ()
f7e6eed5 10269{
f7e6eed5
PA
10270 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10271}
10272
10273/* The to_stopped_by_hw_breakpoint method of target remote. */
10274
f6ac5f3d
PA
10275int
10276remote_target::stopped_by_hw_breakpoint ()
f7e6eed5 10277{
799a2abe 10278 struct thread_info *thread = inferior_thread ();
f7e6eed5 10279
799a2abe 10280 return (thread->priv != NULL
7aabaf9d
SM
10281 && (get_remote_thread_info (thread)->stop_reason
10282 == TARGET_STOPPED_BY_HW_BREAKPOINT));
f7e6eed5
PA
10283}
10284
10285/* The to_supports_stopped_by_hw_breakpoint method of target
10286 remote. */
10287
f6ac5f3d
PA
10288int
10289remote_target::supports_stopped_by_hw_breakpoint ()
f7e6eed5 10290{
f7e6eed5
PA
10291 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10292}
10293
f6ac5f3d
PA
10294int
10295remote_target::stopped_by_watchpoint ()
3c3bea1c 10296{
799a2abe 10297 struct thread_info *thread = inferior_thread ();
ee154bee 10298
799a2abe 10299 return (thread->priv != NULL
7aabaf9d
SM
10300 && (get_remote_thread_info (thread)->stop_reason
10301 == TARGET_STOPPED_BY_WATCHPOINT));
3c3bea1c
GS
10302}
10303
f6ac5f3d
PA
10304int
10305remote_target::stopped_data_address (CORE_ADDR *addr_p)
3c3bea1c 10306{
799a2abe 10307 struct thread_info *thread = inferior_thread ();
a744cf53 10308
799a2abe 10309 if (thread->priv != NULL
7aabaf9d
SM
10310 && (get_remote_thread_info (thread)->stop_reason
10311 == TARGET_STOPPED_BY_WATCHPOINT))
4aa7a7f5 10312 {
7aabaf9d 10313 *addr_p = get_remote_thread_info (thread)->watch_data_address;
799a2abe 10314 return 1;
4aa7a7f5
JJ
10315 }
10316
799a2abe 10317 return 0;
3c3bea1c
GS
10318}
10319
10320
f6ac5f3d
PA
10321int
10322remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10323 struct bp_target_info *bp_tgt)
3c3bea1c 10324{
0d5ed153 10325 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10326 struct remote_state *rs;
bba74b36 10327 char *p, *endbuf;
dd61ec5c 10328 char *message;
3c3bea1c 10329
4082afcc 10330 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10331 return -1;
2bc416ba 10332
28439a30
PA
10333 /* Make sure the remote is pointing at the right process, if
10334 necessary. */
10335 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10336 set_general_process ();
10337
4fff2411
JZ
10338 rs = get_remote_state ();
10339 p = rs->buf;
bba74b36 10340 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 10341
96baa820
JM
10342 *(p++) = 'Z';
10343 *(p++) = '1';
10344 *(p++) = ',';
802188a7 10345
0d5ed153 10346 addr = remote_address_masked (addr);
96baa820 10347 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10348 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10349
f6ac5f3d 10350 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10351 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10352
f6ac5f3d 10353 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10354 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10355
6d820c5c
DJ
10356 putpkt (rs->buf);
10357 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10358
6d820c5c 10359 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10360 {
10361 case PACKET_ERROR:
dd61ec5c
MW
10362 if (rs->buf[1] == '.')
10363 {
10364 message = strchr (rs->buf + 2, '.');
10365 if (message)
0316657e 10366 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
10367 }
10368 return -1;
d471ea57
AC
10369 case PACKET_UNKNOWN:
10370 return -1;
10371 case PACKET_OK:
10372 return 0;
10373 }
8e65ff28 10374 internal_error (__FILE__, __LINE__,
e2e0b3e5 10375 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
10376}
10377
d471ea57 10378
f6ac5f3d
PA
10379int
10380remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10381 struct bp_target_info *bp_tgt)
96baa820 10382{
8181d85f 10383 CORE_ADDR addr;
d01949b6 10384 struct remote_state *rs = get_remote_state ();
6d820c5c 10385 char *p = rs->buf;
bba74b36 10386 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 10387
4082afcc 10388 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10389 return -1;
802188a7 10390
28439a30
PA
10391 /* Make sure the remote is pointing at the right process, if
10392 necessary. */
10393 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10394 set_general_process ();
10395
96baa820
JM
10396 *(p++) = 'z';
10397 *(p++) = '1';
10398 *(p++) = ',';
802188a7 10399
8181d85f 10400 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 10401 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10402 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10403
6d820c5c
DJ
10404 putpkt (rs->buf);
10405 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 10406
6d820c5c 10407 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10408 {
10409 case PACKET_ERROR:
10410 case PACKET_UNKNOWN:
10411 return -1;
10412 case PACKET_OK:
10413 return 0;
10414 }
8e65ff28 10415 internal_error (__FILE__, __LINE__,
e2e0b3e5 10416 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 10417}
96baa820 10418
4a5e7a5b
PA
10419/* Verify memory using the "qCRC:" request. */
10420
f6ac5f3d
PA
10421int
10422remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
4a5e7a5b
PA
10423{
10424 struct remote_state *rs = get_remote_state ();
10425 unsigned long host_crc, target_crc;
10426 char *tmp;
10427
936d2992
PA
10428 /* It doesn't make sense to use qCRC if the remote target is
10429 connected but not running. */
10430 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10431 {
10432 enum packet_result result;
28439a30 10433
936d2992
PA
10434 /* Make sure the remote is pointing at the right process. */
10435 set_general_process ();
4a5e7a5b 10436
936d2992
PA
10437 /* FIXME: assumes lma can fit into long. */
10438 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10439 (long) lma, (long) size);
10440 putpkt (rs->buf);
4a5e7a5b 10441
936d2992
PA
10442 /* Be clever; compute the host_crc before waiting for target
10443 reply. */
10444 host_crc = xcrc32 (data, size, 0xffffffff);
10445
10446 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 10447
936d2992
PA
10448 result = packet_ok (rs->buf,
10449 &remote_protocol_packets[PACKET_qCRC]);
10450 if (result == PACKET_ERROR)
10451 return -1;
10452 else if (result == PACKET_OK)
10453 {
10454 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10455 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 10456
936d2992
PA
10457 return (host_crc == target_crc);
10458 }
10459 }
4a5e7a5b 10460
f6ac5f3d 10461 return simple_verify_memory (this, data, lma, size);
4a5e7a5b
PA
10462}
10463
c906108c
SS
10464/* compare-sections command
10465
10466 With no arguments, compares each loadable section in the exec bfd
10467 with the same memory range on the target, and reports mismatches.
4a5e7a5b 10468 Useful for verifying the image on the target against the exec file. */
e514a9d6 10469
c906108c 10470static void
ac88e2de 10471compare_sections_command (const char *args, int from_tty)
c906108c
SS
10472{
10473 asection *s;
ce359b09 10474 const char *sectname;
c906108c
SS
10475 bfd_size_type size;
10476 bfd_vma lma;
10477 int matched = 0;
10478 int mismatched = 0;
4a5e7a5b 10479 int res;
95cf3b38 10480 int read_only = 0;
c906108c
SS
10481
10482 if (!exec_bfd)
8a3fe4f8 10483 error (_("command cannot be used without an exec file"));
c906108c 10484
28439a30
PA
10485 /* Make sure the remote is pointing at the right process. */
10486 set_general_process ();
10487
95cf3b38
DT
10488 if (args != NULL && strcmp (args, "-r") == 0)
10489 {
10490 read_only = 1;
10491 args = NULL;
10492 }
10493
c5aa993b 10494 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
10495 {
10496 if (!(s->flags & SEC_LOAD))
0df8b418 10497 continue; /* Skip non-loadable section. */
c906108c 10498
95cf3b38
DT
10499 if (read_only && (s->flags & SEC_READONLY) == 0)
10500 continue; /* Skip writeable sections */
10501
2c500098 10502 size = bfd_get_section_size (s);
c906108c 10503 if (size == 0)
0df8b418 10504 continue; /* Skip zero-length section. */
c906108c 10505
ce359b09 10506 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 10507 if (args && strcmp (args, sectname) != 0)
0df8b418 10508 continue; /* Not the section selected by user. */
c906108c 10509
0df8b418 10510 matched = 1; /* Do this section. */
c906108c 10511 lma = s->lma;
c906108c 10512
b80406ac
TT
10513 gdb::byte_vector sectdata (size);
10514 bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
c906108c 10515
b80406ac 10516 res = target_verify_memory (sectdata.data (), lma, size);
4a5e7a5b
PA
10517
10518 if (res == -1)
5af949e3 10519 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
10520 paddress (target_gdbarch (), lma),
10521 paddress (target_gdbarch (), lma + size));
c906108c 10522
5af949e3 10523 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
10524 paddress (target_gdbarch (), lma),
10525 paddress (target_gdbarch (), lma + size));
4a5e7a5b 10526 if (res)
c906108c
SS
10527 printf_filtered ("matched.\n");
10528 else
c5aa993b
JM
10529 {
10530 printf_filtered ("MIS-MATCHED!\n");
10531 mismatched++;
10532 }
c906108c
SS
10533 }
10534 if (mismatched > 0)
936d2992 10535 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 10536the loaded file\n"));
c906108c 10537 if (args && !matched)
a3f17187 10538 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
10539}
10540
0e7f50da
UW
10541/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10542 into remote target. The number of bytes written to the remote
10543 target is returned, or -1 for error. */
10544
9b409511 10545static enum target_xfer_status
f6ac5f3d 10546remote_write_qxfer (const char *object_name,
0e7f50da 10547 const char *annex, const gdb_byte *writebuf,
9b409511 10548 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
10549 struct packet_config *packet)
10550{
10551 int i, buf_len;
10552 ULONGEST n;
0e7f50da
UW
10553 struct remote_state *rs = get_remote_state ();
10554 int max_size = get_memory_write_packet_size ();
10555
7cc244de 10556 if (packet_config_support (packet) == PACKET_DISABLE)
2ed4b548 10557 return TARGET_XFER_E_IO;
0e7f50da
UW
10558
10559 /* Insert header. */
10560 i = snprintf (rs->buf, max_size,
10561 "qXfer:%s:write:%s:%s:",
10562 object_name, annex ? annex : "",
10563 phex_nz (offset, sizeof offset));
10564 max_size -= (i + 1);
10565
10566 /* Escape as much data as fits into rs->buf. */
10567 buf_len = remote_escape_output
124e13d9 10568 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
10569
10570 if (putpkt_binary (rs->buf, i + buf_len) < 0
10571 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10572 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10573 return TARGET_XFER_E_IO;
0e7f50da
UW
10574
10575 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
10576
10577 *xfered_len = n;
92ffd475 10578 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
0e7f50da
UW
10579}
10580
0876f84a
DJ
10581/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10582 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10583 number of bytes read is returned, or 0 for EOF, or -1 for error.
10584 The number of bytes read may be less than LEN without indicating an
10585 EOF. PACKET is checked and updated to indicate whether the remote
10586 target supports this object. */
10587
9b409511 10588static enum target_xfer_status
f6ac5f3d 10589remote_read_qxfer (const char *object_name,
0876f84a
DJ
10590 const char *annex,
10591 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 10592 ULONGEST *xfered_len,
0876f84a
DJ
10593 struct packet_config *packet)
10594{
0876f84a 10595 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
10596 LONGEST i, n, packet_len;
10597
7cc244de 10598 if (packet_config_support (packet) == PACKET_DISABLE)
2ed4b548 10599 return TARGET_XFER_E_IO;
0876f84a
DJ
10600
10601 /* Check whether we've cached an end-of-object packet that matches
10602 this request. */
8e88304f 10603 if (rs->finished_object)
0876f84a 10604 {
8e88304f
TT
10605 if (strcmp (object_name, rs->finished_object) == 0
10606 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10607 && offset == rs->finished_offset)
9b409511
YQ
10608 return TARGET_XFER_EOF;
10609
0876f84a
DJ
10610
10611 /* Otherwise, we're now reading something different. Discard
10612 the cache. */
8e88304f
TT
10613 xfree (rs->finished_object);
10614 xfree (rs->finished_annex);
10615 rs->finished_object = NULL;
10616 rs->finished_annex = NULL;
0876f84a
DJ
10617 }
10618
10619 /* Request only enough to fit in a single packet. The actual data
10620 may not, since we don't know how much of it will need to be escaped;
10621 the target is free to respond with slightly less data. We subtract
10622 five to account for the response type and the protocol frame. */
768adc05 10623 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
0876f84a
DJ
10624 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10625 object_name, annex ? annex : "",
10626 phex_nz (offset, sizeof offset),
10627 phex_nz (n, sizeof n));
10628 i = putpkt (rs->buf);
10629 if (i < 0)
2ed4b548 10630 return TARGET_XFER_E_IO;
0876f84a
DJ
10631
10632 rs->buf[0] = '\0';
10633 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10634 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10635 return TARGET_XFER_E_IO;
0876f84a
DJ
10636
10637 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10638 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10639
10640 /* 'm' means there is (or at least might be) more data after this
10641 batch. That does not make sense unless there's at least one byte
10642 of data in this reply. */
10643 if (rs->buf[0] == 'm' && packet_len == 1)
10644 error (_("Remote qXfer reply contained no data."));
10645
10646 /* Got some data. */
bc20a4af
PA
10647 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10648 packet_len - 1, readbuf, n);
0876f84a
DJ
10649
10650 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
10651 or possibly empty. If we have the final block of a non-empty
10652 object, record this fact to bypass a subsequent partial read. */
10653 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 10654 {
8e88304f
TT
10655 rs->finished_object = xstrdup (object_name);
10656 rs->finished_annex = xstrdup (annex ? annex : "");
10657 rs->finished_offset = offset + i;
0876f84a
DJ
10658 }
10659
9b409511
YQ
10660 if (i == 0)
10661 return TARGET_XFER_EOF;
10662 else
10663 {
10664 *xfered_len = i;
10665 return TARGET_XFER_OK;
10666 }
0876f84a
DJ
10667}
10668
f6ac5f3d
PA
10669enum target_xfer_status
10670remote_target::xfer_partial (enum target_object object,
10671 const char *annex, gdb_byte *readbuf,
10672 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10673 ULONGEST *xfered_len)
c906108c 10674{
82f73884 10675 struct remote_state *rs;
c906108c 10676 int i;
6d820c5c 10677 char *p2;
1e3ff5ad 10678 char query_type;
124e13d9 10679 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 10680
e6e4e701 10681 set_remote_traceframe ();
82f73884
PA
10682 set_general_thread (inferior_ptid);
10683
10684 rs = get_remote_state ();
10685
b2182ed2 10686 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
10687 if (object == TARGET_OBJECT_MEMORY)
10688 {
2d717e4f
DJ
10689 /* If the remote target is connected but not running, we should
10690 pass this request down to a lower stratum (e.g. the executable
10691 file). */
10692 if (!target_has_execution)
9b409511 10693 return TARGET_XFER_EOF;
2d717e4f 10694
21e3b9b9 10695 if (writebuf != NULL)
124e13d9
SM
10696 return remote_write_bytes (offset, writebuf, len, unit_size,
10697 xfered_len);
21e3b9b9 10698 else
f6ac5f3d 10699 return remote_read_bytes (this, offset, readbuf, len, unit_size,
124e13d9 10700 xfered_len);
21e3b9b9
DJ
10701 }
10702
0df8b418 10703 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
10704 if (object == TARGET_OBJECT_SPU)
10705 {
10706 if (readbuf)
f6ac5f3d 10707 return remote_read_qxfer ("spu", annex, readbuf, offset, len,
9b409511
YQ
10708 xfered_len, &remote_protocol_packets
10709 [PACKET_qXfer_spu_read]);
0e7f50da 10710 else
f6ac5f3d 10711 return remote_write_qxfer ("spu", annex, writebuf, offset, len,
9b409511
YQ
10712 xfered_len, &remote_protocol_packets
10713 [PACKET_qXfer_spu_write]);
0e7f50da
UW
10714 }
10715
4aa995e1
PA
10716 /* Handle extra signal info using qxfer packets. */
10717 if (object == TARGET_OBJECT_SIGNAL_INFO)
10718 {
10719 if (readbuf)
f6ac5f3d 10720 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
9b409511 10721 xfered_len, &remote_protocol_packets
4aa995e1
PA
10722 [PACKET_qXfer_siginfo_read]);
10723 else
f6ac5f3d 10724 return remote_write_qxfer ("siginfo", annex,
9b409511 10725 writebuf, offset, len, xfered_len,
4aa995e1
PA
10726 &remote_protocol_packets
10727 [PACKET_qXfer_siginfo_write]);
10728 }
10729
0fb4aa4b
PA
10730 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10731 {
10732 if (readbuf)
f6ac5f3d 10733 return remote_read_qxfer ("statictrace", annex,
9b409511 10734 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
10735 &remote_protocol_packets
10736 [PACKET_qXfer_statictrace_read]);
10737 else
2ed4b548 10738 return TARGET_XFER_E_IO;
0fb4aa4b
PA
10739 }
10740
a76d924d
DJ
10741 /* Only handle flash writes. */
10742 if (writebuf != NULL)
10743 {
a76d924d
DJ
10744 switch (object)
10745 {
10746 case TARGET_OBJECT_FLASH:
f6ac5f3d 10747 return remote_flash_write (this, offset, len, xfered_len,
9b409511 10748 writebuf);
a76d924d
DJ
10749
10750 default:
2ed4b548 10751 return TARGET_XFER_E_IO;
a76d924d
DJ
10752 }
10753 }
4b8a223f 10754
1e3ff5ad
AC
10755 /* Map pre-existing objects onto letters. DO NOT do this for new
10756 objects!!! Instead specify new query packets. */
10757 switch (object)
c906108c 10758 {
1e3ff5ad
AC
10759 case TARGET_OBJECT_AVR:
10760 query_type = 'R';
10761 break;
802188a7
RM
10762
10763 case TARGET_OBJECT_AUXV:
0876f84a 10764 gdb_assert (annex == NULL);
f6ac5f3d 10765 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
9b409511 10766 xfered_len,
0876f84a 10767 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 10768
23181151
DJ
10769 case TARGET_OBJECT_AVAILABLE_FEATURES:
10770 return remote_read_qxfer
f6ac5f3d 10771 ("features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
10772 &remote_protocol_packets[PACKET_qXfer_features]);
10773
cfa9d6d9
DJ
10774 case TARGET_OBJECT_LIBRARIES:
10775 return remote_read_qxfer
f6ac5f3d 10776 ("libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
10777 &remote_protocol_packets[PACKET_qXfer_libraries]);
10778
2268b414
JK
10779 case TARGET_OBJECT_LIBRARIES_SVR4:
10780 return remote_read_qxfer
f6ac5f3d 10781 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
10782 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10783
fd79ecee
DJ
10784 case TARGET_OBJECT_MEMORY_MAP:
10785 gdb_assert (annex == NULL);
f6ac5f3d 10786 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
9b409511 10787 xfered_len,
fd79ecee
DJ
10788 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10789
07e059b5
VP
10790 case TARGET_OBJECT_OSDATA:
10791 /* Should only get here if we're connected. */
5d93a237 10792 gdb_assert (rs->remote_desc);
07e059b5 10793 return remote_read_qxfer
f6ac5f3d 10794 ("osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
10795 &remote_protocol_packets[PACKET_qXfer_osdata]);
10796
dc146f7c
VP
10797 case TARGET_OBJECT_THREADS:
10798 gdb_assert (annex == NULL);
f6ac5f3d 10799 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
9b409511 10800 xfered_len,
dc146f7c
VP
10801 &remote_protocol_packets[PACKET_qXfer_threads]);
10802
b3b9301e
PA
10803 case TARGET_OBJECT_TRACEFRAME_INFO:
10804 gdb_assert (annex == NULL);
10805 return remote_read_qxfer
f6ac5f3d 10806 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 10807 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
10808
10809 case TARGET_OBJECT_FDPIC:
f6ac5f3d 10810 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
9b409511 10811 xfered_len,
78d85199 10812 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
10813
10814 case TARGET_OBJECT_OPENVMS_UIB:
f6ac5f3d 10815 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
9b409511 10816 xfered_len,
169081d0
TG
10817 &remote_protocol_packets[PACKET_qXfer_uib]);
10818
9accd112 10819 case TARGET_OBJECT_BTRACE:
f6ac5f3d 10820 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
9b409511 10821 xfered_len,
9accd112
MM
10822 &remote_protocol_packets[PACKET_qXfer_btrace]);
10823
f4abbc16 10824 case TARGET_OBJECT_BTRACE_CONF:
f6ac5f3d 10825 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
f4abbc16
MM
10826 len, xfered_len,
10827 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10828
c78fa86a 10829 case TARGET_OBJECT_EXEC_FILE:
f6ac5f3d 10830 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
c78fa86a
GB
10831 len, xfered_len,
10832 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10833
1e3ff5ad 10834 default:
2ed4b548 10835 return TARGET_XFER_E_IO;
c906108c
SS
10836 }
10837
0df8b418 10838 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 10839 large enough let the caller deal with it. */
ea9c271d 10840 if (len < get_remote_packet_size ())
2ed4b548 10841 return TARGET_XFER_E_IO;
ea9c271d 10842 len = get_remote_packet_size ();
1e3ff5ad 10843
23860348 10844 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 10845 if (!rs->remote_desc)
8a3fe4f8 10846 error (_("remote query is only available after target open"));
c906108c 10847
1e3ff5ad 10848 gdb_assert (annex != NULL);
4b8a223f 10849 gdb_assert (readbuf != NULL);
c906108c 10850
6d820c5c 10851 p2 = rs->buf;
c906108c
SS
10852 *p2++ = 'q';
10853 *p2++ = query_type;
10854
23860348
MS
10855 /* We used one buffer char for the remote protocol q command and
10856 another for the query type. As the remote protocol encapsulation
10857 uses 4 chars plus one extra in case we are debugging
10858 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10859 string. */
c906108c 10860 i = 0;
ea9c271d 10861 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 10862 {
1e3ff5ad
AC
10863 /* Bad caller may have sent forbidden characters. */
10864 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10865 *p2++ = annex[i];
c906108c
SS
10866 i++;
10867 }
1e3ff5ad
AC
10868 *p2 = '\0';
10869 gdb_assert (annex[i] == '\0');
c906108c 10870
6d820c5c 10871 i = putpkt (rs->buf);
c5aa993b 10872 if (i < 0)
2ed4b548 10873 return TARGET_XFER_E_IO;
c906108c 10874
6d820c5c
DJ
10875 getpkt (&rs->buf, &rs->buf_size, 0);
10876 strcpy ((char *) readbuf, rs->buf);
c906108c 10877
9b409511 10878 *xfered_len = strlen ((char *) readbuf);
92ffd475 10879 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
10880}
10881
09c98b44
DB
10882/* Implementation of to_get_memory_xfer_limit. */
10883
f6ac5f3d
PA
10884ULONGEST
10885remote_target::get_memory_xfer_limit ()
09c98b44
DB
10886{
10887 return get_memory_write_packet_size ();
10888}
10889
f6ac5f3d
PA
10890int
10891remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
10892 const gdb_byte *pattern, ULONGEST pattern_len,
10893 CORE_ADDR *found_addrp)
08388c79 10894{
f5656ead 10895 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
10896 struct remote_state *rs = get_remote_state ();
10897 int max_size = get_memory_write_packet_size ();
10898 struct packet_config *packet =
10899 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
10900 /* Number of packet bytes used to encode the pattern;
10901 this could be more than PATTERN_LEN due to escape characters. */
08388c79 10902 int escaped_pattern_len;
0df8b418 10903 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
10904 int used_pattern_len;
10905 int i;
10906 int found;
10907 ULONGEST found_addr;
10908
7cc244de
PA
10909 /* Don't go to the target if we don't have to. This is done before
10910 checking packet_config_support to avoid the possibility that a
10911 success for this edge case means the facility works in
10912 general. */
08388c79
DE
10913 if (pattern_len > search_space_len)
10914 return 0;
10915 if (pattern_len == 0)
10916 {
10917 *found_addrp = start_addr;
10918 return 1;
10919 }
10920
10921 /* If we already know the packet isn't supported, fall back to the simple
10922 way of searching memory. */
10923
4082afcc 10924 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
10925 {
10926 /* Target doesn't provided special support, fall back and use the
10927 standard support (copy memory and do the search here). */
f6ac5f3d 10928 return simple_search_memory (this, start_addr, search_space_len,
08388c79
DE
10929 pattern, pattern_len, found_addrp);
10930 }
10931
28439a30
PA
10932 /* Make sure the remote is pointing at the right process. */
10933 set_general_process ();
10934
08388c79
DE
10935 /* Insert header. */
10936 i = snprintf (rs->buf, max_size,
10937 "qSearch:memory:%s;%s;",
5af949e3 10938 phex_nz (start_addr, addr_size),
08388c79
DE
10939 phex_nz (search_space_len, sizeof (search_space_len)));
10940 max_size -= (i + 1);
10941
10942 /* Escape as much data as fits into rs->buf. */
10943 escaped_pattern_len =
124e13d9 10944 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
10945 &used_pattern_len, max_size);
10946
10947 /* Bail if the pattern is too large. */
10948 if (used_pattern_len != pattern_len)
9b20d036 10949 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
10950
10951 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10952 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10953 || packet_ok (rs->buf, packet) != PACKET_OK)
10954 {
10955 /* The request may not have worked because the command is not
10956 supported. If so, fall back to the simple way. */
7cc244de 10957 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79 10958 {
f6ac5f3d 10959 return simple_search_memory (this, start_addr, search_space_len,
08388c79
DE
10960 pattern, pattern_len, found_addrp);
10961 }
10962 return -1;
10963 }
10964
10965 if (rs->buf[0] == '0')
10966 found = 0;
10967 else if (rs->buf[0] == '1')
10968 {
10969 found = 1;
10970 if (rs->buf[1] != ',')
10e0fa18 10971 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10972 unpack_varlen_hex (rs->buf + 2, &found_addr);
10973 *found_addrp = found_addr;
10974 }
10975 else
10e0fa18 10976 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10977
10978 return found;
10979}
10980
f6ac5f3d
PA
10981void
10982remote_target::rcmd (const char *command, struct ui_file *outbuf)
96baa820 10983{
d01949b6 10984 struct remote_state *rs = get_remote_state ();
2e9f7625 10985 char *p = rs->buf;
96baa820 10986
5d93a237 10987 if (!rs->remote_desc)
8a3fe4f8 10988 error (_("remote rcmd is only available after target open"));
96baa820 10989
23860348 10990 /* Send a NULL command across as an empty command. */
7be570e7
JM
10991 if (command == NULL)
10992 command = "";
10993
23860348 10994 /* The query prefix. */
2e9f7625
DJ
10995 strcpy (rs->buf, "qRcmd,");
10996 p = strchr (rs->buf, '\0');
96baa820 10997
3e43a32a
MS
10998 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10999 > get_remote_packet_size ())
8a3fe4f8 11000 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 11001
23860348 11002 /* Encode the actual command. */
a30bf1f1 11003 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 11004
6d820c5c 11005 if (putpkt (rs->buf) < 0)
8a3fe4f8 11006 error (_("Communication problem with target."));
96baa820
JM
11007
11008 /* get/display the response */
11009 while (1)
11010 {
2e9f7625
DJ
11011 char *buf;
11012
00bf0b85 11013 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 11014 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 11015 rs->buf[0] = '\0';
5b37825d
PW
11016 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11017 {
11018 /* Timeout. Continue to (try to) read responses.
11019 This is better than stopping with an error, assuming the stub
11020 is still executing the (long) monitor command.
11021 If needed, the user can interrupt gdb using C-c, obtaining
11022 an effect similar to stop on timeout. */
11023 continue;
11024 }
2e9f7625 11025 buf = rs->buf;
96baa820 11026 if (buf[0] == '\0')
8a3fe4f8 11027 error (_("Target does not support this command."));
96baa820
JM
11028 if (buf[0] == 'O' && buf[1] != 'K')
11029 {
23860348 11030 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
11031 continue;
11032 }
11033 if (strcmp (buf, "OK") == 0)
11034 break;
7be570e7
JM
11035 if (strlen (buf) == 3 && buf[0] == 'E'
11036 && isdigit (buf[1]) && isdigit (buf[2]))
11037 {
8a3fe4f8 11038 error (_("Protocol error with Rcmd"));
7be570e7 11039 }
96baa820
JM
11040 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11041 {
11042 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 11043
96baa820
JM
11044 fputc_unfiltered (c, outbuf);
11045 }
11046 break;
11047 }
11048}
11049
f6ac5f3d
PA
11050std::vector<mem_region>
11051remote_target::memory_map ()
fd79ecee 11052{
a664f67e 11053 std::vector<mem_region> result;
9018be22 11054 gdb::optional<gdb::char_vector> text
f6ac5f3d 11055 = target_read_stralloc (target_stack, TARGET_OBJECT_MEMORY_MAP, NULL);
fd79ecee
DJ
11056
11057 if (text)
9018be22 11058 result = parse_memory_map (text->data ());
fd79ecee
DJ
11059
11060 return result;
11061}
11062
c906108c 11063static void
ac88e2de 11064packet_command (const char *args, int from_tty)
c906108c 11065{
d01949b6 11066 struct remote_state *rs = get_remote_state ();
c906108c 11067
5d93a237 11068 if (!rs->remote_desc)
8a3fe4f8 11069 error (_("command can only be used with remote target"));
c906108c 11070
c5aa993b 11071 if (!args)
8a3fe4f8 11072 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
11073
11074 puts_filtered ("sending: ");
11075 print_packet (args);
11076 puts_filtered ("\n");
11077 putpkt (args);
11078
6d820c5c 11079 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 11080 puts_filtered ("received: ");
6d820c5c 11081 print_packet (rs->buf);
c906108c
SS
11082 puts_filtered ("\n");
11083}
11084
11085#if 0
23860348 11086/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 11087
a14ed312 11088static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 11089
a14ed312 11090static void threadset_test_cmd (char *cmd, int tty);
c906108c 11091
a14ed312 11092static void threadalive_test (char *cmd, int tty);
c906108c 11093
a14ed312 11094static void threadlist_test_cmd (char *cmd, int tty);
c906108c 11095
23860348 11096int get_and_display_threadinfo (threadref *ref);
c906108c 11097
a14ed312 11098static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 11099
23860348 11100static int thread_display_step (threadref *ref, void *context);
c906108c 11101
a14ed312 11102static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 11103
a14ed312 11104static void init_remote_threadtests (void);
c906108c 11105
23860348 11106#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
11107
11108static void
0b39b52e 11109threadset_test_cmd (const char *cmd, int tty)
c906108c
SS
11110{
11111 int sample_thread = SAMPLE_THREAD;
11112
a3f17187 11113 printf_filtered (_("Remote threadset test\n"));
79d7f229 11114 set_general_thread (sample_thread);
c906108c
SS
11115}
11116
11117
11118static void
0b39b52e 11119threadalive_test (const char *cmd, int tty)
c906108c
SS
11120{
11121 int sample_thread = SAMPLE_THREAD;
79d7f229 11122 int pid = ptid_get_pid (inferior_ptid);
ba348170 11123 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 11124
79d7f229 11125 if (remote_thread_alive (ptid))
c906108c
SS
11126 printf_filtered ("PASS: Thread alive test\n");
11127 else
11128 printf_filtered ("FAIL: Thread alive test\n");
11129}
11130
23860348 11131void output_threadid (char *title, threadref *ref);
c906108c
SS
11132
11133void
fba45db2 11134output_threadid (char *title, threadref *ref)
c906108c
SS
11135{
11136 char hexid[20];
11137
23860348 11138 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
11139 hexid[16] = 0;
11140 printf_filtered ("%s %s\n", title, (&hexid[0]));
11141}
11142
11143static void
0b39b52e 11144threadlist_test_cmd (const char *cmd, int tty)
c906108c
SS
11145{
11146 int startflag = 1;
11147 threadref nextthread;
11148 int done, result_count;
11149 threadref threadlist[3];
11150
11151 printf_filtered ("Remote Threadlist test\n");
11152 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11153 &result_count, &threadlist[0]))
11154 printf_filtered ("FAIL: threadlist test\n");
11155 else
11156 {
11157 threadref *scan = threadlist;
11158 threadref *limit = scan + result_count;
11159
11160 while (scan < limit)
11161 output_threadid (" thread ", scan++);
11162 }
11163}
11164
11165void
fba45db2 11166display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
11167{
11168 output_threadid ("Threadid: ", &info->threadid);
11169 printf_filtered ("Name: %s\n ", info->shortname);
11170 printf_filtered ("State: %s\n", info->display);
11171 printf_filtered ("other: %s\n\n", info->more_display);
11172}
11173
11174int
fba45db2 11175get_and_display_threadinfo (threadref *ref)
c906108c
SS
11176{
11177 int result;
11178 int set;
11179 struct gdb_ext_thread_info threadinfo;
11180
11181 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11182 | TAG_MOREDISPLAY | TAG_DISPLAY;
11183 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11184 display_thread_info (&threadinfo);
11185 return result;
11186}
11187
11188static void
0b39b52e 11189threadinfo_test_cmd (const char *cmd, int tty)
c906108c
SS
11190{
11191 int athread = SAMPLE_THREAD;
11192 threadref thread;
11193 int set;
11194
11195 int_to_threadref (&thread, athread);
11196 printf_filtered ("Remote Threadinfo test\n");
11197 if (!get_and_display_threadinfo (&thread))
11198 printf_filtered ("FAIL cannot get thread info\n");
11199}
11200
11201static int
fba45db2 11202thread_display_step (threadref *ref, void *context)
c906108c
SS
11203{
11204 /* output_threadid(" threadstep ",ref); *//* simple test */
11205 return get_and_display_threadinfo (ref);
11206}
11207
11208static void
0b39b52e 11209threadlist_update_test_cmd (const char *cmd, int tty)
c906108c
SS
11210{
11211 printf_filtered ("Remote Threadlist update test\n");
11212 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11213}
11214
11215static void
11216init_remote_threadtests (void)
11217{
3e43a32a
MS
11218 add_com ("tlist", class_obscure, threadlist_test_cmd,
11219 _("Fetch and print the remote list of "
11220 "thread identifiers, one pkt only"));
c906108c 11221 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 11222 _("Fetch and display info about one thread"));
c906108c 11223 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 11224 _("Test setting to a different thread"));
c906108c 11225 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 11226 _("Iterate through updating all remote thread info"));
c906108c 11227 add_com ("talive", class_obscure, threadalive_test,
1bedd215 11228 _(" Remote thread alive test "));
c906108c
SS
11229}
11230
11231#endif /* 0 */
11232
f3fb8c85
MS
11233/* Convert a thread ID to a string. Returns the string in a static
11234 buffer. */
11235
f6ac5f3d
PA
11236const char *
11237remote_target::pid_to_str (ptid_t ptid)
f3fb8c85 11238{
79d7f229 11239 static char buf[64];
82f73884 11240 struct remote_state *rs = get_remote_state ();
f3fb8c85 11241
7cee1e54
PA
11242 if (ptid_equal (ptid, null_ptid))
11243 return normal_pid_to_str (ptid);
11244 else if (ptid_is_pid (ptid))
ecd0ada5
PA
11245 {
11246 /* Printing an inferior target id. */
11247
11248 /* When multi-process extensions are off, there's no way in the
11249 remote protocol to know the remote process id, if there's any
11250 at all. There's one exception --- when we're connected with
11251 target extended-remote, and we manually attached to a process
11252 with "attach PID". We don't record anywhere a flag that
11253 allows us to distinguish that case from the case of
11254 connecting with extended-remote and the stub already being
11255 attached to a process, and reporting yes to qAttached, hence
11256 no smart special casing here. */
11257 if (!remote_multi_process_p (rs))
11258 {
11259 xsnprintf (buf, sizeof buf, "Remote target");
11260 return buf;
11261 }
11262
11263 return normal_pid_to_str (ptid);
82f73884 11264 }
ecd0ada5 11265 else
79d7f229 11266 {
ecd0ada5
PA
11267 if (ptid_equal (magic_null_ptid, ptid))
11268 xsnprintf (buf, sizeof buf, "Thread <main>");
8020350c 11269 else if (remote_multi_process_p (rs))
de0d863e
DB
11270 if (ptid_get_lwp (ptid) == 0)
11271 return normal_pid_to_str (ptid);
11272 else
11273 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11274 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
11275 else
11276 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 11277 ptid_get_lwp (ptid));
79d7f229
PA
11278 return buf;
11279 }
f3fb8c85
MS
11280}
11281
38691318
KB
11282/* Get the address of the thread local variable in OBJFILE which is
11283 stored at OFFSET within the thread local storage for thread PTID. */
11284
f6ac5f3d
PA
11285CORE_ADDR
11286remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11287 CORE_ADDR offset)
38691318 11288{
4082afcc 11289 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
11290 {
11291 struct remote_state *rs = get_remote_state ();
6d820c5c 11292 char *p = rs->buf;
82f73884 11293 char *endp = rs->buf + get_remote_packet_size ();
571dd617 11294 enum packet_result result;
38691318
KB
11295
11296 strcpy (p, "qGetTLSAddr:");
11297 p += strlen (p);
82f73884 11298 p = write_ptid (p, endp, ptid);
38691318
KB
11299 *p++ = ',';
11300 p += hexnumstr (p, offset);
11301 *p++ = ',';
11302 p += hexnumstr (p, lm);
11303 *p++ = '\0';
11304
6d820c5c
DJ
11305 putpkt (rs->buf);
11306 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
11307 result = packet_ok (rs->buf,
11308 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 11309 if (result == PACKET_OK)
38691318
KB
11310 {
11311 ULONGEST result;
11312
6d820c5c 11313 unpack_varlen_hex (rs->buf, &result);
38691318
KB
11314 return result;
11315 }
571dd617 11316 else if (result == PACKET_UNKNOWN)
109c3e39
AC
11317 throw_error (TLS_GENERIC_ERROR,
11318 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 11319 else
109c3e39
AC
11320 throw_error (TLS_GENERIC_ERROR,
11321 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
11322 }
11323 else
109c3e39
AC
11324 throw_error (TLS_GENERIC_ERROR,
11325 _("TLS not supported or disabled on this target"));
38691318
KB
11326 /* Not reached. */
11327 return 0;
11328}
11329
711e434b
PM
11330/* Provide thread local base, i.e. Thread Information Block address.
11331 Returns 1 if ptid is found and thread_local_base is non zero. */
11332
f6ac5f3d
PA
11333int
11334remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
711e434b 11335{
4082afcc 11336 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
11337 {
11338 struct remote_state *rs = get_remote_state ();
11339 char *p = rs->buf;
11340 char *endp = rs->buf + get_remote_packet_size ();
11341 enum packet_result result;
11342
11343 strcpy (p, "qGetTIBAddr:");
11344 p += strlen (p);
11345 p = write_ptid (p, endp, ptid);
11346 *p++ = '\0';
11347
11348 putpkt (rs->buf);
11349 getpkt (&rs->buf, &rs->buf_size, 0);
11350 result = packet_ok (rs->buf,
11351 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11352 if (result == PACKET_OK)
11353 {
11354 ULONGEST result;
11355
11356 unpack_varlen_hex (rs->buf, &result);
11357 if (addr)
11358 *addr = (CORE_ADDR) result;
11359 return 1;
11360 }
11361 else if (result == PACKET_UNKNOWN)
11362 error (_("Remote target doesn't support qGetTIBAddr packet"));
11363 else
11364 error (_("Remote target failed to process qGetTIBAddr request"));
11365 }
11366 else
11367 error (_("qGetTIBAddr not supported or disabled on this target"));
11368 /* Not reached. */
11369 return 0;
11370}
11371
29709017
DJ
11372/* Support for inferring a target description based on the current
11373 architecture and the size of a 'g' packet. While the 'g' packet
11374 can have any size (since optional registers can be left off the
11375 end), some sizes are easily recognizable given knowledge of the
11376 approximate architecture. */
11377
11378struct remote_g_packet_guess
11379{
11380 int bytes;
11381 const struct target_desc *tdesc;
11382};
11383typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11384DEF_VEC_O(remote_g_packet_guess_s);
11385
11386struct remote_g_packet_data
11387{
11388 VEC(remote_g_packet_guess_s) *guesses;
11389};
11390
11391static struct gdbarch_data *remote_g_packet_data_handle;
11392
11393static void *
11394remote_g_packet_data_init (struct obstack *obstack)
11395{
11396 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11397}
11398
11399void
11400register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11401 const struct target_desc *tdesc)
11402{
11403 struct remote_g_packet_data *data
19ba03f4
SM
11404 = ((struct remote_g_packet_data *)
11405 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
11406 struct remote_g_packet_guess new_guess, *guess;
11407 int ix;
11408
11409 gdb_assert (tdesc != NULL);
11410
11411 for (ix = 0;
11412 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11413 ix++)
11414 if (guess->bytes == bytes)
11415 internal_error (__FILE__, __LINE__,
9b20d036 11416 _("Duplicate g packet description added for size %d"),
29709017
DJ
11417 bytes);
11418
11419 new_guess.bytes = bytes;
11420 new_guess.tdesc = tdesc;
11421 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11422}
11423
d962ef82
DJ
11424/* Return 1 if remote_read_description would do anything on this target
11425 and architecture, 0 otherwise. */
11426
11427static int
11428remote_read_description_p (struct target_ops *target)
11429{
11430 struct remote_g_packet_data *data
19ba03f4
SM
11431 = ((struct remote_g_packet_data *)
11432 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
11433
11434 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11435 return 1;
11436
11437 return 0;
11438}
11439
f6ac5f3d
PA
11440const struct target_desc *
11441remote_target::read_description ()
29709017
DJ
11442{
11443 struct remote_g_packet_data *data
19ba03f4
SM
11444 = ((struct remote_g_packet_data *)
11445 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 11446
d962ef82
DJ
11447 /* Do not try this during initial connection, when we do not know
11448 whether there is a running but stopped thread. */
11449 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
f6ac5f3d 11450 return beneath->read_description ();
d962ef82 11451
29709017
DJ
11452 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11453 {
11454 struct remote_g_packet_guess *guess;
11455 int ix;
11456 int bytes = send_g_packet ();
11457
11458 for (ix = 0;
11459 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11460 ix++)
11461 if (guess->bytes == bytes)
11462 return guess->tdesc;
11463
11464 /* We discard the g packet. A minor optimization would be to
11465 hold on to it, and fill the register cache once we have selected
11466 an architecture, but it's too tricky to do safely. */
11467 }
11468
f6ac5f3d 11469 return beneath->read_description ();
29709017
DJ
11470}
11471
a6b151f1
DJ
11472/* Remote file transfer support. This is host-initiated I/O, not
11473 target-initiated; for target-initiated, see remote-fileio.c. */
11474
11475/* If *LEFT is at least the length of STRING, copy STRING to
11476 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11477 decrease *LEFT. Otherwise raise an error. */
11478
11479static void
a121b7c1 11480remote_buffer_add_string (char **buffer, int *left, const char *string)
a6b151f1
DJ
11481{
11482 int len = strlen (string);
11483
11484 if (len > *left)
11485 error (_("Packet too long for target."));
11486
11487 memcpy (*buffer, string, len);
11488 *buffer += len;
11489 *left -= len;
11490
11491 /* NUL-terminate the buffer as a convenience, if there is
11492 room. */
11493 if (*left)
11494 **buffer = '\0';
11495}
11496
11497/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11498 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11499 decrease *LEFT. Otherwise raise an error. */
11500
11501static void
11502remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11503 int len)
11504{
11505 if (2 * len > *left)
11506 error (_("Packet too long for target."));
11507
11508 bin2hex (bytes, *buffer, len);
11509 *buffer += 2 * len;
11510 *left -= 2 * len;
11511
11512 /* NUL-terminate the buffer as a convenience, if there is
11513 room. */
11514 if (*left)
11515 **buffer = '\0';
11516}
11517
11518/* If *LEFT is large enough, convert VALUE to hex and add it to
11519 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11520 decrease *LEFT. Otherwise raise an error. */
11521
11522static void
11523remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11524{
11525 int len = hexnumlen (value);
11526
11527 if (len > *left)
11528 error (_("Packet too long for target."));
11529
11530 hexnumstr (*buffer, value);
11531 *buffer += len;
11532 *left -= len;
11533
11534 /* NUL-terminate the buffer as a convenience, if there is
11535 room. */
11536 if (*left)
11537 **buffer = '\0';
11538}
11539
11540/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11541 value, *REMOTE_ERRNO to the remote error number or zero if none
11542 was included, and *ATTACHMENT to point to the start of the annex
11543 if any. The length of the packet isn't needed here; there may
11544 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11545
11546 Return 0 if the packet could be parsed, -1 if it could not. If
11547 -1 is returned, the other variables may not be initialized. */
11548
11549static int
11550remote_hostio_parse_result (char *buffer, int *retcode,
11551 int *remote_errno, char **attachment)
11552{
11553 char *p, *p2;
11554
11555 *remote_errno = 0;
11556 *attachment = NULL;
11557
11558 if (buffer[0] != 'F')
11559 return -1;
11560
11561 errno = 0;
11562 *retcode = strtol (&buffer[1], &p, 16);
11563 if (errno != 0 || p == &buffer[1])
11564 return -1;
11565
11566 /* Check for ",errno". */
11567 if (*p == ',')
11568 {
11569 errno = 0;
11570 *remote_errno = strtol (p + 1, &p2, 16);
11571 if (errno != 0 || p + 1 == p2)
11572 return -1;
11573 p = p2;
11574 }
11575
11576 /* Check for ";attachment". If there is no attachment, the
11577 packet should end here. */
11578 if (*p == ';')
11579 {
11580 *attachment = p + 1;
11581 return 0;
11582 }
11583 else if (*p == '\0')
11584 return 0;
11585 else
11586 return -1;
11587}
11588
11589/* Send a prepared I/O packet to the target and read its response.
11590 The prepared packet is in the global RS->BUF before this function
11591 is called, and the answer is there when we return.
11592
11593 COMMAND_BYTES is the length of the request to send, which may include
11594 binary data. WHICH_PACKET is the packet configuration to check
11595 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11596 is set to the error number and -1 is returned. Otherwise the value
11597 returned by the function is returned.
11598
11599 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11600 attachment is expected; an error will be reported if there's a
11601 mismatch. If one is found, *ATTACHMENT will be set to point into
11602 the packet buffer and *ATTACHMENT_LEN will be set to the
11603 attachment's length. */
11604
11605static int
11606remote_hostio_send_command (int command_bytes, int which_packet,
11607 int *remote_errno, char **attachment,
11608 int *attachment_len)
11609{
11610 struct remote_state *rs = get_remote_state ();
11611 int ret, bytes_read;
11612 char *attachment_tmp;
11613
20db9c52 11614 if (packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
11615 {
11616 *remote_errno = FILEIO_ENOSYS;
11617 return -1;
11618 }
11619
11620 putpkt_binary (rs->buf, command_bytes);
11621 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11622
11623 /* If it timed out, something is wrong. Don't try to parse the
11624 buffer. */
11625 if (bytes_read < 0)
11626 {
11627 *remote_errno = FILEIO_EINVAL;
11628 return -1;
11629 }
11630
11631 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11632 {
11633 case PACKET_ERROR:
11634 *remote_errno = FILEIO_EINVAL;
11635 return -1;
11636 case PACKET_UNKNOWN:
11637 *remote_errno = FILEIO_ENOSYS;
11638 return -1;
11639 case PACKET_OK:
11640 break;
11641 }
11642
11643 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11644 &attachment_tmp))
11645 {
11646 *remote_errno = FILEIO_EINVAL;
11647 return -1;
11648 }
11649
11650 /* Make sure we saw an attachment if and only if we expected one. */
11651 if ((attachment_tmp == NULL && attachment != NULL)
11652 || (attachment_tmp != NULL && attachment == NULL))
11653 {
11654 *remote_errno = FILEIO_EINVAL;
11655 return -1;
11656 }
11657
11658 /* If an attachment was found, it must point into the packet buffer;
11659 work out how many bytes there were. */
11660 if (attachment_tmp != NULL)
11661 {
11662 *attachment = attachment_tmp;
11663 *attachment_len = bytes_read - (*attachment - rs->buf);
11664 }
11665
11666 return ret;
11667}
11668
80152258
PA
11669/* Invalidate the readahead cache. */
11670
11671static void
11672readahead_cache_invalidate (void)
11673{
11674 struct remote_state *rs = get_remote_state ();
11675
11676 rs->readahead_cache.fd = -1;
11677}
11678
11679/* Invalidate the readahead cache if it is holding data for FD. */
11680
11681static void
11682readahead_cache_invalidate_fd (int fd)
11683{
11684 struct remote_state *rs = get_remote_state ();
11685
11686 if (rs->readahead_cache.fd == fd)
11687 rs->readahead_cache.fd = -1;
11688}
11689
15a201c8
GB
11690/* Set the filesystem remote_hostio functions that take FILENAME
11691 arguments will use. Return 0 on success, or -1 if an error
11692 occurs (and set *REMOTE_ERRNO). */
11693
11694static int
11695remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11696{
11697 struct remote_state *rs = get_remote_state ();
11698 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11699 char *p = rs->buf;
11700 int left = get_remote_packet_size () - 1;
11701 char arg[9];
11702 int ret;
11703
11704 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11705 return 0;
11706
11707 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11708 return 0;
11709
11710 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11711
11712 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11713 remote_buffer_add_string (&p, &left, arg);
11714
11715 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11716 remote_errno, NULL, NULL);
11717
11718 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11719 return 0;
11720
11721 if (ret == 0)
11722 rs->fs_pid = required_pid;
11723
11724 return ret;
11725}
11726
12e2a5fd 11727/* Implementation of to_fileio_open. */
a6b151f1
DJ
11728
11729static int
cd897586 11730remote_hostio_open (struct target_ops *self,
07c138c8 11731 struct inferior *inf, const char *filename,
4313b8c0
GB
11732 int flags, int mode, int warn_if_slow,
11733 int *remote_errno)
a6b151f1
DJ
11734{
11735 struct remote_state *rs = get_remote_state ();
11736 char *p = rs->buf;
11737 int left = get_remote_packet_size () - 1;
11738
4313b8c0
GB
11739 if (warn_if_slow)
11740 {
11741 static int warning_issued = 0;
11742
11743 printf_unfiltered (_("Reading %s from remote target...\n"),
11744 filename);
11745
11746 if (!warning_issued)
11747 {
11748 warning (_("File transfers from remote targets can be slow."
11749 " Use \"set sysroot\" to access files locally"
11750 " instead."));
11751 warning_issued = 1;
11752 }
11753 }
11754
15a201c8
GB
11755 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11756 return -1;
11757
a6b151f1
DJ
11758 remote_buffer_add_string (&p, &left, "vFile:open:");
11759
11760 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11761 strlen (filename));
11762 remote_buffer_add_string (&p, &left, ",");
11763
11764 remote_buffer_add_int (&p, &left, flags);
11765 remote_buffer_add_string (&p, &left, ",");
11766
11767 remote_buffer_add_int (&p, &left, mode);
11768
11769 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11770 remote_errno, NULL, NULL);
11771}
11772
f6ac5f3d
PA
11773int
11774remote_target::fileio_open (struct inferior *inf, const char *filename,
11775 int flags, int mode, int warn_if_slow,
11776 int *remote_errno)
11777{
11778 return remote_hostio_open (this, inf, filename, flags, mode, warn_if_slow,
11779 remote_errno);
11780}
11781
12e2a5fd 11782/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
11783
11784static int
0d866f62
TT
11785remote_hostio_pwrite (struct target_ops *self,
11786 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
11787 ULONGEST offset, int *remote_errno)
11788{
11789 struct remote_state *rs = get_remote_state ();
11790 char *p = rs->buf;
11791 int left = get_remote_packet_size ();
11792 int out_len;
11793
80152258
PA
11794 readahead_cache_invalidate_fd (fd);
11795
a6b151f1
DJ
11796 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11797
11798 remote_buffer_add_int (&p, &left, fd);
11799 remote_buffer_add_string (&p, &left, ",");
11800
11801 remote_buffer_add_int (&p, &left, offset);
11802 remote_buffer_add_string (&p, &left, ",");
11803
124e13d9 11804 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
11805 get_remote_packet_size () - (p - rs->buf));
11806
11807 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11808 remote_errno, NULL, NULL);
11809}
11810
f6ac5f3d
PA
11811int
11812remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
11813 ULONGEST offset, int *remote_errno)
11814{
11815 return remote_hostio_pwrite (this, fd, write_buf, len, offset, remote_errno);
11816}
11817
80152258
PA
11818/* Helper for the implementation of to_fileio_pread. Read the file
11819 from the remote side with vFile:pread. */
a6b151f1
DJ
11820
11821static int
80152258
PA
11822remote_hostio_pread_vFile (struct target_ops *self,
11823 int fd, gdb_byte *read_buf, int len,
11824 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
11825{
11826 struct remote_state *rs = get_remote_state ();
11827 char *p = rs->buf;
11828 char *attachment;
11829 int left = get_remote_packet_size ();
11830 int ret, attachment_len;
11831 int read_len;
11832
11833 remote_buffer_add_string (&p, &left, "vFile:pread:");
11834
11835 remote_buffer_add_int (&p, &left, fd);
11836 remote_buffer_add_string (&p, &left, ",");
11837
11838 remote_buffer_add_int (&p, &left, len);
11839 remote_buffer_add_string (&p, &left, ",");
11840
11841 remote_buffer_add_int (&p, &left, offset);
11842
11843 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11844 remote_errno, &attachment,
11845 &attachment_len);
11846
11847 if (ret < 0)
11848 return ret;
11849
bc20a4af 11850 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
11851 read_buf, len);
11852 if (read_len != ret)
11853 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11854
11855 return ret;
11856}
11857
80152258
PA
11858/* Serve pread from the readahead cache. Returns number of bytes
11859 read, or 0 if the request can't be served from the cache. */
11860
11861static int
11862remote_hostio_pread_from_cache (struct remote_state *rs,
11863 int fd, gdb_byte *read_buf, size_t len,
11864 ULONGEST offset)
11865{
11866 struct readahead_cache *cache = &rs->readahead_cache;
11867
11868 if (cache->fd == fd
11869 && cache->offset <= offset
11870 && offset < cache->offset + cache->bufsize)
11871 {
11872 ULONGEST max = cache->offset + cache->bufsize;
11873
11874 if (offset + len > max)
11875 len = max - offset;
11876
11877 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11878 return len;
11879 }
11880
11881 return 0;
11882}
11883
11884/* Implementation of to_fileio_pread. */
11885
11886static int
11887remote_hostio_pread (struct target_ops *self,
11888 int fd, gdb_byte *read_buf, int len,
11889 ULONGEST offset, int *remote_errno)
11890{
11891 int ret;
11892 struct remote_state *rs = get_remote_state ();
11893 struct readahead_cache *cache = &rs->readahead_cache;
11894
11895 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11896 if (ret > 0)
11897 {
11898 cache->hit_count++;
11899
11900 if (remote_debug)
11901 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11902 pulongest (cache->hit_count));
11903 return ret;
11904 }
11905
11906 cache->miss_count++;
11907 if (remote_debug)
11908 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11909 pulongest (cache->miss_count));
11910
11911 cache->fd = fd;
11912 cache->offset = offset;
11913 cache->bufsize = get_remote_packet_size ();
224c3ddb 11914 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258
PA
11915
11916 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11917 cache->offset, remote_errno);
11918 if (ret <= 0)
11919 {
11920 readahead_cache_invalidate_fd (fd);
11921 return ret;
11922 }
11923
11924 cache->bufsize = ret;
11925 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11926}
11927
f6ac5f3d
PA
11928int
11929remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
11930 ULONGEST offset, int *remote_errno)
11931{
11932 return remote_hostio_pread (this, fd, read_buf, len, offset, remote_errno);
11933}
11934
12e2a5fd 11935/* Implementation of to_fileio_close. */
a6b151f1
DJ
11936
11937static int
df39ea25 11938remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
11939{
11940 struct remote_state *rs = get_remote_state ();
11941 char *p = rs->buf;
11942 int left = get_remote_packet_size () - 1;
11943
80152258
PA
11944 readahead_cache_invalidate_fd (fd);
11945
a6b151f1
DJ
11946 remote_buffer_add_string (&p, &left, "vFile:close:");
11947
11948 remote_buffer_add_int (&p, &left, fd);
11949
11950 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11951 remote_errno, NULL, NULL);
11952}
11953
f6ac5f3d
PA
11954int
11955remote_target::fileio_close (int fd, int *remote_errno)
11956{
11957 return remote_hostio_close (this, fd, remote_errno);
11958}
11959
12e2a5fd 11960/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
11961
11962static int
dbbca37d 11963remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
11964 struct inferior *inf, const char *filename,
11965 int *remote_errno)
a6b151f1
DJ
11966{
11967 struct remote_state *rs = get_remote_state ();
11968 char *p = rs->buf;
11969 int left = get_remote_packet_size () - 1;
11970
15a201c8
GB
11971 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11972 return -1;
11973
a6b151f1
DJ
11974 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11975
11976 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11977 strlen (filename));
11978
11979 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11980 remote_errno, NULL, NULL);
11981}
11982
f6ac5f3d
PA
11983int
11984remote_target::fileio_unlink (struct inferior *inf, const char *filename,
11985 int *remote_errno)
11986{
11987 return remote_hostio_unlink (this, inf, filename, remote_errno);
11988}
11989
12e2a5fd 11990/* Implementation of to_fileio_readlink. */
b9e7b9c3 11991
f6ac5f3d
PA
11992gdb::optional<std::string>
11993remote_target::fileio_readlink (struct inferior *inf, const char *filename,
11994 int *remote_errno)
b9e7b9c3
UW
11995{
11996 struct remote_state *rs = get_remote_state ();
11997 char *p = rs->buf;
11998 char *attachment;
11999 int left = get_remote_packet_size ();
12000 int len, attachment_len;
12001 int read_len;
b9e7b9c3 12002
15a201c8 12003 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
e0d3522b 12004 return {};
15a201c8 12005
b9e7b9c3
UW
12006 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12007
12008 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12009 strlen (filename));
12010
12011 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12012 remote_errno, &attachment,
12013 &attachment_len);
12014
12015 if (len < 0)
e0d3522b 12016 return {};
b9e7b9c3 12017
e0d3522b 12018 std::string ret (len, '\0');
b9e7b9c3 12019
bc20a4af 12020 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
e0d3522b 12021 (gdb_byte *) &ret[0], len);
b9e7b9c3
UW
12022 if (read_len != len)
12023 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12024
b9e7b9c3
UW
12025 return ret;
12026}
12027
12e2a5fd 12028/* Implementation of to_fileio_fstat. */
0a93529c 12029
f6ac5f3d
PA
12030int
12031remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
0a93529c
GB
12032{
12033 struct remote_state *rs = get_remote_state ();
12034 char *p = rs->buf;
12035 int left = get_remote_packet_size ();
12036 int attachment_len, ret;
12037 char *attachment;
12038 struct fio_stat fst;
12039 int read_len;
12040
464b0089
GB
12041 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12042
12043 remote_buffer_add_int (&p, &left, fd);
12044
12045 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12046 remote_errno, &attachment,
12047 &attachment_len);
12048 if (ret < 0)
0a93529c 12049 {
464b0089
GB
12050 if (*remote_errno != FILEIO_ENOSYS)
12051 return ret;
12052
0a93529c
GB
12053 /* Strictly we should return -1, ENOSYS here, but when
12054 "set sysroot remote:" was implemented in August 2008
12055 BFD's need for a stat function was sidestepped with
12056 this hack. This was not remedied until March 2015
12057 so we retain the previous behavior to avoid breaking
12058 compatibility.
12059
12060 Note that the memset is a March 2015 addition; older
12061 GDBs set st_size *and nothing else* so the structure
12062 would have garbage in all other fields. This might
12063 break something but retaining the previous behavior
12064 here would be just too wrong. */
12065
12066 memset (st, 0, sizeof (struct stat));
12067 st->st_size = INT_MAX;
12068 return 0;
12069 }
12070
0a93529c
GB
12071 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12072 (gdb_byte *) &fst, sizeof (fst));
12073
12074 if (read_len != ret)
12075 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12076
12077 if (read_len != sizeof (fst))
12078 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12079 read_len, (int) sizeof (fst));
12080
12081 remote_fileio_to_host_stat (&fst, st);
12082
12083 return 0;
12084}
12085
12e2a5fd 12086/* Implementation of to_filesystem_is_local. */
e3dd7556 12087
f6ac5f3d
PA
12088int
12089remote_target::filesystem_is_local ()
e3dd7556
GB
12090{
12091 /* Valgrind GDB presents itself as a remote target but works
12092 on the local filesystem: it does not implement remote get
12093 and users are not expected to set a sysroot. To handle
12094 this case we treat the remote filesystem as local if the
12095 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12096 does not support vFile:open. */
a3be80c3 12097 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
12098 {
12099 enum packet_support ps = packet_support (PACKET_vFile_open);
12100
12101 if (ps == PACKET_SUPPORT_UNKNOWN)
12102 {
12103 int fd, remote_errno;
12104
12105 /* Try opening a file to probe support. The supplied
12106 filename is irrelevant, we only care about whether
12107 the stub recognizes the packet or not. */
f6ac5f3d 12108 fd = remote_hostio_open (this, NULL, "just probing",
4313b8c0 12109 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
12110 &remote_errno);
12111
12112 if (fd >= 0)
f6ac5f3d 12113 remote_hostio_close (this, fd, &remote_errno);
e3dd7556
GB
12114
12115 ps = packet_support (PACKET_vFile_open);
12116 }
12117
12118 if (ps == PACKET_DISABLE)
12119 {
12120 static int warning_issued = 0;
12121
12122 if (!warning_issued)
12123 {
12124 warning (_("remote target does not support file"
12125 " transfer, attempting to access files"
12126 " from local filesystem."));
12127 warning_issued = 1;
12128 }
12129
12130 return 1;
12131 }
12132 }
12133
12134 return 0;
12135}
12136
a6b151f1
DJ
12137static int
12138remote_fileio_errno_to_host (int errnum)
12139{
12140 switch (errnum)
12141 {
12142 case FILEIO_EPERM:
12143 return EPERM;
12144 case FILEIO_ENOENT:
12145 return ENOENT;
12146 case FILEIO_EINTR:
12147 return EINTR;
12148 case FILEIO_EIO:
12149 return EIO;
12150 case FILEIO_EBADF:
12151 return EBADF;
12152 case FILEIO_EACCES:
12153 return EACCES;
12154 case FILEIO_EFAULT:
12155 return EFAULT;
12156 case FILEIO_EBUSY:
12157 return EBUSY;
12158 case FILEIO_EEXIST:
12159 return EEXIST;
12160 case FILEIO_ENODEV:
12161 return ENODEV;
12162 case FILEIO_ENOTDIR:
12163 return ENOTDIR;
12164 case FILEIO_EISDIR:
12165 return EISDIR;
12166 case FILEIO_EINVAL:
12167 return EINVAL;
12168 case FILEIO_ENFILE:
12169 return ENFILE;
12170 case FILEIO_EMFILE:
12171 return EMFILE;
12172 case FILEIO_EFBIG:
12173 return EFBIG;
12174 case FILEIO_ENOSPC:
12175 return ENOSPC;
12176 case FILEIO_ESPIPE:
12177 return ESPIPE;
12178 case FILEIO_EROFS:
12179 return EROFS;
12180 case FILEIO_ENOSYS:
12181 return ENOSYS;
12182 case FILEIO_ENAMETOOLONG:
12183 return ENAMETOOLONG;
12184 }
12185 return -1;
12186}
12187
12188static char *
12189remote_hostio_error (int errnum)
12190{
12191 int host_error = remote_fileio_errno_to_host (errnum);
12192
12193 if (host_error == -1)
12194 error (_("Unknown remote I/O error %d"), errnum);
12195 else
12196 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12197}
12198
a6b151f1
DJ
12199static void
12200remote_hostio_close_cleanup (void *opaque)
12201{
12202 int fd = *(int *) opaque;
12203 int remote_errno;
12204
df39ea25 12205 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
12206}
12207
12208void
12209remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12210{
12211 struct cleanup *back_to, *close_cleanup;
12212 int retcode, fd, remote_errno, bytes, io_size;
a6b151f1
DJ
12213 gdb_byte *buffer;
12214 int bytes_in_buffer;
12215 int saw_eof;
12216 ULONGEST offset;
5d93a237 12217 struct remote_state *rs = get_remote_state ();
a6b151f1 12218
5d93a237 12219 if (!rs->remote_desc)
a6b151f1
DJ
12220 error (_("command can only be used with remote target"));
12221
d419f42d 12222 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
12223 if (file == NULL)
12224 perror_with_name (local_file);
a6b151f1 12225
07c138c8 12226 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 12227 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1 12228 | FILEIO_O_TRUNC),
4313b8c0 12229 0700, 0, &remote_errno);
a6b151f1
DJ
12230 if (fd == -1)
12231 remote_hostio_error (remote_errno);
12232
12233 /* Send up to this many bytes at once. They won't all fit in the
12234 remote packet limit, so we'll transfer slightly fewer. */
12235 io_size = get_remote_packet_size ();
224c3ddb 12236 buffer = (gdb_byte *) xmalloc (io_size);
d419f42d 12237 back_to = make_cleanup (xfree, buffer);
a6b151f1
DJ
12238
12239 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12240
12241 bytes_in_buffer = 0;
12242 saw_eof = 0;
12243 offset = 0;
12244 while (bytes_in_buffer || !saw_eof)
12245 {
12246 if (!saw_eof)
12247 {
3e43a32a
MS
12248 bytes = fread (buffer + bytes_in_buffer, 1,
12249 io_size - bytes_in_buffer,
d419f42d 12250 file.get ());
a6b151f1
DJ
12251 if (bytes == 0)
12252 {
d419f42d 12253 if (ferror (file.get ()))
a6b151f1
DJ
12254 error (_("Error reading %s."), local_file);
12255 else
12256 {
12257 /* EOF. Unless there is something still in the
12258 buffer from the last iteration, we are done. */
12259 saw_eof = 1;
12260 if (bytes_in_buffer == 0)
12261 break;
12262 }
12263 }
12264 }
12265 else
12266 bytes = 0;
12267
12268 bytes += bytes_in_buffer;
12269 bytes_in_buffer = 0;
12270
0d866f62
TT
12271 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
12272 fd, buffer, bytes,
3e43a32a 12273 offset, &remote_errno);
a6b151f1
DJ
12274
12275 if (retcode < 0)
12276 remote_hostio_error (remote_errno);
12277 else if (retcode == 0)
12278 error (_("Remote write of %d bytes returned 0!"), bytes);
12279 else if (retcode < bytes)
12280 {
12281 /* Short write. Save the rest of the read data for the next
12282 write. */
12283 bytes_in_buffer = bytes - retcode;
12284 memmove (buffer, buffer + retcode, bytes_in_buffer);
12285 }
12286
12287 offset += retcode;
12288 }
12289
12290 discard_cleanups (close_cleanup);
df39ea25 12291 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
12292 remote_hostio_error (remote_errno);
12293
12294 if (from_tty)
12295 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12296 do_cleanups (back_to);
12297}
12298
12299void
12300remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12301{
12302 struct cleanup *back_to, *close_cleanup;
cea39f65 12303 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
12304 gdb_byte *buffer;
12305 ULONGEST offset;
5d93a237 12306 struct remote_state *rs = get_remote_state ();
a6b151f1 12307
5d93a237 12308 if (!rs->remote_desc)
a6b151f1
DJ
12309 error (_("command can only be used with remote target"));
12310
07c138c8 12311 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
4313b8c0
GB
12312 remote_file, FILEIO_O_RDONLY, 0, 0,
12313 &remote_errno);
a6b151f1
DJ
12314 if (fd == -1)
12315 remote_hostio_error (remote_errno);
12316
d419f42d 12317 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
12318 if (file == NULL)
12319 perror_with_name (local_file);
a6b151f1
DJ
12320
12321 /* Send up to this many bytes at once. They won't all fit in the
12322 remote packet limit, so we'll transfer slightly fewer. */
12323 io_size = get_remote_packet_size ();
224c3ddb 12324 buffer = (gdb_byte *) xmalloc (io_size);
d419f42d 12325 back_to = make_cleanup (xfree, buffer);
a6b151f1
DJ
12326
12327 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12328
12329 offset = 0;
12330 while (1)
12331 {
a3be983c
TT
12332 bytes = remote_hostio_pread (find_target_at (process_stratum),
12333 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
12334 if (bytes == 0)
12335 /* Success, but no bytes, means end-of-file. */
12336 break;
12337 if (bytes == -1)
12338 remote_hostio_error (remote_errno);
12339
12340 offset += bytes;
12341
d419f42d 12342 bytes = fwrite (buffer, 1, bytes, file.get ());
a6b151f1
DJ
12343 if (bytes == 0)
12344 perror_with_name (local_file);
12345 }
12346
12347 discard_cleanups (close_cleanup);
df39ea25 12348 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
12349 remote_hostio_error (remote_errno);
12350
12351 if (from_tty)
12352 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12353 do_cleanups (back_to);
12354}
12355
12356void
12357remote_file_delete (const char *remote_file, int from_tty)
12358{
12359 int retcode, remote_errno;
5d93a237 12360 struct remote_state *rs = get_remote_state ();
a6b151f1 12361
5d93a237 12362 if (!rs->remote_desc)
a6b151f1
DJ
12363 error (_("command can only be used with remote target"));
12364
dbbca37d 12365 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 12366 NULL, remote_file, &remote_errno);
a6b151f1
DJ
12367 if (retcode == -1)
12368 remote_hostio_error (remote_errno);
12369
12370 if (from_tty)
12371 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12372}
12373
12374static void
ac88e2de 12375remote_put_command (const char *args, int from_tty)
a6b151f1 12376{
d1a41061
PP
12377 if (args == NULL)
12378 error_no_arg (_("file to put"));
12379
773a1edc 12380 gdb_argv argv (args);
a6b151f1
DJ
12381 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12382 error (_("Invalid parameters to remote put"));
12383
12384 remote_file_put (argv[0], argv[1], from_tty);
a6b151f1
DJ
12385}
12386
12387static void
ac88e2de 12388remote_get_command (const char *args, int from_tty)
a6b151f1 12389{
d1a41061
PP
12390 if (args == NULL)
12391 error_no_arg (_("file to get"));
12392
773a1edc 12393 gdb_argv argv (args);
a6b151f1
DJ
12394 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12395 error (_("Invalid parameters to remote get"));
12396
12397 remote_file_get (argv[0], argv[1], from_tty);
a6b151f1
DJ
12398}
12399
12400static void
ac88e2de 12401remote_delete_command (const char *args, int from_tty)
a6b151f1 12402{
d1a41061
PP
12403 if (args == NULL)
12404 error_no_arg (_("file to delete"));
12405
773a1edc 12406 gdb_argv argv (args);
a6b151f1
DJ
12407 if (argv[0] == NULL || argv[1] != NULL)
12408 error (_("Invalid parameters to remote delete"));
12409
12410 remote_file_delete (argv[0], from_tty);
a6b151f1
DJ
12411}
12412
12413static void
981a3fb3 12414remote_command (const char *args, int from_tty)
a6b151f1 12415{
635c7e8a 12416 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
12417}
12418
f6ac5f3d
PA
12419int
12420remote_target::can_execute_reverse ()
b2175913 12421{
4082afcc
PA
12422 if (packet_support (PACKET_bs) == PACKET_ENABLE
12423 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
12424 return 1;
12425 else
12426 return 0;
b2175913
MS
12427}
12428
f6ac5f3d
PA
12429int
12430remote_target::supports_non_stop ()
74531fed
PA
12431{
12432 return 1;
12433}
12434
f6ac5f3d
PA
12435int
12436remote_target::supports_disable_randomization ()
03583c20
UW
12437{
12438 /* Only supported in extended mode. */
12439 return 0;
12440}
12441
f6ac5f3d
PA
12442int
12443remote_target::supports_multi_process ()
8a305172
PA
12444{
12445 struct remote_state *rs = get_remote_state ();
a744cf53 12446
8020350c 12447 return remote_multi_process_p (rs);
8a305172
PA
12448}
12449
70221824 12450static int
f6ac5f3d 12451remote_supports_cond_tracepoints ()
782b2b07 12452{
4082afcc 12453 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
12454}
12455
f6ac5f3d
PA
12456int
12457remote_target::supports_evaluation_of_breakpoint_conditions ()
3788aec7 12458{
4082afcc 12459 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
12460}
12461
70221824 12462static int
f6ac5f3d 12463remote_supports_fast_tracepoints ()
7a697b8d 12464{
4082afcc 12465 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
12466}
12467
0fb4aa4b 12468static int
f6ac5f3d 12469remote_supports_static_tracepoints ()
0fb4aa4b 12470{
4082afcc 12471 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
12472}
12473
1e4d1764 12474static int
f6ac5f3d 12475remote_supports_install_in_trace ()
1e4d1764 12476{
4082afcc 12477 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
12478}
12479
f6ac5f3d
PA
12480int
12481remote_target::supports_enable_disable_tracepoint ()
d248b706 12482{
4082afcc
PA
12483 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12484 == PACKET_ENABLE);
d248b706
KY
12485}
12486
f6ac5f3d
PA
12487int
12488remote_target::supports_string_tracing ()
3065dfb6 12489{
4082afcc 12490 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
12491}
12492
f6ac5f3d
PA
12493int
12494remote_target::can_run_breakpoint_commands ()
d3ce09f5 12495{
4082afcc 12496 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
12497}
12498
f6ac5f3d
PA
12499void
12500remote_target::trace_init ()
35b1e5cc 12501{
b6bb3468
PA
12502 struct remote_state *rs = get_remote_state ();
12503
35b1e5cc 12504 putpkt ("QTinit");
b6bb3468
PA
12505 remote_get_noisy_reply ();
12506 if (strcmp (rs->buf, "OK") != 0)
35b1e5cc
SS
12507 error (_("Target does not support this command."));
12508}
12509
409873ef
SS
12510/* Recursive routine to walk through command list including loops, and
12511 download packets for each command. */
12512
12513static void
12514remote_download_command_source (int num, ULONGEST addr,
12515 struct command_line *cmds)
12516{
12517 struct remote_state *rs = get_remote_state ();
12518 struct command_line *cmd;
12519
12520 for (cmd = cmds; cmd; cmd = cmd->next)
12521 {
0df8b418 12522 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
12523 strcpy (rs->buf, "QTDPsrc:");
12524 encode_source_string (num, addr, "cmd", cmd->line,
12525 rs->buf + strlen (rs->buf),
12526 rs->buf_size - strlen (rs->buf));
12527 putpkt (rs->buf);
b6bb3468
PA
12528 remote_get_noisy_reply ();
12529 if (strcmp (rs->buf, "OK"))
409873ef
SS
12530 warning (_("Target does not support source download."));
12531
12532 if (cmd->control_type == while_control
12533 || cmd->control_type == while_stepping_control)
12534 {
12535 remote_download_command_source (num, addr, *cmd->body_list);
12536
0df8b418 12537 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
12538 strcpy (rs->buf, "QTDPsrc:");
12539 encode_source_string (num, addr, "cmd", "end",
12540 rs->buf + strlen (rs->buf),
12541 rs->buf_size - strlen (rs->buf));
12542 putpkt (rs->buf);
b6bb3468
PA
12543 remote_get_noisy_reply ();
12544 if (strcmp (rs->buf, "OK"))
409873ef
SS
12545 warning (_("Target does not support source download."));
12546 }
12547 }
12548}
12549
f6ac5f3d
PA
12550void
12551remote_target::download_tracepoint (struct bp_location *loc)
35b1e5cc 12552{
bba74b36 12553#define BUF_SIZE 2048
e8ba3115 12554
35b1e5cc 12555 CORE_ADDR tpaddr;
409873ef 12556 char addrbuf[40];
bba74b36 12557 char buf[BUF_SIZE];
b44ec619
SM
12558 std::vector<std::string> tdp_actions;
12559 std::vector<std::string> stepping_actions;
35b1e5cc 12560 char *pkt;
e8ba3115 12561 struct breakpoint *b = loc->owner;
d9b3f62e 12562 struct tracepoint *t = (struct tracepoint *) b;
b6bb3468 12563 struct remote_state *rs = get_remote_state ();
35b1e5cc 12564
dc673c81 12565 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
12566
12567 tpaddr = loc->address;
12568 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
12569 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12570 addrbuf, /* address */
12571 (b->enable_state == bp_enabled ? 'E' : 'D'),
12572 t->step_count, t->pass_count);
e8ba3115
YQ
12573 /* Fast tracepoints are mostly handled by the target, but we can
12574 tell the target how big of an instruction block should be moved
12575 around. */
12576 if (b->type == bp_fast_tracepoint)
12577 {
12578 /* Only test for support at download time; we may not know
12579 target capabilities at definition time. */
12580 if (remote_supports_fast_tracepoints ())
35b1e5cc 12581 {
6b940e6a
PL
12582 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12583 NULL))
bba74b36 12584 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 12585 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 12586 else
e8ba3115
YQ
12587 /* If it passed validation at definition but fails now,
12588 something is very wrong. */
12589 internal_error (__FILE__, __LINE__,
12590 _("Fast tracepoint not "
12591 "valid during download"));
35b1e5cc 12592 }
e8ba3115
YQ
12593 else
12594 /* Fast tracepoints are functionally identical to regular
12595 tracepoints, so don't take lack of support as a reason to
12596 give up on the trace run. */
12597 warning (_("Target does not support fast tracepoints, "
12598 "downloading %d as regular tracepoint"), b->number);
12599 }
12600 else if (b->type == bp_static_tracepoint)
12601 {
12602 /* Only test for support at download time; we may not know
12603 target capabilities at definition time. */
12604 if (remote_supports_static_tracepoints ())
0fb4aa4b 12605 {
e8ba3115 12606 struct static_tracepoint_marker marker;
0fb4aa4b 12607
e8ba3115
YQ
12608 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12609 strcat (buf, ":S");
0fb4aa4b 12610 else
e8ba3115 12611 error (_("Static tracepoint not valid during download"));
0fb4aa4b 12612 }
e8ba3115
YQ
12613 else
12614 /* Fast tracepoints are functionally identical to regular
12615 tracepoints, so don't take lack of support as a reason
12616 to give up on the trace run. */
12617 error (_("Target does not support static tracepoints"));
12618 }
12619 /* If the tracepoint has a conditional, make it into an agent
12620 expression and append to the definition. */
12621 if (loc->cond)
12622 {
12623 /* Only test support at download time, we may not know target
12624 capabilities at definition time. */
12625 if (remote_supports_cond_tracepoints ())
35b1e5cc 12626 {
833177a4 12627 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
bba74b36
YQ
12628 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12629 aexpr->len);
e8ba3115 12630 pkt = buf + strlen (buf);
b44ec619 12631 for (int ndx = 0; ndx < aexpr->len; ++ndx)
e8ba3115
YQ
12632 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12633 *pkt = '\0';
35b1e5cc 12634 }
e8ba3115
YQ
12635 else
12636 warning (_("Target does not support conditional tracepoints, "
12637 "ignoring tp %d cond"), b->number);
12638 }
35b1e5cc 12639
d9b3f62e 12640 if (b->commands || *default_collect)
e8ba3115
YQ
12641 strcat (buf, "-");
12642 putpkt (buf);
b6bb3468
PA
12643 remote_get_noisy_reply ();
12644 if (strcmp (rs->buf, "OK"))
e8ba3115 12645 error (_("Target does not support tracepoints."));
35b1e5cc 12646
e8ba3115 12647 /* do_single_steps (t); */
b44ec619
SM
12648 for (auto action_it = tdp_actions.begin ();
12649 action_it != tdp_actions.end (); action_it++)
e8ba3115 12650 {
b44ec619
SM
12651 QUIT; /* Allow user to bail out with ^C. */
12652
12653 bool has_more = (action_it != tdp_actions.end ()
12654 || !stepping_actions.empty ());
12655
12656 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12657 b->number, addrbuf, /* address */
12658 action_it->c_str (),
12659 has_more ? '-' : 0);
12660 putpkt (buf);
12661 remote_get_noisy_reply ();
12662 if (strcmp (rs->buf, "OK"))
12663 error (_("Error on target while setting tracepoints."));
e8ba3115 12664 }
409873ef 12665
b44ec619
SM
12666 for (auto action_it = stepping_actions.begin ();
12667 action_it != stepping_actions.end (); action_it++)
12668 {
12669 QUIT; /* Allow user to bail out with ^C. */
12670
12671 bool is_first = action_it == stepping_actions.begin ();
12672 bool has_more = action_it != stepping_actions.end ();
12673
12674 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12675 b->number, addrbuf, /* address */
12676 is_first ? "S" : "",
12677 action_it->c_str (),
12678 has_more ? "-" : "");
12679 putpkt (buf);
12680 remote_get_noisy_reply ();
12681 if (strcmp (rs->buf, "OK"))
12682 error (_("Error on target while setting tracepoints."));
12683 }
12684
4082afcc 12685 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 12686 {
f00aae0f 12687 if (b->location != NULL)
409873ef 12688 {
e8ba3115 12689 strcpy (buf, "QTDPsrc:");
f00aae0f 12690 encode_source_string (b->number, loc->address, "at",
d28cd78a 12691 event_location_to_string (b->location.get ()),
f00aae0f 12692 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115 12693 putpkt (buf);
b6bb3468
PA
12694 remote_get_noisy_reply ();
12695 if (strcmp (rs->buf, "OK"))
e8ba3115 12696 warning (_("Target does not support source download."));
409873ef 12697 }
e8ba3115
YQ
12698 if (b->cond_string)
12699 {
12700 strcpy (buf, "QTDPsrc:");
12701 encode_source_string (b->number, loc->address,
12702 "cond", b->cond_string, buf + strlen (buf),
12703 2048 - strlen (buf));
12704 putpkt (buf);
b6bb3468
PA
12705 remote_get_noisy_reply ();
12706 if (strcmp (rs->buf, "OK"))
e8ba3115
YQ
12707 warning (_("Target does not support source download."));
12708 }
12709 remote_download_command_source (b->number, loc->address,
12710 breakpoint_commands (b));
35b1e5cc 12711 }
35b1e5cc
SS
12712}
12713
f6ac5f3d
PA
12714int
12715remote_target::can_download_tracepoint ()
1e4d1764 12716{
1e51243a
PA
12717 struct remote_state *rs = get_remote_state ();
12718 struct trace_status *ts;
12719 int status;
12720
12721 /* Don't try to install tracepoints until we've relocated our
12722 symbols, and fetched and merged the target's tracepoint list with
12723 ours. */
12724 if (rs->starting_up)
12725 return 0;
12726
12727 ts = current_trace_status ();
f6ac5f3d 12728 status = get_trace_status (ts);
1e4d1764
YQ
12729
12730 if (status == -1 || !ts->running_known || !ts->running)
12731 return 0;
12732
12733 /* If we are in a tracing experiment, but remote stub doesn't support
12734 installing tracepoint in trace, we have to return. */
12735 if (!remote_supports_install_in_trace ())
12736 return 0;
12737
12738 return 1;
12739}
12740
12741
f6ac5f3d
PA
12742void
12743remote_target::download_trace_state_variable (const trace_state_variable &tsv)
35b1e5cc
SS
12744{
12745 struct remote_state *rs = get_remote_state ();
00bf0b85 12746 char *p;
35b1e5cc 12747
bba74b36 12748 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
c252925c
SM
12749 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
12750 tsv.builtin);
00bf0b85 12751 p = rs->buf + strlen (rs->buf);
c252925c 12752 if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
00bf0b85 12753 error (_("Trace state variable name too long for tsv definition packet"));
c252925c 12754 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
00bf0b85 12755 *p++ = '\0';
35b1e5cc 12756 putpkt (rs->buf);
b6bb3468
PA
12757 remote_get_noisy_reply ();
12758 if (*rs->buf == '\0')
ad91cd99 12759 error (_("Target does not support this command."));
b6bb3468 12760 if (strcmp (rs->buf, "OK") != 0)
ad91cd99 12761 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
12762}
12763
f6ac5f3d
PA
12764void
12765remote_target::enable_tracepoint (struct bp_location *location)
d248b706
KY
12766{
12767 struct remote_state *rs = get_remote_state ();
12768 char addr_buf[40];
12769
12770 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12771 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12772 location->owner->number, addr_buf);
d248b706 12773 putpkt (rs->buf);
b6bb3468 12774 remote_get_noisy_reply ();
d248b706
KY
12775 if (*rs->buf == '\0')
12776 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12777 if (strcmp (rs->buf, "OK") != 0)
12778 error (_("Error on target while enabling tracepoint."));
12779}
12780
f6ac5f3d
PA
12781void
12782remote_target::disable_tracepoint (struct bp_location *location)
d248b706
KY
12783{
12784 struct remote_state *rs = get_remote_state ();
12785 char addr_buf[40];
12786
12787 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12788 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12789 location->owner->number, addr_buf);
d248b706 12790 putpkt (rs->buf);
b6bb3468 12791 remote_get_noisy_reply ();
d248b706
KY
12792 if (*rs->buf == '\0')
12793 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12794 if (strcmp (rs->buf, "OK") != 0)
12795 error (_("Error on target while disabling tracepoint."));
12796}
12797
f6ac5f3d
PA
12798void
12799remote_target::trace_set_readonly_regions ()
35b1e5cc
SS
12800{
12801 asection *s;
81b9b86e 12802 bfd *abfd = NULL;
35b1e5cc 12803 bfd_size_type size;
608bcef2 12804 bfd_vma vma;
35b1e5cc 12805 int anysecs = 0;
c2fa21f1 12806 int offset = 0;
35b1e5cc
SS
12807
12808 if (!exec_bfd)
12809 return; /* No information to give. */
12810
b6bb3468
PA
12811 struct remote_state *rs = get_remote_state ();
12812
12813 strcpy (rs->buf, "QTro");
12814 offset = strlen (rs->buf);
35b1e5cc
SS
12815 for (s = exec_bfd->sections; s; s = s->next)
12816 {
12817 char tmp1[40], tmp2[40];
c2fa21f1 12818 int sec_length;
35b1e5cc
SS
12819
12820 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 12821 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
12822 (s->flags & SEC_READONLY) == 0)
12823 continue;
12824
12825 anysecs = 1;
81b9b86e 12826 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 12827 size = bfd_get_section_size (s);
608bcef2
HZ
12828 sprintf_vma (tmp1, vma);
12829 sprintf_vma (tmp2, vma + size);
c2fa21f1 12830 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
b6bb3468 12831 if (offset + sec_length + 1 > rs->buf_size)
c2fa21f1 12832 {
4082afcc 12833 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 12834 warning (_("\
c2fa21f1
HZ
12835Too many sections for read-only sections definition packet."));
12836 break;
12837 }
b6bb3468 12838 xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
bba74b36 12839 tmp1, tmp2);
c2fa21f1 12840 offset += sec_length;
35b1e5cc
SS
12841 }
12842 if (anysecs)
12843 {
b6bb3468
PA
12844 putpkt (rs->buf);
12845 getpkt (&rs->buf, &rs->buf_size, 0);
35b1e5cc
SS
12846 }
12847}
12848
f6ac5f3d
PA
12849void
12850remote_target::trace_start ()
35b1e5cc 12851{
b6bb3468
PA
12852 struct remote_state *rs = get_remote_state ();
12853
35b1e5cc 12854 putpkt ("QTStart");
b6bb3468
PA
12855 remote_get_noisy_reply ();
12856 if (*rs->buf == '\0')
ad91cd99 12857 error (_("Target does not support this command."));
b6bb3468
PA
12858 if (strcmp (rs->buf, "OK") != 0)
12859 error (_("Bogus reply from target: %s"), rs->buf);
35b1e5cc
SS
12860}
12861
f6ac5f3d
PA
12862int
12863remote_target::get_trace_status (struct trace_status *ts)
35b1e5cc 12864{
953b98d1 12865 /* Initialize it just to avoid a GCC false warning. */
f652de6f 12866 char *p = NULL;
0df8b418 12867 /* FIXME we need to get register block size some other way. */
00bf0b85 12868 extern int trace_regblock_size;
bd3eecc3 12869 enum packet_result result;
b6bb3468 12870 struct remote_state *rs = get_remote_state ();
bd3eecc3 12871
4082afcc 12872 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 12873 return -1;
a744cf53 12874
5cd63fda
PA
12875 trace_regblock_size
12876 = get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
00bf0b85 12877
049dc89b
JK
12878 putpkt ("qTStatus");
12879
492d29ea 12880 TRY
67f41397 12881 {
b6bb3468 12882 p = remote_get_noisy_reply ();
67f41397 12883 }
492d29ea 12884 CATCH (ex, RETURN_MASK_ERROR)
67f41397 12885 {
598d3636
JK
12886 if (ex.error != TARGET_CLOSE_ERROR)
12887 {
12888 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12889 return -1;
12890 }
12891 throw_exception (ex);
67f41397 12892 }
492d29ea 12893 END_CATCH
00bf0b85 12894
bd3eecc3
PA
12895 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12896
00bf0b85 12897 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 12898 if (result == PACKET_UNKNOWN)
00bf0b85 12899 return -1;
35b1e5cc 12900
00bf0b85 12901 /* We're working with a live target. */
f5911ea1 12902 ts->filename = NULL;
00bf0b85 12903
00bf0b85 12904 if (*p++ != 'T')
b6bb3468 12905 error (_("Bogus trace status reply from target: %s"), rs->buf);
35b1e5cc 12906
84cebc4a
YQ
12907 /* Function 'parse_trace_status' sets default value of each field of
12908 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
12909 parse_trace_status (p, ts);
12910
12911 return ts->running;
35b1e5cc
SS
12912}
12913
f6ac5f3d
PA
12914void
12915remote_target::get_tracepoint_status (struct breakpoint *bp,
12916 struct uploaded_tp *utp)
f196051f
SS
12917{
12918 struct remote_state *rs = get_remote_state ();
f196051f
SS
12919 char *reply;
12920 struct bp_location *loc;
12921 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 12922 size_t size = get_remote_packet_size ();
f196051f
SS
12923
12924 if (tp)
12925 {
c1fc2657 12926 tp->hit_count = 0;
f196051f 12927 tp->traceframe_usage = 0;
c1fc2657 12928 for (loc = tp->loc; loc; loc = loc->next)
f196051f
SS
12929 {
12930 /* If the tracepoint was never downloaded, don't go asking for
12931 any status. */
12932 if (tp->number_on_target == 0)
12933 continue;
bba74b36
YQ
12934 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12935 phex_nz (loc->address, 0));
f196051f 12936 putpkt (rs->buf);
b6bb3468 12937 reply = remote_get_noisy_reply ();
f196051f
SS
12938 if (reply && *reply)
12939 {
12940 if (*reply == 'V')
12941 parse_tracepoint_status (reply + 1, bp, utp);
12942 }
12943 }
12944 }
12945 else if (utp)
12946 {
12947 utp->hit_count = 0;
12948 utp->traceframe_usage = 0;
bba74b36
YQ
12949 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12950 phex_nz (utp->addr, 0));
f196051f 12951 putpkt (rs->buf);
b6bb3468 12952 reply = remote_get_noisy_reply ();
f196051f
SS
12953 if (reply && *reply)
12954 {
12955 if (*reply == 'V')
12956 parse_tracepoint_status (reply + 1, bp, utp);
12957 }
12958 }
12959}
12960
f6ac5f3d
PA
12961void
12962remote_target::trace_stop ()
35b1e5cc 12963{
b6bb3468
PA
12964 struct remote_state *rs = get_remote_state ();
12965
35b1e5cc 12966 putpkt ("QTStop");
b6bb3468
PA
12967 remote_get_noisy_reply ();
12968 if (*rs->buf == '\0')
ad91cd99 12969 error (_("Target does not support this command."));
b6bb3468
PA
12970 if (strcmp (rs->buf, "OK") != 0)
12971 error (_("Bogus reply from target: %s"), rs->buf);
35b1e5cc
SS
12972}
12973
f6ac5f3d
PA
12974int
12975remote_target::trace_find (enum trace_find_type type, int num,
12976 CORE_ADDR addr1, CORE_ADDR addr2,
12977 int *tpp)
35b1e5cc
SS
12978{
12979 struct remote_state *rs = get_remote_state ();
bba74b36 12980 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
12981 char *p, *reply;
12982 int target_frameno = -1, target_tracept = -1;
12983
e6e4e701
PA
12984 /* Lookups other than by absolute frame number depend on the current
12985 trace selected, so make sure it is correct on the remote end
12986 first. */
12987 if (type != tfind_number)
12988 set_remote_traceframe ();
12989
35b1e5cc
SS
12990 p = rs->buf;
12991 strcpy (p, "QTFrame:");
12992 p = strchr (p, '\0');
12993 switch (type)
12994 {
12995 case tfind_number:
bba74b36 12996 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
12997 break;
12998 case tfind_pc:
bba74b36 12999 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
13000 break;
13001 case tfind_tp:
bba74b36 13002 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
13003 break;
13004 case tfind_range:
bba74b36
YQ
13005 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13006 phex_nz (addr2, 0));
35b1e5cc
SS
13007 break;
13008 case tfind_outside:
bba74b36
YQ
13009 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13010 phex_nz (addr2, 0));
35b1e5cc
SS
13011 break;
13012 default:
9b20d036 13013 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
13014 }
13015
13016 putpkt (rs->buf);
b6bb3468 13017 reply = remote_get_noisy_reply ();
ad91cd99
PA
13018 if (*reply == '\0')
13019 error (_("Target does not support this command."));
35b1e5cc
SS
13020
13021 while (reply && *reply)
13022 switch (*reply)
13023 {
13024 case 'F':
f197e0f1
VP
13025 p = ++reply;
13026 target_frameno = (int) strtol (p, &reply, 16);
13027 if (reply == p)
13028 error (_("Unable to parse trace frame number"));
e6e4e701
PA
13029 /* Don't update our remote traceframe number cache on failure
13030 to select a remote traceframe. */
f197e0f1
VP
13031 if (target_frameno == -1)
13032 return -1;
35b1e5cc
SS
13033 break;
13034 case 'T':
f197e0f1
VP
13035 p = ++reply;
13036 target_tracept = (int) strtol (p, &reply, 16);
13037 if (reply == p)
13038 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
13039 break;
13040 case 'O': /* "OK"? */
13041 if (reply[1] == 'K' && reply[2] == '\0')
13042 reply += 2;
13043 else
13044 error (_("Bogus reply from target: %s"), reply);
13045 break;
13046 default:
13047 error (_("Bogus reply from target: %s"), reply);
13048 }
13049 if (tpp)
13050 *tpp = target_tracept;
e6e4e701 13051
262e1174 13052 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
13053 return target_frameno;
13054}
13055
f6ac5f3d
PA
13056int
13057remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
35b1e5cc
SS
13058{
13059 struct remote_state *rs = get_remote_state ();
13060 char *reply;
13061 ULONGEST uval;
13062
e6e4e701
PA
13063 set_remote_traceframe ();
13064
bba74b36 13065 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc 13066 putpkt (rs->buf);
b6bb3468 13067 reply = remote_get_noisy_reply ();
35b1e5cc
SS
13068 if (reply && *reply)
13069 {
13070 if (*reply == 'V')
13071 {
13072 unpack_varlen_hex (reply + 1, &uval);
13073 *val = (LONGEST) uval;
13074 return 1;
13075 }
13076 }
13077 return 0;
13078}
13079
f6ac5f3d
PA
13080int
13081remote_target::save_trace_data (const char *filename)
00bf0b85
SS
13082{
13083 struct remote_state *rs = get_remote_state ();
13084 char *p, *reply;
13085
13086 p = rs->buf;
13087 strcpy (p, "QTSave:");
13088 p += strlen (p);
13089 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13090 error (_("Remote file name too long for trace save packet"));
9f1b45b0 13091 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
13092 *p++ = '\0';
13093 putpkt (rs->buf);
b6bb3468 13094 reply = remote_get_noisy_reply ();
d6c5869f 13095 if (*reply == '\0')
ad91cd99
PA
13096 error (_("Target does not support this command."));
13097 if (strcmp (reply, "OK") != 0)
13098 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
13099 return 0;
13100}
13101
13102/* This is basically a memory transfer, but needs to be its own packet
13103 because we don't know how the target actually organizes its trace
13104 memory, plus we want to be able to ask for as much as possible, but
13105 not be unhappy if we don't get as much as we ask for. */
13106
f6ac5f3d
PA
13107LONGEST
13108remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
13109{
13110 struct remote_state *rs = get_remote_state ();
13111 char *reply;
13112 char *p;
13113 int rslt;
13114
13115 p = rs->buf;
13116 strcpy (p, "qTBuffer:");
13117 p += strlen (p);
13118 p += hexnumstr (p, offset);
13119 *p++ = ',';
13120 p += hexnumstr (p, len);
13121 *p++ = '\0';
13122
13123 putpkt (rs->buf);
b6bb3468 13124 reply = remote_get_noisy_reply ();
00bf0b85
SS
13125 if (reply && *reply)
13126 {
13127 /* 'l' by itself means we're at the end of the buffer and
13128 there is nothing more to get. */
13129 if (*reply == 'l')
13130 return 0;
13131
13132 /* Convert the reply into binary. Limit the number of bytes to
13133 convert according to our passed-in buffer size, rather than
13134 what was returned in the packet; if the target is
13135 unexpectedly generous and gives us a bigger reply than we
13136 asked for, we don't want to crash. */
b6bb3468 13137 rslt = hex2bin (reply, buf, len);
00bf0b85
SS
13138 return rslt;
13139 }
13140
13141 /* Something went wrong, flag as an error. */
13142 return -1;
13143}
13144
f6ac5f3d
PA
13145void
13146remote_target::set_disconnected_tracing (int val)
35b1e5cc
SS
13147{
13148 struct remote_state *rs = get_remote_state ();
13149
4082afcc 13150 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 13151 {
ad91cd99
PA
13152 char *reply;
13153
bba74b36 13154 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 13155 putpkt (rs->buf);
b6bb3468 13156 reply = remote_get_noisy_reply ();
ad91cd99 13157 if (*reply == '\0')
33da3f1c 13158 error (_("Target does not support this command."));
ad91cd99
PA
13159 if (strcmp (reply, "OK") != 0)
13160 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
13161 }
13162 else if (val)
13163 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
13164}
13165
f6ac5f3d
PA
13166int
13167remote_target::core_of_thread (ptid_t ptid)
dc146f7c
VP
13168{
13169 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 13170
7aabaf9d
SM
13171 if (info != NULL && info->priv != NULL)
13172 return get_remote_thread_info (info)->core;
13173
dc146f7c
VP
13174 return -1;
13175}
13176
f6ac5f3d
PA
13177void
13178remote_target::set_circular_trace_buffer (int val)
4daf5ac0
SS
13179{
13180 struct remote_state *rs = get_remote_state ();
ad91cd99 13181 char *reply;
4daf5ac0 13182
bba74b36 13183 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 13184 putpkt (rs->buf);
b6bb3468 13185 reply = remote_get_noisy_reply ();
ad91cd99 13186 if (*reply == '\0')
4daf5ac0 13187 error (_("Target does not support this command."));
ad91cd99
PA
13188 if (strcmp (reply, "OK") != 0)
13189 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
13190}
13191
f6ac5f3d
PA
13192traceframe_info_up
13193remote_target::traceframe_info ()
b3b9301e 13194{
9018be22 13195 gdb::optional<gdb::char_vector> text
f6ac5f3d 13196 = target_read_stralloc (target_stack, TARGET_OBJECT_TRACEFRAME_INFO,
b7b030ad 13197 NULL);
9018be22
SM
13198 if (text)
13199 return parse_traceframe_info (text->data ());
b3b9301e
PA
13200
13201 return NULL;
13202}
13203
405f8e94
SS
13204/* Handle the qTMinFTPILen packet. Returns the minimum length of
13205 instruction on which a fast tracepoint may be placed. Returns -1
13206 if the packet is not supported, and 0 if the minimum instruction
13207 length is unknown. */
13208
f6ac5f3d
PA
13209int
13210remote_target::get_min_fast_tracepoint_insn_len ()
405f8e94
SS
13211{
13212 struct remote_state *rs = get_remote_state ();
13213 char *reply;
13214
e886a173
PA
13215 /* If we're not debugging a process yet, the IPA can't be
13216 loaded. */
13217 if (!target_has_execution)
13218 return 0;
13219
13220 /* Make sure the remote is pointing at the right process. */
13221 set_general_process ();
13222
bba74b36 13223 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94 13224 putpkt (rs->buf);
b6bb3468 13225 reply = remote_get_noisy_reply ();
405f8e94
SS
13226 if (*reply == '\0')
13227 return -1;
13228 else
13229 {
13230 ULONGEST min_insn_len;
13231
13232 unpack_varlen_hex (reply, &min_insn_len);
13233
13234 return (int) min_insn_len;
13235 }
13236}
13237
f6ac5f3d
PA
13238void
13239remote_target::set_trace_buffer_size (LONGEST val)
f6f899bf 13240{
4082afcc 13241 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
13242 {
13243 struct remote_state *rs = get_remote_state ();
13244 char *buf = rs->buf;
13245 char *endbuf = rs->buf + get_remote_packet_size ();
13246 enum packet_result result;
13247
13248 gdb_assert (val >= 0 || val == -1);
13249 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13250 /* Send -1 as literal "-1" to avoid host size dependency. */
13251 if (val < 0)
13252 {
13253 *buf++ = '-';
13254 buf += hexnumstr (buf, (ULONGEST) -val);
13255 }
13256 else
13257 buf += hexnumstr (buf, (ULONGEST) val);
13258
13259 putpkt (rs->buf);
b6bb3468 13260 remote_get_noisy_reply ();
f6f899bf
HAQ
13261 result = packet_ok (rs->buf,
13262 &remote_protocol_packets[PACKET_QTBuffer_size]);
13263
13264 if (result != PACKET_OK)
13265 warning (_("Bogus reply from target: %s"), rs->buf);
13266 }
13267}
13268
f6ac5f3d
PA
13269int
13270remote_target::set_trace_notes (const char *user, const char *notes,
13271 const char *stop_notes)
f196051f
SS
13272{
13273 struct remote_state *rs = get_remote_state ();
13274 char *reply;
13275 char *buf = rs->buf;
13276 char *endbuf = rs->buf + get_remote_packet_size ();
13277 int nbytes;
13278
13279 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13280 if (user)
13281 {
13282 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 13283 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
13284 buf += 2 * nbytes;
13285 *buf++ = ';';
13286 }
13287 if (notes)
13288 {
13289 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 13290 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
13291 buf += 2 * nbytes;
13292 *buf++ = ';';
13293 }
13294 if (stop_notes)
13295 {
13296 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 13297 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
13298 buf += 2 * nbytes;
13299 *buf++ = ';';
13300 }
13301 /* Ensure the buffer is terminated. */
13302 *buf = '\0';
13303
13304 putpkt (rs->buf);
b6bb3468 13305 reply = remote_get_noisy_reply ();
f196051f
SS
13306 if (*reply == '\0')
13307 return 0;
13308
13309 if (strcmp (reply, "OK") != 0)
13310 error (_("Bogus reply from target: %s"), reply);
13311
13312 return 1;
13313}
13314
f6ac5f3d
PA
13315int
13316remote_target::use_agent (int use)
d1feda86 13317{
4082afcc 13318 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
13319 {
13320 struct remote_state *rs = get_remote_state ();
13321
13322 /* If the stub supports QAgent. */
bba74b36 13323 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
13324 putpkt (rs->buf);
13325 getpkt (&rs->buf, &rs->buf_size, 0);
13326
13327 if (strcmp (rs->buf, "OK") == 0)
13328 {
f6ac5f3d 13329 ::use_agent = use;
d1feda86
YQ
13330 return 1;
13331 }
13332 }
13333
13334 return 0;
13335}
13336
f6ac5f3d
PA
13337int
13338remote_target::can_use_agent ()
d1feda86 13339{
4082afcc 13340 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
13341}
13342
9accd112
MM
13343struct btrace_target_info
13344{
13345 /* The ptid of the traced thread. */
13346 ptid_t ptid;
f4abbc16
MM
13347
13348 /* The obtained branch trace configuration. */
13349 struct btrace_config conf;
9accd112
MM
13350};
13351
f4abbc16
MM
13352/* Reset our idea of our target's btrace configuration. */
13353
13354static void
13355remote_btrace_reset (void)
13356{
13357 struct remote_state *rs = get_remote_state ();
13358
13359 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13360}
13361
f4abbc16
MM
13362/* Synchronize the configuration with the target. */
13363
13364static void
13365btrace_sync_conf (const struct btrace_config *conf)
13366{
d33501a5
MM
13367 struct packet_config *packet;
13368 struct remote_state *rs;
13369 char *buf, *pos, *endbuf;
13370
13371 rs = get_remote_state ();
13372 buf = rs->buf;
13373 endbuf = buf + get_remote_packet_size ();
13374
13375 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13376 if (packet_config_support (packet) == PACKET_ENABLE
13377 && conf->bts.size != rs->btrace_config.bts.size)
13378 {
13379 pos = buf;
13380 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13381 conf->bts.size);
13382
13383 putpkt (buf);
13384 getpkt (&buf, &rs->buf_size, 0);
13385
13386 if (packet_ok (buf, packet) == PACKET_ERROR)
13387 {
13388 if (buf[0] == 'E' && buf[1] == '.')
13389 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13390 else
13391 error (_("Failed to configure the BTS buffer size."));
13392 }
13393
13394 rs->btrace_config.bts.size = conf->bts.size;
13395 }
b20a6524
MM
13396
13397 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13398 if (packet_config_support (packet) == PACKET_ENABLE
13399 && conf->pt.size != rs->btrace_config.pt.size)
13400 {
13401 pos = buf;
13402 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13403 conf->pt.size);
13404
13405 putpkt (buf);
13406 getpkt (&buf, &rs->buf_size, 0);
13407
13408 if (packet_ok (buf, packet) == PACKET_ERROR)
13409 {
13410 if (buf[0] == 'E' && buf[1] == '.')
13411 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13412 else
13413 error (_("Failed to configure the trace buffer size."));
13414 }
13415
13416 rs->btrace_config.pt.size = conf->pt.size;
13417 }
f4abbc16
MM
13418}
13419
13420/* Read the current thread's btrace configuration from the target and
13421 store it into CONF. */
13422
13423static void
13424btrace_read_config (struct btrace_config *conf)
13425{
9018be22 13426 gdb::optional<gdb::char_vector> xml
f6ac5f3d 13427 = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE_CONF, "");
9018be22
SM
13428 if (xml)
13429 parse_xml_btrace_conf (conf, xml->data ());
f4abbc16
MM
13430}
13431
c0272db5
TW
13432/* Maybe reopen target btrace. */
13433
13434static void
13435remote_btrace_maybe_reopen (void)
13436{
13437 struct remote_state *rs = get_remote_state ();
c0272db5
TW
13438 struct thread_info *tp;
13439 int btrace_target_pushed = 0;
13440 int warned = 0;
13441
5ed8105e
PA
13442 scoped_restore_current_thread restore_thread;
13443
c0272db5
TW
13444 ALL_NON_EXITED_THREADS (tp)
13445 {
13446 set_general_thread (tp->ptid);
13447
13448 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13449 btrace_read_config (&rs->btrace_config);
13450
13451 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13452 continue;
13453
13454#if !defined (HAVE_LIBIPT)
13455 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13456 {
13457 if (!warned)
13458 {
13459 warned = 1;
c4e12631
MM
13460 warning (_("Target is recording using Intel Processor Trace "
13461 "but support was disabled at compile time."));
c0272db5
TW
13462 }
13463
13464 continue;
13465 }
13466#endif /* !defined (HAVE_LIBIPT) */
13467
13468 /* Push target, once, but before anything else happens. This way our
13469 changes to the threads will be cleaned up by unpushing the target
13470 in case btrace_read_config () throws. */
13471 if (!btrace_target_pushed)
13472 {
13473 btrace_target_pushed = 1;
13474 record_btrace_push_target ();
13475 printf_filtered (_("Target is recording using %s.\n"),
13476 btrace_format_string (rs->btrace_config.format));
13477 }
13478
13479 tp->btrace.target = XCNEW (struct btrace_target_info);
13480 tp->btrace.target->ptid = tp->ptid;
13481 tp->btrace.target->conf = rs->btrace_config;
13482 }
c0272db5
TW
13483}
13484
9accd112
MM
13485/* Enable branch tracing. */
13486
f6ac5f3d
PA
13487struct btrace_target_info *
13488remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
9accd112
MM
13489{
13490 struct btrace_target_info *tinfo = NULL;
b20a6524 13491 struct packet_config *packet = NULL;
9accd112
MM
13492 struct remote_state *rs = get_remote_state ();
13493 char *buf = rs->buf;
13494 char *endbuf = rs->buf + get_remote_packet_size ();
13495
b20a6524
MM
13496 switch (conf->format)
13497 {
13498 case BTRACE_FORMAT_BTS:
13499 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13500 break;
13501
13502 case BTRACE_FORMAT_PT:
13503 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13504 break;
13505 }
13506
13507 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13508 error (_("Target does not support branch tracing."));
13509
f4abbc16
MM
13510 btrace_sync_conf (conf);
13511
9accd112
MM
13512 set_general_thread (ptid);
13513
13514 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13515 putpkt (rs->buf);
13516 getpkt (&rs->buf, &rs->buf_size, 0);
13517
13518 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13519 {
13520 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13521 error (_("Could not enable branch tracing for %s: %s"),
13522 target_pid_to_str (ptid), rs->buf + 2);
13523 else
13524 error (_("Could not enable branch tracing for %s."),
13525 target_pid_to_str (ptid));
13526 }
13527
8d749320 13528 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
13529 tinfo->ptid = ptid;
13530
f4abbc16
MM
13531 /* If we fail to read the configuration, we lose some information, but the
13532 tracing itself is not impacted. */
492d29ea
PA
13533 TRY
13534 {
13535 btrace_read_config (&tinfo->conf);
13536 }
13537 CATCH (err, RETURN_MASK_ERROR)
13538 {
13539 if (err.message != NULL)
13540 warning ("%s", err.message);
13541 }
13542 END_CATCH
f4abbc16 13543
9accd112
MM
13544 return tinfo;
13545}
13546
13547/* Disable branch tracing. */
13548
f6ac5f3d
PA
13549void
13550remote_target::disable_btrace (struct btrace_target_info *tinfo)
9accd112
MM
13551{
13552 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13553 struct remote_state *rs = get_remote_state ();
13554 char *buf = rs->buf;
13555 char *endbuf = rs->buf + get_remote_packet_size ();
13556
4082afcc 13557 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13558 error (_("Target does not support branch tracing."));
13559
13560 set_general_thread (tinfo->ptid);
13561
13562 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13563 putpkt (rs->buf);
13564 getpkt (&rs->buf, &rs->buf_size, 0);
13565
13566 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13567 {
13568 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13569 error (_("Could not disable branch tracing for %s: %s"),
13570 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13571 else
13572 error (_("Could not disable branch tracing for %s."),
13573 target_pid_to_str (tinfo->ptid));
13574 }
13575
13576 xfree (tinfo);
13577}
13578
13579/* Teardown branch tracing. */
13580
f6ac5f3d
PA
13581void
13582remote_target::teardown_btrace (struct btrace_target_info *tinfo)
9accd112
MM
13583{
13584 /* We must not talk to the target during teardown. */
13585 xfree (tinfo);
13586}
13587
13588/* Read the branch trace. */
13589
f6ac5f3d
PA
13590enum btrace_error
13591remote_target::read_btrace (struct btrace_data *btrace,
13592 struct btrace_target_info *tinfo,
13593 enum btrace_read_type type)
9accd112
MM
13594{
13595 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
9accd112 13596 const char *annex;
9accd112 13597
4082afcc 13598 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13599 error (_("Target does not support branch tracing."));
13600
13601#if !defined(HAVE_LIBEXPAT)
13602 error (_("Cannot process branch tracing result. XML parsing not supported."));
13603#endif
13604
13605 switch (type)
13606 {
864089d2 13607 case BTRACE_READ_ALL:
9accd112
MM
13608 annex = "all";
13609 break;
864089d2 13610 case BTRACE_READ_NEW:
9accd112
MM
13611 annex = "new";
13612 break;
969c39fb
MM
13613 case BTRACE_READ_DELTA:
13614 annex = "delta";
13615 break;
9accd112
MM
13616 default:
13617 internal_error (__FILE__, __LINE__,
13618 _("Bad branch tracing read type: %u."),
13619 (unsigned int) type);
13620 }
13621
9018be22 13622 gdb::optional<gdb::char_vector> xml
f6ac5f3d 13623 = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE, annex);
9018be22 13624 if (!xml)
969c39fb 13625 return BTRACE_ERR_UNKNOWN;
9accd112 13626
9018be22 13627 parse_xml_btrace (btrace, xml->data ());
9accd112 13628
969c39fb 13629 return BTRACE_ERR_NONE;
9accd112
MM
13630}
13631
f6ac5f3d
PA
13632const struct btrace_config *
13633remote_target::btrace_conf (const struct btrace_target_info *tinfo)
f4abbc16
MM
13634{
13635 return &tinfo->conf;
13636}
13637
f6ac5f3d
PA
13638int
13639remote_target::augmented_libraries_svr4_read ()
ced63ec0 13640{
4082afcc
PA
13641 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13642 == PACKET_ENABLE);
ced63ec0
GB
13643}
13644
9dd130a0
TT
13645/* Implementation of to_load. */
13646
f6ac5f3d
PA
13647void
13648remote_target::load (const char *name, int from_tty)
9dd130a0
TT
13649{
13650 generic_load (name, from_tty);
13651}
13652
c78fa86a
GB
13653/* Accepts an integer PID; returns a string representing a file that
13654 can be opened on the remote side to get the symbols for the child
13655 process. Returns NULL if the operation is not supported. */
13656
f6ac5f3d
PA
13657char *
13658remote_target::pid_to_exec_file (int pid)
c78fa86a 13659{
9018be22 13660 static gdb::optional<gdb::char_vector> filename;
835205d0
GB
13661 struct inferior *inf;
13662 char *annex = NULL;
c78fa86a
GB
13663
13664 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13665 return NULL;
13666
835205d0
GB
13667 inf = find_inferior_pid (pid);
13668 if (inf == NULL)
13669 internal_error (__FILE__, __LINE__,
13670 _("not currently attached to process %d"), pid);
13671
13672 if (!inf->fake_pid_p)
13673 {
13674 const int annex_size = 9;
13675
224c3ddb 13676 annex = (char *) alloca (annex_size);
835205d0
GB
13677 xsnprintf (annex, annex_size, "%x", pid);
13678 }
13679
f6ac5f3d 13680 filename = target_read_stralloc (target_stack,
c78fa86a
GB
13681 TARGET_OBJECT_EXEC_FILE, annex);
13682
9018be22 13683 return filename ? filename->data () : nullptr;
c78fa86a
GB
13684}
13685
750ce8d1
YQ
13686/* Implement the to_can_do_single_step target_ops method. */
13687
f6ac5f3d
PA
13688int
13689remote_target::can_do_single_step ()
750ce8d1
YQ
13690{
13691 /* We can only tell whether target supports single step or not by
13692 supported s and S vCont actions if the stub supports vContSupported
13693 feature. If the stub doesn't support vContSupported feature,
13694 we have conservatively to think target doesn't supports single
13695 step. */
13696 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13697 {
13698 struct remote_state *rs = get_remote_state ();
13699
13700 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13701 remote_vcont_probe (rs);
13702
13703 return rs->supports_vCont.s && rs->supports_vCont.S;
13704 }
13705 else
13706 return 0;
13707}
13708
3a00c802
PA
13709/* Implementation of the to_execution_direction method for the remote
13710 target. */
13711
f6ac5f3d
PA
13712enum exec_direction_kind
13713remote_target::execution_direction ()
3a00c802
PA
13714{
13715 struct remote_state *rs = get_remote_state ();
13716
13717 return rs->last_resume_exec_dir;
13718}
13719
f6327dcb
KB
13720/* Return pointer to the thread_info struct which corresponds to
13721 THREAD_HANDLE (having length HANDLE_LEN). */
13722
f6ac5f3d
PA
13723thread_info *
13724remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
13725 int handle_len,
13726 inferior *inf)
f6327dcb
KB
13727{
13728 struct thread_info *tp;
13729
13730 ALL_NON_EXITED_THREADS (tp)
13731 {
7aabaf9d 13732 remote_thread_info *priv = get_remote_thread_info (tp);
f6327dcb
KB
13733
13734 if (tp->inf == inf && priv != NULL)
13735 {
7aabaf9d 13736 if (handle_len != priv->thread_handle.size ())
f6327dcb 13737 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
7aabaf9d
SM
13738 handle_len, priv->thread_handle.size ());
13739 if (memcmp (thread_handle, priv->thread_handle.data (),
f6327dcb
KB
13740 handle_len) == 0)
13741 return tp;
13742 }
13743 }
13744
13745 return NULL;
13746}
13747
f6ac5f3d
PA
13748int
13749remote_target::can_async_p ()
6426a772 13750{
5d93a237
TT
13751 struct remote_state *rs = get_remote_state ();
13752
3015c064
SM
13753 /* We don't go async if the user has explicitly prevented it with the
13754 "maint set target-async" command. */
c6ebd6cf 13755 if (!target_async_permitted)
75c99385
PA
13756 return 0;
13757
23860348 13758 /* We're async whenever the serial device is. */
5d93a237 13759 return serial_can_async_p (rs->remote_desc);
6426a772
JM
13760}
13761
f6ac5f3d
PA
13762int
13763remote_target::is_async_p ()
6426a772 13764{
5d93a237
TT
13765 struct remote_state *rs = get_remote_state ();
13766
c6ebd6cf 13767 if (!target_async_permitted)
75c99385
PA
13768 /* We only enable async when the user specifically asks for it. */
13769 return 0;
13770
23860348 13771 /* We're async whenever the serial device is. */
5d93a237 13772 return serial_is_async_p (rs->remote_desc);
6426a772
JM
13773}
13774
2acceee2
JM
13775/* Pass the SERIAL event on and up to the client. One day this code
13776 will be able to delay notifying the client of an event until the
23860348 13777 point where an entire packet has been received. */
2acceee2 13778
2acceee2
JM
13779static serial_event_ftype remote_async_serial_handler;
13780
6426a772 13781static void
819cc324 13782remote_async_serial_handler (struct serial *scb, void *context)
6426a772 13783{
2acceee2
JM
13784 /* Don't propogate error information up to the client. Instead let
13785 the client find out about the error by querying the target. */
6a3753b3 13786 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
13787}
13788
74531fed
PA
13789static void
13790remote_async_inferior_event_handler (gdb_client_data data)
13791{
13792 inferior_event_handler (INF_REG_EVENT, NULL);
13793}
13794
f6ac5f3d
PA
13795void
13796remote_target::async (int enable)
2acceee2 13797{
5d93a237
TT
13798 struct remote_state *rs = get_remote_state ();
13799
6a3753b3 13800 if (enable)
2acceee2 13801 {
88b496c3 13802 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
13803
13804 /* If there are pending events in the stop reply queue tell the
13805 event loop to process them. */
13806 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13807 mark_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13808 /* For simplicity, below we clear the pending events token
13809 without remembering whether it is marked, so here we always
13810 mark it. If there's actually no pending notification to
13811 process, this ends up being a no-op (other than a spurious
13812 event-loop wakeup). */
13813 if (target_is_non_stop_p ())
13814 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
13815 }
13816 else
b7d2e916
PA
13817 {
13818 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
13819 /* If the core is disabling async, it doesn't want to be
13820 disturbed with target events. Clear all async event sources
13821 too. */
b7d2e916 13822 clear_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13823 if (target_is_non_stop_p ())
13824 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 13825 }
6426a772
JM
13826}
13827
65706a29
PA
13828/* Implementation of the to_thread_events method. */
13829
f6ac5f3d
PA
13830void
13831remote_target::thread_events (int enable)
65706a29
PA
13832{
13833 struct remote_state *rs = get_remote_state ();
13834 size_t size = get_remote_packet_size ();
65706a29
PA
13835
13836 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13837 return;
13838
13839 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13840 putpkt (rs->buf);
13841 getpkt (&rs->buf, &rs->buf_size, 0);
13842
13843 switch (packet_ok (rs->buf,
13844 &remote_protocol_packets[PACKET_QThreadEvents]))
13845 {
13846 case PACKET_OK:
13847 if (strcmp (rs->buf, "OK") != 0)
13848 error (_("Remote refused setting thread events: %s"), rs->buf);
13849 break;
13850 case PACKET_ERROR:
13851 warning (_("Remote failure reply: %s"), rs->buf);
13852 break;
13853 case PACKET_UNKNOWN:
13854 break;
13855 }
13856}
13857
5a2468f5 13858static void
981a3fb3 13859set_remote_cmd (const char *args, int from_tty)
5a2468f5 13860{
635c7e8a 13861 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
13862}
13863
d471ea57 13864static void
981a3fb3 13865show_remote_cmd (const char *args, int from_tty)
d471ea57 13866{
37a105a1 13867 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 13868 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1 13869 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 13870 struct ui_out *uiout = current_uiout;
37a105a1 13871
2e783024 13872 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
37a105a1
DJ
13873 for (; list != NULL; list = list->next)
13874 if (strcmp (list->name, "Z-packet") == 0)
13875 continue;
427c3a89
DJ
13876 else if (list->type == not_set_cmd)
13877 /* Alias commands are exactly like the original, except they
13878 don't have the normal type. */
13879 continue;
13880 else
37a105a1 13881 {
2e783024 13882 ui_out_emit_tuple option_emitter (uiout, "option");
a744cf53 13883
112e8700
SM
13884 uiout->field_string ("name", list->name);
13885 uiout->text (": ");
427c3a89 13886 if (list->type == show_cmd)
f5c4fcd9 13887 do_show_command (NULL, from_tty, list);
427c3a89
DJ
13888 else
13889 cmd_func (list, NULL, from_tty);
37a105a1 13890 }
d471ea57 13891}
5a2468f5 13892
0f71a2f6 13893
23860348 13894/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
13895static void
13896remote_new_objfile (struct objfile *objfile)
13897{
5d93a237
TT
13898 struct remote_state *rs = get_remote_state ();
13899
13900 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 13901 remote_check_symbols ();
dc8acb97
MS
13902}
13903
00bf0b85
SS
13904/* Pull all the tracepoints defined on the target and create local
13905 data structures representing them. We don't want to create real
13906 tracepoints yet, we don't want to mess up the user's existing
13907 collection. */
13908
f6ac5f3d
PA
13909int
13910remote_target::upload_tracepoints (struct uploaded_tp **utpp)
d5551862 13911{
00bf0b85
SS
13912 struct remote_state *rs = get_remote_state ();
13913 char *p;
d5551862 13914
00bf0b85
SS
13915 /* Ask for a first packet of tracepoint definition. */
13916 putpkt ("qTfP");
13917 getpkt (&rs->buf, &rs->buf_size, 0);
13918 p = rs->buf;
13919 while (*p && *p != 'l')
d5551862 13920 {
00bf0b85
SS
13921 parse_tracepoint_definition (p, utpp);
13922 /* Ask for another packet of tracepoint definition. */
13923 putpkt ("qTsP");
13924 getpkt (&rs->buf, &rs->buf_size, 0);
13925 p = rs->buf;
d5551862 13926 }
00bf0b85 13927 return 0;
d5551862
SS
13928}
13929
f6ac5f3d
PA
13930int
13931remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
d5551862 13932{
00bf0b85 13933 struct remote_state *rs = get_remote_state ();
d5551862 13934 char *p;
d5551862 13935
00bf0b85
SS
13936 /* Ask for a first packet of variable definition. */
13937 putpkt ("qTfV");
d5551862
SS
13938 getpkt (&rs->buf, &rs->buf_size, 0);
13939 p = rs->buf;
00bf0b85 13940 while (*p && *p != 'l')
d5551862 13941 {
00bf0b85
SS
13942 parse_tsv_definition (p, utsvp);
13943 /* Ask for another packet of variable definition. */
13944 putpkt ("qTsV");
d5551862
SS
13945 getpkt (&rs->buf, &rs->buf_size, 0);
13946 p = rs->buf;
13947 }
00bf0b85 13948 return 0;
d5551862
SS
13949}
13950
c1e36e3e
PA
13951/* The "set/show range-stepping" show hook. */
13952
13953static void
13954show_range_stepping (struct ui_file *file, int from_tty,
13955 struct cmd_list_element *c,
13956 const char *value)
13957{
13958 fprintf_filtered (file,
13959 _("Debugger's willingness to use range stepping "
13960 "is %s.\n"), value);
13961}
13962
13963/* The "set/show range-stepping" set hook. */
13964
13965static void
eb4c3f4a 13966set_range_stepping (const char *ignore_args, int from_tty,
c1e36e3e
PA
13967 struct cmd_list_element *c)
13968{
5d93a237
TT
13969 struct remote_state *rs = get_remote_state ();
13970
c1e36e3e
PA
13971 /* Whene enabling, check whether range stepping is actually
13972 supported by the target, and warn if not. */
13973 if (use_range_stepping)
13974 {
5d93a237 13975 if (rs->remote_desc != NULL)
c1e36e3e 13976 {
4082afcc 13977 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
13978 remote_vcont_probe (rs);
13979
4082afcc 13980 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
13981 && rs->supports_vCont.r)
13982 return;
13983 }
13984
13985 warning (_("Range stepping is not supported by the current target"));
13986 }
13987}
13988
c906108c 13989void
fba45db2 13990_initialize_remote (void)
c906108c 13991{
9a7071a8 13992 struct cmd_list_element *cmd;
6f937416 13993 const char *cmd_name;
ea9c271d 13994
0f71a2f6 13995 /* architecture specific data */
2bc416ba 13996 remote_gdbarch_data_handle =
23860348 13997 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
13998 remote_g_packet_data_handle =
13999 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 14000
94585166
DB
14001 remote_pspace_data
14002 = register_program_space_data_with_cleanup (NULL,
14003 remote_pspace_data_cleanup);
14004
ea9c271d
DJ
14005 /* Initialize the per-target state. At the moment there is only one
14006 of these, not one per target. Only one target is active at a
cf792862
TT
14007 time. */
14008 remote_state = new_remote_state ();
ea9c271d 14009
c906108c 14010 add_target (&remote_ops);
c906108c 14011 add_target (&extended_remote_ops);
cce74817 14012
dc8acb97 14013 /* Hook into new objfile notification. */
76727919 14014 gdb::observers::new_objfile.attach (remote_new_objfile);
5f4cf0bb
YQ
14015 /* We're no longer interested in notification events of an inferior
14016 when it exits. */
76727919 14017 gdb::observers::inferior_exit.attach (discard_pending_stop_replies);
dc8acb97 14018
c906108c
SS
14019#if 0
14020 init_remote_threadtests ();
14021#endif
14022
722247f1 14023 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 14024 /* set/show remote ... */
d471ea57 14025
1bedd215 14026 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
14027Remote protocol specific variables\n\
14028Configure various remote-protocol specific variables such as\n\
1bedd215 14029the packets being used"),
cff3e48b 14030 &remote_set_cmdlist, "set remote ",
23860348 14031 0 /* allow-unknown */, &setlist);
1bedd215 14032 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
14033Remote protocol specific variables\n\
14034Configure various remote-protocol specific variables such as\n\
1bedd215 14035the packets being used"),
cff3e48b 14036 &remote_show_cmdlist, "show remote ",
23860348 14037 0 /* allow-unknown */, &showlist);
5a2468f5 14038
1a966eab
AC
14039 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14040Compare section data on target to the exec file.\n\
95cf3b38
DT
14041Argument is a single section name (default: all loaded sections).\n\
14042To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
14043 &cmdlist);
14044
1a966eab
AC
14045 add_cmd ("packet", class_maintenance, packet_command, _("\
14046Send an arbitrary packet to a remote target.\n\
c906108c
SS
14047 maintenance packet TEXT\n\
14048If GDB is talking to an inferior via the GDB serial protocol, then\n\
14049this command sends the string TEXT to the inferior, and displays the\n\
14050response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 14051terminating `#' character and checksum."),
c906108c
SS
14052 &maintenancelist);
14053
7915a72c
AC
14054 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14055Set whether to send break if interrupted."), _("\
14056Show whether to send break if interrupted."), _("\
14057If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 14058 set_remotebreak, show_remotebreak,
e707bbc2 14059 &setlist, &showlist);
9a7071a8
JB
14060 cmd_name = "remotebreak";
14061 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14062 deprecate_cmd (cmd, "set remote interrupt-sequence");
14063 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14064 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14065 deprecate_cmd (cmd, "show remote interrupt-sequence");
14066
14067 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
14068 interrupt_sequence_modes, &interrupt_sequence_mode,
14069 _("\
9a7071a8
JB
14070Set interrupt sequence to remote target."), _("\
14071Show interrupt sequence to remote target."), _("\
14072Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14073 NULL, show_interrupt_sequence,
14074 &remote_set_cmdlist,
14075 &remote_show_cmdlist);
14076
14077 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14078 &interrupt_on_connect, _("\
14079Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14080Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14081If set, interrupt sequence is sent to remote target."),
14082 NULL, NULL,
14083 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 14084
23860348 14085 /* Install commands for configuring memory read/write packets. */
11cf8741 14086
1a966eab
AC
14087 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14088Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 14089 &setlist);
1a966eab
AC
14090 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14091Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
14092 &showlist);
14093 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
14094 set_memory_write_packet_size, _("\
14095Set the maximum number of bytes per memory-write packet.\n\
14096Specify the number of bytes in a packet or 0 (zero) for the\n\
14097default packet size. The actual limit is further reduced\n\
14098dependent on the target. Specify ``fixed'' to disable the\n\
14099further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14100 &remote_set_cmdlist);
14101 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
14102 set_memory_read_packet_size, _("\
14103Set the maximum number of bytes per memory-read packet.\n\
14104Specify the number of bytes in a packet or 0 (zero) for the\n\
14105default packet size. The actual limit is further reduced\n\
14106dependent on the target. Specify ``fixed'' to disable the\n\
14107further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14108 &remote_set_cmdlist);
14109 add_cmd ("memory-write-packet-size", no_class,
14110 show_memory_write_packet_size,
1a966eab 14111 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
14112 &remote_show_cmdlist);
14113 add_cmd ("memory-read-packet-size", no_class,
14114 show_memory_read_packet_size,
1a966eab 14115 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 14116 &remote_show_cmdlist);
c906108c 14117
b3f42336 14118 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
14119 &remote_hw_watchpoint_limit, _("\
14120Set the maximum number of target hardware watchpoints."), _("\
14121Show the maximum number of target hardware watchpoints."), _("\
14122Specify a negative limit for unlimited."),
3e43a32a
MS
14123 NULL, NULL, /* FIXME: i18n: The maximum
14124 number of target hardware
14125 watchpoints is %s. */
b3f42336 14126 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
14127 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14128 &remote_hw_watchpoint_length_limit, _("\
14129Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14130Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14131Specify a negative limit for unlimited."),
14132 NULL, NULL, /* FIXME: i18n: The maximum
14133 length (in bytes) of a target
14134 hardware watchpoint is %s. */
14135 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 14136 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
14137 &remote_hw_breakpoint_limit, _("\
14138Set the maximum number of target hardware breakpoints."), _("\
14139Show the maximum number of target hardware breakpoints."), _("\
14140Specify a negative limit for unlimited."),
3e43a32a
MS
14141 NULL, NULL, /* FIXME: i18n: The maximum
14142 number of target hardware
14143 breakpoints is %s. */
b3f42336 14144 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 14145
1b493192
PA
14146 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14147 &remote_address_size, _("\
4d28ad1e
AC
14148Set the maximum size of the address (in bits) in a memory packet."), _("\
14149Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
14150 NULL,
14151 NULL, /* FIXME: i18n: */
14152 &setlist, &showlist);
c906108c 14153
ca4f7f8b
PA
14154 init_all_packet_configs ();
14155
444abaca 14156 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 14157 "X", "binary-download", 1);
0f71a2f6 14158
444abaca 14159 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 14160 "vCont", "verbose-resume", 0);
506fb367 14161
89be2091
DJ
14162 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14163 "QPassSignals", "pass-signals", 0);
14164
82075af2
JS
14165 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14166 "QCatchSyscalls", "catch-syscalls", 0);
14167
9b224c5e
PA
14168 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14169 "QProgramSignals", "program-signals", 0);
14170
bc3b087d
SDJ
14171 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14172 "QSetWorkingDir", "set-working-dir", 0);
14173
aefd8b33
SDJ
14174 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14175 "QStartupWithShell", "startup-with-shell", 0);
14176
0a2dde4a
SDJ
14177 add_packet_config_cmd (&remote_protocol_packets
14178 [PACKET_QEnvironmentHexEncoded],
14179 "QEnvironmentHexEncoded", "environment-hex-encoded",
14180 0);
14181
14182 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14183 "QEnvironmentReset", "environment-reset",
14184 0);
14185
14186 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14187 "QEnvironmentUnset", "environment-unset",
14188 0);
14189
444abaca 14190 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 14191 "qSymbol", "symbol-lookup", 0);
dc8acb97 14192
444abaca 14193 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 14194 "P", "set-register", 1);
d471ea57 14195
444abaca 14196 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 14197 "p", "fetch-register", 1);
b96ec7ac 14198
444abaca 14199 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 14200 "Z0", "software-breakpoint", 0);
d471ea57 14201
444abaca 14202 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 14203 "Z1", "hardware-breakpoint", 0);
d471ea57 14204
444abaca 14205 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 14206 "Z2", "write-watchpoint", 0);
d471ea57 14207
444abaca 14208 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 14209 "Z3", "read-watchpoint", 0);
d471ea57 14210
444abaca 14211 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 14212 "Z4", "access-watchpoint", 0);
d471ea57 14213
0876f84a
DJ
14214 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14215 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 14216
c78fa86a
GB
14217 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14218 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14219
23181151
DJ
14220 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14221 "qXfer:features:read", "target-features", 0);
14222
cfa9d6d9
DJ
14223 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14224 "qXfer:libraries:read", "library-info", 0);
14225
2268b414
JK
14226 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14227 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14228
fd79ecee
DJ
14229 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14230 "qXfer:memory-map:read", "memory-map", 0);
14231
0e7f50da
UW
14232 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14233 "qXfer:spu:read", "read-spu-object", 0);
14234
14235 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14236 "qXfer:spu:write", "write-spu-object", 0);
14237
07e059b5
VP
14238 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14239 "qXfer:osdata:read", "osdata", 0);
14240
dc146f7c
VP
14241 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14242 "qXfer:threads:read", "threads", 0);
14243
4aa995e1
PA
14244 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14245 "qXfer:siginfo:read", "read-siginfo-object", 0);
14246
14247 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14248 "qXfer:siginfo:write", "write-siginfo-object", 0);
14249
b3b9301e
PA
14250 add_packet_config_cmd
14251 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 14252 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 14253
169081d0
TG
14254 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14255 "qXfer:uib:read", "unwind-info-block", 0);
14256
444abaca 14257 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 14258 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
14259 0);
14260
711e434b
PM
14261 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14262 "qGetTIBAddr", "get-thread-information-block-address",
14263 0);
14264
40ab02ce
MS
14265 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14266 "bc", "reverse-continue", 0);
14267
14268 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14269 "bs", "reverse-step", 0);
14270
be2a5f71
DJ
14271 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14272 "qSupported", "supported-packets", 0);
14273
08388c79
DE
14274 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14275 "qSearch:memory", "search-memory", 0);
14276
bd3eecc3
PA
14277 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14278 "qTStatus", "trace-status", 0);
14279
15a201c8
GB
14280 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14281 "vFile:setfs", "hostio-setfs", 0);
14282
a6b151f1
DJ
14283 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14284 "vFile:open", "hostio-open", 0);
14285
14286 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14287 "vFile:pread", "hostio-pread", 0);
14288
14289 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14290 "vFile:pwrite", "hostio-pwrite", 0);
14291
14292 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14293 "vFile:close", "hostio-close", 0);
14294
14295 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14296 "vFile:unlink", "hostio-unlink", 0);
14297
b9e7b9c3
UW
14298 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14299 "vFile:readlink", "hostio-readlink", 0);
14300
0a93529c
GB
14301 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14302 "vFile:fstat", "hostio-fstat", 0);
14303
2d717e4f
DJ
14304 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14305 "vAttach", "attach", 0);
14306
14307 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14308 "vRun", "run", 0);
14309
a6f3e723
SL
14310 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14311 "QStartNoAckMode", "noack", 0);
14312
82f73884
PA
14313 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14314 "vKill", "kill", 0);
14315
0b16c5cf
PA
14316 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14317 "qAttached", "query-attached", 0);
14318
782b2b07 14319 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
14320 "ConditionalTracepoints",
14321 "conditional-tracepoints", 0);
3788aec7
LM
14322
14323 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14324 "ConditionalBreakpoints",
14325 "conditional-breakpoints", 0);
14326
d3ce09f5
SS
14327 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14328 "BreakpointCommands",
14329 "breakpoint-commands", 0);
14330
7a697b8d
SS
14331 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14332 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 14333
409873ef
SS
14334 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14335 "TracepointSource", "TracepointSource", 0);
14336
d914c394
SS
14337 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14338 "QAllow", "allow", 0);
14339
0fb4aa4b
PA
14340 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14341 "StaticTracepoints", "static-tracepoints", 0);
14342
1e4d1764
YQ
14343 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14344 "InstallInTrace", "install-in-trace", 0);
14345
0fb4aa4b
PA
14346 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14347 "qXfer:statictrace:read", "read-sdata-object", 0);
14348
78d85199
YQ
14349 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14350 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14351
03583c20
UW
14352 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14353 "QDisableRandomization", "disable-randomization", 0);
14354
d1feda86
YQ
14355 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14356 "QAgent", "agent", 0);
14357
f6f899bf
HAQ
14358 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14359 "QTBuffer:size", "trace-buffer-size", 0);
14360
9accd112
MM
14361 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14362 "Qbtrace:off", "disable-btrace", 0);
14363
14364 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
14365 "Qbtrace:bts", "enable-btrace-bts", 0);
14366
14367 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14368 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
14369
14370 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14371 "qXfer:btrace", "read-btrace", 0);
14372
f4abbc16
MM
14373 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14374 "qXfer:btrace-conf", "read-btrace-conf", 0);
14375
d33501a5
MM
14376 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14377 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14378
73b8c1fd
PA
14379 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14380 "multiprocess-feature", "multiprocess-feature", 0);
14381
f7e6eed5
PA
14382 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14383 "swbreak-feature", "swbreak-feature", 0);
14384
14385 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14386 "hwbreak-feature", "hwbreak-feature", 0);
14387
89245bc0
DB
14388 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14389 "fork-event-feature", "fork-event-feature", 0);
14390
14391 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14392 "vfork-event-feature", "vfork-event-feature", 0);
14393
b20a6524
MM
14394 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14395 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14396
750ce8d1
YQ
14397 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14398 "vContSupported", "verbose-resume-supported", 0);
14399
94585166
DB
14400 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14401 "exec-event-feature", "exec-event-feature", 0);
14402
de979965
PA
14403 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14404 "vCtrlC", "ctrl-c", 0);
14405
65706a29
PA
14406 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14407 "QThreadEvents", "thread-events", 0);
14408
f2faf941
PA
14409 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14410 "N stop reply", "no-resumed-stop-reply", 0);
14411
0b736949
DB
14412 /* Assert that we've registered "set remote foo-packet" commands
14413 for all packet configs. */
ca4f7f8b
PA
14414 {
14415 int i;
14416
14417 for (i = 0; i < PACKET_MAX; i++)
14418 {
14419 /* Ideally all configs would have a command associated. Some
14420 still don't though. */
14421 int excepted;
14422
14423 switch (i)
14424 {
14425 case PACKET_QNonStop:
ca4f7f8b
PA
14426 case PACKET_EnableDisableTracepoints_feature:
14427 case PACKET_tracenz_feature:
14428 case PACKET_DisconnectedTracing_feature:
14429 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
14430 case PACKET_qCRC:
14431 /* Additions to this list need to be well justified:
14432 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
14433 excepted = 1;
14434 break;
14435 default:
14436 excepted = 0;
14437 break;
14438 }
14439
14440 /* This catches both forgetting to add a config command, and
14441 forgetting to remove a packet from the exception list. */
14442 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14443 }
14444 }
14445
37a105a1
DJ
14446 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14447 Z sub-packet has its own set and show commands, but users may
14448 have sets to this variable in their .gdbinit files (or in their
14449 documentation). */
e9e68a56 14450 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
14451 &remote_Z_packet_detect, _("\
14452Set use of remote protocol `Z' packets"), _("\
14453Show use of remote protocol `Z' packets "), _("\
3b64bf98 14454When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 14455packets."),
e9e68a56 14456 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
14457 show_remote_protocol_Z_packet_cmd,
14458 /* FIXME: i18n: Use of remote protocol
14459 `Z' packets is %s. */
e9e68a56 14460 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 14461
a6b151f1
DJ
14462 add_prefix_cmd ("remote", class_files, remote_command, _("\
14463Manipulate files on the remote system\n\
14464Transfer files to and from the remote target system."),
14465 &remote_cmdlist, "remote ",
14466 0 /* allow-unknown */, &cmdlist);
14467
14468 add_cmd ("put", class_files, remote_put_command,
14469 _("Copy a local file to the remote system."),
14470 &remote_cmdlist);
14471
14472 add_cmd ("get", class_files, remote_get_command,
14473 _("Copy a remote file to the local system."),
14474 &remote_cmdlist);
14475
14476 add_cmd ("delete", class_files, remote_delete_command,
14477 _("Delete a remote file."),
14478 &remote_cmdlist);
14479
2d717e4f 14480 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 14481 &remote_exec_file_var, _("\
2d717e4f 14482Set the remote pathname for \"run\""), _("\
94585166
DB
14483Show the remote pathname for \"run\""), NULL,
14484 set_remote_exec_file,
14485 show_remote_exec_file,
14486 &remote_set_cmdlist,
14487 &remote_show_cmdlist);
2d717e4f 14488
c1e36e3e
PA
14489 add_setshow_boolean_cmd ("range-stepping", class_run,
14490 &use_range_stepping, _("\
14491Enable or disable range stepping."), _("\
14492Show whether target-assisted range stepping is enabled."), _("\
14493If on, and the target supports it, when stepping a source line, GDB\n\
14494tells the target to step the corresponding range of addresses itself instead\n\
14495of issuing multiple single-steps. This speeds up source level\n\
14496stepping. If off, GDB always issues single-steps, even if range\n\
14497stepping is supported by the target. The default is on."),
14498 set_range_stepping,
14499 show_range_stepping,
14500 &setlist,
14501 &showlist);
14502
449092f6
CV
14503 /* Eventually initialize fileio. See fileio.c */
14504 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 14505
ba348170 14506 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 14507 special ptids with it set to != 0. */
ba348170
PA
14508 magic_null_ptid = ptid_build (42000, -1, 1);
14509 not_sent_ptid = ptid_build (42000, -2, 1);
14510 any_thread_ptid = ptid_build (42000, 0, 1);
c906108c 14511}