Support UTF-8 identifiers in C/C++ expressions (PR gdb/22973)
[deliverable/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
e2882c85 3 Copyright (C) 1988-2018 Free Software Foundation, Inc.
c906108c 4
c5aa993b
JM
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
a9762ec7 9 the Free Software Foundation; either version 3 of the License, or
c5aa993b
JM
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
a9762ec7 18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5aa993b 19
23860348 20/* See the GDB User Guide for details of the GDB remote protocol. */
c5aa993b 21
c906108c 22#include "defs.h"
c906108c
SS
23#include <ctype.h>
24#include <fcntl.h>
c906108c 25#include "inferior.h"
45741a9c 26#include "infrun.h"
c906108c
SS
27#include "bfd.h"
28#include "symfile.h"
29#include "target.h"
c5aa993b 30/*#include "terminal.h" */
c906108c
SS
31#include "gdbcmd.h"
32#include "objfiles.h"
33#include "gdb-stabs.h"
34#include "gdbthread.h"
c2c6d25f 35#include "remote.h"
722247f1 36#include "remote-notif.h"
4e052eda 37#include "regcache.h"
fd0407d6 38#include "value.h"
76727919 39#include "observable.h"
a77053c2 40#include "solib.h"
37a105a1
DJ
41#include "cli/cli-decode.h"
42#include "cli/cli-setshow.h"
424163ea 43#include "target-descriptions.h"
a4453b7e 44#include "gdb_bfd.h"
614c279d 45#include "filestuff.h"
9c3d6531 46#include "rsp-low.h"
6b940e6a 47#include "disasm.h"
f00aae0f 48#include "location.h"
c906108c 49
438e1e42 50#include "gdb_sys_time.h"
c906108c 51
43ff13b4 52#include "event-loop.h"
c2c6d25f 53#include "event-top.h"
2acceee2 54#include "inf-loop.h"
43ff13b4 55
c906108c
SS
56#include <signal.h>
57#include "serial.h"
58
6240bebf
MS
59#include "gdbcore.h" /* for exec_bfd */
60
449092f6 61#include "remote-fileio.h"
a6b151f1 62#include "gdb/fileio.h"
53ce3c39 63#include <sys/stat.h>
dc146f7c 64#include "xml-support.h"
449092f6 65
fd79ecee
DJ
66#include "memory-map.h"
67
35b1e5cc
SS
68#include "tracepoint.h"
69#include "ax.h"
70#include "ax-gdb.h"
d1feda86 71#include "agent.h"
9accd112 72#include "btrace.h"
c0272db5 73#include "record-btrace.h"
325fac50 74#include <algorithm>
2ec845e7 75#include "common/scoped_restore.h"
0a2dde4a 76#include "environ.h"
f6327dcb 77#include "common/byte-vector.h"
35b1e5cc 78
f6ac5f3d
PA
79/* The remote target. */
80
d9f719f1
PA
81static const char remote_doc[] = N_("\
82Use a remote computer via a serial line, using a gdb-specific protocol.\n\
83Specify the serial device it is connected to\n\
84(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
85
86static const target_info remote_target_info = {
87 "remote",
88 N_("Remote serial target in gdb-specific protocol"),
89 remote_doc
90};
91
f6ac5f3d
PA
92class remote_target : public target_ops
93{
94public:
95 remote_target ()
96 {
97 to_stratum = process_stratum;
98 }
99
d9f719f1
PA
100 const target_info &info () const override
101 { return remote_target_info; }
f6ac5f3d
PA
102
103 thread_control_capabilities get_thread_control_capabilities () override
104 { return tc_schedlock; }
105
d9f719f1
PA
106 /* Open a remote connection. */
107 static void open (const char *, int);
108
f6ac5f3d
PA
109 void close () override;
110
111 void detach (inferior *, int) override;
112 void disconnect (const char *, int) override;
113
114 void commit_resume () override;
115 void resume (ptid_t, int, enum gdb_signal) override;
116 ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
117
118 void fetch_registers (struct regcache *, int) override;
119 void store_registers (struct regcache *, int) override;
120 void prepare_to_store (struct regcache *) override;
121
122 void files_info () override;
123
124 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
125
126 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
127 enum remove_bp_reason) override;
128
129
57810aa7
PA
130 bool stopped_by_sw_breakpoint () override;
131 bool supports_stopped_by_sw_breakpoint () override;
f6ac5f3d 132
57810aa7 133 bool stopped_by_hw_breakpoint () override;
f6ac5f3d 134
57810aa7 135 bool supports_stopped_by_hw_breakpoint () override;
f6ac5f3d 136
57810aa7 137 bool stopped_by_watchpoint () override;
f6ac5f3d 138
57810aa7 139 bool stopped_data_address (CORE_ADDR *) override;
f6ac5f3d 140
57810aa7 141 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
f6ac5f3d
PA
142
143 int can_use_hw_breakpoint (enum bptype, int, int) override;
144
145 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
146
147 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
148
149 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
150
151 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
152 struct expression *) override;
153
154 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
155 struct expression *) override;
156
157 void kill () override;
158
159 void load (const char *, int) override;
160
161 void mourn_inferior () override;
162
163 void pass_signals (int, unsigned char *) override;
164
165 int set_syscall_catchpoint (int, bool, int,
166 gdb::array_view<const int>) override;
167
168 void program_signals (int, unsigned char *) override;
169
57810aa7 170 bool thread_alive (ptid_t ptid) override;
f6ac5f3d
PA
171
172 const char *thread_name (struct thread_info *) override;
173
174 void update_thread_list () override;
175
176 const char *pid_to_str (ptid_t) override;
177
178 const char *extra_thread_info (struct thread_info *) override;
179
180 ptid_t get_ada_task_ptid (long lwp, long thread) override;
181
182 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
183 int handle_len,
184 inferior *inf) override;
185
186 void stop (ptid_t) override;
187
188 void interrupt () override;
189
190 void pass_ctrlc () override;
191
192 enum target_xfer_status xfer_partial (enum target_object object,
193 const char *annex,
194 gdb_byte *readbuf,
195 const gdb_byte *writebuf,
196 ULONGEST offset, ULONGEST len,
197 ULONGEST *xfered_len) override;
198
199 ULONGEST get_memory_xfer_limit () override;
200
201 void rcmd (const char *command, struct ui_file *output) override;
202
203 char *pid_to_exec_file (int pid) override;
204
205 void log_command (const char *cmd) override
206 {
207 serial_log_command (this, cmd);
208 }
209
210 CORE_ADDR get_thread_local_address (ptid_t ptid,
211 CORE_ADDR load_module_addr,
212 CORE_ADDR offset) override;
213
57810aa7
PA
214 bool has_all_memory () override { return default_child_has_all_memory (); }
215 bool has_memory () override { return default_child_has_memory (); }
216 bool has_stack () override { return default_child_has_stack (); }
217 bool has_registers () override { return default_child_has_registers (); }
218 bool has_execution (ptid_t ptid) override { return default_child_has_execution (ptid); }
f6ac5f3d 219
57810aa7 220 bool can_execute_reverse () override;
f6ac5f3d
PA
221
222 std::vector<mem_region> memory_map () override;
223
224 void flash_erase (ULONGEST address, LONGEST length) override;
225
226 void flash_done () override;
227
228 const struct target_desc *read_description () override;
229
230 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
231 const gdb_byte *pattern, ULONGEST pattern_len,
232 CORE_ADDR *found_addrp) override;
233
57810aa7 234 bool can_async_p () override;
f6ac5f3d 235
57810aa7 236 bool is_async_p () override;
f6ac5f3d
PA
237
238 void async (int) override;
239
240 void thread_events (int) override;
241
242 int can_do_single_step () override;
243
244 void terminal_inferior () override;
245
246 void terminal_ours () override;
247
57810aa7 248 bool supports_non_stop () override;
f6ac5f3d 249
57810aa7 250 bool supports_multi_process () override;
f6ac5f3d 251
57810aa7 252 bool supports_disable_randomization () override;
f6ac5f3d 253
57810aa7 254 bool filesystem_is_local () override;
f6ac5f3d
PA
255
256
257 int fileio_open (struct inferior *inf, const char *filename,
258 int flags, int mode, int warn_if_slow,
259 int *target_errno) override;
260
261 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
262 ULONGEST offset, int *target_errno) override;
263
264 int fileio_pread (int fd, gdb_byte *read_buf, int len,
265 ULONGEST offset, int *target_errno) override;
266
267 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
268
269 int fileio_close (int fd, int *target_errno) override;
270
271 int fileio_unlink (struct inferior *inf,
272 const char *filename,
273 int *target_errno) override;
274
275 gdb::optional<std::string>
276 fileio_readlink (struct inferior *inf,
277 const char *filename,
278 int *target_errno) override;
279
57810aa7 280 bool supports_enable_disable_tracepoint () override;
f6ac5f3d 281
57810aa7 282 bool supports_string_tracing () override;
f6ac5f3d 283
57810aa7 284 bool supports_evaluation_of_breakpoint_conditions () override;
f6ac5f3d 285
57810aa7 286 bool can_run_breakpoint_commands () override;
f6ac5f3d
PA
287
288 void trace_init () override;
289
290 void download_tracepoint (struct bp_location *location) override;
291
57810aa7 292 bool can_download_tracepoint () override;
f6ac5f3d
PA
293
294 void download_trace_state_variable (const trace_state_variable &tsv) override;
295
296 void enable_tracepoint (struct bp_location *location) override;
297
298 void disable_tracepoint (struct bp_location *location) override;
299
300 void trace_set_readonly_regions () override;
301
302 void trace_start () override;
303
304 int get_trace_status (struct trace_status *ts) override;
305
306 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
307 override;
308
309 void trace_stop () override;
310
311 int trace_find (enum trace_find_type type, int num,
312 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
313
57810aa7 314 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
f6ac5f3d
PA
315
316 int save_trace_data (const char *filename) override;
317
318 int upload_tracepoints (struct uploaded_tp **utpp) override;
319
320 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
321
322 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
323
324 int get_min_fast_tracepoint_insn_len () override;
325
326 void set_disconnected_tracing (int val) override;
327
328 void set_circular_trace_buffer (int val) override;
329
330 void set_trace_buffer_size (LONGEST val) override;
331
57810aa7
PA
332 bool set_trace_notes (const char *user, const char *notes,
333 const char *stopnotes) override;
f6ac5f3d
PA
334
335 int core_of_thread (ptid_t ptid) override;
336
337 int verify_memory (const gdb_byte *data,
338 CORE_ADDR memaddr, ULONGEST size) override;
339
340
57810aa7 341 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
f6ac5f3d
PA
342
343 void set_permissions () override;
344
345 bool static_tracepoint_marker_at (CORE_ADDR,
346 struct static_tracepoint_marker *marker)
347 override;
348
349 std::vector<static_tracepoint_marker>
350 static_tracepoint_markers_by_strid (const char *id) override;
351
352 traceframe_info_up traceframe_info () override;
353
57810aa7
PA
354 bool use_agent (bool use) override;
355 bool can_use_agent () override;
f6ac5f3d
PA
356
357 struct btrace_target_info *enable_btrace (ptid_t ptid,
358 const struct btrace_config *conf) override;
359
360 void disable_btrace (struct btrace_target_info *tinfo) override;
361
362 void teardown_btrace (struct btrace_target_info *tinfo) override;
363
364 enum btrace_error read_btrace (struct btrace_data *data,
365 struct btrace_target_info *btinfo,
366 enum btrace_read_type type) override;
367
368 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
57810aa7 369 bool augmented_libraries_svr4_read () override;
f6ac5f3d
PA
370 int follow_fork (int, int) override;
371 void follow_exec (struct inferior *, char *) override;
372 int insert_fork_catchpoint (int) override;
373 int remove_fork_catchpoint (int) override;
374 int insert_vfork_catchpoint (int) override;
375 int remove_vfork_catchpoint (int) override;
376 int insert_exec_catchpoint (int) override;
377 int remove_exec_catchpoint (int) override;
378 enum exec_direction_kind execution_direction () override;
379
380protected:
d9f719f1 381 static void open_1 (const char *name, int from_tty, int extended_p);
f6ac5f3d
PA
382 void start_remote (int from_tty, int extended_p);
383};
384
d9f719f1
PA
385static const target_info extended_remote_target_info = {
386 "extended-remote",
387 N_("Extended remote serial target in gdb-specific protocol"),
388 remote_doc
389};
390
f6ac5f3d
PA
391/* Set up the extended remote target by extending the standard remote
392 target and adding to it. */
393
394class extended_remote_target final : public remote_target
395{
396public:
d9f719f1
PA
397 const target_info &info () const override
398 { return extended_remote_target_info; }
f6ac5f3d 399
d9f719f1
PA
400 /* Open an extended-remote connection. */
401 static void open (const char *, int);
f6ac5f3d
PA
402
403 bool can_create_inferior () override { return true; }
404 void create_inferior (const char *, const std::string &,
405 char **, int) override;
406
407 void detach (inferior *, int) override;
408
409 bool can_attach () override { return true; }
410 void attach (const char *, int) override;
411
412 void post_attach (int) override;
57810aa7 413 bool supports_disable_randomization () override;
f6ac5f3d
PA
414};
415
94585166
DB
416/* Per-program-space data key. */
417static const struct program_space_data *remote_pspace_data;
418
419/* The variable registered as the control variable used by the
420 remote exec-file commands. While the remote exec-file setting is
421 per-program-space, the set/show machinery uses this as the
422 location of the remote exec-file value. */
423static char *remote_exec_file_var;
424
6765f3e5
DJ
425/* The size to align memory write packets, when practical. The protocol
426 does not guarantee any alignment, and gdb will generate short
427 writes and unaligned writes, but even as a best-effort attempt this
428 can improve bulk transfers. For instance, if a write is misaligned
429 relative to the target's data bus, the stub may need to make an extra
430 round trip fetching data from the target. This doesn't make a
431 huge difference, but it's easy to do, so we try to be helpful.
432
433 The alignment chosen is arbitrary; usually data bus width is
434 important here, not the possibly larger cache line size. */
435enum { REMOTE_ALIGN_WRITES = 16 };
436
23860348 437/* Prototypes for local functions. */
6d820c5c 438static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
74531fed 439static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
fee9eda9 440 int forever, int *is_notif);
6426a772 441
cbb8991c
DB
442struct remote_state;
443
444static int remote_vkill (int pid, struct remote_state *rs);
445
8020350c
DB
446static void remote_kill_k (void);
447
a14ed312 448static int readchar (int timeout);
c906108c 449
c33e31fd
PA
450static void remote_serial_write (const char *str, int len);
451
a14ed312 452static void interrupt_query (void);
c906108c 453
d62a8ae2
SM
454static void set_general_thread (ptid_t ptid);
455static void set_continue_thread (ptid_t ptid);
c906108c 456
a14ed312 457static void get_offsets (void);
c906108c 458
6d820c5c
DJ
459static void skip_frame (void);
460
461static long read_frame (char **buf_p, long *sizeof_buf);
c906108c 462
a14ed312 463static int hexnumlen (ULONGEST num);
c906108c 464
a14ed312 465static int stubhex (int ch);
c906108c 466
a14ed312 467static int hexnumstr (char *, ULONGEST);
c906108c 468
a14ed312 469static int hexnumnstr (char *, ULONGEST, int);
2df3850c 470
a14ed312 471static CORE_ADDR remote_address_masked (CORE_ADDR);
c906108c 472
baa336ce 473static void print_packet (const char *);
c906108c 474
a14ed312 475static int stub_unpack_int (char *buff, int fieldlength);
c906108c 476
39f77062 477static ptid_t remote_current_thread (ptid_t oldptid);
c906108c 478
baa336ce 479static int putpkt_binary (const char *buf, int cnt);
c906108c 480
a14ed312 481static void check_binary_download (CORE_ADDR addr);
c906108c 482
5a2468f5 483struct packet_config;
5a2468f5 484
a14ed312 485static void show_packet_config_cmd (struct packet_config *config);
5a2468f5 486
bb572ddd
DJ
487static void show_remote_protocol_packet_cmd (struct ui_file *file,
488 int from_tty,
489 struct cmd_list_element *c,
490 const char *value);
491
82f73884 492static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
256642e8 493static ptid_t read_ptid (const char *buf, const char **obuf);
82f73884 494
c8d104ad
PA
495static void remote_query_supported (void);
496
36d25514 497static void remote_check_symbols (void);
c8d104ad 498
74531fed 499struct stop_reply;
74531fed 500static void stop_reply_xfree (struct stop_reply *);
722247f1 501static void remote_parse_stop_reply (char *, struct stop_reply *);
74531fed 502static void push_stop_reply (struct stop_reply *);
bcc75809 503static void discard_pending_stop_replies_in_queue (struct remote_state *);
74531fed
PA
504static int peek_stop_reply (ptid_t ptid);
505
cbb8991c
DB
506struct threads_listing_context;
507static void remove_new_fork_children (struct threads_listing_context *);
508
74531fed 509static void remote_async_inferior_event_handler (gdb_client_data);
74531fed 510
d962ef82
DJ
511static int remote_read_description_p (struct target_ops *target);
512
176a6961 513static void remote_console_output (char *msg);
dde08ee1 514
f4abbc16
MM
515static void remote_btrace_reset (void);
516
c0272db5
TW
517static void remote_btrace_maybe_reopen (void);
518
221e1a37
PA
519static int stop_reply_queue_length (void);
520
80152258
PA
521static void readahead_cache_invalidate (void);
522
048094ac
PA
523static void remote_unpush_and_throw (void);
524
b6bb3468
PA
525static struct remote_state *get_remote_state (void);
526
a6b151f1
DJ
527/* For "remote". */
528
529static struct cmd_list_element *remote_cmdlist;
530
bb572ddd
DJ
531/* For "set remote" and "show remote". */
532
533static struct cmd_list_element *remote_set_cmdlist;
534static struct cmd_list_element *remote_show_cmdlist;
535
d458bd84
PA
536/* Stub vCont actions support.
537
538 Each field is a boolean flag indicating whether the stub reports
539 support for the corresponding action. */
540
541struct vCont_action_support
542{
543 /* vCont;t */
544 int t;
c1e36e3e
PA
545
546 /* vCont;r */
547 int r;
750ce8d1
YQ
548
549 /* vCont;s */
550 int s;
551
552 /* vCont;S */
553 int S;
d458bd84
PA
554};
555
c1e36e3e
PA
556/* Controls whether GDB is willing to use range stepping. */
557
558static int use_range_stepping = 1;
559
0d031856
TT
560#define OPAQUETHREADBYTES 8
561
562/* a 64 bit opaque identifier */
563typedef unsigned char threadref[OPAQUETHREADBYTES];
564
565/* About this many threadisds fit in a packet. */
566
567#define MAXTHREADLISTRESULTS 32
568
6f8976bf
YQ
569/* The max number of chars in debug output. The rest of chars are
570 omitted. */
571
572#define REMOTE_DEBUG_MAX_CHAR 512
573
80152258
PA
574/* Data for the vFile:pread readahead cache. */
575
576struct readahead_cache
577{
578 /* The file descriptor for the file that is being cached. -1 if the
579 cache is invalid. */
580 int fd;
581
582 /* The offset into the file that the cache buffer corresponds
583 to. */
584 ULONGEST offset;
585
586 /* The buffer holding the cache contents. */
587 gdb_byte *buf;
588 /* The buffer's size. We try to read as much as fits into a packet
589 at a time. */
590 size_t bufsize;
591
592 /* Cache hit and miss counters. */
593 ULONGEST hit_count;
594 ULONGEST miss_count;
595};
596
ea9c271d
DJ
597/* Description of the remote protocol state for the currently
598 connected target. This is per-target state, and independent of the
599 selected architecture. */
600
601struct remote_state
602{
603 /* A buffer to use for incoming packets, and its current size. The
604 buffer is grown dynamically for larger incoming packets.
605 Outgoing packets may also be constructed in this buffer.
606 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
607 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
608 packets. */
609 char *buf;
610 long buf_size;
be2a5f71 611
1e51243a
PA
612 /* True if we're going through initial connection setup (finding out
613 about the remote side's threads, relocating symbols, etc.). */
614 int starting_up;
615
be2a5f71
DJ
616 /* If we negotiated packet size explicitly (and thus can bypass
617 heuristics for the largest packet size that will not overflow
618 a buffer in the stub), this will be set to that packet size.
619 Otherwise zero, meaning to use the guessed size. */
620 long explicit_packet_size;
2d717e4f
DJ
621
622 /* remote_wait is normally called when the target is running and
623 waits for a stop reply packet. But sometimes we need to call it
624 when the target is already stopped. We can send a "?" packet
625 and have remote_wait read the response. Or, if we already have
626 the response, we can stash it in BUF and tell remote_wait to
627 skip calling getpkt. This flag is set when BUF contains a
628 stop reply packet and the target is not waiting. */
629 int cached_wait_status;
a6f3e723
SL
630
631 /* True, if in no ack mode. That is, neither GDB nor the stub will
632 expect acks from each other. The connection is assumed to be
633 reliable. */
634 int noack_mode;
82f73884
PA
635
636 /* True if we're connected in extended remote mode. */
637 int extended;
638
e24a49d8
PA
639 /* True if we resumed the target and we're waiting for the target to
640 stop. In the mean time, we can't start another command/query.
641 The remote server wouldn't be ready to process it, so we'd
642 timeout waiting for a reply that would never come and eventually
643 we'd close the connection. This can happen in asynchronous mode
644 because we allow GDB commands while the target is running. */
645 int waiting_for_stop_reply;
74531fed 646
d458bd84
PA
647 /* The status of the stub support for the various vCont actions. */
648 struct vCont_action_support supports_vCont;
782b2b07 649
3a29589a
DJ
650 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
651 responded to that. */
652 int ctrlc_pending_p;
5d93a237 653
048094ac
PA
654 /* True if we saw a Ctrl-C while reading or writing from/to the
655 remote descriptor. At that point it is not safe to send a remote
656 interrupt packet, so we instead remember we saw the Ctrl-C and
657 process it once we're done with sending/receiving the current
658 packet, which should be shortly. If however that takes too long,
659 and the user presses Ctrl-C again, we offer to disconnect. */
660 int got_ctrlc_during_io;
661
5d93a237
TT
662 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
663 remote_open knows that we don't have a file open when the program
664 starts. */
665 struct serial *remote_desc;
47f8a51d
TT
666
667 /* These are the threads which we last sent to the remote system. The
668 TID member will be -1 for all or -2 for not sent yet. */
669 ptid_t general_thread;
670 ptid_t continue_thread;
262e1174
TT
671
672 /* This is the traceframe which we last selected on the remote system.
673 It will be -1 if no traceframe is selected. */
674 int remote_traceframe_number;
747dc59d
TT
675
676 char *last_pass_packet;
5e4a05c4
TT
677
678 /* The last QProgramSignals packet sent to the target. We bypass
679 sending a new program signals list down to the target if the new
680 packet is exactly the same as the last we sent. IOW, we only let
681 the target know about program signals list changes. */
682 char *last_program_signals_packet;
b73be471
TT
683
684 enum gdb_signal last_sent_signal;
280ceea3
TT
685
686 int last_sent_step;
8e88304f 687
3a00c802
PA
688 /* The execution direction of the last resume we got. */
689 enum exec_direction_kind last_resume_exec_dir;
690
8e88304f
TT
691 char *finished_object;
692 char *finished_annex;
693 ULONGEST finished_offset;
b80fafe3
TT
694
695 /* Should we try the 'ThreadInfo' query packet?
696
697 This variable (NOT available to the user: auto-detect only!)
698 determines whether GDB will use the new, simpler "ThreadInfo"
699 query or the older, more complex syntax for thread queries.
700 This is an auto-detect variable (set to true at each connect,
701 and set to false when the target fails to recognize it). */
702 int use_threadinfo_query;
703 int use_threadextra_query;
88b496c3 704
0d031856
TT
705 threadref echo_nextthread;
706 threadref nextthread;
707 threadref resultthreadlist[MAXTHREADLISTRESULTS];
5965e028
YQ
708
709 /* The state of remote notification. */
710 struct remote_notif_state *notif_state;
f4abbc16
MM
711
712 /* The branch trace configuration. */
713 struct btrace_config btrace_config;
15a201c8
GB
714
715 /* The argument to the last "vFile:setfs:" packet we sent, used
716 to avoid sending repeated unnecessary "vFile:setfs:" packets.
717 Initialized to -1 to indicate that no "vFile:setfs:" packet
718 has yet been sent. */
719 int fs_pid;
80152258
PA
720
721 /* A readahead cache for vFile:pread. Often, reading a binary
722 involves a sequence of small reads. E.g., when parsing an ELF
723 file. A readahead cache helps mostly the case of remote
724 debugging on a connection with higher latency, due to the
725 request/reply nature of the RSP. We only cache data for a single
726 file descriptor at a time. */
727 struct readahead_cache readahead_cache;
ea9c271d
DJ
728};
729
7aabaf9d
SM
730/* Private data that we'll store in (struct thread_info)->priv. */
731struct remote_thread_info : public private_thread_info
dc146f7c 732{
7aabaf9d
SM
733 std::string extra;
734 std::string name;
735 int core = -1;
799a2abe 736
f6327dcb
KB
737 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
738 sequence of bytes. */
7aabaf9d 739 gdb::byte_vector thread_handle;
f6327dcb 740
799a2abe 741 /* Whether the target stopped for a breakpoint/watchpoint. */
7aabaf9d 742 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
799a2abe
PA
743
744 /* This is set to the data address of the access causing the target
745 to stop for a watchpoint. */
7aabaf9d 746 CORE_ADDR watch_data_address = 0;
85ad3aaf
PA
747
748 /* Fields used by the vCont action coalescing implemented in
749 remote_resume / remote_commit_resume. remote_resume stores each
750 thread's last resume request in these fields, so that a later
751 remote_commit_resume knows which is the proper action for this
752 thread to include in the vCont packet. */
753
754 /* True if the last target_resume call for this thread was a step
755 request, false if a continue request. */
7aabaf9d 756 int last_resume_step = 0;
85ad3aaf
PA
757
758 /* The signal specified in the last target_resume call for this
759 thread. */
7aabaf9d 760 gdb_signal last_resume_sig = GDB_SIGNAL_0;
85ad3aaf
PA
761
762 /* Whether this thread was already vCont-resumed on the remote
763 side. */
7aabaf9d 764 int vcont_resumed = 0;
dc146f7c
VP
765};
766
ea9c271d
DJ
767/* This data could be associated with a target, but we do not always
768 have access to the current target when we need it, so for now it is
769 static. This will be fine for as long as only one target is in use
770 at a time. */
cf792862 771static struct remote_state *remote_state;
ea9c271d
DJ
772
773static struct remote_state *
0b83947e 774get_remote_state_raw (void)
ea9c271d 775{
cf792862
TT
776 return remote_state;
777}
778
779/* Allocate a new struct remote_state with xmalloc, initialize it, and
780 return it. */
781
782static struct remote_state *
783new_remote_state (void)
784{
785 struct remote_state *result = XCNEW (struct remote_state);
786
787 /* The default buffer size is unimportant; it will be expanded
788 whenever a larger buffer is needed. */
789 result->buf_size = 400;
224c3ddb 790 result->buf = (char *) xmalloc (result->buf_size);
262e1174 791 result->remote_traceframe_number = -1;
b73be471 792 result->last_sent_signal = GDB_SIGNAL_0;
3a00c802 793 result->last_resume_exec_dir = EXEC_FORWARD;
15a201c8 794 result->fs_pid = -1;
cf792862
TT
795
796 return result;
ea9c271d
DJ
797}
798
799/* Description of the remote protocol for a given architecture. */
d01949b6 800
ad10f812
AC
801struct packet_reg
802{
803 long offset; /* Offset into G packet. */
804 long regnum; /* GDB's internal register number. */
805 LONGEST pnum; /* Remote protocol register number. */
b323314b 806 int in_g_packet; /* Always part of G packet. */
f5656ead 807 /* long size in bytes; == register_size (target_gdbarch (), regnum);
23860348 808 at present. */
f5656ead 809 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
c9f4d572 810 at present. */
ad10f812
AC
811};
812
ea9c271d 813struct remote_arch_state
d01949b6 814{
ad10f812
AC
815 /* Description of the remote protocol registers. */
816 long sizeof_g_packet;
b323314b
AC
817
818 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 819 (making an array gdbarch_num_regs in size). */
b323314b 820 struct packet_reg *regs;
ad10f812 821
d01949b6
AC
822 /* This is the size (in chars) of the first response to the ``g''
823 packet. It is used as a heuristic when determining the maximum
824 size of memory-read and memory-write packets. A target will
825 typically only reserve a buffer large enough to hold the ``g''
826 packet. The size does not include packet overhead (headers and
23860348 827 trailers). */
d01949b6
AC
828 long actual_register_packet_size;
829
830 /* This is the maximum size (in chars) of a non read/write packet.
23860348 831 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
832 long remote_packet_size;
833};
834
35b1e5cc
SS
835/* Utility: generate error from an incoming stub packet. */
836static void
837trace_error (char *buf)
838{
839 if (*buf++ != 'E')
840 return; /* not an error msg */
841 switch (*buf)
842 {
843 case '1': /* malformed packet error */
844 if (*++buf == '0') /* general case: */
845 error (_("remote.c: error in outgoing packet."));
846 else
847 error (_("remote.c: error in outgoing packet at field #%ld."),
848 strtol (buf, NULL, 16));
35b1e5cc
SS
849 default:
850 error (_("Target returns error code '%s'."), buf);
851 }
852}
853
854/* Utility: wait for reply from stub, while accepting "O" packets. */
b6bb3468 855
35b1e5cc 856static char *
b6bb3468 857remote_get_noisy_reply ()
35b1e5cc 858{
b6bb3468
PA
859 struct remote_state *rs = get_remote_state ();
860
35b1e5cc
SS
861 do /* Loop on reply from remote stub. */
862 {
863 char *buf;
a744cf53 864
0df8b418 865 QUIT; /* Allow user to bail out with ^C. */
b6bb3468
PA
866 getpkt (&rs->buf, &rs->buf_size, 0);
867 buf = rs->buf;
ad91cd99 868 if (buf[0] == 'E')
35b1e5cc 869 trace_error (buf);
61012eef 870 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
871 {
872 ULONGEST ul;
873 CORE_ADDR from, to, org_to;
256642e8 874 const char *p, *pp;
dde08ee1 875 int adjusted_size = 0;
7556d4a4 876 int relocated = 0;
dde08ee1
PA
877
878 p = buf + strlen ("qRelocInsn:");
879 pp = unpack_varlen_hex (p, &ul);
880 if (*pp != ';')
cb91c06a 881 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
882 from = ul;
883
884 p = pp + 1;
a9cbf802 885 unpack_varlen_hex (p, &ul);
dde08ee1
PA
886 to = ul;
887
888 org_to = to;
889
492d29ea 890 TRY
dde08ee1 891 {
f5656ead 892 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 893 relocated = 1;
dde08ee1 894 }
492d29ea 895 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
896 {
897 if (ex.error == MEMORY_ERROR)
898 {
899 /* Propagate memory errors silently back to the
900 target. The stub may have limited the range of
901 addresses we can write to, for example. */
902 }
903 else
904 {
905 /* Something unexpectedly bad happened. Be verbose
906 so we can tell what, and propagate the error back
907 to the stub, so it doesn't get stuck waiting for
908 a response. */
909 exception_fprintf (gdb_stderr, ex,
910 _("warning: relocating instruction: "));
911 }
912 putpkt ("E01");
913 }
492d29ea 914 END_CATCH
7556d4a4
PA
915
916 if (relocated)
dde08ee1
PA
917 {
918 adjusted_size = to - org_to;
919
b6bb3468 920 xsnprintf (buf, rs->buf_size, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
921 putpkt (buf);
922 }
dde08ee1 923 }
ad91cd99 924 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
925 remote_console_output (buf + 1); /* 'O' message from stub */
926 else
0df8b418 927 return buf; /* Here's the actual reply. */
35b1e5cc
SS
928 }
929 while (1);
930}
3c3bea1c 931
d01949b6
AC
932/* Handle for retreving the remote protocol data from gdbarch. */
933static struct gdbarch_data *remote_gdbarch_data_handle;
934
ea9c271d 935static struct remote_arch_state *
5cd63fda 936get_remote_arch_state (struct gdbarch *gdbarch)
d01949b6 937{
5cd63fda 938 gdb_assert (gdbarch != NULL);
19ba03f4 939 return ((struct remote_arch_state *)
5cd63fda 940 gdbarch_data (gdbarch, remote_gdbarch_data_handle));
d01949b6
AC
941}
942
0b83947e
DJ
943/* Fetch the global remote target state. */
944
945static struct remote_state *
946get_remote_state (void)
947{
948 /* Make sure that the remote architecture state has been
949 initialized, because doing so might reallocate rs->buf. Any
950 function which calls getpkt also needs to be mindful of changes
951 to rs->buf, but this call limits the number of places which run
952 into trouble. */
5cd63fda 953 get_remote_arch_state (target_gdbarch ());
0b83947e
DJ
954
955 return get_remote_state_raw ();
956}
957
94585166
DB
958/* Cleanup routine for the remote module's pspace data. */
959
960static void
961remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
962{
19ba03f4 963 char *remote_exec_file = (char *) arg;
94585166
DB
964
965 xfree (remote_exec_file);
966}
967
968/* Fetch the remote exec-file from the current program space. */
969
970static const char *
971get_remote_exec_file (void)
972{
973 char *remote_exec_file;
974
19ba03f4
SM
975 remote_exec_file
976 = (char *) program_space_data (current_program_space,
977 remote_pspace_data);
94585166
DB
978 if (remote_exec_file == NULL)
979 return "";
980
981 return remote_exec_file;
982}
983
984/* Set the remote exec file for PSPACE. */
985
986static void
987set_pspace_remote_exec_file (struct program_space *pspace,
988 char *remote_exec_file)
989{
19ba03f4 990 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
94585166
DB
991
992 xfree (old_file);
993 set_program_space_data (pspace, remote_pspace_data,
994 xstrdup (remote_exec_file));
995}
996
997/* The "set/show remote exec-file" set command hook. */
998
999static void
eb4c3f4a 1000set_remote_exec_file (const char *ignored, int from_tty,
94585166
DB
1001 struct cmd_list_element *c)
1002{
1003 gdb_assert (remote_exec_file_var != NULL);
1004 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
1005}
1006
1007/* The "set/show remote exec-file" show command hook. */
1008
1009static void
1010show_remote_exec_file (struct ui_file *file, int from_tty,
1011 struct cmd_list_element *cmd, const char *value)
1012{
1013 fprintf_filtered (file, "%s\n", remote_exec_file_var);
1014}
1015
74ca34ce
DJ
1016static int
1017compare_pnums (const void *lhs_, const void *rhs_)
1018{
19ba03f4
SM
1019 const struct packet_reg * const *lhs
1020 = (const struct packet_reg * const *) lhs_;
1021 const struct packet_reg * const *rhs
1022 = (const struct packet_reg * const *) rhs_;
74ca34ce
DJ
1023
1024 if ((*lhs)->pnum < (*rhs)->pnum)
1025 return -1;
1026 else if ((*lhs)->pnum == (*rhs)->pnum)
1027 return 0;
1028 else
1029 return 1;
1030}
1031
c21236dc
PA
1032static int
1033map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 1034{
74ca34ce 1035 int regnum, num_remote_regs, offset;
74ca34ce 1036 struct packet_reg **remote_regs;
ea9c271d 1037
4a22f64d 1038 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 1039 {
c21236dc 1040 struct packet_reg *r = &regs[regnum];
baef701f 1041
4a22f64d 1042 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
1043 /* Do not try to fetch zero-sized (placeholder) registers. */
1044 r->pnum = -1;
1045 else
1046 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1047
b323314b 1048 r->regnum = regnum;
74ca34ce
DJ
1049 }
1050
1051 /* Define the g/G packet format as the contents of each register
1052 with a remote protocol number, in order of ascending protocol
1053 number. */
1054
224c3ddb 1055 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 1056 for (num_remote_regs = 0, regnum = 0;
4a22f64d 1057 regnum < gdbarch_num_regs (gdbarch);
f57d151a 1058 regnum++)
c21236dc
PA
1059 if (regs[regnum].pnum != -1)
1060 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 1061
74ca34ce
DJ
1062 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
1063 compare_pnums);
1064
1065 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1066 {
1067 remote_regs[regnum]->in_g_packet = 1;
1068 remote_regs[regnum]->offset = offset;
4a22f64d 1069 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
1070 }
1071
c21236dc
PA
1072 return offset;
1073}
1074
1075/* Given the architecture described by GDBARCH, return the remote
1076 protocol register's number and the register's offset in the g/G
1077 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1078 If the target does not have a mapping for REGNUM, return false,
1079 otherwise, return true. */
1080
1081int
1082remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1083 int *pnum, int *poffset)
1084{
c21236dc
PA
1085 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1086
b80406ac 1087 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
c21236dc 1088
b80406ac 1089 map_regcache_remote_table (gdbarch, regs.data ());
c21236dc
PA
1090
1091 *pnum = regs[regnum].pnum;
1092 *poffset = regs[regnum].offset;
1093
c21236dc
PA
1094 return *pnum != -1;
1095}
1096
1097static void *
1098init_remote_state (struct gdbarch *gdbarch)
1099{
1100 struct remote_state *rs = get_remote_state_raw ();
1101 struct remote_arch_state *rsa;
1102
1103 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
1104
1105 /* Use the architecture to build a regnum<->pnum table, which will be
1106 1:1 unless a feature set specifies otherwise. */
1107 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
1108 gdbarch_num_regs (gdbarch),
1109 struct packet_reg);
1110
74ca34ce
DJ
1111 /* Record the maximum possible size of the g packet - it may turn out
1112 to be smaller. */
c21236dc 1113 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 1114
0df8b418 1115 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
1116 remote stubs have a hardwired buffer size of 400 bytes
1117 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1118 as the maximum packet-size to ensure that the packet and an extra
1119 NUL character can always fit in the buffer. This stops GDB
1120 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
1121 already a full buffer (As of 1999-12-04 that was most stubs). */
1122 rsa->remote_packet_size = 400 - 1;
d01949b6 1123
ea9c271d
DJ
1124 /* This one is filled in when a ``g'' packet is received. */
1125 rsa->actual_register_packet_size = 0;
1126
1127 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
1128 default, adjust the size accordingly. Remember that each byte is
1129 encoded as two characters. 32 is the overhead for the packet
1130 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 1131 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 1132 little. */
ea9c271d
DJ
1133 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
1134 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 1135
ea9c271d
DJ
1136 /* Make sure that the packet buffer is plenty big enough for
1137 this architecture. */
1138 if (rs->buf_size < rsa->remote_packet_size)
1139 {
1140 rs->buf_size = 2 * rsa->remote_packet_size;
224c3ddb 1141 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
ea9c271d 1142 }
6d820c5c 1143
ea9c271d
DJ
1144 return rsa;
1145}
1146
1147/* Return the current allowed size of a remote packet. This is
1148 inferred from the current architecture, and should be used to
1149 limit the length of outgoing packets. */
1150static long
1151get_remote_packet_size (void)
1152{
be2a5f71 1153 struct remote_state *rs = get_remote_state ();
5cd63fda 1154 remote_arch_state *rsa = get_remote_arch_state (target_gdbarch ());
ea9c271d 1155
be2a5f71
DJ
1156 if (rs->explicit_packet_size)
1157 return rs->explicit_packet_size;
1158
ea9c271d 1159 return rsa->remote_packet_size;
d01949b6
AC
1160}
1161
ad10f812 1162static struct packet_reg *
5cd63fda
PA
1163packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1164 long regnum)
ad10f812 1165{
5cd63fda 1166 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
b323314b
AC
1167 return NULL;
1168 else
ad10f812 1169 {
ea9c271d 1170 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 1171
b323314b
AC
1172 gdb_assert (r->regnum == regnum);
1173 return r;
ad10f812 1174 }
ad10f812
AC
1175}
1176
1177static struct packet_reg *
5cd63fda
PA
1178packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1179 LONGEST pnum)
ad10f812 1180{
b323314b 1181 int i;
a744cf53 1182
5cd63fda 1183 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
ad10f812 1184 {
ea9c271d 1185 struct packet_reg *r = &rsa->regs[i];
a744cf53 1186
b323314b
AC
1187 if (r->pnum == pnum)
1188 return r;
ad10f812
AC
1189 }
1190 return NULL;
d01949b6
AC
1191}
1192
f6ac5f3d 1193static remote_target remote_ops;
c906108c 1194
f6ac5f3d 1195static extended_remote_target extended_remote_ops;
c906108c 1196
6426a772
JM
1197/* FIXME: cagney/1999-09-23: Even though getpkt was called with
1198 ``forever'' still use the normal timeout mechanism. This is
1199 currently used by the ASYNC code to guarentee that target reads
1200 during the initial connect always time-out. Once getpkt has been
1201 modified to return a timeout indication and, in turn
1202 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 1203 this can go away. */
6426a772
JM
1204static int wait_forever_enabled_p = 1;
1205
9a7071a8
JB
1206/* Allow the user to specify what sequence to send to the remote
1207 when he requests a program interruption: Although ^C is usually
1208 what remote systems expect (this is the default, here), it is
1209 sometimes preferable to send a break. On other systems such
1210 as the Linux kernel, a break followed by g, which is Magic SysRq g
1211 is required in order to interrupt the execution. */
1212const char interrupt_sequence_control_c[] = "Ctrl-C";
1213const char interrupt_sequence_break[] = "BREAK";
1214const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 1215static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
1216 {
1217 interrupt_sequence_control_c,
1218 interrupt_sequence_break,
1219 interrupt_sequence_break_g,
1220 NULL
1221 };
1222static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1223
1224static void
1225show_interrupt_sequence (struct ui_file *file, int from_tty,
1226 struct cmd_list_element *c,
1227 const char *value)
1228{
1229 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1230 fprintf_filtered (file,
1231 _("Send the ASCII ETX character (Ctrl-c) "
1232 "to the remote target to interrupt the "
1233 "execution of the program.\n"));
1234 else if (interrupt_sequence_mode == interrupt_sequence_break)
1235 fprintf_filtered (file,
1236 _("send a break signal to the remote target "
1237 "to interrupt the execution of the program.\n"));
1238 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1239 fprintf_filtered (file,
1240 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1241 "the remote target to interrupt the execution "
1242 "of Linux kernel.\n"));
1243 else
1244 internal_error (__FILE__, __LINE__,
1245 _("Invalid value for interrupt_sequence_mode: %s."),
1246 interrupt_sequence_mode);
1247}
6426a772 1248
9a7071a8
JB
1249/* This boolean variable specifies whether interrupt_sequence is sent
1250 to the remote target when gdb connects to it.
1251 This is mostly needed when you debug the Linux kernel: The Linux kernel
1252 expects BREAK g which is Magic SysRq g for connecting gdb. */
1253static int interrupt_on_connect = 0;
c906108c 1254
9a7071a8
JB
1255/* This variable is used to implement the "set/show remotebreak" commands.
1256 Since these commands are now deprecated in favor of "set/show remote
1257 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
1258static int remote_break;
1259
9a7071a8 1260static void
eb4c3f4a 1261set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
9a7071a8
JB
1262{
1263 if (remote_break)
1264 interrupt_sequence_mode = interrupt_sequence_break;
1265 else
1266 interrupt_sequence_mode = interrupt_sequence_control_c;
1267}
1268
1269static void
1270show_remotebreak (struct ui_file *file, int from_tty,
1271 struct cmd_list_element *c,
1272 const char *value)
1273{
1274}
1275
c906108c
SS
1276/* This variable sets the number of bits in an address that are to be
1277 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 1278 leading zeros, the entire address would be sent. This variable
c906108c
SS
1279 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1280 initial implementation of remote.c restricted the address sent in
1281 memory packets to ``host::sizeof long'' bytes - (typically 32
1282 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1283 address was never sent. Since fixing this bug may cause a break in
1284 some remote targets this variable is principly provided to
23860348 1285 facilitate backward compatibility. */
c906108c 1286
883b9c6c 1287static unsigned int remote_address_size;
c906108c 1288
11cf8741 1289\f
11cf8741 1290/* User configurable variables for the number of characters in a
ea9c271d
DJ
1291 memory read/write packet. MIN (rsa->remote_packet_size,
1292 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 1293 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
1294 (speed up transfers). The variables ``preferred_*'' (the user
1295 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 1296 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
1297
1298struct memory_packet_config
1299{
a121b7c1 1300 const char *name;
11cf8741
JM
1301 long size;
1302 int fixed_p;
1303};
1304
a5c0808e
PA
1305/* The default max memory-write-packet-size. The 16k is historical.
1306 (It came from older GDB's using alloca for buffers and the
1307 knowledge (folklore?) that some hosts don't cope very well with
1308 large alloca calls.) */
1309#define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1310
1311/* The minimum remote packet size for memory transfers. Ensures we
1312 can write at least one byte. */
1313#define MIN_MEMORY_PACKET_SIZE 20
1314
11cf8741
JM
1315/* Compute the current size of a read/write packet. Since this makes
1316 use of ``actual_register_packet_size'' the computation is dynamic. */
1317
1318static long
1319get_memory_packet_size (struct memory_packet_config *config)
1320{
d01949b6 1321 struct remote_state *rs = get_remote_state ();
5cd63fda 1322 remote_arch_state *rsa = get_remote_arch_state (target_gdbarch ());
ea9c271d 1323
11cf8741
JM
1324 long what_they_get;
1325 if (config->fixed_p)
1326 {
1327 if (config->size <= 0)
a5c0808e 1328 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
11cf8741
JM
1329 else
1330 what_they_get = config->size;
1331 }
1332 else
1333 {
ea9c271d 1334 what_they_get = get_remote_packet_size ();
23860348 1335 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1336 if (config->size > 0
1337 && what_they_get > config->size)
1338 what_they_get = config->size;
be2a5f71
DJ
1339
1340 /* Limit it to the size of the targets ``g'' response unless we have
1341 permission from the stub to use a larger packet size. */
1342 if (rs->explicit_packet_size == 0
1343 && rsa->actual_register_packet_size > 0
1344 && what_they_get > rsa->actual_register_packet_size)
1345 what_they_get = rsa->actual_register_packet_size;
11cf8741 1346 }
a5c0808e
PA
1347 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1348 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1349
1350 /* Make sure there is room in the global buffer for this packet
1351 (including its trailing NUL byte). */
1352 if (rs->buf_size < what_they_get + 1)
1353 {
1354 rs->buf_size = 2 * what_they_get;
224c3ddb 1355 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
6d820c5c
DJ
1356 }
1357
11cf8741
JM
1358 return what_they_get;
1359}
1360
0df8b418 1361/* Update the size of a read/write packet. If they user wants
23860348 1362 something really big then do a sanity check. */
11cf8741
JM
1363
1364static void
ac88e2de 1365set_memory_packet_size (const char *args, struct memory_packet_config *config)
11cf8741
JM
1366{
1367 int fixed_p = config->fixed_p;
1368 long size = config->size;
a744cf53 1369
11cf8741 1370 if (args == NULL)
8a3fe4f8 1371 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1372 else if (strcmp (args, "hard") == 0
1373 || strcmp (args, "fixed") == 0)
1374 fixed_p = 1;
1375 else if (strcmp (args, "soft") == 0
1376 || strcmp (args, "limit") == 0)
1377 fixed_p = 0;
1378 else
1379 {
1380 char *end;
a744cf53 1381
11cf8741
JM
1382 size = strtoul (args, &end, 0);
1383 if (args == end)
8a3fe4f8 1384 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1385
1386 /* Instead of explicitly capping the size of a packet to or
1387 disallowing it, the user is allowed to set the size to
1388 something arbitrarily large. */
11cf8741 1389 }
a5c0808e
PA
1390
1391 /* So that the query shows the correct value. */
1392 if (size <= 0)
1393 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1394
23860348 1395 /* Extra checks? */
11cf8741
JM
1396 if (fixed_p && !config->fixed_p)
1397 {
e2e0b3e5
AC
1398 if (! query (_("The target may not be able to correctly handle a %s\n"
1399 "of %ld bytes. Change the packet size? "),
11cf8741 1400 config->name, size))
8a3fe4f8 1401 error (_("Packet size not changed."));
11cf8741 1402 }
23860348 1403 /* Update the config. */
11cf8741
JM
1404 config->fixed_p = fixed_p;
1405 config->size = size;
1406}
1407
1408static void
1409show_memory_packet_size (struct memory_packet_config *config)
1410{
a3f17187 1411 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1412 if (config->fixed_p)
a3f17187 1413 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
1414 get_memory_packet_size (config));
1415 else
a3f17187 1416 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
1417 get_memory_packet_size (config));
1418}
1419
1420static struct memory_packet_config memory_write_packet_config =
1421{
1422 "memory-write-packet-size",
1423};
1424
1425static void
ac88e2de 1426set_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1427{
1428 set_memory_packet_size (args, &memory_write_packet_config);
1429}
1430
1431static void
ac88e2de 1432show_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1433{
1434 show_memory_packet_size (&memory_write_packet_config);
1435}
1436
1437static long
1438get_memory_write_packet_size (void)
1439{
1440 return get_memory_packet_size (&memory_write_packet_config);
1441}
1442
1443static struct memory_packet_config memory_read_packet_config =
1444{
1445 "memory-read-packet-size",
1446};
1447
1448static void
ac88e2de 1449set_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1450{
1451 set_memory_packet_size (args, &memory_read_packet_config);
1452}
1453
1454static void
ac88e2de 1455show_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1456{
1457 show_memory_packet_size (&memory_read_packet_config);
1458}
1459
1460static long
1461get_memory_read_packet_size (void)
1462{
1463 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1464
11cf8741
JM
1465 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1466 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1467 increased beyond this. */
1468 if (size > get_remote_packet_size ())
1469 size = get_remote_packet_size ();
11cf8741
JM
1470 return size;
1471}
1472
11cf8741 1473\f
5a2468f5 1474/* Generic configuration support for packets the stub optionally
0df8b418 1475 supports. Allows the user to specify the use of the packet as well
23860348 1476 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1477
1478enum packet_support
1479 {
1480 PACKET_SUPPORT_UNKNOWN = 0,
1481 PACKET_ENABLE,
1482 PACKET_DISABLE
1483 };
1484
5a2468f5
JM
1485struct packet_config
1486 {
bb572ddd
DJ
1487 const char *name;
1488 const char *title;
4082afcc
PA
1489
1490 /* If auto, GDB auto-detects support for this packet or feature,
1491 either through qSupported, or by trying the packet and looking
1492 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1493 packet. If false, the packet is disabled. Configs that don't
1494 have an associated command always have this set to auto. */
7f19b9a2 1495 enum auto_boolean detect;
4082afcc
PA
1496
1497 /* Does the target support this packet? */
5a2468f5
JM
1498 enum packet_support support;
1499 };
1500
d471ea57 1501/* Analyze a packet's return value and update the packet config
23860348 1502 accordingly. */
d471ea57
AC
1503
1504enum packet_result
1505{
1506 PACKET_ERROR,
1507 PACKET_OK,
1508 PACKET_UNKNOWN
1509};
1510
4082afcc
PA
1511static enum packet_support packet_config_support (struct packet_config *config);
1512static enum packet_support packet_support (int packet);
5a2468f5
JM
1513
1514static void
fba45db2 1515show_packet_config_cmd (struct packet_config *config)
5a2468f5 1516{
a121b7c1 1517 const char *support = "internal-error";
a744cf53 1518
4082afcc 1519 switch (packet_config_support (config))
5a2468f5
JM
1520 {
1521 case PACKET_ENABLE:
1522 support = "enabled";
1523 break;
1524 case PACKET_DISABLE:
1525 support = "disabled";
1526 break;
1527 case PACKET_SUPPORT_UNKNOWN:
1528 support = "unknown";
1529 break;
1530 }
1531 switch (config->detect)
1532 {
7f19b9a2 1533 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1534 printf_filtered (_("Support for the `%s' packet "
1535 "is auto-detected, currently %s.\n"),
37a105a1 1536 config->name, support);
5a2468f5 1537 break;
7f19b9a2
AC
1538 case AUTO_BOOLEAN_TRUE:
1539 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1540 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1541 config->name, support);
8e248173 1542 break;
5a2468f5
JM
1543 }
1544}
1545
1546static void
bb572ddd
DJ
1547add_packet_config_cmd (struct packet_config *config, const char *name,
1548 const char *title, int legacy)
d471ea57 1549{
5a2468f5
JM
1550 char *set_doc;
1551 char *show_doc;
d471ea57 1552 char *cmd_name;
3ed07be4 1553
5a2468f5
JM
1554 config->name = name;
1555 config->title = title;
b435e160
AC
1556 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1557 name, title);
3e43a32a
MS
1558 show_doc = xstrprintf ("Show current use of remote "
1559 "protocol `%s' (%s) packet",
b435e160 1560 name, title);
d471ea57 1561 /* set/show TITLE-packet {auto,on,off} */
b435e160 1562 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1563 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1564 &config->detect, set_doc,
1565 show_doc, NULL, /* help_doc */
4082afcc 1566 NULL,
bb572ddd
DJ
1567 show_remote_protocol_packet_cmd,
1568 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1569 /* The command code copies the documentation strings. */
1570 xfree (set_doc);
1571 xfree (show_doc);
23860348 1572 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1573 if (legacy)
1574 {
1575 char *legacy_name;
a744cf53 1576
b435e160 1577 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1578 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1579 &remote_set_cmdlist);
d471ea57 1580 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1581 &remote_show_cmdlist);
d471ea57 1582 }
5a2468f5
JM
1583}
1584
d471ea57 1585static enum packet_result
a76d924d 1586packet_check_result (const char *buf)
5a2468f5 1587{
d471ea57 1588 if (buf[0] != '\0')
5a2468f5 1589 {
d471ea57 1590 /* The stub recognized the packet request. Check that the
23860348 1591 operation succeeded. */
a76d924d
DJ
1592 if (buf[0] == 'E'
1593 && isxdigit (buf[1]) && isxdigit (buf[2])
1594 && buf[3] == '\0')
1595 /* "Enn" - definitly an error. */
1596 return PACKET_ERROR;
1597
1598 /* Always treat "E." as an error. This will be used for
1599 more verbose error messages, such as E.memtypes. */
1600 if (buf[0] == 'E' && buf[1] == '.')
1601 return PACKET_ERROR;
1602
1603 /* The packet may or may not be OK. Just assume it is. */
1604 return PACKET_OK;
1605 }
1606 else
1607 /* The stub does not support the packet. */
1608 return PACKET_UNKNOWN;
1609}
1610
1611static enum packet_result
1612packet_ok (const char *buf, struct packet_config *config)
1613{
1614 enum packet_result result;
1615
4082afcc
PA
1616 if (config->detect != AUTO_BOOLEAN_TRUE
1617 && config->support == PACKET_DISABLE)
1618 internal_error (__FILE__, __LINE__,
1619 _("packet_ok: attempt to use a disabled packet"));
1620
a76d924d
DJ
1621 result = packet_check_result (buf);
1622 switch (result)
1623 {
1624 case PACKET_OK:
1625 case PACKET_ERROR:
1626 /* The stub recognized the packet request. */
4082afcc 1627 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1628 {
d471ea57
AC
1629 if (remote_debug)
1630 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1631 "Packet %s (%s) is supported\n",
1632 config->name, config->title);
d471ea57 1633 config->support = PACKET_ENABLE;
d471ea57 1634 }
a76d924d
DJ
1635 break;
1636 case PACKET_UNKNOWN:
23860348 1637 /* The stub does not support the packet. */
4082afcc
PA
1638 if (config->detect == AUTO_BOOLEAN_AUTO
1639 && config->support == PACKET_ENABLE)
d471ea57 1640 {
4082afcc
PA
1641 /* If the stub previously indicated that the packet was
1642 supported then there is a protocol error. */
1643 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1644 config->name, config->title);
1645 }
1646 else if (config->detect == AUTO_BOOLEAN_TRUE)
1647 {
1648 /* The user set it wrong. */
1649 error (_("Enabled packet %s (%s) not recognized by stub"),
1650 config->name, config->title);
d471ea57 1651 }
4082afcc
PA
1652
1653 if (remote_debug)
1654 fprintf_unfiltered (gdb_stdlog,
1655 "Packet %s (%s) is NOT supported\n",
1656 config->name, config->title);
1657 config->support = PACKET_DISABLE;
a76d924d 1658 break;
5a2468f5 1659 }
a76d924d
DJ
1660
1661 return result;
5a2468f5
JM
1662}
1663
444abaca
DJ
1664enum {
1665 PACKET_vCont = 0,
1666 PACKET_X,
1667 PACKET_qSymbol,
1668 PACKET_P,
1669 PACKET_p,
1670 PACKET_Z0,
1671 PACKET_Z1,
1672 PACKET_Z2,
1673 PACKET_Z3,
1674 PACKET_Z4,
15a201c8 1675 PACKET_vFile_setfs,
a6b151f1
DJ
1676 PACKET_vFile_open,
1677 PACKET_vFile_pread,
1678 PACKET_vFile_pwrite,
1679 PACKET_vFile_close,
1680 PACKET_vFile_unlink,
b9e7b9c3 1681 PACKET_vFile_readlink,
0a93529c 1682 PACKET_vFile_fstat,
0876f84a 1683 PACKET_qXfer_auxv,
23181151 1684 PACKET_qXfer_features,
c78fa86a 1685 PACKET_qXfer_exec_file,
cfa9d6d9 1686 PACKET_qXfer_libraries,
2268b414 1687 PACKET_qXfer_libraries_svr4,
fd79ecee 1688 PACKET_qXfer_memory_map,
0e7f50da
UW
1689 PACKET_qXfer_spu_read,
1690 PACKET_qXfer_spu_write,
07e059b5 1691 PACKET_qXfer_osdata,
dc146f7c 1692 PACKET_qXfer_threads,
0fb4aa4b 1693 PACKET_qXfer_statictrace_read,
b3b9301e 1694 PACKET_qXfer_traceframe_info,
169081d0 1695 PACKET_qXfer_uib,
711e434b 1696 PACKET_qGetTIBAddr,
444abaca 1697 PACKET_qGetTLSAddr,
be2a5f71 1698 PACKET_qSupported,
bd3eecc3 1699 PACKET_qTStatus,
89be2091 1700 PACKET_QPassSignals,
82075af2 1701 PACKET_QCatchSyscalls,
9b224c5e 1702 PACKET_QProgramSignals,
bc3b087d 1703 PACKET_QSetWorkingDir,
aefd8b33 1704 PACKET_QStartupWithShell,
0a2dde4a
SDJ
1705 PACKET_QEnvironmentHexEncoded,
1706 PACKET_QEnvironmentReset,
1707 PACKET_QEnvironmentUnset,
936d2992 1708 PACKET_qCRC,
08388c79 1709 PACKET_qSearch_memory,
2d717e4f
DJ
1710 PACKET_vAttach,
1711 PACKET_vRun,
a6f3e723 1712 PACKET_QStartNoAckMode,
82f73884 1713 PACKET_vKill,
4aa995e1
PA
1714 PACKET_qXfer_siginfo_read,
1715 PACKET_qXfer_siginfo_write,
0b16c5cf 1716 PACKET_qAttached,
4082afcc
PA
1717
1718 /* Support for conditional tracepoints. */
782b2b07 1719 PACKET_ConditionalTracepoints,
4082afcc
PA
1720
1721 /* Support for target-side breakpoint conditions. */
3788aec7 1722 PACKET_ConditionalBreakpoints,
4082afcc
PA
1723
1724 /* Support for target-side breakpoint commands. */
d3ce09f5 1725 PACKET_BreakpointCommands,
4082afcc
PA
1726
1727 /* Support for fast tracepoints. */
7a697b8d 1728 PACKET_FastTracepoints,
4082afcc
PA
1729
1730 /* Support for static tracepoints. */
0fb4aa4b 1731 PACKET_StaticTracepoints,
4082afcc
PA
1732
1733 /* Support for installing tracepoints while a trace experiment is
1734 running. */
1e4d1764 1735 PACKET_InstallInTrace,
4082afcc 1736
40ab02ce
MS
1737 PACKET_bc,
1738 PACKET_bs,
409873ef 1739 PACKET_TracepointSource,
d914c394 1740 PACKET_QAllow,
78d85199 1741 PACKET_qXfer_fdpic,
03583c20 1742 PACKET_QDisableRandomization,
d1feda86 1743 PACKET_QAgent,
f6f899bf 1744 PACKET_QTBuffer_size,
9accd112
MM
1745 PACKET_Qbtrace_off,
1746 PACKET_Qbtrace_bts,
b20a6524 1747 PACKET_Qbtrace_pt,
9accd112 1748 PACKET_qXfer_btrace,
4082afcc
PA
1749
1750 /* Support for the QNonStop packet. */
1751 PACKET_QNonStop,
1752
65706a29
PA
1753 /* Support for the QThreadEvents packet. */
1754 PACKET_QThreadEvents,
1755
4082afcc
PA
1756 /* Support for multi-process extensions. */
1757 PACKET_multiprocess_feature,
1758
1759 /* Support for enabling and disabling tracepoints while a trace
1760 experiment is running. */
1761 PACKET_EnableDisableTracepoints_feature,
1762
1763 /* Support for collecting strings using the tracenz bytecode. */
1764 PACKET_tracenz_feature,
1765
1766 /* Support for continuing to run a trace experiment while GDB is
1767 disconnected. */
1768 PACKET_DisconnectedTracing_feature,
1769
1770 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1771 PACKET_augmented_libraries_svr4_read_feature,
1772
f4abbc16
MM
1773 /* Support for the qXfer:btrace-conf:read packet. */
1774 PACKET_qXfer_btrace_conf,
1775
d33501a5
MM
1776 /* Support for the Qbtrace-conf:bts:size packet. */
1777 PACKET_Qbtrace_conf_bts_size,
1778
f7e6eed5
PA
1779 /* Support for swbreak+ feature. */
1780 PACKET_swbreak_feature,
1781
1782 /* Support for hwbreak+ feature. */
1783 PACKET_hwbreak_feature,
1784
89245bc0
DB
1785 /* Support for fork events. */
1786 PACKET_fork_event_feature,
1787
1788 /* Support for vfork events. */
1789 PACKET_vfork_event_feature,
1790
b20a6524
MM
1791 /* Support for the Qbtrace-conf:pt:size packet. */
1792 PACKET_Qbtrace_conf_pt_size,
1793
94585166
DB
1794 /* Support for exec events. */
1795 PACKET_exec_event_feature,
1796
750ce8d1
YQ
1797 /* Support for query supported vCont actions. */
1798 PACKET_vContSupported,
1799
de979965
PA
1800 /* Support remote CTRL-C. */
1801 PACKET_vCtrlC,
1802
f2faf941
PA
1803 /* Support TARGET_WAITKIND_NO_RESUMED. */
1804 PACKET_no_resumed,
1805
444abaca
DJ
1806 PACKET_MAX
1807};
506fb367 1808
444abaca 1809static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1810
f7e6eed5
PA
1811/* Returns the packet's corresponding "set remote foo-packet" command
1812 state. See struct packet_config for more details. */
1813
1814static enum auto_boolean
1815packet_set_cmd_state (int packet)
1816{
1817 return remote_protocol_packets[packet].detect;
1818}
1819
4082afcc
PA
1820/* Returns whether a given packet or feature is supported. This takes
1821 into account the state of the corresponding "set remote foo-packet"
1822 command, which may be used to bypass auto-detection. */
dc8acb97 1823
4082afcc
PA
1824static enum packet_support
1825packet_config_support (struct packet_config *config)
1826{
1827 switch (config->detect)
444abaca 1828 {
4082afcc
PA
1829 case AUTO_BOOLEAN_TRUE:
1830 return PACKET_ENABLE;
1831 case AUTO_BOOLEAN_FALSE:
1832 return PACKET_DISABLE;
1833 case AUTO_BOOLEAN_AUTO:
1834 return config->support;
1835 default:
1836 gdb_assert_not_reached (_("bad switch"));
444abaca 1837 }
4082afcc
PA
1838}
1839
1840/* Same as packet_config_support, but takes the packet's enum value as
1841 argument. */
1842
1843static enum packet_support
1844packet_support (int packet)
1845{
1846 struct packet_config *config = &remote_protocol_packets[packet];
1847
1848 return packet_config_support (config);
dc8acb97
MS
1849}
1850
5a2468f5 1851static void
444abaca
DJ
1852show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1853 struct cmd_list_element *c,
1854 const char *value)
5a2468f5 1855{
444abaca 1856 struct packet_config *packet;
5a2468f5 1857
444abaca
DJ
1858 for (packet = remote_protocol_packets;
1859 packet < &remote_protocol_packets[PACKET_MAX];
1860 packet++)
1861 {
1862 if (&packet->detect == c->var)
1863 {
1864 show_packet_config_cmd (packet);
1865 return;
1866 }
1867 }
9b20d036 1868 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1869 c->name);
5a2468f5
JM
1870}
1871
d471ea57
AC
1872/* Should we try one of the 'Z' requests? */
1873
1874enum Z_packet_type
1875{
1876 Z_PACKET_SOFTWARE_BP,
1877 Z_PACKET_HARDWARE_BP,
1878 Z_PACKET_WRITE_WP,
1879 Z_PACKET_READ_WP,
1880 Z_PACKET_ACCESS_WP,
1881 NR_Z_PACKET_TYPES
1882};
96baa820 1883
d471ea57 1884/* For compatibility with older distributions. Provide a ``set remote
23860348 1885 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1886
7f19b9a2 1887static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1888
1889static void
eb4c3f4a 1890set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
fba45db2 1891 struct cmd_list_element *c)
96baa820 1892{
d471ea57 1893 int i;
a744cf53 1894
d471ea57 1895 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1896 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1897}
1898
1899static void
08546159
AC
1900show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1901 struct cmd_list_element *c,
1902 const char *value)
96baa820 1903{
d471ea57 1904 int i;
a744cf53 1905
d471ea57
AC
1906 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1907 {
444abaca 1908 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1909 }
96baa820
JM
1910}
1911
4082afcc
PA
1912/* Returns true if the multi-process extensions are in effect. */
1913
1914static int
1915remote_multi_process_p (struct remote_state *rs)
1916{
1917 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1918}
1919
de0d863e
DB
1920/* Returns true if fork events are supported. */
1921
1922static int
1923remote_fork_event_p (struct remote_state *rs)
1924{
1925 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1926}
1927
c269dbdb
DB
1928/* Returns true if vfork events are supported. */
1929
1930static int
1931remote_vfork_event_p (struct remote_state *rs)
1932{
1933 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1934}
1935
d46addbb
DB
1936/* Returns true if exec events are supported. */
1937
1938static int
1939remote_exec_event_p (struct remote_state *rs)
1940{
1941 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1942}
1943
cbb8991c
DB
1944/* Insert fork catchpoint target routine. If fork events are enabled
1945 then return success, nothing more to do. */
1946
f6ac5f3d
PA
1947int
1948remote_target::insert_fork_catchpoint (int pid)
cbb8991c
DB
1949{
1950 struct remote_state *rs = get_remote_state ();
1951
1952 return !remote_fork_event_p (rs);
1953}
1954
1955/* Remove fork catchpoint target routine. Nothing to do, just
1956 return success. */
1957
f6ac5f3d
PA
1958int
1959remote_target::remove_fork_catchpoint (int pid)
cbb8991c
DB
1960{
1961 return 0;
1962}
1963
1964/* Insert vfork catchpoint target routine. If vfork events are enabled
1965 then return success, nothing more to do. */
1966
f6ac5f3d
PA
1967int
1968remote_target::insert_vfork_catchpoint (int pid)
cbb8991c
DB
1969{
1970 struct remote_state *rs = get_remote_state ();
1971
1972 return !remote_vfork_event_p (rs);
1973}
1974
1975/* Remove vfork catchpoint target routine. Nothing to do, just
1976 return success. */
1977
f6ac5f3d
PA
1978int
1979remote_target::remove_vfork_catchpoint (int pid)
cbb8991c
DB
1980{
1981 return 0;
1982}
1983
d46addbb
DB
1984/* Insert exec catchpoint target routine. If exec events are
1985 enabled, just return success. */
1986
f6ac5f3d
PA
1987int
1988remote_target::insert_exec_catchpoint (int pid)
d46addbb
DB
1989{
1990 struct remote_state *rs = get_remote_state ();
1991
1992 return !remote_exec_event_p (rs);
1993}
1994
1995/* Remove exec catchpoint target routine. Nothing to do, just
1996 return success. */
1997
f6ac5f3d
PA
1998int
1999remote_target::remove_exec_catchpoint (int pid)
d46addbb
DB
2000{
2001 return 0;
2002}
2003
74531fed
PA
2004\f
2005/* Asynchronous signal handle registered as event loop source for
2006 when we have pending events ready to be passed to the core. */
2007
2008static struct async_event_handler *remote_async_inferior_event_token;
2009
c906108c
SS
2010\f
2011
79d7f229
PA
2012static ptid_t magic_null_ptid;
2013static ptid_t not_sent_ptid;
2014static ptid_t any_thread_ptid;
2015
0b16c5cf
PA
2016/* Find out if the stub attached to PID (and hence GDB should offer to
2017 detach instead of killing it when bailing out). */
2018
2019static int
2020remote_query_attached (int pid)
2021{
2022 struct remote_state *rs = get_remote_state ();
bba74b36 2023 size_t size = get_remote_packet_size ();
0b16c5cf 2024
4082afcc 2025 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
2026 return 0;
2027
2028 if (remote_multi_process_p (rs))
bba74b36 2029 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 2030 else
bba74b36 2031 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
2032
2033 putpkt (rs->buf);
2034 getpkt (&rs->buf, &rs->buf_size, 0);
2035
2036 switch (packet_ok (rs->buf,
1554e9be 2037 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
2038 {
2039 case PACKET_OK:
2040 if (strcmp (rs->buf, "1") == 0)
2041 return 1;
2042 break;
2043 case PACKET_ERROR:
2044 warning (_("Remote failure reply: %s"), rs->buf);
2045 break;
2046 case PACKET_UNKNOWN:
2047 break;
2048 }
2049
2050 return 0;
2051}
2052
49c62f2e
PA
2053/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2054 has been invented by GDB, instead of reported by the target. Since
2055 we can be connected to a remote system before before knowing about
2056 any inferior, mark the target with execution when we find the first
2057 inferior. If ATTACHED is 1, then we had just attached to this
2058 inferior. If it is 0, then we just created this inferior. If it
2059 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
2060 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2061 attempt to open this inferior's executable as the main executable
2062 if no main executable is open already. */
1941c569
PA
2063
2064static struct inferior *
1b6e6f5c
GB
2065remote_add_inferior (int fake_pid_p, int pid, int attached,
2066 int try_open_exec)
1941c569 2067{
1941c569
PA
2068 struct inferior *inf;
2069
0b16c5cf
PA
2070 /* Check whether this process we're learning about is to be
2071 considered attached, or if is to be considered to have been
2072 spawned by the stub. */
2073 if (attached == -1)
2074 attached = remote_query_attached (pid);
2075
f5656ead 2076 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
2077 {
2078 /* If the target shares code across all inferiors, then every
2079 attach adds a new inferior. */
2080 inf = add_inferior (pid);
2081
2082 /* ... and every inferior is bound to the same program space.
2083 However, each inferior may still have its own address
2084 space. */
2085 inf->aspace = maybe_new_address_space ();
2086 inf->pspace = current_program_space;
2087 }
2088 else
2089 {
2090 /* In the traditional debugging scenario, there's a 1-1 match
2091 between program/address spaces. We simply bind the inferior
2092 to the program space's address space. */
2093 inf = current_inferior ();
2094 inferior_appeared (inf, pid);
2095 }
1941c569 2096
0b16c5cf 2097 inf->attach_flag = attached;
49c62f2e 2098 inf->fake_pid_p = fake_pid_p;
0b16c5cf 2099
1b6e6f5c
GB
2100 /* If no main executable is currently open then attempt to
2101 open the file that was executed to create this inferior. */
835205d0 2102 if (try_open_exec && get_exec_file (0) == NULL)
bb805577 2103 exec_file_locate_attach (pid, 0, 1);
1b6e6f5c 2104
1941c569
PA
2105 return inf;
2106}
2107
7aabaf9d 2108static remote_thread_info *get_remote_thread_info (thread_info *thread);
85ad3aaf 2109
1941c569
PA
2110/* Add thread PTID to GDB's thread list. Tag it as executing/running
2111 according to RUNNING. */
2112
c906108c 2113static void
0d5b594f 2114remote_add_thread (ptid_t ptid, int running, int executing)
c906108c 2115{
b7ea362b 2116 struct remote_state *rs = get_remote_state ();
85ad3aaf 2117 struct thread_info *thread;
b7ea362b
PA
2118
2119 /* GDB historically didn't pull threads in the initial connection
2120 setup. If the remote target doesn't even have a concept of
2121 threads (e.g., a bare-metal target), even if internally we
2122 consider that a single-threaded target, mentioning a new thread
2123 might be confusing to the user. Be silent then, preserving the
2124 age old behavior. */
2125 if (rs->starting_up)
85ad3aaf 2126 thread = add_thread_silent (ptid);
b7ea362b 2127 else
85ad3aaf 2128 thread = add_thread (ptid);
1941c569 2129
7aabaf9d 2130 get_remote_thread_info (thread)->vcont_resumed = executing;
0d5b594f 2131 set_executing (ptid, executing);
1941c569
PA
2132 set_running (ptid, running);
2133}
2134
2135/* Come here when we learn about a thread id from the remote target.
2136 It may be the first time we hear about such thread, so take the
2137 opportunity to add it to GDB's thread list. In case this is the
2138 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
2139 GDB's inferior list as well. EXECUTING indicates whether the
2140 thread is (internally) executing or stopped. */
1941c569
PA
2141
2142static void
0d5b594f 2143remote_notice_new_inferior (ptid_t currthread, int executing)
1941c569 2144{
0d5b594f
PA
2145 /* In non-stop mode, we assume new found threads are (externally)
2146 running until proven otherwise with a stop reply. In all-stop,
2147 we can only get here if all threads are stopped. */
2148 int running = target_is_non_stop_p () ? 1 : 0;
2149
c906108c
SS
2150 /* If this is a new thread, add it to GDB's thread list.
2151 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
2152
2153 if (in_thread_list (currthread) && is_exited (currthread))
2154 {
2155 /* We're seeing an event on a thread id we knew had exited.
2156 This has to be a new thread reusing the old id. Add it. */
0d5b594f 2157 remote_add_thread (currthread, running, executing);
82f73884
PA
2158 return;
2159 }
2160
79d7f229 2161 if (!in_thread_list (currthread))
c0a2216e 2162 {
1941c569 2163 struct inferior *inf = NULL;
bad34192 2164 int pid = ptid_get_pid (currthread);
1941c569 2165
bad34192
PA
2166 if (ptid_is_pid (inferior_ptid)
2167 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
2168 {
2169 /* inferior_ptid has no thread member yet. This can happen
2170 with the vAttach -> remote_wait,"TAAthread:" path if the
2171 stub doesn't support qC. This is the first stop reported
2172 after an attach, so this is the main thread. Update the
2173 ptid in the thread list. */
bad34192
PA
2174 if (in_thread_list (pid_to_ptid (pid)))
2175 thread_change_ptid (inferior_ptid, currthread);
2176 else
2177 {
0d5b594f 2178 remote_add_thread (currthread, running, executing);
bad34192
PA
2179 inferior_ptid = currthread;
2180 }
dc146f7c 2181 return;
c0a2216e 2182 }
82f73884
PA
2183
2184 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
2185 {
2186 /* inferior_ptid is not set yet. This can happen with the
2187 vRun -> remote_wait,"TAAthread:" path if the stub
2188 doesn't support qC. This is the first stop reported
2189 after an attach, so this is the main thread. Update the
2190 ptid in the thread list. */
dc146f7c 2191 thread_change_ptid (inferior_ptid, currthread);
82f73884 2192 return;
c0a2216e 2193 }
82f73884 2194
29c87f7f
PA
2195 /* When connecting to a target remote, or to a target
2196 extended-remote which already was debugging an inferior, we
2197 may not know about it yet. Add it before adding its child
2198 thread, so notifications are emitted in a sensible order. */
2199 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
2200 {
2201 struct remote_state *rs = get_remote_state ();
2202 int fake_pid_p = !remote_multi_process_p (rs);
2203
2204 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 2205 ptid_get_pid (currthread), -1, 1);
49c62f2e 2206 }
29c87f7f 2207
82f73884 2208 /* This is really a new thread. Add it. */
0d5b594f 2209 remote_add_thread (currthread, running, executing);
1941c569
PA
2210
2211 /* If we found a new inferior, let the common code do whatever
2212 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
2213 breakpoints), unless we're just setting up an all-stop
2214 connection. */
1941c569 2215 if (inf != NULL)
b7ea362b
PA
2216 {
2217 struct remote_state *rs = get_remote_state ();
2218
6efcd9a8 2219 if (!rs->starting_up)
0d5b594f 2220 notice_new_inferior (currthread, executing, 0);
b7ea362b 2221 }
c0a2216e 2222 }
c906108c
SS
2223}
2224
85ad3aaf 2225/* Return THREAD's private thread data, creating it if necessary. */
dc146f7c 2226
7aabaf9d
SM
2227static remote_thread_info *
2228get_remote_thread_info (thread_info *thread)
dc146f7c 2229{
85ad3aaf 2230 gdb_assert (thread != NULL);
dc146f7c 2231
85ad3aaf 2232 if (thread->priv == NULL)
7aabaf9d 2233 thread->priv.reset (new remote_thread_info);
dc146f7c 2234
7aabaf9d 2235 return static_cast<remote_thread_info *> (thread->priv.get ());
85ad3aaf
PA
2236}
2237
2238/* Return PTID's private thread data, creating it if necessary. */
2239
7aabaf9d
SM
2240static remote_thread_info *
2241get_remote_thread_info (ptid_t ptid)
85ad3aaf
PA
2242{
2243 struct thread_info *info = find_thread_ptid (ptid);
2244
7aabaf9d 2245 return get_remote_thread_info (info);
dc146f7c
VP
2246}
2247
74531fed
PA
2248/* Call this function as a result of
2249 1) A halt indication (T packet) containing a thread id
2250 2) A direct query of currthread
0df8b418 2251 3) Successful execution of set thread */
74531fed
PA
2252
2253static void
47f8a51d 2254record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 2255{
47f8a51d 2256 rs->general_thread = currthread;
74531fed
PA
2257}
2258
89be2091
DJ
2259/* If 'QPassSignals' is supported, tell the remote stub what signals
2260 it can simply pass through to the inferior without reporting. */
2261
f6ac5f3d
PA
2262void
2263remote_target::pass_signals (int numsigs, unsigned char *pass_signals)
89be2091 2264{
4082afcc 2265 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
2266 {
2267 char *pass_packet, *p;
89be2091 2268 int count = 0, i;
747dc59d 2269 struct remote_state *rs = get_remote_state ();
89be2091
DJ
2270
2271 gdb_assert (numsigs < 256);
2272 for (i = 0; i < numsigs; i++)
2273 {
2455069d 2274 if (pass_signals[i])
89be2091
DJ
2275 count++;
2276 }
224c3ddb 2277 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
2278 strcpy (pass_packet, "QPassSignals:");
2279 p = pass_packet + strlen (pass_packet);
2280 for (i = 0; i < numsigs; i++)
2281 {
2455069d 2282 if (pass_signals[i])
89be2091
DJ
2283 {
2284 if (i >= 16)
2285 *p++ = tohex (i >> 4);
2286 *p++ = tohex (i & 15);
2287 if (count)
2288 *p++ = ';';
2289 else
2290 break;
2291 count--;
2292 }
2293 }
2294 *p = 0;
747dc59d 2295 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 2296 {
89be2091
DJ
2297 putpkt (pass_packet);
2298 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2299 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
2300 if (rs->last_pass_packet)
2301 xfree (rs->last_pass_packet);
2302 rs->last_pass_packet = pass_packet;
89be2091
DJ
2303 }
2304 else
2305 xfree (pass_packet);
2306 }
2307}
2308
82075af2
JS
2309/* If 'QCatchSyscalls' is supported, tell the remote stub
2310 to report syscalls to GDB. */
2311
f6ac5f3d
PA
2312int
2313remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2314 gdb::array_view<const int> syscall_counts)
82075af2 2315{
b80406ac 2316 const char *catch_packet;
82075af2
JS
2317 enum packet_result result;
2318 int n_sysno = 0;
2319
2320 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2321 {
2322 /* Not supported. */
2323 return 1;
2324 }
2325
649a140c 2326 if (needed && any_count == 0)
82075af2 2327 {
649a140c
PA
2328 /* Count how many syscalls are to be caught. */
2329 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2330 {
649a140c 2331 if (syscall_counts[i] != 0)
82075af2
JS
2332 n_sysno++;
2333 }
2334 }
2335
2336 if (remote_debug)
2337 {
2338 fprintf_unfiltered (gdb_stdlog,
2339 "remote_set_syscall_catchpoint "
2340 "pid %d needed %d any_count %d n_sysno %d\n",
2341 pid, needed, any_count, n_sysno);
2342 }
2343
1b81856f 2344 std::string built_packet;
82075af2
JS
2345 if (needed)
2346 {
2347 /* Prepare a packet with the sysno list, assuming max 8+1
2348 characters for a sysno. If the resulting packet size is too
2349 big, fallback on the non-selective packet. */
2350 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
1b81856f
PA
2351 built_packet.reserve (maxpktsz);
2352 built_packet = "QCatchSyscalls:1";
649a140c 2353 if (any_count == 0)
82075af2 2354 {
649a140c
PA
2355 /* Add in each syscall to be caught. */
2356 for (size_t i = 0; i < syscall_counts.size (); i++)
82075af2 2357 {
649a140c
PA
2358 if (syscall_counts[i] != 0)
2359 string_appendf (built_packet, ";%zx", i);
82075af2
JS
2360 }
2361 }
1b81856f 2362 if (built_packet.size () > get_remote_packet_size ())
82075af2
JS
2363 {
2364 /* catch_packet too big. Fallback to less efficient
2365 non selective mode, with GDB doing the filtering. */
b80406ac 2366 catch_packet = "QCatchSyscalls:1";
82075af2 2367 }
b80406ac 2368 else
1b81856f 2369 catch_packet = built_packet.c_str ();
82075af2
JS
2370 }
2371 else
b80406ac 2372 catch_packet = "QCatchSyscalls:0";
82075af2 2373
b80406ac 2374 struct remote_state *rs = get_remote_state ();
82075af2 2375
b80406ac
TT
2376 putpkt (catch_packet);
2377 getpkt (&rs->buf, &rs->buf_size, 0);
2378 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2379 if (result == PACKET_OK)
2380 return 0;
2381 else
2382 return -1;
82075af2
JS
2383}
2384
9b224c5e
PA
2385/* If 'QProgramSignals' is supported, tell the remote stub what
2386 signals it should pass through to the inferior when detaching. */
2387
f6ac5f3d
PA
2388void
2389remote_target::program_signals (int numsigs, unsigned char *signals)
9b224c5e 2390{
4082afcc 2391 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
2392 {
2393 char *packet, *p;
2394 int count = 0, i;
5e4a05c4 2395 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
2396
2397 gdb_assert (numsigs < 256);
2398 for (i = 0; i < numsigs; i++)
2399 {
2400 if (signals[i])
2401 count++;
2402 }
224c3ddb 2403 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2404 strcpy (packet, "QProgramSignals:");
2405 p = packet + strlen (packet);
2406 for (i = 0; i < numsigs; i++)
2407 {
2408 if (signal_pass_state (i))
2409 {
2410 if (i >= 16)
2411 *p++ = tohex (i >> 4);
2412 *p++ = tohex (i & 15);
2413 if (count)
2414 *p++ = ';';
2415 else
2416 break;
2417 count--;
2418 }
2419 }
2420 *p = 0;
5e4a05c4
TT
2421 if (!rs->last_program_signals_packet
2422 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2423 {
9b224c5e
PA
2424 putpkt (packet);
2425 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2426 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2427 xfree (rs->last_program_signals_packet);
2428 rs->last_program_signals_packet = packet;
9b224c5e
PA
2429 }
2430 else
2431 xfree (packet);
2432 }
2433}
2434
79d7f229
PA
2435/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2436 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2437 thread. If GEN is set, set the general thread, if not, then set
2438 the step/continue thread. */
c906108c 2439static void
d62a8ae2 2440set_thread (ptid_t ptid, int gen)
c906108c 2441{
d01949b6 2442 struct remote_state *rs = get_remote_state ();
47f8a51d 2443 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 2444 char *buf = rs->buf;
79d7f229 2445 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 2446
79d7f229 2447 if (ptid_equal (state, ptid))
c906108c
SS
2448 return;
2449
79d7f229
PA
2450 *buf++ = 'H';
2451 *buf++ = gen ? 'g' : 'c';
2452 if (ptid_equal (ptid, magic_null_ptid))
2453 xsnprintf (buf, endbuf - buf, "0");
2454 else if (ptid_equal (ptid, any_thread_ptid))
2455 xsnprintf (buf, endbuf - buf, "0");
2456 else if (ptid_equal (ptid, minus_one_ptid))
2457 xsnprintf (buf, endbuf - buf, "-1");
2458 else
82f73884 2459 write_ptid (buf, endbuf, ptid);
79d7f229 2460 putpkt (rs->buf);
6d820c5c 2461 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2462 if (gen)
47f8a51d 2463 rs->general_thread = ptid;
c906108c 2464 else
47f8a51d 2465 rs->continue_thread = ptid;
c906108c 2466}
79d7f229
PA
2467
2468static void
d62a8ae2 2469set_general_thread (ptid_t ptid)
79d7f229
PA
2470{
2471 set_thread (ptid, 1);
2472}
2473
2474static void
d62a8ae2 2475set_continue_thread (ptid_t ptid)
79d7f229
PA
2476{
2477 set_thread (ptid, 0);
2478}
2479
3c9c4b83
PA
2480/* Change the remote current process. Which thread within the process
2481 ends up selected isn't important, as long as it is the same process
2482 as what INFERIOR_PTID points to.
2483
2484 This comes from that fact that there is no explicit notion of
2485 "selected process" in the protocol. The selected process for
2486 general operations is the process the selected general thread
2487 belongs to. */
2488
2489static void
2490set_general_process (void)
2491{
2492 struct remote_state *rs = get_remote_state ();
2493
2494 /* If the remote can't handle multiple processes, don't bother. */
8020350c 2495 if (!remote_multi_process_p (rs))
3c9c4b83
PA
2496 return;
2497
2498 /* We only need to change the remote current thread if it's pointing
2499 at some other process. */
47f8a51d 2500 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
2501 set_general_thread (inferior_ptid);
2502}
2503
c906108c 2504\f
7d1a114c
PA
2505/* Return nonzero if this is the main thread that we made up ourselves
2506 to model non-threaded targets as single-threaded. */
c906108c
SS
2507
2508static int
f6ac5f3d 2509remote_thread_always_alive (ptid_t ptid)
c906108c 2510{
c0a2216e
PA
2511 if (ptid_equal (ptid, magic_null_ptid))
2512 /* The main thread is always alive. */
2513 return 1;
2514
ba348170 2515 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
2516 /* The main thread is always alive. This can happen after a
2517 vAttach, if the remote side doesn't support
2518 multi-threading. */
2519 return 1;
2520
7d1a114c
PA
2521 return 0;
2522}
2523
2524/* Return nonzero if the thread PTID is still alive on the remote
2525 system. */
2526
57810aa7 2527bool
f6ac5f3d 2528remote_target::thread_alive (ptid_t ptid)
7d1a114c
PA
2529{
2530 struct remote_state *rs = get_remote_state ();
2531 char *p, *endp;
2532
2533 /* Check if this is a thread that we made up ourselves to model
2534 non-threaded targets as single-threaded. */
f6ac5f3d 2535 if (remote_thread_always_alive (ptid))
7d1a114c
PA
2536 return 1;
2537
82f73884
PA
2538 p = rs->buf;
2539 endp = rs->buf + get_remote_packet_size ();
2540
2541 *p++ = 'T';
2542 write_ptid (p, endp, ptid);
2543
2e9f7625 2544 putpkt (rs->buf);
6d820c5c 2545 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2546 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2547}
2548
79efa585
SM
2549/* Return a pointer to a thread name if we know it and NULL otherwise.
2550 The thread_info object owns the memory for the name. */
2551
f6ac5f3d
PA
2552const char *
2553remote_target::thread_name (struct thread_info *info)
79efa585
SM
2554{
2555 if (info->priv != NULL)
a9334058
SM
2556 {
2557 const std::string &name = get_remote_thread_info (info)->name;
2558 return !name.empty () ? name.c_str () : NULL;
2559 }
79efa585
SM
2560
2561 return NULL;
2562}
2563
c906108c
SS
2564/* About these extended threadlist and threadinfo packets. They are
2565 variable length packets but, the fields within them are often fixed
2566 length. They are redundent enough to send over UDP as is the
2567 remote protocol in general. There is a matching unit test module
2568 in libstub. */
2569
23860348 2570/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2571 libstub protocol encoding, and remote.c. It is not particularly
23860348 2572 changable. */
cce74817
JM
2573
2574/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2575 Plan to fix this. */
cce74817 2576
23860348 2577typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2578
9d1f7ab2 2579/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2580 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2581
2582struct gdb_ext_thread_info
c5aa993b 2583 {
23860348 2584 threadref threadid; /* External form of thread reference. */
2bc416ba 2585 int active; /* Has state interesting to GDB?
23860348 2586 regs, stack. */
2bc416ba 2587 char display[256]; /* Brief state display, name,
cedea757 2588 blocked/suspended. */
23860348 2589 char shortname[32]; /* To be used to name threads. */
2bc416ba 2590 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2591 whatever. */
c5aa993b 2592 };
cce74817
JM
2593
2594/* The volume of remote transfers can be limited by submitting
2595 a mask containing bits specifying the desired information.
2596 Use a union of these values as the 'selection' parameter to
0df8b418 2597 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2598
2599#define TAG_THREADID 1
2600#define TAG_EXISTS 2
2601#define TAG_DISPLAY 4
2602#define TAG_THREADNAME 8
c5aa993b 2603#define TAG_MOREDISPLAY 16
cce74817 2604
23860348 2605#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2606
a14ed312 2607static char *unpack_nibble (char *buf, int *val);
cce74817 2608
a14ed312 2609static char *unpack_byte (char *buf, int *value);
cce74817 2610
a14ed312 2611static char *pack_int (char *buf, int value);
cce74817 2612
a14ed312 2613static char *unpack_int (char *buf, int *value);
cce74817 2614
a14ed312 2615static char *unpack_string (char *src, char *dest, int length);
cce74817 2616
23860348 2617static char *pack_threadid (char *pkt, threadref *id);
cce74817 2618
23860348 2619static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2620
23860348 2621void int_to_threadref (threadref *id, int value);
cce74817 2622
23860348 2623static int threadref_to_int (threadref *ref);
cce74817 2624
23860348 2625static void copy_threadref (threadref *dest, threadref *src);
cce74817 2626
23860348 2627static int threadmatch (threadref *dest, threadref *src);
cce74817 2628
2bc416ba 2629static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2630 threadref *id);
cce74817 2631
a14ed312 2632static int remote_unpack_thread_info_response (char *pkt,
23860348 2633 threadref *expectedref,
a14ed312
KB
2634 struct gdb_ext_thread_info
2635 *info);
cce74817
JM
2636
2637
2bc416ba 2638static int remote_get_threadinfo (threadref *threadid,
23860348 2639 int fieldset, /*TAG mask */
a14ed312 2640 struct gdb_ext_thread_info *info);
cce74817 2641
a14ed312
KB
2642static char *pack_threadlist_request (char *pkt, int startflag,
2643 int threadcount,
23860348 2644 threadref *nextthread);
cce74817 2645
a14ed312
KB
2646static int parse_threadlist_response (char *pkt,
2647 int result_limit,
23860348 2648 threadref *original_echo,
2bc416ba 2649 threadref *resultlist,
23860348 2650 int *doneflag);
cce74817 2651
a14ed312 2652static int remote_get_threadlist (int startflag,
23860348 2653 threadref *nextthread,
a14ed312
KB
2654 int result_limit,
2655 int *done,
2bc416ba 2656 int *result_count,
23860348 2657 threadref *threadlist);
cce74817 2658
23860348 2659typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2660
a14ed312
KB
2661static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2662 void *context, int looplimit);
cce74817 2663
23860348 2664static int remote_newthread_step (threadref *ref, void *context);
cce74817 2665
82f73884
PA
2666
2667/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2668 buffer we're allowed to write to. Returns
2669 BUF+CHARACTERS_WRITTEN. */
2670
2671static char *
2672write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2673{
2674 int pid, tid;
2675 struct remote_state *rs = get_remote_state ();
2676
2677 if (remote_multi_process_p (rs))
2678 {
2679 pid = ptid_get_pid (ptid);
2680 if (pid < 0)
2681 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2682 else
2683 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2684 }
ba348170 2685 tid = ptid_get_lwp (ptid);
82f73884
PA
2686 if (tid < 0)
2687 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2688 else
2689 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2690
2691 return buf;
2692}
2693
256642e8
PA
2694/* Extract a PTID from BUF. If non-null, OBUF is set to one past the
2695 last parsed char. Returns null_ptid if no thread id is found, and
2696 throws an error if the thread id has an invalid format. */
82f73884
PA
2697
2698static ptid_t
256642e8 2699read_ptid (const char *buf, const char **obuf)
82f73884 2700{
256642e8
PA
2701 const char *p = buf;
2702 const char *pp;
82f73884 2703 ULONGEST pid = 0, tid = 0;
82f73884
PA
2704
2705 if (*p == 'p')
2706 {
2707 /* Multi-process ptid. */
2708 pp = unpack_varlen_hex (p + 1, &pid);
2709 if (*pp != '.')
b37520b6 2710 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2711
2712 p = pp;
2713 pp = unpack_varlen_hex (p + 1, &tid);
2714 if (obuf)
2715 *obuf = pp;
ba348170 2716 return ptid_build (pid, tid, 0);
82f73884
PA
2717 }
2718
2719 /* No multi-process. Just a tid. */
2720 pp = unpack_varlen_hex (p, &tid);
2721
c9f35b34
KB
2722 /* Return null_ptid when no thread id is found. */
2723 if (p == pp)
2724 {
2725 if (obuf)
2726 *obuf = pp;
2727 return null_ptid;
2728 }
2729
82f73884 2730 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2731 what's in inferior_ptid, unless it's null at this point. If so,
2732 then since there's no way to know the pid of the reported
2733 threads, use the magic number. */
2734 if (ptid_equal (inferior_ptid, null_ptid))
2735 pid = ptid_get_pid (magic_null_ptid);
2736 else
2737 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2738
2739 if (obuf)
2740 *obuf = pp;
ba348170 2741 return ptid_build (pid, tid, 0);
82f73884
PA
2742}
2743
c906108c 2744static int
fba45db2 2745stubhex (int ch)
c906108c
SS
2746{
2747 if (ch >= 'a' && ch <= 'f')
2748 return ch - 'a' + 10;
2749 if (ch >= '0' && ch <= '9')
2750 return ch - '0';
2751 if (ch >= 'A' && ch <= 'F')
2752 return ch - 'A' + 10;
2753 return -1;
2754}
2755
2756static int
fba45db2 2757stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2758{
2759 int nibble;
2760 int retval = 0;
2761
2762 while (fieldlength)
2763 {
2764 nibble = stubhex (*buff++);
2765 retval |= nibble;
2766 fieldlength--;
2767 if (fieldlength)
2768 retval = retval << 4;
2769 }
2770 return retval;
2771}
2772
c906108c 2773static char *
fba45db2 2774unpack_nibble (char *buf, int *val)
c906108c 2775{
b7589f7d 2776 *val = fromhex (*buf++);
c906108c
SS
2777 return buf;
2778}
2779
c906108c 2780static char *
fba45db2 2781unpack_byte (char *buf, int *value)
c906108c
SS
2782{
2783 *value = stub_unpack_int (buf, 2);
2784 return buf + 2;
2785}
2786
2787static char *
fba45db2 2788pack_int (char *buf, int value)
c906108c
SS
2789{
2790 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2791 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2792 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2793 buf = pack_hex_byte (buf, (value & 0xff));
2794 return buf;
2795}
2796
2797static char *
fba45db2 2798unpack_int (char *buf, int *value)
c906108c
SS
2799{
2800 *value = stub_unpack_int (buf, 8);
2801 return buf + 8;
2802}
2803
23860348 2804#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2805static char *pack_string (char *pkt, char *string);
c906108c
SS
2806
2807static char *
fba45db2 2808pack_string (char *pkt, char *string)
c906108c
SS
2809{
2810 char ch;
2811 int len;
2812
2813 len = strlen (string);
2814 if (len > 200)
23860348 2815 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2816 pkt = pack_hex_byte (pkt, len);
2817 while (len-- > 0)
2818 {
2819 ch = *string++;
2820 if ((ch == '\0') || (ch == '#'))
23860348 2821 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2822 *pkt++ = ch;
2823 }
2824 return pkt;
2825}
2826#endif /* 0 (unused) */
2827
2828static char *
fba45db2 2829unpack_string (char *src, char *dest, int length)
c906108c
SS
2830{
2831 while (length--)
2832 *dest++ = *src++;
2833 *dest = '\0';
2834 return src;
2835}
2836
2837static char *
fba45db2 2838pack_threadid (char *pkt, threadref *id)
c906108c
SS
2839{
2840 char *limit;
2841 unsigned char *altid;
2842
2843 altid = (unsigned char *) id;
2844 limit = pkt + BUF_THREAD_ID_SIZE;
2845 while (pkt < limit)
2846 pkt = pack_hex_byte (pkt, *altid++);
2847 return pkt;
2848}
2849
2850
2851static char *
fba45db2 2852unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2853{
2854 char *altref;
2855 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2856 int x, y;
2857
2858 altref = (char *) id;
2859
2860 while (inbuf < limit)
2861 {
2862 x = stubhex (*inbuf++);
2863 y = stubhex (*inbuf++);
2864 *altref++ = (x << 4) | y;
2865 }
2866 return inbuf;
2867}
2868
2869/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2870 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2871 to use 64bit thread references internally. This is an adapter
2872 function. */
2873
2874void
fba45db2 2875int_to_threadref (threadref *id, int value)
c906108c
SS
2876{
2877 unsigned char *scan;
2878
2879 scan = (unsigned char *) id;
2880 {
2881 int i = 4;
2882 while (i--)
2883 *scan++ = 0;
2884 }
2885 *scan++ = (value >> 24) & 0xff;
2886 *scan++ = (value >> 16) & 0xff;
2887 *scan++ = (value >> 8) & 0xff;
2888 *scan++ = (value & 0xff);
2889}
2890
2891static int
fba45db2 2892threadref_to_int (threadref *ref)
c906108c
SS
2893{
2894 int i, value = 0;
2895 unsigned char *scan;
2896
cfd77fa1 2897 scan = *ref;
c906108c
SS
2898 scan += 4;
2899 i = 4;
2900 while (i-- > 0)
2901 value = (value << 8) | ((*scan++) & 0xff);
2902 return value;
2903}
2904
2905static void
fba45db2 2906copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2907{
2908 int i;
2909 unsigned char *csrc, *cdest;
2910
2911 csrc = (unsigned char *) src;
2912 cdest = (unsigned char *) dest;
2913 i = 8;
2914 while (i--)
2915 *cdest++ = *csrc++;
2916}
2917
2918static int
fba45db2 2919threadmatch (threadref *dest, threadref *src)
c906108c 2920{
23860348 2921 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2922#if 0
2923 unsigned char *srcp, *destp;
2924 int i, result;
2925 srcp = (char *) src;
2926 destp = (char *) dest;
2927
2928 result = 1;
2929 while (i-- > 0)
2930 result &= (*srcp++ == *destp++) ? 1 : 0;
2931 return result;
2932#endif
2933 return 1;
2934}
2935
2936/*
c5aa993b
JM
2937 threadid:1, # always request threadid
2938 context_exists:2,
2939 display:4,
2940 unique_name:8,
2941 more_display:16
2942 */
c906108c
SS
2943
2944/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2945
2946static char *
fba45db2 2947pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2948{
23860348
MS
2949 *pkt++ = 'q'; /* Info Query */
2950 *pkt++ = 'P'; /* process or thread info */
2951 pkt = pack_int (pkt, mode); /* mode */
c906108c 2952 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2953 *pkt = '\0'; /* terminate */
c906108c
SS
2954 return pkt;
2955}
2956
23860348 2957/* These values tag the fields in a thread info response packet. */
c906108c 2958/* Tagging the fields allows us to request specific fields and to
23860348 2959 add more fields as time goes by. */
c906108c 2960
23860348 2961#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2962#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2963 fetch registers and its stack? */
c5aa993b 2964#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2965#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2966#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2967 the process. */
c906108c
SS
2968
2969static int
fba45db2
KB
2970remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2971 struct gdb_ext_thread_info *info)
c906108c 2972{
d01949b6 2973 struct remote_state *rs = get_remote_state ();
c906108c 2974 int mask, length;
cfd77fa1 2975 int tag;
c906108c 2976 threadref ref;
6d820c5c 2977 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2978 int retval = 1;
2979
23860348 2980 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2981 info->active = 0;
2982 info->display[0] = '\0';
2983 info->shortname[0] = '\0';
2984 info->more_display[0] = '\0';
2985
23860348
MS
2986 /* Assume the characters indicating the packet type have been
2987 stripped. */
c906108c
SS
2988 pkt = unpack_int (pkt, &mask); /* arg mask */
2989 pkt = unpack_threadid (pkt, &ref);
2990
2991 if (mask == 0)
8a3fe4f8 2992 warning (_("Incomplete response to threadinfo request."));
c906108c 2993 if (!threadmatch (&ref, expectedref))
23860348 2994 { /* This is an answer to a different request. */
8a3fe4f8 2995 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2996 return 0;
2997 }
2998 copy_threadref (&info->threadid, &ref);
2999
23860348 3000 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 3001
23860348
MS
3002 /* Packets are terminated with nulls. */
3003 while ((pkt < limit) && mask && *pkt)
c906108c
SS
3004 {
3005 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
3006 pkt = unpack_byte (pkt, &length); /* length */
3007 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 3008 {
8a3fe4f8 3009 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
3010 retval = 0;
3011 break;
3012 }
3013 if (tag == TAG_THREADID)
3014 {
3015 if (length != 16)
3016 {
8a3fe4f8 3017 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
3018 retval = 0;
3019 break;
3020 }
3021 pkt = unpack_threadid (pkt, &ref);
3022 mask = mask & ~TAG_THREADID;
3023 continue;
3024 }
3025 if (tag == TAG_EXISTS)
3026 {
3027 info->active = stub_unpack_int (pkt, length);
3028 pkt += length;
3029 mask = mask & ~(TAG_EXISTS);
3030 if (length > 8)
3031 {
8a3fe4f8 3032 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
3033 retval = 0;
3034 break;
3035 }
3036 continue;
3037 }
3038 if (tag == TAG_THREADNAME)
3039 {
3040 pkt = unpack_string (pkt, &info->shortname[0], length);
3041 mask = mask & ~TAG_THREADNAME;
3042 continue;
3043 }
3044 if (tag == TAG_DISPLAY)
3045 {
3046 pkt = unpack_string (pkt, &info->display[0], length);
3047 mask = mask & ~TAG_DISPLAY;
3048 continue;
3049 }
3050 if (tag == TAG_MOREDISPLAY)
3051 {
3052 pkt = unpack_string (pkt, &info->more_display[0], length);
3053 mask = mask & ~TAG_MOREDISPLAY;
3054 continue;
3055 }
8a3fe4f8 3056 warning (_("ERROR RMT: unknown thread info tag."));
23860348 3057 break; /* Not a tag we know about. */
c906108c
SS
3058 }
3059 return retval;
3060}
3061
3062static int
fba45db2
KB
3063remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
3064 struct gdb_ext_thread_info *info)
c906108c 3065{
d01949b6 3066 struct remote_state *rs = get_remote_state ();
c906108c 3067 int result;
c906108c 3068
2e9f7625
DJ
3069 pack_threadinfo_request (rs->buf, fieldset, threadid);
3070 putpkt (rs->buf);
6d820c5c 3071 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
3072
3073 if (rs->buf[0] == '\0')
3074 return 0;
3075
2e9f7625 3076 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 3077 threadid, info);
c906108c
SS
3078 return result;
3079}
3080
c906108c
SS
3081/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3082
3083static char *
fba45db2
KB
3084pack_threadlist_request (char *pkt, int startflag, int threadcount,
3085 threadref *nextthread)
c906108c
SS
3086{
3087 *pkt++ = 'q'; /* info query packet */
3088 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 3089 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
3090 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3091 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3092 *pkt = '\0';
3093 return pkt;
3094}
3095
3096/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3097
3098static int
fba45db2
KB
3099parse_threadlist_response (char *pkt, int result_limit,
3100 threadref *original_echo, threadref *resultlist,
3101 int *doneflag)
c906108c 3102{
d01949b6 3103 struct remote_state *rs = get_remote_state ();
c906108c
SS
3104 char *limit;
3105 int count, resultcount, done;
3106
3107 resultcount = 0;
3108 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 3109 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 3110 /* done parse past here */
c906108c
SS
3111 pkt = unpack_byte (pkt, &count); /* count field */
3112 pkt = unpack_nibble (pkt, &done);
3113 /* The first threadid is the argument threadid. */
3114 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3115 while ((count-- > 0) && (pkt < limit))
3116 {
3117 pkt = unpack_threadid (pkt, resultlist++);
3118 if (resultcount++ >= result_limit)
3119 break;
3120 }
3121 if (doneflag)
3122 *doneflag = done;
3123 return resultcount;
3124}
3125
6dc54d91
PA
3126/* Fetch the next batch of threads from the remote. Returns -1 if the
3127 qL packet is not supported, 0 on error and 1 on success. */
3128
c906108c 3129static int
fba45db2
KB
3130remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
3131 int *done, int *result_count, threadref *threadlist)
c906108c 3132{
d01949b6 3133 struct remote_state *rs = get_remote_state ();
c906108c
SS
3134 int result = 1;
3135
23860348 3136 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
3137 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3138 >= get_remote_packet_size ())
ea9c271d 3139 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 3140
6d820c5c
DJ
3141 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
3142 putpkt (rs->buf);
3143 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 3144 if (*rs->buf == '\0')
6dc54d91
PA
3145 {
3146 /* Packet not supported. */
3147 return -1;
3148 }
3149
3150 *result_count =
3151 parse_threadlist_response (rs->buf + 2, result_limit,
3152 &rs->echo_nextthread, threadlist, done);
c906108c 3153
0d031856 3154 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 3155 {
23860348
MS
3156 /* FIXME: This is a good reason to drop the packet. */
3157 /* Possably, there is a duplicate response. */
c906108c
SS
3158 /* Possabilities :
3159 retransmit immediatly - race conditions
3160 retransmit after timeout - yes
3161 exit
3162 wait for packet, then exit
3163 */
8a3fe4f8 3164 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 3165 return 0; /* I choose simply exiting. */
c906108c
SS
3166 }
3167 if (*result_count <= 0)
3168 {
3169 if (*done != 1)
3170 {
8a3fe4f8 3171 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
3172 result = 0;
3173 }
3174 return result; /* break; */
3175 }
3176 if (*result_count > result_limit)
3177 {
3178 *result_count = 0;
8a3fe4f8 3179 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
3180 return 0;
3181 }
3182 return result;
3183}
3184
6dc54d91
PA
3185/* Fetch the list of remote threads, with the qL packet, and call
3186 STEPFUNCTION for each thread found. Stops iterating and returns 1
3187 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3188 STEPFUNCTION returns false. If the packet is not supported,
3189 returns -1. */
c906108c 3190
c906108c 3191static int
fba45db2
KB
3192remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
3193 int looplimit)
c906108c 3194{
0d031856 3195 struct remote_state *rs = get_remote_state ();
c906108c
SS
3196 int done, i, result_count;
3197 int startflag = 1;
3198 int result = 1;
3199 int loopcount = 0;
c906108c
SS
3200
3201 done = 0;
3202 while (!done)
3203 {
3204 if (loopcount++ > looplimit)
3205 {
3206 result = 0;
8a3fe4f8 3207 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
3208 break;
3209 }
6dc54d91
PA
3210 result = remote_get_threadlist (startflag, &rs->nextthread,
3211 MAXTHREADLISTRESULTS,
3212 &done, &result_count,
3213 rs->resultthreadlist);
3214 if (result <= 0)
3215 break;
23860348 3216 /* Clear for later iterations. */
c906108c
SS
3217 startflag = 0;
3218 /* Setup to resume next batch of thread references, set nextthread. */
3219 if (result_count >= 1)
0d031856
TT
3220 copy_threadref (&rs->nextthread,
3221 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
3222 i = 0;
3223 while (result_count--)
6dc54d91
PA
3224 {
3225 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3226 {
3227 result = 0;
3228 break;
3229 }
3230 }
c906108c
SS
3231 }
3232 return result;
3233}
3234
6dc54d91
PA
3235/* A thread found on the remote target. */
3236
21fe1c75 3237struct thread_item
6dc54d91 3238{
21fe1c75
SM
3239 explicit thread_item (ptid_t ptid_)
3240 : ptid (ptid_)
3241 {}
3242
3243 thread_item (thread_item &&other) = default;
3244 thread_item &operator= (thread_item &&other) = default;
3245
3246 DISABLE_COPY_AND_ASSIGN (thread_item);
3247
6dc54d91
PA
3248 /* The thread's PTID. */
3249 ptid_t ptid;
3250
21fe1c75
SM
3251 /* The thread's extra info. */
3252 std::string extra;
6dc54d91 3253
21fe1c75
SM
3254 /* The thread's name. */
3255 std::string name;
79efa585 3256
6dc54d91 3257 /* The core the thread was running on. -1 if not known. */
21fe1c75 3258 int core = -1;
f6327dcb
KB
3259
3260 /* The thread handle associated with the thread. */
21fe1c75 3261 gdb::byte_vector thread_handle;
21fe1c75 3262};
6dc54d91
PA
3263
3264/* Context passed around to the various methods listing remote
3265 threads. As new threads are found, they're added to the ITEMS
3266 vector. */
3267
3268struct threads_listing_context
3269{
21fe1c75
SM
3270 /* Return true if this object contains an entry for a thread with ptid
3271 PTID. */
6dc54d91 3272
21fe1c75
SM
3273 bool contains_thread (ptid_t ptid) const
3274 {
3275 auto match_ptid = [&] (const thread_item &item)
3276 {
3277 return item.ptid == ptid;
3278 };
80134cf5 3279
21fe1c75
SM
3280 auto it = std::find_if (this->items.begin (),
3281 this->items.end (),
3282 match_ptid);
80134cf5 3283
21fe1c75
SM
3284 return it != this->items.end ();
3285 }
80134cf5 3286
21fe1c75 3287 /* Remove the thread with ptid PTID. */
80134cf5 3288
21fe1c75
SM
3289 void remove_thread (ptid_t ptid)
3290 {
3291 auto match_ptid = [&] (const thread_item &item)
3292 {
3293 return item.ptid == ptid;
3294 };
cbb8991c 3295
21fe1c75
SM
3296 auto it = std::remove_if (this->items.begin (),
3297 this->items.end (),
3298 match_ptid);
cbb8991c 3299
21fe1c75
SM
3300 if (it != this->items.end ())
3301 this->items.erase (it);
3302 }
3303
3304 /* The threads found on the remote target. */
3305 std::vector<thread_item> items;
3306};
cbb8991c 3307
c906108c 3308static int
6dc54d91 3309remote_newthread_step (threadref *ref, void *data)
c906108c 3310{
19ba03f4
SM
3311 struct threads_listing_context *context
3312 = (struct threads_listing_context *) data;
21fe1c75
SM
3313 int pid = inferior_ptid.pid ();
3314 int lwp = threadref_to_int (ref);
3315 ptid_t ptid (pid, lwp);
6dc54d91 3316
21fe1c75 3317 context->items.emplace_back (ptid);
6dc54d91 3318
c906108c
SS
3319 return 1; /* continue iterator */
3320}
3321
3322#define CRAZY_MAX_THREADS 1000
3323
39f77062
KB
3324static ptid_t
3325remote_current_thread (ptid_t oldpid)
c906108c 3326{
d01949b6 3327 struct remote_state *rs = get_remote_state ();
c906108c
SS
3328
3329 putpkt ("qC");
6d820c5c 3330 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3331 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34 3332 {
256642e8 3333 const char *obuf;
c9f35b34
KB
3334 ptid_t result;
3335
3336 result = read_ptid (&rs->buf[2], &obuf);
3337 if (*obuf != '\0' && remote_debug)
3338 fprintf_unfiltered (gdb_stdlog,
3339 "warning: garbage in qC reply\n");
3340
3341 return result;
3342 }
c906108c
SS
3343 else
3344 return oldpid;
3345}
3346
6dc54d91 3347/* List remote threads using the deprecated qL packet. */
cce74817 3348
6dc54d91
PA
3349static int
3350remote_get_threads_with_ql (struct target_ops *ops,
3351 struct threads_listing_context *context)
c906108c 3352{
6dc54d91
PA
3353 if (remote_threadlist_iterator (remote_newthread_step, context,
3354 CRAZY_MAX_THREADS) >= 0)
3355 return 1;
3356
3357 return 0;
c906108c
SS
3358}
3359
dc146f7c
VP
3360#if defined(HAVE_LIBEXPAT)
3361
dc146f7c
VP
3362static void
3363start_thread (struct gdb_xml_parser *parser,
3364 const struct gdb_xml_element *element,
4d0fdd9b
SM
3365 void *user_data,
3366 std::vector<gdb_xml_value> &attributes)
dc146f7c 3367{
19ba03f4
SM
3368 struct threads_listing_context *data
3369 = (struct threads_listing_context *) user_data;
3d2c1d41 3370 struct gdb_xml_value *attr;
dc146f7c 3371
4d0fdd9b 3372 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
21fe1c75
SM
3373 ptid_t ptid = read_ptid (id, NULL);
3374
3375 data->items.emplace_back (ptid);
3376 thread_item &item = data->items.back ();
dc146f7c 3377
3d2c1d41
PA
3378 attr = xml_find_attribute (attributes, "core");
3379 if (attr != NULL)
4d0fdd9b 3380 item.core = *(ULONGEST *) attr->value.get ();
dc146f7c 3381
79efa585 3382 attr = xml_find_attribute (attributes, "name");
21fe1c75 3383 if (attr != NULL)
4d0fdd9b 3384 item.name = (const char *) attr->value.get ();
79efa585 3385
f6327dcb
KB
3386 attr = xml_find_attribute (attributes, "handle");
3387 if (attr != NULL)
4d0fdd9b 3388 item.thread_handle = hex2bin ((const char *) attr->value.get ());
dc146f7c
VP
3389}
3390
3391static void
3392end_thread (struct gdb_xml_parser *parser,
3393 const struct gdb_xml_element *element,
3394 void *user_data, const char *body_text)
3395{
19ba03f4
SM
3396 struct threads_listing_context *data
3397 = (struct threads_listing_context *) user_data;
dc146f7c 3398
21fe1c75
SM
3399 if (body_text != NULL && *body_text != '\0')
3400 data->items.back ().extra = body_text;
dc146f7c
VP
3401}
3402
3403const struct gdb_xml_attribute thread_attributes[] = {
3404 { "id", GDB_XML_AF_NONE, NULL, NULL },
3405 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3406 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
f6327dcb 3407 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3408 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3409};
3410
3411const struct gdb_xml_element thread_children[] = {
3412 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3413};
3414
3415const struct gdb_xml_element threads_children[] = {
3416 { "thread", thread_attributes, thread_children,
3417 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3418 start_thread, end_thread },
3419 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3420};
3421
3422const struct gdb_xml_element threads_elements[] = {
3423 { "threads", NULL, threads_children,
3424 GDB_XML_EF_NONE, NULL, NULL },
3425 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3426};
3427
3428#endif
3429
6dc54d91 3430/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3431
6dc54d91
PA
3432static int
3433remote_get_threads_with_qxfer (struct target_ops *ops,
3434 struct threads_listing_context *context)
0f71a2f6 3435{
dc146f7c 3436#if defined(HAVE_LIBEXPAT)
4082afcc 3437 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3438 {
9018be22 3439 gdb::optional<gdb::char_vector> xml
b7b030ad 3440 = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
efc0eabd 3441
9018be22 3442 if (xml && (*xml)[0] != '\0')
dc146f7c 3443 {
6dc54d91 3444 gdb_xml_parse_quick (_("threads"), "threads.dtd",
9018be22 3445 threads_elements, xml->data (), context);
dc146f7c
VP
3446 }
3447
6dc54d91 3448 return 1;
dc146f7c
VP
3449 }
3450#endif
3451
6dc54d91
PA
3452 return 0;
3453}
3454
3455/* List remote threads using qfThreadInfo/qsThreadInfo. */
3456
3457static int
3458remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3459 struct threads_listing_context *context)
3460{
3461 struct remote_state *rs = get_remote_state ();
3462
b80fafe3 3463 if (rs->use_threadinfo_query)
9d1f7ab2 3464 {
256642e8 3465 const char *bufp;
6dc54d91 3466
9d1f7ab2 3467 putpkt ("qfThreadInfo");
6d820c5c 3468 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3469 bufp = rs->buf;
9d1f7ab2 3470 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3471 {
9d1f7ab2
MS
3472 while (*bufp++ == 'm') /* reply contains one or more TID */
3473 {
3474 do
3475 {
21fe1c75
SM
3476 ptid_t ptid = read_ptid (bufp, &bufp);
3477 context->items.emplace_back (ptid);
9d1f7ab2
MS
3478 }
3479 while (*bufp++ == ','); /* comma-separated list */
3480 putpkt ("qsThreadInfo");
6d820c5c 3481 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 3482 bufp = rs->buf;
9d1f7ab2 3483 }
6dc54d91
PA
3484 return 1;
3485 }
3486 else
3487 {
3488 /* Packet not recognized. */
3489 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3490 }
3491 }
3492
6dc54d91
PA
3493 return 0;
3494}
3495
e8032dde 3496/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3497 targets. */
3498
f6ac5f3d
PA
3499void
3500remote_target::update_thread_list ()
6dc54d91 3501{
6dc54d91 3502 struct threads_listing_context context;
ab970af1 3503 int got_list = 0;
e8032dde 3504
6dc54d91
PA
3505 /* We have a few different mechanisms to fetch the thread list. Try
3506 them all, starting with the most preferred one first, falling
3507 back to older methods. */
f6ac5f3d
PA
3508 if (remote_get_threads_with_qxfer (this, &context)
3509 || remote_get_threads_with_qthreadinfo (this, &context)
3510 || remote_get_threads_with_ql (this, &context))
6dc54d91 3511 {
ab970af1
PA
3512 struct thread_info *tp, *tmp;
3513
3514 got_list = 1;
3515
21fe1c75 3516 if (context.items.empty ()
f6ac5f3d 3517 && remote_thread_always_alive (inferior_ptid))
7d1a114c
PA
3518 {
3519 /* Some targets don't really support threads, but still
3520 reply an (empty) thread list in response to the thread
3521 listing packets, instead of replying "packet not
3522 supported". Exit early so we don't delete the main
3523 thread. */
7d1a114c
PA
3524 return;
3525 }
3526
ab970af1
PA
3527 /* CONTEXT now holds the current thread list on the remote
3528 target end. Delete GDB-side threads no longer found on the
3529 target. */
8a06aea7 3530 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3531 {
21fe1c75 3532 if (!context.contains_thread (tp->ptid))
ab970af1
PA
3533 {
3534 /* Not found. */
3535 delete_thread (tp->ptid);
3536 }
cbb8991c
DB
3537 }
3538
3539 /* Remove any unreported fork child threads from CONTEXT so
3540 that we don't interfere with follow fork, which is where
3541 creation of such threads is handled. */
3542 remove_new_fork_children (&context);
74531fed 3543
ab970af1 3544 /* And now add threads we don't know about yet to our list. */
21fe1c75 3545 for (thread_item &item : context.items)
6dc54d91 3546 {
21fe1c75 3547 if (item.ptid != null_ptid)
6dc54d91 3548 {
6dc54d91 3549 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
3550 executing until proven otherwise with a stop reply.
3551 In all-stop, we can only get here if all threads are
6dc54d91 3552 stopped. */
0d5b594f 3553 int executing = target_is_non_stop_p () ? 1 : 0;
6dc54d91 3554
21fe1c75 3555 remote_notice_new_inferior (item.ptid, executing);
6dc54d91 3556
7aabaf9d 3557 remote_thread_info *info = get_remote_thread_info (item.ptid);
21fe1c75 3558 info->core = item.core;
7aabaf9d
SM
3559 info->extra = std::move (item.extra);
3560 info->name = std::move (item.name);
3561 info->thread_handle = std::move (item.thread_handle);
6dc54d91
PA
3562 }
3563 }
3564 }
3565
ab970af1
PA
3566 if (!got_list)
3567 {
3568 /* If no thread listing method is supported, then query whether
3569 each known thread is alive, one by one, with the T packet.
3570 If the target doesn't support threads at all, then this is a
3571 no-op. See remote_thread_alive. */
3572 prune_threads ();
3573 }
9d1f7ab2
MS
3574}
3575
802188a7 3576/*
9d1f7ab2
MS
3577 * Collect a descriptive string about the given thread.
3578 * The target may say anything it wants to about the thread
3579 * (typically info about its blocked / runnable state, name, etc.).
3580 * This string will appear in the info threads display.
802188a7 3581 *
9d1f7ab2
MS
3582 * Optional: targets are not required to implement this function.
3583 */
3584
f6ac5f3d
PA
3585const char *
3586remote_target::extra_thread_info (thread_info *tp)
9d1f7ab2 3587{
d01949b6 3588 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3589 int result;
3590 int set;
3591 threadref id;
3592 struct gdb_ext_thread_info threadinfo;
23860348 3593 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3594 int n = 0; /* position in display_buf */
3595
5d93a237 3596 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3597 internal_error (__FILE__, __LINE__,
e2e0b3e5 3598 _("remote_threads_extra_info"));
9d1f7ab2 3599
60e569b9 3600 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3601 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3602 /* This is the main thread which was added by GDB. The remote
3603 server doesn't know about it. */
3604 return NULL;
3605
4082afcc 3606 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3607 {
3608 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3609
7aabaf9d 3610 if (info != NULL && info->priv != NULL)
a9334058
SM
3611 {
3612 const std::string &extra = get_remote_thread_info (info)->extra;
3613 return !extra.empty () ? extra.c_str () : NULL;
3614 }
dc146f7c
VP
3615 else
3616 return NULL;
3617 }
3618
b80fafe3 3619 if (rs->use_threadextra_query)
9d1f7ab2 3620 {
82f73884
PA
3621 char *b = rs->buf;
3622 char *endb = rs->buf + get_remote_packet_size ();
3623
3624 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3625 b += strlen (b);
3626 write_ptid (b, endb, tp->ptid);
3627
2e9f7625 3628 putpkt (rs->buf);
6d820c5c 3629 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3630 if (rs->buf[0] != 0)
9d1f7ab2 3631 {
325fac50 3632 n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
2e9f7625 3633 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3634 display_buf [result] = '\0';
9d1f7ab2
MS
3635 return display_buf;
3636 }
0f71a2f6 3637 }
9d1f7ab2
MS
3638
3639 /* If the above query fails, fall back to the old method. */
b80fafe3 3640 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3641 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3642 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3643 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3644 if (remote_get_threadinfo (&id, set, &threadinfo))
3645 if (threadinfo.active)
0f71a2f6 3646 {
9d1f7ab2 3647 if (*threadinfo.shortname)
2bc416ba 3648 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3649 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3650 if (*threadinfo.display)
2bc416ba 3651 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3652 " State: %s,", threadinfo.display);
9d1f7ab2 3653 if (*threadinfo.more_display)
2bc416ba 3654 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3655 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3656
3657 if (n > 0)
c5aa993b 3658 {
23860348 3659 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3660 if (',' == display_buf[n-1])
3661 display_buf[n-1] = ' ';
3662 return display_buf;
c5aa993b 3663 }
0f71a2f6 3664 }
9d1f7ab2 3665 return NULL;
0f71a2f6 3666}
c906108c 3667\f
c5aa993b 3668
f6ac5f3d
PA
3669bool
3670remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3671 struct static_tracepoint_marker *marker)
0fb4aa4b
PA
3672{
3673 struct remote_state *rs = get_remote_state ();
3674 char *p = rs->buf;
3675
bba74b36 3676 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3677 p += strlen (p);
3678 p += hexnumstr (p, addr);
3679 putpkt (rs->buf);
3680 getpkt (&rs->buf, &rs->buf_size, 0);
3681 p = rs->buf;
3682
3683 if (*p == 'E')
3684 error (_("Remote failure reply: %s"), p);
3685
3686 if (*p++ == 'm')
3687 {
256642e8 3688 parse_static_tracepoint_marker_definition (p, NULL, marker);
5d9310c4 3689 return true;
0fb4aa4b
PA
3690 }
3691
5d9310c4 3692 return false;
0fb4aa4b
PA
3693}
3694
f6ac5f3d
PA
3695std::vector<static_tracepoint_marker>
3696remote_target::static_tracepoint_markers_by_strid (const char *strid)
0fb4aa4b
PA
3697{
3698 struct remote_state *rs = get_remote_state ();
5d9310c4 3699 std::vector<static_tracepoint_marker> markers;
256642e8 3700 const char *p;
5d9310c4 3701 static_tracepoint_marker marker;
0fb4aa4b
PA
3702
3703 /* Ask for a first packet of static tracepoint marker
3704 definition. */
3705 putpkt ("qTfSTM");
3706 getpkt (&rs->buf, &rs->buf_size, 0);
3707 p = rs->buf;
3708 if (*p == 'E')
3709 error (_("Remote failure reply: %s"), p);
3710
0fb4aa4b
PA
3711 while (*p++ == 'm')
3712 {
0fb4aa4b
PA
3713 do
3714 {
5d9310c4 3715 parse_static_tracepoint_marker_definition (p, &p, &marker);
0fb4aa4b 3716
5d9310c4
SM
3717 if (strid == NULL || marker.str_id == strid)
3718 markers.push_back (std::move (marker));
0fb4aa4b
PA
3719 }
3720 while (*p++ == ','); /* comma-separated list */
3721 /* Ask for another packet of static tracepoint definition. */
3722 putpkt ("qTsSTM");
3723 getpkt (&rs->buf, &rs->buf_size, 0);
3724 p = rs->buf;
3725 }
3726
0fb4aa4b
PA
3727 return markers;
3728}
3729
3730\f
10760264
JB
3731/* Implement the to_get_ada_task_ptid function for the remote targets. */
3732
f6ac5f3d
PA
3733ptid_t
3734remote_target::get_ada_task_ptid (long lwp, long thread)
10760264 3735{
ba348170 3736 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3737}
3738\f
3739
24b06219 3740/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3741
3742static void
fba45db2 3743extended_remote_restart (void)
c906108c 3744{
d01949b6 3745 struct remote_state *rs = get_remote_state ();
c906108c
SS
3746
3747 /* Send the restart command; for reasons I don't understand the
3748 remote side really expects a number after the "R". */
ea9c271d 3749 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3750 putpkt (rs->buf);
c906108c 3751
ad9a8f3f 3752 remote_fileio_reset ();
c906108c
SS
3753}
3754\f
3755/* Clean up connection to a remote debugger. */
3756
f6ac5f3d
PA
3757void
3758remote_target::close ()
c906108c 3759{
5d93a237
TT
3760 struct remote_state *rs = get_remote_state ();
3761
3762 if (rs->remote_desc == NULL)
d3fd5342
PA
3763 return; /* already closed */
3764
048094ac 3765 /* Make sure we leave stdin registered in the event loop. */
f6ac5f3d 3766 terminal_ours ();
ce5ce7ed 3767
5d93a237
TT
3768 serial_close (rs->remote_desc);
3769 rs->remote_desc = NULL;
ce5ce7ed
PA
3770
3771 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3772 of all the inferiors and their threads we were controlling.
3773 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3774 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3775 inferior_ptid = null_ptid;
f67fd822 3776 discard_all_inferiors ();
ce5ce7ed 3777
f48ff2a7
YQ
3778 /* We are closing the remote target, so we should discard
3779 everything of this target. */
bcc75809 3780 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3781
3782 if (remote_async_inferior_event_token)
3783 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3784
5965e028 3785 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3786
3787 trace_reset_local_state ();
c906108c
SS
3788}
3789
23860348 3790/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3791
3792static void
fba45db2 3793get_offsets (void)
c906108c 3794{
d01949b6 3795 struct remote_state *rs = get_remote_state ();
2e9f7625 3796 char *buf;
085dd6e6 3797 char *ptr;
31d99776
DJ
3798 int lose, num_segments = 0, do_sections, do_segments;
3799 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3800 struct section_offsets *offs;
31d99776
DJ
3801 struct symfile_segment_data *data;
3802
3803 if (symfile_objfile == NULL)
3804 return;
c906108c
SS
3805
3806 putpkt ("qOffsets");
6d820c5c 3807 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3808 buf = rs->buf;
c906108c
SS
3809
3810 if (buf[0] == '\000')
3811 return; /* Return silently. Stub doesn't support
23860348 3812 this command. */
c906108c
SS
3813 if (buf[0] == 'E')
3814 {
8a3fe4f8 3815 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3816 return;
3817 }
3818
3819 /* Pick up each field in turn. This used to be done with scanf, but
3820 scanf will make trouble if CORE_ADDR size doesn't match
3821 conversion directives correctly. The following code will work
3822 with any size of CORE_ADDR. */
3823 text_addr = data_addr = bss_addr = 0;
3824 ptr = buf;
3825 lose = 0;
3826
61012eef 3827 if (startswith (ptr, "Text="))
c906108c
SS
3828 {
3829 ptr += 5;
3830 /* Don't use strtol, could lose on big values. */
3831 while (*ptr && *ptr != ';')
3832 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3833
61012eef 3834 if (startswith (ptr, ";Data="))
31d99776
DJ
3835 {
3836 ptr += 6;
3837 while (*ptr && *ptr != ';')
3838 data_addr = (data_addr << 4) + fromhex (*ptr++);
3839 }
3840 else
3841 lose = 1;
3842
61012eef 3843 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3844 {
3845 ptr += 5;
3846 while (*ptr && *ptr != ';')
3847 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3848
31d99776
DJ
3849 if (bss_addr != data_addr)
3850 warning (_("Target reported unsupported offsets: %s"), buf);
3851 }
3852 else
3853 lose = 1;
3854 }
61012eef 3855 else if (startswith (ptr, "TextSeg="))
c906108c 3856 {
31d99776
DJ
3857 ptr += 8;
3858 /* Don't use strtol, could lose on big values. */
c906108c 3859 while (*ptr && *ptr != ';')
31d99776
DJ
3860 text_addr = (text_addr << 4) + fromhex (*ptr++);
3861 num_segments = 1;
3862
61012eef 3863 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3864 {
3865 ptr += 9;
3866 while (*ptr && *ptr != ';')
3867 data_addr = (data_addr << 4) + fromhex (*ptr++);
3868 num_segments++;
3869 }
c906108c
SS
3870 }
3871 else
3872 lose = 1;
3873
3874 if (lose)
8a3fe4f8 3875 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3876 else if (*ptr != '\0')
3877 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3878
802188a7 3879 offs = ((struct section_offsets *)
a39a16c4 3880 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3881 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3882 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3883
31d99776
DJ
3884 data = get_symfile_segment_data (symfile_objfile->obfd);
3885 do_segments = (data != NULL);
3886 do_sections = num_segments == 0;
c906108c 3887
28c32713 3888 if (num_segments > 0)
31d99776 3889 {
31d99776
DJ
3890 segments[0] = text_addr;
3891 segments[1] = data_addr;
3892 }
28c32713
JB
3893 /* If we have two segments, we can still try to relocate everything
3894 by assuming that the .text and .data offsets apply to the whole
3895 text and data segments. Convert the offsets given in the packet
3896 to base addresses for symfile_map_offsets_to_segments. */
3897 else if (data && data->num_segments == 2)
3898 {
3899 segments[0] = data->segment_bases[0] + text_addr;
3900 segments[1] = data->segment_bases[1] + data_addr;
3901 num_segments = 2;
3902 }
8d385431
DJ
3903 /* If the object file has only one segment, assume that it is text
3904 rather than data; main programs with no writable data are rare,
3905 but programs with no code are useless. Of course the code might
3906 have ended up in the data segment... to detect that we would need
3907 the permissions here. */
3908 else if (data && data->num_segments == 1)
3909 {
3910 segments[0] = data->segment_bases[0] + text_addr;
3911 num_segments = 1;
3912 }
28c32713
JB
3913 /* There's no way to relocate by segment. */
3914 else
3915 do_segments = 0;
31d99776
DJ
3916
3917 if (do_segments)
3918 {
3919 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3920 offs, num_segments, segments);
3921
3922 if (ret == 0 && !do_sections)
3e43a32a
MS
3923 error (_("Can not handle qOffsets TextSeg "
3924 "response with this symbol file"));
31d99776
DJ
3925
3926 if (ret > 0)
3927 do_sections = 0;
3928 }
c906108c 3929
9ef895d6
DJ
3930 if (data)
3931 free_symfile_segment_data (data);
31d99776
DJ
3932
3933 if (do_sections)
3934 {
3935 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3936
3e43a32a
MS
3937 /* This is a temporary kludge to force data and bss to use the
3938 same offsets because that's what nlmconv does now. The real
3939 solution requires changes to the stub and remote.c that I
3940 don't have time to do right now. */
31d99776
DJ
3941
3942 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3943 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3944 }
c906108c
SS
3945
3946 objfile_relocate (symfile_objfile, offs);
3947}
3948
9a7071a8
JB
3949/* Send interrupt_sequence to remote target. */
3950static void
eeae04df 3951send_interrupt_sequence (void)
9a7071a8 3952{
5d93a237
TT
3953 struct remote_state *rs = get_remote_state ();
3954
9a7071a8 3955 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3956 remote_serial_write ("\x03", 1);
9a7071a8 3957 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3958 serial_send_break (rs->remote_desc);
9a7071a8
JB
3959 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3960 {
5d93a237 3961 serial_send_break (rs->remote_desc);
c33e31fd 3962 remote_serial_write ("g", 1);
9a7071a8
JB
3963 }
3964 else
3965 internal_error (__FILE__, __LINE__,
3966 _("Invalid value for interrupt_sequence_mode: %s."),
3967 interrupt_sequence_mode);
3968}
3969
3405876a
PA
3970
3971/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3972 and extract the PTID. Returns NULL_PTID if not found. */
3973
3974static ptid_t
3975stop_reply_extract_thread (char *stop_reply)
3976{
3977 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3978 {
256642e8 3979 const char *p;
3405876a
PA
3980
3981 /* Txx r:val ; r:val (...) */
3982 p = &stop_reply[3];
3983
3984 /* Look for "register" named "thread". */
3985 while (*p != '\0')
3986 {
256642e8 3987 const char *p1;
3405876a
PA
3988
3989 p1 = strchr (p, ':');
3990 if (p1 == NULL)
3991 return null_ptid;
3992
3993 if (strncmp (p, "thread", p1 - p) == 0)
3994 return read_ptid (++p1, &p);
3995
3996 p1 = strchr (p, ';');
3997 if (p1 == NULL)
3998 return null_ptid;
3999 p1++;
4000
4001 p = p1;
4002 }
4003 }
4004
4005 return null_ptid;
4006}
4007
b7ea362b
PA
4008/* Determine the remote side's current thread. If we have a stop
4009 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4010 "thread" register we can extract the current thread from. If not,
4011 ask the remote which is the current thread with qC. The former
4012 method avoids a roundtrip. */
4013
4014static ptid_t
4015get_current_thread (char *wait_status)
4016{
6a49a997 4017 ptid_t ptid = null_ptid;
b7ea362b
PA
4018
4019 /* Note we don't use remote_parse_stop_reply as that makes use of
4020 the target architecture, which we haven't yet fully determined at
4021 this point. */
4022 if (wait_status != NULL)
4023 ptid = stop_reply_extract_thread (wait_status);
4024 if (ptid_equal (ptid, null_ptid))
4025 ptid = remote_current_thread (inferior_ptid);
4026
4027 return ptid;
4028}
4029
49c62f2e
PA
4030/* Query the remote target for which is the current thread/process,
4031 add it to our tables, and update INFERIOR_PTID. The caller is
4032 responsible for setting the state such that the remote end is ready
3405876a
PA
4033 to return the current thread.
4034
4035 This function is called after handling the '?' or 'vRun' packets,
4036 whose response is a stop reply from which we can also try
4037 extracting the thread. If the target doesn't support the explicit
4038 qC query, we infer the current thread from that stop reply, passed
4039 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
4040
4041static void
3405876a 4042add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
4043{
4044 struct remote_state *rs = get_remote_state ();
4045 int fake_pid_p = 0;
49c62f2e
PA
4046
4047 inferior_ptid = null_ptid;
4048
b7ea362b 4049 /* Now, if we have thread information, update inferior_ptid. */
87215ad1 4050 ptid_t curr_ptid = get_current_thread (wait_status);
3405876a 4051
87215ad1 4052 if (curr_ptid != null_ptid)
49c62f2e
PA
4053 {
4054 if (!remote_multi_process_p (rs))
4055 fake_pid_p = 1;
49c62f2e
PA
4056 }
4057 else
4058 {
4059 /* Without this, some commands which require an active target
4060 (such as kill) won't work. This variable serves (at least)
4061 double duty as both the pid of the target process (if it has
4062 such), and as a flag indicating that a target is active. */
87215ad1 4063 curr_ptid = magic_null_ptid;
49c62f2e
PA
4064 fake_pid_p = 1;
4065 }
4066
87215ad1 4067 remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
49c62f2e 4068
87215ad1
SDJ
4069 /* Add the main thread and switch to it. Don't try reading
4070 registers yet, since we haven't fetched the target description
4071 yet. */
4072 thread_info *tp = add_thread_silent (curr_ptid);
4073 switch_to_thread_no_regs (tp);
49c62f2e
PA
4074}
4075
6efcd9a8
PA
4076/* Print info about a thread that was found already stopped on
4077 connection. */
4078
4079static void
4080print_one_stopped_thread (struct thread_info *thread)
4081{
4082 struct target_waitstatus *ws = &thread->suspend.waitstatus;
4083
4084 switch_to_thread (thread->ptid);
4085 stop_pc = get_frame_pc (get_current_frame ());
4086 set_current_sal_from_frame (get_current_frame ());
4087
4088 thread->suspend.waitstatus_pending_p = 0;
4089
4090 if (ws->kind == TARGET_WAITKIND_STOPPED)
4091 {
4092 enum gdb_signal sig = ws->value.sig;
4093
4094 if (signal_print_state (sig))
76727919 4095 gdb::observers::signal_received.notify (sig);
6efcd9a8 4096 }
76727919 4097 gdb::observers::normal_stop.notify (NULL, 1);
6efcd9a8
PA
4098}
4099
221e1a37
PA
4100/* Process all initial stop replies the remote side sent in response
4101 to the ? packet. These indicate threads that were already stopped
4102 on initial connection. We mark these threads as stopped and print
4103 their current frame before giving the user the prompt. */
4104
4105static void
6efcd9a8 4106process_initial_stop_replies (int from_tty)
221e1a37
PA
4107{
4108 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
4109 struct inferior *inf;
4110 struct thread_info *thread;
4111 struct thread_info *selected = NULL;
4112 struct thread_info *lowest_stopped = NULL;
4113 struct thread_info *first = NULL;
221e1a37
PA
4114
4115 /* Consume the initial pending events. */
4116 while (pending_stop_replies-- > 0)
4117 {
4118 ptid_t waiton_ptid = minus_one_ptid;
4119 ptid_t event_ptid;
4120 struct target_waitstatus ws;
4121 int ignore_event = 0;
6efcd9a8 4122 struct thread_info *thread;
221e1a37
PA
4123
4124 memset (&ws, 0, sizeof (ws));
4125 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4126 if (remote_debug)
4127 print_target_wait_results (waiton_ptid, event_ptid, &ws);
4128
4129 switch (ws.kind)
4130 {
4131 case TARGET_WAITKIND_IGNORE:
4132 case TARGET_WAITKIND_NO_RESUMED:
4133 case TARGET_WAITKIND_SIGNALLED:
4134 case TARGET_WAITKIND_EXITED:
4135 /* We shouldn't see these, but if we do, just ignore. */
4136 if (remote_debug)
4137 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4138 ignore_event = 1;
4139 break;
4140
4141 case TARGET_WAITKIND_EXECD:
4142 xfree (ws.value.execd_pathname);
4143 break;
4144 default:
4145 break;
4146 }
4147
4148 if (ignore_event)
4149 continue;
4150
6efcd9a8 4151 thread = find_thread_ptid (event_ptid);
221e1a37
PA
4152
4153 if (ws.kind == TARGET_WAITKIND_STOPPED)
4154 {
4155 enum gdb_signal sig = ws.value.sig;
4156
4157 /* Stubs traditionally report SIGTRAP as initial signal,
4158 instead of signal 0. Suppress it. */
4159 if (sig == GDB_SIGNAL_TRAP)
4160 sig = GDB_SIGNAL_0;
6efcd9a8
PA
4161 thread->suspend.stop_signal = sig;
4162 ws.value.sig = sig;
4163 }
221e1a37 4164
6efcd9a8
PA
4165 thread->suspend.waitstatus = ws;
4166
4167 if (ws.kind != TARGET_WAITKIND_STOPPED
4168 || ws.value.sig != GDB_SIGNAL_0)
4169 thread->suspend.waitstatus_pending_p = 1;
4170
4171 set_executing (event_ptid, 0);
4172 set_running (event_ptid, 0);
7aabaf9d 4173 get_remote_thread_info (thread)->vcont_resumed = 0;
6efcd9a8
PA
4174 }
4175
4176 /* "Notice" the new inferiors before anything related to
4177 registers/memory. */
4178 ALL_INFERIORS (inf)
4179 {
4180 if (inf->pid == 0)
4181 continue;
4182
4183 inf->needs_setup = 1;
4184
4185 if (non_stop)
4186 {
4187 thread = any_live_thread_of_process (inf->pid);
4188 notice_new_inferior (thread->ptid,
4189 thread->state == THREAD_RUNNING,
4190 from_tty);
4191 }
4192 }
4193
4194 /* If all-stop on top of non-stop, pause all threads. Note this
4195 records the threads' stop pc, so must be done after "noticing"
4196 the inferiors. */
4197 if (!non_stop)
4198 {
4199 stop_all_threads ();
4200
4201 /* If all threads of an inferior were already stopped, we
4202 haven't setup the inferior yet. */
4203 ALL_INFERIORS (inf)
4204 {
4205 if (inf->pid == 0)
4206 continue;
221e1a37 4207
6efcd9a8
PA
4208 if (inf->needs_setup)
4209 {
4210 thread = any_live_thread_of_process (inf->pid);
4211 switch_to_thread_no_regs (thread);
4212 setup_inferior (0);
4213 }
4214 }
221e1a37 4215 }
6efcd9a8
PA
4216
4217 /* Now go over all threads that are stopped, and print their current
4218 frame. If all-stop, then if there's a signalled thread, pick
4219 that as current. */
4220 ALL_NON_EXITED_THREADS (thread)
4221 {
6efcd9a8
PA
4222 if (first == NULL)
4223 first = thread;
4224
4225 if (!non_stop)
4226 set_running (thread->ptid, 0);
4227 else if (thread->state != THREAD_STOPPED)
4228 continue;
4229
6efcd9a8
PA
4230 if (selected == NULL
4231 && thread->suspend.waitstatus_pending_p)
4232 selected = thread;
4233
5d5658a1
PA
4234 if (lowest_stopped == NULL
4235 || thread->inf->num < lowest_stopped->inf->num
4236 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
4237 lowest_stopped = thread;
4238
4239 if (non_stop)
4240 print_one_stopped_thread (thread);
4241 }
4242
4243 /* In all-stop, we only print the status of one thread, and leave
4244 others with their status pending. */
4245 if (!non_stop)
4246 {
4247 thread = selected;
4248 if (thread == NULL)
4249 thread = lowest_stopped;
4250 if (thread == NULL)
4251 thread = first;
4252
4253 print_one_stopped_thread (thread);
4254 }
4255
4256 /* For "info program". */
4257 thread = inferior_thread ();
4258 if (thread->state == THREAD_STOPPED)
4259 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
4260}
4261
048094ac
PA
4262/* Start the remote connection and sync state. */
4263
f6ac5f3d
PA
4264void
4265remote_target::start_remote (int from_tty, int extended_p)
c906108c 4266{
c8d104ad
PA
4267 struct remote_state *rs = get_remote_state ();
4268 struct packet_config *noack_config;
2d717e4f 4269 char *wait_status = NULL;
8621d6a9 4270
048094ac
PA
4271 /* Signal other parts that we're going through the initial setup,
4272 and so things may not be stable yet. E.g., we don't try to
4273 install tracepoints until we've relocated symbols. Also, a
4274 Ctrl-C before we're connected and synced up can't interrupt the
4275 target. Instead, it offers to drop the (potentially wedged)
4276 connection. */
4277 rs->starting_up = 1;
4278
522002f9 4279 QUIT;
c906108c 4280
9a7071a8
JB
4281 if (interrupt_on_connect)
4282 send_interrupt_sequence ();
4283
57e12211 4284 /* Ack any packet which the remote side has already sent. */
048094ac 4285 remote_serial_write ("+", 1);
1e51243a 4286
c8d104ad
PA
4287 /* The first packet we send to the target is the optional "supported
4288 packets" request. If the target can answer this, it will tell us
4289 which later probes to skip. */
4290 remote_query_supported ();
4291
d914c394 4292 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 4293 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
f6ac5f3d 4294 set_permissions ();
d914c394 4295
57809e5e
JK
4296 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4297 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4298 as a reply to known packet. For packet "vFile:setfs:" it is an
4299 invalid reply and GDB would return error in
4300 remote_hostio_set_filesystem, making remote files access impossible.
4301 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4302 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4303 {
4304 const char v_mustreplyempty[] = "vMustReplyEmpty";
4305
4306 putpkt (v_mustreplyempty);
4307 getpkt (&rs->buf, &rs->buf_size, 0);
4308 if (strcmp (rs->buf, "OK") == 0)
4309 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4310 else if (strcmp (rs->buf, "") != 0)
4311 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4312 rs->buf);
4313 }
4314
c8d104ad
PA
4315 /* Next, we possibly activate noack mode.
4316
4317 If the QStartNoAckMode packet configuration is set to AUTO,
4318 enable noack mode if the stub reported a wish for it with
4319 qSupported.
4320
4321 If set to TRUE, then enable noack mode even if the stub didn't
4322 report it in qSupported. If the stub doesn't reply OK, the
4323 session ends with an error.
4324
4325 If FALSE, then don't activate noack mode, regardless of what the
4326 stub claimed should be the default with qSupported. */
4327
4328 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 4329 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
4330 {
4331 putpkt ("QStartNoAckMode");
4332 getpkt (&rs->buf, &rs->buf_size, 0);
4333 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4334 rs->noack_mode = 1;
4335 }
4336
04bd08de 4337 if (extended_p)
5fe04517
PA
4338 {
4339 /* Tell the remote that we are using the extended protocol. */
4340 putpkt ("!");
4341 getpkt (&rs->buf, &rs->buf_size, 0);
4342 }
4343
9b224c5e
PA
4344 /* Let the target know which signals it is allowed to pass down to
4345 the program. */
4346 update_signals_program_target ();
4347
d962ef82
DJ
4348 /* Next, if the target can specify a description, read it. We do
4349 this before anything involving memory or registers. */
4350 target_find_description ();
4351
6c95b8df
PA
4352 /* Next, now that we know something about the target, update the
4353 address spaces in the program spaces. */
4354 update_address_spaces ();
4355
50c71eaf
PA
4356 /* On OSs where the list of libraries is global to all
4357 processes, we fetch them early. */
f5656ead 4358 if (gdbarch_has_global_solist (target_gdbarch ()))
e696b3ad 4359 solib_add (NULL, from_tty, auto_solib_add);
50c71eaf 4360
6efcd9a8 4361 if (target_is_non_stop_p ())
74531fed 4362 {
4082afcc 4363 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
4364 error (_("Non-stop mode requested, but remote "
4365 "does not support non-stop"));
74531fed
PA
4366
4367 putpkt ("QNonStop:1");
4368 getpkt (&rs->buf, &rs->buf_size, 0);
4369
4370 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4371 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
4372
4373 /* Find about threads and processes the stub is already
4374 controlling. We default to adding them in the running state.
4375 The '?' query below will then tell us about which threads are
4376 stopped. */
f6ac5f3d 4377 this->update_thread_list ();
74531fed 4378 }
4082afcc 4379 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4380 {
4381 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4382 Request it explicitly. */
74531fed
PA
4383 putpkt ("QNonStop:0");
4384 getpkt (&rs->buf, &rs->buf_size, 0);
4385
4386 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4387 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
4388 }
4389
a0743c90
YQ
4390 /* Upload TSVs regardless of whether the target is running or not. The
4391 remote stub, such as GDBserver, may have some predefined or builtin
4392 TSVs, even if the target is not running. */
f6ac5f3d 4393 if (get_trace_status (current_trace_status ()) != -1)
a0743c90
YQ
4394 {
4395 struct uploaded_tsv *uploaded_tsvs = NULL;
4396
f6ac5f3d 4397 upload_trace_state_variables (&uploaded_tsvs);
a0743c90
YQ
4398 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4399 }
4400
2d717e4f
DJ
4401 /* Check whether the target is running now. */
4402 putpkt ("?");
4403 getpkt (&rs->buf, &rs->buf_size, 0);
4404
6efcd9a8 4405 if (!target_is_non_stop_p ())
2d717e4f 4406 {
74531fed 4407 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4408 {
04bd08de 4409 if (!extended_p)
74531fed 4410 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4411
4412 /* We're connected, but not running. Drop out before we
4413 call start_remote. */
e278ad5b 4414 rs->starting_up = 0;
c35b1492 4415 return;
2d717e4f
DJ
4416 }
4417 else
74531fed 4418 {
74531fed 4419 /* Save the reply for later. */
224c3ddb 4420 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
4421 strcpy (wait_status, rs->buf);
4422 }
4423
b7ea362b 4424 /* Fetch thread list. */
e8032dde 4425 target_update_thread_list ();
b7ea362b 4426
74531fed
PA
4427 /* Let the stub know that we want it to return the thread. */
4428 set_continue_thread (minus_one_ptid);
4429
b7ea362b
PA
4430 if (thread_count () == 0)
4431 {
4432 /* Target has no concept of threads at all. GDB treats
4433 non-threaded target as single-threaded; add a main
4434 thread. */
4435 add_current_inferior_and_thread (wait_status);
4436 }
4437 else
4438 {
4439 /* We have thread information; select the thread the target
4440 says should be current. If we're reconnecting to a
4441 multi-threaded program, this will ideally be the thread
4442 that last reported an event before GDB disconnected. */
4443 inferior_ptid = get_current_thread (wait_status);
4444 if (ptid_equal (inferior_ptid, null_ptid))
4445 {
4446 /* Odd... The target was able to list threads, but not
4447 tell us which thread was current (no "thread"
4448 register in T stop reply?). Just pick the first
4449 thread in the thread list then. */
c9f35b34
KB
4450
4451 if (remote_debug)
4452 fprintf_unfiltered (gdb_stdlog,
4453 "warning: couldn't determine remote "
4454 "current thread; picking first in list.\n");
4455
b7ea362b
PA
4456 inferior_ptid = thread_list->ptid;
4457 }
4458 }
74531fed 4459
6e586cc5
YQ
4460 /* init_wait_for_inferior should be called before get_offsets in order
4461 to manage `inserted' flag in bp loc in a correct state.
4462 breakpoint_init_inferior, called from init_wait_for_inferior, set
4463 `inserted' flag to 0, while before breakpoint_re_set, called from
4464 start_remote, set `inserted' flag to 1. In the initialization of
4465 inferior, breakpoint_init_inferior should be called first, and then
4466 breakpoint_re_set can be called. If this order is broken, state of
4467 `inserted' flag is wrong, and cause some problems on breakpoint
4468 manipulation. */
4469 init_wait_for_inferior ();
4470
74531fed
PA
4471 get_offsets (); /* Get text, data & bss offsets. */
4472
d962ef82
DJ
4473 /* If we could not find a description using qXfer, and we know
4474 how to do it some other way, try again. This is not
4475 supported for non-stop; it could be, but it is tricky if
4476 there are no stopped threads when we connect. */
f6ac5f3d 4477 if (remote_read_description_p (this)
f5656ead 4478 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4479 {
4480 target_clear_description ();
4481 target_find_description ();
4482 }
4483
74531fed
PA
4484 /* Use the previously fetched status. */
4485 gdb_assert (wait_status != NULL);
4486 strcpy (rs->buf, wait_status);
4487 rs->cached_wait_status = 1;
4488
f6ac5f3d 4489 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4490 }
4491 else
4492 {
68c97600
PA
4493 /* Clear WFI global state. Do this before finding about new
4494 threads and inferiors, and setting the current inferior.
4495 Otherwise we would clear the proceed status of the current
4496 inferior when we want its stop_soon state to be preserved
4497 (see notice_new_inferior). */
4498 init_wait_for_inferior ();
4499
74531fed
PA
4500 /* In non-stop, we will either get an "OK", meaning that there
4501 are no stopped threads at this time; or, a regular stop
4502 reply. In the latter case, there may be more than one thread
4503 stopped --- we pull them all out using the vStopped
4504 mechanism. */
4505 if (strcmp (rs->buf, "OK") != 0)
4506 {
722247f1 4507 struct notif_client *notif = &notif_client_stop;
2d717e4f 4508
722247f1
YQ
4509 /* remote_notif_get_pending_replies acks this one, and gets
4510 the rest out. */
f48ff2a7 4511 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
4512 = remote_notif_parse (notif, rs->buf);
4513 remote_notif_get_pending_events (notif);
74531fed 4514 }
2d717e4f 4515
74531fed
PA
4516 if (thread_count () == 0)
4517 {
04bd08de 4518 if (!extended_p)
74531fed 4519 error (_("The target is not running (try extended-remote?)"));
82f73884 4520
c35b1492
PA
4521 /* We're connected, but not running. Drop out before we
4522 call start_remote. */
e278ad5b 4523 rs->starting_up = 0;
c35b1492
PA
4524 return;
4525 }
74531fed 4526
74531fed
PA
4527 /* In non-stop mode, any cached wait status will be stored in
4528 the stop reply queue. */
4529 gdb_assert (wait_status == NULL);
f0223081 4530
2455069d 4531 /* Report all signals during attach/startup. */
f6ac5f3d 4532 pass_signals (0, NULL);
221e1a37
PA
4533
4534 /* If there are already stopped threads, mark them stopped and
4535 report their stops before giving the prompt to the user. */
6efcd9a8 4536 process_initial_stop_replies (from_tty);
221e1a37
PA
4537
4538 if (target_can_async_p ())
4539 target_async (1);
74531fed 4540 }
c8d104ad 4541
c8d104ad
PA
4542 /* If we connected to a live target, do some additional setup. */
4543 if (target_has_execution)
4544 {
f4ccffad 4545 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4546 remote_check_symbols ();
c8d104ad 4547 }
50c71eaf 4548
d5551862
SS
4549 /* Possibly the target has been engaged in a trace run started
4550 previously; find out where things are at. */
f6ac5f3d 4551 if (get_trace_status (current_trace_status ()) != -1)
d5551862 4552 {
00bf0b85 4553 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4554
00bf0b85
SS
4555 if (current_trace_status ()->running)
4556 printf_filtered (_("Trace is already running on the target.\n"));
4557
f6ac5f3d 4558 upload_tracepoints (&uploaded_tps);
00bf0b85
SS
4559
4560 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4561 }
4562
c0272db5
TW
4563 /* Possibly the target has been engaged in a btrace record started
4564 previously; find out where things are at. */
4565 remote_btrace_maybe_reopen ();
4566
1e51243a
PA
4567 /* The thread and inferior lists are now synchronized with the
4568 target, our symbols have been relocated, and we're merged the
4569 target's tracepoints with ours. We're done with basic start
4570 up. */
4571 rs->starting_up = 0;
4572
a25a5a45
PA
4573 /* Maybe breakpoints are global and need to be inserted now. */
4574 if (breakpoints_should_be_inserted_now ())
50c71eaf 4575 insert_breakpoints ();
c906108c
SS
4576}
4577
4578/* Open a connection to a remote debugger.
4579 NAME is the filename used for communication. */
4580
f6ac5f3d
PA
4581void
4582remote_target::open (const char *name, int from_tty)
c906108c 4583{
f6ac5f3d 4584 open_1 (name, from_tty, 0);
43ff13b4
JM
4585}
4586
c906108c
SS
4587/* Open a connection to a remote debugger using the extended
4588 remote gdb protocol. NAME is the filename used for communication. */
4589
f6ac5f3d
PA
4590void
4591extended_remote_target::open (const char *name, int from_tty)
c906108c 4592{
f6ac5f3d 4593 open_1 (name, from_tty, 1 /*extended_p */);
43ff13b4
JM
4594}
4595
ca4f7f8b
PA
4596/* Reset all packets back to "unknown support". Called when opening a
4597 new connection to a remote target. */
c906108c 4598
d471ea57 4599static void
ca4f7f8b 4600reset_all_packet_configs_support (void)
d471ea57
AC
4601{
4602 int i;
a744cf53 4603
444abaca 4604 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4605 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4606}
4607
ca4f7f8b
PA
4608/* Initialize all packet configs. */
4609
4610static void
4611init_all_packet_configs (void)
4612{
4613 int i;
4614
4615 for (i = 0; i < PACKET_MAX; i++)
4616 {
4617 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4618 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4619 }
4620}
4621
23860348 4622/* Symbol look-up. */
dc8acb97
MS
4623
4624static void
36d25514 4625remote_check_symbols (void)
dc8acb97
MS
4626{
4627 char *msg, *reply, *tmp;
dc8acb97 4628 int end;
28170b88 4629 long reply_size;
a5c0808e 4630 struct cleanup *old_chain;
dc8acb97 4631
63154eca
PA
4632 /* The remote side has no concept of inferiors that aren't running
4633 yet, it only knows about running processes. If we're connected
4634 but our current inferior is not running, we should not invite the
4635 remote target to request symbol lookups related to its
4636 (unrelated) current process. */
4637 if (!target_has_execution)
4638 return;
4639
4082afcc 4640 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4641 return;
4642
63154eca
PA
4643 /* Make sure the remote is pointing at the right process. Note
4644 there's no way to select "no process". */
3c9c4b83
PA
4645 set_general_process ();
4646
6d820c5c
DJ
4647 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4648 because we need both at the same time. */
224c3ddb 4649 msg = (char *) xmalloc (get_remote_packet_size ());
a5c0808e 4650 old_chain = make_cleanup (xfree, msg);
28170b88
MK
4651 reply = (char *) xmalloc (get_remote_packet_size ());
4652 make_cleanup (free_current_contents, &reply);
4653 reply_size = get_remote_packet_size ();
6d820c5c 4654
23860348 4655 /* Invite target to request symbol lookups. */
dc8acb97
MS
4656
4657 putpkt ("qSymbol::");
28170b88
MK
4658 getpkt (&reply, &reply_size, 0);
4659 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
dc8acb97 4660
61012eef 4661 while (startswith (reply, "qSymbol:"))
dc8acb97 4662 {
77e371c0
TT
4663 struct bound_minimal_symbol sym;
4664
dc8acb97 4665 tmp = &reply[8];
cfd77fa1 4666 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4667 msg[end] = '\0';
4668 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4669 if (sym.minsym == NULL)
ea9c271d 4670 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4671 else
2bbe3cc1 4672 {
f5656ead 4673 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4674 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4675
4676 /* If this is a function address, return the start of code
4677 instead of any data function descriptor. */
f5656ead 4678 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1 4679 sym_addr,
f6ac5f3d 4680 target_stack);
2bbe3cc1
DJ
4681
4682 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4683 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4684 }
4685
dc8acb97 4686 putpkt (msg);
28170b88 4687 getpkt (&reply, &reply_size, 0);
dc8acb97 4688 }
a5c0808e
PA
4689
4690 do_cleanups (old_chain);
dc8acb97
MS
4691}
4692
9db8d71f 4693static struct serial *
baa336ce 4694remote_serial_open (const char *name)
9db8d71f
DJ
4695{
4696 static int udp_warning = 0;
4697
4698 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4699 of in ser-tcp.c, because it is the remote protocol assuming that the
4700 serial connection is reliable and not the serial connection promising
4701 to be. */
61012eef 4702 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4703 {
3e43a32a
MS
4704 warning (_("The remote protocol may be unreliable over UDP.\n"
4705 "Some events may be lost, rendering further debugging "
4706 "impossible."));
9db8d71f
DJ
4707 udp_warning = 1;
4708 }
4709
4710 return serial_open (name);
4711}
4712
d914c394
SS
4713/* Inform the target of our permission settings. The permission flags
4714 work without this, but if the target knows the settings, it can do
4715 a couple things. First, it can add its own check, to catch cases
4716 that somehow manage to get by the permissions checks in target
4717 methods. Second, if the target is wired to disallow particular
4718 settings (for instance, a system in the field that is not set up to
4719 be able to stop at a breakpoint), it can object to any unavailable
4720 permissions. */
4721
4722void
f6ac5f3d 4723remote_target::set_permissions ()
d914c394
SS
4724{
4725 struct remote_state *rs = get_remote_state ();
4726
bba74b36
YQ
4727 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4728 "WriteReg:%x;WriteMem:%x;"
4729 "InsertBreak:%x;InsertTrace:%x;"
4730 "InsertFastTrace:%x;Stop:%x",
4731 may_write_registers, may_write_memory,
4732 may_insert_breakpoints, may_insert_tracepoints,
4733 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4734 putpkt (rs->buf);
4735 getpkt (&rs->buf, &rs->buf_size, 0);
4736
4737 /* If the target didn't like the packet, warn the user. Do not try
4738 to undo the user's settings, that would just be maddening. */
4739 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4740 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4741}
4742
be2a5f71
DJ
4743/* This type describes each known response to the qSupported
4744 packet. */
4745struct protocol_feature
4746{
4747 /* The name of this protocol feature. */
4748 const char *name;
4749
4750 /* The default for this protocol feature. */
4751 enum packet_support default_support;
4752
4753 /* The function to call when this feature is reported, or after
4754 qSupported processing if the feature is not supported.
4755 The first argument points to this structure. The second
4756 argument indicates whether the packet requested support be
4757 enabled, disabled, or probed (or the default, if this function
4758 is being called at the end of processing and this feature was
4759 not reported). The third argument may be NULL; if not NULL, it
4760 is a NUL-terminated string taken from the packet following
4761 this feature's name and an equals sign. */
4762 void (*func) (const struct protocol_feature *, enum packet_support,
4763 const char *);
4764
4765 /* The corresponding packet for this feature. Only used if
4766 FUNC is remote_supported_packet. */
4767 int packet;
4768};
4769
be2a5f71
DJ
4770static void
4771remote_supported_packet (const struct protocol_feature *feature,
4772 enum packet_support support,
4773 const char *argument)
4774{
4775 if (argument)
4776 {
4777 warning (_("Remote qSupported response supplied an unexpected value for"
4778 " \"%s\"."), feature->name);
4779 return;
4780 }
4781
4082afcc 4782 remote_protocol_packets[feature->packet].support = support;
be2a5f71 4783}
be2a5f71
DJ
4784
4785static void
4786remote_packet_size (const struct protocol_feature *feature,
4787 enum packet_support support, const char *value)
4788{
4789 struct remote_state *rs = get_remote_state ();
4790
4791 int packet_size;
4792 char *value_end;
4793
4794 if (support != PACKET_ENABLE)
4795 return;
4796
4797 if (value == NULL || *value == '\0')
4798 {
4799 warning (_("Remote target reported \"%s\" without a size."),
4800 feature->name);
4801 return;
4802 }
4803
4804 errno = 0;
4805 packet_size = strtol (value, &value_end, 16);
4806 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4807 {
4808 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4809 feature->name, value);
4810 return;
4811 }
4812
be2a5f71
DJ
4813 /* Record the new maximum packet size. */
4814 rs->explicit_packet_size = packet_size;
4815}
4816
dc473cfb 4817static const struct protocol_feature remote_protocol_features[] = {
0876f84a 4818 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 4819 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 4820 PACKET_qXfer_auxv },
c78fa86a
GB
4821 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4822 PACKET_qXfer_exec_file },
23181151
DJ
4823 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4824 PACKET_qXfer_features },
cfa9d6d9
DJ
4825 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4826 PACKET_qXfer_libraries },
2268b414
JK
4827 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4828 PACKET_qXfer_libraries_svr4 },
ced63ec0 4829 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 4830 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 4831 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 4832 PACKET_qXfer_memory_map },
4de6483e
UW
4833 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4834 PACKET_qXfer_spu_read },
4835 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4836 PACKET_qXfer_spu_write },
07e059b5
VP
4837 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4838 PACKET_qXfer_osdata },
dc146f7c
VP
4839 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4840 PACKET_qXfer_threads },
b3b9301e
PA
4841 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4842 PACKET_qXfer_traceframe_info },
89be2091
DJ
4843 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4844 PACKET_QPassSignals },
82075af2
JS
4845 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4846 PACKET_QCatchSyscalls },
9b224c5e
PA
4847 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4848 PACKET_QProgramSignals },
bc3b087d
SDJ
4849 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
4850 PACKET_QSetWorkingDir },
aefd8b33
SDJ
4851 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
4852 PACKET_QStartupWithShell },
0a2dde4a
SDJ
4853 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
4854 PACKET_QEnvironmentHexEncoded },
4855 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
4856 PACKET_QEnvironmentReset },
4857 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
4858 PACKET_QEnvironmentUnset },
a6f3e723
SL
4859 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4860 PACKET_QStartNoAckMode },
4082afcc
PA
4861 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4862 PACKET_multiprocess_feature },
4863 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4864 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4865 PACKET_qXfer_siginfo_read },
4866 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4867 PACKET_qXfer_siginfo_write },
4082afcc 4868 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4869 PACKET_ConditionalTracepoints },
4082afcc 4870 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4871 PACKET_ConditionalBreakpoints },
4082afcc 4872 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4873 PACKET_BreakpointCommands },
4082afcc 4874 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4875 PACKET_FastTracepoints },
4082afcc 4876 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4877 PACKET_StaticTracepoints },
4082afcc 4878 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4879 PACKET_InstallInTrace},
4082afcc
PA
4880 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4881 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4882 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4883 PACKET_bc },
4884 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4885 PACKET_bs },
409873ef
SS
4886 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4887 PACKET_TracepointSource },
d914c394
SS
4888 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4889 PACKET_QAllow },
4082afcc
PA
4890 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4891 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4892 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4893 PACKET_qXfer_fdpic },
169081d0
TG
4894 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4895 PACKET_qXfer_uib },
03583c20
UW
4896 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4897 PACKET_QDisableRandomization },
d1feda86 4898 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4899 { "QTBuffer:size", PACKET_DISABLE,
4900 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4901 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4902 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4903 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 4904 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 4905 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4906 PACKET_qXfer_btrace },
4907 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4908 PACKET_qXfer_btrace_conf },
4909 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4910 PACKET_Qbtrace_conf_bts_size },
4911 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4912 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
4913 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4914 PACKET_fork_event_feature },
4915 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4916 PACKET_vfork_event_feature },
94585166
DB
4917 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4918 PACKET_exec_event_feature },
b20a6524 4919 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 4920 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
4921 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4922 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 4923 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
be2a5f71
DJ
4924};
4925
c8d5aac9
L
4926static char *remote_support_xml;
4927
4928/* Register string appended to "xmlRegisters=" in qSupported query. */
4929
4930void
6e39997a 4931register_remote_support_xml (const char *xml)
c8d5aac9
L
4932{
4933#if defined(HAVE_LIBEXPAT)
4934 if (remote_support_xml == NULL)
c4f7c687 4935 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4936 else
4937 {
4938 char *copy = xstrdup (remote_support_xml + 13);
4939 char *p = strtok (copy, ",");
4940
4941 do
4942 {
4943 if (strcmp (p, xml) == 0)
4944 {
4945 /* already there */
4946 xfree (copy);
4947 return;
4948 }
4949 }
4950 while ((p = strtok (NULL, ",")) != NULL);
4951 xfree (copy);
4952
94b0dee1
PA
4953 remote_support_xml = reconcat (remote_support_xml,
4954 remote_support_xml, ",", xml,
4955 (char *) NULL);
c8d5aac9
L
4956 }
4957#endif
4958}
4959
69b6ecb0
TT
4960static void
4961remote_query_supported_append (std::string *msg, const char *append)
c8d5aac9 4962{
69b6ecb0
TT
4963 if (!msg->empty ())
4964 msg->append (";");
4965 msg->append (append);
c8d5aac9
L
4966}
4967
be2a5f71
DJ
4968static void
4969remote_query_supported (void)
4970{
4971 struct remote_state *rs = get_remote_state ();
4972 char *next;
4973 int i;
4974 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4975
4976 /* The packet support flags are handled differently for this packet
4977 than for most others. We treat an error, a disabled packet, and
4978 an empty response identically: any features which must be reported
4979 to be used will be automatically disabled. An empty buffer
4980 accomplishes this, since that is also the representation for a list
4981 containing no features. */
4982
4983 rs->buf[0] = 0;
4082afcc 4984 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4985 {
69b6ecb0 4986 std::string q;
c8d5aac9 4987
73b8c1fd 4988 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 4989 remote_query_supported_append (&q, "multiprocess+");
c8d5aac9 4990
f7e6eed5 4991 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 4992 remote_query_supported_append (&q, "swbreak+");
f7e6eed5 4993 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
69b6ecb0 4994 remote_query_supported_append (&q, "hwbreak+");
f7e6eed5 4995
69b6ecb0 4996 remote_query_supported_append (&q, "qRelocInsn+");
dde08ee1 4997
8020350c
DB
4998 if (packet_set_cmd_state (PACKET_fork_event_feature)
4999 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5000 remote_query_supported_append (&q, "fork-events+");
8020350c
DB
5001 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5002 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5003 remote_query_supported_append (&q, "vfork-events+");
8020350c
DB
5004 if (packet_set_cmd_state (PACKET_exec_event_feature)
5005 != AUTO_BOOLEAN_FALSE)
69b6ecb0 5006 remote_query_supported_append (&q, "exec-events+");
89245bc0 5007
750ce8d1 5008 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5009 remote_query_supported_append (&q, "vContSupported+");
750ce8d1 5010
65706a29 5011 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5012 remote_query_supported_append (&q, "QThreadEvents+");
65706a29 5013
f2faf941 5014 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
69b6ecb0 5015 remote_query_supported_append (&q, "no-resumed+");
f2faf941 5016
b35d5edb
PA
5017 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5018 the qSupported:xmlRegisters=i386 handling. */
7cc244de
PA
5019 if (remote_support_xml != NULL
5020 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
69b6ecb0 5021 remote_query_supported_append (&q, remote_support_xml);
82f73884 5022
69b6ecb0
TT
5023 q = "qSupported:" + q;
5024 putpkt (q.c_str ());
94b0dee1 5025
be2a5f71
DJ
5026 getpkt (&rs->buf, &rs->buf_size, 0);
5027
5028 /* If an error occured, warn, but do not return - just reset the
5029 buffer to empty and go on to disable features. */
5030 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5031 == PACKET_ERROR)
5032 {
5033 warning (_("Remote failure reply: %s"), rs->buf);
5034 rs->buf[0] = 0;
5035 }
5036 }
5037
5038 memset (seen, 0, sizeof (seen));
5039
5040 next = rs->buf;
5041 while (*next)
5042 {
5043 enum packet_support is_supported;
5044 char *p, *end, *name_end, *value;
5045
5046 /* First separate out this item from the rest of the packet. If
5047 there's another item after this, we overwrite the separator
5048 (terminated strings are much easier to work with). */
5049 p = next;
5050 end = strchr (p, ';');
5051 if (end == NULL)
5052 {
5053 end = p + strlen (p);
5054 next = end;
5055 }
5056 else
5057 {
89be2091
DJ
5058 *end = '\0';
5059 next = end + 1;
5060
be2a5f71
DJ
5061 if (end == p)
5062 {
5063 warning (_("empty item in \"qSupported\" response"));
5064 continue;
5065 }
be2a5f71
DJ
5066 }
5067
5068 name_end = strchr (p, '=');
5069 if (name_end)
5070 {
5071 /* This is a name=value entry. */
5072 is_supported = PACKET_ENABLE;
5073 value = name_end + 1;
5074 *name_end = '\0';
5075 }
5076 else
5077 {
5078 value = NULL;
5079 switch (end[-1])
5080 {
5081 case '+':
5082 is_supported = PACKET_ENABLE;
5083 break;
5084
5085 case '-':
5086 is_supported = PACKET_DISABLE;
5087 break;
5088
5089 case '?':
5090 is_supported = PACKET_SUPPORT_UNKNOWN;
5091 break;
5092
5093 default:
3e43a32a
MS
5094 warning (_("unrecognized item \"%s\" "
5095 "in \"qSupported\" response"), p);
be2a5f71
DJ
5096 continue;
5097 }
5098 end[-1] = '\0';
5099 }
5100
5101 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5102 if (strcmp (remote_protocol_features[i].name, p) == 0)
5103 {
5104 const struct protocol_feature *feature;
5105
5106 seen[i] = 1;
5107 feature = &remote_protocol_features[i];
5108 feature->func (feature, is_supported, value);
5109 break;
5110 }
5111 }
5112
5113 /* If we increased the packet size, make sure to increase the global
5114 buffer size also. We delay this until after parsing the entire
5115 qSupported packet, because this is the same buffer we were
5116 parsing. */
5117 if (rs->buf_size < rs->explicit_packet_size)
5118 {
5119 rs->buf_size = rs->explicit_packet_size;
224c3ddb 5120 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
be2a5f71
DJ
5121 }
5122
5123 /* Handle the defaults for unmentioned features. */
5124 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5125 if (!seen[i])
5126 {
5127 const struct protocol_feature *feature;
5128
5129 feature = &remote_protocol_features[i];
5130 feature->func (feature, feature->default_support, NULL);
5131 }
5132}
5133
048094ac
PA
5134/* Serial QUIT handler for the remote serial descriptor.
5135
5136 Defers handling a Ctrl-C until we're done with the current
5137 command/response packet sequence, unless:
5138
5139 - We're setting up the connection. Don't send a remote interrupt
5140 request, as we're not fully synced yet. Quit immediately
5141 instead.
5142
5143 - The target has been resumed in the foreground
223ffa71 5144 (target_terminal::is_ours is false) with a synchronous resume
048094ac
PA
5145 packet, and we're blocked waiting for the stop reply, thus a
5146 Ctrl-C should be immediately sent to the target.
5147
5148 - We get a second Ctrl-C while still within the same serial read or
5149 write. In that case the serial is seemingly wedged --- offer to
5150 quit/disconnect.
5151
5152 - We see a second Ctrl-C without target response, after having
5153 previously interrupted the target. In that case the target/stub
5154 is probably wedged --- offer to quit/disconnect.
5155*/
5156
5157static void
5158remote_serial_quit_handler (void)
5159{
5160 struct remote_state *rs = get_remote_state ();
5161
5162 if (check_quit_flag ())
5163 {
5164 /* If we're starting up, we're not fully synced yet. Quit
5165 immediately. */
5166 if (rs->starting_up)
5167 quit ();
5168 else if (rs->got_ctrlc_during_io)
5169 {
5170 if (query (_("The target is not responding to GDB commands.\n"
5171 "Stop debugging it? ")))
5172 remote_unpush_and_throw ();
5173 }
5174 /* If ^C has already been sent once, offer to disconnect. */
223ffa71 5175 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
048094ac
PA
5176 interrupt_query ();
5177 /* All-stop protocol, and blocked waiting for stop reply. Send
5178 an interrupt request. */
223ffa71 5179 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
e671cd59 5180 target_interrupt ();
048094ac
PA
5181 else
5182 rs->got_ctrlc_during_io = 1;
5183 }
5184}
5185
78a095c3
JK
5186/* Remove any of the remote.c targets from target stack. Upper targets depend
5187 on it so remove them first. */
5188
5189static void
5190remote_unpush_target (void)
5191{
915ef8b1 5192 pop_all_targets_at_and_above (process_stratum);
78a095c3 5193}
be2a5f71 5194
048094ac
PA
5195static void
5196remote_unpush_and_throw (void)
5197{
5198 remote_unpush_target ();
5199 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5200}
5201
f6ac5f3d
PA
5202void
5203remote_target::open_1 (const char *name, int from_tty, int extended_p)
c906108c 5204{
d01949b6 5205 struct remote_state *rs = get_remote_state ();
a6f3e723 5206
c906108c 5207 if (name == 0)
8a3fe4f8 5208 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 5209 "serial device is attached to the remote system\n"
8a3fe4f8 5210 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 5211
23860348 5212 /* See FIXME above. */
c6ebd6cf 5213 if (!target_async_permitted)
92d1e331 5214 wait_forever_enabled_p = 1;
6426a772 5215
2d717e4f 5216 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
5217 Ask this question first, before target_preopen has a chance to kill
5218 anything. */
5d93a237 5219 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 5220 {
78a095c3
JK
5221 if (from_tty
5222 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
5223 error (_("Still connected."));
5224 }
5225
78a095c3 5226 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
5227 target_preopen (from_tty);
5228
89be2091 5229 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
5230 xfree (rs->last_pass_packet);
5231 rs->last_pass_packet = NULL;
89be2091 5232
9b224c5e
PA
5233 /* Make sure we send the program signals list the next time we
5234 resume. */
5e4a05c4
TT
5235 xfree (rs->last_program_signals_packet);
5236 rs->last_program_signals_packet = NULL;
9b224c5e 5237
ad9a8f3f 5238 remote_fileio_reset ();
1dd41f16
NS
5239 reopen_exec_file ();
5240 reread_symbols ();
5241
5d93a237
TT
5242 rs->remote_desc = remote_serial_open (name);
5243 if (!rs->remote_desc)
c906108c
SS
5244 perror_with_name (name);
5245
5246 if (baud_rate != -1)
5247 {
5d93a237 5248 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 5249 {
9b74d5d3
KB
5250 /* The requested speed could not be set. Error out to
5251 top level after closing remote_desc. Take care to
5252 set remote_desc to NULL to avoid closing remote_desc
5253 more than once. */
5d93a237
TT
5254 serial_close (rs->remote_desc);
5255 rs->remote_desc = NULL;
c906108c
SS
5256 perror_with_name (name);
5257 }
5258 }
5259
236af5e3 5260 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 5261 serial_raw (rs->remote_desc);
c906108c
SS
5262
5263 /* If there is something sitting in the buffer we might take it as a
5264 response to a command, which would be bad. */
5d93a237 5265 serial_flush_input (rs->remote_desc);
c906108c
SS
5266
5267 if (from_tty)
5268 {
5269 puts_filtered ("Remote debugging using ");
5270 puts_filtered (name);
5271 puts_filtered ("\n");
5272 }
d9f719f1
PA
5273
5274 remote_target *target
5275 = extended_p ? &extended_remote_ops : &remote_ops;
5276 push_target (target); /* Switch to using remote target now. */
c906108c 5277
74531fed
PA
5278 /* Register extra event sources in the event loop. */
5279 remote_async_inferior_event_token
5280 = create_async_event_handler (remote_async_inferior_event_handler,
5281 NULL);
5965e028 5282 rs->notif_state = remote_notif_state_allocate ();
74531fed 5283
be2a5f71
DJ
5284 /* Reset the target state; these things will be queried either by
5285 remote_query_supported or as they are needed. */
ca4f7f8b 5286 reset_all_packet_configs_support ();
74531fed 5287 rs->cached_wait_status = 0;
be2a5f71 5288 rs->explicit_packet_size = 0;
a6f3e723 5289 rs->noack_mode = 0;
82f73884 5290 rs->extended = extended_p;
e24a49d8 5291 rs->waiting_for_stop_reply = 0;
3a29589a 5292 rs->ctrlc_pending_p = 0;
048094ac 5293 rs->got_ctrlc_during_io = 0;
802188a7 5294
47f8a51d
TT
5295 rs->general_thread = not_sent_ptid;
5296 rs->continue_thread = not_sent_ptid;
262e1174 5297 rs->remote_traceframe_number = -1;
c906108c 5298
3a00c802
PA
5299 rs->last_resume_exec_dir = EXEC_FORWARD;
5300
9d1f7ab2 5301 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
5302 rs->use_threadinfo_query = 1;
5303 rs->use_threadextra_query = 1;
9d1f7ab2 5304
80152258
PA
5305 readahead_cache_invalidate ();
5306
c6ebd6cf 5307 if (target_async_permitted)
92d1e331 5308 {
92d1e331
DJ
5309 /* FIXME: cagney/1999-09-23: During the initial connection it is
5310 assumed that the target is already ready and able to respond to
0df8b418 5311 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 5312 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 5313 around this. Eventually a mechanism that allows
92d1e331 5314 wait_for_inferior() to expect/get timeouts will be
23860348 5315 implemented. */
92d1e331
DJ
5316 wait_forever_enabled_p = 0;
5317 }
5318
23860348 5319 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 5320 no_shared_libraries (NULL, 0);
f78f6cf1 5321
74531fed
PA
5322 /* Start afresh. */
5323 init_thread_list ();
5324
36918e70 5325 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
5326 target (we'd otherwise be in an inconsistent state) and then
5327 propogate the error on up the exception chain. This ensures that
5328 the caller doesn't stumble along blindly assuming that the
5329 function succeeded. The CLI doesn't have this problem but other
5330 UI's, such as MI do.
36918e70
AC
5331
5332 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5333 this function should return an error indication letting the
ce2826aa 5334 caller restore the previous state. Unfortunately the command
36918e70
AC
5335 ``target remote'' is directly wired to this function making that
5336 impossible. On a positive note, the CLI side of this problem has
5337 been fixed - the function set_cmd_context() makes it possible for
5338 all the ``target ....'' commands to share a common callback
5339 function. See cli-dump.c. */
109c3e39 5340 {
2d717e4f 5341
492d29ea 5342 TRY
04bd08de 5343 {
d9f719f1 5344 target->start_remote (from_tty, extended_p);
04bd08de 5345 }
492d29ea 5346 CATCH (ex, RETURN_MASK_ALL)
109c3e39 5347 {
c8d104ad
PA
5348 /* Pop the partially set up target - unless something else did
5349 already before throwing the exception. */
5d93a237 5350 if (rs->remote_desc != NULL)
78a095c3 5351 remote_unpush_target ();
c6ebd6cf 5352 if (target_async_permitted)
109c3e39
AC
5353 wait_forever_enabled_p = 1;
5354 throw_exception (ex);
5355 }
492d29ea 5356 END_CATCH
109c3e39 5357 }
c906108c 5358
f4abbc16
MM
5359 remote_btrace_reset ();
5360
c6ebd6cf 5361 if (target_async_permitted)
92d1e331 5362 wait_forever_enabled_p = 1;
43ff13b4
JM
5363}
5364
de0d863e
DB
5365/* Detach the specified process. */
5366
5367static void
5368remote_detach_pid (int pid)
5369{
5370 struct remote_state *rs = get_remote_state ();
5371
5372 if (remote_multi_process_p (rs))
5373 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5374 else
5375 strcpy (rs->buf, "D");
5376
5377 putpkt (rs->buf);
5378 getpkt (&rs->buf, &rs->buf_size, 0);
5379
5380 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5381 ;
5382 else if (rs->buf[0] == '\0')
5383 error (_("Remote doesn't know how to detach"));
5384 else
5385 error (_("Can't detach process."));
5386}
5387
5388/* This detaches a program to which we previously attached, using
5389 inferior_ptid to identify the process. After this is done, GDB
5390 can be used to debug some other program. We better not have left
5391 any breakpoints in the target program or it'll die when it hits
5392 one. */
c906108c
SS
5393
5394static void
6e1e1966 5395remote_detach_1 (int from_tty, inferior *inf)
c906108c 5396{
82f73884 5397 int pid = ptid_get_pid (inferior_ptid);
d01949b6 5398 struct remote_state *rs = get_remote_state ();
de0d863e
DB
5399 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5400 int is_fork_parent;
c906108c 5401
2d717e4f
DJ
5402 if (!target_has_execution)
5403 error (_("No process to detach from."));
5404
0f48b757 5405 target_announce_detach (from_tty);
7cee1e54 5406
c906108c 5407 /* Tell the remote target to detach. */
de0d863e 5408 remote_detach_pid (pid);
82f73884 5409
8020350c
DB
5410 /* Exit only if this is the only active inferior. */
5411 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
7cee1e54 5412 puts_filtered (_("Ending remote debugging.\n"));
82f73884 5413
de0d863e
DB
5414 /* Check to see if we are detaching a fork parent. Note that if we
5415 are detaching a fork child, tp == NULL. */
5416 is_fork_parent = (tp != NULL
5417 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5418
5419 /* If doing detach-on-fork, we don't mourn, because that will delete
5420 breakpoints that should be available for the followed inferior. */
5421 if (!is_fork_parent)
f67c0c91 5422 {
249b5733
PA
5423 /* Save the pid as a string before mourning, since that will
5424 unpush the remote target, and we need the string after. */
5425 std::string infpid = target_pid_to_str (pid_to_ptid (pid));
f67c0c91
SDJ
5426
5427 target_mourn_inferior (inferior_ptid);
5428 if (print_inferior_events)
5429 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5430 inf->num, infpid.c_str ());
5431 }
de0d863e
DB
5432 else
5433 {
5434 inferior_ptid = null_ptid;
5435 detach_inferior (pid);
5436 }
2d717e4f
DJ
5437}
5438
f6ac5f3d
PA
5439void
5440remote_target::detach (inferior *inf, int from_tty)
2d717e4f 5441{
6e1e1966 5442 remote_detach_1 (from_tty, inf);
2d717e4f
DJ
5443}
5444
f6ac5f3d
PA
5445void
5446extended_remote_target::detach (inferior *inf, int from_tty)
2d717e4f 5447{
6e1e1966 5448 remote_detach_1 (from_tty, inf);
de0d863e
DB
5449}
5450
5451/* Target follow-fork function for remote targets. On entry, and
5452 at return, the current inferior is the fork parent.
5453
5454 Note that although this is currently only used for extended-remote,
5455 it is named remote_follow_fork in anticipation of using it for the
5456 remote target as well. */
5457
f6ac5f3d
PA
5458int
5459remote_target::follow_fork (int follow_child, int detach_fork)
de0d863e
DB
5460{
5461 struct remote_state *rs = get_remote_state ();
c269dbdb 5462 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5463
c269dbdb
DB
5464 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5465 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5466 {
5467 /* When following the parent and detaching the child, we detach
5468 the child here. For the case of following the child and
5469 detaching the parent, the detach is done in the target-
5470 independent follow fork code in infrun.c. We can't use
5471 target_detach when detaching an unfollowed child because
5472 the client side doesn't know anything about the child. */
5473 if (detach_fork && !follow_child)
5474 {
5475 /* Detach the fork child. */
5476 ptid_t child_ptid;
5477 pid_t child_pid;
5478
5479 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5480 child_pid = ptid_get_pid (child_ptid);
5481
5482 remote_detach_pid (child_pid);
de0d863e
DB
5483 }
5484 }
5485 return 0;
c906108c
SS
5486}
5487
94585166
DB
5488/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5489 in the program space of the new inferior. On entry and at return the
5490 current inferior is the exec'ing inferior. INF is the new exec'd
5491 inferior, which may be the same as the exec'ing inferior unless
5492 follow-exec-mode is "new". */
5493
f6ac5f3d
PA
5494void
5495remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
94585166
DB
5496{
5497 /* We know that this is a target file name, so if it has the "target:"
5498 prefix we strip it off before saving it in the program space. */
5499 if (is_target_filename (execd_pathname))
5500 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5501
5502 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5503}
5504
6ad8ae5c
DJ
5505/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5506
f6ac5f3d
PA
5507void
5508remote_target::disconnect (const char *args, int from_tty)
43ff13b4 5509{
43ff13b4 5510 if (args)
2d717e4f 5511 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5512
8020350c
DB
5513 /* Make sure we unpush even the extended remote targets. Calling
5514 target_mourn_inferior won't unpush, and remote_mourn won't
5515 unpush if there is more than one inferior left. */
f6ac5f3d 5516 unpush_target (this);
8020350c 5517 generic_mourn_inferior ();
2d717e4f 5518
43ff13b4
JM
5519 if (from_tty)
5520 puts_filtered ("Ending remote debugging.\n");
5521}
5522
2d717e4f
DJ
5523/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5524 be chatty about it. */
5525
f6ac5f3d
PA
5526void
5527extended_remote_target::attach (const char *args, int from_tty)
2d717e4f
DJ
5528{
5529 struct remote_state *rs = get_remote_state ();
be86555c 5530 int pid;
96ef3384 5531 char *wait_status = NULL;
2d717e4f 5532
74164c56 5533 pid = parse_pid_to_attach (args);
2d717e4f 5534
74164c56
JK
5535 /* Remote PID can be freely equal to getpid, do not check it here the same
5536 way as in other targets. */
2d717e4f 5537
4082afcc 5538 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5539 error (_("This target does not support attaching to a process"));
5540
7cee1e54
PA
5541 if (from_tty)
5542 {
5543 char *exec_file = get_exec_file (0);
5544
5545 if (exec_file)
5546 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5547 target_pid_to_str (pid_to_ptid (pid)));
5548 else
5549 printf_unfiltered (_("Attaching to %s\n"),
5550 target_pid_to_str (pid_to_ptid (pid)));
5551
5552 gdb_flush (gdb_stdout);
5553 }
5554
bba74b36 5555 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
5556 putpkt (rs->buf);
5557 getpkt (&rs->buf, &rs->buf_size, 0);
5558
4082afcc
PA
5559 switch (packet_ok (rs->buf,
5560 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5561 {
4082afcc 5562 case PACKET_OK:
6efcd9a8 5563 if (!target_is_non_stop_p ())
74531fed
PA
5564 {
5565 /* Save the reply for later. */
224c3ddb 5566 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
5567 strcpy (wait_status, rs->buf);
5568 }
5569 else if (strcmp (rs->buf, "OK") != 0)
5570 error (_("Attaching to %s failed with: %s"),
5571 target_pid_to_str (pid_to_ptid (pid)),
5572 rs->buf);
4082afcc
PA
5573 break;
5574 case PACKET_UNKNOWN:
5575 error (_("This target does not support attaching to a process"));
5576 default:
5577 error (_("Attaching to %s failed"),
5578 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 5579 }
2d717e4f 5580
1b6e6f5c 5581 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 5582
2d717e4f 5583 inferior_ptid = pid_to_ptid (pid);
79d7f229 5584
6efcd9a8 5585 if (target_is_non_stop_p ())
bad34192
PA
5586 {
5587 struct thread_info *thread;
79d7f229 5588
bad34192 5589 /* Get list of threads. */
f6ac5f3d 5590 update_thread_list ();
82f73884 5591
bad34192
PA
5592 thread = first_thread_of_process (pid);
5593 if (thread)
5594 inferior_ptid = thread->ptid;
5595 else
5596 inferior_ptid = pid_to_ptid (pid);
5597
5598 /* Invalidate our notion of the remote current thread. */
47f8a51d 5599 record_currthread (rs, minus_one_ptid);
bad34192 5600 }
74531fed 5601 else
bad34192
PA
5602 {
5603 /* Now, if we have thread information, update inferior_ptid. */
5604 inferior_ptid = remote_current_thread (inferior_ptid);
5605
5606 /* Add the main thread to the thread list. */
00aecdcf
PA
5607 thread_info *thr = add_thread_silent (inferior_ptid);
5608 /* Don't consider the thread stopped until we've processed the
5609 saved stop reply. */
5610 set_executing (thr->ptid, true);
bad34192 5611 }
c0a2216e 5612
96ef3384
UW
5613 /* Next, if the target can specify a description, read it. We do
5614 this before anything involving memory or registers. */
5615 target_find_description ();
5616
6efcd9a8 5617 if (!target_is_non_stop_p ())
74531fed
PA
5618 {
5619 /* Use the previously fetched status. */
5620 gdb_assert (wait_status != NULL);
5621
5622 if (target_can_async_p ())
5623 {
722247f1
YQ
5624 struct notif_event *reply
5625 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 5626
722247f1 5627 push_stop_reply ((struct stop_reply *) reply);
74531fed 5628
6a3753b3 5629 target_async (1);
74531fed
PA
5630 }
5631 else
5632 {
5633 gdb_assert (wait_status != NULL);
5634 strcpy (rs->buf, wait_status);
5635 rs->cached_wait_status = 1;
5636 }
5637 }
5638 else
5639 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5640}
5641
b9c1d481
AS
5642/* Implementation of the to_post_attach method. */
5643
f6ac5f3d
PA
5644void
5645extended_remote_target::post_attach (int pid)
b9c1d481 5646{
6efcd9a8
PA
5647 /* Get text, data & bss offsets. */
5648 get_offsets ();
5649
b9c1d481
AS
5650 /* In certain cases GDB might not have had the chance to start
5651 symbol lookup up until now. This could happen if the debugged
5652 binary is not using shared libraries, the vsyscall page is not
5653 present (on Linux) and the binary itself hadn't changed since the
5654 debugging process was started. */
5655 if (symfile_objfile != NULL)
5656 remote_check_symbols();
5657}
5658
c906108c 5659\f
506fb367
DJ
5660/* Check for the availability of vCont. This function should also check
5661 the response. */
c906108c
SS
5662
5663static void
6d820c5c 5664remote_vcont_probe (struct remote_state *rs)
c906108c 5665{
2e9f7625 5666 char *buf;
6d820c5c 5667
2e9f7625
DJ
5668 strcpy (rs->buf, "vCont?");
5669 putpkt (rs->buf);
6d820c5c 5670 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 5671 buf = rs->buf;
c906108c 5672
506fb367 5673 /* Make sure that the features we assume are supported. */
61012eef 5674 if (startswith (buf, "vCont"))
506fb367
DJ
5675 {
5676 char *p = &buf[5];
750ce8d1 5677 int support_c, support_C;
506fb367 5678
750ce8d1
YQ
5679 rs->supports_vCont.s = 0;
5680 rs->supports_vCont.S = 0;
506fb367
DJ
5681 support_c = 0;
5682 support_C = 0;
d458bd84 5683 rs->supports_vCont.t = 0;
c1e36e3e 5684 rs->supports_vCont.r = 0;
506fb367
DJ
5685 while (p && *p == ';')
5686 {
5687 p++;
5688 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5689 rs->supports_vCont.s = 1;
506fb367 5690 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5691 rs->supports_vCont.S = 1;
506fb367
DJ
5692 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5693 support_c = 1;
5694 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5695 support_C = 1;
74531fed 5696 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5697 rs->supports_vCont.t = 1;
c1e36e3e
PA
5698 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5699 rs->supports_vCont.r = 1;
506fb367
DJ
5700
5701 p = strchr (p, ';');
5702 }
c906108c 5703
750ce8d1
YQ
5704 /* If c, and C are not all supported, we can't use vCont. Clearing
5705 BUF will make packet_ok disable the packet. */
5706 if (!support_c || !support_C)
506fb367
DJ
5707 buf[0] = 0;
5708 }
c906108c 5709
444abaca 5710 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 5711}
c906108c 5712
0d8f58ca
PA
5713/* Helper function for building "vCont" resumptions. Write a
5714 resumption to P. ENDP points to one-passed-the-end of the buffer
5715 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5716 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5717 resumed thread should be single-stepped and/or signalled. If PTID
5718 equals minus_one_ptid, then all threads are resumed; if PTID
5719 represents a process, then all threads of the process are resumed;
5720 the thread to be stepped and/or signalled is given in the global
5721 INFERIOR_PTID. */
5722
5723static char *
5724append_resumption (char *p, char *endp,
2ea28649 5725 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
5726{
5727 struct remote_state *rs = get_remote_state ();
5728
a493e3e2 5729 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5730 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5731 else if (step
5732 /* GDB is willing to range step. */
5733 && use_range_stepping
5734 /* Target supports range stepping. */
5735 && rs->supports_vCont.r
5736 /* We don't currently support range stepping multiple
5737 threads with a wildcard (though the protocol allows it,
5738 so stubs shouldn't make an active effort to forbid
5739 it). */
5740 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5741 {
5742 struct thread_info *tp;
5743
5744 if (ptid_equal (ptid, minus_one_ptid))
5745 {
5746 /* If we don't know about the target thread's tid, then
5747 we're resuming magic_null_ptid (see caller). */
5748 tp = find_thread_ptid (magic_null_ptid);
5749 }
5750 else
5751 tp = find_thread_ptid (ptid);
5752 gdb_assert (tp != NULL);
5753
5754 if (tp->control.may_range_step)
5755 {
5756 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5757
5758 p += xsnprintf (p, endp - p, ";r%s,%s",
5759 phex_nz (tp->control.step_range_start,
5760 addr_size),
5761 phex_nz (tp->control.step_range_end,
5762 addr_size));
5763 }
5764 else
5765 p += xsnprintf (p, endp - p, ";s");
5766 }
0d8f58ca
PA
5767 else if (step)
5768 p += xsnprintf (p, endp - p, ";s");
a493e3e2 5769 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
5770 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5771 else
5772 p += xsnprintf (p, endp - p, ";c");
5773
5774 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5775 {
5776 ptid_t nptid;
5777
5778 /* All (-1) threads of process. */
ba348170 5779 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
5780
5781 p += xsnprintf (p, endp - p, ":");
5782 p = write_ptid (p, endp, nptid);
5783 }
5784 else if (!ptid_equal (ptid, minus_one_ptid))
5785 {
5786 p += xsnprintf (p, endp - p, ":");
5787 p = write_ptid (p, endp, ptid);
5788 }
5789
5790 return p;
5791}
5792
799a2abe
PA
5793/* Clear the thread's private info on resume. */
5794
5795static void
5796resume_clear_thread_private_info (struct thread_info *thread)
5797{
5798 if (thread->priv != NULL)
5799 {
7aabaf9d
SM
5800 remote_thread_info *priv = get_remote_thread_info (thread);
5801
5802 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5803 priv->watch_data_address = 0;
799a2abe
PA
5804 }
5805}
5806
e5ef252a
PA
5807/* Append a vCont continue-with-signal action for threads that have a
5808 non-zero stop signal. */
5809
5810static char *
5811append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5812{
5813 struct thread_info *thread;
5814
034f788c 5815 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
5816 if (ptid_match (thread->ptid, ptid)
5817 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 5818 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
5819 {
5820 p = append_resumption (p, endp, thread->ptid,
5821 0, thread->suspend.stop_signal);
5822 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 5823 resume_clear_thread_private_info (thread);
e5ef252a
PA
5824 }
5825
5826 return p;
5827}
5828
7b68ffbb
PA
5829/* Set the target running, using the packets that use Hc
5830 (c/s/C/S). */
5831
5832static void
5833remote_resume_with_hc (struct target_ops *ops,
5834 ptid_t ptid, int step, enum gdb_signal siggnal)
5835{
5836 struct remote_state *rs = get_remote_state ();
5837 struct thread_info *thread;
5838 char *buf;
5839
5840 rs->last_sent_signal = siggnal;
5841 rs->last_sent_step = step;
5842
5843 /* The c/s/C/S resume packets use Hc, so set the continue
5844 thread. */
5845 if (ptid_equal (ptid, minus_one_ptid))
5846 set_continue_thread (any_thread_ptid);
5847 else
5848 set_continue_thread (ptid);
5849
5850 ALL_NON_EXITED_THREADS (thread)
5851 resume_clear_thread_private_info (thread);
5852
5853 buf = rs->buf;
5854 if (execution_direction == EXEC_REVERSE)
5855 {
5856 /* We don't pass signals to the target in reverse exec mode. */
5857 if (info_verbose && siggnal != GDB_SIGNAL_0)
5858 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5859 siggnal);
5860
5861 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5862 error (_("Remote reverse-step not supported."));
5863 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5864 error (_("Remote reverse-continue not supported."));
5865
5866 strcpy (buf, step ? "bs" : "bc");
5867 }
5868 else if (siggnal != GDB_SIGNAL_0)
5869 {
5870 buf[0] = step ? 'S' : 'C';
5871 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5872 buf[2] = tohex (((int) siggnal) & 0xf);
5873 buf[3] = '\0';
5874 }
5875 else
5876 strcpy (buf, step ? "s" : "c");
5877
5878 putpkt (buf);
5879}
5880
506fb367
DJ
5881/* Resume the remote inferior by using a "vCont" packet. The thread
5882 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
5883 resumed thread should be single-stepped and/or signalled. If PTID
5884 equals minus_one_ptid, then all threads are resumed; the thread to
5885 be stepped and/or signalled is given in the global INFERIOR_PTID.
5886 This function returns non-zero iff it resumes the inferior.
44eaed12 5887
7b68ffbb
PA
5888 This function issues a strict subset of all possible vCont commands
5889 at the moment. */
44eaed12 5890
506fb367 5891static int
7b68ffbb 5892remote_resume_with_vcont (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
5893{
5894 struct remote_state *rs = get_remote_state ();
82f73884
PA
5895 char *p;
5896 char *endp;
44eaed12 5897
7b68ffbb
PA
5898 /* No reverse execution actions defined for vCont. */
5899 if (execution_direction == EXEC_REVERSE)
5900 return 0;
5901
4082afcc 5902 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 5903 remote_vcont_probe (rs);
44eaed12 5904
4082afcc 5905 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 5906 return 0;
44eaed12 5907
82f73884
PA
5908 p = rs->buf;
5909 endp = rs->buf + get_remote_packet_size ();
5910
506fb367
DJ
5911 /* If we could generate a wider range of packets, we'd have to worry
5912 about overflowing BUF. Should there be a generic
5913 "multi-part-packet" packet? */
5914
0d8f58ca
PA
5915 p += xsnprintf (p, endp - p, "vCont");
5916
79d7f229 5917 if (ptid_equal (ptid, magic_null_ptid))
c906108c 5918 {
79d7f229
PA
5919 /* MAGIC_NULL_PTID means that we don't have any active threads,
5920 so we don't have any TID numbers the inferior will
5921 understand. Make sure to only send forms that do not specify
5922 a TID. */
a9cbf802 5923 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 5924 }
0d8f58ca 5925 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 5926 {
0d8f58ca
PA
5927 /* Resume all threads (of all processes, or of a single
5928 process), with preference for INFERIOR_PTID. This assumes
5929 inferior_ptid belongs to the set of all threads we are about
5930 to resume. */
a493e3e2 5931 if (step || siggnal != GDB_SIGNAL_0)
82f73884 5932 {
0d8f58ca
PA
5933 /* Step inferior_ptid, with or without signal. */
5934 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 5935 }
0d8f58ca 5936
e5ef252a
PA
5937 /* Also pass down any pending signaled resumption for other
5938 threads not the current. */
5939 p = append_pending_thread_resumptions (p, endp, ptid);
5940
0d8f58ca 5941 /* And continue others without a signal. */
a493e3e2 5942 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
5943 }
5944 else
506fb367
DJ
5945 {
5946 /* Scheduler locking; resume only PTID. */
a9cbf802 5947 append_resumption (p, endp, ptid, step, siggnal);
506fb367 5948 }
c906108c 5949
82f73884
PA
5950 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5951 putpkt (rs->buf);
506fb367 5952
6efcd9a8 5953 if (target_is_non_stop_p ())
74531fed
PA
5954 {
5955 /* In non-stop, the stub replies to vCont with "OK". The stop
5956 reply will be reported asynchronously by means of a `%Stop'
5957 notification. */
5958 getpkt (&rs->buf, &rs->buf_size, 0);
5959 if (strcmp (rs->buf, "OK") != 0)
5960 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5961 }
5962
506fb367 5963 return 1;
c906108c 5964}
43ff13b4 5965
506fb367
DJ
5966/* Tell the remote machine to resume. */
5967
f6ac5f3d
PA
5968void
5969remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 5970{
d01949b6 5971 struct remote_state *rs = get_remote_state ();
43ff13b4 5972
85ad3aaf
PA
5973 /* When connected in non-stop mode, the core resumes threads
5974 individually. Resuming remote threads directly in target_resume
5975 would thus result in sending one packet per thread. Instead, to
5976 minimize roundtrip latency, here we just store the resume
5977 request; the actual remote resumption will be done in
5978 target_commit_resume / remote_commit_resume, where we'll be able
5979 to do vCont action coalescing. */
f6ac5f3d 5980 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
85ad3aaf 5981 {
7aabaf9d 5982 remote_thread_info *remote_thr;
85ad3aaf
PA
5983
5984 if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
7aabaf9d 5985 remote_thr = get_remote_thread_info (inferior_ptid);
85ad3aaf 5986 else
7aabaf9d
SM
5987 remote_thr = get_remote_thread_info (ptid);
5988
85ad3aaf
PA
5989 remote_thr->last_resume_step = step;
5990 remote_thr->last_resume_sig = siggnal;
5991 return;
5992 }
5993
722247f1
YQ
5994 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5995 (explained in remote-notif.c:handle_notification) so
5996 remote_notif_process is not called. We need find a place where
5997 it is safe to start a 'vNotif' sequence. It is good to do it
5998 before resuming inferior, because inferior was stopped and no RSP
5999 traffic at that moment. */
6efcd9a8 6000 if (!target_is_non_stop_p ())
5965e028 6001 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 6002
f6ac5f3d 6003 rs->last_resume_exec_dir = ::execution_direction;
3a00c802 6004
7b68ffbb
PA
6005 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6006 if (!remote_resume_with_vcont (ptid, step, siggnal))
f6ac5f3d 6007 remote_resume_with_hc (this, ptid, step, siggnal);
43ff13b4 6008
2acceee2 6009 /* We are about to start executing the inferior, let's register it
0df8b418
MS
6010 with the event loop. NOTE: this is the one place where all the
6011 execution commands end up. We could alternatively do this in each
23860348 6012 of the execution commands in infcmd.c. */
2acceee2
JM
6013 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6014 into infcmd.c in order to allow inferior function calls to work
23860348 6015 NOT asynchronously. */
362646f5 6016 if (target_can_async_p ())
6a3753b3 6017 target_async (1);
e24a49d8
PA
6018
6019 /* We've just told the target to resume. The remote server will
6020 wait for the inferior to stop, and then send a stop reply. In
6021 the mean time, we can't start another command/query ourselves
74531fed
PA
6022 because the stub wouldn't be ready to process it. This applies
6023 only to the base all-stop protocol, however. In non-stop (which
6024 only supports vCont), the stub replies with an "OK", and is
6025 immediate able to process further serial input. */
6efcd9a8 6026 if (!target_is_non_stop_p ())
74531fed 6027 rs->waiting_for_stop_reply = 1;
43ff13b4 6028}
85ad3aaf
PA
6029
6030static void check_pending_events_prevent_wildcard_vcont
6031 (int *may_global_wildcard_vcont);
6032static int is_pending_fork_parent_thread (struct thread_info *thread);
6033
6034/* Private per-inferior info for target remote processes. */
6035
089354bb 6036struct remote_inferior : public private_inferior
85ad3aaf
PA
6037{
6038 /* Whether we can send a wildcard vCont for this process. */
089354bb 6039 bool may_wildcard_vcont = true;
85ad3aaf
PA
6040};
6041
089354bb
SM
6042/* Get the remote private inferior data associated to INF. */
6043
6044static remote_inferior *
6045get_remote_inferior (inferior *inf)
6046{
6047 if (inf->priv == NULL)
6048 inf->priv.reset (new remote_inferior);
6049
6050 return static_cast<remote_inferior *> (inf->priv.get ());
6051}
6052
85ad3aaf
PA
6053/* Structure used to track the construction of a vCont packet in the
6054 outgoing packet buffer. This is used to send multiple vCont
6055 packets if we have more actions than would fit a single packet. */
6056
6057struct vcont_builder
6058{
6059 /* Pointer to the first action. P points here if no action has been
6060 appended yet. */
6061 char *first_action;
6062
6063 /* Where the next action will be appended. */
6064 char *p;
6065
6066 /* The end of the buffer. Must never write past this. */
6067 char *endp;
6068};
6069
6070/* Prepare the outgoing buffer for a new vCont packet. */
6071
6072static void
6073vcont_builder_restart (struct vcont_builder *builder)
6074{
6075 struct remote_state *rs = get_remote_state ();
6076
6077 builder->p = rs->buf;
6078 builder->endp = rs->buf + get_remote_packet_size ();
6079 builder->p += xsnprintf (builder->p, builder->endp - builder->p, "vCont");
6080 builder->first_action = builder->p;
6081}
6082
6083/* If the vCont packet being built has any action, send it to the
6084 remote end. */
6085
6086static void
6087vcont_builder_flush (struct vcont_builder *builder)
6088{
6089 struct remote_state *rs;
6090
6091 if (builder->p == builder->first_action)
6092 return;
6093
6094 rs = get_remote_state ();
6095 putpkt (rs->buf);
6096 getpkt (&rs->buf, &rs->buf_size, 0);
6097 if (strcmp (rs->buf, "OK") != 0)
6098 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6099}
6100
6101/* The largest action is range-stepping, with its two addresses. This
6102 is more than sufficient. If a new, bigger action is created, it'll
6103 quickly trigger a failed assertion in append_resumption (and we'll
6104 just bump this). */
6105#define MAX_ACTION_SIZE 200
6106
6107/* Append a new vCont action in the outgoing packet being built. If
6108 the action doesn't fit the packet along with previous actions, push
6109 what we've got so far to the remote end and start over a new vCont
6110 packet (with the new action). */
6111
6112static void
6113vcont_builder_push_action (struct vcont_builder *builder,
6114 ptid_t ptid, int step, enum gdb_signal siggnal)
6115{
6116 char buf[MAX_ACTION_SIZE + 1];
6117 char *endp;
6118 size_t rsize;
6119
6120 endp = append_resumption (buf, buf + sizeof (buf),
6121 ptid, step, siggnal);
6122
6123 /* Check whether this new action would fit in the vCont packet along
6124 with previous actions. If not, send what we've got so far and
6125 start a new vCont packet. */
6126 rsize = endp - buf;
6127 if (rsize > builder->endp - builder->p)
6128 {
6129 vcont_builder_flush (builder);
6130 vcont_builder_restart (builder);
6131
6132 /* Should now fit. */
6133 gdb_assert (rsize <= builder->endp - builder->p);
6134 }
6135
6136 memcpy (builder->p, buf, rsize);
6137 builder->p += rsize;
6138 *builder->p = '\0';
6139}
6140
6141/* to_commit_resume implementation. */
6142
f6ac5f3d
PA
6143void
6144remote_target::commit_resume ()
85ad3aaf 6145{
85ad3aaf
PA
6146 struct inferior *inf;
6147 struct thread_info *tp;
6148 int any_process_wildcard;
6149 int may_global_wildcard_vcont;
6150 struct vcont_builder vcont_builder;
6151
6152 /* If connected in all-stop mode, we'd send the remote resume
6153 request directly from remote_resume. Likewise if
6154 reverse-debugging, as there are no defined vCont actions for
6155 reverse execution. */
f6ac5f3d 6156 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
85ad3aaf
PA
6157 return;
6158
6159 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6160 instead of resuming all threads of each process individually.
6161 However, if any thread of a process must remain halted, we can't
6162 send wildcard resumes and must send one action per thread.
6163
6164 Care must be taken to not resume threads/processes the server
6165 side already told us are stopped, but the core doesn't know about
6166 yet, because the events are still in the vStopped notification
6167 queue. For example:
6168
6169 #1 => vCont s:p1.1;c
6170 #2 <= OK
6171 #3 <= %Stopped T05 p1.1
6172 #4 => vStopped
6173 #5 <= T05 p1.2
6174 #6 => vStopped
6175 #7 <= OK
6176 #8 (infrun handles the stop for p1.1 and continues stepping)
6177 #9 => vCont s:p1.1;c
6178
6179 The last vCont above would resume thread p1.2 by mistake, because
6180 the server has no idea that the event for p1.2 had not been
6181 handled yet.
6182
6183 The server side must similarly ignore resume actions for the
6184 thread that has a pending %Stopped notification (and any other
6185 threads with events pending), until GDB acks the notification
6186 with vStopped. Otherwise, e.g., the following case is
6187 mishandled:
6188
6189 #1 => g (or any other packet)
6190 #2 <= [registers]
6191 #3 <= %Stopped T05 p1.2
6192 #4 => vCont s:p1.1;c
6193 #5 <= OK
6194
6195 Above, the server must not resume thread p1.2. GDB can't know
6196 that p1.2 stopped until it acks the %Stopped notification, and
6197 since from GDB's perspective all threads should be running, it
6198 sends a "c" action.
6199
6200 Finally, special care must also be given to handling fork/vfork
6201 events. A (v)fork event actually tells us that two processes
6202 stopped -- the parent and the child. Until we follow the fork,
6203 we must not resume the child. Therefore, if we have a pending
6204 fork follow, we must not send a global wildcard resume action
6205 (vCont;c). We can still send process-wide wildcards though. */
6206
6207 /* Start by assuming a global wildcard (vCont;c) is possible. */
6208 may_global_wildcard_vcont = 1;
6209
6210 /* And assume every process is individually wildcard-able too. */
6211 ALL_NON_EXITED_INFERIORS (inf)
6212 {
089354bb
SM
6213 remote_inferior *priv = get_remote_inferior (inf);
6214
6215 priv->may_wildcard_vcont = true;
85ad3aaf
PA
6216 }
6217
6218 /* Check for any pending events (not reported or processed yet) and
6219 disable process and global wildcard resumes appropriately. */
6220 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6221
6222 ALL_NON_EXITED_THREADS (tp)
6223 {
6224 /* If a thread of a process is not meant to be resumed, then we
6225 can't wildcard that process. */
6226 if (!tp->executing)
6227 {
089354bb 6228 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
85ad3aaf
PA
6229
6230 /* And if we can't wildcard a process, we can't wildcard
6231 everything either. */
6232 may_global_wildcard_vcont = 0;
6233 continue;
6234 }
6235
6236 /* If a thread is the parent of an unfollowed fork, then we
6237 can't do a global wildcard, as that would resume the fork
6238 child. */
6239 if (is_pending_fork_parent_thread (tp))
6240 may_global_wildcard_vcont = 0;
6241 }
6242
6243 /* Now let's build the vCont packet(s). Actions must be appended
6244 from narrower to wider scopes (thread -> process -> global). If
6245 we end up with too many actions for a single packet vcont_builder
6246 flushes the current vCont packet to the remote side and starts a
6247 new one. */
6248 vcont_builder_restart (&vcont_builder);
6249
6250 /* Threads first. */
6251 ALL_NON_EXITED_THREADS (tp)
6252 {
7aabaf9d 6253 remote_thread_info *remote_thr = get_remote_thread_info (tp);
85ad3aaf
PA
6254
6255 if (!tp->executing || remote_thr->vcont_resumed)
6256 continue;
6257
6258 gdb_assert (!thread_is_in_step_over_chain (tp));
6259
6260 if (!remote_thr->last_resume_step
6261 && remote_thr->last_resume_sig == GDB_SIGNAL_0
089354bb 6262 && get_remote_inferior (tp->inf)->may_wildcard_vcont)
85ad3aaf
PA
6263 {
6264 /* We'll send a wildcard resume instead. */
6265 remote_thr->vcont_resumed = 1;
6266 continue;
6267 }
6268
6269 vcont_builder_push_action (&vcont_builder, tp->ptid,
6270 remote_thr->last_resume_step,
6271 remote_thr->last_resume_sig);
6272 remote_thr->vcont_resumed = 1;
6273 }
6274
6275 /* Now check whether we can send any process-wide wildcard. This is
6276 to avoid sending a global wildcard in the case nothing is
6277 supposed to be resumed. */
6278 any_process_wildcard = 0;
6279
6280 ALL_NON_EXITED_INFERIORS (inf)
6281 {
089354bb 6282 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf
PA
6283 {
6284 any_process_wildcard = 1;
6285 break;
6286 }
6287 }
6288
6289 if (any_process_wildcard)
6290 {
6291 /* If all processes are wildcard-able, then send a single "c"
6292 action, otherwise, send an "all (-1) threads of process"
6293 continue action for each running process, if any. */
6294 if (may_global_wildcard_vcont)
6295 {
6296 vcont_builder_push_action (&vcont_builder, minus_one_ptid,
6297 0, GDB_SIGNAL_0);
6298 }
6299 else
6300 {
6301 ALL_NON_EXITED_INFERIORS (inf)
6302 {
089354bb 6303 if (get_remote_inferior (inf)->may_wildcard_vcont)
85ad3aaf
PA
6304 {
6305 vcont_builder_push_action (&vcont_builder,
6306 pid_to_ptid (inf->pid),
6307 0, GDB_SIGNAL_0);
6308 }
6309 }
6310 }
6311 }
6312
6313 vcont_builder_flush (&vcont_builder);
6314}
6315
c906108c 6316\f
43ff13b4 6317
74531fed
PA
6318/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6319 thread, all threads of a remote process, or all threads of all
6320 processes. */
6321
6322static void
6323remote_stop_ns (ptid_t ptid)
6324{
6325 struct remote_state *rs = get_remote_state ();
6326 char *p = rs->buf;
6327 char *endp = rs->buf + get_remote_packet_size ();
74531fed 6328
4082afcc 6329 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
6330 remote_vcont_probe (rs);
6331
d458bd84 6332 if (!rs->supports_vCont.t)
74531fed
PA
6333 error (_("Remote server does not support stopping threads"));
6334
f91d3df5
PA
6335 if (ptid_equal (ptid, minus_one_ptid)
6336 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
6337 p += xsnprintf (p, endp - p, "vCont;t");
6338 else
6339 {
6340 ptid_t nptid;
6341
74531fed
PA
6342 p += xsnprintf (p, endp - p, "vCont;t:");
6343
6344 if (ptid_is_pid (ptid))
6345 /* All (-1) threads of process. */
ba348170 6346 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
6347 else
6348 {
6349 /* Small optimization: if we already have a stop reply for
6350 this thread, no use in telling the stub we want this
6351 stopped. */
6352 if (peek_stop_reply (ptid))
6353 return;
6354
6355 nptid = ptid;
6356 }
6357
a9cbf802 6358 write_ptid (p, endp, nptid);
74531fed
PA
6359 }
6360
6361 /* In non-stop, we get an immediate OK reply. The stop reply will
6362 come in asynchronously by notification. */
6363 putpkt (rs->buf);
6364 getpkt (&rs->buf, &rs->buf_size, 0);
6365 if (strcmp (rs->buf, "OK") != 0)
6366 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6367}
6368
bfedc46a
PA
6369/* All-stop version of target_interrupt. Sends a break or a ^C to
6370 interrupt the remote target. It is undefined which thread of which
6371 process reports the interrupt. */
74531fed
PA
6372
6373static void
de979965 6374remote_interrupt_as (void)
74531fed
PA
6375{
6376 struct remote_state *rs = get_remote_state ();
6377
3a29589a
DJ
6378 rs->ctrlc_pending_p = 1;
6379
74531fed
PA
6380 /* If the inferior is stopped already, but the core didn't know
6381 about it yet, just ignore the request. The cached wait status
6382 will be collected in remote_wait. */
6383 if (rs->cached_wait_status)
6384 return;
6385
9a7071a8
JB
6386 /* Send interrupt_sequence to remote target. */
6387 send_interrupt_sequence ();
74531fed
PA
6388}
6389
de979965
PA
6390/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6391 the remote target. It is undefined which thread of which process
e42de8c7
PA
6392 reports the interrupt. Throws an error if the packet is not
6393 supported by the server. */
de979965 6394
e42de8c7 6395static void
de979965
PA
6396remote_interrupt_ns (void)
6397{
6398 struct remote_state *rs = get_remote_state ();
6399 char *p = rs->buf;
6400 char *endp = rs->buf + get_remote_packet_size ();
6401
6402 xsnprintf (p, endp - p, "vCtrlC");
6403
6404 /* In non-stop, we get an immediate OK reply. The stop reply will
6405 come in asynchronously by notification. */
6406 putpkt (rs->buf);
6407 getpkt (&rs->buf, &rs->buf_size, 0);
6408
6409 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6410 {
6411 case PACKET_OK:
6412 break;
6413 case PACKET_UNKNOWN:
e42de8c7 6414 error (_("No support for interrupting the remote target."));
de979965
PA
6415 case PACKET_ERROR:
6416 error (_("Interrupting target failed: %s"), rs->buf);
6417 }
de979965
PA
6418}
6419
bfedc46a 6420/* Implement the to_stop function for the remote targets. */
74531fed 6421
f6ac5f3d
PA
6422void
6423remote_target::stop (ptid_t ptid)
c906108c 6424{
7a292a7a 6425 if (remote_debug)
0f71a2f6 6426 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 6427
6efcd9a8 6428 if (target_is_non_stop_p ())
74531fed 6429 remote_stop_ns (ptid);
c906108c 6430 else
bfedc46a
PA
6431 {
6432 /* We don't currently have a way to transparently pause the
6433 remote target in all-stop mode. Interrupt it instead. */
de979965 6434 remote_interrupt_as ();
bfedc46a
PA
6435 }
6436}
6437
6438/* Implement the to_interrupt function for the remote targets. */
6439
f6ac5f3d
PA
6440void
6441remote_target::interrupt ()
bfedc46a
PA
6442{
6443 if (remote_debug)
6444 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6445
e42de8c7
PA
6446 if (target_is_non_stop_p ())
6447 remote_interrupt_ns ();
bfedc46a 6448 else
e42de8c7 6449 remote_interrupt_as ();
c906108c
SS
6450}
6451
93692b58
PA
6452/* Implement the to_pass_ctrlc function for the remote targets. */
6453
f6ac5f3d
PA
6454void
6455remote_target::pass_ctrlc ()
93692b58
PA
6456{
6457 struct remote_state *rs = get_remote_state ();
6458
6459 if (remote_debug)
6460 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6461
6462 /* If we're starting up, we're not fully synced yet. Quit
6463 immediately. */
6464 if (rs->starting_up)
6465 quit ();
6466 /* If ^C has already been sent once, offer to disconnect. */
6467 else if (rs->ctrlc_pending_p)
6468 interrupt_query ();
6469 else
e671cd59 6470 target_interrupt ();
93692b58
PA
6471}
6472
c906108c
SS
6473/* Ask the user what to do when an interrupt is received. */
6474
6475static void
fba45db2 6476interrupt_query (void)
c906108c 6477{
abc56d60 6478 struct remote_state *rs = get_remote_state ();
c906108c 6479
abc56d60 6480 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 6481 {
abc56d60
PA
6482 if (query (_("The target is not responding to interrupt requests.\n"
6483 "Stop debugging it? ")))
74531fed 6484 {
78a095c3 6485 remote_unpush_target ();
abc56d60 6486 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
6487 }
6488 }
abc56d60
PA
6489 else
6490 {
6491 if (query (_("Interrupted while waiting for the program.\n"
6492 "Give up waiting? ")))
6493 quit ();
6494 }
c906108c
SS
6495}
6496
6426a772
JM
6497/* Enable/disable target terminal ownership. Most targets can use
6498 terminal groups to control terminal ownership. Remote targets are
6499 different in that explicit transfer of ownership to/from GDB/target
23860348 6500 is required. */
6426a772 6501
f6ac5f3d
PA
6502void
6503remote_target::terminal_inferior ()
6426a772 6504{
6426a772
JM
6505 /* NOTE: At this point we could also register our selves as the
6506 recipient of all input. Any characters typed could then be
23860348 6507 passed on down to the target. */
6426a772
JM
6508}
6509
f6ac5f3d
PA
6510void
6511remote_target::terminal_ours ()
6426a772 6512{
6426a772
JM
6513}
6514
176a6961 6515static void
917317f4 6516remote_console_output (char *msg)
c906108c
SS
6517{
6518 char *p;
6519
c5aa993b 6520 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
6521 {
6522 char tb[2];
6523 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 6524
c906108c
SS
6525 tb[0] = c;
6526 tb[1] = 0;
43ff13b4 6527 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 6528 }
00db5b94
PA
6529 gdb_flush (gdb_stdtarg);
6530}
74531fed 6531
74531fed
PA
6532DEF_VEC_O(cached_reg_t);
6533
722247f1 6534typedef struct stop_reply
74531fed 6535{
722247f1 6536 struct notif_event base;
74531fed 6537
722247f1 6538 /* The identifier of the thread about this event */
74531fed
PA
6539 ptid_t ptid;
6540
340e3c99 6541 /* The remote state this event is associated with. When the remote
bcc75809
YQ
6542 connection, represented by a remote_state object, is closed,
6543 all the associated stop_reply events should be released. */
6544 struct remote_state *rs;
6545
74531fed
PA
6546 struct target_waitstatus ws;
6547
5cd63fda
PA
6548 /* The architecture associated with the expedited registers. */
6549 gdbarch *arch;
6550
15148d6a
PA
6551 /* Expedited registers. This makes remote debugging a bit more
6552 efficient for those targets that provide critical registers as
6553 part of their normal status mechanism (as another roundtrip to
6554 fetch them is avoided). */
74531fed
PA
6555 VEC(cached_reg_t) *regcache;
6556
f7e6eed5
PA
6557 enum target_stop_reason stop_reason;
6558
74531fed
PA
6559 CORE_ADDR watch_data_address;
6560
dc146f7c 6561 int core;
722247f1 6562} *stop_reply_p;
a744cf53 6563
722247f1
YQ
6564DECLARE_QUEUE_P (stop_reply_p);
6565DEFINE_QUEUE_P (stop_reply_p);
6566/* The list of already fetched and acknowledged stop events. This
6567 queue is used for notification Stop, and other notifications
6568 don't need queue for their events, because the notification events
6569 of Stop can't be consumed immediately, so that events should be
6570 queued first, and be consumed by remote_wait_{ns,as} one per
6571 time. Other notifications can consume their events immediately,
6572 so queue is not needed for them. */
6573static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
6574
6575static void
6576stop_reply_xfree (struct stop_reply *r)
6577{
f48ff2a7 6578 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
6579}
6580
221e1a37
PA
6581/* Return the length of the stop reply queue. */
6582
6583static int
6584stop_reply_queue_length (void)
6585{
6586 return QUEUE_length (stop_reply_p, stop_reply_queue);
6587}
6588
722247f1
YQ
6589static void
6590remote_notif_stop_parse (struct notif_client *self, char *buf,
6591 struct notif_event *event)
6592{
6593 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6594}
6595
6596static void
6597remote_notif_stop_ack (struct notif_client *self, char *buf,
6598 struct notif_event *event)
6599{
6600 struct stop_reply *stop_reply = (struct stop_reply *) event;
6601
6602 /* acknowledge */
f5c4fcd9 6603 putpkt (self->ack_command);
722247f1
YQ
6604
6605 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6606 /* We got an unknown stop reply. */
6607 error (_("Unknown stop reply"));
6608
6609 push_stop_reply (stop_reply);
6610}
6611
6612static int
6613remote_notif_stop_can_get_pending_events (struct notif_client *self)
6614{
6615 /* We can't get pending events in remote_notif_process for
6616 notification stop, and we have to do this in remote_wait_ns
6617 instead. If we fetch all queued events from stub, remote stub
6618 may exit and we have no chance to process them back in
6619 remote_wait_ns. */
6620 mark_async_event_handler (remote_async_inferior_event_token);
6621 return 0;
6622}
6623
6624static void
6625stop_reply_dtr (struct notif_event *event)
6626{
6627 struct stop_reply *r = (struct stop_reply *) event;
d1dff226
AH
6628 cached_reg_t *reg;
6629 int ix;
6630
6631 for (ix = 0;
6632 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6633 ix++)
6634 xfree (reg->data);
722247f1
YQ
6635
6636 VEC_free (cached_reg_t, r->regcache);
6637}
6638
6639static struct notif_event *
6640remote_notif_stop_alloc_reply (void)
6641{
8d749320
SM
6642 /* We cast to a pointer to the "base class". */
6643 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
6644
6645 r->dtr = stop_reply_dtr;
6646
6647 return r;
6648}
6649
6650/* A client of notification Stop. */
6651
6652struct notif_client notif_client_stop =
6653{
6654 "Stop",
6655 "vStopped",
6656 remote_notif_stop_parse,
6657 remote_notif_stop_ack,
6658 remote_notif_stop_can_get_pending_events,
6659 remote_notif_stop_alloc_reply,
f48ff2a7 6660 REMOTE_NOTIF_STOP,
722247f1
YQ
6661};
6662
6663/* A parameter to pass data in and out. */
6664
6665struct queue_iter_param
6666{
6667 void *input;
6668 struct stop_reply *output;
6669};
6670
85ad3aaf 6671/* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
cbb8991c
DB
6672 the pid of the process that owns the threads we want to check, or
6673 -1 if we want to check all threads. */
6674
6675static int
6676is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6677 ptid_t thread_ptid)
6678{
6679 if (ws->kind == TARGET_WAITKIND_FORKED
6680 || ws->kind == TARGET_WAITKIND_VFORKED)
6681 {
6682 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6683 return 1;
6684 }
6685
6686 return 0;
6687}
6688
85ad3aaf
PA
6689/* Return the thread's pending status used to determine whether the
6690 thread is a fork parent stopped at a fork event. */
6691
6692static struct target_waitstatus *
6693thread_pending_fork_status (struct thread_info *thread)
6694{
6695 if (thread->suspend.waitstatus_pending_p)
6696 return &thread->suspend.waitstatus;
6697 else
6698 return &thread->pending_follow;
6699}
6700
6701/* Determine if THREAD is a pending fork parent thread. */
6702
6703static int
6704is_pending_fork_parent_thread (struct thread_info *thread)
6705{
6706 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6707 int pid = -1;
6708
6709 return is_pending_fork_parent (ws, pid, thread->ptid);
6710}
6711
cbb8991c
DB
6712/* Check whether EVENT is a fork event, and if it is, remove the
6713 fork child from the context list passed in DATA. */
6714
6715static int
6716remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6717 QUEUE_ITER (stop_reply_p) *iter,
6718 stop_reply_p event,
6719 void *data)
6720{
19ba03f4
SM
6721 struct queue_iter_param *param = (struct queue_iter_param *) data;
6722 struct threads_listing_context *context
6723 = (struct threads_listing_context *) param->input;
cbb8991c
DB
6724
6725 if (event->ws.kind == TARGET_WAITKIND_FORKED
65706a29
PA
6726 || event->ws.kind == TARGET_WAITKIND_VFORKED
6727 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
21fe1c75 6728 context->remove_thread (event->ws.value.related_pid);
cbb8991c
DB
6729
6730 return 1;
6731}
6732
6733/* If CONTEXT contains any fork child threads that have not been
6734 reported yet, remove them from the CONTEXT list. If such a
6735 thread exists it is because we are stopped at a fork catchpoint
6736 and have not yet called follow_fork, which will set up the
6737 host-side data structures for the new process. */
6738
6739static void
6740remove_new_fork_children (struct threads_listing_context *context)
6741{
6742 struct thread_info * thread;
6743 int pid = -1;
6744 struct notif_client *notif = &notif_client_stop;
6745 struct queue_iter_param param;
6746
6747 /* For any threads stopped at a fork event, remove the corresponding
6748 fork child threads from the CONTEXT list. */
6749 ALL_NON_EXITED_THREADS (thread)
6750 {
85ad3aaf 6751 struct target_waitstatus *ws = thread_pending_fork_status (thread);
cbb8991c
DB
6752
6753 if (is_pending_fork_parent (ws, pid, thread->ptid))
21fe1c75 6754 context->remove_thread (ws->value.related_pid);
cbb8991c
DB
6755 }
6756
6757 /* Check for any pending fork events (not reported or processed yet)
6758 in process PID and remove those fork child threads from the
6759 CONTEXT list as well. */
6760 remote_notif_get_pending_events (notif);
6761 param.input = context;
6762 param.output = NULL;
6763 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6764 remove_child_of_pending_fork, &param);
6765}
6766
85ad3aaf
PA
6767/* Check whether EVENT would prevent a global or process wildcard
6768 vCont action. */
6769
6770static int
6771check_pending_event_prevents_wildcard_vcont_callback
6772 (QUEUE (stop_reply_p) *q,
6773 QUEUE_ITER (stop_reply_p) *iter,
6774 stop_reply_p event,
6775 void *data)
6776{
6777 struct inferior *inf;
6778 int *may_global_wildcard_vcont = (int *) data;
6779
6780 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
6781 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
6782 return 1;
6783
6784 if (event->ws.kind == TARGET_WAITKIND_FORKED
6785 || event->ws.kind == TARGET_WAITKIND_VFORKED)
6786 *may_global_wildcard_vcont = 0;
6787
6788 inf = find_inferior_ptid (event->ptid);
6789
6790 /* This may be the first time we heard about this process.
6791 Regardless, we must not do a global wildcard resume, otherwise
6792 we'd resume this process too. */
6793 *may_global_wildcard_vcont = 0;
6794 if (inf != NULL)
089354bb 6795 get_remote_inferior (inf)->may_wildcard_vcont = false;
85ad3aaf
PA
6796
6797 return 1;
6798}
6799
6800/* Check whether any event pending in the vStopped queue would prevent
6801 a global or process wildcard vCont action. Clear
6802 *may_global_wildcard if we can't do a global wildcard (vCont;c),
6803 and clear the event inferior's may_wildcard_vcont flag if we can't
6804 do a process-wide wildcard resume (vCont;c:pPID.-1). */
6805
6806static void
6807check_pending_events_prevent_wildcard_vcont (int *may_global_wildcard)
6808{
6809 struct notif_client *notif = &notif_client_stop;
6810
6811 remote_notif_get_pending_events (notif);
6812 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6813 check_pending_event_prevents_wildcard_vcont_callback,
6814 may_global_wildcard);
6815}
6816
f48ff2a7
YQ
6817/* Remove stop replies in the queue if its pid is equal to the given
6818 inferior's pid. */
722247f1
YQ
6819
6820static int
f48ff2a7
YQ
6821remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6822 QUEUE_ITER (stop_reply_p) *iter,
6823 stop_reply_p event,
6824 void *data)
722247f1 6825{
19ba03f4
SM
6826 struct queue_iter_param *param = (struct queue_iter_param *) data;
6827 struct inferior *inf = (struct inferior *) param->input;
722247f1 6828
f48ff2a7 6829 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
6830 {
6831 stop_reply_xfree (event);
6832 QUEUE_remove_elem (stop_reply_p, q, iter);
6833 }
6834
6835 return 1;
6836}
6837
f48ff2a7 6838/* Discard all pending stop replies of inferior INF. */
c906108c 6839
74531fed 6840static void
5f4cf0bb 6841discard_pending_stop_replies (struct inferior *inf)
c906108c 6842{
722247f1 6843 struct queue_iter_param param;
f48ff2a7
YQ
6844 struct stop_reply *reply;
6845 struct remote_state *rs = get_remote_state ();
6846 struct remote_notif_state *rns = rs->notif_state;
6847
6848 /* This function can be notified when an inferior exists. When the
6849 target is not remote, the notification state is NULL. */
6850 if (rs->remote_desc == NULL)
6851 return;
6852
6853 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 6854
74531fed 6855 /* Discard the in-flight notification. */
f48ff2a7 6856 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 6857 {
722247f1 6858 stop_reply_xfree (reply);
f48ff2a7 6859 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 6860 }
c906108c 6861
722247f1
YQ
6862 param.input = inf;
6863 param.output = NULL;
74531fed
PA
6864 /* Discard the stop replies we have already pulled with
6865 vStopped. */
722247f1 6866 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
6867 remove_stop_reply_for_inferior, &param);
6868}
6869
bcc75809
YQ
6870/* If its remote state is equal to the given remote state,
6871 remove EVENT from the stop reply queue. */
6872
6873static int
6874remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6875 QUEUE_ITER (stop_reply_p) *iter,
6876 stop_reply_p event,
6877 void *data)
6878{
19ba03f4
SM
6879 struct queue_iter_param *param = (struct queue_iter_param *) data;
6880 struct remote_state *rs = (struct remote_state *) param->input;
bcc75809
YQ
6881
6882 if (event->rs == rs)
6883 {
6884 stop_reply_xfree (event);
6885 QUEUE_remove_elem (stop_reply_p, q, iter);
6886 }
6887
6888 return 1;
6889}
6890
6891/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
6892
6893static void
bcc75809 6894discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
6895{
6896 struct queue_iter_param param;
6897
bcc75809 6898 param.input = rs;
f48ff2a7
YQ
6899 param.output = NULL;
6900 /* Discard the stop replies we have already pulled with
6901 vStopped. */
6902 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 6903 remove_stop_reply_of_remote_state, &param);
722247f1 6904}
74531fed 6905
722247f1
YQ
6906/* A parameter to pass data in and out. */
6907
6908static int
6909remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6910 QUEUE_ITER (stop_reply_p) *iter,
6911 stop_reply_p event,
6912 void *data)
6913{
19ba03f4
SM
6914 struct queue_iter_param *param = (struct queue_iter_param *) data;
6915 ptid_t *ptid = (ptid_t *) param->input;
722247f1
YQ
6916
6917 if (ptid_match (event->ptid, *ptid))
6918 {
6919 param->output = event;
6920 QUEUE_remove_elem (stop_reply_p, q, iter);
6921 return 0;
c8e38a49 6922 }
722247f1
YQ
6923
6924 return 1;
74531fed 6925}
43ff13b4 6926
722247f1
YQ
6927/* Remove the first reply in 'stop_reply_queue' which matches
6928 PTID. */
2e9f7625 6929
722247f1
YQ
6930static struct stop_reply *
6931remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 6932{
722247f1
YQ
6933 struct queue_iter_param param;
6934
6935 param.input = &ptid;
6936 param.output = NULL;
6937
6938 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6939 remote_notif_remove_once_on_match, &param);
6940 if (notif_debug)
6941 fprintf_unfiltered (gdb_stdlog,
6942 "notif: discard queued event: 'Stop' in %s\n",
6943 target_pid_to_str (ptid));
a744cf53 6944
722247f1 6945 return param.output;
74531fed 6946}
75c99385 6947
74531fed
PA
6948/* Look for a queued stop reply belonging to PTID. If one is found,
6949 remove it from the queue, and return it. Returns NULL if none is
6950 found. If there are still queued events left to process, tell the
6951 event loop to get back to target_wait soon. */
e24a49d8 6952
74531fed
PA
6953static struct stop_reply *
6954queued_stop_reply (ptid_t ptid)
6955{
722247f1 6956 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 6957
722247f1 6958 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
6959 /* There's still at least an event left. */
6960 mark_async_event_handler (remote_async_inferior_event_token);
6961
722247f1 6962 return r;
74531fed
PA
6963}
6964
6965/* Push a fully parsed stop reply in the stop reply queue. Since we
6966 know that we now have at least one queued event left to pass to the
6967 core side, tell the event loop to get back to target_wait soon. */
6968
6969static void
6970push_stop_reply (struct stop_reply *new_event)
6971{
722247f1 6972 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 6973
722247f1
YQ
6974 if (notif_debug)
6975 fprintf_unfiltered (gdb_stdlog,
6976 "notif: push 'Stop' %s to queue %d\n",
6977 target_pid_to_str (new_event->ptid),
6978 QUEUE_length (stop_reply_p,
6979 stop_reply_queue));
74531fed
PA
6980
6981 mark_async_event_handler (remote_async_inferior_event_token);
6982}
6983
722247f1
YQ
6984static int
6985stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6986 QUEUE_ITER (stop_reply_p) *iter,
6987 struct stop_reply *event,
6988 void *data)
6989{
19ba03f4 6990 ptid_t *ptid = (ptid_t *) data;
722247f1
YQ
6991
6992 return !(ptid_equal (*ptid, event->ptid)
6993 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6994}
6995
74531fed
PA
6996/* Returns true if we have a stop reply for PTID. */
6997
6998static int
6999peek_stop_reply (ptid_t ptid)
7000{
722247f1
YQ
7001 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
7002 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
7003}
7004
26d56a93
SL
7005/* Helper for remote_parse_stop_reply. Return nonzero if the substring
7006 starting with P and ending with PEND matches PREFIX. */
7007
7008static int
7009strprefix (const char *p, const char *pend, const char *prefix)
7010{
7011 for ( ; p < pend; p++, prefix++)
7012 if (*p != *prefix)
7013 return 0;
7014 return *prefix == '\0';
7015}
7016
74531fed
PA
7017/* Parse the stop reply in BUF. Either the function succeeds, and the
7018 result is stored in EVENT, or throws an error. */
7019
7020static void
7021remote_parse_stop_reply (char *buf, struct stop_reply *event)
7022{
5cd63fda 7023 remote_arch_state *rsa = NULL;
74531fed 7024 ULONGEST addr;
256642e8 7025 const char *p;
94585166 7026 int skipregs = 0;
74531fed
PA
7027
7028 event->ptid = null_ptid;
bcc75809 7029 event->rs = get_remote_state ();
74531fed
PA
7030 event->ws.kind = TARGET_WAITKIND_IGNORE;
7031 event->ws.value.integer = 0;
f7e6eed5 7032 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 7033 event->regcache = NULL;
dc146f7c 7034 event->core = -1;
74531fed
PA
7035
7036 switch (buf[0])
7037 {
7038 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
7039 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7040 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7041 ss = signal number
7042 n... = register number
7043 r... = register contents
7044 */
7045
7046 p = &buf[3]; /* after Txx */
7047 while (*p)
7048 {
256642e8 7049 const char *p1;
cea39f65 7050 int fieldsize;
43ff13b4 7051
1f10ba14
PA
7052 p1 = strchr (p, ':');
7053 if (p1 == NULL)
7054 error (_("Malformed packet(a) (missing colon): %s\n\
7055Packet: '%s'\n"),
7056 p, buf);
7057 if (p == p1)
7058 error (_("Malformed packet(a) (missing register number): %s\n\
7059Packet: '%s'\n"),
7060 p, buf);
3c3bea1c 7061
1f10ba14
PA
7062 /* Some "registers" are actually extended stop information.
7063 Note if you're adding a new entry here: GDB 7.9 and
7064 earlier assume that all register "numbers" that start
7065 with an hex digit are real register numbers. Make sure
7066 the server only sends such a packet if it knows the
7067 client understands it. */
c8e38a49 7068
26d56a93 7069 if (strprefix (p, p1, "thread"))
1f10ba14 7070 event->ptid = read_ptid (++p1, &p);
82075af2
JS
7071 else if (strprefix (p, p1, "syscall_entry"))
7072 {
7073 ULONGEST sysno;
7074
7075 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7076 p = unpack_varlen_hex (++p1, &sysno);
7077 event->ws.value.syscall_number = (int) sysno;
7078 }
7079 else if (strprefix (p, p1, "syscall_return"))
7080 {
7081 ULONGEST sysno;
7082
7083 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7084 p = unpack_varlen_hex (++p1, &sysno);
7085 event->ws.value.syscall_number = (int) sysno;
7086 }
26d56a93
SL
7087 else if (strprefix (p, p1, "watch")
7088 || strprefix (p, p1, "rwatch")
7089 || strprefix (p, p1, "awatch"))
cea39f65 7090 {
f7e6eed5 7091 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
7092 p = unpack_varlen_hex (++p1, &addr);
7093 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 7094 }
26d56a93 7095 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
7096 {
7097 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7098
7099 /* Make sure the stub doesn't forget to indicate support
7100 with qSupported. */
7101 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7102 error (_("Unexpected swbreak stop reason"));
7103
7104 /* The value part is documented as "must be empty",
7105 though we ignore it, in case we ever decide to make
7106 use of it in a backward compatible way. */
8424cc97 7107 p = strchrnul (p1 + 1, ';');
f7e6eed5 7108 }
26d56a93 7109 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
7110 {
7111 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7112
7113 /* Make sure the stub doesn't forget to indicate support
7114 with qSupported. */
7115 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7116 error (_("Unexpected hwbreak stop reason"));
7117
7118 /* See above. */
8424cc97 7119 p = strchrnul (p1 + 1, ';');
f7e6eed5 7120 }
26d56a93 7121 else if (strprefix (p, p1, "library"))
cea39f65 7122 {
1f10ba14 7123 event->ws.kind = TARGET_WAITKIND_LOADED;
8424cc97 7124 p = strchrnul (p1 + 1, ';');
1f10ba14 7125 }
26d56a93 7126 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
7127 {
7128 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7129 /* p1 will indicate "begin" or "end", but it makes
7130 no difference for now, so ignore it. */
8424cc97 7131 p = strchrnul (p1 + 1, ';');
1f10ba14 7132 }
26d56a93 7133 else if (strprefix (p, p1, "core"))
1f10ba14
PA
7134 {
7135 ULONGEST c;
a744cf53 7136
1f10ba14
PA
7137 p = unpack_varlen_hex (++p1, &c);
7138 event->core = c;
cea39f65 7139 }
26d56a93 7140 else if (strprefix (p, p1, "fork"))
de0d863e
DB
7141 {
7142 event->ws.value.related_pid = read_ptid (++p1, &p);
7143 event->ws.kind = TARGET_WAITKIND_FORKED;
7144 }
26d56a93 7145 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
7146 {
7147 event->ws.value.related_pid = read_ptid (++p1, &p);
7148 event->ws.kind = TARGET_WAITKIND_VFORKED;
7149 }
26d56a93 7150 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
7151 {
7152 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
8424cc97 7153 p = strchrnul (p1 + 1, ';');
c269dbdb 7154 }
6ab24463 7155 else if (strprefix (p, p1, "exec"))
94585166
DB
7156 {
7157 ULONGEST ignored;
7158 char pathname[PATH_MAX];
7159 int pathlen;
7160
7161 /* Determine the length of the execd pathname. */
7162 p = unpack_varlen_hex (++p1, &ignored);
7163 pathlen = (p - p1) / 2;
7164
7165 /* Save the pathname for event reporting and for
7166 the next run command. */
7167 hex2bin (p1, (gdb_byte *) pathname, pathlen);
7168 pathname[pathlen] = '\0';
7169
7170 /* This is freed during event handling. */
7171 event->ws.value.execd_pathname = xstrdup (pathname);
7172 event->ws.kind = TARGET_WAITKIND_EXECD;
7173
7174 /* Skip the registers included in this packet, since
7175 they may be for an architecture different from the
7176 one used by the original program. */
7177 skipregs = 1;
7178 }
65706a29
PA
7179 else if (strprefix (p, p1, "create"))
7180 {
7181 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
8424cc97 7182 p = strchrnul (p1 + 1, ';');
65706a29 7183 }
cea39f65
MS
7184 else
7185 {
1f10ba14 7186 ULONGEST pnum;
256642e8 7187 const char *p_temp;
1f10ba14 7188
94585166
DB
7189 if (skipregs)
7190 {
8424cc97 7191 p = strchrnul (p1 + 1, ';');
94585166
DB
7192 p++;
7193 continue;
7194 }
7195
1f10ba14
PA
7196 /* Maybe a real ``P'' register number. */
7197 p_temp = unpack_varlen_hex (p, &pnum);
7198 /* If the first invalid character is the colon, we got a
7199 register number. Otherwise, it's an unknown stop
7200 reason. */
7201 if (p_temp == p1)
7202 {
5cd63fda
PA
7203 /* If we haven't parsed the event's thread yet, find
7204 it now, in order to find the architecture of the
7205 reported expedited registers. */
7206 if (event->ptid == null_ptid)
7207 {
7208 const char *thr = strstr (p1 + 1, ";thread:");
7209 if (thr != NULL)
7210 event->ptid = read_ptid (thr + strlen (";thread:"),
7211 NULL);
7212 else
3cada740
PA
7213 {
7214 /* Either the current thread hasn't changed,
7215 or the inferior is not multi-threaded.
7216 The event must be for the thread we last
7217 set as (or learned as being) current. */
7218 event->ptid = event->rs->general_thread;
7219 }
5cd63fda
PA
7220 }
7221
7222 if (rsa == NULL)
7223 {
7224 inferior *inf = (event->ptid == null_ptid
7225 ? NULL
7226 : find_inferior_ptid (event->ptid));
7227 /* If this is the first time we learn anything
7228 about this process, skip the registers
7229 included in this packet, since we don't yet
7230 know which architecture to use to parse them.
7231 We'll determine the architecture later when
7232 we process the stop reply and retrieve the
7233 target description, via
7234 remote_notice_new_inferior ->
7235 post_create_inferior. */
7236 if (inf == NULL)
7237 {
7238 p = strchrnul (p1 + 1, ';');
7239 p++;
7240 continue;
7241 }
7242
7243 event->arch = inf->gdbarch;
7244 rsa = get_remote_arch_state (event->arch);
7245 }
7246
7247 packet_reg *reg
7248 = packet_reg_from_pnum (event->arch, rsa, pnum);
1f10ba14 7249 cached_reg_t cached_reg;
43ff13b4 7250
1f10ba14
PA
7251 if (reg == NULL)
7252 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 7253Packet: '%s'\n"),
1f10ba14 7254 hex_string (pnum), p, buf);
c8e38a49 7255
1f10ba14 7256 cached_reg.num = reg->regnum;
d1dff226 7257 cached_reg.data = (gdb_byte *)
5cd63fda 7258 xmalloc (register_size (event->arch, reg->regnum));
4100683b 7259
1f10ba14
PA
7260 p = p1 + 1;
7261 fieldsize = hex2bin (p, cached_reg.data,
5cd63fda 7262 register_size (event->arch, reg->regnum));
1f10ba14 7263 p += 2 * fieldsize;
5cd63fda 7264 if (fieldsize < register_size (event->arch, reg->regnum))
1f10ba14 7265 warning (_("Remote reply is too short: %s"), buf);
74531fed 7266
1f10ba14
PA
7267 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7268 }
7269 else
7270 {
7271 /* Not a number. Silently skip unknown optional
7272 info. */
8424cc97 7273 p = strchrnul (p1 + 1, ';');
1f10ba14 7274 }
cea39f65 7275 }
c8e38a49 7276
cea39f65
MS
7277 if (*p != ';')
7278 error (_("Remote register badly formatted: %s\nhere: %s"),
7279 buf, p);
7280 ++p;
7281 }
5b5596ff
PA
7282
7283 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7284 break;
7285
c8e38a49
PA
7286 /* fall through */
7287 case 'S': /* Old style status, just signal only. */
3a09da41
PA
7288 {
7289 int sig;
7290
7291 event->ws.kind = TARGET_WAITKIND_STOPPED;
7292 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7293 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7294 event->ws.value.sig = (enum gdb_signal) sig;
7295 else
7296 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7297 }
c8e38a49 7298 break;
65706a29
PA
7299 case 'w': /* Thread exited. */
7300 {
256642e8 7301 const char *p;
65706a29
PA
7302 ULONGEST value;
7303
7304 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7305 p = unpack_varlen_hex (&buf[1], &value);
7306 event->ws.value.integer = value;
7307 if (*p != ';')
7308 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 7309 event->ptid = read_ptid (++p, NULL);
65706a29
PA
7310 break;
7311 }
c8e38a49
PA
7312 case 'W': /* Target exited. */
7313 case 'X':
7314 {
256642e8 7315 const char *p;
c8e38a49
PA
7316 int pid;
7317 ULONGEST value;
82f73884 7318
c8e38a49
PA
7319 /* GDB used to accept only 2 hex chars here. Stubs should
7320 only send more if they detect GDB supports multi-process
7321 support. */
7322 p = unpack_varlen_hex (&buf[1], &value);
82f73884 7323
c8e38a49
PA
7324 if (buf[0] == 'W')
7325 {
7326 /* The remote process exited. */
74531fed
PA
7327 event->ws.kind = TARGET_WAITKIND_EXITED;
7328 event->ws.value.integer = value;
c8e38a49
PA
7329 }
7330 else
7331 {
7332 /* The remote process exited with a signal. */
74531fed 7333 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
7334 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7335 event->ws.value.sig = (enum gdb_signal) value;
7336 else
7337 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 7338 }
82f73884 7339
c8e38a49
PA
7340 /* If no process is specified, assume inferior_ptid. */
7341 pid = ptid_get_pid (inferior_ptid);
7342 if (*p == '\0')
7343 ;
7344 else if (*p == ';')
7345 {
7346 p++;
7347
0b24eb2d 7348 if (*p == '\0')
82f73884 7349 ;
61012eef 7350 else if (startswith (p, "process:"))
82f73884 7351 {
c8e38a49 7352 ULONGEST upid;
a744cf53 7353
c8e38a49
PA
7354 p += sizeof ("process:") - 1;
7355 unpack_varlen_hex (p, &upid);
7356 pid = upid;
82f73884
PA
7357 }
7358 else
7359 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 7360 }
c8e38a49
PA
7361 else
7362 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
7363 event->ptid = pid_to_ptid (pid);
7364 }
7365 break;
f2faf941
PA
7366 case 'N':
7367 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7368 event->ptid = minus_one_ptid;
7369 break;
74531fed
PA
7370 }
7371
6efcd9a8 7372 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
74531fed
PA
7373 error (_("No process or thread specified in stop reply: %s"), buf);
7374}
7375
722247f1
YQ
7376/* When the stub wants to tell GDB about a new notification reply, it
7377 sends a notification (%Stop, for example). Those can come it at
7378 any time, hence, we have to make sure that any pending
7379 putpkt/getpkt sequence we're making is finished, before querying
7380 the stub for more events with the corresponding ack command
7381 (vStopped, for example). E.g., if we started a vStopped sequence
7382 immediately upon receiving the notification, something like this
7383 could happen:
74531fed
PA
7384
7385 1.1) --> Hg 1
7386 1.2) <-- OK
7387 1.3) --> g
7388 1.4) <-- %Stop
7389 1.5) --> vStopped
7390 1.6) <-- (registers reply to step #1.3)
7391
7392 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7393 query.
7394
796cb314 7395 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
7396 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7397 doing whatever we were doing:
7398
7399 2.1) --> Hg 1
7400 2.2) <-- OK
7401 2.3) --> g
7402 2.4) <-- %Stop
7403 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7404 2.5) <-- (registers reply to step #2.3)
7405
7406 Eventualy after step #2.5, we return to the event loop, which
7407 notices there's an event on the
7408 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7409 associated callback --- the function below. At this point, we're
7410 always safe to start a vStopped sequence. :
7411
7412 2.6) --> vStopped
7413 2.7) <-- T05 thread:2
7414 2.8) --> vStopped
7415 2.9) --> OK
7416*/
7417
722247f1
YQ
7418void
7419remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
7420{
7421 struct remote_state *rs = get_remote_state ();
74531fed 7422
f48ff2a7 7423 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 7424 {
722247f1
YQ
7425 if (notif_debug)
7426 fprintf_unfiltered (gdb_stdlog,
7427 "notif: process: '%s' ack pending event\n",
7428 nc->name);
74531fed 7429
722247f1 7430 /* acknowledge */
f48ff2a7
YQ
7431 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7432 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
7433
7434 while (1)
7435 {
7436 getpkt (&rs->buf, &rs->buf_size, 0);
7437 if (strcmp (rs->buf, "OK") == 0)
7438 break;
7439 else
722247f1 7440 remote_notif_ack (nc, rs->buf);
74531fed
PA
7441 }
7442 }
722247f1
YQ
7443 else
7444 {
7445 if (notif_debug)
7446 fprintf_unfiltered (gdb_stdlog,
7447 "notif: process: '%s' no pending reply\n",
7448 nc->name);
7449 }
74531fed
PA
7450}
7451
74531fed
PA
7452/* Called when it is decided that STOP_REPLY holds the info of the
7453 event that is to be returned to the core. This function always
7454 destroys STOP_REPLY. */
7455
7456static ptid_t
7457process_stop_reply (struct stop_reply *stop_reply,
7458 struct target_waitstatus *status)
7459{
7460 ptid_t ptid;
7461
7462 *status = stop_reply->ws;
7463 ptid = stop_reply->ptid;
7464
7465 /* If no thread/process was reported by the stub, assume the current
7466 inferior. */
7467 if (ptid_equal (ptid, null_ptid))
7468 ptid = inferior_ptid;
7469
5f3563ea 7470 if (status->kind != TARGET_WAITKIND_EXITED
f2faf941
PA
7471 && status->kind != TARGET_WAITKIND_SIGNALLED
7472 && status->kind != TARGET_WAITKIND_NO_RESUMED)
74531fed 7473 {
5f3563ea
PA
7474 /* Expedited registers. */
7475 if (stop_reply->regcache)
7476 {
217f1f79 7477 struct regcache *regcache
5cd63fda 7478 = get_thread_arch_regcache (ptid, stop_reply->arch);
5f3563ea
PA
7479 cached_reg_t *reg;
7480 int ix;
7481
7482 for (ix = 0;
d1dff226 7483 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
5f3563ea 7484 ix++)
d1dff226 7485 {
217f1f79 7486 regcache_raw_supply (regcache, reg->num, reg->data);
d1dff226
AH
7487 xfree (reg->data);
7488 }
7489
5f3563ea
PA
7490 VEC_free (cached_reg_t, stop_reply->regcache);
7491 }
74531fed 7492
1941c569 7493 remote_notice_new_inferior (ptid, 0);
7aabaf9d 7494 remote_thread_info *remote_thr = get_remote_thread_info (ptid);
799a2abe
PA
7495 remote_thr->core = stop_reply->core;
7496 remote_thr->stop_reason = stop_reply->stop_reason;
7497 remote_thr->watch_data_address = stop_reply->watch_data_address;
85ad3aaf 7498 remote_thr->vcont_resumed = 0;
74531fed
PA
7499 }
7500
74531fed
PA
7501 stop_reply_xfree (stop_reply);
7502 return ptid;
7503}
7504
7505/* The non-stop mode version of target_wait. */
7506
7507static ptid_t
47608cb1 7508remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
7509{
7510 struct remote_state *rs = get_remote_state ();
74531fed
PA
7511 struct stop_reply *stop_reply;
7512 int ret;
fee9eda9 7513 int is_notif = 0;
74531fed
PA
7514
7515 /* If in non-stop mode, get out of getpkt even if a
7516 notification is received. */
7517
7518 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 7519 0 /* forever */, &is_notif);
74531fed
PA
7520 while (1)
7521 {
fee9eda9 7522 if (ret != -1 && !is_notif)
74531fed
PA
7523 switch (rs->buf[0])
7524 {
7525 case 'E': /* Error of some sort. */
7526 /* We're out of sync with the target now. Did it continue
7527 or not? We can't tell which thread it was in non-stop,
7528 so just ignore this. */
7529 warning (_("Remote failure reply: %s"), rs->buf);
7530 break;
7531 case 'O': /* Console output. */
7532 remote_console_output (rs->buf + 1);
7533 break;
7534 default:
7535 warning (_("Invalid remote reply: %s"), rs->buf);
7536 break;
7537 }
7538
7539 /* Acknowledge a pending stop reply that may have arrived in the
7540 mean time. */
f48ff2a7 7541 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 7542 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
7543
7544 /* If indeed we noticed a stop reply, we're done. */
7545 stop_reply = queued_stop_reply (ptid);
7546 if (stop_reply != NULL)
7547 return process_stop_reply (stop_reply, status);
7548
47608cb1 7549 /* Still no event. If we're just polling for an event, then
74531fed 7550 return to the event loop. */
47608cb1 7551 if (options & TARGET_WNOHANG)
74531fed
PA
7552 {
7553 status->kind = TARGET_WAITKIND_IGNORE;
7554 return minus_one_ptid;
7555 }
7556
47608cb1 7557 /* Otherwise do a blocking wait. */
74531fed 7558 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 7559 1 /* forever */, &is_notif);
74531fed
PA
7560 }
7561}
7562
7563/* Wait until the remote machine stops, then return, storing status in
7564 STATUS just as `wait' would. */
7565
7566static ptid_t
47608cb1 7567remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
7568{
7569 struct remote_state *rs = get_remote_state ();
74531fed 7570 ptid_t event_ptid = null_ptid;
cea39f65 7571 char *buf;
74531fed
PA
7572 struct stop_reply *stop_reply;
7573
47608cb1
PA
7574 again:
7575
74531fed
PA
7576 status->kind = TARGET_WAITKIND_IGNORE;
7577 status->value.integer = 0;
7578
7579 stop_reply = queued_stop_reply (ptid);
7580 if (stop_reply != NULL)
7581 return process_stop_reply (stop_reply, status);
7582
7583 if (rs->cached_wait_status)
7584 /* Use the cached wait status, but only once. */
7585 rs->cached_wait_status = 0;
7586 else
7587 {
7588 int ret;
722247f1 7589 int is_notif;
567420d1
PA
7590 int forever = ((options & TARGET_WNOHANG) == 0
7591 && wait_forever_enabled_p);
7592
7593 if (!rs->waiting_for_stop_reply)
7594 {
7595 status->kind = TARGET_WAITKIND_NO_RESUMED;
7596 return minus_one_ptid;
7597 }
74531fed 7598
74531fed
PA
7599 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7600 _never_ wait for ever -> test on target_is_async_p().
7601 However, before we do that we need to ensure that the caller
7602 knows how to take the target into/out of async mode. */
722247f1 7603 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 7604 forever, &is_notif);
722247f1
YQ
7605
7606 /* GDB gets a notification. Return to core as this event is
7607 not interesting. */
7608 if (ret != -1 && is_notif)
7609 return minus_one_ptid;
567420d1
PA
7610
7611 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7612 return minus_one_ptid;
74531fed
PA
7613 }
7614
7615 buf = rs->buf;
7616
3a29589a
DJ
7617 /* Assume that the target has acknowledged Ctrl-C unless we receive
7618 an 'F' or 'O' packet. */
7619 if (buf[0] != 'F' && buf[0] != 'O')
7620 rs->ctrlc_pending_p = 0;
7621
74531fed
PA
7622 switch (buf[0])
7623 {
7624 case 'E': /* Error of some sort. */
7625 /* We're out of sync with the target now. Did it continue or
7626 not? Not is more likely, so report a stop. */
29090fb6
LM
7627 rs->waiting_for_stop_reply = 0;
7628
74531fed
PA
7629 warning (_("Remote failure reply: %s"), buf);
7630 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 7631 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
7632 break;
7633 case 'F': /* File-I/O request. */
e42e5352
YQ
7634 /* GDB may access the inferior memory while handling the File-I/O
7635 request, but we don't want GDB accessing memory while waiting
7636 for a stop reply. See the comments in putpkt_binary. Set
7637 waiting_for_stop_reply to 0 temporarily. */
7638 rs->waiting_for_stop_reply = 0;
3a29589a
DJ
7639 remote_fileio_request (buf, rs->ctrlc_pending_p);
7640 rs->ctrlc_pending_p = 0;
e42e5352
YQ
7641 /* GDB handled the File-I/O request, and the target is running
7642 again. Keep waiting for events. */
7643 rs->waiting_for_stop_reply = 1;
74531fed 7644 break;
f2faf941 7645 case 'N': case 'T': case 'S': case 'X': case 'W':
74531fed 7646 {
29090fb6
LM
7647 struct stop_reply *stop_reply;
7648
7649 /* There is a stop reply to handle. */
7650 rs->waiting_for_stop_reply = 0;
7651
7652 stop_reply
722247f1
YQ
7653 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
7654 rs->buf);
74531fed 7655
74531fed 7656 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
7657 break;
7658 }
7659 case 'O': /* Console output. */
7660 remote_console_output (buf + 1);
c8e38a49
PA
7661 break;
7662 case '\0':
b73be471 7663 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
7664 {
7665 /* Zero length reply means that we tried 'S' or 'C' and the
7666 remote system doesn't support it. */
223ffa71 7667 target_terminal::ours_for_output ();
c8e38a49
PA
7668 printf_filtered
7669 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
7670 gdb_signal_to_name (rs->last_sent_signal));
7671 rs->last_sent_signal = GDB_SIGNAL_0;
223ffa71 7672 target_terminal::inferior ();
c8e38a49 7673
f5c4fcd9
TT
7674 strcpy (buf, rs->last_sent_step ? "s" : "c");
7675 putpkt (buf);
c8e38a49 7676 break;
43ff13b4 7677 }
86a73007 7678 /* fallthrough */
c8e38a49
PA
7679 default:
7680 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 7681 break;
43ff13b4 7682 }
c8e38a49 7683
f2faf941
PA
7684 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7685 return minus_one_ptid;
7686 else if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
7687 {
7688 /* Nothing interesting happened. If we're doing a non-blocking
7689 poll, we're done. Otherwise, go back to waiting. */
7690 if (options & TARGET_WNOHANG)
7691 return minus_one_ptid;
7692 else
7693 goto again;
7694 }
74531fed
PA
7695 else if (status->kind != TARGET_WAITKIND_EXITED
7696 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
7697 {
7698 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 7699 record_currthread (rs, event_ptid);
82f73884
PA
7700 else
7701 event_ptid = inferior_ptid;
43ff13b4 7702 }
74531fed
PA
7703 else
7704 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 7705 record_currthread (rs, minus_one_ptid);
79d7f229 7706
82f73884 7707 return event_ptid;
43ff13b4
JM
7708}
7709
74531fed
PA
7710/* Wait until the remote machine stops, then return, storing status in
7711 STATUS just as `wait' would. */
7712
f6ac5f3d
PA
7713ptid_t
7714remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
7715{
7716 ptid_t event_ptid;
7717
6efcd9a8 7718 if (target_is_non_stop_p ())
47608cb1 7719 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 7720 else
47608cb1 7721 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 7722
d9d41e78 7723 if (target_is_async_p ())
c8e38a49 7724 {
74531fed
PA
7725 /* If there are are events left in the queue tell the event loop
7726 to return here. */
722247f1 7727 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 7728 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 7729 }
c8e38a49
PA
7730
7731 return event_ptid;
7732}
7733
74ca34ce 7734/* Fetch a single register using a 'p' packet. */
c906108c 7735
b96ec7ac 7736static int
56be3814 7737fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac 7738{
ac7936df 7739 struct gdbarch *gdbarch = regcache->arch ();
b96ec7ac 7740 struct remote_state *rs = get_remote_state ();
2e9f7625 7741 char *buf, *p;
9890e433 7742 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
b96ec7ac
AC
7743 int i;
7744
4082afcc 7745 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
7746 return 0;
7747
7748 if (reg->pnum == -1)
7749 return 0;
7750
2e9f7625 7751 p = rs->buf;
fcad0fa4 7752 *p++ = 'p';
74ca34ce 7753 p += hexnumstr (p, reg->pnum);
fcad0fa4 7754 *p++ = '\0';
1f4437a4
MS
7755 putpkt (rs->buf);
7756 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 7757
2e9f7625
DJ
7758 buf = rs->buf;
7759
74ca34ce
DJ
7760 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7761 {
7762 case PACKET_OK:
7763 break;
7764 case PACKET_UNKNOWN:
7765 return 0;
7766 case PACKET_ERROR:
27a9c0bf 7767 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
ac7936df 7768 gdbarch_register_name (regcache->arch (),
27a9c0bf
MS
7769 reg->regnum),
7770 buf);
74ca34ce 7771 }
3f9a994c
JB
7772
7773 /* If this register is unfetchable, tell the regcache. */
7774 if (buf[0] == 'x')
8480adf2 7775 {
56be3814 7776 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 7777 return 1;
b96ec7ac 7778 }
b96ec7ac 7779
3f9a994c
JB
7780 /* Otherwise, parse and supply the value. */
7781 p = buf;
7782 i = 0;
7783 while (p[0] != 0)
7784 {
7785 if (p[1] == 0)
74ca34ce 7786 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
7787
7788 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7789 p += 2;
7790 }
56be3814 7791 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 7792 return 1;
b96ec7ac
AC
7793}
7794
74ca34ce
DJ
7795/* Fetch the registers included in the target's 'g' packet. */
7796
29709017
DJ
7797static int
7798send_g_packet (void)
c906108c 7799{
d01949b6 7800 struct remote_state *rs = get_remote_state ();
cea39f65 7801 int buf_len;
c906108c 7802
bba74b36 7803 xsnprintf (rs->buf, get_remote_packet_size (), "g");
b75abf5b
AK
7804 putpkt (rs->buf);
7805 getpkt (&rs->buf, &rs->buf_size, 0);
7806 if (packet_check_result (rs->buf) == PACKET_ERROR)
7807 error (_("Could not read registers; remote failure reply '%s'"),
7808 rs->buf);
c906108c 7809
29709017
DJ
7810 /* We can get out of synch in various cases. If the first character
7811 in the buffer is not a hex character, assume that has happened
7812 and try to fetch another packet to read. */
7813 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7814 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7815 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7816 && rs->buf[0] != 'x') /* New: unavailable register value. */
7817 {
7818 if (remote_debug)
7819 fprintf_unfiltered (gdb_stdlog,
7820 "Bad register packet; fetching a new packet\n");
7821 getpkt (&rs->buf, &rs->buf_size, 0);
7822 }
7823
74ca34ce
DJ
7824 buf_len = strlen (rs->buf);
7825
7826 /* Sanity check the received packet. */
7827 if (buf_len % 2 != 0)
7828 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
7829
7830 return buf_len / 2;
7831}
7832
7833static void
56be3814 7834process_g_packet (struct regcache *regcache)
29709017 7835{
ac7936df 7836 struct gdbarch *gdbarch = regcache->arch ();
29709017 7837 struct remote_state *rs = get_remote_state ();
5cd63fda 7838 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
29709017
DJ
7839 int i, buf_len;
7840 char *p;
7841 char *regs;
7842
7843 buf_len = strlen (rs->buf);
7844
7845 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce 7846 if (buf_len > 2 * rsa->sizeof_g_packet)
fc809827
SM
7847 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
7848 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
74ca34ce
DJ
7849
7850 /* Save the size of the packet sent to us by the target. It is used
7851 as a heuristic when determining the max size of packets that the
7852 target can safely receive. */
7853 if (rsa->actual_register_packet_size == 0)
7854 rsa->actual_register_packet_size = buf_len;
7855
7856 /* If this is smaller than we guessed the 'g' packet would be,
7857 update our records. A 'g' reply that doesn't include a register's
7858 value implies either that the register is not available, or that
7859 the 'p' packet must be used. */
7860 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 7861 {
9dc193c3 7862 long sizeof_g_packet = buf_len / 2;
74ca34ce 7863
4a22f64d 7864 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 7865 {
9dc193c3
LF
7866 long offset = rsa->regs[i].offset;
7867 long reg_size = register_size (gdbarch, i);
7868
74ca34ce
DJ
7869 if (rsa->regs[i].pnum == -1)
7870 continue;
7871
9dc193c3 7872 if (offset >= sizeof_g_packet)
74ca34ce 7873 rsa->regs[i].in_g_packet = 0;
9dc193c3
LF
7874 else if (offset + reg_size > sizeof_g_packet)
7875 error (_("Truncated register %d in remote 'g' packet"), i);
b96ec7ac 7876 else
74ca34ce 7877 rsa->regs[i].in_g_packet = 1;
b96ec7ac 7878 }
9dc193c3
LF
7879
7880 /* Looks valid enough, we can assume this is the correct length
7881 for a 'g' packet. It's important not to adjust
7882 rsa->sizeof_g_packet if we have truncated registers otherwise
7883 this "if" won't be run the next time the method is called
7884 with a packet of the same size and one of the internal errors
7885 below will trigger instead. */
7886 rsa->sizeof_g_packet = sizeof_g_packet;
74ca34ce 7887 }
b323314b 7888
224c3ddb 7889 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
7890
7891 /* Unimplemented registers read as all bits zero. */
ea9c271d 7892 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 7893
c906108c
SS
7894 /* Reply describes registers byte by byte, each byte encoded as two
7895 hex characters. Suck them all up, then supply them to the
7896 register cacheing/storage mechanism. */
7897
74ca34ce 7898 p = rs->buf;
ea9c271d 7899 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 7900 {
74ca34ce
DJ
7901 if (p[0] == 0 || p[1] == 0)
7902 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7903 internal_error (__FILE__, __LINE__,
9b20d036 7904 _("unexpected end of 'g' packet reply"));
74ca34ce 7905
c906108c 7906 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 7907 regs[i] = 0; /* 'x' */
c906108c
SS
7908 else
7909 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7910 p += 2;
7911 }
7912
a744cf53
MS
7913 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7914 {
7915 struct packet_reg *r = &rsa->regs[i];
9dc193c3 7916 long reg_size = register_size (gdbarch, i);
a744cf53
MS
7917
7918 if (r->in_g_packet)
7919 {
9dc193c3 7920 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
a744cf53
MS
7921 /* This shouldn't happen - we adjusted in_g_packet above. */
7922 internal_error (__FILE__, __LINE__,
9b20d036 7923 _("unexpected end of 'g' packet reply"));
a744cf53
MS
7924 else if (rs->buf[r->offset * 2] == 'x')
7925 {
7926 gdb_assert (r->offset * 2 < strlen (rs->buf));
7927 /* The register isn't available, mark it as such (at
7928 the same time setting the value to zero). */
7929 regcache_raw_supply (regcache, r->regnum, NULL);
7930 }
7931 else
7932 regcache_raw_supply (regcache, r->regnum,
7933 regs + r->offset);
7934 }
7935 }
c906108c
SS
7936}
7937
29709017 7938static void
56be3814 7939fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
7940{
7941 send_g_packet ();
56be3814 7942 process_g_packet (regcache);
29709017
DJ
7943}
7944
e6e4e701
PA
7945/* Make the remote selected traceframe match GDB's selected
7946 traceframe. */
7947
7948static void
7949set_remote_traceframe (void)
7950{
7951 int newnum;
262e1174 7952 struct remote_state *rs = get_remote_state ();
e6e4e701 7953
262e1174 7954 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
7955 return;
7956
7957 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 7958 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
7959
7960 newnum = target_trace_find (tfind_number,
7961 get_traceframe_number (), 0, 0, NULL);
7962
7963 /* Should not happen. If it does, all bets are off. */
7964 if (newnum != get_traceframe_number ())
7965 warning (_("could not set remote traceframe"));
7966}
7967
f6ac5f3d
PA
7968void
7969remote_target::fetch_registers (struct regcache *regcache, int regnum)
74ca34ce 7970{
ac7936df 7971 struct gdbarch *gdbarch = regcache->arch ();
5cd63fda 7972 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
74ca34ce
DJ
7973 int i;
7974
e6e4e701 7975 set_remote_traceframe ();
bcc0c096 7976 set_general_thread (regcache_get_ptid (regcache));
74ca34ce
DJ
7977
7978 if (regnum >= 0)
7979 {
5cd63fda 7980 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 7981
74ca34ce
DJ
7982 gdb_assert (reg != NULL);
7983
7984 /* If this register might be in the 'g' packet, try that first -
7985 we are likely to read more than one register. If this is the
7986 first 'g' packet, we might be overly optimistic about its
7987 contents, so fall back to 'p'. */
7988 if (reg->in_g_packet)
7989 {
56be3814 7990 fetch_registers_using_g (regcache);
74ca34ce
DJ
7991 if (reg->in_g_packet)
7992 return;
7993 }
7994
56be3814 7995 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
7996 return;
7997
7998 /* This register is not available. */
56be3814 7999 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
8000
8001 return;
8002 }
8003
56be3814 8004 fetch_registers_using_g (regcache);
74ca34ce 8005
5cd63fda 8006 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8007 if (!rsa->regs[i].in_g_packet)
56be3814 8008 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
8009 {
8010 /* This register is not available. */
56be3814 8011 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
8012 }
8013}
8014
c906108c
SS
8015/* Prepare to store registers. Since we may send them all (using a
8016 'G' request), we have to read out the ones we don't want to change
8017 first. */
8018
f6ac5f3d
PA
8019void
8020remote_target::prepare_to_store (struct regcache *regcache)
c906108c 8021{
5cd63fda 8022 remote_arch_state *rsa = get_remote_arch_state (regcache->arch ());
cf0e1e0d 8023 int i;
cf0e1e0d 8024
c906108c 8025 /* Make sure the entire registers array is valid. */
4082afcc 8026 switch (packet_support (PACKET_P))
5a2468f5
JM
8027 {
8028 case PACKET_DISABLE:
8029 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 8030 /* Make sure all the necessary registers are cached. */
ac7936df 8031 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
ea9c271d 8032 if (rsa->regs[i].in_g_packet)
8e368124 8033 regcache_raw_update (regcache, rsa->regs[i].regnum);
5a2468f5
JM
8034 break;
8035 case PACKET_ENABLE:
8036 break;
8037 }
8038}
8039
ad10f812 8040/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 8041 packet was not recognized. */
5a2468f5
JM
8042
8043static int
1f4437a4
MS
8044store_register_using_P (const struct regcache *regcache,
8045 struct packet_reg *reg)
5a2468f5 8046{
ac7936df 8047 struct gdbarch *gdbarch = regcache->arch ();
d01949b6 8048 struct remote_state *rs = get_remote_state ();
5a2468f5 8049 /* Try storing a single register. */
6d820c5c 8050 char *buf = rs->buf;
9890e433 8051 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
5a2468f5 8052 char *p;
5a2468f5 8053
4082afcc 8054 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
8055 return 0;
8056
8057 if (reg->pnum == -1)
8058 return 0;
8059
ea9c271d 8060 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 8061 p = buf + strlen (buf);
56be3814 8062 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 8063 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
8064 putpkt (rs->buf);
8065 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 8066
74ca34ce
DJ
8067 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8068 {
8069 case PACKET_OK:
8070 return 1;
8071 case PACKET_ERROR:
27a9c0bf
MS
8072 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8073 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
8074 case PACKET_UNKNOWN:
8075 return 0;
8076 default:
8077 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8078 }
c906108c
SS
8079}
8080
23860348
MS
8081/* Store register REGNUM, or all registers if REGNUM == -1, from the
8082 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
8083
8084static void
56be3814 8085store_registers_using_G (const struct regcache *regcache)
c906108c 8086{
d01949b6 8087 struct remote_state *rs = get_remote_state ();
5cd63fda 8088 remote_arch_state *rsa = get_remote_arch_state (regcache->arch ());
cfd77fa1 8089 gdb_byte *regs;
c906108c
SS
8090 char *p;
8091
193cb69f
AC
8092 /* Extract all the registers in the regcache copying them into a
8093 local buffer. */
8094 {
b323314b 8095 int i;
a744cf53 8096
224c3ddb 8097 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 8098 memset (regs, 0, rsa->sizeof_g_packet);
ac7936df 8099 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
193cb69f 8100 {
ea9c271d 8101 struct packet_reg *r = &rsa->regs[i];
a744cf53 8102
b323314b 8103 if (r->in_g_packet)
56be3814 8104 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
8105 }
8106 }
c906108c
SS
8107
8108 /* Command describes registers byte by byte,
8109 each byte encoded as two hex characters. */
6d820c5c 8110 p = rs->buf;
193cb69f 8111 *p++ = 'G';
74ca34ce 8112 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
8113 putpkt (rs->buf);
8114 getpkt (&rs->buf, &rs->buf_size, 0);
8115 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
8116 error (_("Could not write registers; remote failure reply '%s'"),
8117 rs->buf);
c906108c 8118}
74ca34ce
DJ
8119
8120/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8121 of the register cache buffer. FIXME: ignores errors. */
8122
f6ac5f3d
PA
8123void
8124remote_target::store_registers (struct regcache *regcache, int regnum)
74ca34ce 8125{
5cd63fda
PA
8126 struct gdbarch *gdbarch = regcache->arch ();
8127 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
74ca34ce
DJ
8128 int i;
8129
e6e4e701 8130 set_remote_traceframe ();
bcc0c096 8131 set_general_thread (regcache_get_ptid (regcache));
74ca34ce
DJ
8132
8133 if (regnum >= 0)
8134 {
5cd63fda 8135 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 8136
74ca34ce
DJ
8137 gdb_assert (reg != NULL);
8138
8139 /* Always prefer to store registers using the 'P' packet if
8140 possible; we often change only a small number of registers.
8141 Sometimes we change a larger number; we'd need help from a
8142 higher layer to know to use 'G'. */
56be3814 8143 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
8144 return;
8145
8146 /* For now, don't complain if we have no way to write the
8147 register. GDB loses track of unavailable registers too
8148 easily. Some day, this may be an error. We don't have
0df8b418 8149 any way to read the register, either... */
74ca34ce
DJ
8150 if (!reg->in_g_packet)
8151 return;
8152
56be3814 8153 store_registers_using_G (regcache);
74ca34ce
DJ
8154 return;
8155 }
8156
56be3814 8157 store_registers_using_G (regcache);
74ca34ce 8158
5cd63fda 8159 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 8160 if (!rsa->regs[i].in_g_packet)
56be3814 8161 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
8162 /* See above for why we do not issue an error here. */
8163 continue;
8164}
c906108c
SS
8165\f
8166
8167/* Return the number of hex digits in num. */
8168
8169static int
fba45db2 8170hexnumlen (ULONGEST num)
c906108c
SS
8171{
8172 int i;
8173
8174 for (i = 0; num != 0; i++)
8175 num >>= 4;
8176
325fac50 8177 return std::max (i, 1);
c906108c
SS
8178}
8179
2df3850c 8180/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
8181
8182static int
fba45db2 8183hexnumstr (char *buf, ULONGEST num)
c906108c 8184{
c906108c 8185 int len = hexnumlen (num);
a744cf53 8186
2df3850c
JM
8187 return hexnumnstr (buf, num, len);
8188}
8189
c906108c 8190
2df3850c 8191/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 8192
2df3850c 8193static int
fba45db2 8194hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
8195{
8196 int i;
8197
8198 buf[width] = '\0';
8199
8200 for (i = width - 1; i >= 0; i--)
c906108c 8201 {
c5aa993b 8202 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
8203 num >>= 4;
8204 }
8205
2df3850c 8206 return width;
c906108c
SS
8207}
8208
23860348 8209/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
8210
8211static CORE_ADDR
fba45db2 8212remote_address_masked (CORE_ADDR addr)
c906108c 8213{
883b9c6c 8214 unsigned int address_size = remote_address_size;
a744cf53 8215
911c95a5
UW
8216 /* If "remoteaddresssize" was not set, default to target address size. */
8217 if (!address_size)
f5656ead 8218 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
8219
8220 if (address_size > 0
8221 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
8222 {
8223 /* Only create a mask when that mask can safely be constructed
23860348 8224 in a ULONGEST variable. */
c906108c 8225 ULONGEST mask = 1;
a744cf53 8226
911c95a5 8227 mask = (mask << address_size) - 1;
c906108c
SS
8228 addr &= mask;
8229 }
8230 return addr;
8231}
8232
8233/* Determine whether the remote target supports binary downloading.
8234 This is accomplished by sending a no-op memory write of zero length
8235 to the target at the specified address. It does not suffice to send
23860348
MS
8236 the whole packet, since many stubs strip the eighth bit and
8237 subsequently compute a wrong checksum, which causes real havoc with
8238 remote_write_bytes.
7a292a7a 8239
96baa820 8240 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 8241 clean. In cases like this, the user should clear "remote
23860348 8242 X-packet". */
96baa820 8243
c906108c 8244static void
fba45db2 8245check_binary_download (CORE_ADDR addr)
c906108c 8246{
d01949b6 8247 struct remote_state *rs = get_remote_state ();
24b06219 8248
4082afcc 8249 switch (packet_support (PACKET_X))
c906108c 8250 {
96baa820
JM
8251 case PACKET_DISABLE:
8252 break;
8253 case PACKET_ENABLE:
8254 break;
8255 case PACKET_SUPPORT_UNKNOWN:
8256 {
96baa820 8257 char *p;
802188a7 8258
2e9f7625 8259 p = rs->buf;
96baa820
JM
8260 *p++ = 'X';
8261 p += hexnumstr (p, (ULONGEST) addr);
8262 *p++ = ',';
8263 p += hexnumstr (p, (ULONGEST) 0);
8264 *p++ = ':';
8265 *p = '\0';
802188a7 8266
2e9f7625 8267 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 8268 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 8269
2e9f7625 8270 if (rs->buf[0] == '\0')
96baa820
JM
8271 {
8272 if (remote_debug)
8273 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8274 "binary downloading NOT "
8275 "supported by target\n");
444abaca 8276 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
8277 }
8278 else
8279 {
8280 if (remote_debug)
8281 fprintf_unfiltered (gdb_stdlog,
64b9b334 8282 "binary downloading supported by target\n");
444abaca 8283 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
8284 }
8285 break;
8286 }
c906108c
SS
8287 }
8288}
8289
124e13d9
SM
8290/* Helper function to resize the payload in order to try to get a good
8291 alignment. We try to write an amount of data such that the next write will
8292 start on an address aligned on REMOTE_ALIGN_WRITES. */
8293
8294static int
8295align_for_efficient_write (int todo, CORE_ADDR memaddr)
8296{
8297 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8298}
8299
c906108c
SS
8300/* Write memory data directly to the remote machine.
8301 This does not inform the data cache; the data cache uses this.
a76d924d 8302 HEADER is the starting part of the packet.
c906108c
SS
8303 MEMADDR is the address in the remote memory space.
8304 MYADDR is the address of the buffer in our space.
124e13d9
SM
8305 LEN_UNITS is the number of addressable units to write.
8306 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
8307 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8308 should send data as binary ('X'), or hex-encoded ('M').
8309
8310 The function creates packet of the form
8311 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8312
124e13d9 8313 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
8314
8315 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8316 are omitted.
8317
9b409511 8318 Return the transferred status, error or OK (an
124e13d9
SM
8319 'enum target_xfer_status' value). Save the number of addressable units
8320 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8321
8322 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8323 exchange between gdb and the stub could look like (?? in place of the
8324 checksum):
8325
8326 -> $m1000,4#??
8327 <- aaaabbbbccccdddd
8328
8329 -> $M1000,3:eeeeffffeeee#??
8330 <- OK
8331
8332 -> $m1000,4#??
8333 <- eeeeffffeeeedddd */
c906108c 8334
9b409511 8335static enum target_xfer_status
a76d924d 8336remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
124e13d9
SM
8337 const gdb_byte *myaddr, ULONGEST len_units,
8338 int unit_size, ULONGEST *xfered_len_units,
8339 char packet_format, int use_length)
c906108c 8340{
6d820c5c 8341 struct remote_state *rs = get_remote_state ();
cfd77fa1 8342 char *p;
a76d924d
DJ
8343 char *plen = NULL;
8344 int plenlen = 0;
124e13d9
SM
8345 int todo_units;
8346 int units_written;
8347 int payload_capacity_bytes;
8348 int payload_length_bytes;
a76d924d
DJ
8349
8350 if (packet_format != 'X' && packet_format != 'M')
8351 internal_error (__FILE__, __LINE__,
9b20d036 8352 _("remote_write_bytes_aux: bad packet format"));
c906108c 8353
124e13d9 8354 if (len_units == 0)
9b409511 8355 return TARGET_XFER_EOF;
b2182ed2 8356
124e13d9 8357 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 8358
6d820c5c
DJ
8359 /* The packet buffer will be large enough for the payload;
8360 get_memory_packet_size ensures this. */
a76d924d 8361 rs->buf[0] = '\0';
c906108c 8362
a257b5bb 8363 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
8364 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8365
124e13d9 8366 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 8367 if (!use_length)
0df8b418 8368 /* The comma won't be used. */
124e13d9
SM
8369 payload_capacity_bytes += 1;
8370 payload_capacity_bytes -= strlen (header);
8371 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 8372
a76d924d 8373 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 8374
a76d924d
DJ
8375 strcat (rs->buf, header);
8376 p = rs->buf + strlen (header);
8377
8378 /* Compute a best guess of the number of bytes actually transfered. */
8379 if (packet_format == 'X')
c906108c 8380 {
23860348 8381 /* Best guess at number of bytes that will fit. */
325fac50
PA
8382 todo_units = std::min (len_units,
8383 (ULONGEST) payload_capacity_bytes / unit_size);
a76d924d 8384 if (use_length)
124e13d9 8385 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50 8386 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
8387 }
8388 else
8389 {
124e13d9 8390 /* Number of bytes that will fit. */
325fac50
PA
8391 todo_units
8392 = std::min (len_units,
8393 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
a76d924d 8394 if (use_length)
124e13d9 8395 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50
PA
8396 todo_units = std::min (todo_units,
8397 (payload_capacity_bytes / unit_size) / 2);
917317f4 8398 }
a76d924d 8399
124e13d9 8400 if (todo_units <= 0)
3de11b2e 8401 internal_error (__FILE__, __LINE__,
405f8e94 8402 _("minimum packet size too small to write data"));
802188a7 8403
6765f3e5
DJ
8404 /* If we already need another packet, then try to align the end
8405 of this packet to a useful boundary. */
124e13d9
SM
8406 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8407 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 8408
a257b5bb 8409 /* Append "<memaddr>". */
917317f4
JM
8410 memaddr = remote_address_masked (memaddr);
8411 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 8412
a76d924d
DJ
8413 if (use_length)
8414 {
8415 /* Append ",". */
8416 *p++ = ',';
802188a7 8417
124e13d9
SM
8418 /* Append the length and retain its location and size. It may need to be
8419 adjusted once the packet body has been created. */
a76d924d 8420 plen = p;
124e13d9 8421 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
8422 p += plenlen;
8423 }
a257b5bb
AC
8424
8425 /* Append ":". */
917317f4
JM
8426 *p++ = ':';
8427 *p = '\0';
802188a7 8428
a257b5bb 8429 /* Append the packet body. */
a76d924d 8430 if (packet_format == 'X')
917317f4 8431 {
917317f4
JM
8432 /* Binary mode. Send target system values byte by byte, in
8433 increasing byte addresses. Only escape certain critical
8434 characters. */
124e13d9
SM
8435 payload_length_bytes =
8436 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8437 &units_written, payload_capacity_bytes);
6765f3e5 8438
124e13d9 8439 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
8440 a second try to keep the end of the packet aligned. Don't do
8441 this if the packet is tiny. */
124e13d9 8442 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 8443 {
124e13d9
SM
8444 int new_todo_units;
8445
8446 new_todo_units = align_for_efficient_write (units_written, memaddr);
8447
8448 if (new_todo_units != units_written)
8449 payload_length_bytes =
8450 remote_escape_output (myaddr, new_todo_units, unit_size,
8451 (gdb_byte *) p, &units_written,
8452 payload_capacity_bytes);
6765f3e5
DJ
8453 }
8454
124e13d9
SM
8455 p += payload_length_bytes;
8456 if (use_length && units_written < todo_units)
c906108c 8457 {
802188a7 8458 /* Escape chars have filled up the buffer prematurely,
124e13d9 8459 and we have actually sent fewer units than planned.
917317f4
JM
8460 Fix-up the length field of the packet. Use the same
8461 number of characters as before. */
124e13d9
SM
8462 plen += hexnumnstr (plen, (ULONGEST) units_written,
8463 plenlen);
917317f4 8464 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 8465 }
a76d924d
DJ
8466 }
8467 else
8468 {
917317f4
JM
8469 /* Normal mode: Send target system values byte by byte, in
8470 increasing byte addresses. Each byte is encoded as a two hex
8471 value. */
124e13d9
SM
8472 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8473 units_written = todo_units;
c906108c 8474 }
802188a7 8475
2e9f7625 8476 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 8477 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 8478
2e9f7625 8479 if (rs->buf[0] == 'E')
00d84524 8480 return TARGET_XFER_E_IO;
802188a7 8481
124e13d9
SM
8482 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8483 send fewer units than we'd planned. */
8484 *xfered_len_units = (ULONGEST) units_written;
92ffd475 8485 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
8486}
8487
a76d924d
DJ
8488/* Write memory data directly to the remote machine.
8489 This does not inform the data cache; the data cache uses this.
8490 MEMADDR is the address in the remote memory space.
8491 MYADDR is the address of the buffer in our space.
8492 LEN is the number of bytes.
8493
9b409511
YQ
8494 Return the transferred status, error or OK (an
8495 'enum target_xfer_status' value). Save the number of bytes
8496 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 8497
9b409511
YQ
8498static enum target_xfer_status
8499remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
124e13d9 8500 int unit_size, ULONGEST *xfered_len)
a76d924d 8501{
a121b7c1 8502 const char *packet_format = NULL;
a76d924d
DJ
8503
8504 /* Check whether the target supports binary download. */
8505 check_binary_download (memaddr);
8506
4082afcc 8507 switch (packet_support (PACKET_X))
a76d924d
DJ
8508 {
8509 case PACKET_ENABLE:
8510 packet_format = "X";
8511 break;
8512 case PACKET_DISABLE:
8513 packet_format = "M";
8514 break;
8515 case PACKET_SUPPORT_UNKNOWN:
8516 internal_error (__FILE__, __LINE__,
8517 _("remote_write_bytes: bad internal state"));
8518 default:
8519 internal_error (__FILE__, __LINE__, _("bad switch"));
8520 }
8521
8522 return remote_write_bytes_aux (packet_format,
124e13d9 8523 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 8524 packet_format[0], 1);
a76d924d
DJ
8525}
8526
9217e74e
YQ
8527/* Read memory data directly from the remote machine.
8528 This does not use the data cache; the data cache uses this.
8529 MEMADDR is the address in the remote memory space.
8530 MYADDR is the address of the buffer in our space.
124e13d9
SM
8531 LEN_UNITS is the number of addressable memory units to read..
8532 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
8533
8534 Return the transferred status, error or OK (an
8535 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
8536 transferred in *XFERED_LEN_UNITS.
8537
8538 See the comment of remote_write_bytes_aux for an example of
8539 memory read/write exchange between gdb and the stub. */
9217e74e
YQ
8540
8541static enum target_xfer_status
124e13d9
SM
8542remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
8543 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
8544{
8545 struct remote_state *rs = get_remote_state ();
124e13d9 8546 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 8547 char *p;
124e13d9
SM
8548 int todo_units;
8549 int decoded_bytes;
9217e74e 8550
124e13d9 8551 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
8552 /* The packet buffer will be large enough for the payload;
8553 get_memory_packet_size ensures this. */
8554
124e13d9 8555 /* Number of units that will fit. */
325fac50
PA
8556 todo_units = std::min (len_units,
8557 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
8558
8559 /* Construct "m"<memaddr>","<len>". */
8560 memaddr = remote_address_masked (memaddr);
8561 p = rs->buf;
8562 *p++ = 'm';
8563 p += hexnumstr (p, (ULONGEST) memaddr);
8564 *p++ = ',';
124e13d9 8565 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
8566 *p = '\0';
8567 putpkt (rs->buf);
8568 getpkt (&rs->buf, &rs->buf_size, 0);
8569 if (rs->buf[0] == 'E'
8570 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8571 && rs->buf[3] == '\0')
8572 return TARGET_XFER_E_IO;
8573 /* Reply describes memory byte by byte, each byte encoded as two hex
8574 characters. */
8575 p = rs->buf;
124e13d9 8576 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 8577 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 8578 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
92ffd475 8579 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9217e74e
YQ
8580}
8581
b55fbac4
YQ
8582/* Using the set of read-only target sections of remote, read live
8583 read-only memory.
8acf9577
YQ
8584
8585 For interface/parameters/return description see target.h,
8586 to_xfer_partial. */
8587
8588static enum target_xfer_status
b55fbac4
YQ
8589remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
8590 ULONGEST memaddr, ULONGEST len,
124e13d9 8591 int unit_size, ULONGEST *xfered_len)
8acf9577
YQ
8592{
8593 struct target_section *secp;
8594 struct target_section_table *table;
8595
8596 secp = target_section_by_addr (ops, memaddr);
8597 if (secp != NULL
8598 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8599 secp->the_bfd_section)
8600 & SEC_READONLY))
8601 {
8602 struct target_section *p;
8603 ULONGEST memend = memaddr + len;
8604
8605 table = target_get_section_table (ops);
8606
8607 for (p = table->sections; p < table->sections_end; p++)
8608 {
8609 if (memaddr >= p->addr)
8610 {
8611 if (memend <= p->endaddr)
8612 {
8613 /* Entire transfer is within this section. */
124e13d9 8614 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8615 xfered_len);
8acf9577
YQ
8616 }
8617 else if (memaddr >= p->endaddr)
8618 {
8619 /* This section ends before the transfer starts. */
8620 continue;
8621 }
8622 else
8623 {
8624 /* This section overlaps the transfer. Just do half. */
8625 len = p->endaddr - memaddr;
124e13d9 8626 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8627 xfered_len);
8acf9577
YQ
8628 }
8629 }
8630 }
8631 }
8632
8633 return TARGET_XFER_EOF;
8634}
8635
9217e74e
YQ
8636/* Similar to remote_read_bytes_1, but it reads from the remote stub
8637 first if the requested memory is unavailable in traceframe.
8638 Otherwise, fall back to remote_read_bytes_1. */
c906108c 8639
9b409511 8640static enum target_xfer_status
8acf9577 8641remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
124e13d9
SM
8642 gdb_byte *myaddr, ULONGEST len, int unit_size,
8643 ULONGEST *xfered_len)
c906108c 8644{
6b6aa828 8645 if (len == 0)
96c4f946 8646 return TARGET_XFER_EOF;
b2182ed2 8647
8acf9577
YQ
8648 if (get_traceframe_number () != -1)
8649 {
a79b1bc6 8650 std::vector<mem_range> available;
8acf9577
YQ
8651
8652 /* If we fail to get the set of available memory, then the
8653 target does not support querying traceframe info, and so we
8654 attempt reading from the traceframe anyway (assuming the
8655 target implements the old QTro packet then). */
8656 if (traceframe_available_memory (&available, memaddr, len))
8657 {
a79b1bc6 8658 if (available.empty () || available[0].start != memaddr)
8acf9577
YQ
8659 {
8660 enum target_xfer_status res;
8661
8662 /* Don't read into the traceframe's available
8663 memory. */
a79b1bc6 8664 if (!available.empty ())
8acf9577
YQ
8665 {
8666 LONGEST oldlen = len;
8667
a79b1bc6 8668 len = available[0].start - memaddr;
8acf9577
YQ
8669 gdb_assert (len <= oldlen);
8670 }
8671
8acf9577 8672 /* This goes through the topmost target again. */
b55fbac4 8673 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
124e13d9 8674 len, unit_size, xfered_len);
8acf9577
YQ
8675 if (res == TARGET_XFER_OK)
8676 return TARGET_XFER_OK;
8677 else
8678 {
8679 /* No use trying further, we know some memory starting
8680 at MEMADDR isn't available. */
8681 *xfered_len = len;
92ffd475
PC
8682 return (*xfered_len != 0) ?
8683 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8acf9577
YQ
8684 }
8685 }
8686
8687 /* Don't try to read more than how much is available, in
8688 case the target implements the deprecated QTro packet to
8689 cater for older GDBs (the target's knowledge of read-only
8690 sections may be outdated by now). */
a79b1bc6 8691 len = available[0].length;
8acf9577
YQ
8692 }
8693 }
8694
124e13d9 8695 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 8696}
74531fed 8697
c906108c 8698\f
c906108c 8699
a76d924d
DJ
8700/* Sends a packet with content determined by the printf format string
8701 FORMAT and the remaining arguments, then gets the reply. Returns
8702 whether the packet was a success, a failure, or unknown. */
8703
77b64a49
PA
8704static enum packet_result remote_send_printf (const char *format, ...)
8705 ATTRIBUTE_PRINTF (1, 2);
8706
2c0b251b 8707static enum packet_result
a76d924d
DJ
8708remote_send_printf (const char *format, ...)
8709{
8710 struct remote_state *rs = get_remote_state ();
8711 int max_size = get_remote_packet_size ();
a76d924d 8712 va_list ap;
a744cf53 8713
a76d924d
DJ
8714 va_start (ap, format);
8715
8716 rs->buf[0] = '\0';
8717 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 8718 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
8719
8720 if (putpkt (rs->buf) < 0)
8721 error (_("Communication problem with target."));
8722
8723 rs->buf[0] = '\0';
8724 getpkt (&rs->buf, &rs->buf_size, 0);
8725
8726 return packet_check_result (rs->buf);
8727}
8728
a76d924d
DJ
8729/* Flash writing can take quite some time. We'll set
8730 effectively infinite timeout for flash operations.
8731 In future, we'll need to decide on a better approach. */
8732static const int remote_flash_timeout = 1000;
8733
f6ac5f3d
PA
8734void
8735remote_target::flash_erase (ULONGEST address, LONGEST length)
a76d924d 8736{
f5656ead 8737 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d 8738 enum packet_result ret;
2ec845e7
TT
8739 scoped_restore restore_timeout
8740 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
a76d924d
DJ
8741
8742 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 8743 phex (address, addr_size),
a76d924d
DJ
8744 phex (length, 4));
8745 switch (ret)
8746 {
8747 case PACKET_UNKNOWN:
8748 error (_("Remote target does not support flash erase"));
8749 case PACKET_ERROR:
8750 error (_("Error erasing flash with vFlashErase packet"));
8751 default:
8752 break;
8753 }
a76d924d
DJ
8754}
8755
9b409511
YQ
8756static enum target_xfer_status
8757remote_flash_write (struct target_ops *ops, ULONGEST address,
8758 ULONGEST length, ULONGEST *xfered_len,
8759 const gdb_byte *data)
a76d924d 8760{
2ec845e7
TT
8761 scoped_restore restore_timeout
8762 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8763 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8764 xfered_len,'X', 0);
a76d924d
DJ
8765}
8766
f6ac5f3d
PA
8767void
8768remote_target::flash_done ()
a76d924d 8769{
a76d924d 8770 int ret;
a76d924d 8771
2ec845e7
TT
8772 scoped_restore restore_timeout
8773 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8774
a76d924d 8775 ret = remote_send_printf ("vFlashDone");
a76d924d
DJ
8776
8777 switch (ret)
8778 {
8779 case PACKET_UNKNOWN:
8780 error (_("Remote target does not support vFlashDone"));
8781 case PACKET_ERROR:
8782 error (_("Error finishing flash operation"));
8783 default:
8784 break;
8785 }
8786}
8787
f6ac5f3d
PA
8788void
8789remote_target::files_info ()
c906108c
SS
8790{
8791 puts_filtered ("Debugging a target over a serial line.\n");
8792}
8793\f
8794/* Stuff for dealing with the packets which are part of this protocol.
8795 See comment at top of file for details. */
8796
1927e618
PA
8797/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8798 error to higher layers. Called when a serial error is detected.
8799 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
8800 the system error message for errno at function entry and final dot
8801 for output compatibility with throw_perror_with_name. */
1927e618
PA
8802
8803static void
8804unpush_and_perror (const char *string)
8805{
d6cb50a2 8806 int saved_errno = errno;
1927e618
PA
8807
8808 remote_unpush_target ();
d6cb50a2
JK
8809 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8810 safe_strerror (saved_errno));
1927e618
PA
8811}
8812
048094ac
PA
8813/* Read a single character from the remote end. The current quit
8814 handler is overridden to avoid quitting in the middle of packet
8815 sequence, as that would break communication with the remote server.
8816 See remote_serial_quit_handler for more detail. */
c906108c
SS
8817
8818static int
fba45db2 8819readchar (int timeout)
c906108c
SS
8820{
8821 int ch;
5d93a237 8822 struct remote_state *rs = get_remote_state ();
048094ac 8823
2ec845e7
TT
8824 {
8825 scoped_restore restore_quit
8826 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
c906108c 8827
2ec845e7 8828 rs->got_ctrlc_during_io = 0;
c906108c 8829
2ec845e7 8830 ch = serial_readchar (rs->remote_desc, timeout);
048094ac 8831
2ec845e7
TT
8832 if (rs->got_ctrlc_during_io)
8833 set_quit_flag ();
8834 }
048094ac 8835
2acceee2 8836 if (ch >= 0)
0876f84a 8837 return ch;
2acceee2
JM
8838
8839 switch ((enum serial_rc) ch)
c906108c
SS
8840 {
8841 case SERIAL_EOF:
78a095c3 8842 remote_unpush_target ();
598d3636 8843 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 8844 /* no return */
c906108c 8845 case SERIAL_ERROR:
1927e618
PA
8846 unpush_and_perror (_("Remote communication error. "
8847 "Target disconnected."));
2acceee2 8848 /* no return */
c906108c 8849 case SERIAL_TIMEOUT:
2acceee2 8850 break;
c906108c 8851 }
2acceee2 8852 return ch;
c906108c
SS
8853}
8854
c33e31fd 8855/* Wrapper for serial_write that closes the target and throws if
048094ac
PA
8856 writing fails. The current quit handler is overridden to avoid
8857 quitting in the middle of packet sequence, as that would break
8858 communication with the remote server. See
8859 remote_serial_quit_handler for more detail. */
c33e31fd
PA
8860
8861static void
8862remote_serial_write (const char *str, int len)
8863{
5d93a237 8864 struct remote_state *rs = get_remote_state ();
048094ac 8865
2ec845e7
TT
8866 scoped_restore restore_quit
8867 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
048094ac
PA
8868
8869 rs->got_ctrlc_during_io = 0;
5d93a237
TT
8870
8871 if (serial_write (rs->remote_desc, str, len))
c33e31fd 8872 {
1927e618
PA
8873 unpush_and_perror (_("Remote communication error. "
8874 "Target disconnected."));
c33e31fd 8875 }
048094ac
PA
8876
8877 if (rs->got_ctrlc_during_io)
8878 set_quit_flag ();
c33e31fd
PA
8879}
8880
b3ced9ba
PA
8881/* Return a string representing an escaped version of BUF, of len N.
8882 E.g. \n is converted to \\n, \t to \\t, etc. */
6e5abd65 8883
b3ced9ba 8884static std::string
6e5abd65
PA
8885escape_buffer (const char *buf, int n)
8886{
d7e74731 8887 string_file stb;
6e5abd65 8888
d7e74731
PA
8889 stb.putstrn (buf, n, '\\');
8890 return std::move (stb.string ());
6e5abd65
PA
8891}
8892
c906108c
SS
8893/* Display a null-terminated packet on stdout, for debugging, using C
8894 string notation. */
8895
8896static void
baa336ce 8897print_packet (const char *buf)
c906108c
SS
8898{
8899 puts_filtered ("\"");
43e526b9 8900 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
8901 puts_filtered ("\"");
8902}
8903
8904int
baa336ce 8905putpkt (const char *buf)
c906108c
SS
8906{
8907 return putpkt_binary (buf, strlen (buf));
8908}
8909
8910/* Send a packet to the remote machine, with error checking. The data
23860348 8911 of the packet is in BUF. The string in BUF can be at most
ea9c271d 8912 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
8913 and for a possible /0 if we are debugging (remote_debug) and want
8914 to print the sent packet as a string. */
c906108c
SS
8915
8916static int
baa336ce 8917putpkt_binary (const char *buf, int cnt)
c906108c 8918{
2d717e4f 8919 struct remote_state *rs = get_remote_state ();
c906108c
SS
8920 int i;
8921 unsigned char csum = 0;
b80406ac
TT
8922 gdb::def_vector<char> data (cnt + 6);
8923 char *buf2 = data.data ();
085dd6e6 8924
c906108c
SS
8925 int ch;
8926 int tcount = 0;
8927 char *p;
8928
e24a49d8
PA
8929 /* Catch cases like trying to read memory or listing threads while
8930 we're waiting for a stop reply. The remote server wouldn't be
8931 ready to handle this request, so we'd hang and timeout. We don't
8932 have to worry about this in synchronous mode, because in that
8933 case it's not possible to issue a command while the target is
74531fed
PA
8934 running. This is not a problem in non-stop mode, because in that
8935 case, the stub is always ready to process serial input. */
6efcd9a8
PA
8936 if (!target_is_non_stop_p ()
8937 && target_is_async_p ()
8938 && rs->waiting_for_stop_reply)
9597b22a
DE
8939 {
8940 error (_("Cannot execute this command while the target is running.\n"
8941 "Use the \"interrupt\" command to stop the target\n"
8942 "and then try again."));
8943 }
e24a49d8 8944
2d717e4f
DJ
8945 /* We're sending out a new packet. Make sure we don't look at a
8946 stale cached response. */
8947 rs->cached_wait_status = 0;
8948
c906108c
SS
8949 /* Copy the packet into buffer BUF2, encapsulating it
8950 and giving it a checksum. */
8951
c906108c
SS
8952 p = buf2;
8953 *p++ = '$';
8954
8955 for (i = 0; i < cnt; i++)
8956 {
8957 csum += buf[i];
8958 *p++ = buf[i];
8959 }
8960 *p++ = '#';
8961 *p++ = tohex ((csum >> 4) & 0xf);
8962 *p++ = tohex (csum & 0xf);
8963
8964 /* Send it over and over until we get a positive ack. */
8965
8966 while (1)
8967 {
8968 int started_error_output = 0;
8969
8970 if (remote_debug)
8971 {
8972 *p = '\0';
b3ced9ba 8973
6f8976bf
YQ
8974 int len = (int) (p - buf2);
8975
8976 std::string str
8977 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
8978
8979 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
8980
567a3e54
SM
8981 if (len > REMOTE_DEBUG_MAX_CHAR)
8982 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
8983 len - REMOTE_DEBUG_MAX_CHAR);
6f8976bf
YQ
8984
8985 fprintf_unfiltered (gdb_stdlog, "...");
b3ced9ba 8986
0f71a2f6 8987 gdb_flush (gdb_stdlog);
c906108c 8988 }
c33e31fd 8989 remote_serial_write (buf2, p - buf2);
c906108c 8990
a6f3e723
SL
8991 /* If this is a no acks version of the remote protocol, send the
8992 packet and move on. */
8993 if (rs->noack_mode)
8994 break;
8995
74531fed
PA
8996 /* Read until either a timeout occurs (-2) or '+' is read.
8997 Handle any notification that arrives in the mean time. */
c906108c
SS
8998 while (1)
8999 {
9000 ch = readchar (remote_timeout);
9001
c5aa993b 9002 if (remote_debug)
c906108c
SS
9003 {
9004 switch (ch)
9005 {
9006 case '+':
1216fa2c 9007 case '-':
c906108c
SS
9008 case SERIAL_TIMEOUT:
9009 case '$':
74531fed 9010 case '%':
c906108c
SS
9011 if (started_error_output)
9012 {
9013 putchar_unfiltered ('\n');
9014 started_error_output = 0;
9015 }
9016 }
9017 }
9018
9019 switch (ch)
9020 {
9021 case '+':
9022 if (remote_debug)
0f71a2f6 9023 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 9024 return 1;
1216fa2c
AC
9025 case '-':
9026 if (remote_debug)
9027 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 9028 /* FALLTHROUGH */
c906108c 9029 case SERIAL_TIMEOUT:
c5aa993b 9030 tcount++;
c906108c 9031 if (tcount > 3)
b80406ac 9032 return 0;
23860348 9033 break; /* Retransmit buffer. */
c906108c
SS
9034 case '$':
9035 {
40e3f985 9036 if (remote_debug)
2bc416ba 9037 fprintf_unfiltered (gdb_stdlog,
23860348 9038 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
9039 /* It's probably an old response sent because an ACK
9040 was lost. Gobble up the packet and ack it so it
9041 doesn't get retransmitted when we resend this
9042 packet. */
6d820c5c 9043 skip_frame ();
c33e31fd 9044 remote_serial_write ("+", 1);
23860348 9045 continue; /* Now, go look for +. */
c906108c 9046 }
74531fed
PA
9047
9048 case '%':
9049 {
9050 int val;
9051
9052 /* If we got a notification, handle it, and go back to looking
9053 for an ack. */
9054 /* We've found the start of a notification. Now
9055 collect the data. */
9056 val = read_frame (&rs->buf, &rs->buf_size);
9057 if (val >= 0)
9058 {
9059 if (remote_debug)
9060 {
b3ced9ba 9061 std::string str = escape_buffer (rs->buf, val);
6e5abd65 9062
6e5abd65
PA
9063 fprintf_unfiltered (gdb_stdlog,
9064 " Notification received: %s\n",
b3ced9ba 9065 str.c_str ());
74531fed 9066 }
5965e028 9067 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
9068 /* We're in sync now, rewait for the ack. */
9069 tcount = 0;
9070 }
9071 else
9072 {
9073 if (remote_debug)
9074 {
9075 if (!started_error_output)
9076 {
9077 started_error_output = 1;
9078 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9079 }
9080 fputc_unfiltered (ch & 0177, gdb_stdlog);
9081 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9082 }
9083 }
9084 continue;
9085 }
9086 /* fall-through */
c906108c
SS
9087 default:
9088 if (remote_debug)
9089 {
9090 if (!started_error_output)
9091 {
9092 started_error_output = 1;
0f71a2f6 9093 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 9094 }
0f71a2f6 9095 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
9096 }
9097 continue;
9098 }
23860348 9099 break; /* Here to retransmit. */
c906108c
SS
9100 }
9101
9102#if 0
9103 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
9104 able to get out next time we call QUIT, without anything as
9105 violent as interrupt_query. If we want to provide a way out of
9106 here without getting to the next QUIT, it should be based on
9107 hitting ^C twice as in remote_wait. */
c906108c
SS
9108 if (quit_flag)
9109 {
9110 quit_flag = 0;
9111 interrupt_query ();
9112 }
9113#endif
9114 }
a5c0808e 9115
a6f3e723 9116 return 0;
c906108c
SS
9117}
9118
6d820c5c
DJ
9119/* Come here after finding the start of a frame when we expected an
9120 ack. Do our best to discard the rest of this packet. */
9121
9122static void
9123skip_frame (void)
9124{
9125 int c;
9126
9127 while (1)
9128 {
9129 c = readchar (remote_timeout);
9130 switch (c)
9131 {
9132 case SERIAL_TIMEOUT:
9133 /* Nothing we can do. */
9134 return;
9135 case '#':
9136 /* Discard the two bytes of checksum and stop. */
9137 c = readchar (remote_timeout);
9138 if (c >= 0)
9139 c = readchar (remote_timeout);
9140
9141 return;
9142 case '*': /* Run length encoding. */
9143 /* Discard the repeat count. */
9144 c = readchar (remote_timeout);
9145 if (c < 0)
9146 return;
9147 break;
9148 default:
9149 /* A regular character. */
9150 break;
9151 }
9152 }
9153}
9154
c906108c 9155/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
9156 into *BUF, verifying the checksum, length, and handling run-length
9157 compression. NUL terminate the buffer. If there is not enough room,
9158 expand *BUF using xrealloc.
c906108c 9159
c2d11a7d
JM
9160 Returns -1 on error, number of characters in buffer (ignoring the
9161 trailing NULL) on success. (could be extended to return one of the
23860348 9162 SERIAL status indications). */
c2d11a7d
JM
9163
9164static long
6d820c5c
DJ
9165read_frame (char **buf_p,
9166 long *sizeof_buf)
c906108c
SS
9167{
9168 unsigned char csum;
c2d11a7d 9169 long bc;
c906108c 9170 int c;
6d820c5c 9171 char *buf = *buf_p;
a6f3e723 9172 struct remote_state *rs = get_remote_state ();
c906108c
SS
9173
9174 csum = 0;
c2d11a7d 9175 bc = 0;
c906108c
SS
9176
9177 while (1)
9178 {
9179 c = readchar (remote_timeout);
c906108c
SS
9180 switch (c)
9181 {
9182 case SERIAL_TIMEOUT:
9183 if (remote_debug)
0f71a2f6 9184 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 9185 return -1;
c906108c
SS
9186 case '$':
9187 if (remote_debug)
0f71a2f6
JM
9188 fputs_filtered ("Saw new packet start in middle of old one\n",
9189 gdb_stdlog);
23860348 9190 return -1; /* Start a new packet, count retries. */
c906108c
SS
9191 case '#':
9192 {
9193 unsigned char pktcsum;
e1b09194
AC
9194 int check_0 = 0;
9195 int check_1 = 0;
c906108c 9196
c2d11a7d 9197 buf[bc] = '\0';
c906108c 9198
e1b09194
AC
9199 check_0 = readchar (remote_timeout);
9200 if (check_0 >= 0)
9201 check_1 = readchar (remote_timeout);
802188a7 9202
e1b09194
AC
9203 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9204 {
9205 if (remote_debug)
2bc416ba 9206 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 9207 gdb_stdlog);
e1b09194
AC
9208 return -1;
9209 }
9210 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
9211 {
9212 if (remote_debug)
2bc416ba 9213 fputs_filtered ("Communication error in checksum\n",
23860348 9214 gdb_stdlog);
40e3f985
FN
9215 return -1;
9216 }
c906108c 9217
a6f3e723
SL
9218 /* Don't recompute the checksum; with no ack packets we
9219 don't have any way to indicate a packet retransmission
9220 is necessary. */
9221 if (rs->noack_mode)
9222 return bc;
9223
e1b09194 9224 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 9225 if (csum == pktcsum)
c2d11a7d 9226 return bc;
c906108c 9227
c5aa993b 9228 if (remote_debug)
c906108c 9229 {
b3ced9ba 9230 std::string str = escape_buffer (buf, bc);
6e5abd65 9231
6e5abd65 9232 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
9233 "Bad checksum, sentsum=0x%x, "
9234 "csum=0x%x, buf=%s\n",
b3ced9ba 9235 pktcsum, csum, str.c_str ());
c906108c 9236 }
c2d11a7d 9237 /* Number of characters in buffer ignoring trailing
23860348 9238 NULL. */
c2d11a7d 9239 return -1;
c906108c 9240 }
23860348 9241 case '*': /* Run length encoding. */
c2c6d25f
JM
9242 {
9243 int repeat;
c906108c 9244
a744cf53 9245 csum += c;
b4501125
AC
9246 c = readchar (remote_timeout);
9247 csum += c;
23860348 9248 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 9249
23860348 9250 /* The character before ``*'' is repeated. */
c2d11a7d 9251
6d820c5c 9252 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 9253 {
6d820c5c
DJ
9254 if (bc + repeat - 1 >= *sizeof_buf - 1)
9255 {
9256 /* Make some more room in the buffer. */
9257 *sizeof_buf += repeat;
224c3ddb 9258 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c
DJ
9259 buf = *buf_p;
9260 }
9261
c2d11a7d
JM
9262 memset (&buf[bc], buf[bc - 1], repeat);
9263 bc += repeat;
c2c6d25f
JM
9264 continue;
9265 }
9266
c2d11a7d 9267 buf[bc] = '\0';
6d820c5c 9268 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 9269 return -1;
c2c6d25f 9270 }
c906108c 9271 default:
6d820c5c 9272 if (bc >= *sizeof_buf - 1)
c906108c 9273 {
6d820c5c
DJ
9274 /* Make some more room in the buffer. */
9275 *sizeof_buf *= 2;
224c3ddb 9276 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c 9277 buf = *buf_p;
c906108c
SS
9278 }
9279
6d820c5c
DJ
9280 buf[bc++] = c;
9281 csum += c;
9282 continue;
c906108c
SS
9283 }
9284 }
9285}
9286
9287/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
9288 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9289 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9290 rather than timing out; this is used (in synchronous mode) to wait
9291 for a target that is is executing user code to stop. */
d9fcf2fb
JM
9292/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9293 don't have to change all the calls to getpkt to deal with the
9294 return value, because at the moment I don't know what the right
23860348 9295 thing to do it for those. */
c906108c 9296void
6d820c5c
DJ
9297getpkt (char **buf,
9298 long *sizeof_buf,
c2d11a7d 9299 int forever)
d9fcf2fb 9300{
54887903 9301 getpkt_sane (buf, sizeof_buf, forever);
d9fcf2fb
JM
9302}
9303
9304
9305/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
9306 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9307 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9308 rather than timing out; this is used (in synchronous mode) to wait
9309 for a target that is is executing user code to stop. If FOREVER ==
9310 0, this function is allowed to time out gracefully and return an
74531fed
PA
9311 indication of this to the caller. Otherwise return the number of
9312 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
9313 enough reason to return to the caller. *IS_NOTIF is an output
9314 boolean that indicates whether *BUF holds a notification or not
9315 (a regular packet). */
74531fed 9316
3172dc30 9317static int
74531fed 9318getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 9319 int expecting_notif, int *is_notif)
c906108c 9320{
2d717e4f 9321 struct remote_state *rs = get_remote_state ();
c906108c
SS
9322 int c;
9323 int tries;
9324 int timeout;
df4b58fe 9325 int val = -1;
c906108c 9326
2d717e4f
DJ
9327 /* We're reading a new response. Make sure we don't look at a
9328 previously cached response. */
9329 rs->cached_wait_status = 0;
9330
6d820c5c 9331 strcpy (*buf, "timeout");
c906108c
SS
9332
9333 if (forever)
74531fed
PA
9334 timeout = watchdog > 0 ? watchdog : -1;
9335 else if (expecting_notif)
9336 timeout = 0; /* There should already be a char in the buffer. If
9337 not, bail out. */
c906108c
SS
9338 else
9339 timeout = remote_timeout;
9340
9341#define MAX_TRIES 3
9342
74531fed
PA
9343 /* Process any number of notifications, and then return when
9344 we get a packet. */
9345 for (;;)
c906108c 9346 {
d9c43928 9347 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
9348 times. */
9349 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 9350 {
74531fed
PA
9351 /* This can loop forever if the remote side sends us
9352 characters continuously, but if it pauses, we'll get
9353 SERIAL_TIMEOUT from readchar because of timeout. Then
9354 we'll count that as a retry.
9355
9356 Note that even when forever is set, we will only wait
9357 forever prior to the start of a packet. After that, we
9358 expect characters to arrive at a brisk pace. They should
9359 show up within remote_timeout intervals. */
9360 do
9361 c = readchar (timeout);
9362 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
9363
9364 if (c == SERIAL_TIMEOUT)
9365 {
74531fed
PA
9366 if (expecting_notif)
9367 return -1; /* Don't complain, it's normal to not get
9368 anything in this case. */
9369
23860348 9370 if (forever) /* Watchdog went off? Kill the target. */
c906108c 9371 {
78a095c3 9372 remote_unpush_target ();
598d3636
JK
9373 throw_error (TARGET_CLOSE_ERROR,
9374 _("Watchdog timeout has expired. "
9375 "Target detached."));
c906108c 9376 }
c906108c 9377 if (remote_debug)
0f71a2f6 9378 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 9379 }
74531fed
PA
9380 else
9381 {
9382 /* We've found the start of a packet or notification.
9383 Now collect the data. */
9384 val = read_frame (buf, sizeof_buf);
9385 if (val >= 0)
9386 break;
9387 }
9388
c33e31fd 9389 remote_serial_write ("-", 1);
c906108c 9390 }
c906108c 9391
74531fed
PA
9392 if (tries > MAX_TRIES)
9393 {
9394 /* We have tried hard enough, and just can't receive the
9395 packet/notification. Give up. */
9396 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 9397
74531fed
PA
9398 /* Skip the ack char if we're in no-ack mode. */
9399 if (!rs->noack_mode)
c33e31fd 9400 remote_serial_write ("+", 1);
74531fed
PA
9401 return -1;
9402 }
c906108c 9403
74531fed
PA
9404 /* If we got an ordinary packet, return that to our caller. */
9405 if (c == '$')
c906108c
SS
9406 {
9407 if (remote_debug)
43e526b9 9408 {
6f8976bf
YQ
9409 std::string str
9410 = escape_buffer (*buf,
9411 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9412
9413 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9414 str.c_str ());
9415
567a3e54
SM
9416 if (val > REMOTE_DEBUG_MAX_CHAR)
9417 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9418 val - REMOTE_DEBUG_MAX_CHAR);
6e5abd65 9419
6f8976bf 9420 fprintf_unfiltered (gdb_stdlog, "\n");
43e526b9 9421 }
a6f3e723
SL
9422
9423 /* Skip the ack char if we're in no-ack mode. */
9424 if (!rs->noack_mode)
c33e31fd 9425 remote_serial_write ("+", 1);
fee9eda9
YQ
9426 if (is_notif != NULL)
9427 *is_notif = 0;
0876f84a 9428 return val;
c906108c
SS
9429 }
9430
74531fed
PA
9431 /* If we got a notification, handle it, and go back to looking
9432 for a packet. */
9433 else
9434 {
9435 gdb_assert (c == '%');
9436
9437 if (remote_debug)
9438 {
b3ced9ba 9439 std::string str = escape_buffer (*buf, val);
6e5abd65 9440
6e5abd65
PA
9441 fprintf_unfiltered (gdb_stdlog,
9442 " Notification received: %s\n",
b3ced9ba 9443 str.c_str ());
74531fed 9444 }
fee9eda9
YQ
9445 if (is_notif != NULL)
9446 *is_notif = 1;
c906108c 9447
5965e028 9448 handle_notification (rs->notif_state, *buf);
c906108c 9449
74531fed 9450 /* Notifications require no acknowledgement. */
a6f3e723 9451
74531fed 9452 if (expecting_notif)
fee9eda9 9453 return val;
74531fed
PA
9454 }
9455 }
9456}
9457
9458static int
9459getpkt_sane (char **buf, long *sizeof_buf, int forever)
9460{
fee9eda9 9461 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
9462}
9463
9464static int
fee9eda9
YQ
9465getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9466 int *is_notif)
74531fed 9467{
fee9eda9
YQ
9468 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9469 is_notif);
c906108c 9470}
74531fed 9471
cbb8991c
DB
9472/* Check whether EVENT is a fork event for the process specified
9473 by the pid passed in DATA, and if it is, kill the fork child. */
9474
9475static int
9476kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9477 QUEUE_ITER (stop_reply_p) *iter,
9478 stop_reply_p event,
9479 void *data)
9480{
19ba03f4 9481 struct queue_iter_param *param = (struct queue_iter_param *) data;
cbb8991c
DB
9482 int parent_pid = *(int *) param->input;
9483
9484 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9485 {
9486 struct remote_state *rs = get_remote_state ();
9487 int child_pid = ptid_get_pid (event->ws.value.related_pid);
9488 int res;
9489
9490 res = remote_vkill (child_pid, rs);
9491 if (res != 0)
9492 error (_("Can't kill fork child process %d"), child_pid);
9493 }
9494
9495 return 1;
9496}
9497
9498/* Kill any new fork children of process PID that haven't been
9499 processed by follow_fork. */
9500
9501static void
9502kill_new_fork_children (int pid, struct remote_state *rs)
9503{
9504 struct thread_info *thread;
9505 struct notif_client *notif = &notif_client_stop;
9506 struct queue_iter_param param;
9507
9508 /* Kill the fork child threads of any threads in process PID
9509 that are stopped at a fork event. */
9510 ALL_NON_EXITED_THREADS (thread)
9511 {
9512 struct target_waitstatus *ws = &thread->pending_follow;
9513
9514 if (is_pending_fork_parent (ws, pid, thread->ptid))
9515 {
9516 struct remote_state *rs = get_remote_state ();
9517 int child_pid = ptid_get_pid (ws->value.related_pid);
9518 int res;
9519
9520 res = remote_vkill (child_pid, rs);
9521 if (res != 0)
9522 error (_("Can't kill fork child process %d"), child_pid);
9523 }
9524 }
9525
9526 /* Check for any pending fork events (not reported or processed yet)
9527 in process PID and kill those fork child threads as well. */
9528 remote_notif_get_pending_events (notif);
9529 param.input = &pid;
9530 param.output = NULL;
9531 QUEUE_iterate (stop_reply_p, stop_reply_queue,
9532 kill_child_of_pending_fork, &param);
9533}
9534
c906108c 9535\f
8020350c
DB
9536/* Target hook to kill the current inferior. */
9537
f6ac5f3d
PA
9538void
9539remote_target::kill ()
43ff13b4 9540{
8020350c
DB
9541 int res = -1;
9542 int pid = ptid_get_pid (inferior_ptid);
9543 struct remote_state *rs = get_remote_state ();
0fdf84ca 9544
8020350c 9545 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 9546 {
8020350c
DB
9547 /* If we're stopped while forking and we haven't followed yet,
9548 kill the child task. We need to do this before killing the
9549 parent task because if this is a vfork then the parent will
9550 be sleeping. */
9551 kill_new_fork_children (pid, rs);
9552
9553 res = remote_vkill (pid, rs);
9554 if (res == 0)
0fdf84ca 9555 {
bc1e6c81 9556 target_mourn_inferior (inferior_ptid);
0fdf84ca
PA
9557 return;
9558 }
8020350c 9559 }
0fdf84ca 9560
8020350c
DB
9561 /* If we are in 'target remote' mode and we are killing the only
9562 inferior, then we will tell gdbserver to exit and unpush the
9563 target. */
9564 if (res == -1 && !remote_multi_process_p (rs)
9565 && number_of_live_inferiors () == 1)
9566 {
9567 remote_kill_k ();
9568
9569 /* We've killed the remote end, we get to mourn it. If we are
9570 not in extended mode, mourning the inferior also unpushes
9571 remote_ops from the target stack, which closes the remote
9572 connection. */
bc1e6c81 9573 target_mourn_inferior (inferior_ptid);
8020350c
DB
9574
9575 return;
0fdf84ca 9576 }
43ff13b4 9577
8020350c 9578 error (_("Can't kill process"));
43ff13b4
JM
9579}
9580
8020350c
DB
9581/* Send a kill request to the target using the 'vKill' packet. */
9582
82f73884
PA
9583static int
9584remote_vkill (int pid, struct remote_state *rs)
9585{
4082afcc 9586 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
9587 return -1;
9588
9589 /* Tell the remote target to detach. */
bba74b36 9590 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
9591 putpkt (rs->buf);
9592 getpkt (&rs->buf, &rs->buf_size, 0);
9593
4082afcc
PA
9594 switch (packet_ok (rs->buf,
9595 &remote_protocol_packets[PACKET_vKill]))
9596 {
9597 case PACKET_OK:
9598 return 0;
9599 case PACKET_ERROR:
9600 return 1;
9601 case PACKET_UNKNOWN:
9602 return -1;
9603 default:
9604 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9605 }
82f73884
PA
9606}
9607
8020350c
DB
9608/* Send a kill request to the target using the 'k' packet. */
9609
82f73884 9610static void
8020350c 9611remote_kill_k (void)
82f73884 9612{
8020350c
DB
9613 /* Catch errors so the user can quit from gdb even when we
9614 aren't on speaking terms with the remote system. */
9615 TRY
82f73884 9616 {
82f73884 9617 putpkt ("k");
82f73884 9618 }
8020350c
DB
9619 CATCH (ex, RETURN_MASK_ERROR)
9620 {
9621 if (ex.error == TARGET_CLOSE_ERROR)
9622 {
9623 /* If we got an (EOF) error that caused the target
9624 to go away, then we're done, that's what we wanted.
9625 "k" is susceptible to cause a premature EOF, given
9626 that the remote server isn't actually required to
9627 reply to "k", and it can happen that it doesn't
9628 even get to reply ACK to the "k". */
9629 return;
9630 }
82f73884 9631
8020350c
DB
9632 /* Otherwise, something went wrong. We didn't actually kill
9633 the target. Just propagate the exception, and let the
9634 user or higher layers decide what to do. */
9635 throw_exception (ex);
9636 }
9637 END_CATCH
82f73884
PA
9638}
9639
f6ac5f3d
PA
9640void
9641remote_target::mourn_inferior ()
c906108c 9642{
8020350c 9643 struct remote_state *rs = get_remote_state ();
ce5ce7ed 9644
8020350c
DB
9645 /* In 'target remote' mode with one inferior, we close the connection. */
9646 if (!rs->extended && number_of_live_inferiors () <= 1)
9647 {
f6ac5f3d 9648 unpush_target (this);
c906108c 9649
8020350c
DB
9650 /* remote_close takes care of doing most of the clean up. */
9651 generic_mourn_inferior ();
9652 return;
9653 }
c906108c 9654
e24a49d8
PA
9655 /* In case we got here due to an error, but we're going to stay
9656 connected. */
9657 rs->waiting_for_stop_reply = 0;
9658
dc1981d7
PA
9659 /* If the current general thread belonged to the process we just
9660 detached from or has exited, the remote side current general
9661 thread becomes undefined. Considering a case like this:
9662
9663 - We just got here due to a detach.
9664 - The process that we're detaching from happens to immediately
9665 report a global breakpoint being hit in non-stop mode, in the
9666 same thread we had selected before.
9667 - GDB attaches to this process again.
9668 - This event happens to be the next event we handle.
9669
9670 GDB would consider that the current general thread didn't need to
9671 be set on the stub side (with Hg), since for all it knew,
9672 GENERAL_THREAD hadn't changed.
9673
9674 Notice that although in all-stop mode, the remote server always
9675 sets the current thread to the thread reporting the stop event,
9676 that doesn't happen in non-stop mode; in non-stop, the stub *must
9677 not* change the current thread when reporting a breakpoint hit,
9678 due to the decoupling of event reporting and event handling.
9679
9680 To keep things simple, we always invalidate our notion of the
9681 current thread. */
47f8a51d 9682 record_currthread (rs, minus_one_ptid);
dc1981d7 9683
8020350c 9684 /* Call common code to mark the inferior as not running. */
48aa3c27
PA
9685 generic_mourn_inferior ();
9686
d729566a 9687 if (!have_inferiors ())
2d717e4f 9688 {
82f73884
PA
9689 if (!remote_multi_process_p (rs))
9690 {
9691 /* Check whether the target is running now - some remote stubs
9692 automatically restart after kill. */
9693 putpkt ("?");
9694 getpkt (&rs->buf, &rs->buf_size, 0);
9695
9696 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9697 {
3e43a32a
MS
9698 /* Assume that the target has been restarted. Set
9699 inferior_ptid so that bits of core GDB realizes
9700 there's something here, e.g., so that the user can
9701 say "kill" again. */
82f73884
PA
9702 inferior_ptid = magic_null_ptid;
9703 }
82f73884 9704 }
2d717e4f
DJ
9705 }
9706}
c906108c 9707
57810aa7 9708bool
f6ac5f3d 9709extended_remote_target::supports_disable_randomization ()
03583c20 9710{
4082afcc 9711 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
9712}
9713
9714static void
9715extended_remote_disable_randomization (int val)
9716{
9717 struct remote_state *rs = get_remote_state ();
9718 char *reply;
9719
bba74b36
YQ
9720 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9721 val);
03583c20 9722 putpkt (rs->buf);
b6bb3468 9723 reply = remote_get_noisy_reply ();
03583c20
UW
9724 if (*reply == '\0')
9725 error (_("Target does not support QDisableRandomization."));
9726 if (strcmp (reply, "OK") != 0)
9727 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9728}
9729
2d717e4f 9730static int
7c5ded6a 9731extended_remote_run (const std::string &args)
2d717e4f
DJ
9732{
9733 struct remote_state *rs = get_remote_state ();
2d717e4f 9734 int len;
94585166 9735 const char *remote_exec_file = get_remote_exec_file ();
c906108c 9736
2d717e4f
DJ
9737 /* If the user has disabled vRun support, or we have detected that
9738 support is not available, do not try it. */
4082afcc 9739 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 9740 return -1;
424163ea 9741
2d717e4f
DJ
9742 strcpy (rs->buf, "vRun;");
9743 len = strlen (rs->buf);
c906108c 9744
2d717e4f
DJ
9745 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9746 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
9747 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9748 strlen (remote_exec_file));
2d717e4f 9749
7c5ded6a 9750 if (!args.empty ())
2d717e4f 9751 {
2d717e4f 9752 int i;
2d717e4f 9753
773a1edc 9754 gdb_argv argv (args.c_str ());
2d717e4f
DJ
9755 for (i = 0; argv[i] != NULL; i++)
9756 {
9757 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9758 error (_("Argument list too long for run packet"));
9759 rs->buf[len++] = ';';
9f1b45b0
TT
9760 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9761 strlen (argv[i]));
2d717e4f 9762 }
2d717e4f
DJ
9763 }
9764
9765 rs->buf[len++] = '\0';
9766
9767 putpkt (rs->buf);
9768 getpkt (&rs->buf, &rs->buf_size, 0);
9769
4082afcc 9770 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 9771 {
4082afcc 9772 case PACKET_OK:
3405876a 9773 /* We have a wait response. All is well. */
2d717e4f 9774 return 0;
4082afcc
PA
9775 case PACKET_UNKNOWN:
9776 return -1;
9777 case PACKET_ERROR:
2d717e4f
DJ
9778 if (remote_exec_file[0] == '\0')
9779 error (_("Running the default executable on the remote target failed; "
9780 "try \"set remote exec-file\"?"));
9781 else
9782 error (_("Running \"%s\" on the remote target failed"),
9783 remote_exec_file);
4082afcc
PA
9784 default:
9785 gdb_assert_not_reached (_("bad switch"));
2d717e4f 9786 }
c906108c
SS
9787}
9788
0a2dde4a
SDJ
9789/* Helper function to send set/unset environment packets. ACTION is
9790 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
9791 or "QEnvironmentUnsetVariable". VALUE is the variable to be
9792 sent. */
9793
9794static void
9795send_environment_packet (struct remote_state *rs,
9796 const char *action,
9797 const char *packet,
9798 const char *value)
9799{
9800 /* Convert the environment variable to an hex string, which
9801 is the best format to be transmitted over the wire. */
9802 std::string encoded_value = bin2hex ((const gdb_byte *) value,
9803 strlen (value));
9804
9805 xsnprintf (rs->buf, get_remote_packet_size (),
9806 "%s:%s", packet, encoded_value.c_str ());
9807
9808 putpkt (rs->buf);
9809 getpkt (&rs->buf, &rs->buf_size, 0);
9810 if (strcmp (rs->buf, "OK") != 0)
9811 warning (_("Unable to %s environment variable '%s' on remote."),
9812 action, value);
9813}
9814
9815/* Helper function to handle the QEnvironment* packets. */
9816
9817static void
9818extended_remote_environment_support (struct remote_state *rs)
9819{
9820 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
9821 {
9822 putpkt ("QEnvironmentReset");
9823 getpkt (&rs->buf, &rs->buf_size, 0);
9824 if (strcmp (rs->buf, "OK") != 0)
9825 warning (_("Unable to reset environment on remote."));
9826 }
9827
9828 gdb_environ *e = &current_inferior ()->environment;
9829
9830 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
9831 for (const std::string &el : e->user_set_env ())
9832 send_environment_packet (rs, "set", "QEnvironmentHexEncoded",
9833 el.c_str ());
9834
9835 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
9836 for (const std::string &el : e->user_unset_env ())
9837 send_environment_packet (rs, "unset", "QEnvironmentUnset", el.c_str ());
9838}
9839
bc3b087d
SDJ
9840/* Helper function to set the current working directory for the
9841 inferior in the remote target. */
9842
9843static void
9844extended_remote_set_inferior_cwd (struct remote_state *rs)
9845{
9846 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
9847 {
9848 const char *inferior_cwd = get_inferior_cwd ();
9849
9850 if (inferior_cwd != NULL)
9851 {
9852 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
9853 strlen (inferior_cwd));
9854
9855 xsnprintf (rs->buf, get_remote_packet_size (),
9856 "QSetWorkingDir:%s", hexpath.c_str ());
9857 }
9858 else
9859 {
9860 /* An empty inferior_cwd means that the user wants us to
9861 reset the remote server's inferior's cwd. */
9862 xsnprintf (rs->buf, get_remote_packet_size (),
9863 "QSetWorkingDir:");
9864 }
9865
9866 putpkt (rs->buf);
9867 getpkt (&rs->buf, &rs->buf_size, 0);
9868 if (packet_ok (rs->buf,
9869 &remote_protocol_packets[PACKET_QSetWorkingDir])
9870 != PACKET_OK)
9871 error (_("\
9872Remote replied unexpectedly while setting the inferior's working\n\
9873directory: %s"),
9874 rs->buf);
9875
9876 }
9877}
9878
2d717e4f
DJ
9879/* In the extended protocol we want to be able to do things like
9880 "run" and have them basically work as expected. So we need
9881 a special create_inferior function. We support changing the
9882 executable file and the command line arguments, but not the
9883 environment. */
9884
f6ac5f3d
PA
9885void
9886extended_remote_target::create_inferior (const char *exec_file,
9887 const std::string &args,
9888 char **env, int from_tty)
43ff13b4 9889{
3405876a
PA
9890 int run_worked;
9891 char *stop_reply;
9892 struct remote_state *rs = get_remote_state ();
94585166 9893 const char *remote_exec_file = get_remote_exec_file ();
3405876a 9894
43ff13b4 9895 /* If running asynchronously, register the target file descriptor
23860348 9896 with the event loop. */
75c99385 9897 if (target_can_async_p ())
6a3753b3 9898 target_async (1);
43ff13b4 9899
03583c20 9900 /* Disable address space randomization if requested (and supported). */
f6ac5f3d 9901 if (supports_disable_randomization ())
03583c20
UW
9902 extended_remote_disable_randomization (disable_randomization);
9903
aefd8b33
SDJ
9904 /* If startup-with-shell is on, we inform gdbserver to start the
9905 remote inferior using a shell. */
9906 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
9907 {
9908 xsnprintf (rs->buf, get_remote_packet_size (),
9909 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
9910 putpkt (rs->buf);
9911 getpkt (&rs->buf, &rs->buf_size, 0);
9912 if (strcmp (rs->buf, "OK") != 0)
9913 error (_("\
9914Remote replied unexpectedly while setting startup-with-shell: %s"),
9915 rs->buf);
9916 }
9917
0a2dde4a
SDJ
9918 extended_remote_environment_support (rs);
9919
bc3b087d
SDJ
9920 extended_remote_set_inferior_cwd (rs);
9921
43ff13b4 9922 /* Now restart the remote server. */
3405876a
PA
9923 run_worked = extended_remote_run (args) != -1;
9924 if (!run_worked)
2d717e4f
DJ
9925 {
9926 /* vRun was not supported. Fail if we need it to do what the
9927 user requested. */
9928 if (remote_exec_file[0])
9929 error (_("Remote target does not support \"set remote exec-file\""));
7c5ded6a 9930 if (!args.empty ())
2d717e4f 9931 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 9932
2d717e4f
DJ
9933 /* Fall back to "R". */
9934 extended_remote_restart ();
9935 }
424163ea 9936
6c95b8df
PA
9937 if (!have_inferiors ())
9938 {
9939 /* Clean up from the last time we ran, before we mark the target
9940 running again. This will mark breakpoints uninserted, and
9941 get_offsets may insert breakpoints. */
9942 init_thread_list ();
9943 init_wait_for_inferior ();
9944 }
45280a52 9945
3405876a
PA
9946 /* vRun's success return is a stop reply. */
9947 stop_reply = run_worked ? rs->buf : NULL;
9948 add_current_inferior_and_thread (stop_reply);
c0a2216e 9949
2d717e4f
DJ
9950 /* Get updated offsets, if the stub uses qOffsets. */
9951 get_offsets ();
2d717e4f 9952}
c906108c 9953\f
c5aa993b 9954
b775012e
LM
9955/* Given a location's target info BP_TGT and the packet buffer BUF, output
9956 the list of conditions (in agent expression bytecode format), if any, the
9957 target needs to evaluate. The output is placed into the packet buffer
bba74b36 9958 started from BUF and ended at BUF_END. */
b775012e
LM
9959
9960static int
9961remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
9962 struct bp_target_info *bp_tgt, char *buf,
9963 char *buf_end)
b775012e 9964{
3cde5c42 9965 if (bp_tgt->conditions.empty ())
b775012e
LM
9966 return 0;
9967
9968 buf += strlen (buf);
bba74b36 9969 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
9970 buf++;
9971
83621223 9972 /* Send conditions to the target. */
d538e36d 9973 for (agent_expr *aexpr : bp_tgt->conditions)
b775012e 9974 {
bba74b36 9975 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e 9976 buf += strlen (buf);
3cde5c42 9977 for (int i = 0; i < aexpr->len; ++i)
b775012e
LM
9978 buf = pack_hex_byte (buf, aexpr->buf[i]);
9979 *buf = '\0';
9980 }
b775012e
LM
9981 return 0;
9982}
9983
d3ce09f5
SS
9984static void
9985remote_add_target_side_commands (struct gdbarch *gdbarch,
9986 struct bp_target_info *bp_tgt, char *buf)
9987{
3cde5c42 9988 if (bp_tgt->tcommands.empty ())
d3ce09f5
SS
9989 return;
9990
9991 buf += strlen (buf);
9992
9993 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9994 buf += strlen (buf);
9995
9996 /* Concatenate all the agent expressions that are commands into the
9997 cmds parameter. */
df97be55 9998 for (agent_expr *aexpr : bp_tgt->tcommands)
d3ce09f5
SS
9999 {
10000 sprintf (buf, "X%x,", aexpr->len);
10001 buf += strlen (buf);
3cde5c42 10002 for (int i = 0; i < aexpr->len; ++i)
d3ce09f5
SS
10003 buf = pack_hex_byte (buf, aexpr->buf[i]);
10004 *buf = '\0';
10005 }
d3ce09f5
SS
10006}
10007
8181d85f
DJ
10008/* Insert a breakpoint. On targets that have software breakpoint
10009 support, we ask the remote target to do the work; on targets
10010 which don't, we insert a traditional memory breakpoint. */
c906108c 10011
f6ac5f3d
PA
10012int
10013remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10014 struct bp_target_info *bp_tgt)
c906108c 10015{
d471ea57
AC
10016 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10017 If it succeeds, then set the support to PACKET_ENABLE. If it
10018 fails, and the user has explicitly requested the Z support then
23860348 10019 report an error, otherwise, mark it disabled and go on. */
802188a7 10020
4082afcc 10021 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10022 {
0d5ed153 10023 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10024 struct remote_state *rs;
bba74b36 10025 char *p, *endbuf;
4fff2411 10026
28439a30
PA
10027 /* Make sure the remote is pointing at the right process, if
10028 necessary. */
10029 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10030 set_general_process ();
10031
4fff2411
JZ
10032 rs = get_remote_state ();
10033 p = rs->buf;
bba74b36 10034 endbuf = rs->buf + get_remote_packet_size ();
802188a7 10035
96baa820
JM
10036 *(p++) = 'Z';
10037 *(p++) = '0';
10038 *(p++) = ',';
7c0f6dcc 10039 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 10040 p += hexnumstr (p, addr);
579c6ad9 10041 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10042
f6ac5f3d 10043 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10044 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10045
f6ac5f3d 10046 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10047 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10048
6d820c5c
DJ
10049 putpkt (rs->buf);
10050 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10051
6d820c5c 10052 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 10053 {
d471ea57
AC
10054 case PACKET_ERROR:
10055 return -1;
10056 case PACKET_OK:
10057 return 0;
10058 case PACKET_UNKNOWN:
10059 break;
96baa820
JM
10060 }
10061 }
c906108c 10062
0000e5cc
PA
10063 /* If this breakpoint has target-side commands but this stub doesn't
10064 support Z0 packets, throw error. */
3cde5c42 10065 if (!bp_tgt->tcommands.empty ())
0000e5cc
PA
10066 throw_error (NOT_SUPPORTED_ERROR, _("\
10067Target doesn't support breakpoints that have target side commands."));
10068
f6ac5f3d 10069 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
c906108c
SS
10070}
10071
f6ac5f3d
PA
10072int
10073remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10074 struct bp_target_info *bp_tgt,
10075 enum remove_bp_reason reason)
c906108c 10076{
8181d85f 10077 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 10078 struct remote_state *rs = get_remote_state ();
96baa820 10079
4082afcc 10080 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 10081 {
6d820c5c 10082 char *p = rs->buf;
bba74b36 10083 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 10084
28439a30
PA
10085 /* Make sure the remote is pointing at the right process, if
10086 necessary. */
10087 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10088 set_general_process ();
10089
96baa820
JM
10090 *(p++) = 'z';
10091 *(p++) = '0';
10092 *(p++) = ',';
10093
8181d85f
DJ
10094 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10095 p += hexnumstr (p, addr);
579c6ad9 10096 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 10097
6d820c5c
DJ
10098 putpkt (rs->buf);
10099 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10100
6d820c5c 10101 return (rs->buf[0] == 'E');
96baa820
JM
10102 }
10103
f6ac5f3d 10104 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
c906108c
SS
10105}
10106
f486487f 10107static enum Z_packet_type
d471ea57
AC
10108watchpoint_to_Z_packet (int type)
10109{
10110 switch (type)
10111 {
10112 case hw_write:
bb858e6a 10113 return Z_PACKET_WRITE_WP;
d471ea57
AC
10114 break;
10115 case hw_read:
bb858e6a 10116 return Z_PACKET_READ_WP;
d471ea57
AC
10117 break;
10118 case hw_access:
bb858e6a 10119 return Z_PACKET_ACCESS_WP;
d471ea57
AC
10120 break;
10121 default:
8e65ff28 10122 internal_error (__FILE__, __LINE__,
e2e0b3e5 10123 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
10124 }
10125}
10126
f6ac5f3d
PA
10127int
10128remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10129 enum target_hw_bp_type type, struct expression *cond)
96baa820 10130{
d01949b6 10131 struct remote_state *rs = get_remote_state ();
bba74b36 10132 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 10133 char *p;
d471ea57 10134 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 10135
4082afcc 10136 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 10137 return 1;
802188a7 10138
28439a30
PA
10139 /* Make sure the remote is pointing at the right process, if
10140 necessary. */
10141 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10142 set_general_process ();
10143
bba74b36 10144 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 10145 p = strchr (rs->buf, '\0');
96baa820
JM
10146 addr = remote_address_masked (addr);
10147 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10148 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 10149
6d820c5c
DJ
10150 putpkt (rs->buf);
10151 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10152
6d820c5c 10153 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10154 {
10155 case PACKET_ERROR:
d471ea57 10156 return -1;
85d721b8
PA
10157 case PACKET_UNKNOWN:
10158 return 1;
d471ea57
AC
10159 case PACKET_OK:
10160 return 0;
10161 }
8e65ff28 10162 internal_error (__FILE__, __LINE__,
e2e0b3e5 10163 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
10164}
10165
57810aa7 10166bool
f6ac5f3d
PA
10167remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10168 CORE_ADDR start, int length)
283002cf
MR
10169{
10170 CORE_ADDR diff = remote_address_masked (addr - start);
10171
10172 return diff < length;
10173}
10174
d471ea57 10175
f6ac5f3d
PA
10176int
10177remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10178 enum target_hw_bp_type type, struct expression *cond)
96baa820 10179{
d01949b6 10180 struct remote_state *rs = get_remote_state ();
bba74b36 10181 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 10182 char *p;
d471ea57
AC
10183 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10184
4082afcc 10185 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 10186 return -1;
802188a7 10187
28439a30
PA
10188 /* Make sure the remote is pointing at the right process, if
10189 necessary. */
10190 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10191 set_general_process ();
10192
bba74b36 10193 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 10194 p = strchr (rs->buf, '\0');
96baa820
JM
10195 addr = remote_address_masked (addr);
10196 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10197 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
10198 putpkt (rs->buf);
10199 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10200
6d820c5c 10201 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10202 {
10203 case PACKET_ERROR:
10204 case PACKET_UNKNOWN:
10205 return -1;
10206 case PACKET_OK:
10207 return 0;
10208 }
8e65ff28 10209 internal_error (__FILE__, __LINE__,
e2e0b3e5 10210 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
10211}
10212
3c3bea1c 10213
501eef12 10214int remote_hw_watchpoint_limit = -1;
480a3f21 10215int remote_hw_watchpoint_length_limit = -1;
501eef12 10216int remote_hw_breakpoint_limit = -1;
d471ea57 10217
f6ac5f3d
PA
10218int
10219remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
480a3f21
PW
10220{
10221 if (remote_hw_watchpoint_length_limit == 0)
10222 return 0;
10223 else if (remote_hw_watchpoint_length_limit < 0)
10224 return 1;
10225 else if (len <= remote_hw_watchpoint_length_limit)
10226 return 1;
10227 else
10228 return 0;
10229}
10230
f6ac5f3d
PA
10231int
10232remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
96baa820 10233{
3c3bea1c
GS
10234 if (type == bp_hardware_breakpoint)
10235 {
10236 if (remote_hw_breakpoint_limit == 0)
10237 return 0;
501eef12
AC
10238 else if (remote_hw_breakpoint_limit < 0)
10239 return 1;
3c3bea1c
GS
10240 else if (cnt <= remote_hw_breakpoint_limit)
10241 return 1;
10242 }
10243 else
10244 {
10245 if (remote_hw_watchpoint_limit == 0)
10246 return 0;
501eef12
AC
10247 else if (remote_hw_watchpoint_limit < 0)
10248 return 1;
3c3bea1c
GS
10249 else if (ot)
10250 return -1;
10251 else if (cnt <= remote_hw_watchpoint_limit)
10252 return 1;
10253 }
10254 return -1;
10255}
10256
f7e6eed5
PA
10257/* The to_stopped_by_sw_breakpoint method of target remote. */
10258
57810aa7 10259bool
f6ac5f3d 10260remote_target::stopped_by_sw_breakpoint ()
f7e6eed5 10261{
799a2abe 10262 struct thread_info *thread = inferior_thread ();
f7e6eed5 10263
799a2abe 10264 return (thread->priv != NULL
7aabaf9d
SM
10265 && (get_remote_thread_info (thread)->stop_reason
10266 == TARGET_STOPPED_BY_SW_BREAKPOINT));
f7e6eed5
PA
10267}
10268
10269/* The to_supports_stopped_by_sw_breakpoint method of target
10270 remote. */
10271
57810aa7 10272bool
f6ac5f3d 10273remote_target::supports_stopped_by_sw_breakpoint ()
f7e6eed5 10274{
f7e6eed5
PA
10275 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10276}
10277
10278/* The to_stopped_by_hw_breakpoint method of target remote. */
10279
57810aa7 10280bool
f6ac5f3d 10281remote_target::stopped_by_hw_breakpoint ()
f7e6eed5 10282{
799a2abe 10283 struct thread_info *thread = inferior_thread ();
f7e6eed5 10284
799a2abe 10285 return (thread->priv != NULL
7aabaf9d
SM
10286 && (get_remote_thread_info (thread)->stop_reason
10287 == TARGET_STOPPED_BY_HW_BREAKPOINT));
f7e6eed5
PA
10288}
10289
10290/* The to_supports_stopped_by_hw_breakpoint method of target
10291 remote. */
10292
57810aa7 10293bool
f6ac5f3d 10294remote_target::supports_stopped_by_hw_breakpoint ()
f7e6eed5 10295{
f7e6eed5
PA
10296 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10297}
10298
57810aa7 10299bool
f6ac5f3d 10300remote_target::stopped_by_watchpoint ()
3c3bea1c 10301{
799a2abe 10302 struct thread_info *thread = inferior_thread ();
ee154bee 10303
799a2abe 10304 return (thread->priv != NULL
7aabaf9d
SM
10305 && (get_remote_thread_info (thread)->stop_reason
10306 == TARGET_STOPPED_BY_WATCHPOINT));
3c3bea1c
GS
10307}
10308
57810aa7 10309bool
f6ac5f3d 10310remote_target::stopped_data_address (CORE_ADDR *addr_p)
3c3bea1c 10311{
799a2abe 10312 struct thread_info *thread = inferior_thread ();
a744cf53 10313
799a2abe 10314 if (thread->priv != NULL
7aabaf9d
SM
10315 && (get_remote_thread_info (thread)->stop_reason
10316 == TARGET_STOPPED_BY_WATCHPOINT))
4aa7a7f5 10317 {
7aabaf9d 10318 *addr_p = get_remote_thread_info (thread)->watch_data_address;
57810aa7 10319 return true;
4aa7a7f5
JJ
10320 }
10321
57810aa7 10322 return false;
3c3bea1c
GS
10323}
10324
10325
f6ac5f3d
PA
10326int
10327remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10328 struct bp_target_info *bp_tgt)
3c3bea1c 10329{
0d5ed153 10330 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10331 struct remote_state *rs;
bba74b36 10332 char *p, *endbuf;
dd61ec5c 10333 char *message;
3c3bea1c 10334
4082afcc 10335 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10336 return -1;
2bc416ba 10337
28439a30
PA
10338 /* Make sure the remote is pointing at the right process, if
10339 necessary. */
10340 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10341 set_general_process ();
10342
4fff2411
JZ
10343 rs = get_remote_state ();
10344 p = rs->buf;
bba74b36 10345 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 10346
96baa820
JM
10347 *(p++) = 'Z';
10348 *(p++) = '1';
10349 *(p++) = ',';
802188a7 10350
0d5ed153 10351 addr = remote_address_masked (addr);
96baa820 10352 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10353 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10354
f6ac5f3d 10355 if (supports_evaluation_of_breakpoint_conditions ())
bba74b36 10356 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10357
f6ac5f3d 10358 if (can_run_breakpoint_commands ())
d3ce09f5
SS
10359 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10360
6d820c5c
DJ
10361 putpkt (rs->buf);
10362 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10363
6d820c5c 10364 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10365 {
10366 case PACKET_ERROR:
dd61ec5c
MW
10367 if (rs->buf[1] == '.')
10368 {
10369 message = strchr (rs->buf + 2, '.');
10370 if (message)
0316657e 10371 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
10372 }
10373 return -1;
d471ea57
AC
10374 case PACKET_UNKNOWN:
10375 return -1;
10376 case PACKET_OK:
10377 return 0;
10378 }
8e65ff28 10379 internal_error (__FILE__, __LINE__,
e2e0b3e5 10380 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
10381}
10382
d471ea57 10383
f6ac5f3d
PA
10384int
10385remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10386 struct bp_target_info *bp_tgt)
96baa820 10387{
8181d85f 10388 CORE_ADDR addr;
d01949b6 10389 struct remote_state *rs = get_remote_state ();
6d820c5c 10390 char *p = rs->buf;
bba74b36 10391 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 10392
4082afcc 10393 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10394 return -1;
802188a7 10395
28439a30
PA
10396 /* Make sure the remote is pointing at the right process, if
10397 necessary. */
10398 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10399 set_general_process ();
10400
96baa820
JM
10401 *(p++) = 'z';
10402 *(p++) = '1';
10403 *(p++) = ',';
802188a7 10404
8181d85f 10405 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 10406 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10407 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10408
6d820c5c
DJ
10409 putpkt (rs->buf);
10410 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 10411
6d820c5c 10412 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10413 {
10414 case PACKET_ERROR:
10415 case PACKET_UNKNOWN:
10416 return -1;
10417 case PACKET_OK:
10418 return 0;
10419 }
8e65ff28 10420 internal_error (__FILE__, __LINE__,
e2e0b3e5 10421 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 10422}
96baa820 10423
4a5e7a5b
PA
10424/* Verify memory using the "qCRC:" request. */
10425
f6ac5f3d
PA
10426int
10427remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
4a5e7a5b
PA
10428{
10429 struct remote_state *rs = get_remote_state ();
10430 unsigned long host_crc, target_crc;
10431 char *tmp;
10432
936d2992
PA
10433 /* It doesn't make sense to use qCRC if the remote target is
10434 connected but not running. */
10435 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10436 {
10437 enum packet_result result;
28439a30 10438
936d2992
PA
10439 /* Make sure the remote is pointing at the right process. */
10440 set_general_process ();
4a5e7a5b 10441
936d2992
PA
10442 /* FIXME: assumes lma can fit into long. */
10443 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10444 (long) lma, (long) size);
10445 putpkt (rs->buf);
4a5e7a5b 10446
936d2992
PA
10447 /* Be clever; compute the host_crc before waiting for target
10448 reply. */
10449 host_crc = xcrc32 (data, size, 0xffffffff);
10450
10451 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 10452
936d2992
PA
10453 result = packet_ok (rs->buf,
10454 &remote_protocol_packets[PACKET_qCRC]);
10455 if (result == PACKET_ERROR)
10456 return -1;
10457 else if (result == PACKET_OK)
10458 {
10459 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10460 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 10461
936d2992
PA
10462 return (host_crc == target_crc);
10463 }
10464 }
4a5e7a5b 10465
f6ac5f3d 10466 return simple_verify_memory (this, data, lma, size);
4a5e7a5b
PA
10467}
10468
c906108c
SS
10469/* compare-sections command
10470
10471 With no arguments, compares each loadable section in the exec bfd
10472 with the same memory range on the target, and reports mismatches.
4a5e7a5b 10473 Useful for verifying the image on the target against the exec file. */
e514a9d6 10474
c906108c 10475static void
ac88e2de 10476compare_sections_command (const char *args, int from_tty)
c906108c
SS
10477{
10478 asection *s;
ce359b09 10479 const char *sectname;
c906108c
SS
10480 bfd_size_type size;
10481 bfd_vma lma;
10482 int matched = 0;
10483 int mismatched = 0;
4a5e7a5b 10484 int res;
95cf3b38 10485 int read_only = 0;
c906108c
SS
10486
10487 if (!exec_bfd)
8a3fe4f8 10488 error (_("command cannot be used without an exec file"));
c906108c 10489
28439a30
PA
10490 /* Make sure the remote is pointing at the right process. */
10491 set_general_process ();
10492
95cf3b38
DT
10493 if (args != NULL && strcmp (args, "-r") == 0)
10494 {
10495 read_only = 1;
10496 args = NULL;
10497 }
10498
c5aa993b 10499 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
10500 {
10501 if (!(s->flags & SEC_LOAD))
0df8b418 10502 continue; /* Skip non-loadable section. */
c906108c 10503
95cf3b38
DT
10504 if (read_only && (s->flags & SEC_READONLY) == 0)
10505 continue; /* Skip writeable sections */
10506
2c500098 10507 size = bfd_get_section_size (s);
c906108c 10508 if (size == 0)
0df8b418 10509 continue; /* Skip zero-length section. */
c906108c 10510
ce359b09 10511 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 10512 if (args && strcmp (args, sectname) != 0)
0df8b418 10513 continue; /* Not the section selected by user. */
c906108c 10514
0df8b418 10515 matched = 1; /* Do this section. */
c906108c 10516 lma = s->lma;
c906108c 10517
b80406ac
TT
10518 gdb::byte_vector sectdata (size);
10519 bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
c906108c 10520
b80406ac 10521 res = target_verify_memory (sectdata.data (), lma, size);
4a5e7a5b
PA
10522
10523 if (res == -1)
5af949e3 10524 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
10525 paddress (target_gdbarch (), lma),
10526 paddress (target_gdbarch (), lma + size));
c906108c 10527
5af949e3 10528 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
10529 paddress (target_gdbarch (), lma),
10530 paddress (target_gdbarch (), lma + size));
4a5e7a5b 10531 if (res)
c906108c
SS
10532 printf_filtered ("matched.\n");
10533 else
c5aa993b
JM
10534 {
10535 printf_filtered ("MIS-MATCHED!\n");
10536 mismatched++;
10537 }
c906108c
SS
10538 }
10539 if (mismatched > 0)
936d2992 10540 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 10541the loaded file\n"));
c906108c 10542 if (args && !matched)
a3f17187 10543 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
10544}
10545
0e7f50da
UW
10546/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10547 into remote target. The number of bytes written to the remote
10548 target is returned, or -1 for error. */
10549
9b409511 10550static enum target_xfer_status
f6ac5f3d 10551remote_write_qxfer (const char *object_name,
0e7f50da 10552 const char *annex, const gdb_byte *writebuf,
9b409511 10553 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
10554 struct packet_config *packet)
10555{
10556 int i, buf_len;
10557 ULONGEST n;
0e7f50da
UW
10558 struct remote_state *rs = get_remote_state ();
10559 int max_size = get_memory_write_packet_size ();
10560
7cc244de 10561 if (packet_config_support (packet) == PACKET_DISABLE)
2ed4b548 10562 return TARGET_XFER_E_IO;
0e7f50da
UW
10563
10564 /* Insert header. */
10565 i = snprintf (rs->buf, max_size,
10566 "qXfer:%s:write:%s:%s:",
10567 object_name, annex ? annex : "",
10568 phex_nz (offset, sizeof offset));
10569 max_size -= (i + 1);
10570
10571 /* Escape as much data as fits into rs->buf. */
10572 buf_len = remote_escape_output
124e13d9 10573 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
10574
10575 if (putpkt_binary (rs->buf, i + buf_len) < 0
10576 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10577 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10578 return TARGET_XFER_E_IO;
0e7f50da
UW
10579
10580 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
10581
10582 *xfered_len = n;
92ffd475 10583 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
0e7f50da
UW
10584}
10585
0876f84a
DJ
10586/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10587 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10588 number of bytes read is returned, or 0 for EOF, or -1 for error.
10589 The number of bytes read may be less than LEN without indicating an
10590 EOF. PACKET is checked and updated to indicate whether the remote
10591 target supports this object. */
10592
9b409511 10593static enum target_xfer_status
f6ac5f3d 10594remote_read_qxfer (const char *object_name,
0876f84a
DJ
10595 const char *annex,
10596 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 10597 ULONGEST *xfered_len,
0876f84a
DJ
10598 struct packet_config *packet)
10599{
0876f84a 10600 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
10601 LONGEST i, n, packet_len;
10602
7cc244de 10603 if (packet_config_support (packet) == PACKET_DISABLE)
2ed4b548 10604 return TARGET_XFER_E_IO;
0876f84a
DJ
10605
10606 /* Check whether we've cached an end-of-object packet that matches
10607 this request. */
8e88304f 10608 if (rs->finished_object)
0876f84a 10609 {
8e88304f
TT
10610 if (strcmp (object_name, rs->finished_object) == 0
10611 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10612 && offset == rs->finished_offset)
9b409511
YQ
10613 return TARGET_XFER_EOF;
10614
0876f84a
DJ
10615
10616 /* Otherwise, we're now reading something different. Discard
10617 the cache. */
8e88304f
TT
10618 xfree (rs->finished_object);
10619 xfree (rs->finished_annex);
10620 rs->finished_object = NULL;
10621 rs->finished_annex = NULL;
0876f84a
DJ
10622 }
10623
10624 /* Request only enough to fit in a single packet. The actual data
10625 may not, since we don't know how much of it will need to be escaped;
10626 the target is free to respond with slightly less data. We subtract
10627 five to account for the response type and the protocol frame. */
768adc05 10628 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
0876f84a
DJ
10629 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10630 object_name, annex ? annex : "",
10631 phex_nz (offset, sizeof offset),
10632 phex_nz (n, sizeof n));
10633 i = putpkt (rs->buf);
10634 if (i < 0)
2ed4b548 10635 return TARGET_XFER_E_IO;
0876f84a
DJ
10636
10637 rs->buf[0] = '\0';
10638 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10639 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10640 return TARGET_XFER_E_IO;
0876f84a
DJ
10641
10642 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10643 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10644
10645 /* 'm' means there is (or at least might be) more data after this
10646 batch. That does not make sense unless there's at least one byte
10647 of data in this reply. */
10648 if (rs->buf[0] == 'm' && packet_len == 1)
10649 error (_("Remote qXfer reply contained no data."));
10650
10651 /* Got some data. */
bc20a4af
PA
10652 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10653 packet_len - 1, readbuf, n);
0876f84a
DJ
10654
10655 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
10656 or possibly empty. If we have the final block of a non-empty
10657 object, record this fact to bypass a subsequent partial read. */
10658 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 10659 {
8e88304f
TT
10660 rs->finished_object = xstrdup (object_name);
10661 rs->finished_annex = xstrdup (annex ? annex : "");
10662 rs->finished_offset = offset + i;
0876f84a
DJ
10663 }
10664
9b409511
YQ
10665 if (i == 0)
10666 return TARGET_XFER_EOF;
10667 else
10668 {
10669 *xfered_len = i;
10670 return TARGET_XFER_OK;
10671 }
0876f84a
DJ
10672}
10673
f6ac5f3d
PA
10674enum target_xfer_status
10675remote_target::xfer_partial (enum target_object object,
10676 const char *annex, gdb_byte *readbuf,
10677 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10678 ULONGEST *xfered_len)
c906108c 10679{
82f73884 10680 struct remote_state *rs;
c906108c 10681 int i;
6d820c5c 10682 char *p2;
1e3ff5ad 10683 char query_type;
124e13d9 10684 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 10685
e6e4e701 10686 set_remote_traceframe ();
82f73884
PA
10687 set_general_thread (inferior_ptid);
10688
10689 rs = get_remote_state ();
10690
b2182ed2 10691 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
10692 if (object == TARGET_OBJECT_MEMORY)
10693 {
2d717e4f
DJ
10694 /* If the remote target is connected but not running, we should
10695 pass this request down to a lower stratum (e.g. the executable
10696 file). */
10697 if (!target_has_execution)
9b409511 10698 return TARGET_XFER_EOF;
2d717e4f 10699
21e3b9b9 10700 if (writebuf != NULL)
124e13d9
SM
10701 return remote_write_bytes (offset, writebuf, len, unit_size,
10702 xfered_len);
21e3b9b9 10703 else
f6ac5f3d 10704 return remote_read_bytes (this, offset, readbuf, len, unit_size,
124e13d9 10705 xfered_len);
21e3b9b9
DJ
10706 }
10707
0df8b418 10708 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
10709 if (object == TARGET_OBJECT_SPU)
10710 {
10711 if (readbuf)
f6ac5f3d 10712 return remote_read_qxfer ("spu", annex, readbuf, offset, len,
9b409511
YQ
10713 xfered_len, &remote_protocol_packets
10714 [PACKET_qXfer_spu_read]);
0e7f50da 10715 else
f6ac5f3d 10716 return remote_write_qxfer ("spu", annex, writebuf, offset, len,
9b409511
YQ
10717 xfered_len, &remote_protocol_packets
10718 [PACKET_qXfer_spu_write]);
0e7f50da
UW
10719 }
10720
4aa995e1
PA
10721 /* Handle extra signal info using qxfer packets. */
10722 if (object == TARGET_OBJECT_SIGNAL_INFO)
10723 {
10724 if (readbuf)
f6ac5f3d 10725 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
9b409511 10726 xfered_len, &remote_protocol_packets
4aa995e1
PA
10727 [PACKET_qXfer_siginfo_read]);
10728 else
f6ac5f3d 10729 return remote_write_qxfer ("siginfo", annex,
9b409511 10730 writebuf, offset, len, xfered_len,
4aa995e1
PA
10731 &remote_protocol_packets
10732 [PACKET_qXfer_siginfo_write]);
10733 }
10734
0fb4aa4b
PA
10735 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10736 {
10737 if (readbuf)
f6ac5f3d 10738 return remote_read_qxfer ("statictrace", annex,
9b409511 10739 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
10740 &remote_protocol_packets
10741 [PACKET_qXfer_statictrace_read]);
10742 else
2ed4b548 10743 return TARGET_XFER_E_IO;
0fb4aa4b
PA
10744 }
10745
a76d924d
DJ
10746 /* Only handle flash writes. */
10747 if (writebuf != NULL)
10748 {
a76d924d
DJ
10749 switch (object)
10750 {
10751 case TARGET_OBJECT_FLASH:
f6ac5f3d 10752 return remote_flash_write (this, offset, len, xfered_len,
9b409511 10753 writebuf);
a76d924d
DJ
10754
10755 default:
2ed4b548 10756 return TARGET_XFER_E_IO;
a76d924d
DJ
10757 }
10758 }
4b8a223f 10759
1e3ff5ad
AC
10760 /* Map pre-existing objects onto letters. DO NOT do this for new
10761 objects!!! Instead specify new query packets. */
10762 switch (object)
c906108c 10763 {
1e3ff5ad
AC
10764 case TARGET_OBJECT_AVR:
10765 query_type = 'R';
10766 break;
802188a7
RM
10767
10768 case TARGET_OBJECT_AUXV:
0876f84a 10769 gdb_assert (annex == NULL);
f6ac5f3d 10770 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
9b409511 10771 xfered_len,
0876f84a 10772 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 10773
23181151
DJ
10774 case TARGET_OBJECT_AVAILABLE_FEATURES:
10775 return remote_read_qxfer
f6ac5f3d 10776 ("features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
10777 &remote_protocol_packets[PACKET_qXfer_features]);
10778
cfa9d6d9
DJ
10779 case TARGET_OBJECT_LIBRARIES:
10780 return remote_read_qxfer
f6ac5f3d 10781 ("libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
10782 &remote_protocol_packets[PACKET_qXfer_libraries]);
10783
2268b414
JK
10784 case TARGET_OBJECT_LIBRARIES_SVR4:
10785 return remote_read_qxfer
f6ac5f3d 10786 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
10787 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10788
fd79ecee
DJ
10789 case TARGET_OBJECT_MEMORY_MAP:
10790 gdb_assert (annex == NULL);
f6ac5f3d 10791 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
9b409511 10792 xfered_len,
fd79ecee
DJ
10793 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10794
07e059b5
VP
10795 case TARGET_OBJECT_OSDATA:
10796 /* Should only get here if we're connected. */
5d93a237 10797 gdb_assert (rs->remote_desc);
07e059b5 10798 return remote_read_qxfer
f6ac5f3d 10799 ("osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
10800 &remote_protocol_packets[PACKET_qXfer_osdata]);
10801
dc146f7c
VP
10802 case TARGET_OBJECT_THREADS:
10803 gdb_assert (annex == NULL);
f6ac5f3d 10804 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
9b409511 10805 xfered_len,
dc146f7c
VP
10806 &remote_protocol_packets[PACKET_qXfer_threads]);
10807
b3b9301e
PA
10808 case TARGET_OBJECT_TRACEFRAME_INFO:
10809 gdb_assert (annex == NULL);
10810 return remote_read_qxfer
f6ac5f3d 10811 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 10812 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
10813
10814 case TARGET_OBJECT_FDPIC:
f6ac5f3d 10815 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
9b409511 10816 xfered_len,
78d85199 10817 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
10818
10819 case TARGET_OBJECT_OPENVMS_UIB:
f6ac5f3d 10820 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
9b409511 10821 xfered_len,
169081d0
TG
10822 &remote_protocol_packets[PACKET_qXfer_uib]);
10823
9accd112 10824 case TARGET_OBJECT_BTRACE:
f6ac5f3d 10825 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
9b409511 10826 xfered_len,
9accd112
MM
10827 &remote_protocol_packets[PACKET_qXfer_btrace]);
10828
f4abbc16 10829 case TARGET_OBJECT_BTRACE_CONF:
f6ac5f3d 10830 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
f4abbc16
MM
10831 len, xfered_len,
10832 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10833
c78fa86a 10834 case TARGET_OBJECT_EXEC_FILE:
f6ac5f3d 10835 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
c78fa86a
GB
10836 len, xfered_len,
10837 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10838
1e3ff5ad 10839 default:
2ed4b548 10840 return TARGET_XFER_E_IO;
c906108c
SS
10841 }
10842
0df8b418 10843 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 10844 large enough let the caller deal with it. */
ea9c271d 10845 if (len < get_remote_packet_size ())
2ed4b548 10846 return TARGET_XFER_E_IO;
ea9c271d 10847 len = get_remote_packet_size ();
1e3ff5ad 10848
23860348 10849 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 10850 if (!rs->remote_desc)
8a3fe4f8 10851 error (_("remote query is only available after target open"));
c906108c 10852
1e3ff5ad 10853 gdb_assert (annex != NULL);
4b8a223f 10854 gdb_assert (readbuf != NULL);
c906108c 10855
6d820c5c 10856 p2 = rs->buf;
c906108c
SS
10857 *p2++ = 'q';
10858 *p2++ = query_type;
10859
23860348
MS
10860 /* We used one buffer char for the remote protocol q command and
10861 another for the query type. As the remote protocol encapsulation
10862 uses 4 chars plus one extra in case we are debugging
10863 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10864 string. */
c906108c 10865 i = 0;
ea9c271d 10866 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 10867 {
1e3ff5ad
AC
10868 /* Bad caller may have sent forbidden characters. */
10869 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10870 *p2++ = annex[i];
c906108c
SS
10871 i++;
10872 }
1e3ff5ad
AC
10873 *p2 = '\0';
10874 gdb_assert (annex[i] == '\0');
c906108c 10875
6d820c5c 10876 i = putpkt (rs->buf);
c5aa993b 10877 if (i < 0)
2ed4b548 10878 return TARGET_XFER_E_IO;
c906108c 10879
6d820c5c
DJ
10880 getpkt (&rs->buf, &rs->buf_size, 0);
10881 strcpy ((char *) readbuf, rs->buf);
c906108c 10882
9b409511 10883 *xfered_len = strlen ((char *) readbuf);
92ffd475 10884 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
c906108c
SS
10885}
10886
09c98b44
DB
10887/* Implementation of to_get_memory_xfer_limit. */
10888
f6ac5f3d
PA
10889ULONGEST
10890remote_target::get_memory_xfer_limit ()
09c98b44
DB
10891{
10892 return get_memory_write_packet_size ();
10893}
10894
f6ac5f3d
PA
10895int
10896remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
10897 const gdb_byte *pattern, ULONGEST pattern_len,
10898 CORE_ADDR *found_addrp)
08388c79 10899{
f5656ead 10900 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
10901 struct remote_state *rs = get_remote_state ();
10902 int max_size = get_memory_write_packet_size ();
10903 struct packet_config *packet =
10904 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
10905 /* Number of packet bytes used to encode the pattern;
10906 this could be more than PATTERN_LEN due to escape characters. */
08388c79 10907 int escaped_pattern_len;
0df8b418 10908 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
10909 int used_pattern_len;
10910 int i;
10911 int found;
10912 ULONGEST found_addr;
10913
7cc244de
PA
10914 /* Don't go to the target if we don't have to. This is done before
10915 checking packet_config_support to avoid the possibility that a
10916 success for this edge case means the facility works in
10917 general. */
08388c79
DE
10918 if (pattern_len > search_space_len)
10919 return 0;
10920 if (pattern_len == 0)
10921 {
10922 *found_addrp = start_addr;
10923 return 1;
10924 }
10925
10926 /* If we already know the packet isn't supported, fall back to the simple
10927 way of searching memory. */
10928
4082afcc 10929 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
10930 {
10931 /* Target doesn't provided special support, fall back and use the
10932 standard support (copy memory and do the search here). */
f6ac5f3d 10933 return simple_search_memory (this, start_addr, search_space_len,
08388c79
DE
10934 pattern, pattern_len, found_addrp);
10935 }
10936
28439a30
PA
10937 /* Make sure the remote is pointing at the right process. */
10938 set_general_process ();
10939
08388c79
DE
10940 /* Insert header. */
10941 i = snprintf (rs->buf, max_size,
10942 "qSearch:memory:%s;%s;",
5af949e3 10943 phex_nz (start_addr, addr_size),
08388c79
DE
10944 phex_nz (search_space_len, sizeof (search_space_len)));
10945 max_size -= (i + 1);
10946
10947 /* Escape as much data as fits into rs->buf. */
10948 escaped_pattern_len =
124e13d9 10949 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
10950 &used_pattern_len, max_size);
10951
10952 /* Bail if the pattern is too large. */
10953 if (used_pattern_len != pattern_len)
9b20d036 10954 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
10955
10956 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10957 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10958 || packet_ok (rs->buf, packet) != PACKET_OK)
10959 {
10960 /* The request may not have worked because the command is not
10961 supported. If so, fall back to the simple way. */
7cc244de 10962 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79 10963 {
f6ac5f3d 10964 return simple_search_memory (this, start_addr, search_space_len,
08388c79
DE
10965 pattern, pattern_len, found_addrp);
10966 }
10967 return -1;
10968 }
10969
10970 if (rs->buf[0] == '0')
10971 found = 0;
10972 else if (rs->buf[0] == '1')
10973 {
10974 found = 1;
10975 if (rs->buf[1] != ',')
10e0fa18 10976 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10977 unpack_varlen_hex (rs->buf + 2, &found_addr);
10978 *found_addrp = found_addr;
10979 }
10980 else
10e0fa18 10981 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10982
10983 return found;
10984}
10985
f6ac5f3d
PA
10986void
10987remote_target::rcmd (const char *command, struct ui_file *outbuf)
96baa820 10988{
d01949b6 10989 struct remote_state *rs = get_remote_state ();
2e9f7625 10990 char *p = rs->buf;
96baa820 10991
5d93a237 10992 if (!rs->remote_desc)
8a3fe4f8 10993 error (_("remote rcmd is only available after target open"));
96baa820 10994
23860348 10995 /* Send a NULL command across as an empty command. */
7be570e7
JM
10996 if (command == NULL)
10997 command = "";
10998
23860348 10999 /* The query prefix. */
2e9f7625
DJ
11000 strcpy (rs->buf, "qRcmd,");
11001 p = strchr (rs->buf, '\0');
96baa820 11002
3e43a32a
MS
11003 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
11004 > get_remote_packet_size ())
8a3fe4f8 11005 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 11006
23860348 11007 /* Encode the actual command. */
a30bf1f1 11008 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 11009
6d820c5c 11010 if (putpkt (rs->buf) < 0)
8a3fe4f8 11011 error (_("Communication problem with target."));
96baa820
JM
11012
11013 /* get/display the response */
11014 while (1)
11015 {
2e9f7625
DJ
11016 char *buf;
11017
00bf0b85 11018 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 11019 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 11020 rs->buf[0] = '\0';
5b37825d
PW
11021 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11022 {
11023 /* Timeout. Continue to (try to) read responses.
11024 This is better than stopping with an error, assuming the stub
11025 is still executing the (long) monitor command.
11026 If needed, the user can interrupt gdb using C-c, obtaining
11027 an effect similar to stop on timeout. */
11028 continue;
11029 }
2e9f7625 11030 buf = rs->buf;
96baa820 11031 if (buf[0] == '\0')
8a3fe4f8 11032 error (_("Target does not support this command."));
96baa820
JM
11033 if (buf[0] == 'O' && buf[1] != 'K')
11034 {
23860348 11035 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
11036 continue;
11037 }
11038 if (strcmp (buf, "OK") == 0)
11039 break;
7be570e7
JM
11040 if (strlen (buf) == 3 && buf[0] == 'E'
11041 && isdigit (buf[1]) && isdigit (buf[2]))
11042 {
8a3fe4f8 11043 error (_("Protocol error with Rcmd"));
7be570e7 11044 }
96baa820
JM
11045 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11046 {
11047 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 11048
96baa820
JM
11049 fputc_unfiltered (c, outbuf);
11050 }
11051 break;
11052 }
11053}
11054
f6ac5f3d
PA
11055std::vector<mem_region>
11056remote_target::memory_map ()
fd79ecee 11057{
a664f67e 11058 std::vector<mem_region> result;
9018be22 11059 gdb::optional<gdb::char_vector> text
f6ac5f3d 11060 = target_read_stralloc (target_stack, TARGET_OBJECT_MEMORY_MAP, NULL);
fd79ecee
DJ
11061
11062 if (text)
9018be22 11063 result = parse_memory_map (text->data ());
fd79ecee
DJ
11064
11065 return result;
11066}
11067
c906108c 11068static void
ac88e2de 11069packet_command (const char *args, int from_tty)
c906108c 11070{
d01949b6 11071 struct remote_state *rs = get_remote_state ();
c906108c 11072
5d93a237 11073 if (!rs->remote_desc)
8a3fe4f8 11074 error (_("command can only be used with remote target"));
c906108c 11075
c5aa993b 11076 if (!args)
8a3fe4f8 11077 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
11078
11079 puts_filtered ("sending: ");
11080 print_packet (args);
11081 puts_filtered ("\n");
11082 putpkt (args);
11083
6d820c5c 11084 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 11085 puts_filtered ("received: ");
6d820c5c 11086 print_packet (rs->buf);
c906108c
SS
11087 puts_filtered ("\n");
11088}
11089
11090#if 0
23860348 11091/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 11092
a14ed312 11093static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 11094
a14ed312 11095static void threadset_test_cmd (char *cmd, int tty);
c906108c 11096
a14ed312 11097static void threadalive_test (char *cmd, int tty);
c906108c 11098
a14ed312 11099static void threadlist_test_cmd (char *cmd, int tty);
c906108c 11100
23860348 11101int get_and_display_threadinfo (threadref *ref);
c906108c 11102
a14ed312 11103static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 11104
23860348 11105static int thread_display_step (threadref *ref, void *context);
c906108c 11106
a14ed312 11107static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 11108
a14ed312 11109static void init_remote_threadtests (void);
c906108c 11110
23860348 11111#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
11112
11113static void
0b39b52e 11114threadset_test_cmd (const char *cmd, int tty)
c906108c
SS
11115{
11116 int sample_thread = SAMPLE_THREAD;
11117
a3f17187 11118 printf_filtered (_("Remote threadset test\n"));
79d7f229 11119 set_general_thread (sample_thread);
c906108c
SS
11120}
11121
11122
11123static void
0b39b52e 11124threadalive_test (const char *cmd, int tty)
c906108c
SS
11125{
11126 int sample_thread = SAMPLE_THREAD;
79d7f229 11127 int pid = ptid_get_pid (inferior_ptid);
ba348170 11128 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 11129
79d7f229 11130 if (remote_thread_alive (ptid))
c906108c
SS
11131 printf_filtered ("PASS: Thread alive test\n");
11132 else
11133 printf_filtered ("FAIL: Thread alive test\n");
11134}
11135
23860348 11136void output_threadid (char *title, threadref *ref);
c906108c
SS
11137
11138void
fba45db2 11139output_threadid (char *title, threadref *ref)
c906108c
SS
11140{
11141 char hexid[20];
11142
23860348 11143 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
11144 hexid[16] = 0;
11145 printf_filtered ("%s %s\n", title, (&hexid[0]));
11146}
11147
11148static void
0b39b52e 11149threadlist_test_cmd (const char *cmd, int tty)
c906108c
SS
11150{
11151 int startflag = 1;
11152 threadref nextthread;
11153 int done, result_count;
11154 threadref threadlist[3];
11155
11156 printf_filtered ("Remote Threadlist test\n");
11157 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11158 &result_count, &threadlist[0]))
11159 printf_filtered ("FAIL: threadlist test\n");
11160 else
11161 {
11162 threadref *scan = threadlist;
11163 threadref *limit = scan + result_count;
11164
11165 while (scan < limit)
11166 output_threadid (" thread ", scan++);
11167 }
11168}
11169
11170void
fba45db2 11171display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
11172{
11173 output_threadid ("Threadid: ", &info->threadid);
11174 printf_filtered ("Name: %s\n ", info->shortname);
11175 printf_filtered ("State: %s\n", info->display);
11176 printf_filtered ("other: %s\n\n", info->more_display);
11177}
11178
11179int
fba45db2 11180get_and_display_threadinfo (threadref *ref)
c906108c
SS
11181{
11182 int result;
11183 int set;
11184 struct gdb_ext_thread_info threadinfo;
11185
11186 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11187 | TAG_MOREDISPLAY | TAG_DISPLAY;
11188 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11189 display_thread_info (&threadinfo);
11190 return result;
11191}
11192
11193static void
0b39b52e 11194threadinfo_test_cmd (const char *cmd, int tty)
c906108c
SS
11195{
11196 int athread = SAMPLE_THREAD;
11197 threadref thread;
11198 int set;
11199
11200 int_to_threadref (&thread, athread);
11201 printf_filtered ("Remote Threadinfo test\n");
11202 if (!get_and_display_threadinfo (&thread))
11203 printf_filtered ("FAIL cannot get thread info\n");
11204}
11205
11206static int
fba45db2 11207thread_display_step (threadref *ref, void *context)
c906108c
SS
11208{
11209 /* output_threadid(" threadstep ",ref); *//* simple test */
11210 return get_and_display_threadinfo (ref);
11211}
11212
11213static void
0b39b52e 11214threadlist_update_test_cmd (const char *cmd, int tty)
c906108c
SS
11215{
11216 printf_filtered ("Remote Threadlist update test\n");
11217 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11218}
11219
11220static void
11221init_remote_threadtests (void)
11222{
3e43a32a
MS
11223 add_com ("tlist", class_obscure, threadlist_test_cmd,
11224 _("Fetch and print the remote list of "
11225 "thread identifiers, one pkt only"));
c906108c 11226 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 11227 _("Fetch and display info about one thread"));
c906108c 11228 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 11229 _("Test setting to a different thread"));
c906108c 11230 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 11231 _("Iterate through updating all remote thread info"));
c906108c 11232 add_com ("talive", class_obscure, threadalive_test,
1bedd215 11233 _(" Remote thread alive test "));
c906108c
SS
11234}
11235
11236#endif /* 0 */
11237
f3fb8c85
MS
11238/* Convert a thread ID to a string. Returns the string in a static
11239 buffer. */
11240
f6ac5f3d
PA
11241const char *
11242remote_target::pid_to_str (ptid_t ptid)
f3fb8c85 11243{
79d7f229 11244 static char buf[64];
82f73884 11245 struct remote_state *rs = get_remote_state ();
f3fb8c85 11246
7cee1e54
PA
11247 if (ptid_equal (ptid, null_ptid))
11248 return normal_pid_to_str (ptid);
11249 else if (ptid_is_pid (ptid))
ecd0ada5
PA
11250 {
11251 /* Printing an inferior target id. */
11252
11253 /* When multi-process extensions are off, there's no way in the
11254 remote protocol to know the remote process id, if there's any
11255 at all. There's one exception --- when we're connected with
11256 target extended-remote, and we manually attached to a process
11257 with "attach PID". We don't record anywhere a flag that
11258 allows us to distinguish that case from the case of
11259 connecting with extended-remote and the stub already being
11260 attached to a process, and reporting yes to qAttached, hence
11261 no smart special casing here. */
11262 if (!remote_multi_process_p (rs))
11263 {
11264 xsnprintf (buf, sizeof buf, "Remote target");
11265 return buf;
11266 }
11267
11268 return normal_pid_to_str (ptid);
82f73884 11269 }
ecd0ada5 11270 else
79d7f229 11271 {
ecd0ada5
PA
11272 if (ptid_equal (magic_null_ptid, ptid))
11273 xsnprintf (buf, sizeof buf, "Thread <main>");
8020350c 11274 else if (remote_multi_process_p (rs))
de0d863e
DB
11275 if (ptid_get_lwp (ptid) == 0)
11276 return normal_pid_to_str (ptid);
11277 else
11278 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11279 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
11280 else
11281 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 11282 ptid_get_lwp (ptid));
79d7f229
PA
11283 return buf;
11284 }
f3fb8c85
MS
11285}
11286
38691318
KB
11287/* Get the address of the thread local variable in OBJFILE which is
11288 stored at OFFSET within the thread local storage for thread PTID. */
11289
f6ac5f3d
PA
11290CORE_ADDR
11291remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11292 CORE_ADDR offset)
38691318 11293{
4082afcc 11294 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
11295 {
11296 struct remote_state *rs = get_remote_state ();
6d820c5c 11297 char *p = rs->buf;
82f73884 11298 char *endp = rs->buf + get_remote_packet_size ();
571dd617 11299 enum packet_result result;
38691318
KB
11300
11301 strcpy (p, "qGetTLSAddr:");
11302 p += strlen (p);
82f73884 11303 p = write_ptid (p, endp, ptid);
38691318
KB
11304 *p++ = ',';
11305 p += hexnumstr (p, offset);
11306 *p++ = ',';
11307 p += hexnumstr (p, lm);
11308 *p++ = '\0';
11309
6d820c5c
DJ
11310 putpkt (rs->buf);
11311 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
11312 result = packet_ok (rs->buf,
11313 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 11314 if (result == PACKET_OK)
38691318
KB
11315 {
11316 ULONGEST result;
11317
6d820c5c 11318 unpack_varlen_hex (rs->buf, &result);
38691318
KB
11319 return result;
11320 }
571dd617 11321 else if (result == PACKET_UNKNOWN)
109c3e39
AC
11322 throw_error (TLS_GENERIC_ERROR,
11323 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 11324 else
109c3e39
AC
11325 throw_error (TLS_GENERIC_ERROR,
11326 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
11327 }
11328 else
109c3e39
AC
11329 throw_error (TLS_GENERIC_ERROR,
11330 _("TLS not supported or disabled on this target"));
38691318
KB
11331 /* Not reached. */
11332 return 0;
11333}
11334
711e434b
PM
11335/* Provide thread local base, i.e. Thread Information Block address.
11336 Returns 1 if ptid is found and thread_local_base is non zero. */
11337
57810aa7 11338bool
f6ac5f3d 11339remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
711e434b 11340{
4082afcc 11341 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
11342 {
11343 struct remote_state *rs = get_remote_state ();
11344 char *p = rs->buf;
11345 char *endp = rs->buf + get_remote_packet_size ();
11346 enum packet_result result;
11347
11348 strcpy (p, "qGetTIBAddr:");
11349 p += strlen (p);
11350 p = write_ptid (p, endp, ptid);
11351 *p++ = '\0';
11352
11353 putpkt (rs->buf);
11354 getpkt (&rs->buf, &rs->buf_size, 0);
11355 result = packet_ok (rs->buf,
11356 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11357 if (result == PACKET_OK)
11358 {
11359 ULONGEST result;
11360
11361 unpack_varlen_hex (rs->buf, &result);
11362 if (addr)
11363 *addr = (CORE_ADDR) result;
57810aa7 11364 return true;
711e434b
PM
11365 }
11366 else if (result == PACKET_UNKNOWN)
11367 error (_("Remote target doesn't support qGetTIBAddr packet"));
11368 else
11369 error (_("Remote target failed to process qGetTIBAddr request"));
11370 }
11371 else
11372 error (_("qGetTIBAddr not supported or disabled on this target"));
11373 /* Not reached. */
57810aa7 11374 return false;
711e434b
PM
11375}
11376
29709017
DJ
11377/* Support for inferring a target description based on the current
11378 architecture and the size of a 'g' packet. While the 'g' packet
11379 can have any size (since optional registers can be left off the
11380 end), some sizes are easily recognizable given knowledge of the
11381 approximate architecture. */
11382
11383struct remote_g_packet_guess
11384{
11385 int bytes;
11386 const struct target_desc *tdesc;
11387};
11388typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11389DEF_VEC_O(remote_g_packet_guess_s);
11390
11391struct remote_g_packet_data
11392{
11393 VEC(remote_g_packet_guess_s) *guesses;
11394};
11395
11396static struct gdbarch_data *remote_g_packet_data_handle;
11397
11398static void *
11399remote_g_packet_data_init (struct obstack *obstack)
11400{
11401 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11402}
11403
11404void
11405register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11406 const struct target_desc *tdesc)
11407{
11408 struct remote_g_packet_data *data
19ba03f4
SM
11409 = ((struct remote_g_packet_data *)
11410 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
11411 struct remote_g_packet_guess new_guess, *guess;
11412 int ix;
11413
11414 gdb_assert (tdesc != NULL);
11415
11416 for (ix = 0;
11417 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11418 ix++)
11419 if (guess->bytes == bytes)
11420 internal_error (__FILE__, __LINE__,
9b20d036 11421 _("Duplicate g packet description added for size %d"),
29709017
DJ
11422 bytes);
11423
11424 new_guess.bytes = bytes;
11425 new_guess.tdesc = tdesc;
11426 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11427}
11428
d962ef82
DJ
11429/* Return 1 if remote_read_description would do anything on this target
11430 and architecture, 0 otherwise. */
11431
11432static int
11433remote_read_description_p (struct target_ops *target)
11434{
11435 struct remote_g_packet_data *data
19ba03f4
SM
11436 = ((struct remote_g_packet_data *)
11437 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
11438
11439 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11440 return 1;
11441
11442 return 0;
11443}
11444
f6ac5f3d
PA
11445const struct target_desc *
11446remote_target::read_description ()
29709017
DJ
11447{
11448 struct remote_g_packet_data *data
19ba03f4
SM
11449 = ((struct remote_g_packet_data *)
11450 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 11451
d962ef82
DJ
11452 /* Do not try this during initial connection, when we do not know
11453 whether there is a running but stopped thread. */
11454 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
f6ac5f3d 11455 return beneath->read_description ();
d962ef82 11456
29709017
DJ
11457 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11458 {
11459 struct remote_g_packet_guess *guess;
11460 int ix;
11461 int bytes = send_g_packet ();
11462
11463 for (ix = 0;
11464 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11465 ix++)
11466 if (guess->bytes == bytes)
11467 return guess->tdesc;
11468
11469 /* We discard the g packet. A minor optimization would be to
11470 hold on to it, and fill the register cache once we have selected
11471 an architecture, but it's too tricky to do safely. */
11472 }
11473
f6ac5f3d 11474 return beneath->read_description ();
29709017
DJ
11475}
11476
a6b151f1
DJ
11477/* Remote file transfer support. This is host-initiated I/O, not
11478 target-initiated; for target-initiated, see remote-fileio.c. */
11479
11480/* If *LEFT is at least the length of STRING, copy STRING to
11481 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11482 decrease *LEFT. Otherwise raise an error. */
11483
11484static void
a121b7c1 11485remote_buffer_add_string (char **buffer, int *left, const char *string)
a6b151f1
DJ
11486{
11487 int len = strlen (string);
11488
11489 if (len > *left)
11490 error (_("Packet too long for target."));
11491
11492 memcpy (*buffer, string, len);
11493 *buffer += len;
11494 *left -= len;
11495
11496 /* NUL-terminate the buffer as a convenience, if there is
11497 room. */
11498 if (*left)
11499 **buffer = '\0';
11500}
11501
11502/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11503 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11504 decrease *LEFT. Otherwise raise an error. */
11505
11506static void
11507remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11508 int len)
11509{
11510 if (2 * len > *left)
11511 error (_("Packet too long for target."));
11512
11513 bin2hex (bytes, *buffer, len);
11514 *buffer += 2 * len;
11515 *left -= 2 * len;
11516
11517 /* NUL-terminate the buffer as a convenience, if there is
11518 room. */
11519 if (*left)
11520 **buffer = '\0';
11521}
11522
11523/* If *LEFT is large enough, convert VALUE to hex and add it to
11524 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11525 decrease *LEFT. Otherwise raise an error. */
11526
11527static void
11528remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11529{
11530 int len = hexnumlen (value);
11531
11532 if (len > *left)
11533 error (_("Packet too long for target."));
11534
11535 hexnumstr (*buffer, value);
11536 *buffer += len;
11537 *left -= len;
11538
11539 /* NUL-terminate the buffer as a convenience, if there is
11540 room. */
11541 if (*left)
11542 **buffer = '\0';
11543}
11544
11545/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11546 value, *REMOTE_ERRNO to the remote error number or zero if none
11547 was included, and *ATTACHMENT to point to the start of the annex
11548 if any. The length of the packet isn't needed here; there may
11549 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11550
11551 Return 0 if the packet could be parsed, -1 if it could not. If
11552 -1 is returned, the other variables may not be initialized. */
11553
11554static int
11555remote_hostio_parse_result (char *buffer, int *retcode,
11556 int *remote_errno, char **attachment)
11557{
11558 char *p, *p2;
11559
11560 *remote_errno = 0;
11561 *attachment = NULL;
11562
11563 if (buffer[0] != 'F')
11564 return -1;
11565
11566 errno = 0;
11567 *retcode = strtol (&buffer[1], &p, 16);
11568 if (errno != 0 || p == &buffer[1])
11569 return -1;
11570
11571 /* Check for ",errno". */
11572 if (*p == ',')
11573 {
11574 errno = 0;
11575 *remote_errno = strtol (p + 1, &p2, 16);
11576 if (errno != 0 || p + 1 == p2)
11577 return -1;
11578 p = p2;
11579 }
11580
11581 /* Check for ";attachment". If there is no attachment, the
11582 packet should end here. */
11583 if (*p == ';')
11584 {
11585 *attachment = p + 1;
11586 return 0;
11587 }
11588 else if (*p == '\0')
11589 return 0;
11590 else
11591 return -1;
11592}
11593
11594/* Send a prepared I/O packet to the target and read its response.
11595 The prepared packet is in the global RS->BUF before this function
11596 is called, and the answer is there when we return.
11597
11598 COMMAND_BYTES is the length of the request to send, which may include
11599 binary data. WHICH_PACKET is the packet configuration to check
11600 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11601 is set to the error number and -1 is returned. Otherwise the value
11602 returned by the function is returned.
11603
11604 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11605 attachment is expected; an error will be reported if there's a
11606 mismatch. If one is found, *ATTACHMENT will be set to point into
11607 the packet buffer and *ATTACHMENT_LEN will be set to the
11608 attachment's length. */
11609
11610static int
11611remote_hostio_send_command (int command_bytes, int which_packet,
11612 int *remote_errno, char **attachment,
11613 int *attachment_len)
11614{
11615 struct remote_state *rs = get_remote_state ();
11616 int ret, bytes_read;
11617 char *attachment_tmp;
11618
20db9c52 11619 if (packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
11620 {
11621 *remote_errno = FILEIO_ENOSYS;
11622 return -1;
11623 }
11624
11625 putpkt_binary (rs->buf, command_bytes);
11626 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11627
11628 /* If it timed out, something is wrong. Don't try to parse the
11629 buffer. */
11630 if (bytes_read < 0)
11631 {
11632 *remote_errno = FILEIO_EINVAL;
11633 return -1;
11634 }
11635
11636 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11637 {
11638 case PACKET_ERROR:
11639 *remote_errno = FILEIO_EINVAL;
11640 return -1;
11641 case PACKET_UNKNOWN:
11642 *remote_errno = FILEIO_ENOSYS;
11643 return -1;
11644 case PACKET_OK:
11645 break;
11646 }
11647
11648 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11649 &attachment_tmp))
11650 {
11651 *remote_errno = FILEIO_EINVAL;
11652 return -1;
11653 }
11654
11655 /* Make sure we saw an attachment if and only if we expected one. */
11656 if ((attachment_tmp == NULL && attachment != NULL)
11657 || (attachment_tmp != NULL && attachment == NULL))
11658 {
11659 *remote_errno = FILEIO_EINVAL;
11660 return -1;
11661 }
11662
11663 /* If an attachment was found, it must point into the packet buffer;
11664 work out how many bytes there were. */
11665 if (attachment_tmp != NULL)
11666 {
11667 *attachment = attachment_tmp;
11668 *attachment_len = bytes_read - (*attachment - rs->buf);
11669 }
11670
11671 return ret;
11672}
11673
80152258
PA
11674/* Invalidate the readahead cache. */
11675
11676static void
11677readahead_cache_invalidate (void)
11678{
11679 struct remote_state *rs = get_remote_state ();
11680
11681 rs->readahead_cache.fd = -1;
11682}
11683
11684/* Invalidate the readahead cache if it is holding data for FD. */
11685
11686static void
11687readahead_cache_invalidate_fd (int fd)
11688{
11689 struct remote_state *rs = get_remote_state ();
11690
11691 if (rs->readahead_cache.fd == fd)
11692 rs->readahead_cache.fd = -1;
11693}
11694
15a201c8
GB
11695/* Set the filesystem remote_hostio functions that take FILENAME
11696 arguments will use. Return 0 on success, or -1 if an error
11697 occurs (and set *REMOTE_ERRNO). */
11698
11699static int
11700remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11701{
11702 struct remote_state *rs = get_remote_state ();
11703 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11704 char *p = rs->buf;
11705 int left = get_remote_packet_size () - 1;
11706 char arg[9];
11707 int ret;
11708
11709 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11710 return 0;
11711
11712 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11713 return 0;
11714
11715 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11716
11717 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11718 remote_buffer_add_string (&p, &left, arg);
11719
11720 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11721 remote_errno, NULL, NULL);
11722
11723 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11724 return 0;
11725
11726 if (ret == 0)
11727 rs->fs_pid = required_pid;
11728
11729 return ret;
11730}
11731
12e2a5fd 11732/* Implementation of to_fileio_open. */
a6b151f1
DJ
11733
11734static int
cd897586 11735remote_hostio_open (struct target_ops *self,
07c138c8 11736 struct inferior *inf, const char *filename,
4313b8c0
GB
11737 int flags, int mode, int warn_if_slow,
11738 int *remote_errno)
a6b151f1
DJ
11739{
11740 struct remote_state *rs = get_remote_state ();
11741 char *p = rs->buf;
11742 int left = get_remote_packet_size () - 1;
11743
4313b8c0
GB
11744 if (warn_if_slow)
11745 {
11746 static int warning_issued = 0;
11747
11748 printf_unfiltered (_("Reading %s from remote target...\n"),
11749 filename);
11750
11751 if (!warning_issued)
11752 {
11753 warning (_("File transfers from remote targets can be slow."
11754 " Use \"set sysroot\" to access files locally"
11755 " instead."));
11756 warning_issued = 1;
11757 }
11758 }
11759
15a201c8
GB
11760 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11761 return -1;
11762
a6b151f1
DJ
11763 remote_buffer_add_string (&p, &left, "vFile:open:");
11764
11765 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11766 strlen (filename));
11767 remote_buffer_add_string (&p, &left, ",");
11768
11769 remote_buffer_add_int (&p, &left, flags);
11770 remote_buffer_add_string (&p, &left, ",");
11771
11772 remote_buffer_add_int (&p, &left, mode);
11773
11774 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11775 remote_errno, NULL, NULL);
11776}
11777
f6ac5f3d
PA
11778int
11779remote_target::fileio_open (struct inferior *inf, const char *filename,
11780 int flags, int mode, int warn_if_slow,
11781 int *remote_errno)
11782{
11783 return remote_hostio_open (this, inf, filename, flags, mode, warn_if_slow,
11784 remote_errno);
11785}
11786
12e2a5fd 11787/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
11788
11789static int
0d866f62
TT
11790remote_hostio_pwrite (struct target_ops *self,
11791 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
11792 ULONGEST offset, int *remote_errno)
11793{
11794 struct remote_state *rs = get_remote_state ();
11795 char *p = rs->buf;
11796 int left = get_remote_packet_size ();
11797 int out_len;
11798
80152258
PA
11799 readahead_cache_invalidate_fd (fd);
11800
a6b151f1
DJ
11801 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11802
11803 remote_buffer_add_int (&p, &left, fd);
11804 remote_buffer_add_string (&p, &left, ",");
11805
11806 remote_buffer_add_int (&p, &left, offset);
11807 remote_buffer_add_string (&p, &left, ",");
11808
124e13d9 11809 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
11810 get_remote_packet_size () - (p - rs->buf));
11811
11812 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11813 remote_errno, NULL, NULL);
11814}
11815
f6ac5f3d
PA
11816int
11817remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
11818 ULONGEST offset, int *remote_errno)
11819{
11820 return remote_hostio_pwrite (this, fd, write_buf, len, offset, remote_errno);
11821}
11822
80152258
PA
11823/* Helper for the implementation of to_fileio_pread. Read the file
11824 from the remote side with vFile:pread. */
a6b151f1
DJ
11825
11826static int
80152258
PA
11827remote_hostio_pread_vFile (struct target_ops *self,
11828 int fd, gdb_byte *read_buf, int len,
11829 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
11830{
11831 struct remote_state *rs = get_remote_state ();
11832 char *p = rs->buf;
11833 char *attachment;
11834 int left = get_remote_packet_size ();
11835 int ret, attachment_len;
11836 int read_len;
11837
11838 remote_buffer_add_string (&p, &left, "vFile:pread:");
11839
11840 remote_buffer_add_int (&p, &left, fd);
11841 remote_buffer_add_string (&p, &left, ",");
11842
11843 remote_buffer_add_int (&p, &left, len);
11844 remote_buffer_add_string (&p, &left, ",");
11845
11846 remote_buffer_add_int (&p, &left, offset);
11847
11848 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11849 remote_errno, &attachment,
11850 &attachment_len);
11851
11852 if (ret < 0)
11853 return ret;
11854
bc20a4af 11855 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
11856 read_buf, len);
11857 if (read_len != ret)
11858 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11859
11860 return ret;
11861}
11862
80152258
PA
11863/* Serve pread from the readahead cache. Returns number of bytes
11864 read, or 0 if the request can't be served from the cache. */
11865
11866static int
11867remote_hostio_pread_from_cache (struct remote_state *rs,
11868 int fd, gdb_byte *read_buf, size_t len,
11869 ULONGEST offset)
11870{
11871 struct readahead_cache *cache = &rs->readahead_cache;
11872
11873 if (cache->fd == fd
11874 && cache->offset <= offset
11875 && offset < cache->offset + cache->bufsize)
11876 {
11877 ULONGEST max = cache->offset + cache->bufsize;
11878
11879 if (offset + len > max)
11880 len = max - offset;
11881
11882 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11883 return len;
11884 }
11885
11886 return 0;
11887}
11888
11889/* Implementation of to_fileio_pread. */
11890
11891static int
11892remote_hostio_pread (struct target_ops *self,
11893 int fd, gdb_byte *read_buf, int len,
11894 ULONGEST offset, int *remote_errno)
11895{
11896 int ret;
11897 struct remote_state *rs = get_remote_state ();
11898 struct readahead_cache *cache = &rs->readahead_cache;
11899
11900 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11901 if (ret > 0)
11902 {
11903 cache->hit_count++;
11904
11905 if (remote_debug)
11906 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11907 pulongest (cache->hit_count));
11908 return ret;
11909 }
11910
11911 cache->miss_count++;
11912 if (remote_debug)
11913 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11914 pulongest (cache->miss_count));
11915
11916 cache->fd = fd;
11917 cache->offset = offset;
11918 cache->bufsize = get_remote_packet_size ();
224c3ddb 11919 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258
PA
11920
11921 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11922 cache->offset, remote_errno);
11923 if (ret <= 0)
11924 {
11925 readahead_cache_invalidate_fd (fd);
11926 return ret;
11927 }
11928
11929 cache->bufsize = ret;
11930 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11931}
11932
f6ac5f3d
PA
11933int
11934remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
11935 ULONGEST offset, int *remote_errno)
11936{
11937 return remote_hostio_pread (this, fd, read_buf, len, offset, remote_errno);
11938}
11939
12e2a5fd 11940/* Implementation of to_fileio_close. */
a6b151f1
DJ
11941
11942static int
df39ea25 11943remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
11944{
11945 struct remote_state *rs = get_remote_state ();
11946 char *p = rs->buf;
11947 int left = get_remote_packet_size () - 1;
11948
80152258
PA
11949 readahead_cache_invalidate_fd (fd);
11950
a6b151f1
DJ
11951 remote_buffer_add_string (&p, &left, "vFile:close:");
11952
11953 remote_buffer_add_int (&p, &left, fd);
11954
11955 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11956 remote_errno, NULL, NULL);
11957}
11958
f6ac5f3d
PA
11959int
11960remote_target::fileio_close (int fd, int *remote_errno)
11961{
11962 return remote_hostio_close (this, fd, remote_errno);
11963}
11964
12e2a5fd 11965/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
11966
11967static int
dbbca37d 11968remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
11969 struct inferior *inf, const char *filename,
11970 int *remote_errno)
a6b151f1
DJ
11971{
11972 struct remote_state *rs = get_remote_state ();
11973 char *p = rs->buf;
11974 int left = get_remote_packet_size () - 1;
11975
15a201c8
GB
11976 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11977 return -1;
11978
a6b151f1
DJ
11979 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11980
11981 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11982 strlen (filename));
11983
11984 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11985 remote_errno, NULL, NULL);
11986}
11987
f6ac5f3d
PA
11988int
11989remote_target::fileio_unlink (struct inferior *inf, const char *filename,
11990 int *remote_errno)
11991{
11992 return remote_hostio_unlink (this, inf, filename, remote_errno);
11993}
11994
12e2a5fd 11995/* Implementation of to_fileio_readlink. */
b9e7b9c3 11996
f6ac5f3d
PA
11997gdb::optional<std::string>
11998remote_target::fileio_readlink (struct inferior *inf, const char *filename,
11999 int *remote_errno)
b9e7b9c3
UW
12000{
12001 struct remote_state *rs = get_remote_state ();
12002 char *p = rs->buf;
12003 char *attachment;
12004 int left = get_remote_packet_size ();
12005 int len, attachment_len;
12006 int read_len;
b9e7b9c3 12007
15a201c8 12008 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
e0d3522b 12009 return {};
15a201c8 12010
b9e7b9c3
UW
12011 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12012
12013 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12014 strlen (filename));
12015
12016 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12017 remote_errno, &attachment,
12018 &attachment_len);
12019
12020 if (len < 0)
e0d3522b 12021 return {};
b9e7b9c3 12022
e0d3522b 12023 std::string ret (len, '\0');
b9e7b9c3 12024
bc20a4af 12025 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
e0d3522b 12026 (gdb_byte *) &ret[0], len);
b9e7b9c3
UW
12027 if (read_len != len)
12028 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12029
b9e7b9c3
UW
12030 return ret;
12031}
12032
12e2a5fd 12033/* Implementation of to_fileio_fstat. */
0a93529c 12034
f6ac5f3d
PA
12035int
12036remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
0a93529c
GB
12037{
12038 struct remote_state *rs = get_remote_state ();
12039 char *p = rs->buf;
12040 int left = get_remote_packet_size ();
12041 int attachment_len, ret;
12042 char *attachment;
12043 struct fio_stat fst;
12044 int read_len;
12045
464b0089
GB
12046 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12047
12048 remote_buffer_add_int (&p, &left, fd);
12049
12050 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12051 remote_errno, &attachment,
12052 &attachment_len);
12053 if (ret < 0)
0a93529c 12054 {
464b0089
GB
12055 if (*remote_errno != FILEIO_ENOSYS)
12056 return ret;
12057
0a93529c
GB
12058 /* Strictly we should return -1, ENOSYS here, but when
12059 "set sysroot remote:" was implemented in August 2008
12060 BFD's need for a stat function was sidestepped with
12061 this hack. This was not remedied until March 2015
12062 so we retain the previous behavior to avoid breaking
12063 compatibility.
12064
12065 Note that the memset is a March 2015 addition; older
12066 GDBs set st_size *and nothing else* so the structure
12067 would have garbage in all other fields. This might
12068 break something but retaining the previous behavior
12069 here would be just too wrong. */
12070
12071 memset (st, 0, sizeof (struct stat));
12072 st->st_size = INT_MAX;
12073 return 0;
12074 }
12075
0a93529c
GB
12076 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12077 (gdb_byte *) &fst, sizeof (fst));
12078
12079 if (read_len != ret)
12080 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12081
12082 if (read_len != sizeof (fst))
12083 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12084 read_len, (int) sizeof (fst));
12085
12086 remote_fileio_to_host_stat (&fst, st);
12087
12088 return 0;
12089}
12090
12e2a5fd 12091/* Implementation of to_filesystem_is_local. */
e3dd7556 12092
57810aa7 12093bool
f6ac5f3d 12094remote_target::filesystem_is_local ()
e3dd7556
GB
12095{
12096 /* Valgrind GDB presents itself as a remote target but works
12097 on the local filesystem: it does not implement remote get
12098 and users are not expected to set a sysroot. To handle
12099 this case we treat the remote filesystem as local if the
12100 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12101 does not support vFile:open. */
a3be80c3 12102 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
12103 {
12104 enum packet_support ps = packet_support (PACKET_vFile_open);
12105
12106 if (ps == PACKET_SUPPORT_UNKNOWN)
12107 {
12108 int fd, remote_errno;
12109
12110 /* Try opening a file to probe support. The supplied
12111 filename is irrelevant, we only care about whether
12112 the stub recognizes the packet or not. */
f6ac5f3d 12113 fd = remote_hostio_open (this, NULL, "just probing",
4313b8c0 12114 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
12115 &remote_errno);
12116
12117 if (fd >= 0)
f6ac5f3d 12118 remote_hostio_close (this, fd, &remote_errno);
e3dd7556
GB
12119
12120 ps = packet_support (PACKET_vFile_open);
12121 }
12122
12123 if (ps == PACKET_DISABLE)
12124 {
12125 static int warning_issued = 0;
12126
12127 if (!warning_issued)
12128 {
12129 warning (_("remote target does not support file"
12130 " transfer, attempting to access files"
12131 " from local filesystem."));
12132 warning_issued = 1;
12133 }
12134
57810aa7 12135 return true;
e3dd7556
GB
12136 }
12137 }
12138
57810aa7 12139 return false;
e3dd7556
GB
12140}
12141
a6b151f1
DJ
12142static int
12143remote_fileio_errno_to_host (int errnum)
12144{
12145 switch (errnum)
12146 {
12147 case FILEIO_EPERM:
12148 return EPERM;
12149 case FILEIO_ENOENT:
12150 return ENOENT;
12151 case FILEIO_EINTR:
12152 return EINTR;
12153 case FILEIO_EIO:
12154 return EIO;
12155 case FILEIO_EBADF:
12156 return EBADF;
12157 case FILEIO_EACCES:
12158 return EACCES;
12159 case FILEIO_EFAULT:
12160 return EFAULT;
12161 case FILEIO_EBUSY:
12162 return EBUSY;
12163 case FILEIO_EEXIST:
12164 return EEXIST;
12165 case FILEIO_ENODEV:
12166 return ENODEV;
12167 case FILEIO_ENOTDIR:
12168 return ENOTDIR;
12169 case FILEIO_EISDIR:
12170 return EISDIR;
12171 case FILEIO_EINVAL:
12172 return EINVAL;
12173 case FILEIO_ENFILE:
12174 return ENFILE;
12175 case FILEIO_EMFILE:
12176 return EMFILE;
12177 case FILEIO_EFBIG:
12178 return EFBIG;
12179 case FILEIO_ENOSPC:
12180 return ENOSPC;
12181 case FILEIO_ESPIPE:
12182 return ESPIPE;
12183 case FILEIO_EROFS:
12184 return EROFS;
12185 case FILEIO_ENOSYS:
12186 return ENOSYS;
12187 case FILEIO_ENAMETOOLONG:
12188 return ENAMETOOLONG;
12189 }
12190 return -1;
12191}
12192
12193static char *
12194remote_hostio_error (int errnum)
12195{
12196 int host_error = remote_fileio_errno_to_host (errnum);
12197
12198 if (host_error == -1)
12199 error (_("Unknown remote I/O error %d"), errnum);
12200 else
12201 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12202}
12203
a6b151f1
DJ
12204static void
12205remote_hostio_close_cleanup (void *opaque)
12206{
12207 int fd = *(int *) opaque;
12208 int remote_errno;
12209
df39ea25 12210 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
12211}
12212
12213void
12214remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12215{
12216 struct cleanup *back_to, *close_cleanup;
12217 int retcode, fd, remote_errno, bytes, io_size;
a6b151f1
DJ
12218 gdb_byte *buffer;
12219 int bytes_in_buffer;
12220 int saw_eof;
12221 ULONGEST offset;
5d93a237 12222 struct remote_state *rs = get_remote_state ();
a6b151f1 12223
5d93a237 12224 if (!rs->remote_desc)
a6b151f1
DJ
12225 error (_("command can only be used with remote target"));
12226
d419f42d 12227 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
12228 if (file == NULL)
12229 perror_with_name (local_file);
a6b151f1 12230
07c138c8 12231 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 12232 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1 12233 | FILEIO_O_TRUNC),
4313b8c0 12234 0700, 0, &remote_errno);
a6b151f1
DJ
12235 if (fd == -1)
12236 remote_hostio_error (remote_errno);
12237
12238 /* Send up to this many bytes at once. They won't all fit in the
12239 remote packet limit, so we'll transfer slightly fewer. */
12240 io_size = get_remote_packet_size ();
224c3ddb 12241 buffer = (gdb_byte *) xmalloc (io_size);
d419f42d 12242 back_to = make_cleanup (xfree, buffer);
a6b151f1
DJ
12243
12244 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12245
12246 bytes_in_buffer = 0;
12247 saw_eof = 0;
12248 offset = 0;
12249 while (bytes_in_buffer || !saw_eof)
12250 {
12251 if (!saw_eof)
12252 {
3e43a32a
MS
12253 bytes = fread (buffer + bytes_in_buffer, 1,
12254 io_size - bytes_in_buffer,
d419f42d 12255 file.get ());
a6b151f1
DJ
12256 if (bytes == 0)
12257 {
d419f42d 12258 if (ferror (file.get ()))
a6b151f1
DJ
12259 error (_("Error reading %s."), local_file);
12260 else
12261 {
12262 /* EOF. Unless there is something still in the
12263 buffer from the last iteration, we are done. */
12264 saw_eof = 1;
12265 if (bytes_in_buffer == 0)
12266 break;
12267 }
12268 }
12269 }
12270 else
12271 bytes = 0;
12272
12273 bytes += bytes_in_buffer;
12274 bytes_in_buffer = 0;
12275
0d866f62
TT
12276 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
12277 fd, buffer, bytes,
3e43a32a 12278 offset, &remote_errno);
a6b151f1
DJ
12279
12280 if (retcode < 0)
12281 remote_hostio_error (remote_errno);
12282 else if (retcode == 0)
12283 error (_("Remote write of %d bytes returned 0!"), bytes);
12284 else if (retcode < bytes)
12285 {
12286 /* Short write. Save the rest of the read data for the next
12287 write. */
12288 bytes_in_buffer = bytes - retcode;
12289 memmove (buffer, buffer + retcode, bytes_in_buffer);
12290 }
12291
12292 offset += retcode;
12293 }
12294
12295 discard_cleanups (close_cleanup);
df39ea25 12296 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
12297 remote_hostio_error (remote_errno);
12298
12299 if (from_tty)
12300 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12301 do_cleanups (back_to);
12302}
12303
12304void
12305remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12306{
12307 struct cleanup *back_to, *close_cleanup;
cea39f65 12308 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
12309 gdb_byte *buffer;
12310 ULONGEST offset;
5d93a237 12311 struct remote_state *rs = get_remote_state ();
a6b151f1 12312
5d93a237 12313 if (!rs->remote_desc)
a6b151f1
DJ
12314 error (_("command can only be used with remote target"));
12315
07c138c8 12316 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
4313b8c0
GB
12317 remote_file, FILEIO_O_RDONLY, 0, 0,
12318 &remote_errno);
a6b151f1
DJ
12319 if (fd == -1)
12320 remote_hostio_error (remote_errno);
12321
d419f42d 12322 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
12323 if (file == NULL)
12324 perror_with_name (local_file);
a6b151f1
DJ
12325
12326 /* Send up to this many bytes at once. They won't all fit in the
12327 remote packet limit, so we'll transfer slightly fewer. */
12328 io_size = get_remote_packet_size ();
224c3ddb 12329 buffer = (gdb_byte *) xmalloc (io_size);
d419f42d 12330 back_to = make_cleanup (xfree, buffer);
a6b151f1
DJ
12331
12332 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12333
12334 offset = 0;
12335 while (1)
12336 {
a3be983c
TT
12337 bytes = remote_hostio_pread (find_target_at (process_stratum),
12338 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
12339 if (bytes == 0)
12340 /* Success, but no bytes, means end-of-file. */
12341 break;
12342 if (bytes == -1)
12343 remote_hostio_error (remote_errno);
12344
12345 offset += bytes;
12346
d419f42d 12347 bytes = fwrite (buffer, 1, bytes, file.get ());
a6b151f1
DJ
12348 if (bytes == 0)
12349 perror_with_name (local_file);
12350 }
12351
12352 discard_cleanups (close_cleanup);
df39ea25 12353 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
12354 remote_hostio_error (remote_errno);
12355
12356 if (from_tty)
12357 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12358 do_cleanups (back_to);
12359}
12360
12361void
12362remote_file_delete (const char *remote_file, int from_tty)
12363{
12364 int retcode, remote_errno;
5d93a237 12365 struct remote_state *rs = get_remote_state ();
a6b151f1 12366
5d93a237 12367 if (!rs->remote_desc)
a6b151f1
DJ
12368 error (_("command can only be used with remote target"));
12369
dbbca37d 12370 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 12371 NULL, remote_file, &remote_errno);
a6b151f1
DJ
12372 if (retcode == -1)
12373 remote_hostio_error (remote_errno);
12374
12375 if (from_tty)
12376 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12377}
12378
12379static void
ac88e2de 12380remote_put_command (const char *args, int from_tty)
a6b151f1 12381{
d1a41061
PP
12382 if (args == NULL)
12383 error_no_arg (_("file to put"));
12384
773a1edc 12385 gdb_argv argv (args);
a6b151f1
DJ
12386 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12387 error (_("Invalid parameters to remote put"));
12388
12389 remote_file_put (argv[0], argv[1], from_tty);
a6b151f1
DJ
12390}
12391
12392static void
ac88e2de 12393remote_get_command (const char *args, int from_tty)
a6b151f1 12394{
d1a41061
PP
12395 if (args == NULL)
12396 error_no_arg (_("file to get"));
12397
773a1edc 12398 gdb_argv argv (args);
a6b151f1
DJ
12399 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12400 error (_("Invalid parameters to remote get"));
12401
12402 remote_file_get (argv[0], argv[1], from_tty);
a6b151f1
DJ
12403}
12404
12405static void
ac88e2de 12406remote_delete_command (const char *args, int from_tty)
a6b151f1 12407{
d1a41061
PP
12408 if (args == NULL)
12409 error_no_arg (_("file to delete"));
12410
773a1edc 12411 gdb_argv argv (args);
a6b151f1
DJ
12412 if (argv[0] == NULL || argv[1] != NULL)
12413 error (_("Invalid parameters to remote delete"));
12414
12415 remote_file_delete (argv[0], from_tty);
a6b151f1
DJ
12416}
12417
12418static void
981a3fb3 12419remote_command (const char *args, int from_tty)
a6b151f1 12420{
635c7e8a 12421 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
12422}
12423
57810aa7 12424bool
f6ac5f3d 12425remote_target::can_execute_reverse ()
b2175913 12426{
4082afcc
PA
12427 if (packet_support (PACKET_bs) == PACKET_ENABLE
12428 || packet_support (PACKET_bc) == PACKET_ENABLE)
57810aa7 12429 return true;
40ab02ce 12430 else
57810aa7 12431 return false;
b2175913
MS
12432}
12433
57810aa7 12434bool
f6ac5f3d 12435remote_target::supports_non_stop ()
74531fed 12436{
57810aa7 12437 return true;
74531fed
PA
12438}
12439
57810aa7 12440bool
f6ac5f3d 12441remote_target::supports_disable_randomization ()
03583c20
UW
12442{
12443 /* Only supported in extended mode. */
57810aa7 12444 return false;
03583c20
UW
12445}
12446
57810aa7 12447bool
f6ac5f3d 12448remote_target::supports_multi_process ()
8a305172
PA
12449{
12450 struct remote_state *rs = get_remote_state ();
a744cf53 12451
8020350c 12452 return remote_multi_process_p (rs);
8a305172
PA
12453}
12454
70221824 12455static int
f6ac5f3d 12456remote_supports_cond_tracepoints ()
782b2b07 12457{
4082afcc 12458 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
12459}
12460
57810aa7 12461bool
f6ac5f3d 12462remote_target::supports_evaluation_of_breakpoint_conditions ()
3788aec7 12463{
4082afcc 12464 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
12465}
12466
70221824 12467static int
f6ac5f3d 12468remote_supports_fast_tracepoints ()
7a697b8d 12469{
4082afcc 12470 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
12471}
12472
0fb4aa4b 12473static int
f6ac5f3d 12474remote_supports_static_tracepoints ()
0fb4aa4b 12475{
4082afcc 12476 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
12477}
12478
1e4d1764 12479static int
f6ac5f3d 12480remote_supports_install_in_trace ()
1e4d1764 12481{
4082afcc 12482 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
12483}
12484
57810aa7 12485bool
f6ac5f3d 12486remote_target::supports_enable_disable_tracepoint ()
d248b706 12487{
4082afcc
PA
12488 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12489 == PACKET_ENABLE);
d248b706
KY
12490}
12491
57810aa7 12492bool
f6ac5f3d 12493remote_target::supports_string_tracing ()
3065dfb6 12494{
4082afcc 12495 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
12496}
12497
57810aa7 12498bool
f6ac5f3d 12499remote_target::can_run_breakpoint_commands ()
d3ce09f5 12500{
4082afcc 12501 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
12502}
12503
f6ac5f3d
PA
12504void
12505remote_target::trace_init ()
35b1e5cc 12506{
b6bb3468
PA
12507 struct remote_state *rs = get_remote_state ();
12508
35b1e5cc 12509 putpkt ("QTinit");
b6bb3468
PA
12510 remote_get_noisy_reply ();
12511 if (strcmp (rs->buf, "OK") != 0)
35b1e5cc
SS
12512 error (_("Target does not support this command."));
12513}
12514
409873ef
SS
12515/* Recursive routine to walk through command list including loops, and
12516 download packets for each command. */
12517
12518static void
12519remote_download_command_source (int num, ULONGEST addr,
12520 struct command_line *cmds)
12521{
12522 struct remote_state *rs = get_remote_state ();
12523 struct command_line *cmd;
12524
12525 for (cmd = cmds; cmd; cmd = cmd->next)
12526 {
0df8b418 12527 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
12528 strcpy (rs->buf, "QTDPsrc:");
12529 encode_source_string (num, addr, "cmd", cmd->line,
12530 rs->buf + strlen (rs->buf),
12531 rs->buf_size - strlen (rs->buf));
12532 putpkt (rs->buf);
b6bb3468
PA
12533 remote_get_noisy_reply ();
12534 if (strcmp (rs->buf, "OK"))
409873ef
SS
12535 warning (_("Target does not support source download."));
12536
12537 if (cmd->control_type == while_control
12538 || cmd->control_type == while_stepping_control)
12539 {
12973681 12540 remote_download_command_source (num, addr, cmd->body_list_0.get ());
409873ef 12541
0df8b418 12542 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
12543 strcpy (rs->buf, "QTDPsrc:");
12544 encode_source_string (num, addr, "cmd", "end",
12545 rs->buf + strlen (rs->buf),
12546 rs->buf_size - strlen (rs->buf));
12547 putpkt (rs->buf);
b6bb3468
PA
12548 remote_get_noisy_reply ();
12549 if (strcmp (rs->buf, "OK"))
409873ef
SS
12550 warning (_("Target does not support source download."));
12551 }
12552 }
12553}
12554
f6ac5f3d
PA
12555void
12556remote_target::download_tracepoint (struct bp_location *loc)
35b1e5cc 12557{
bba74b36 12558#define BUF_SIZE 2048
e8ba3115 12559
35b1e5cc 12560 CORE_ADDR tpaddr;
409873ef 12561 char addrbuf[40];
bba74b36 12562 char buf[BUF_SIZE];
b44ec619
SM
12563 std::vector<std::string> tdp_actions;
12564 std::vector<std::string> stepping_actions;
35b1e5cc 12565 char *pkt;
e8ba3115 12566 struct breakpoint *b = loc->owner;
d9b3f62e 12567 struct tracepoint *t = (struct tracepoint *) b;
b6bb3468 12568 struct remote_state *rs = get_remote_state ();
35b1e5cc 12569
dc673c81 12570 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
12571
12572 tpaddr = loc->address;
12573 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
12574 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12575 addrbuf, /* address */
12576 (b->enable_state == bp_enabled ? 'E' : 'D'),
12577 t->step_count, t->pass_count);
e8ba3115
YQ
12578 /* Fast tracepoints are mostly handled by the target, but we can
12579 tell the target how big of an instruction block should be moved
12580 around. */
12581 if (b->type == bp_fast_tracepoint)
12582 {
12583 /* Only test for support at download time; we may not know
12584 target capabilities at definition time. */
12585 if (remote_supports_fast_tracepoints ())
35b1e5cc 12586 {
6b940e6a
PL
12587 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12588 NULL))
bba74b36 12589 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 12590 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 12591 else
e8ba3115
YQ
12592 /* If it passed validation at definition but fails now,
12593 something is very wrong. */
12594 internal_error (__FILE__, __LINE__,
12595 _("Fast tracepoint not "
12596 "valid during download"));
35b1e5cc 12597 }
e8ba3115
YQ
12598 else
12599 /* Fast tracepoints are functionally identical to regular
12600 tracepoints, so don't take lack of support as a reason to
12601 give up on the trace run. */
12602 warning (_("Target does not support fast tracepoints, "
12603 "downloading %d as regular tracepoint"), b->number);
12604 }
12605 else if (b->type == bp_static_tracepoint)
12606 {
12607 /* Only test for support at download time; we may not know
12608 target capabilities at definition time. */
12609 if (remote_supports_static_tracepoints ())
0fb4aa4b 12610 {
e8ba3115 12611 struct static_tracepoint_marker marker;
0fb4aa4b 12612
e8ba3115
YQ
12613 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12614 strcat (buf, ":S");
0fb4aa4b 12615 else
e8ba3115 12616 error (_("Static tracepoint not valid during download"));
0fb4aa4b 12617 }
e8ba3115
YQ
12618 else
12619 /* Fast tracepoints are functionally identical to regular
12620 tracepoints, so don't take lack of support as a reason
12621 to give up on the trace run. */
12622 error (_("Target does not support static tracepoints"));
12623 }
12624 /* If the tracepoint has a conditional, make it into an agent
12625 expression and append to the definition. */
12626 if (loc->cond)
12627 {
12628 /* Only test support at download time, we may not know target
12629 capabilities at definition time. */
12630 if (remote_supports_cond_tracepoints ())
35b1e5cc 12631 {
833177a4 12632 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
bba74b36
YQ
12633 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12634 aexpr->len);
e8ba3115 12635 pkt = buf + strlen (buf);
b44ec619 12636 for (int ndx = 0; ndx < aexpr->len; ++ndx)
e8ba3115
YQ
12637 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12638 *pkt = '\0';
35b1e5cc 12639 }
e8ba3115
YQ
12640 else
12641 warning (_("Target does not support conditional tracepoints, "
12642 "ignoring tp %d cond"), b->number);
12643 }
35b1e5cc 12644
d9b3f62e 12645 if (b->commands || *default_collect)
e8ba3115
YQ
12646 strcat (buf, "-");
12647 putpkt (buf);
b6bb3468
PA
12648 remote_get_noisy_reply ();
12649 if (strcmp (rs->buf, "OK"))
e8ba3115 12650 error (_("Target does not support tracepoints."));
35b1e5cc 12651
e8ba3115 12652 /* do_single_steps (t); */
b44ec619
SM
12653 for (auto action_it = tdp_actions.begin ();
12654 action_it != tdp_actions.end (); action_it++)
e8ba3115 12655 {
b44ec619
SM
12656 QUIT; /* Allow user to bail out with ^C. */
12657
12658 bool has_more = (action_it != tdp_actions.end ()
12659 || !stepping_actions.empty ());
12660
12661 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12662 b->number, addrbuf, /* address */
12663 action_it->c_str (),
12664 has_more ? '-' : 0);
12665 putpkt (buf);
12666 remote_get_noisy_reply ();
12667 if (strcmp (rs->buf, "OK"))
12668 error (_("Error on target while setting tracepoints."));
e8ba3115 12669 }
409873ef 12670
b44ec619
SM
12671 for (auto action_it = stepping_actions.begin ();
12672 action_it != stepping_actions.end (); action_it++)
12673 {
12674 QUIT; /* Allow user to bail out with ^C. */
12675
12676 bool is_first = action_it == stepping_actions.begin ();
12677 bool has_more = action_it != stepping_actions.end ();
12678
12679 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12680 b->number, addrbuf, /* address */
12681 is_first ? "S" : "",
12682 action_it->c_str (),
12683 has_more ? "-" : "");
12684 putpkt (buf);
12685 remote_get_noisy_reply ();
12686 if (strcmp (rs->buf, "OK"))
12687 error (_("Error on target while setting tracepoints."));
12688 }
12689
4082afcc 12690 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 12691 {
f00aae0f 12692 if (b->location != NULL)
409873ef 12693 {
e8ba3115 12694 strcpy (buf, "QTDPsrc:");
f00aae0f 12695 encode_source_string (b->number, loc->address, "at",
d28cd78a 12696 event_location_to_string (b->location.get ()),
f00aae0f 12697 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115 12698 putpkt (buf);
b6bb3468
PA
12699 remote_get_noisy_reply ();
12700 if (strcmp (rs->buf, "OK"))
e8ba3115 12701 warning (_("Target does not support source download."));
409873ef 12702 }
e8ba3115
YQ
12703 if (b->cond_string)
12704 {
12705 strcpy (buf, "QTDPsrc:");
12706 encode_source_string (b->number, loc->address,
12707 "cond", b->cond_string, buf + strlen (buf),
12708 2048 - strlen (buf));
12709 putpkt (buf);
b6bb3468
PA
12710 remote_get_noisy_reply ();
12711 if (strcmp (rs->buf, "OK"))
e8ba3115
YQ
12712 warning (_("Target does not support source download."));
12713 }
12714 remote_download_command_source (b->number, loc->address,
12715 breakpoint_commands (b));
35b1e5cc 12716 }
35b1e5cc
SS
12717}
12718
57810aa7 12719bool
f6ac5f3d 12720remote_target::can_download_tracepoint ()
1e4d1764 12721{
1e51243a
PA
12722 struct remote_state *rs = get_remote_state ();
12723 struct trace_status *ts;
12724 int status;
12725
12726 /* Don't try to install tracepoints until we've relocated our
12727 symbols, and fetched and merged the target's tracepoint list with
12728 ours. */
12729 if (rs->starting_up)
57810aa7 12730 return false;
1e51243a
PA
12731
12732 ts = current_trace_status ();
f6ac5f3d 12733 status = get_trace_status (ts);
1e4d1764
YQ
12734
12735 if (status == -1 || !ts->running_known || !ts->running)
57810aa7 12736 return false;
1e4d1764
YQ
12737
12738 /* If we are in a tracing experiment, but remote stub doesn't support
12739 installing tracepoint in trace, we have to return. */
12740 if (!remote_supports_install_in_trace ())
57810aa7 12741 return false;
1e4d1764 12742
57810aa7 12743 return true;
1e4d1764
YQ
12744}
12745
12746
f6ac5f3d
PA
12747void
12748remote_target::download_trace_state_variable (const trace_state_variable &tsv)
35b1e5cc
SS
12749{
12750 struct remote_state *rs = get_remote_state ();
00bf0b85 12751 char *p;
35b1e5cc 12752
bba74b36 12753 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
c252925c
SM
12754 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
12755 tsv.builtin);
00bf0b85 12756 p = rs->buf + strlen (rs->buf);
c252925c 12757 if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
00bf0b85 12758 error (_("Trace state variable name too long for tsv definition packet"));
c252925c 12759 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
00bf0b85 12760 *p++ = '\0';
35b1e5cc 12761 putpkt (rs->buf);
b6bb3468
PA
12762 remote_get_noisy_reply ();
12763 if (*rs->buf == '\0')
ad91cd99 12764 error (_("Target does not support this command."));
b6bb3468 12765 if (strcmp (rs->buf, "OK") != 0)
ad91cd99 12766 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
12767}
12768
f6ac5f3d
PA
12769void
12770remote_target::enable_tracepoint (struct bp_location *location)
d248b706
KY
12771{
12772 struct remote_state *rs = get_remote_state ();
12773 char addr_buf[40];
12774
12775 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12776 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12777 location->owner->number, addr_buf);
d248b706 12778 putpkt (rs->buf);
b6bb3468 12779 remote_get_noisy_reply ();
d248b706
KY
12780 if (*rs->buf == '\0')
12781 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12782 if (strcmp (rs->buf, "OK") != 0)
12783 error (_("Error on target while enabling tracepoint."));
12784}
12785
f6ac5f3d
PA
12786void
12787remote_target::disable_tracepoint (struct bp_location *location)
d248b706
KY
12788{
12789 struct remote_state *rs = get_remote_state ();
12790 char addr_buf[40];
12791
12792 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12793 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12794 location->owner->number, addr_buf);
d248b706 12795 putpkt (rs->buf);
b6bb3468 12796 remote_get_noisy_reply ();
d248b706
KY
12797 if (*rs->buf == '\0')
12798 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12799 if (strcmp (rs->buf, "OK") != 0)
12800 error (_("Error on target while disabling tracepoint."));
12801}
12802
f6ac5f3d
PA
12803void
12804remote_target::trace_set_readonly_regions ()
35b1e5cc
SS
12805{
12806 asection *s;
81b9b86e 12807 bfd *abfd = NULL;
35b1e5cc 12808 bfd_size_type size;
608bcef2 12809 bfd_vma vma;
35b1e5cc 12810 int anysecs = 0;
c2fa21f1 12811 int offset = 0;
35b1e5cc
SS
12812
12813 if (!exec_bfd)
12814 return; /* No information to give. */
12815
b6bb3468
PA
12816 struct remote_state *rs = get_remote_state ();
12817
12818 strcpy (rs->buf, "QTro");
12819 offset = strlen (rs->buf);
35b1e5cc
SS
12820 for (s = exec_bfd->sections; s; s = s->next)
12821 {
12822 char tmp1[40], tmp2[40];
c2fa21f1 12823 int sec_length;
35b1e5cc
SS
12824
12825 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 12826 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
12827 (s->flags & SEC_READONLY) == 0)
12828 continue;
12829
12830 anysecs = 1;
81b9b86e 12831 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 12832 size = bfd_get_section_size (s);
608bcef2
HZ
12833 sprintf_vma (tmp1, vma);
12834 sprintf_vma (tmp2, vma + size);
c2fa21f1 12835 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
b6bb3468 12836 if (offset + sec_length + 1 > rs->buf_size)
c2fa21f1 12837 {
4082afcc 12838 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 12839 warning (_("\
c2fa21f1
HZ
12840Too many sections for read-only sections definition packet."));
12841 break;
12842 }
b6bb3468 12843 xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
bba74b36 12844 tmp1, tmp2);
c2fa21f1 12845 offset += sec_length;
35b1e5cc
SS
12846 }
12847 if (anysecs)
12848 {
b6bb3468
PA
12849 putpkt (rs->buf);
12850 getpkt (&rs->buf, &rs->buf_size, 0);
35b1e5cc
SS
12851 }
12852}
12853
f6ac5f3d
PA
12854void
12855remote_target::trace_start ()
35b1e5cc 12856{
b6bb3468
PA
12857 struct remote_state *rs = get_remote_state ();
12858
35b1e5cc 12859 putpkt ("QTStart");
b6bb3468
PA
12860 remote_get_noisy_reply ();
12861 if (*rs->buf == '\0')
ad91cd99 12862 error (_("Target does not support this command."));
b6bb3468
PA
12863 if (strcmp (rs->buf, "OK") != 0)
12864 error (_("Bogus reply from target: %s"), rs->buf);
35b1e5cc
SS
12865}
12866
f6ac5f3d
PA
12867int
12868remote_target::get_trace_status (struct trace_status *ts)
35b1e5cc 12869{
953b98d1 12870 /* Initialize it just to avoid a GCC false warning. */
f652de6f 12871 char *p = NULL;
0df8b418 12872 /* FIXME we need to get register block size some other way. */
00bf0b85 12873 extern int trace_regblock_size;
bd3eecc3 12874 enum packet_result result;
b6bb3468 12875 struct remote_state *rs = get_remote_state ();
bd3eecc3 12876
4082afcc 12877 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 12878 return -1;
a744cf53 12879
5cd63fda
PA
12880 trace_regblock_size
12881 = get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
00bf0b85 12882
049dc89b
JK
12883 putpkt ("qTStatus");
12884
492d29ea 12885 TRY
67f41397 12886 {
b6bb3468 12887 p = remote_get_noisy_reply ();
67f41397 12888 }
492d29ea 12889 CATCH (ex, RETURN_MASK_ERROR)
67f41397 12890 {
598d3636
JK
12891 if (ex.error != TARGET_CLOSE_ERROR)
12892 {
12893 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12894 return -1;
12895 }
12896 throw_exception (ex);
67f41397 12897 }
492d29ea 12898 END_CATCH
00bf0b85 12899
bd3eecc3
PA
12900 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12901
00bf0b85 12902 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 12903 if (result == PACKET_UNKNOWN)
00bf0b85 12904 return -1;
35b1e5cc 12905
00bf0b85 12906 /* We're working with a live target. */
f5911ea1 12907 ts->filename = NULL;
00bf0b85 12908
00bf0b85 12909 if (*p++ != 'T')
b6bb3468 12910 error (_("Bogus trace status reply from target: %s"), rs->buf);
35b1e5cc 12911
84cebc4a
YQ
12912 /* Function 'parse_trace_status' sets default value of each field of
12913 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
12914 parse_trace_status (p, ts);
12915
12916 return ts->running;
35b1e5cc
SS
12917}
12918
f6ac5f3d
PA
12919void
12920remote_target::get_tracepoint_status (struct breakpoint *bp,
12921 struct uploaded_tp *utp)
f196051f
SS
12922{
12923 struct remote_state *rs = get_remote_state ();
f196051f
SS
12924 char *reply;
12925 struct bp_location *loc;
12926 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 12927 size_t size = get_remote_packet_size ();
f196051f
SS
12928
12929 if (tp)
12930 {
c1fc2657 12931 tp->hit_count = 0;
f196051f 12932 tp->traceframe_usage = 0;
c1fc2657 12933 for (loc = tp->loc; loc; loc = loc->next)
f196051f
SS
12934 {
12935 /* If the tracepoint was never downloaded, don't go asking for
12936 any status. */
12937 if (tp->number_on_target == 0)
12938 continue;
bba74b36
YQ
12939 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12940 phex_nz (loc->address, 0));
f196051f 12941 putpkt (rs->buf);
b6bb3468 12942 reply = remote_get_noisy_reply ();
f196051f
SS
12943 if (reply && *reply)
12944 {
12945 if (*reply == 'V')
12946 parse_tracepoint_status (reply + 1, bp, utp);
12947 }
12948 }
12949 }
12950 else if (utp)
12951 {
12952 utp->hit_count = 0;
12953 utp->traceframe_usage = 0;
bba74b36
YQ
12954 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12955 phex_nz (utp->addr, 0));
f196051f 12956 putpkt (rs->buf);
b6bb3468 12957 reply = remote_get_noisy_reply ();
f196051f
SS
12958 if (reply && *reply)
12959 {
12960 if (*reply == 'V')
12961 parse_tracepoint_status (reply + 1, bp, utp);
12962 }
12963 }
12964}
12965
f6ac5f3d
PA
12966void
12967remote_target::trace_stop ()
35b1e5cc 12968{
b6bb3468
PA
12969 struct remote_state *rs = get_remote_state ();
12970
35b1e5cc 12971 putpkt ("QTStop");
b6bb3468
PA
12972 remote_get_noisy_reply ();
12973 if (*rs->buf == '\0')
ad91cd99 12974 error (_("Target does not support this command."));
b6bb3468
PA
12975 if (strcmp (rs->buf, "OK") != 0)
12976 error (_("Bogus reply from target: %s"), rs->buf);
35b1e5cc
SS
12977}
12978
f6ac5f3d
PA
12979int
12980remote_target::trace_find (enum trace_find_type type, int num,
12981 CORE_ADDR addr1, CORE_ADDR addr2,
12982 int *tpp)
35b1e5cc
SS
12983{
12984 struct remote_state *rs = get_remote_state ();
bba74b36 12985 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
12986 char *p, *reply;
12987 int target_frameno = -1, target_tracept = -1;
12988
e6e4e701
PA
12989 /* Lookups other than by absolute frame number depend on the current
12990 trace selected, so make sure it is correct on the remote end
12991 first. */
12992 if (type != tfind_number)
12993 set_remote_traceframe ();
12994
35b1e5cc
SS
12995 p = rs->buf;
12996 strcpy (p, "QTFrame:");
12997 p = strchr (p, '\0');
12998 switch (type)
12999 {
13000 case tfind_number:
bba74b36 13001 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
13002 break;
13003 case tfind_pc:
bba74b36 13004 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
13005 break;
13006 case tfind_tp:
bba74b36 13007 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
13008 break;
13009 case tfind_range:
bba74b36
YQ
13010 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13011 phex_nz (addr2, 0));
35b1e5cc
SS
13012 break;
13013 case tfind_outside:
bba74b36
YQ
13014 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13015 phex_nz (addr2, 0));
35b1e5cc
SS
13016 break;
13017 default:
9b20d036 13018 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
13019 }
13020
13021 putpkt (rs->buf);
b6bb3468 13022 reply = remote_get_noisy_reply ();
ad91cd99
PA
13023 if (*reply == '\0')
13024 error (_("Target does not support this command."));
35b1e5cc
SS
13025
13026 while (reply && *reply)
13027 switch (*reply)
13028 {
13029 case 'F':
f197e0f1
VP
13030 p = ++reply;
13031 target_frameno = (int) strtol (p, &reply, 16);
13032 if (reply == p)
13033 error (_("Unable to parse trace frame number"));
e6e4e701
PA
13034 /* Don't update our remote traceframe number cache on failure
13035 to select a remote traceframe. */
f197e0f1
VP
13036 if (target_frameno == -1)
13037 return -1;
35b1e5cc
SS
13038 break;
13039 case 'T':
f197e0f1
VP
13040 p = ++reply;
13041 target_tracept = (int) strtol (p, &reply, 16);
13042 if (reply == p)
13043 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
13044 break;
13045 case 'O': /* "OK"? */
13046 if (reply[1] == 'K' && reply[2] == '\0')
13047 reply += 2;
13048 else
13049 error (_("Bogus reply from target: %s"), reply);
13050 break;
13051 default:
13052 error (_("Bogus reply from target: %s"), reply);
13053 }
13054 if (tpp)
13055 *tpp = target_tracept;
e6e4e701 13056
262e1174 13057 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
13058 return target_frameno;
13059}
13060
57810aa7 13061bool
f6ac5f3d 13062remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
35b1e5cc
SS
13063{
13064 struct remote_state *rs = get_remote_state ();
13065 char *reply;
13066 ULONGEST uval;
13067
e6e4e701
PA
13068 set_remote_traceframe ();
13069
bba74b36 13070 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc 13071 putpkt (rs->buf);
b6bb3468 13072 reply = remote_get_noisy_reply ();
35b1e5cc
SS
13073 if (reply && *reply)
13074 {
13075 if (*reply == 'V')
13076 {
13077 unpack_varlen_hex (reply + 1, &uval);
13078 *val = (LONGEST) uval;
57810aa7 13079 return true;
35b1e5cc
SS
13080 }
13081 }
57810aa7 13082 return false;
35b1e5cc
SS
13083}
13084
f6ac5f3d
PA
13085int
13086remote_target::save_trace_data (const char *filename)
00bf0b85
SS
13087{
13088 struct remote_state *rs = get_remote_state ();
13089 char *p, *reply;
13090
13091 p = rs->buf;
13092 strcpy (p, "QTSave:");
13093 p += strlen (p);
13094 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13095 error (_("Remote file name too long for trace save packet"));
9f1b45b0 13096 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
13097 *p++ = '\0';
13098 putpkt (rs->buf);
b6bb3468 13099 reply = remote_get_noisy_reply ();
d6c5869f 13100 if (*reply == '\0')
ad91cd99
PA
13101 error (_("Target does not support this command."));
13102 if (strcmp (reply, "OK") != 0)
13103 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
13104 return 0;
13105}
13106
13107/* This is basically a memory transfer, but needs to be its own packet
13108 because we don't know how the target actually organizes its trace
13109 memory, plus we want to be able to ask for as much as possible, but
13110 not be unhappy if we don't get as much as we ask for. */
13111
f6ac5f3d
PA
13112LONGEST
13113remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
13114{
13115 struct remote_state *rs = get_remote_state ();
13116 char *reply;
13117 char *p;
13118 int rslt;
13119
13120 p = rs->buf;
13121 strcpy (p, "qTBuffer:");
13122 p += strlen (p);
13123 p += hexnumstr (p, offset);
13124 *p++ = ',';
13125 p += hexnumstr (p, len);
13126 *p++ = '\0';
13127
13128 putpkt (rs->buf);
b6bb3468 13129 reply = remote_get_noisy_reply ();
00bf0b85
SS
13130 if (reply && *reply)
13131 {
13132 /* 'l' by itself means we're at the end of the buffer and
13133 there is nothing more to get. */
13134 if (*reply == 'l')
13135 return 0;
13136
13137 /* Convert the reply into binary. Limit the number of bytes to
13138 convert according to our passed-in buffer size, rather than
13139 what was returned in the packet; if the target is
13140 unexpectedly generous and gives us a bigger reply than we
13141 asked for, we don't want to crash. */
b6bb3468 13142 rslt = hex2bin (reply, buf, len);
00bf0b85
SS
13143 return rslt;
13144 }
13145
13146 /* Something went wrong, flag as an error. */
13147 return -1;
13148}
13149
f6ac5f3d
PA
13150void
13151remote_target::set_disconnected_tracing (int val)
35b1e5cc
SS
13152{
13153 struct remote_state *rs = get_remote_state ();
13154
4082afcc 13155 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 13156 {
ad91cd99
PA
13157 char *reply;
13158
bba74b36 13159 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 13160 putpkt (rs->buf);
b6bb3468 13161 reply = remote_get_noisy_reply ();
ad91cd99 13162 if (*reply == '\0')
33da3f1c 13163 error (_("Target does not support this command."));
ad91cd99
PA
13164 if (strcmp (reply, "OK") != 0)
13165 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
13166 }
13167 else if (val)
13168 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
13169}
13170
f6ac5f3d
PA
13171int
13172remote_target::core_of_thread (ptid_t ptid)
dc146f7c
VP
13173{
13174 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 13175
7aabaf9d
SM
13176 if (info != NULL && info->priv != NULL)
13177 return get_remote_thread_info (info)->core;
13178
dc146f7c
VP
13179 return -1;
13180}
13181
f6ac5f3d
PA
13182void
13183remote_target::set_circular_trace_buffer (int val)
4daf5ac0
SS
13184{
13185 struct remote_state *rs = get_remote_state ();
ad91cd99 13186 char *reply;
4daf5ac0 13187
bba74b36 13188 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 13189 putpkt (rs->buf);
b6bb3468 13190 reply = remote_get_noisy_reply ();
ad91cd99 13191 if (*reply == '\0')
4daf5ac0 13192 error (_("Target does not support this command."));
ad91cd99
PA
13193 if (strcmp (reply, "OK") != 0)
13194 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
13195}
13196
f6ac5f3d
PA
13197traceframe_info_up
13198remote_target::traceframe_info ()
b3b9301e 13199{
9018be22 13200 gdb::optional<gdb::char_vector> text
f6ac5f3d 13201 = target_read_stralloc (target_stack, TARGET_OBJECT_TRACEFRAME_INFO,
b7b030ad 13202 NULL);
9018be22
SM
13203 if (text)
13204 return parse_traceframe_info (text->data ());
b3b9301e
PA
13205
13206 return NULL;
13207}
13208
405f8e94
SS
13209/* Handle the qTMinFTPILen packet. Returns the minimum length of
13210 instruction on which a fast tracepoint may be placed. Returns -1
13211 if the packet is not supported, and 0 if the minimum instruction
13212 length is unknown. */
13213
f6ac5f3d
PA
13214int
13215remote_target::get_min_fast_tracepoint_insn_len ()
405f8e94
SS
13216{
13217 struct remote_state *rs = get_remote_state ();
13218 char *reply;
13219
e886a173
PA
13220 /* If we're not debugging a process yet, the IPA can't be
13221 loaded. */
13222 if (!target_has_execution)
13223 return 0;
13224
13225 /* Make sure the remote is pointing at the right process. */
13226 set_general_process ();
13227
bba74b36 13228 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94 13229 putpkt (rs->buf);
b6bb3468 13230 reply = remote_get_noisy_reply ();
405f8e94
SS
13231 if (*reply == '\0')
13232 return -1;
13233 else
13234 {
13235 ULONGEST min_insn_len;
13236
13237 unpack_varlen_hex (reply, &min_insn_len);
13238
13239 return (int) min_insn_len;
13240 }
13241}
13242
f6ac5f3d
PA
13243void
13244remote_target::set_trace_buffer_size (LONGEST val)
f6f899bf 13245{
4082afcc 13246 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
13247 {
13248 struct remote_state *rs = get_remote_state ();
13249 char *buf = rs->buf;
13250 char *endbuf = rs->buf + get_remote_packet_size ();
13251 enum packet_result result;
13252
13253 gdb_assert (val >= 0 || val == -1);
13254 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13255 /* Send -1 as literal "-1" to avoid host size dependency. */
13256 if (val < 0)
13257 {
13258 *buf++ = '-';
13259 buf += hexnumstr (buf, (ULONGEST) -val);
13260 }
13261 else
13262 buf += hexnumstr (buf, (ULONGEST) val);
13263
13264 putpkt (rs->buf);
b6bb3468 13265 remote_get_noisy_reply ();
f6f899bf
HAQ
13266 result = packet_ok (rs->buf,
13267 &remote_protocol_packets[PACKET_QTBuffer_size]);
13268
13269 if (result != PACKET_OK)
13270 warning (_("Bogus reply from target: %s"), rs->buf);
13271 }
13272}
13273
57810aa7 13274bool
f6ac5f3d
PA
13275remote_target::set_trace_notes (const char *user, const char *notes,
13276 const char *stop_notes)
f196051f
SS
13277{
13278 struct remote_state *rs = get_remote_state ();
13279 char *reply;
13280 char *buf = rs->buf;
13281 char *endbuf = rs->buf + get_remote_packet_size ();
13282 int nbytes;
13283
13284 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13285 if (user)
13286 {
13287 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 13288 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
13289 buf += 2 * nbytes;
13290 *buf++ = ';';
13291 }
13292 if (notes)
13293 {
13294 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 13295 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
13296 buf += 2 * nbytes;
13297 *buf++ = ';';
13298 }
13299 if (stop_notes)
13300 {
13301 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 13302 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
13303 buf += 2 * nbytes;
13304 *buf++ = ';';
13305 }
13306 /* Ensure the buffer is terminated. */
13307 *buf = '\0';
13308
13309 putpkt (rs->buf);
b6bb3468 13310 reply = remote_get_noisy_reply ();
f196051f 13311 if (*reply == '\0')
57810aa7 13312 return false;
f196051f
SS
13313
13314 if (strcmp (reply, "OK") != 0)
13315 error (_("Bogus reply from target: %s"), reply);
13316
57810aa7 13317 return true;
f196051f
SS
13318}
13319
57810aa7
PA
13320bool
13321remote_target::use_agent (bool use)
d1feda86 13322{
4082afcc 13323 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
13324 {
13325 struct remote_state *rs = get_remote_state ();
13326
13327 /* If the stub supports QAgent. */
bba74b36 13328 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
13329 putpkt (rs->buf);
13330 getpkt (&rs->buf, &rs->buf_size, 0);
13331
13332 if (strcmp (rs->buf, "OK") == 0)
13333 {
f6ac5f3d 13334 ::use_agent = use;
57810aa7 13335 return true;
d1feda86
YQ
13336 }
13337 }
13338
57810aa7 13339 return false;
d1feda86
YQ
13340}
13341
57810aa7 13342bool
f6ac5f3d 13343remote_target::can_use_agent ()
d1feda86 13344{
4082afcc 13345 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
13346}
13347
9accd112
MM
13348struct btrace_target_info
13349{
13350 /* The ptid of the traced thread. */
13351 ptid_t ptid;
f4abbc16
MM
13352
13353 /* The obtained branch trace configuration. */
13354 struct btrace_config conf;
9accd112
MM
13355};
13356
f4abbc16
MM
13357/* Reset our idea of our target's btrace configuration. */
13358
13359static void
13360remote_btrace_reset (void)
13361{
13362 struct remote_state *rs = get_remote_state ();
13363
13364 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13365}
13366
f4abbc16
MM
13367/* Synchronize the configuration with the target. */
13368
13369static void
13370btrace_sync_conf (const struct btrace_config *conf)
13371{
d33501a5
MM
13372 struct packet_config *packet;
13373 struct remote_state *rs;
13374 char *buf, *pos, *endbuf;
13375
13376 rs = get_remote_state ();
13377 buf = rs->buf;
13378 endbuf = buf + get_remote_packet_size ();
13379
13380 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13381 if (packet_config_support (packet) == PACKET_ENABLE
13382 && conf->bts.size != rs->btrace_config.bts.size)
13383 {
13384 pos = buf;
13385 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13386 conf->bts.size);
13387
13388 putpkt (buf);
13389 getpkt (&buf, &rs->buf_size, 0);
13390
13391 if (packet_ok (buf, packet) == PACKET_ERROR)
13392 {
13393 if (buf[0] == 'E' && buf[1] == '.')
13394 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13395 else
13396 error (_("Failed to configure the BTS buffer size."));
13397 }
13398
13399 rs->btrace_config.bts.size = conf->bts.size;
13400 }
b20a6524
MM
13401
13402 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13403 if (packet_config_support (packet) == PACKET_ENABLE
13404 && conf->pt.size != rs->btrace_config.pt.size)
13405 {
13406 pos = buf;
13407 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13408 conf->pt.size);
13409
13410 putpkt (buf);
13411 getpkt (&buf, &rs->buf_size, 0);
13412
13413 if (packet_ok (buf, packet) == PACKET_ERROR)
13414 {
13415 if (buf[0] == 'E' && buf[1] == '.')
13416 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13417 else
13418 error (_("Failed to configure the trace buffer size."));
13419 }
13420
13421 rs->btrace_config.pt.size = conf->pt.size;
13422 }
f4abbc16
MM
13423}
13424
13425/* Read the current thread's btrace configuration from the target and
13426 store it into CONF. */
13427
13428static void
13429btrace_read_config (struct btrace_config *conf)
13430{
9018be22 13431 gdb::optional<gdb::char_vector> xml
f6ac5f3d 13432 = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE_CONF, "");
9018be22
SM
13433 if (xml)
13434 parse_xml_btrace_conf (conf, xml->data ());
f4abbc16
MM
13435}
13436
c0272db5
TW
13437/* Maybe reopen target btrace. */
13438
13439static void
13440remote_btrace_maybe_reopen (void)
13441{
13442 struct remote_state *rs = get_remote_state ();
c0272db5
TW
13443 struct thread_info *tp;
13444 int btrace_target_pushed = 0;
13445 int warned = 0;
13446
5ed8105e
PA
13447 scoped_restore_current_thread restore_thread;
13448
c0272db5
TW
13449 ALL_NON_EXITED_THREADS (tp)
13450 {
13451 set_general_thread (tp->ptid);
13452
13453 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13454 btrace_read_config (&rs->btrace_config);
13455
13456 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13457 continue;
13458
13459#if !defined (HAVE_LIBIPT)
13460 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13461 {
13462 if (!warned)
13463 {
13464 warned = 1;
c4e12631
MM
13465 warning (_("Target is recording using Intel Processor Trace "
13466 "but support was disabled at compile time."));
c0272db5
TW
13467 }
13468
13469 continue;
13470 }
13471#endif /* !defined (HAVE_LIBIPT) */
13472
13473 /* Push target, once, but before anything else happens. This way our
13474 changes to the threads will be cleaned up by unpushing the target
13475 in case btrace_read_config () throws. */
13476 if (!btrace_target_pushed)
13477 {
13478 btrace_target_pushed = 1;
13479 record_btrace_push_target ();
13480 printf_filtered (_("Target is recording using %s.\n"),
13481 btrace_format_string (rs->btrace_config.format));
13482 }
13483
13484 tp->btrace.target = XCNEW (struct btrace_target_info);
13485 tp->btrace.target->ptid = tp->ptid;
13486 tp->btrace.target->conf = rs->btrace_config;
13487 }
c0272db5
TW
13488}
13489
9accd112
MM
13490/* Enable branch tracing. */
13491
f6ac5f3d
PA
13492struct btrace_target_info *
13493remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
9accd112
MM
13494{
13495 struct btrace_target_info *tinfo = NULL;
b20a6524 13496 struct packet_config *packet = NULL;
9accd112
MM
13497 struct remote_state *rs = get_remote_state ();
13498 char *buf = rs->buf;
13499 char *endbuf = rs->buf + get_remote_packet_size ();
13500
b20a6524
MM
13501 switch (conf->format)
13502 {
13503 case BTRACE_FORMAT_BTS:
13504 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13505 break;
13506
13507 case BTRACE_FORMAT_PT:
13508 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13509 break;
13510 }
13511
13512 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13513 error (_("Target does not support branch tracing."));
13514
f4abbc16
MM
13515 btrace_sync_conf (conf);
13516
9accd112
MM
13517 set_general_thread (ptid);
13518
13519 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13520 putpkt (rs->buf);
13521 getpkt (&rs->buf, &rs->buf_size, 0);
13522
13523 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13524 {
13525 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13526 error (_("Could not enable branch tracing for %s: %s"),
13527 target_pid_to_str (ptid), rs->buf + 2);
13528 else
13529 error (_("Could not enable branch tracing for %s."),
13530 target_pid_to_str (ptid));
13531 }
13532
8d749320 13533 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
13534 tinfo->ptid = ptid;
13535
f4abbc16
MM
13536 /* If we fail to read the configuration, we lose some information, but the
13537 tracing itself is not impacted. */
492d29ea
PA
13538 TRY
13539 {
13540 btrace_read_config (&tinfo->conf);
13541 }
13542 CATCH (err, RETURN_MASK_ERROR)
13543 {
13544 if (err.message != NULL)
13545 warning ("%s", err.message);
13546 }
13547 END_CATCH
f4abbc16 13548
9accd112
MM
13549 return tinfo;
13550}
13551
13552/* Disable branch tracing. */
13553
f6ac5f3d
PA
13554void
13555remote_target::disable_btrace (struct btrace_target_info *tinfo)
9accd112
MM
13556{
13557 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13558 struct remote_state *rs = get_remote_state ();
13559 char *buf = rs->buf;
13560 char *endbuf = rs->buf + get_remote_packet_size ();
13561
4082afcc 13562 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13563 error (_("Target does not support branch tracing."));
13564
13565 set_general_thread (tinfo->ptid);
13566
13567 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13568 putpkt (rs->buf);
13569 getpkt (&rs->buf, &rs->buf_size, 0);
13570
13571 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13572 {
13573 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13574 error (_("Could not disable branch tracing for %s: %s"),
13575 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13576 else
13577 error (_("Could not disable branch tracing for %s."),
13578 target_pid_to_str (tinfo->ptid));
13579 }
13580
13581 xfree (tinfo);
13582}
13583
13584/* Teardown branch tracing. */
13585
f6ac5f3d
PA
13586void
13587remote_target::teardown_btrace (struct btrace_target_info *tinfo)
9accd112
MM
13588{
13589 /* We must not talk to the target during teardown. */
13590 xfree (tinfo);
13591}
13592
13593/* Read the branch trace. */
13594
f6ac5f3d
PA
13595enum btrace_error
13596remote_target::read_btrace (struct btrace_data *btrace,
13597 struct btrace_target_info *tinfo,
13598 enum btrace_read_type type)
9accd112
MM
13599{
13600 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
9accd112 13601 const char *annex;
9accd112 13602
4082afcc 13603 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13604 error (_("Target does not support branch tracing."));
13605
13606#if !defined(HAVE_LIBEXPAT)
13607 error (_("Cannot process branch tracing result. XML parsing not supported."));
13608#endif
13609
13610 switch (type)
13611 {
864089d2 13612 case BTRACE_READ_ALL:
9accd112
MM
13613 annex = "all";
13614 break;
864089d2 13615 case BTRACE_READ_NEW:
9accd112
MM
13616 annex = "new";
13617 break;
969c39fb
MM
13618 case BTRACE_READ_DELTA:
13619 annex = "delta";
13620 break;
9accd112
MM
13621 default:
13622 internal_error (__FILE__, __LINE__,
13623 _("Bad branch tracing read type: %u."),
13624 (unsigned int) type);
13625 }
13626
9018be22 13627 gdb::optional<gdb::char_vector> xml
f6ac5f3d 13628 = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE, annex);
9018be22 13629 if (!xml)
969c39fb 13630 return BTRACE_ERR_UNKNOWN;
9accd112 13631
9018be22 13632 parse_xml_btrace (btrace, xml->data ());
9accd112 13633
969c39fb 13634 return BTRACE_ERR_NONE;
9accd112
MM
13635}
13636
f6ac5f3d
PA
13637const struct btrace_config *
13638remote_target::btrace_conf (const struct btrace_target_info *tinfo)
f4abbc16
MM
13639{
13640 return &tinfo->conf;
13641}
13642
57810aa7 13643bool
f6ac5f3d 13644remote_target::augmented_libraries_svr4_read ()
ced63ec0 13645{
4082afcc
PA
13646 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13647 == PACKET_ENABLE);
ced63ec0
GB
13648}
13649
9dd130a0
TT
13650/* Implementation of to_load. */
13651
f6ac5f3d
PA
13652void
13653remote_target::load (const char *name, int from_tty)
9dd130a0
TT
13654{
13655 generic_load (name, from_tty);
13656}
13657
c78fa86a
GB
13658/* Accepts an integer PID; returns a string representing a file that
13659 can be opened on the remote side to get the symbols for the child
13660 process. Returns NULL if the operation is not supported. */
13661
f6ac5f3d
PA
13662char *
13663remote_target::pid_to_exec_file (int pid)
c78fa86a 13664{
9018be22 13665 static gdb::optional<gdb::char_vector> filename;
835205d0
GB
13666 struct inferior *inf;
13667 char *annex = NULL;
c78fa86a
GB
13668
13669 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13670 return NULL;
13671
835205d0
GB
13672 inf = find_inferior_pid (pid);
13673 if (inf == NULL)
13674 internal_error (__FILE__, __LINE__,
13675 _("not currently attached to process %d"), pid);
13676
13677 if (!inf->fake_pid_p)
13678 {
13679 const int annex_size = 9;
13680
224c3ddb 13681 annex = (char *) alloca (annex_size);
835205d0
GB
13682 xsnprintf (annex, annex_size, "%x", pid);
13683 }
13684
f6ac5f3d 13685 filename = target_read_stralloc (target_stack,
c78fa86a
GB
13686 TARGET_OBJECT_EXEC_FILE, annex);
13687
9018be22 13688 return filename ? filename->data () : nullptr;
c78fa86a
GB
13689}
13690
750ce8d1
YQ
13691/* Implement the to_can_do_single_step target_ops method. */
13692
f6ac5f3d
PA
13693int
13694remote_target::can_do_single_step ()
750ce8d1
YQ
13695{
13696 /* We can only tell whether target supports single step or not by
13697 supported s and S vCont actions if the stub supports vContSupported
13698 feature. If the stub doesn't support vContSupported feature,
13699 we have conservatively to think target doesn't supports single
13700 step. */
13701 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13702 {
13703 struct remote_state *rs = get_remote_state ();
13704
13705 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13706 remote_vcont_probe (rs);
13707
13708 return rs->supports_vCont.s && rs->supports_vCont.S;
13709 }
13710 else
13711 return 0;
13712}
13713
3a00c802
PA
13714/* Implementation of the to_execution_direction method for the remote
13715 target. */
13716
f6ac5f3d
PA
13717enum exec_direction_kind
13718remote_target::execution_direction ()
3a00c802
PA
13719{
13720 struct remote_state *rs = get_remote_state ();
13721
13722 return rs->last_resume_exec_dir;
13723}
13724
f6327dcb
KB
13725/* Return pointer to the thread_info struct which corresponds to
13726 THREAD_HANDLE (having length HANDLE_LEN). */
13727
f6ac5f3d
PA
13728thread_info *
13729remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
13730 int handle_len,
13731 inferior *inf)
f6327dcb
KB
13732{
13733 struct thread_info *tp;
13734
13735 ALL_NON_EXITED_THREADS (tp)
13736 {
7aabaf9d 13737 remote_thread_info *priv = get_remote_thread_info (tp);
f6327dcb
KB
13738
13739 if (tp->inf == inf && priv != NULL)
13740 {
7aabaf9d 13741 if (handle_len != priv->thread_handle.size ())
f6327dcb 13742 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
7aabaf9d
SM
13743 handle_len, priv->thread_handle.size ());
13744 if (memcmp (thread_handle, priv->thread_handle.data (),
f6327dcb
KB
13745 handle_len) == 0)
13746 return tp;
13747 }
13748 }
13749
13750 return NULL;
13751}
13752
57810aa7 13753bool
f6ac5f3d 13754remote_target::can_async_p ()
6426a772 13755{
5d93a237
TT
13756 struct remote_state *rs = get_remote_state ();
13757
3015c064
SM
13758 /* We don't go async if the user has explicitly prevented it with the
13759 "maint set target-async" command. */
c6ebd6cf 13760 if (!target_async_permitted)
57810aa7 13761 return false;
75c99385 13762
23860348 13763 /* We're async whenever the serial device is. */
5d93a237 13764 return serial_can_async_p (rs->remote_desc);
6426a772
JM
13765}
13766
57810aa7 13767bool
f6ac5f3d 13768remote_target::is_async_p ()
6426a772 13769{
5d93a237
TT
13770 struct remote_state *rs = get_remote_state ();
13771
c6ebd6cf 13772 if (!target_async_permitted)
75c99385 13773 /* We only enable async when the user specifically asks for it. */
57810aa7 13774 return false;
75c99385 13775
23860348 13776 /* We're async whenever the serial device is. */
5d93a237 13777 return serial_is_async_p (rs->remote_desc);
6426a772
JM
13778}
13779
2acceee2
JM
13780/* Pass the SERIAL event on and up to the client. One day this code
13781 will be able to delay notifying the client of an event until the
23860348 13782 point where an entire packet has been received. */
2acceee2 13783
2acceee2
JM
13784static serial_event_ftype remote_async_serial_handler;
13785
6426a772 13786static void
819cc324 13787remote_async_serial_handler (struct serial *scb, void *context)
6426a772 13788{
2acceee2
JM
13789 /* Don't propogate error information up to the client. Instead let
13790 the client find out about the error by querying the target. */
6a3753b3 13791 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
13792}
13793
74531fed
PA
13794static void
13795remote_async_inferior_event_handler (gdb_client_data data)
13796{
13797 inferior_event_handler (INF_REG_EVENT, NULL);
13798}
13799
f6ac5f3d
PA
13800void
13801remote_target::async (int enable)
2acceee2 13802{
5d93a237
TT
13803 struct remote_state *rs = get_remote_state ();
13804
6a3753b3 13805 if (enable)
2acceee2 13806 {
88b496c3 13807 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
13808
13809 /* If there are pending events in the stop reply queue tell the
13810 event loop to process them. */
13811 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13812 mark_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13813 /* For simplicity, below we clear the pending events token
13814 without remembering whether it is marked, so here we always
13815 mark it. If there's actually no pending notification to
13816 process, this ends up being a no-op (other than a spurious
13817 event-loop wakeup). */
13818 if (target_is_non_stop_p ())
13819 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
13820 }
13821 else
b7d2e916
PA
13822 {
13823 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
13824 /* If the core is disabling async, it doesn't want to be
13825 disturbed with target events. Clear all async event sources
13826 too. */
b7d2e916 13827 clear_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13828 if (target_is_non_stop_p ())
13829 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 13830 }
6426a772
JM
13831}
13832
65706a29
PA
13833/* Implementation of the to_thread_events method. */
13834
f6ac5f3d
PA
13835void
13836remote_target::thread_events (int enable)
65706a29
PA
13837{
13838 struct remote_state *rs = get_remote_state ();
13839 size_t size = get_remote_packet_size ();
65706a29
PA
13840
13841 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13842 return;
13843
13844 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13845 putpkt (rs->buf);
13846 getpkt (&rs->buf, &rs->buf_size, 0);
13847
13848 switch (packet_ok (rs->buf,
13849 &remote_protocol_packets[PACKET_QThreadEvents]))
13850 {
13851 case PACKET_OK:
13852 if (strcmp (rs->buf, "OK") != 0)
13853 error (_("Remote refused setting thread events: %s"), rs->buf);
13854 break;
13855 case PACKET_ERROR:
13856 warning (_("Remote failure reply: %s"), rs->buf);
13857 break;
13858 case PACKET_UNKNOWN:
13859 break;
13860 }
13861}
13862
5a2468f5 13863static void
981a3fb3 13864set_remote_cmd (const char *args, int from_tty)
5a2468f5 13865{
635c7e8a 13866 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
13867}
13868
d471ea57 13869static void
981a3fb3 13870show_remote_cmd (const char *args, int from_tty)
d471ea57 13871{
37a105a1 13872 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 13873 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1 13874 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 13875 struct ui_out *uiout = current_uiout;
37a105a1 13876
2e783024 13877 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
37a105a1
DJ
13878 for (; list != NULL; list = list->next)
13879 if (strcmp (list->name, "Z-packet") == 0)
13880 continue;
427c3a89
DJ
13881 else if (list->type == not_set_cmd)
13882 /* Alias commands are exactly like the original, except they
13883 don't have the normal type. */
13884 continue;
13885 else
37a105a1 13886 {
2e783024 13887 ui_out_emit_tuple option_emitter (uiout, "option");
a744cf53 13888
112e8700
SM
13889 uiout->field_string ("name", list->name);
13890 uiout->text (": ");
427c3a89 13891 if (list->type == show_cmd)
f5c4fcd9 13892 do_show_command (NULL, from_tty, list);
427c3a89
DJ
13893 else
13894 cmd_func (list, NULL, from_tty);
37a105a1 13895 }
d471ea57 13896}
5a2468f5 13897
0f71a2f6 13898
23860348 13899/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
13900static void
13901remote_new_objfile (struct objfile *objfile)
13902{
5d93a237
TT
13903 struct remote_state *rs = get_remote_state ();
13904
13905 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 13906 remote_check_symbols ();
dc8acb97
MS
13907}
13908
00bf0b85
SS
13909/* Pull all the tracepoints defined on the target and create local
13910 data structures representing them. We don't want to create real
13911 tracepoints yet, we don't want to mess up the user's existing
13912 collection. */
13913
f6ac5f3d
PA
13914int
13915remote_target::upload_tracepoints (struct uploaded_tp **utpp)
d5551862 13916{
00bf0b85
SS
13917 struct remote_state *rs = get_remote_state ();
13918 char *p;
d5551862 13919
00bf0b85
SS
13920 /* Ask for a first packet of tracepoint definition. */
13921 putpkt ("qTfP");
13922 getpkt (&rs->buf, &rs->buf_size, 0);
13923 p = rs->buf;
13924 while (*p && *p != 'l')
d5551862 13925 {
00bf0b85
SS
13926 parse_tracepoint_definition (p, utpp);
13927 /* Ask for another packet of tracepoint definition. */
13928 putpkt ("qTsP");
13929 getpkt (&rs->buf, &rs->buf_size, 0);
13930 p = rs->buf;
d5551862 13931 }
00bf0b85 13932 return 0;
d5551862
SS
13933}
13934
f6ac5f3d
PA
13935int
13936remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
d5551862 13937{
00bf0b85 13938 struct remote_state *rs = get_remote_state ();
d5551862 13939 char *p;
d5551862 13940
00bf0b85
SS
13941 /* Ask for a first packet of variable definition. */
13942 putpkt ("qTfV");
d5551862
SS
13943 getpkt (&rs->buf, &rs->buf_size, 0);
13944 p = rs->buf;
00bf0b85 13945 while (*p && *p != 'l')
d5551862 13946 {
00bf0b85
SS
13947 parse_tsv_definition (p, utsvp);
13948 /* Ask for another packet of variable definition. */
13949 putpkt ("qTsV");
d5551862
SS
13950 getpkt (&rs->buf, &rs->buf_size, 0);
13951 p = rs->buf;
13952 }
00bf0b85 13953 return 0;
d5551862
SS
13954}
13955
c1e36e3e
PA
13956/* The "set/show range-stepping" show hook. */
13957
13958static void
13959show_range_stepping (struct ui_file *file, int from_tty,
13960 struct cmd_list_element *c,
13961 const char *value)
13962{
13963 fprintf_filtered (file,
13964 _("Debugger's willingness to use range stepping "
13965 "is %s.\n"), value);
13966}
13967
13968/* The "set/show range-stepping" set hook. */
13969
13970static void
eb4c3f4a 13971set_range_stepping (const char *ignore_args, int from_tty,
c1e36e3e
PA
13972 struct cmd_list_element *c)
13973{
5d93a237
TT
13974 struct remote_state *rs = get_remote_state ();
13975
c1e36e3e
PA
13976 /* Whene enabling, check whether range stepping is actually
13977 supported by the target, and warn if not. */
13978 if (use_range_stepping)
13979 {
5d93a237 13980 if (rs->remote_desc != NULL)
c1e36e3e 13981 {
4082afcc 13982 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
13983 remote_vcont_probe (rs);
13984
4082afcc 13985 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
13986 && rs->supports_vCont.r)
13987 return;
13988 }
13989
13990 warning (_("Range stepping is not supported by the current target"));
13991 }
13992}
13993
c906108c 13994void
fba45db2 13995_initialize_remote (void)
c906108c 13996{
9a7071a8 13997 struct cmd_list_element *cmd;
6f937416 13998 const char *cmd_name;
ea9c271d 13999
0f71a2f6 14000 /* architecture specific data */
2bc416ba 14001 remote_gdbarch_data_handle =
23860348 14002 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
14003 remote_g_packet_data_handle =
14004 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 14005
94585166
DB
14006 remote_pspace_data
14007 = register_program_space_data_with_cleanup (NULL,
14008 remote_pspace_data_cleanup);
14009
ea9c271d
DJ
14010 /* Initialize the per-target state. At the moment there is only one
14011 of these, not one per target. Only one target is active at a
cf792862
TT
14012 time. */
14013 remote_state = new_remote_state ();
ea9c271d 14014
d9f719f1
PA
14015 add_target (remote_target_info, remote_target::open);
14016 add_target (extended_remote_target_info, extended_remote_target::open);
cce74817 14017
dc8acb97 14018 /* Hook into new objfile notification. */
76727919 14019 gdb::observers::new_objfile.attach (remote_new_objfile);
5f4cf0bb
YQ
14020 /* We're no longer interested in notification events of an inferior
14021 when it exits. */
76727919 14022 gdb::observers::inferior_exit.attach (discard_pending_stop_replies);
dc8acb97 14023
c906108c
SS
14024#if 0
14025 init_remote_threadtests ();
14026#endif
14027
722247f1 14028 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 14029 /* set/show remote ... */
d471ea57 14030
1bedd215 14031 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
14032Remote protocol specific variables\n\
14033Configure various remote-protocol specific variables such as\n\
1bedd215 14034the packets being used"),
cff3e48b 14035 &remote_set_cmdlist, "set remote ",
23860348 14036 0 /* allow-unknown */, &setlist);
1bedd215 14037 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
14038Remote protocol specific variables\n\
14039Configure various remote-protocol specific variables such as\n\
1bedd215 14040the packets being used"),
cff3e48b 14041 &remote_show_cmdlist, "show remote ",
23860348 14042 0 /* allow-unknown */, &showlist);
5a2468f5 14043
1a966eab
AC
14044 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14045Compare section data on target to the exec file.\n\
95cf3b38
DT
14046Argument is a single section name (default: all loaded sections).\n\
14047To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
14048 &cmdlist);
14049
1a966eab
AC
14050 add_cmd ("packet", class_maintenance, packet_command, _("\
14051Send an arbitrary packet to a remote target.\n\
c906108c
SS
14052 maintenance packet TEXT\n\
14053If GDB is talking to an inferior via the GDB serial protocol, then\n\
14054this command sends the string TEXT to the inferior, and displays the\n\
14055response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 14056terminating `#' character and checksum."),
c906108c
SS
14057 &maintenancelist);
14058
7915a72c
AC
14059 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14060Set whether to send break if interrupted."), _("\
14061Show whether to send break if interrupted."), _("\
14062If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 14063 set_remotebreak, show_remotebreak,
e707bbc2 14064 &setlist, &showlist);
9a7071a8
JB
14065 cmd_name = "remotebreak";
14066 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14067 deprecate_cmd (cmd, "set remote interrupt-sequence");
14068 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14069 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14070 deprecate_cmd (cmd, "show remote interrupt-sequence");
14071
14072 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
14073 interrupt_sequence_modes, &interrupt_sequence_mode,
14074 _("\
9a7071a8
JB
14075Set interrupt sequence to remote target."), _("\
14076Show interrupt sequence to remote target."), _("\
14077Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14078 NULL, show_interrupt_sequence,
14079 &remote_set_cmdlist,
14080 &remote_show_cmdlist);
14081
14082 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14083 &interrupt_on_connect, _("\
14084Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14085Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14086If set, interrupt sequence is sent to remote target."),
14087 NULL, NULL,
14088 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 14089
23860348 14090 /* Install commands for configuring memory read/write packets. */
11cf8741 14091
1a966eab
AC
14092 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14093Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 14094 &setlist);
1a966eab
AC
14095 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14096Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
14097 &showlist);
14098 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
14099 set_memory_write_packet_size, _("\
14100Set the maximum number of bytes per memory-write packet.\n\
14101Specify the number of bytes in a packet or 0 (zero) for the\n\
14102default packet size. The actual limit is further reduced\n\
14103dependent on the target. Specify ``fixed'' to disable the\n\
14104further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14105 &remote_set_cmdlist);
14106 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
14107 set_memory_read_packet_size, _("\
14108Set the maximum number of bytes per memory-read packet.\n\
14109Specify the number of bytes in a packet or 0 (zero) for the\n\
14110default packet size. The actual limit is further reduced\n\
14111dependent on the target. Specify ``fixed'' to disable the\n\
14112further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14113 &remote_set_cmdlist);
14114 add_cmd ("memory-write-packet-size", no_class,
14115 show_memory_write_packet_size,
1a966eab 14116 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
14117 &remote_show_cmdlist);
14118 add_cmd ("memory-read-packet-size", no_class,
14119 show_memory_read_packet_size,
1a966eab 14120 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 14121 &remote_show_cmdlist);
c906108c 14122
b3f42336 14123 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
14124 &remote_hw_watchpoint_limit, _("\
14125Set the maximum number of target hardware watchpoints."), _("\
14126Show the maximum number of target hardware watchpoints."), _("\
14127Specify a negative limit for unlimited."),
3e43a32a
MS
14128 NULL, NULL, /* FIXME: i18n: The maximum
14129 number of target hardware
14130 watchpoints is %s. */
b3f42336 14131 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
14132 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14133 &remote_hw_watchpoint_length_limit, _("\
14134Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14135Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14136Specify a negative limit for unlimited."),
14137 NULL, NULL, /* FIXME: i18n: The maximum
14138 length (in bytes) of a target
14139 hardware watchpoint is %s. */
14140 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 14141 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
14142 &remote_hw_breakpoint_limit, _("\
14143Set the maximum number of target hardware breakpoints."), _("\
14144Show the maximum number of target hardware breakpoints."), _("\
14145Specify a negative limit for unlimited."),
3e43a32a
MS
14146 NULL, NULL, /* FIXME: i18n: The maximum
14147 number of target hardware
14148 breakpoints is %s. */
b3f42336 14149 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 14150
1b493192
PA
14151 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14152 &remote_address_size, _("\
4d28ad1e
AC
14153Set the maximum size of the address (in bits) in a memory packet."), _("\
14154Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
14155 NULL,
14156 NULL, /* FIXME: i18n: */
14157 &setlist, &showlist);
c906108c 14158
ca4f7f8b
PA
14159 init_all_packet_configs ();
14160
444abaca 14161 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 14162 "X", "binary-download", 1);
0f71a2f6 14163
444abaca 14164 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 14165 "vCont", "verbose-resume", 0);
506fb367 14166
89be2091
DJ
14167 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14168 "QPassSignals", "pass-signals", 0);
14169
82075af2
JS
14170 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14171 "QCatchSyscalls", "catch-syscalls", 0);
14172
9b224c5e
PA
14173 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14174 "QProgramSignals", "program-signals", 0);
14175
bc3b087d
SDJ
14176 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14177 "QSetWorkingDir", "set-working-dir", 0);
14178
aefd8b33
SDJ
14179 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14180 "QStartupWithShell", "startup-with-shell", 0);
14181
0a2dde4a
SDJ
14182 add_packet_config_cmd (&remote_protocol_packets
14183 [PACKET_QEnvironmentHexEncoded],
14184 "QEnvironmentHexEncoded", "environment-hex-encoded",
14185 0);
14186
14187 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14188 "QEnvironmentReset", "environment-reset",
14189 0);
14190
14191 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14192 "QEnvironmentUnset", "environment-unset",
14193 0);
14194
444abaca 14195 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 14196 "qSymbol", "symbol-lookup", 0);
dc8acb97 14197
444abaca 14198 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 14199 "P", "set-register", 1);
d471ea57 14200
444abaca 14201 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 14202 "p", "fetch-register", 1);
b96ec7ac 14203
444abaca 14204 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 14205 "Z0", "software-breakpoint", 0);
d471ea57 14206
444abaca 14207 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 14208 "Z1", "hardware-breakpoint", 0);
d471ea57 14209
444abaca 14210 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 14211 "Z2", "write-watchpoint", 0);
d471ea57 14212
444abaca 14213 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 14214 "Z3", "read-watchpoint", 0);
d471ea57 14215
444abaca 14216 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 14217 "Z4", "access-watchpoint", 0);
d471ea57 14218
0876f84a
DJ
14219 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14220 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 14221
c78fa86a
GB
14222 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14223 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14224
23181151
DJ
14225 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14226 "qXfer:features:read", "target-features", 0);
14227
cfa9d6d9
DJ
14228 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14229 "qXfer:libraries:read", "library-info", 0);
14230
2268b414
JK
14231 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14232 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14233
fd79ecee
DJ
14234 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14235 "qXfer:memory-map:read", "memory-map", 0);
14236
0e7f50da
UW
14237 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14238 "qXfer:spu:read", "read-spu-object", 0);
14239
14240 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14241 "qXfer:spu:write", "write-spu-object", 0);
14242
07e059b5
VP
14243 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14244 "qXfer:osdata:read", "osdata", 0);
14245
dc146f7c
VP
14246 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14247 "qXfer:threads:read", "threads", 0);
14248
4aa995e1
PA
14249 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14250 "qXfer:siginfo:read", "read-siginfo-object", 0);
14251
14252 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14253 "qXfer:siginfo:write", "write-siginfo-object", 0);
14254
b3b9301e
PA
14255 add_packet_config_cmd
14256 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 14257 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 14258
169081d0
TG
14259 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14260 "qXfer:uib:read", "unwind-info-block", 0);
14261
444abaca 14262 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 14263 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
14264 0);
14265
711e434b
PM
14266 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14267 "qGetTIBAddr", "get-thread-information-block-address",
14268 0);
14269
40ab02ce
MS
14270 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14271 "bc", "reverse-continue", 0);
14272
14273 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14274 "bs", "reverse-step", 0);
14275
be2a5f71
DJ
14276 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14277 "qSupported", "supported-packets", 0);
14278
08388c79
DE
14279 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14280 "qSearch:memory", "search-memory", 0);
14281
bd3eecc3
PA
14282 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14283 "qTStatus", "trace-status", 0);
14284
15a201c8
GB
14285 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14286 "vFile:setfs", "hostio-setfs", 0);
14287
a6b151f1
DJ
14288 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14289 "vFile:open", "hostio-open", 0);
14290
14291 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14292 "vFile:pread", "hostio-pread", 0);
14293
14294 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14295 "vFile:pwrite", "hostio-pwrite", 0);
14296
14297 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14298 "vFile:close", "hostio-close", 0);
14299
14300 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14301 "vFile:unlink", "hostio-unlink", 0);
14302
b9e7b9c3
UW
14303 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14304 "vFile:readlink", "hostio-readlink", 0);
14305
0a93529c
GB
14306 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14307 "vFile:fstat", "hostio-fstat", 0);
14308
2d717e4f
DJ
14309 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14310 "vAttach", "attach", 0);
14311
14312 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14313 "vRun", "run", 0);
14314
a6f3e723
SL
14315 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14316 "QStartNoAckMode", "noack", 0);
14317
82f73884
PA
14318 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14319 "vKill", "kill", 0);
14320
0b16c5cf
PA
14321 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14322 "qAttached", "query-attached", 0);
14323
782b2b07 14324 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
14325 "ConditionalTracepoints",
14326 "conditional-tracepoints", 0);
3788aec7
LM
14327
14328 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14329 "ConditionalBreakpoints",
14330 "conditional-breakpoints", 0);
14331
d3ce09f5
SS
14332 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14333 "BreakpointCommands",
14334 "breakpoint-commands", 0);
14335
7a697b8d
SS
14336 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14337 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 14338
409873ef
SS
14339 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14340 "TracepointSource", "TracepointSource", 0);
14341
d914c394
SS
14342 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14343 "QAllow", "allow", 0);
14344
0fb4aa4b
PA
14345 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14346 "StaticTracepoints", "static-tracepoints", 0);
14347
1e4d1764
YQ
14348 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14349 "InstallInTrace", "install-in-trace", 0);
14350
0fb4aa4b
PA
14351 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14352 "qXfer:statictrace:read", "read-sdata-object", 0);
14353
78d85199
YQ
14354 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14355 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14356
03583c20
UW
14357 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14358 "QDisableRandomization", "disable-randomization", 0);
14359
d1feda86
YQ
14360 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14361 "QAgent", "agent", 0);
14362
f6f899bf
HAQ
14363 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14364 "QTBuffer:size", "trace-buffer-size", 0);
14365
9accd112
MM
14366 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14367 "Qbtrace:off", "disable-btrace", 0);
14368
14369 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
14370 "Qbtrace:bts", "enable-btrace-bts", 0);
14371
14372 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14373 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
14374
14375 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14376 "qXfer:btrace", "read-btrace", 0);
14377
f4abbc16
MM
14378 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14379 "qXfer:btrace-conf", "read-btrace-conf", 0);
14380
d33501a5
MM
14381 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14382 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14383
73b8c1fd
PA
14384 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14385 "multiprocess-feature", "multiprocess-feature", 0);
14386
f7e6eed5
PA
14387 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14388 "swbreak-feature", "swbreak-feature", 0);
14389
14390 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14391 "hwbreak-feature", "hwbreak-feature", 0);
14392
89245bc0
DB
14393 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14394 "fork-event-feature", "fork-event-feature", 0);
14395
14396 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14397 "vfork-event-feature", "vfork-event-feature", 0);
14398
b20a6524
MM
14399 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14400 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14401
750ce8d1
YQ
14402 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14403 "vContSupported", "verbose-resume-supported", 0);
14404
94585166
DB
14405 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14406 "exec-event-feature", "exec-event-feature", 0);
14407
de979965
PA
14408 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14409 "vCtrlC", "ctrl-c", 0);
14410
65706a29
PA
14411 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14412 "QThreadEvents", "thread-events", 0);
14413
f2faf941
PA
14414 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14415 "N stop reply", "no-resumed-stop-reply", 0);
14416
0b736949
DB
14417 /* Assert that we've registered "set remote foo-packet" commands
14418 for all packet configs. */
ca4f7f8b
PA
14419 {
14420 int i;
14421
14422 for (i = 0; i < PACKET_MAX; i++)
14423 {
14424 /* Ideally all configs would have a command associated. Some
14425 still don't though. */
14426 int excepted;
14427
14428 switch (i)
14429 {
14430 case PACKET_QNonStop:
ca4f7f8b
PA
14431 case PACKET_EnableDisableTracepoints_feature:
14432 case PACKET_tracenz_feature:
14433 case PACKET_DisconnectedTracing_feature:
14434 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
14435 case PACKET_qCRC:
14436 /* Additions to this list need to be well justified:
14437 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
14438 excepted = 1;
14439 break;
14440 default:
14441 excepted = 0;
14442 break;
14443 }
14444
14445 /* This catches both forgetting to add a config command, and
14446 forgetting to remove a packet from the exception list. */
14447 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14448 }
14449 }
14450
37a105a1
DJ
14451 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14452 Z sub-packet has its own set and show commands, but users may
14453 have sets to this variable in their .gdbinit files (or in their
14454 documentation). */
e9e68a56 14455 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
14456 &remote_Z_packet_detect, _("\
14457Set use of remote protocol `Z' packets"), _("\
14458Show use of remote protocol `Z' packets "), _("\
3b64bf98 14459When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 14460packets."),
e9e68a56 14461 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
14462 show_remote_protocol_Z_packet_cmd,
14463 /* FIXME: i18n: Use of remote protocol
14464 `Z' packets is %s. */
e9e68a56 14465 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 14466
a6b151f1
DJ
14467 add_prefix_cmd ("remote", class_files, remote_command, _("\
14468Manipulate files on the remote system\n\
14469Transfer files to and from the remote target system."),
14470 &remote_cmdlist, "remote ",
14471 0 /* allow-unknown */, &cmdlist);
14472
14473 add_cmd ("put", class_files, remote_put_command,
14474 _("Copy a local file to the remote system."),
14475 &remote_cmdlist);
14476
14477 add_cmd ("get", class_files, remote_get_command,
14478 _("Copy a remote file to the local system."),
14479 &remote_cmdlist);
14480
14481 add_cmd ("delete", class_files, remote_delete_command,
14482 _("Delete a remote file."),
14483 &remote_cmdlist);
14484
2d717e4f 14485 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 14486 &remote_exec_file_var, _("\
2d717e4f 14487Set the remote pathname for \"run\""), _("\
94585166
DB
14488Show the remote pathname for \"run\""), NULL,
14489 set_remote_exec_file,
14490 show_remote_exec_file,
14491 &remote_set_cmdlist,
14492 &remote_show_cmdlist);
2d717e4f 14493
c1e36e3e
PA
14494 add_setshow_boolean_cmd ("range-stepping", class_run,
14495 &use_range_stepping, _("\
14496Enable or disable range stepping."), _("\
14497Show whether target-assisted range stepping is enabled."), _("\
14498If on, and the target supports it, when stepping a source line, GDB\n\
14499tells the target to step the corresponding range of addresses itself instead\n\
14500of issuing multiple single-steps. This speeds up source level\n\
14501stepping. If off, GDB always issues single-steps, even if range\n\
14502stepping is supported by the target. The default is on."),
14503 set_range_stepping,
14504 show_range_stepping,
14505 &setlist,
14506 &showlist);
14507
449092f6
CV
14508 /* Eventually initialize fileio. See fileio.c */
14509 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 14510
ba348170 14511 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 14512 special ptids with it set to != 0. */
ba348170
PA
14513 magic_null_ptid = ptid_build (42000, -1, 1);
14514 not_sent_ptid = ptid_build (42000, -2, 1);
14515 any_thread_ptid = ptid_build (42000, 0, 1);
c906108c 14516}
This page took 3.368671 seconds and 4 git commands to generate.